Agenda: New face for entries from the Emacs diary
[rgr-org-mode.git] / lisp / org.el
blob75ddcd1401765c439f84ffec3076a20d380ec0e9
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 (options (org-combine-plists (org-default-export-plist)
4806 (org-infile-export-plist)))
4807 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4808 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4809 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4810 (org-export-html-expand (plist-get options :expand-quoted-html))
4811 (org-export-with-special-strings (plist-get options :special-strings))
4812 (re-sub
4813 (cond
4814 ((equal org-export-with-sub-superscripts '{})
4815 (list org-match-substring-with-braces-regexp))
4816 (org-export-with-sub-superscripts
4817 (list org-match-substring-regexp))
4818 (t nil)))
4819 (re-latex
4820 (if org-export-with-LaTeX-fragments
4821 (mapcar (lambda (x) (nth 1 x)) latexs)))
4822 (re-macros
4823 (if org-export-with-TeX-macros
4824 (list (concat "\\\\"
4825 (regexp-opt
4826 (append (mapcar 'car org-html-entities)
4827 (if (boundp 'org-latex-entities)
4828 (mapcar (lambda (x)
4829 (or (car-safe x) x))
4830 org-latex-entities)
4831 nil))
4832 'words))) ; FIXME
4834 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4835 (re-special (if org-export-with-special-strings
4836 (mapcar (lambda (x) (car x))
4837 org-export-html-special-string-regexps)))
4838 (re-rest
4839 (delq nil
4840 (list
4841 (if org-export-html-expand "@<[^>\n]+>")
4842 ))))
4843 (org-set-local
4844 'org-latex-and-specials-regexp
4845 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4846 re-rest) "\\|")))))
4848 (defun org-do-latex-and-special-faces (limit)
4849 "Run through the buffer and add overlays to links."
4850 (when org-latex-and-specials-regexp
4851 (let (rtn d)
4852 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4853 limit t))
4854 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4855 'face))
4856 '(org-code org-verbatim underline)))
4857 (progn
4858 (setq rtn t
4859 d (cond ((member (char-after (1+ (match-beginning 0)))
4860 '(?_ ?^)) 1)
4861 (t 0)))
4862 (font-lock-prepend-text-property
4863 (+ d (match-beginning 0)) (match-end 0)
4864 'face 'org-latex-and-export-specials)
4865 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4866 '(font-lock-multiline t)))))
4867 rtn)))
4869 (defun org-restart-font-lock ()
4870 "Restart font-lock-mode, to force refontification."
4871 (when (and (boundp 'font-lock-mode) font-lock-mode)
4872 (font-lock-mode -1)
4873 (font-lock-mode 1)))
4875 (defun org-all-targets (&optional radio)
4876 "Return a list of all targets in this file.
4877 With optional argument RADIO, only find radio targets."
4878 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4879 rtn)
4880 (save-excursion
4881 (goto-char (point-min))
4882 (while (re-search-forward re nil t)
4883 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4884 rtn)))
4886 (defun org-make-target-link-regexp (targets)
4887 "Make regular expression matching all strings in TARGETS.
4888 The regular expression finds the targets also if there is a line break
4889 between words."
4890 (and targets
4891 (concat
4892 "\\<\\("
4893 (mapconcat
4894 (lambda (x)
4895 (while (string-match " +" x)
4896 (setq x (replace-match "\\s-+" t t x)))
4898 targets
4899 "\\|")
4900 "\\)\\>")))
4902 (defun org-activate-tags (limit)
4903 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4904 (progn
4905 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
4906 (add-text-properties (match-beginning 1) (match-end 1)
4907 (list 'mouse-face 'highlight
4908 'keymap org-mouse-map))
4909 (org-rear-nonsticky-at (match-end 1))
4910 t)))
4912 (defun org-outline-level ()
4913 "Compute the outline level of the heading at point.
4914 This function assumes that the cursor is at the beginning of a line matched
4915 by outline-regexp. Otherwise it returns garbage.
4916 If this is called at a normal headline, the level is the number of stars.
4917 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4918 For plain list items, if they are matched by `outline-regexp', this returns
4919 1000 plus the line indentation."
4920 (save-excursion
4921 (looking-at outline-regexp)
4922 (if (match-beginning 1)
4923 (+ (org-get-string-indentation (match-string 1)) 1000)
4924 (1- (- (match-end 0) (match-beginning 0))))))
4926 (defvar org-font-lock-keywords nil)
4928 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4929 "Regular expression matching a property line.")
4931 (defvar org-font-lock-hook nil
4932 "Functions to be called for special font lock stuff.")
4934 (defun org-font-lock-hook (limit)
4935 (run-hook-with-args 'org-font-lock-hook limit))
4937 (defun org-set-font-lock-defaults ()
4938 (let* ((em org-fontify-emphasized-text)
4939 (lk org-activate-links)
4940 (org-font-lock-extra-keywords
4941 (list
4942 ;; Call the hook
4943 '(org-font-lock-hook)
4944 ;; Headlines
4945 `(,(if org-fontify-whole-heading-line
4946 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4947 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4948 (1 (org-get-level-face 1))
4949 (2 (org-get-level-face 2))
4950 (3 (org-get-level-face 3)))
4951 ;; Table lines
4952 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4953 (1 'org-table t))
4954 ;; Table internals
4955 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4956 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4957 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4958 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4959 ;; Drawers
4960 (list org-drawer-regexp '(0 'org-special-keyword t))
4961 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4962 ;; Properties
4963 (list org-property-re
4964 '(1 'org-special-keyword t)
4965 '(3 'org-property-value t))
4966 ;; Links
4967 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4968 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4969 (if (memq 'plain lk) '(org-activate-plain-links))
4970 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4971 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4972 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4973 (if (memq 'footnote lk) '(org-activate-footnote-links
4974 (2 'org-footnote t)))
4975 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4976 '(org-hide-wide-columns (0 nil append))
4977 ;; TODO lines
4978 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4979 '(1 (org-get-todo-face 1) t))
4980 ;; DONE
4981 (if org-fontify-done-headline
4982 (list (concat "^[*]+ +\\<\\("
4983 (mapconcat 'regexp-quote org-done-keywords "\\|")
4984 "\\)\\(.*\\)")
4985 '(2 'org-headline-done t))
4986 nil)
4987 ;; Priorities
4988 '(org-font-lock-add-priority-faces)
4989 ;; Tags
4990 '(org-font-lock-add-tag-faces)
4991 ;; Special keywords
4992 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4993 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4994 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4995 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4996 ;; Emphasis
4997 (if em
4998 (if (featurep 'xemacs)
4999 '(org-do-emphasis-faces (0 nil append))
5000 '(org-do-emphasis-faces)))
5001 ;; Checkboxes
5002 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5003 2 'org-checkbox prepend)
5004 (if org-provide-checkbox-statistics
5005 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5006 (0 (org-get-checkbox-statistics-face) t)))
5007 ;; Description list items
5008 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5009 2 'bold prepend)
5010 ;; ARCHIVEd headings
5011 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5012 '(1 'org-archived prepend))
5013 ;; Specials
5014 '(org-do-latex-and-special-faces)
5015 ;; Code
5016 '(org-activate-code (1 'org-code t))
5017 ;; COMMENT
5018 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5019 "\\|" org-quote-string "\\)\\>")
5020 '(1 'org-special-keyword t))
5021 '("^#.*" (0 'font-lock-comment-face t))
5022 ;; Blocks and meta lines
5023 '(org-fontify-meta-lines-and-blocks)
5025 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5026 ;; Now set the full font-lock-keywords
5027 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5028 (org-set-local 'font-lock-defaults
5029 '(org-font-lock-keywords t nil nil backward-paragraph))
5030 (kill-local-variable 'font-lock-keywords) nil))
5032 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5033 "Fontify string S like in Org-mode"
5034 (with-temp-buffer
5035 (insert s)
5036 (let ((org-odd-levels-only odd-levels))
5037 (org-mode)
5038 (font-lock-fontify-buffer)
5039 (buffer-string))))
5041 (defvar org-m nil)
5042 (defvar org-l nil)
5043 (defvar org-f nil)
5044 (defun org-get-level-face (n)
5045 "Get the right face for match N in font-lock matching of headlines."
5046 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5047 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5048 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5049 (cond
5050 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5051 ((eq n 2) org-f)
5052 (t (if org-level-color-stars-only nil org-f))))
5054 (defun org-get-todo-face (kwd)
5055 "Get the right face for a TODO keyword KWD.
5056 If KWD is a number, get the corresponding match group."
5057 (if (numberp kwd) (setq kwd (match-string kwd)))
5058 (or (cdr (assoc kwd org-todo-keyword-faces))
5059 (and (member kwd org-done-keywords) 'org-done)
5060 'org-todo))
5062 (defun org-font-lock-add-tag-faces (limit)
5063 "Add the special tag faces."
5064 (when (and org-tag-faces org-tags-special-faces-re)
5065 (while (re-search-forward org-tags-special-faces-re limit t)
5066 (add-text-properties (match-beginning 1) (match-end 1)
5067 (list 'face (org-get-tag-face 1)
5068 'font-lock-fontified t))
5069 (backward-char 1))))
5071 (defun org-font-lock-add-priority-faces (limit)
5072 "Add the special priority faces."
5073 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5074 (add-text-properties
5075 (match-beginning 0) (match-end 0)
5076 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
5077 org-priority-faces))
5078 'org-special-keyword)
5079 'font-lock-fontified t))))
5081 (defun org-get-tag-face (kwd)
5082 "Get the right face for a TODO keyword KWD.
5083 If KWD is a number, get the corresponding match group."
5084 (if (numberp kwd) (setq kwd (match-string kwd)))
5085 (or (cdr (assoc kwd org-tag-faces))
5086 'org-tag))
5088 (defun org-unfontify-region (beg end &optional maybe_loudly)
5089 "Remove fontification and activation overlays from links."
5090 (font-lock-default-unfontify-region beg end)
5091 (let* ((buffer-undo-list t)
5092 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5093 (inhibit-modification-hooks t)
5094 deactivate-mark buffer-file-name buffer-file-truename)
5095 (remove-text-properties
5096 beg end
5097 (if org-indent-mode
5098 ;; also remove line-prefix and wrap-prefix properties
5099 '(mouse-face t keymap t org-linked-text t
5100 invisible t intangible t
5101 line-prefix t wrap-prefix t
5102 org-no-flyspell t)
5103 '(mouse-face t keymap t org-linked-text t
5104 invisible t intangible t
5105 org-no-flyspell t)))))
5107 ;;;; Visibility cycling, including org-goto and indirect buffer
5109 ;;; Cycling
5111 (defvar org-cycle-global-status nil)
5112 (make-variable-buffer-local 'org-cycle-global-status)
5113 (defvar org-cycle-subtree-status nil)
5114 (make-variable-buffer-local 'org-cycle-subtree-status)
5116 ;;;###autoload
5118 (defvar org-inlinetask-min-level)
5120 (defun org-cycle (&optional arg)
5121 "TAB-action and visibility cycling for Org-mode.
5123 This is the command invoked in Org-mode by the TAB key. Its main purpose
5124 is outline visibility cycling, but it also invokes other actions
5125 in special contexts.
5127 - When this function is called with a prefix argument, rotate the entire
5128 buffer through 3 states (global cycling)
5129 1. OVERVIEW: Show only top-level headlines.
5130 2. CONTENTS: Show all headlines of all levels, but no body text.
5131 3. SHOW ALL: Show everything.
5132 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5133 determined by the variable `org-startup-folded', and by any VISIBILITY
5134 properties in the buffer.
5135 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5136 including any drawers.
5138 - When inside a table, re-align the table and move to the next field.
5140 - When point is at the beginning of a headline, rotate the subtree started
5141 by this line through 3 different states (local cycling)
5142 1. FOLDED: Only the main headline is shown.
5143 2. CHILDREN: The main headline and the direct children are shown.
5144 From this state, you can move to one of the children
5145 and zoom in further.
5146 3. SUBTREE: Show the entire subtree, including body text.
5147 If there is no subtree, switch directly from CHILDREN to FOLDED.
5149 - When there is a numeric prefix, go up to a heading with level ARG, do
5150 a `show-subtree' and return to the previous cursor position. If ARG
5151 is negative, go up that many levels.
5153 - When point is not at the beginning of a headline, execute the global
5154 binding for TAB, which is re-indenting the line. See the option
5155 `org-cycle-emulate-tab' for details.
5157 - Special case: if point is at the beginning of the buffer and there is
5158 no headline in line 1, this function will act as if called with prefix arg.
5159 But only if also the variable `org-cycle-global-at-bob' is t."
5160 (interactive "P")
5161 (org-load-modules-maybe)
5162 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5163 (and org-cycle-level-after-item/entry-creation
5164 (or (org-cycle-level)
5165 (org-cycle-item-indentation))))
5166 (let* ((limit-level
5167 (or org-cycle-max-level
5168 (and (boundp 'org-inlinetask-min-level)
5169 org-inlinetask-min-level
5170 (1- org-inlinetask-min-level))))
5171 (nstars (and limit-level
5172 (if org-odd-levels-only
5173 (and limit-level (1- (* limit-level 2)))
5174 limit-level)))
5175 (outline-regexp
5176 (cond
5177 ((not (org-mode-p)) outline-regexp)
5178 ((or (eq org-cycle-include-plain-lists 'integrate)
5179 (and org-cycle-include-plain-lists (org-at-item-p)))
5180 (concat "\\(?:\\*"
5181 (if nstars (format "\\{1,%d\\}" nstars) "+")
5182 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5183 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5184 (bob-special (and org-cycle-global-at-bob (bobp)
5185 (not (looking-at outline-regexp))))
5186 (org-cycle-hook
5187 (if bob-special
5188 (delq 'org-optimize-window-after-visibility-change
5189 (copy-sequence org-cycle-hook))
5190 org-cycle-hook))
5191 (pos (point)))
5193 (if (or bob-special (equal arg '(4)))
5194 ;; special case: use global cycling
5195 (setq arg t))
5197 (cond
5199 ((equal arg '(16))
5200 (org-set-startup-visibility)
5201 (message "Startup visibility, plus VISIBILITY properties"))
5203 ((equal arg '(64))
5204 (show-all)
5205 (message "Entire buffer visible, including drawers"))
5207 ((org-at-table-p 'any)
5208 ;; Enter the table or move to the next field in the table
5209 (or (org-table-recognize-table.el)
5210 (progn
5211 (if arg (org-table-edit-field t)
5212 (org-table-justify-field-maybe)
5213 (call-interactively 'org-table-next-field)))))
5215 ((run-hook-with-args-until-success
5216 'org-tab-after-check-for-table-hook))
5218 ((eq arg t) ;; Global cycling
5219 (org-cycle-internal-global))
5221 ((and org-drawers org-drawer-regexp
5222 (save-excursion
5223 (beginning-of-line 1)
5224 (looking-at org-drawer-regexp)))
5225 ;; Toggle block visibility
5226 (org-flag-drawer
5227 (not (get-char-property (match-end 0) 'invisible))))
5229 ((integerp arg)
5230 ;; Show-subtree, ARG levels up from here.
5231 (save-excursion
5232 (org-back-to-heading)
5233 (outline-up-heading (if (< arg 0) (- arg)
5234 (- (funcall outline-level) arg)))
5235 (org-show-subtree)))
5237 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5238 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5240 (org-cycle-internal-local))
5242 ;; TAB emulation and template completion
5243 (buffer-read-only (org-back-to-heading))
5245 ((run-hook-with-args-until-success
5246 'org-tab-after-check-for-cycling-hook))
5248 ((org-try-structure-completion))
5250 ((org-try-cdlatex-tab))
5252 ((run-hook-with-args-until-success
5253 'org-tab-before-tab-emulation-hook))
5255 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5256 (or (not (bolp))
5257 (not (looking-at outline-regexp))))
5258 (call-interactively (global-key-binding "\t")))
5260 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5261 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5262 (or (and (eq org-cycle-emulate-tab 'white)
5263 (= (match-end 0) (point-at-eol)))
5264 (and (eq org-cycle-emulate-tab 'whitestart)
5265 (>= (match-end 0) pos))))
5267 (eq org-cycle-emulate-tab t))
5268 (call-interactively (global-key-binding "\t")))
5270 (t (save-excursion
5271 (org-back-to-heading)
5272 (org-cycle)))))))
5274 (defun org-cycle-internal-global ()
5275 "Do the global cycling action."
5276 (cond
5277 ((and (eq last-command this-command)
5278 (eq org-cycle-global-status 'overview))
5279 ;; We just created the overview - now do table of contents
5280 ;; This can be slow in very large buffers, so indicate action
5281 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5282 (message "CONTENTS...")
5283 (org-content)
5284 (message "CONTENTS...done")
5285 (setq org-cycle-global-status 'contents)
5286 (run-hook-with-args 'org-cycle-hook 'contents))
5288 ((and (eq last-command this-command)
5289 (eq org-cycle-global-status 'contents))
5290 ;; We just showed the table of contents - now show everything
5291 (run-hook-with-args 'org-pre-cycle-hook 'all)
5292 (show-all)
5293 (message "SHOW ALL")
5294 (setq org-cycle-global-status 'all)
5295 (run-hook-with-args 'org-cycle-hook 'all))
5298 ;; Default action: go to overview
5299 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5300 (org-overview)
5301 (message "OVERVIEW")
5302 (setq org-cycle-global-status 'overview)
5303 (run-hook-with-args 'org-cycle-hook 'overview))))
5305 (defun org-cycle-internal-local ()
5306 "Do the local cycling action."
5307 (org-back-to-heading)
5308 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5309 ;; First, some boundaries
5310 (save-excursion
5311 (org-back-to-heading)
5312 (setq level (funcall outline-level))
5313 (save-excursion
5314 (beginning-of-line 2)
5315 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5316 ; XEmacs does not have `next-single-char-property-change'
5317 ; I'm not sure about Emacs 21.
5318 (while (and (not (eobp)) ;; this is like `next-line'
5319 (get-char-property (1- (point)) 'invisible))
5320 (beginning-of-line 2))
5321 (while (and (not (eobp)) ;; this is like `next-line'
5322 (get-char-property (1- (point)) 'invisible))
5323 (goto-char (next-single-char-property-change (point) 'invisible))
5324 ;;;??? (or (bolp) (beginning-of-line 2))))
5325 (and (eolp) (beginning-of-line 2))))
5326 (setq eol (point)))
5327 (outline-end-of-heading) (setq eoh (point))
5328 (save-excursion
5329 (outline-next-heading)
5330 (setq has-children (and (org-at-heading-p t)
5331 (> (funcall outline-level) level))))
5332 (org-end-of-subtree t)
5333 (unless (eobp)
5334 (skip-chars-forward " \t\n")
5335 (beginning-of-line 1) ; in case this is an item
5337 (setq eos (if (eobp) (point) (1- (point)))))
5338 ;; Find out what to do next and set `this-command'
5339 (cond
5340 ((= eos eoh)
5341 ;; Nothing is hidden behind this heading
5342 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5343 (message "EMPTY ENTRY")
5344 (setq org-cycle-subtree-status nil)
5345 (save-excursion
5346 (goto-char eos)
5347 (outline-next-heading)
5348 (if (org-invisible-p) (org-flag-heading nil))))
5349 ((and (or (>= eol eos)
5350 (not (string-match "\\S-" (buffer-substring eol eos))))
5351 (or has-children
5352 (not (setq children-skipped
5353 org-cycle-skip-children-state-if-no-children))))
5354 ;; Entire subtree is hidden in one line: children view
5355 (run-hook-with-args 'org-pre-cycle-hook 'children)
5356 (org-show-entry)
5357 (show-children)
5358 (message "CHILDREN")
5359 (save-excursion
5360 (goto-char eos)
5361 (outline-next-heading)
5362 (if (org-invisible-p) (org-flag-heading nil)))
5363 (setq org-cycle-subtree-status 'children)
5364 (run-hook-with-args 'org-cycle-hook 'children))
5365 ((or children-skipped
5366 (and (eq last-command this-command)
5367 (eq org-cycle-subtree-status 'children)))
5368 ;; We just showed the children, or no children are there,
5369 ;; now show everything.
5370 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5371 (org-show-subtree)
5372 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5373 (setq org-cycle-subtree-status 'subtree)
5374 (run-hook-with-args 'org-cycle-hook 'subtree))
5376 ;; Default action: hide the subtree.
5377 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5378 (hide-subtree)
5379 (message "FOLDED")
5380 (setq org-cycle-subtree-status 'folded)
5381 (run-hook-with-args 'org-cycle-hook 'folded)))))
5383 ;;;###autoload
5384 (defun org-global-cycle (&optional arg)
5385 "Cycle the global visibility. For details see `org-cycle'.
5386 With C-u prefix arg, switch to startup visibility.
5387 With a numeric prefix, show all headlines up to that level."
5388 (interactive "P")
5389 (let ((org-cycle-include-plain-lists
5390 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5391 (cond
5392 ((integerp arg)
5393 (show-all)
5394 (hide-sublevels arg)
5395 (setq org-cycle-global-status 'contents))
5396 ((equal arg '(4))
5397 (org-set-startup-visibility)
5398 (message "Startup visibility, plus VISIBILITY properties."))
5400 (org-cycle '(4))))))
5402 (defun org-set-startup-visibility ()
5403 "Set the visibility required by startup options and properties."
5404 (cond
5405 ((eq org-startup-folded t)
5406 (org-cycle '(4)))
5407 ((eq org-startup-folded 'content)
5408 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5409 (org-cycle '(4)) (org-cycle '(4)))))
5410 (unless (eq org-startup-folded 'showeverything)
5411 (if org-hide-block-startup (org-hide-block-all))
5412 (org-set-visibility-according-to-property 'no-cleanup)
5413 (org-cycle-hide-archived-subtrees 'all)
5414 (org-cycle-hide-drawers 'all)
5415 (org-cycle-show-empty-lines 'all)))
5417 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5418 "Switch subtree visibilities according to :VISIBILITY: property."
5419 (interactive)
5420 (let (org-show-entry-below state)
5421 (save-excursion
5422 (goto-char (point-min))
5423 (while (re-search-forward
5424 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5425 nil t)
5426 (setq state (match-string 1))
5427 (save-excursion
5428 (org-back-to-heading t)
5429 (hide-subtree)
5430 (org-reveal)
5431 (cond
5432 ((equal state '("fold" "folded"))
5433 (hide-subtree))
5434 ((equal state "children")
5435 (org-show-hidden-entry)
5436 (show-children))
5437 ((equal state "content")
5438 (save-excursion
5439 (save-restriction
5440 (org-narrow-to-subtree)
5441 (org-content))))
5442 ((member state '("all" "showall"))
5443 (show-subtree)))))
5444 (unless no-cleanup
5445 (org-cycle-hide-archived-subtrees 'all)
5446 (org-cycle-hide-drawers 'all)
5447 (org-cycle-show-empty-lines 'all)))))
5449 (defun org-overview ()
5450 "Switch to overview mode, showing only top-level headlines.
5451 Really, this shows all headlines with level equal or greater than the level
5452 of the first headline in the buffer. This is important, because if the
5453 first headline is not level one, then (hide-sublevels 1) gives confusing
5454 results."
5455 (interactive)
5456 (let ((level (save-excursion
5457 (goto-char (point-min))
5458 (if (re-search-forward (concat "^" outline-regexp) nil t)
5459 (progn
5460 (goto-char (match-beginning 0))
5461 (funcall outline-level))))))
5462 (and level (hide-sublevels level))))
5464 (defun org-content (&optional arg)
5465 "Show all headlines in the buffer, like a table of contents.
5466 With numerical argument N, show content up to level N."
5467 (interactive "P")
5468 (save-excursion
5469 ;; Visit all headings and show their offspring
5470 (and (integerp arg) (org-overview))
5471 (goto-char (point-max))
5472 (catch 'exit
5473 (while (and (progn (condition-case nil
5474 (outline-previous-visible-heading 1)
5475 (error (goto-char (point-min))))
5477 (looking-at outline-regexp))
5478 (if (integerp arg)
5479 (show-children (1- arg))
5480 (show-branches))
5481 (if (bobp) (throw 'exit nil))))))
5484 (defun org-optimize-window-after-visibility-change (state)
5485 "Adjust the window after a change in outline visibility.
5486 This function is the default value of the hook `org-cycle-hook'."
5487 (when (get-buffer-window (current-buffer))
5488 (cond
5489 ((eq state 'content) nil)
5490 ((eq state 'all) nil)
5491 ((eq state 'folded) nil)
5492 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5493 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5495 (defun org-remove-empty-overlays-at (pos)
5496 "Remove outline overlays that do not contain non-white stuff."
5497 (mapc
5498 (lambda (o)
5499 (and (eq 'outline (org-overlay-get o 'invisible))
5500 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5501 (org-overlay-end o))))
5502 (org-delete-overlay o)))
5503 (org-overlays-at pos)))
5505 (defun org-clean-visibility-after-subtree-move ()
5506 "Fix visibility issues after moving a subtree."
5507 ;; First, find a reasonable region to look at:
5508 ;; Start two siblings above, end three below
5509 (let* ((beg (save-excursion
5510 (and (org-get-last-sibling)
5511 (org-get-last-sibling))
5512 (point)))
5513 (end (save-excursion
5514 (and (org-get-next-sibling)
5515 (org-get-next-sibling)
5516 (org-get-next-sibling))
5517 (if (org-at-heading-p)
5518 (point-at-eol)
5519 (point))))
5520 (level (looking-at "\\*+"))
5521 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5522 (save-excursion
5523 (save-restriction
5524 (narrow-to-region beg end)
5525 (when re
5526 ;; Properly fold already folded siblings
5527 (goto-char (point-min))
5528 (while (re-search-forward re nil t)
5529 (if (and (not (org-invisible-p))
5530 (save-excursion
5531 (goto-char (point-at-eol)) (org-invisible-p)))
5532 (hide-entry))))
5533 (org-cycle-show-empty-lines 'overview)
5534 (org-cycle-hide-drawers 'overview)))))
5536 (defun org-cycle-show-empty-lines (state)
5537 "Show empty lines above all visible headlines.
5538 The region to be covered depends on STATE when called through
5539 `org-cycle-hook'. Lisp program can use t for STATE to get the
5540 entire buffer covered. Note that an empty line is only shown if there
5541 are at least `org-cycle-separator-lines' empty lines before the headline."
5542 (when (not (= org-cycle-separator-lines 0))
5543 (save-excursion
5544 (let* ((n (abs org-cycle-separator-lines))
5545 (re (cond
5546 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5547 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5548 (t (let ((ns (number-to-string (- n 2))))
5549 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5550 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5551 beg end b e)
5552 (cond
5553 ((memq state '(overview contents t))
5554 (setq beg (point-min) end (point-max)))
5555 ((memq state '(children folded))
5556 (setq beg (point) end (progn (org-end-of-subtree t t)
5557 (beginning-of-line 2)
5558 (point)))))
5559 (when beg
5560 (goto-char beg)
5561 (while (re-search-forward re end t)
5562 (unless (get-char-property (match-end 1) 'invisible)
5563 (setq e (match-end 1))
5564 (if (< org-cycle-separator-lines 0)
5565 (setq b (save-excursion
5566 (goto-char (match-beginning 0))
5567 (org-back-over-empty-lines)
5568 (if (save-excursion
5569 (goto-char (max (point-min) (1- (point))))
5570 (org-on-heading-p))
5571 (1- (point))
5572 (point))))
5573 (setq b (match-beginning 1)))
5574 (outline-flag-region b e nil)))))))
5575 ;; Never hide empty lines at the end of the file.
5576 (save-excursion
5577 (goto-char (point-max))
5578 (outline-previous-heading)
5579 (outline-end-of-heading)
5580 (if (and (looking-at "[ \t\n]+")
5581 (= (match-end 0) (point-max)))
5582 (outline-flag-region (point) (match-end 0) nil))))
5584 (defun org-show-empty-lines-in-parent ()
5585 "Move to the parent and re-show empty lines before visible headlines."
5586 (save-excursion
5587 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5588 (org-cycle-show-empty-lines context))))
5590 (defun org-files-list ()
5591 "Return `org-agenda-files' list, plus all open org-mode files.
5592 This is useful for operations that need to scan all of a user's
5593 open and agenda-wise Org files."
5594 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5595 (dolist (buf (buffer-list))
5596 (with-current-buffer buf
5597 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5598 (let ((file (expand-file-name (buffer-file-name))))
5599 (unless (member file files)
5600 (push file files))))))
5601 files))
5603 (defsubst org-entry-beginning-position ()
5604 "Return the beginning position of the current entry."
5605 (save-excursion (outline-back-to-heading t) (point)))
5607 (defsubst org-entry-end-position ()
5608 "Return the end position of the current entry."
5609 (save-excursion (outline-next-heading) (point)))
5611 (defun org-cycle-hide-drawers (state)
5612 "Re-hide all drawers after a visibility state change."
5613 (when (and (org-mode-p)
5614 (not (memq state '(overview folded contents))))
5615 (save-excursion
5616 (let* ((globalp (memq state '(contents all)))
5617 (beg (if globalp (point-min) (point)))
5618 (end (if globalp (point-max)
5619 (if (eq state 'children)
5620 (save-excursion (outline-next-heading) (point))
5621 (org-end-of-subtree t)))))
5622 (goto-char beg)
5623 (while (re-search-forward org-drawer-regexp end t)
5624 (org-flag-drawer t))))))
5626 (defun org-flag-drawer (flag)
5627 (save-excursion
5628 (beginning-of-line 1)
5629 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5630 (let ((b (match-end 0))
5631 (outline-regexp org-outline-regexp))
5632 (if (re-search-forward
5633 "^[ \t]*:END:"
5634 (save-excursion (outline-next-heading) (point)) t)
5635 (outline-flag-region b (point-at-eol) flag)
5636 (error ":END: line missing at position %s" b))))))
5638 (defun org-subtree-end-visible-p ()
5639 "Is the end of the current subtree visible?"
5640 (pos-visible-in-window-p
5641 (save-excursion (org-end-of-subtree t) (point))))
5643 (defun org-first-headline-recenter (&optional N)
5644 "Move cursor to the first headline and recenter the headline.
5645 Optional argument N means, put the headline into the Nth line of the window."
5646 (goto-char (point-min))
5647 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5648 (beginning-of-line)
5649 (recenter (prefix-numeric-value N))))
5651 ;;; Saving and restoring visibility
5653 (defun org-outline-overlay-data (&optional use-markers)
5654 "Return a list of the locations of all outline overlays.
5655 The are overlays with the `invisible' property value `outline'.
5656 The return valus is a list of cons cells, with start and stop
5657 positions for each overlay.
5658 If USE-MARKERS is set, return the positions as markers."
5659 (let (beg end)
5660 (save-excursion
5661 (save-restriction
5662 (widen)
5663 (delq nil
5664 (mapcar (lambda (o)
5665 (when (eq (org-overlay-get o 'invisible) 'outline)
5666 (setq beg (org-overlay-start o)
5667 end (org-overlay-end o))
5668 (and beg end (> end beg)
5669 (if use-markers
5670 (cons (move-marker (make-marker) beg)
5671 (move-marker (make-marker) end))
5672 (cons beg end)))))
5673 (org-overlays-in (point-min) (point-max))))))))
5675 (defun org-set-outline-overlay-data (data)
5676 "Create visibility overlays for all positions in DATA.
5677 DATA should have been made by `org-outline-overlay-data'."
5678 (let (o)
5679 (save-excursion
5680 (save-restriction
5681 (widen)
5682 (show-all)
5683 (mapc (lambda (c)
5684 (setq o (org-make-overlay (car c) (cdr c)))
5685 (org-overlay-put o 'invisible 'outline))
5686 data)))))
5688 (defmacro org-save-outline-visibility (use-markers &rest body)
5689 "Save and restore outline visibility around BODY.
5690 If USE-MARKERS is non-nil, use markers for the positions.
5691 This means that the buffer may change while running BODY,
5692 but it also means that the buffer should stay alive
5693 during the operation, because otherwise all these markers will
5694 point nowhere."
5695 `(let ((data (org-outline-overlay-data ,use-markers)))
5696 (unwind-protect
5697 (progn
5698 ,@body
5699 (org-set-outline-overlay-data data))
5700 (when ,use-markers
5701 (mapc (lambda (c)
5702 (and (markerp (car c)) (move-marker (car c) nil))
5703 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
5704 data)))))
5707 ;;; Folding of blocks
5709 (defconst org-block-regexp
5711 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5712 "Regular expression for hiding blocks.")
5714 (defvar org-hide-block-overlays nil
5715 "Overlays hiding blocks.")
5716 (make-variable-buffer-local 'org-hide-block-overlays)
5718 (defun org-block-map (function &optional start end)
5719 "Call func at the head of all source blocks in the current
5720 buffer. Optional arguments START and END can be used to limit
5721 the range."
5722 (let ((start (or start (point-min)))
5723 (end (or end (point-max))))
5724 (save-excursion
5725 (goto-char start)
5726 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5727 (save-excursion
5728 (save-match-data
5729 (goto-char (match-beginning 0))
5730 (funcall function)))))))
5732 (defun org-hide-block-toggle-all ()
5733 "Toggle the visibility of all blocks in the current buffer."
5734 (org-block-map #'org-hide-block-toggle))
5736 (defun org-hide-block-all ()
5737 "Fold all blocks in the current buffer."
5738 (interactive)
5739 (org-show-block-all)
5740 (org-block-map #'org-hide-block-toggle-maybe))
5742 (defun org-show-block-all ()
5743 "Unfold all blocks in the current buffer."
5744 (mapc 'org-delete-overlay org-hide-block-overlays)
5745 (setq org-hide-block-overlays nil))
5747 (defun org-hide-block-toggle-maybe ()
5748 "Toggle visibility of block at point."
5749 (interactive)
5750 (let ((case-fold-search t))
5751 (if (save-excursion
5752 (beginning-of-line 1)
5753 (looking-at org-block-regexp))
5754 (progn (org-hide-block-toggle)
5755 t) ;; to signal that we took action
5756 nil))) ;; to signal that we did not
5758 (defun org-hide-block-toggle (&optional force)
5759 "Toggle the visibility of the current block."
5760 (interactive)
5761 (save-excursion
5762 (beginning-of-line)
5763 (if (re-search-forward org-block-regexp nil t)
5764 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5765 (end (match-end 0)) ;; end of entire body
5767 (if (memq t (mapcar (lambda (overlay)
5768 (eq (org-overlay-get overlay 'invisible)
5769 'org-hide-block))
5770 (org-overlays-at start)))
5771 (if (or (not force) (eq force 'off))
5772 (mapc (lambda (ov)
5773 (when (member ov org-hide-block-overlays)
5774 (setq org-hide-block-overlays
5775 (delq ov org-hide-block-overlays)))
5776 (when (eq (org-overlay-get ov 'invisible)
5777 'org-hide-block)
5778 (org-delete-overlay ov)))
5779 (org-overlays-at start)))
5780 (setq ov (org-make-overlay start end))
5781 (org-overlay-put ov 'invisible 'org-hide-block)
5782 ;; make the block accessible to isearch
5783 (org-overlay-put
5784 ov 'isearch-open-invisible
5785 (lambda (ov)
5786 (when (member ov org-hide-block-overlays)
5787 (setq org-hide-block-overlays
5788 (delq ov org-hide-block-overlays)))
5789 (when (eq (org-overlay-get ov 'invisible)
5790 'org-hide-block)
5791 (org-delete-overlay ov))))
5792 (push ov org-hide-block-overlays)))
5793 (error "Not looking at a source block"))))
5795 ;; org-tab-after-check-for-cycling-hook
5796 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5797 ;; Remove overlays when changing major mode
5798 (add-hook 'org-mode-hook
5799 (lambda () (org-add-hook 'change-major-mode-hook
5800 'org-show-block-all 'append 'local)))
5802 ;;; Org-goto
5804 (defvar org-goto-window-configuration nil)
5805 (defvar org-goto-marker nil)
5806 (defvar org-goto-map
5807 (let ((map (make-sparse-keymap)))
5808 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5809 (while (setq cmd (pop cmds))
5810 (substitute-key-definition cmd cmd map global-map)))
5811 (suppress-keymap map)
5812 (org-defkey map "\C-m" 'org-goto-ret)
5813 (org-defkey map [(return)] 'org-goto-ret)
5814 (org-defkey map [(left)] 'org-goto-left)
5815 (org-defkey map [(right)] 'org-goto-right)
5816 (org-defkey map [(control ?g)] 'org-goto-quit)
5817 (org-defkey map "\C-i" 'org-cycle)
5818 (org-defkey map [(tab)] 'org-cycle)
5819 (org-defkey map [(down)] 'outline-next-visible-heading)
5820 (org-defkey map [(up)] 'outline-previous-visible-heading)
5821 (if org-goto-auto-isearch
5822 (if (fboundp 'define-key-after)
5823 (define-key-after map [t] 'org-goto-local-auto-isearch)
5824 nil)
5825 (org-defkey map "q" 'org-goto-quit)
5826 (org-defkey map "n" 'outline-next-visible-heading)
5827 (org-defkey map "p" 'outline-previous-visible-heading)
5828 (org-defkey map "f" 'outline-forward-same-level)
5829 (org-defkey map "b" 'outline-backward-same-level)
5830 (org-defkey map "u" 'outline-up-heading))
5831 (org-defkey map "/" 'org-occur)
5832 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5833 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5834 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5835 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5836 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5837 map))
5839 (defconst org-goto-help
5840 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5841 RET=jump to location [Q]uit and return to previous location
5842 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5844 (defvar org-goto-start-pos) ; dynamically scoped parameter
5846 ;; FIXME: Docstring does not mention both interfaces
5847 (defun org-goto (&optional alternative-interface)
5848 "Look up a different location in the current file, keeping current visibility.
5850 When you want look-up or go to a different location in a document, the
5851 fastest way is often to fold the entire buffer and then dive into the tree.
5852 This method has the disadvantage, that the previous location will be folded,
5853 which may not be what you want.
5855 This command works around this by showing a copy of the current buffer
5856 in an indirect buffer, in overview mode. You can dive into the tree in
5857 that copy, use org-occur and incremental search to find a location.
5858 When pressing RET or `Q', the command returns to the original buffer in
5859 which the visibility is still unchanged. After RET is will also jump to
5860 the location selected in the indirect buffer and expose the
5861 the headline hierarchy above."
5862 (interactive "P")
5863 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5864 (org-refile-use-outline-path t)
5865 (org-refile-target-verify-function nil)
5866 (interface
5867 (if (not alternative-interface)
5868 org-goto-interface
5869 (if (eq org-goto-interface 'outline)
5870 'outline-path-completion
5871 'outline)))
5872 (org-goto-start-pos (point))
5873 (selected-point
5874 (if (eq interface 'outline)
5875 (car (org-get-location (current-buffer) org-goto-help))
5876 (nth 3 (org-refile-get-location "Goto: ")))))
5877 (if selected-point
5878 (progn
5879 (org-mark-ring-push org-goto-start-pos)
5880 (goto-char selected-point)
5881 (if (or (org-invisible-p) (org-invisible-p2))
5882 (org-show-context 'org-goto)))
5883 (message "Quit"))))
5885 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5886 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5887 (defvar org-goto-local-auto-isearch-map) ; defined below
5889 (defun org-get-location (buf help)
5890 "Let the user select a location in the Org-mode buffer BUF.
5891 This function uses a recursive edit. It returns the selected position
5892 or nil."
5893 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5894 (isearch-hide-immediately nil)
5895 (isearch-search-fun-function
5896 (lambda () 'org-goto-local-search-headings))
5897 (org-goto-selected-point org-goto-exit-command))
5898 (save-excursion
5899 (save-window-excursion
5900 (delete-other-windows)
5901 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5902 (switch-to-buffer
5903 (condition-case nil
5904 (make-indirect-buffer (current-buffer) "*org-goto*")
5905 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5906 (with-output-to-temp-buffer "*Help*"
5907 (princ help))
5908 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5909 (setq buffer-read-only nil)
5910 (let ((org-startup-truncated t)
5911 (org-startup-folded nil)
5912 (org-startup-align-all-tables nil))
5913 (org-mode)
5914 (org-overview))
5915 (setq buffer-read-only t)
5916 (if (and (boundp 'org-goto-start-pos)
5917 (integer-or-marker-p org-goto-start-pos))
5918 (let ((org-show-hierarchy-above t)
5919 (org-show-siblings t)
5920 (org-show-following-heading t))
5921 (goto-char org-goto-start-pos)
5922 (and (org-invisible-p) (org-show-context)))
5923 (goto-char (point-min)))
5924 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5925 (message "Select location and press RET")
5926 (use-local-map org-goto-map)
5927 (recursive-edit)
5929 (kill-buffer "*org-goto*")
5930 (cons org-goto-selected-point org-goto-exit-command)))
5932 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5933 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5934 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5935 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5937 (defun org-goto-local-search-headings (string bound noerror)
5938 "Search and make sure that any matches are in headlines."
5939 (catch 'return
5940 (while (if isearch-forward
5941 (search-forward string bound noerror)
5942 (search-backward string bound noerror))
5943 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5944 (and (member :headline context)
5945 (not (member :tags context))))
5946 (throw 'return (point))))))
5948 (defun org-goto-local-auto-isearch ()
5949 "Start isearch."
5950 (interactive)
5951 (goto-char (point-min))
5952 (let ((keys (this-command-keys)))
5953 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5954 (isearch-mode t)
5955 (isearch-process-search-char (string-to-char keys)))))
5957 (defun org-goto-ret (&optional arg)
5958 "Finish `org-goto' by going to the new location."
5959 (interactive "P")
5960 (setq org-goto-selected-point (point)
5961 org-goto-exit-command 'return)
5962 (throw 'exit nil))
5964 (defun org-goto-left ()
5965 "Finish `org-goto' by going to the new location."
5966 (interactive)
5967 (if (org-on-heading-p)
5968 (progn
5969 (beginning-of-line 1)
5970 (setq org-goto-selected-point (point)
5971 org-goto-exit-command 'left)
5972 (throw 'exit nil))
5973 (error "Not on a heading")))
5975 (defun org-goto-right ()
5976 "Finish `org-goto' by going to the new location."
5977 (interactive)
5978 (if (org-on-heading-p)
5979 (progn
5980 (setq org-goto-selected-point (point)
5981 org-goto-exit-command 'right)
5982 (throw 'exit nil))
5983 (error "Not on a heading")))
5985 (defun org-goto-quit ()
5986 "Finish `org-goto' without cursor motion."
5987 (interactive)
5988 (setq org-goto-selected-point nil)
5989 (setq org-goto-exit-command 'quit)
5990 (throw 'exit nil))
5992 ;;; Indirect buffer display of subtrees
5994 (defvar org-indirect-dedicated-frame nil
5995 "This is the frame being used for indirect tree display.")
5996 (defvar org-last-indirect-buffer nil)
5998 (defun org-tree-to-indirect-buffer (&optional arg)
5999 "Create indirect buffer and narrow it to current subtree.
6000 With numerical prefix ARG, go up to this level and then take that tree.
6001 If ARG is negative, go up that many levels.
6002 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6003 indirect buffer previously made with this command, to avoid proliferation of
6004 indirect buffers. However, when you call the command with a `C-u' prefix, or
6005 when `org-indirect-buffer-display' is `new-frame', the last buffer
6006 is kept so that you can work with several indirect buffers at the same time.
6007 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6008 requests that a new frame be made for the new buffer, so that the dedicated
6009 frame is not changed."
6010 (interactive "P")
6011 (let ((cbuf (current-buffer))
6012 (cwin (selected-window))
6013 (pos (point))
6014 beg end level heading ibuf)
6015 (save-excursion
6016 (org-back-to-heading t)
6017 (when (numberp arg)
6018 (setq level (org-outline-level))
6019 (if (< arg 0) (setq arg (+ level arg)))
6020 (while (> (setq level (org-outline-level)) arg)
6021 (outline-up-heading 1 t)))
6022 (setq beg (point)
6023 heading (org-get-heading))
6024 (org-end-of-subtree t t) (setq end (point)))
6025 (if (and (buffer-live-p org-last-indirect-buffer)
6026 (not (eq org-indirect-buffer-display 'new-frame))
6027 (not arg))
6028 (kill-buffer org-last-indirect-buffer))
6029 (setq ibuf (org-get-indirect-buffer cbuf)
6030 org-last-indirect-buffer ibuf)
6031 (cond
6032 ((or (eq org-indirect-buffer-display 'new-frame)
6033 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6034 (select-frame (make-frame))
6035 (delete-other-windows)
6036 (switch-to-buffer ibuf)
6037 (org-set-frame-title heading))
6038 ((eq org-indirect-buffer-display 'dedicated-frame)
6039 (raise-frame
6040 (select-frame (or (and org-indirect-dedicated-frame
6041 (frame-live-p org-indirect-dedicated-frame)
6042 org-indirect-dedicated-frame)
6043 (setq org-indirect-dedicated-frame (make-frame)))))
6044 (delete-other-windows)
6045 (switch-to-buffer ibuf)
6046 (org-set-frame-title (concat "Indirect: " heading)))
6047 ((eq org-indirect-buffer-display 'current-window)
6048 (switch-to-buffer ibuf))
6049 ((eq org-indirect-buffer-display 'other-window)
6050 (pop-to-buffer ibuf))
6051 (t (error "Invalid value")))
6052 (if (featurep 'xemacs)
6053 (save-excursion (org-mode) (turn-on-font-lock)))
6054 (narrow-to-region beg end)
6055 (show-all)
6056 (goto-char pos)
6057 (and (window-live-p cwin) (select-window cwin))))
6059 (defun org-get-indirect-buffer (&optional buffer)
6060 (setq buffer (or buffer (current-buffer)))
6061 (let ((n 1) (base (buffer-name buffer)) bname)
6062 (while (buffer-live-p
6063 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6064 (setq n (1+ n)))
6065 (condition-case nil
6066 (make-indirect-buffer buffer bname 'clone)
6067 (error (make-indirect-buffer buffer bname)))))
6069 (defun org-set-frame-title (title)
6070 "Set the title of the current frame to the string TITLE."
6071 ;; FIXME: how to name a single frame in XEmacs???
6072 (unless (featurep 'xemacs)
6073 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6075 ;;;; Structure editing
6077 ;;; Inserting headlines
6079 (defun org-previous-line-empty-p ()
6080 (save-excursion
6081 (and (not (bobp))
6082 (or (beginning-of-line 0) t)
6083 (save-match-data
6084 (looking-at "[ \t]*$")))))
6086 (defun org-insert-heading (&optional force-heading)
6087 "Insert a new heading or item with same depth at point.
6088 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6089 If point is at the beginning of a headline, insert a sibling before the
6090 current headline. If point is not at the beginning, do not split the line,
6091 but create the new headline after the current line."
6092 (interactive "P")
6093 (if (or (= (buffer-size) 0)
6094 (and (not (save-excursion (and (ignore-errors (org-back-to-heading))
6095 (org-on-heading-p))))
6096 (not (org-in-item-p))))
6097 (insert "\n* ")
6098 (when (or force-heading (not (org-insert-item)))
6099 (let* ((empty-line-p nil)
6100 (head (save-excursion
6101 (condition-case nil
6102 (progn
6103 (org-back-to-heading)
6104 (setq empty-line-p (org-previous-line-empty-p))
6105 (match-string 0))
6106 (error "*"))))
6107 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6108 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6109 pos hide-previous previous-pos)
6110 (cond
6111 ((and (org-on-heading-p) (bolp)
6112 (or (bobp)
6113 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6114 ;; insert before the current line
6115 (open-line (if blank 2 1)))
6116 ((and (bolp)
6117 (not org-insert-heading-respect-content)
6118 (or (bobp)
6119 (save-excursion
6120 (backward-char 1) (not (org-invisible-p)))))
6121 ;; insert right here
6122 nil)
6124 ;; somewhere in the line
6125 (save-excursion
6126 (setq previous-pos (point-at-bol))
6127 (end-of-line)
6128 (setq hide-previous (org-invisible-p)))
6129 (and org-insert-heading-respect-content (org-show-subtree))
6130 (let ((split
6131 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6132 (save-excursion
6133 (let ((p (point)))
6134 (goto-char (point-at-bol))
6135 (and (looking-at org-complex-heading-regexp)
6136 (> p (match-beginning 4)))))))
6137 tags pos)
6138 (cond
6139 (org-insert-heading-respect-content
6140 (org-end-of-subtree nil t)
6141 (or (bolp) (newline))
6142 (or (org-previous-line-empty-p)
6143 (and blank (newline)))
6144 (open-line 1))
6145 ((org-on-heading-p)
6146 (when hide-previous
6147 (show-children)
6148 (org-show-entry))
6149 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6150 (setq tags (and (match-end 2) (match-string 2)))
6151 (and (match-end 1)
6152 (delete-region (match-beginning 1) (match-end 1)))
6153 (setq pos (point-at-bol))
6154 (or split (end-of-line 1))
6155 (delete-horizontal-space)
6156 (newline (if blank 2 1))
6157 (when tags
6158 (save-excursion
6159 (goto-char pos)
6160 (end-of-line 1)
6161 (insert " " tags)
6162 (org-set-tags nil 'align))))
6164 (or split (end-of-line 1))
6165 (newline (if blank 2 1)))))))
6166 (insert head) (just-one-space)
6167 (setq pos (point))
6168 (end-of-line 1)
6169 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6170 (when (and org-insert-heading-respect-content hide-previous)
6171 (save-excursion
6172 (goto-char previous-pos)
6173 (hide-subtree)))
6174 (run-hooks 'org-insert-heading-hook)))))
6176 (defun org-get-heading (&optional no-tags)
6177 "Return the heading of the current entry, without the stars."
6178 (save-excursion
6179 (org-back-to-heading t)
6180 (if (looking-at
6181 (if no-tags
6182 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6183 "\\*+[ \t]+\\([^\r\n]*\\)"))
6184 (match-string 1) "")))
6186 (defun org-heading-components ()
6187 "Return the components of the current heading.
6188 This is a list with the following elements:
6189 - the level as an integer
6190 - the reduced level, different if `org-odd-levels-only' is set.
6191 - the TODO keyword, or nil
6192 - the priority character, like ?A, or nil if no priority is given
6193 - the headline text itself, or the tags string if no headline text
6194 - the tags string, or nil."
6195 (save-excursion
6196 (org-back-to-heading t)
6197 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6198 (list (length (match-string 1))
6199 (org-reduced-level (length (match-string 1)))
6200 (org-match-string-no-properties 2)
6201 (and (match-end 3) (aref (match-string 3) 2))
6202 (org-match-string-no-properties 4)
6203 (org-match-string-no-properties 5)))))
6205 (defun org-get-entry ()
6206 "Get the entry text, after heading, entire subtree."
6207 (save-excursion
6208 (org-back-to-heading t)
6209 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6211 (defun org-insert-heading-after-current ()
6212 "Insert a new heading with same level as current, after current subtree."
6213 (interactive)
6214 (org-back-to-heading)
6215 (org-insert-heading)
6216 (org-move-subtree-down)
6217 (end-of-line 1))
6219 (defun org-insert-heading-respect-content ()
6220 (interactive)
6221 (let ((org-insert-heading-respect-content t))
6222 (org-insert-heading t)))
6224 (defun org-insert-todo-heading-respect-content (&optional force-state)
6225 (interactive "P")
6226 (let ((org-insert-heading-respect-content t))
6227 (org-insert-todo-heading force-state t)))
6229 (defun org-insert-todo-heading (arg &optional force-heading)
6230 "Insert a new heading with the same level and TODO state as current heading.
6231 If the heading has no TODO state, or if the state is DONE, use the first
6232 state (TODO by default). Also with prefix arg, force first state."
6233 (interactive "P")
6234 (when (or force-heading (not (org-insert-item 'checkbox)))
6235 (org-insert-heading force-heading)
6236 (save-excursion
6237 (org-back-to-heading)
6238 (outline-previous-heading)
6239 (looking-at org-todo-line-regexp))
6240 (let*
6241 ((new-mark-x
6242 (if (or arg
6243 (not (match-beginning 2))
6244 (member (match-string 2) org-done-keywords))
6245 (car org-todo-keywords-1)
6246 (match-string 2)))
6247 (new-mark
6249 (run-hook-with-args-until-success
6250 'org-todo-get-default-hook new-mark-x nil)
6251 new-mark-x)))
6252 (beginning-of-line 1)
6253 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6254 (if org-treat-insert-todo-heading-as-state-change
6255 (org-todo new-mark)
6256 (insert new-mark " "))))
6257 (when org-provide-todo-statistics
6258 (org-update-parent-todo-statistics))))
6260 (defun org-insert-subheading (arg)
6261 "Insert a new subheading and demote it.
6262 Works for outline headings and for plain lists alike."
6263 (interactive "P")
6264 (org-insert-heading arg)
6265 (cond
6266 ((org-on-heading-p) (org-do-demote))
6267 ((org-at-item-p) (org-indent-item 1))))
6269 (defun org-insert-todo-subheading (arg)
6270 "Insert a new subheading with TODO keyword or checkbox and demote it.
6271 Works for outline headings and for plain lists alike."
6272 (interactive "P")
6273 (org-insert-todo-heading arg)
6274 (cond
6275 ((org-on-heading-p) (org-do-demote))
6276 ((org-at-item-p) (org-indent-item 1))))
6278 ;;; Promotion and Demotion
6280 (defvar org-after-demote-entry-hook nil
6281 "Hook run after an entry has been demoted.
6282 The cursor will be at the beginning of the entry.
6283 When a subtree is being demoted, the hook will be called for each node.")
6285 (defvar org-after-promote-entry-hook nil
6286 "Hook run after an entry has been promoted.
6287 The cursor will be at the beginning of the entry.
6288 When a subtree is being promoted, the hook will be called for each node.")
6290 (defun org-promote-subtree ()
6291 "Promote the entire subtree.
6292 See also `org-promote'."
6293 (interactive)
6294 (save-excursion
6295 (org-map-tree 'org-promote))
6296 (org-fix-position-after-promote))
6298 (defun org-demote-subtree ()
6299 "Demote the entire subtree. See `org-demote'.
6300 See also `org-promote'."
6301 (interactive)
6302 (save-excursion
6303 (org-map-tree 'org-demote))
6304 (org-fix-position-after-promote))
6307 (defun org-do-promote ()
6308 "Promote the current heading higher up the tree.
6309 If the region is active in `transient-mark-mode', promote all headings
6310 in the region."
6311 (interactive)
6312 (save-excursion
6313 (if (org-region-active-p)
6314 (org-map-region 'org-promote (region-beginning) (region-end))
6315 (org-promote)))
6316 (org-fix-position-after-promote))
6318 (defun org-do-demote ()
6319 "Demote the current heading lower down the tree.
6320 If the region is active in `transient-mark-mode', demote all headings
6321 in the region."
6322 (interactive)
6323 (save-excursion
6324 (if (org-region-active-p)
6325 (org-map-region 'org-demote (region-beginning) (region-end))
6326 (org-demote)))
6327 (org-fix-position-after-promote))
6329 (defun org-fix-position-after-promote ()
6330 "Make sure that after pro/demotion cursor position is right."
6331 (let ((pos (point)))
6332 (when (save-excursion
6333 (beginning-of-line 1)
6334 (looking-at org-todo-line-regexp)
6335 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6336 (cond ((eobp) (insert " "))
6337 ((eolp) (insert " "))
6338 ((equal (char-after) ?\ ) (forward-char 1))))))
6340 (defun org-current-level ()
6341 "Return the level of the current entry, or nil if before the first headline.
6342 The level is the number of stars at the beginning of the headline."
6343 (save-excursion
6344 (condition-case nil
6345 (progn
6346 (org-back-to-heading t)
6347 (funcall outline-level))
6348 (error nil))))
6350 (defun org-reduced-level (l)
6351 "Compute the effective level of a heading.
6352 This takes into account the setting of `org-odd-levels-only'."
6353 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6355 (defun org-get-valid-level (level &optional change)
6356 "Rectify a level change under the influence of `org-odd-levels-only'
6357 LEVEL is a current level, CHANGE is by how much the level should be
6358 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6359 even level numbers will become the next higher odd number."
6360 (if org-odd-levels-only
6361 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6362 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6363 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6364 (max 1 (+ level (or change 0)))))
6366 (if (boundp 'define-obsolete-function-alias)
6367 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6368 (define-obsolete-function-alias 'org-get-legal-level
6369 'org-get-valid-level)
6370 (define-obsolete-function-alias 'org-get-legal-level
6371 'org-get-valid-level "23.1")))
6373 (defun org-promote ()
6374 "Promote the current heading higher up the tree.
6375 If the region is active in `transient-mark-mode', promote all headings
6376 in the region."
6377 (org-back-to-heading t)
6378 (let* ((level (save-match-data (funcall outline-level)))
6379 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6380 (diff (abs (- level (length up-head) -1))))
6381 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6382 (replace-match up-head nil t)
6383 ;; Fixup tag positioning
6384 (and org-auto-align-tags (org-set-tags nil t))
6385 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6386 (run-hooks 'org-after-promote-entry-hook)))
6388 (defun org-demote ()
6389 "Demote the current heading lower down the tree.
6390 If the region is active in `transient-mark-mode', demote all headings
6391 in the region."
6392 (org-back-to-heading t)
6393 (let* ((level (save-match-data (funcall outline-level)))
6394 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6395 (diff (abs (- level (length down-head) -1))))
6396 (replace-match down-head nil t)
6397 ;; Fixup tag positioning
6398 (and org-auto-align-tags (org-set-tags nil t))
6399 (if org-adapt-indentation (org-fixup-indentation diff))
6400 (run-hooks 'org-after-demote-entry-hook)))
6402 (defvar org-tab-ind-state nil)
6404 (defun org-cycle-level ()
6405 (let ((org-adapt-indentation nil))
6406 (when (and (looking-at "[ \t]*$")
6407 (org-looking-back
6408 (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))
6409 (setq this-command 'org-cycle-level)
6410 (if (eq last-command 'org-cycle-level)
6411 (condition-case nil
6412 (progn (org-do-promote)
6413 (if (equal org-tab-ind-state (org-current-level))
6414 (org-do-promote)))
6415 (error
6416 (progn
6417 (save-excursion
6418 (beginning-of-line 1)
6419 (and (looking-at "\\*+")
6420 (replace-match
6421 (make-string org-tab-ind-state ?*))))
6422 (setq this-command 'org-cycle))))
6423 (setq org-tab-ind-state (- (match-end 1) (match-beginning 1)))
6424 (org-do-demote))
6425 t)))
6427 (defun org-map-tree (fun)
6428 "Call FUN for every heading underneath the current one."
6429 (org-back-to-heading)
6430 (let ((level (funcall outline-level)))
6431 (save-excursion
6432 (funcall fun)
6433 (while (and (progn
6434 (outline-next-heading)
6435 (> (funcall outline-level) level))
6436 (not (eobp)))
6437 (funcall fun)))))
6439 (defun org-map-region (fun beg end)
6440 "Call FUN for every heading between BEG and END."
6441 (let ((org-ignore-region t))
6442 (save-excursion
6443 (setq end (copy-marker end))
6444 (goto-char beg)
6445 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6446 (< (point) end))
6447 (funcall fun))
6448 (while (and (progn
6449 (outline-next-heading)
6450 (< (point) end))
6451 (not (eobp)))
6452 (funcall fun)))))
6454 (defun org-fixup-indentation (diff)
6455 "Change the indentation in the current entry by DIFF
6456 However, if any line in the current entry has no indentation, or if it
6457 would end up with no indentation after the change, nothing at all is done."
6458 (save-excursion
6459 (let ((end (save-excursion (outline-next-heading)
6460 (point-marker)))
6461 (prohibit (if (> diff 0)
6462 "^\\S-"
6463 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6464 col)
6465 (unless (save-excursion (end-of-line 1)
6466 (re-search-forward prohibit end t))
6467 (while (and (< (point) end)
6468 (re-search-forward "^[ \t]+" end t))
6469 (goto-char (match-end 0))
6470 (setq col (current-column))
6471 (if (< diff 0) (replace-match ""))
6472 (org-indent-to-column (+ diff col))))
6473 (move-marker end nil))))
6475 (defun org-convert-to-odd-levels ()
6476 "Convert an org-mode file with all levels allowed to one with odd levels.
6477 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6478 level 5 etc."
6479 (interactive)
6480 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6481 (let ((outline-regexp org-outline-regexp)
6482 (outline-level 'org-outline-level)
6483 (org-odd-levels-only nil) n)
6484 (save-excursion
6485 (goto-char (point-min))
6486 (while (re-search-forward "^\\*\\*+ " nil t)
6487 (setq n (- (length (match-string 0)) 2))
6488 (while (>= (setq n (1- n)) 0)
6489 (org-demote))
6490 (end-of-line 1))))))
6492 (defun org-convert-to-oddeven-levels ()
6493 "Convert an org-mode file with only odd levels to one with odd and even levels.
6494 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6495 section with an even level, conversion would destroy the structure of the file. An error
6496 is signaled in this case."
6497 (interactive)
6498 (goto-char (point-min))
6499 ;; First check if there are no even levels
6500 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6501 (org-show-context t)
6502 (error "Not all levels are odd in this file. Conversion not possible"))
6503 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6504 (let ((outline-regexp org-outline-regexp)
6505 (outline-level 'org-outline-level)
6506 (org-odd-levels-only nil) n)
6507 (save-excursion
6508 (goto-char (point-min))
6509 (while (re-search-forward "^\\*\\*+ " nil t)
6510 (setq n (/ (1- (length (match-string 0))) 2))
6511 (while (>= (setq n (1- n)) 0)
6512 (org-promote))
6513 (end-of-line 1))))))
6515 (defun org-tr-level (n)
6516 "Make N odd if required."
6517 (if org-odd-levels-only (1+ (/ n 2)) n))
6519 ;;; Vertical tree motion, cutting and pasting of subtrees
6521 (defun org-move-subtree-up (&optional arg)
6522 "Move the current subtree up past ARG headlines of the same level."
6523 (interactive "p")
6524 (org-move-subtree-down (- (prefix-numeric-value arg))))
6526 (defun org-move-subtree-down (&optional arg)
6527 "Move the current subtree down past ARG headlines of the same level."
6528 (interactive "p")
6529 (setq arg (prefix-numeric-value arg))
6530 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6531 'org-get-last-sibling))
6532 (ins-point (make-marker))
6533 (cnt (abs arg))
6534 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6535 ;; Select the tree
6536 (org-back-to-heading)
6537 (setq beg0 (point))
6538 (save-excursion
6539 (setq ne-beg (org-back-over-empty-lines))
6540 (setq beg (point)))
6541 (save-match-data
6542 (save-excursion (outline-end-of-heading)
6543 (setq folded (org-invisible-p)))
6544 (outline-end-of-subtree))
6545 (outline-next-heading)
6546 (setq ne-end (org-back-over-empty-lines))
6547 (setq end (point))
6548 (goto-char beg0)
6549 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6550 ;; include less whitespace
6551 (save-excursion
6552 (goto-char beg)
6553 (forward-line (- ne-beg ne-end))
6554 (setq beg (point))))
6555 ;; Find insertion point, with error handling
6556 (while (> cnt 0)
6557 (or (and (funcall movfunc) (looking-at outline-regexp))
6558 (progn (goto-char beg0)
6559 (error "Cannot move past superior level or buffer limit")))
6560 (setq cnt (1- cnt)))
6561 (if (> arg 0)
6562 ;; Moving forward - still need to move over subtree
6563 (progn (org-end-of-subtree t t)
6564 (save-excursion
6565 (org-back-over-empty-lines)
6566 (or (bolp) (newline)))))
6567 (setq ne-ins (org-back-over-empty-lines))
6568 (move-marker ins-point (point))
6569 (setq txt (buffer-substring beg end))
6570 (org-save-markers-in-region beg end)
6571 (delete-region beg end)
6572 (org-remove-empty-overlays-at beg)
6573 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6574 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6575 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6576 (let ((bbb (point)))
6577 (insert-before-markers txt)
6578 (org-reinstall-markers-in-region bbb)
6579 (move-marker ins-point bbb))
6580 (or (bolp) (insert "\n"))
6581 (setq ins-end (point))
6582 (goto-char ins-point)
6583 (org-skip-whitespace)
6584 (when (and (< arg 0)
6585 (org-first-sibling-p)
6586 (> ne-ins ne-beg))
6587 ;; Move whitespace back to beginning
6588 (save-excursion
6589 (goto-char ins-end)
6590 (let ((kill-whole-line t))
6591 (kill-line (- ne-ins ne-beg)) (point)))
6592 (insert (make-string (- ne-ins ne-beg) ?\n)))
6593 (move-marker ins-point nil)
6594 (if folded
6595 (hide-subtree)
6596 (org-show-entry)
6597 (show-children)
6598 (org-cycle-hide-drawers 'children))
6599 (org-clean-visibility-after-subtree-move)))
6601 (defvar org-subtree-clip ""
6602 "Clipboard for cut and paste of subtrees.
6603 This is actually only a copy of the kill, because we use the normal kill
6604 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6606 (defvar org-subtree-clip-folded nil
6607 "Was the last copied subtree folded?
6608 This is used to fold the tree back after pasting.")
6610 (defun org-cut-subtree (&optional n)
6611 "Cut the current subtree into the clipboard.
6612 With prefix arg N, cut this many sequential subtrees.
6613 This is a short-hand for marking the subtree and then cutting it."
6614 (interactive "p")
6615 (org-copy-subtree n 'cut))
6617 (defun org-copy-subtree (&optional n cut force-store-markers)
6618 "Cut the current subtree into the clipboard.
6619 With prefix arg N, cut this many sequential subtrees.
6620 This is a short-hand for marking the subtree and then copying it.
6621 If CUT is non-nil, actually cut the subtree.
6622 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6623 of some markers in the region, even if CUT is non-nil. This is
6624 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6625 (interactive "p")
6626 (let (beg end folded (beg0 (point)))
6627 (if (interactive-p)
6628 (org-back-to-heading nil) ; take what looks like a subtree
6629 (org-back-to-heading t)) ; take what is really there
6630 (org-back-over-empty-lines)
6631 (setq beg (point))
6632 (skip-chars-forward " \t\r\n")
6633 (save-match-data
6634 (save-excursion (outline-end-of-heading)
6635 (setq folded (org-invisible-p)))
6636 (condition-case nil
6637 (org-forward-same-level (1- n) t)
6638 (error nil))
6639 (org-end-of-subtree t t))
6640 (org-back-over-empty-lines)
6641 (setq end (point))
6642 (goto-char beg0)
6643 (when (> end beg)
6644 (setq org-subtree-clip-folded folded)
6645 (when (or cut force-store-markers)
6646 (org-save-markers-in-region beg end))
6647 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6648 (setq org-subtree-clip (current-kill 0))
6649 (message "%s: Subtree(s) with %d characters"
6650 (if cut "Cut" "Copied")
6651 (length org-subtree-clip)))))
6653 (defun org-paste-subtree (&optional level tree for-yank)
6654 "Paste the clipboard as a subtree, with modification of headline level.
6655 The entire subtree is promoted or demoted in order to match a new headline
6656 level.
6658 If the cursor is at the beginning of a headline, the same level as
6659 that headline is used to paste the tree
6661 If not, the new level is derived from the *visible* headings
6662 before and after the insertion point, and taken to be the inferior headline
6663 level of the two. So if the previous visible heading is level 3 and the
6664 next is level 4 (or vice versa), level 4 will be used for insertion.
6665 This makes sure that the subtree remains an independent subtree and does
6666 not swallow low level entries.
6668 You can also force a different level, either by using a numeric prefix
6669 argument, or by inserting the heading marker by hand. For example, if the
6670 cursor is after \"*****\", then the tree will be shifted to level 5.
6672 If optional TREE is given, use this text instead of the kill ring.
6674 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6675 move back over whitespace before inserting, and move point to the end of
6676 the inserted text when done."
6677 (interactive "P")
6678 (setq tree (or tree (and kill-ring (current-kill 0))))
6679 (unless (org-kill-is-subtree-p tree)
6680 (error "%s"
6681 (substitute-command-keys
6682 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6683 (let* ((visp (not (org-invisible-p)))
6684 (txt tree)
6685 (^re (concat "^\\(" outline-regexp "\\)"))
6686 (re (concat "\\(" outline-regexp "\\)"))
6687 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6689 (old-level (if (string-match ^re txt)
6690 (- (match-end 0) (match-beginning 0) 1)
6691 -1))
6692 (force-level (cond (level (prefix-numeric-value level))
6693 ((and (looking-at "[ \t]*$")
6694 (string-match
6695 ^re_ (buffer-substring
6696 (point-at-bol) (point))))
6697 (- (match-end 1) (match-beginning 1)))
6698 ((and (bolp)
6699 (looking-at org-outline-regexp))
6700 (- (match-end 0) (point) 1))
6701 (t nil)))
6702 (previous-level (save-excursion
6703 (condition-case nil
6704 (progn
6705 (outline-previous-visible-heading 1)
6706 (if (looking-at re)
6707 (- (match-end 0) (match-beginning 0) 1)
6709 (error 1))))
6710 (next-level (save-excursion
6711 (condition-case nil
6712 (progn
6713 (or (looking-at outline-regexp)
6714 (outline-next-visible-heading 1))
6715 (if (looking-at re)
6716 (- (match-end 0) (match-beginning 0) 1)
6718 (error 1))))
6719 (new-level (or force-level (max previous-level next-level)))
6720 (shift (if (or (= old-level -1)
6721 (= new-level -1)
6722 (= old-level new-level))
6724 (- new-level old-level)))
6725 (delta (if (> shift 0) -1 1))
6726 (func (if (> shift 0) 'org-demote 'org-promote))
6727 (org-odd-levels-only nil)
6728 beg end newend)
6729 ;; Remove the forced level indicator
6730 (if force-level
6731 (delete-region (point-at-bol) (point)))
6732 ;; Paste
6733 (beginning-of-line 1)
6734 (unless for-yank (org-back-over-empty-lines))
6735 (setq beg (point))
6736 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6737 (insert-before-markers txt)
6738 (unless (string-match "\n\\'" txt) (insert "\n"))
6739 (setq newend (point))
6740 (org-reinstall-markers-in-region beg)
6741 (setq end (point))
6742 (goto-char beg)
6743 (skip-chars-forward " \t\n\r")
6744 (setq beg (point))
6745 (if (and (org-invisible-p) visp)
6746 (save-excursion (outline-show-heading)))
6747 ;; Shift if necessary
6748 (unless (= shift 0)
6749 (save-restriction
6750 (narrow-to-region beg end)
6751 (while (not (= shift 0))
6752 (org-map-region func (point-min) (point-max))
6753 (setq shift (+ delta shift)))
6754 (goto-char (point-min))
6755 (setq newend (point-max))))
6756 (when (or (interactive-p) for-yank)
6757 (message "Clipboard pasted as level %d subtree" new-level))
6758 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6759 kill-ring
6760 (eq org-subtree-clip (current-kill 0))
6761 org-subtree-clip-folded)
6762 ;; The tree was folded before it was killed/copied
6763 (hide-subtree))
6764 (and for-yank (goto-char newend))))
6766 (defun org-kill-is-subtree-p (&optional txt)
6767 "Check if the current kill is an outline subtree, or a set of trees.
6768 Returns nil if kill does not start with a headline, or if the first
6769 headline level is not the largest headline level in the tree.
6770 So this will actually accept several entries of equal levels as well,
6771 which is OK for `org-paste-subtree'.
6772 If optional TXT is given, check this string instead of the current kill."
6773 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6774 (start-level (and kill
6775 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6776 org-outline-regexp "\\)")
6777 kill)
6778 (- (match-end 2) (match-beginning 2) 1)))
6779 (re (concat "^" org-outline-regexp))
6780 (start (1+ (or (match-beginning 2) -1))))
6781 (if (not start-level)
6782 (progn
6783 nil) ;; does not even start with a heading
6784 (catch 'exit
6785 (while (setq start (string-match re kill (1+ start)))
6786 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6787 (throw 'exit nil)))
6788 t))))
6790 (defvar org-markers-to-move nil
6791 "Markers that should be moved with a cut-and-paste operation.
6792 Those markers are stored together with their positions relative to
6793 the start of the region.")
6795 (defun org-save-markers-in-region (beg end)
6796 "Check markers in region.
6797 If these markers are between BEG and END, record their position relative
6798 to BEG, so that after moving the block of text, we can put the markers back
6799 into place.
6800 This function gets called just before an entry or tree gets cut from the
6801 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6802 called immediately, to move the markers with the entries."
6803 (setq org-markers-to-move nil)
6804 (when (featurep 'org-clock)
6805 (org-clock-save-markers-for-cut-and-paste beg end))
6806 (when (featurep 'org-agenda)
6807 (org-agenda-save-markers-for-cut-and-paste beg end)))
6809 (defun org-check-and-save-marker (marker beg end)
6810 "Check if MARKER is between BEG and END.
6811 If yes, remember the marker and the distance to BEG."
6812 (when (and (marker-buffer marker)
6813 (equal (marker-buffer marker) (current-buffer)))
6814 (if (and (>= marker beg) (< marker end))
6815 (push (cons marker (- marker beg)) org-markers-to-move))))
6817 (defun org-reinstall-markers-in-region (beg)
6818 "Move all remembered markers to their position relative to BEG."
6819 (mapc (lambda (x)
6820 (move-marker (car x) (+ beg (cdr x))))
6821 org-markers-to-move)
6822 (setq org-markers-to-move nil))
6824 (defun org-narrow-to-subtree ()
6825 "Narrow buffer to the current subtree."
6826 (interactive)
6827 (save-excursion
6828 (save-match-data
6829 (narrow-to-region
6830 (progn (org-back-to-heading t) (point))
6831 (progn (org-end-of-subtree t t) (point))))))
6833 (defun org-clone-subtree-with-time-shift (n &optional shift)
6834 "Clone the task (subtree) at point N times.
6835 The clones will be inserted as siblings.
6837 In interactive use, the user will be prompted for the number of clones
6838 to be produced, and for a time SHIFT, which may be a repeater as used
6839 in time stamps, for example `+3d'.
6841 When a valid repeater is given and the entry contains any time stamps,
6842 the clones will become a sequence in time, with time stamps in the
6843 subtree shifted for each clone produced. If SHIFT is nil or the
6844 empty string, time stamps will be left alone.
6846 If the original subtree did contain time stamps with a repeater,
6847 the following will happen:
6848 - the repeater will be removed in each clone
6849 - an additional clone will be produced, with the current, unshifted
6850 date(s) in the entry.
6851 - the original entry will be placed *after* all the clones, with
6852 repeater intact.
6853 - the start days in the repeater in the original entry will be shifted
6854 to past the last clone.
6855 I this way you can spell out a number of instances of a repeating task,
6856 and still retain the repeater to cover future instances of the task."
6857 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6858 (let (beg end template task
6859 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6860 (if (not (and (integerp n) (> n 0)))
6861 (error "Invalid number of replications %s" n))
6862 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6863 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6864 shift)))
6865 (error "Invalid shift specification %s" shift))
6866 (when doshift
6867 (setq shift-n (string-to-number (match-string 1 shift))
6868 shift-what (cdr (assoc (match-string 2 shift)
6869 '(("d" . day) ("w" . week)
6870 ("m" . month) ("y" . year))))))
6871 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6872 (setq nmin 1 nmax n)
6873 (org-back-to-heading t)
6874 (setq beg (point))
6875 (org-end-of-subtree t t)
6876 (or (bolp) (insert "\n"))
6877 (setq end (point))
6878 (setq template (buffer-substring beg end))
6879 (when (and doshift
6880 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6881 (delete-region beg end)
6882 (setq end beg)
6883 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6884 (goto-char end)
6885 (loop for n from nmin to nmax do
6886 (if (not doshift)
6887 (setq task template)
6888 (with-temp-buffer
6889 (insert template)
6890 (org-mode)
6891 (goto-char (point-min))
6892 (while (re-search-forward org-ts-regexp-both nil t)
6893 (org-timestamp-change (* n shift-n) shift-what))
6894 (unless (= n n-no-remove)
6895 (goto-char (point-min))
6896 (while (re-search-forward org-ts-regexp nil t)
6897 (save-excursion
6898 (goto-char (match-beginning 0))
6899 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6900 (delete-region (match-beginning 1) (match-end 1))))))
6901 (setq task (buffer-string))))
6902 (insert task))
6903 (goto-char beg)))
6905 ;;; Outline Sorting
6907 (defun org-sort (with-case)
6908 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6909 Optional argument WITH-CASE means sort case-sensitively.
6910 With a double prefix argument, also remove duplicate entries."
6911 (interactive "P")
6912 (if (org-at-table-p)
6913 (org-call-with-arg 'org-table-sort-lines with-case)
6914 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6916 (defun org-sort-remove-invisible (s)
6917 (remove-text-properties 0 (length s) org-rm-props s)
6918 (while (string-match org-bracket-link-regexp s)
6919 (setq s (replace-match (if (match-end 2)
6920 (match-string 3 s)
6921 (match-string 1 s)) t t s)))
6924 (defvar org-priority-regexp) ; defined later in the file
6926 (defvar org-after-sorting-entries-or-items-hook nil
6927 "Hook that is run after a bunch of entries or items have been sorted.
6928 When children are sorted, the cursor is in the parent line when this
6929 hook gets called. When a region or a plain list is sorted, the cursor
6930 will be in the first entry of the sorted region/list.")
6932 (defun org-sort-entries-or-items
6933 (&optional with-case sorting-type getkey-func compare-func property)
6934 "Sort entries on a certain level of an outline tree, or plain list items.
6935 If there is an active region, the entries in the region are sorted.
6936 Else, if the cursor is before the first entry, sort the top-level items.
6937 Else, the children of the entry at point are sorted.
6938 If the cursor is at the first item in a plain list, the list items will be
6939 sorted.
6941 Sorting can be alphabetically, numerically, by date/time as given by
6942 a time stamp, by a property or by priority.
6944 The command prompts for the sorting type unless it has been given to the
6945 function through the SORTING-TYPE argument, which needs to a character,
6946 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6947 precise meaning of each character:
6949 n Numerically, by converting the beginning of the entry/item to a number.
6950 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6951 t By date/time, either the first active time stamp in the entry, or, if
6952 none exist, by the first inactive one.
6953 In items, only the first line will be checked.
6954 s By the scheduled date/time.
6955 d By deadline date/time.
6956 c By creation time, which is assumed to be the first inactive time stamp
6957 at the beginning of a line.
6958 p By priority according to the cookie.
6959 r By the value of a property.
6961 Capital letters will reverse the sort order.
6963 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6964 called with point at the beginning of the record. It must return either
6965 a string or a number that should serve as the sorting key for that record.
6967 Comparing entries ignores case by default. However, with an optional argument
6968 WITH-CASE, the sorting considers case as well."
6969 (interactive "P")
6970 (let ((case-func (if with-case 'identity 'downcase))
6971 start beg end stars re re2
6972 txt what tmp plain-list-p)
6973 ;; Find beginning and end of region to sort
6974 (cond
6975 ((org-region-active-p)
6976 ;; we will sort the region
6977 (setq end (region-end)
6978 what "region")
6979 (goto-char (region-beginning))
6980 (if (not (org-on-heading-p)) (outline-next-heading))
6981 (setq start (point)))
6982 ((org-at-item-p)
6983 ;; we will sort this plain list
6984 (org-beginning-of-item-list) (setq start (point))
6985 (org-end-of-item-list)
6986 (or (bolp) (insert "\n"))
6987 (setq end (point))
6988 (goto-char start)
6989 (setq plain-list-p t
6990 what "plain list"))
6991 ((or (org-on-heading-p)
6992 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6993 ;; we will sort the children of the current headline
6994 (org-back-to-heading)
6995 (setq start (point)
6996 end (progn (org-end-of-subtree t t)
6997 (or (bolp) (insert "\n"))
6998 (org-back-over-empty-lines)
6999 (point))
7000 what "children")
7001 (goto-char start)
7002 (show-subtree)
7003 (outline-next-heading))
7005 ;; we will sort the top-level entries in this file
7006 (goto-char (point-min))
7007 (or (org-on-heading-p) (outline-next-heading))
7008 (setq start (point))
7009 (goto-char (point-max))
7010 (beginning-of-line 1)
7011 (when (looking-at ".*?\\S-")
7012 ;; File ends in a non-white line
7013 (end-of-line 1)
7014 (insert "\n"))
7015 (setq end (point-max))
7016 (setq what "top-level")
7017 (goto-char start)
7018 (show-all)))
7020 (setq beg (point))
7021 (if (>= beg end) (error "Nothing to sort"))
7023 (unless plain-list-p
7024 (looking-at "\\(\\*+\\)")
7025 (setq stars (match-string 1)
7026 re (concat "^" (regexp-quote stars) " +")
7027 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7028 txt (buffer-substring beg end))
7029 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7030 (if (and (not (equal stars "*")) (string-match re2 txt))
7031 (error "Region to sort contains a level above the first entry")))
7033 (unless sorting-type
7034 (message
7035 (if plain-list-p
7036 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7037 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7038 [t]ime [s]cheduled [d]eadline [c]reated
7039 A/N/T/S/D/C/P/O/F means reversed:")
7040 what)
7041 (setq sorting-type (read-char-exclusive))
7043 (and (= (downcase sorting-type) ?f)
7044 (setq getkey-func
7045 (org-icompleting-read "Sort using function: "
7046 obarray 'fboundp t nil nil))
7047 (setq getkey-func (intern getkey-func)))
7049 (and (= (downcase sorting-type) ?r)
7050 (setq property
7051 (org-icompleting-read "Property: "
7052 (mapcar 'list (org-buffer-property-keys t))
7053 nil t))))
7055 (message "Sorting entries...")
7057 (save-restriction
7058 (narrow-to-region start end)
7060 (let ((dcst (downcase sorting-type))
7061 (case-fold-search nil)
7062 (now (current-time)))
7063 (sort-subr
7064 (/= dcst sorting-type)
7065 ;; This function moves to the beginning character of the "record" to
7066 ;; be sorted.
7067 (if plain-list-p
7068 (lambda nil
7069 (if (org-at-item-p) t (goto-char (point-max))))
7070 (lambda nil
7071 (if (re-search-forward re nil t)
7072 (goto-char (match-beginning 0))
7073 (goto-char (point-max)))))
7074 ;; This function moves to the last character of the "record" being
7075 ;; sorted.
7076 (if plain-list-p
7077 'org-end-of-item
7078 (lambda nil
7079 (save-match-data
7080 (condition-case nil
7081 (outline-forward-same-level 1)
7082 (error
7083 (goto-char (point-max)))))))
7085 ;; This function returns the value that gets sorted against.
7086 (if plain-list-p
7087 (lambda nil
7088 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7089 (cond
7090 ((= dcst ?n)
7091 (string-to-number (buffer-substring (match-end 0)
7092 (point-at-eol))))
7093 ((= dcst ?a)
7094 (buffer-substring (match-end 0) (point-at-eol)))
7095 ((= dcst ?t)
7096 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7097 (re-search-forward org-ts-regexp-both
7098 (point-at-eol) t))
7099 (org-time-string-to-seconds (match-string 0))
7100 (org-float-time now)))
7101 ((= dcst ?f)
7102 (if getkey-func
7103 (progn
7104 (setq tmp (funcall getkey-func))
7105 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7106 tmp)
7107 (error "Invalid key function `%s'" getkey-func)))
7108 (t (error "Invalid sorting type `%c'" sorting-type)))))
7109 (lambda nil
7110 (cond
7111 ((= dcst ?n)
7112 (if (looking-at org-complex-heading-regexp)
7113 (string-to-number (match-string 4))
7114 nil))
7115 ((= dcst ?a)
7116 (if (looking-at org-complex-heading-regexp)
7117 (funcall case-func (match-string 4))
7118 nil))
7119 ((= dcst ?t)
7120 (let ((end (save-excursion (outline-next-heading) (point))))
7121 (if (or (re-search-forward org-ts-regexp end t)
7122 (re-search-forward org-ts-regexp-both end t))
7123 (org-time-string-to-seconds (match-string 0))
7124 (org-float-time now))))
7125 ((= dcst ?c)
7126 (let ((end (save-excursion (outline-next-heading) (point))))
7127 (if (re-search-forward
7128 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7129 end t)
7130 (org-time-string-to-seconds (match-string 0))
7131 (org-float-time now))))
7132 ((= dcst ?s)
7133 (let ((end (save-excursion (outline-next-heading) (point))))
7134 (if (re-search-forward org-scheduled-time-regexp end t)
7135 (org-time-string-to-seconds (match-string 1))
7136 (org-float-time now))))
7137 ((= dcst ?d)
7138 (let ((end (save-excursion (outline-next-heading) (point))))
7139 (if (re-search-forward org-deadline-time-regexp end t)
7140 (org-time-string-to-seconds (match-string 1))
7141 (org-float-time now))))
7142 ((= dcst ?p)
7143 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7144 (string-to-char (match-string 2))
7145 org-default-priority))
7146 ((= dcst ?r)
7147 (or (org-entry-get nil property) ""))
7148 ((= dcst ?o)
7149 (if (looking-at org-complex-heading-regexp)
7150 (- 9999 (length (member (match-string 2)
7151 org-todo-keywords-1)))))
7152 ((= dcst ?f)
7153 (if getkey-func
7154 (progn
7155 (setq tmp (funcall getkey-func))
7156 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7157 tmp)
7158 (error "Invalid key function `%s'" getkey-func)))
7159 (t (error "Invalid sorting type `%c'" sorting-type)))))
7161 (cond
7162 ((= dcst ?a) 'string<)
7163 ((= dcst ?f) compare-func)
7164 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7165 (t nil)))))
7166 (run-hooks 'org-after-sorting-entries-or-items-hook)
7167 (message "Sorting entries...done")))
7169 (defun org-do-sort (table what &optional with-case sorting-type)
7170 "Sort TABLE of WHAT according to SORTING-TYPE.
7171 The user will be prompted for the SORTING-TYPE if the call to this
7172 function does not specify it. WHAT is only for the prompt, to indicate
7173 what is being sorted. The sorting key will be extracted from
7174 the car of the elements of the table.
7175 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7176 (unless sorting-type
7177 (message
7178 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7179 what)
7180 (setq sorting-type (read-char-exclusive)))
7181 (let ((dcst (downcase sorting-type))
7182 extractfun comparefun)
7183 ;; Define the appropriate functions
7184 (cond
7185 ((= dcst ?n)
7186 (setq extractfun 'string-to-number
7187 comparefun (if (= dcst sorting-type) '< '>)))
7188 ((= dcst ?a)
7189 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7190 (lambda(x) (downcase (org-sort-remove-invisible x))))
7191 comparefun (if (= dcst sorting-type)
7192 'string<
7193 (lambda (a b) (and (not (string< a b))
7194 (not (string= a b)))))))
7195 ((= dcst ?t)
7196 (setq extractfun
7197 (lambda (x)
7198 (if (or (string-match org-ts-regexp x)
7199 (string-match org-ts-regexp-both x))
7200 (org-float-time
7201 (org-time-string-to-time (match-string 0 x)))
7203 comparefun (if (= dcst sorting-type) '< '>)))
7204 (t (error "Invalid sorting type `%c'" sorting-type)))
7206 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7207 table)
7208 (lambda (a b) (funcall comparefun (car a) (car b))))))
7211 ;;; The orgstruct minor mode
7213 ;; Define a minor mode which can be used in other modes in order to
7214 ;; integrate the org-mode structure editing commands.
7216 ;; This is really a hack, because the org-mode structure commands use
7217 ;; keys which normally belong to the major mode. Here is how it
7218 ;; works: The minor mode defines all the keys necessary to operate the
7219 ;; structure commands, but wraps the commands into a function which
7220 ;; tests if the cursor is currently at a headline or a plain list
7221 ;; item. If that is the case, the structure command is used,
7222 ;; temporarily setting many Org-mode variables like regular
7223 ;; expressions for filling etc. However, when any of those keys is
7224 ;; used at a different location, function uses `key-binding' to look
7225 ;; up if the key has an associated command in another currently active
7226 ;; keymap (minor modes, major mode, global), and executes that
7227 ;; command. There might be problems if any of the keys is otherwise
7228 ;; used as a prefix key.
7230 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7231 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7232 ;; addresses this by checking explicitly for both bindings.
7234 (defvar orgstruct-mode-map (make-sparse-keymap)
7235 "Keymap for the minor `orgstruct-mode'.")
7237 (defvar org-local-vars nil
7238 "List of local variables, for use by `orgstruct-mode'")
7240 ;;;###autoload
7241 (define-minor-mode orgstruct-mode
7242 "Toggle the minor more `orgstruct-mode'.
7243 This mode is for using Org-mode structure commands in other modes.
7244 The following key behave as if Org-mode was active, if the cursor
7245 is on a headline, or on a plain list item (both in the definition
7246 of Org-mode).
7248 M-up Move entry/item up
7249 M-down Move entry/item down
7250 M-left Promote
7251 M-right Demote
7252 M-S-up Move entry/item up
7253 M-S-down Move entry/item down
7254 M-S-left Promote subtree
7255 M-S-right Demote subtree
7256 M-q Fill paragraph and items like in Org-mode
7257 C-c ^ Sort entries
7258 C-c - Cycle list bullet
7259 TAB Cycle item visibility
7260 M-RET Insert new heading/item
7261 S-M-RET Insert new TODO heading / Checkbox item
7262 C-c C-c Set tags / toggle checkbox"
7263 nil " OrgStruct" nil
7264 (org-load-modules-maybe)
7265 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7267 ;;;###autoload
7268 (defun turn-on-orgstruct ()
7269 "Unconditionally turn on `orgstruct-mode'."
7270 (orgstruct-mode 1))
7272 (defun orgstruct++-mode (&optional arg)
7273 "Toggle `orgstruct-mode', the enhanced version of it.
7274 In addition to setting orgstruct-mode, this also exports all indentation
7275 and autofilling variables from org-mode into the buffer. It will also
7276 recognize item context in multiline items.
7277 Note that turning off orgstruct-mode will *not* remove the
7278 indentation/paragraph settings. This can only be done by refreshing the
7279 major mode, for example with \\[normal-mode]."
7280 (interactive "P")
7281 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7282 (if (< arg 1)
7283 (orgstruct-mode -1)
7284 (orgstruct-mode 1)
7285 (let (var val)
7286 (mapc
7287 (lambda (x)
7288 (when (string-match
7289 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7290 (symbol-name (car x)))
7291 (setq var (car x) val (nth 1 x))
7292 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7293 org-local-vars)
7294 (org-set-local 'orgstruct-is-++ t))))
7296 (defvar orgstruct-is-++ nil
7297 "Is orgstruct-mode in ++ version in the current-buffer?")
7298 (make-variable-buffer-local 'orgstruct-is-++)
7300 ;;;###autoload
7301 (defun turn-on-orgstruct++ ()
7302 "Unconditionally turn on `orgstruct++-mode'."
7303 (orgstruct++-mode 1))
7305 (defun orgstruct-error ()
7306 "Error when there is no default binding for a structure key."
7307 (interactive)
7308 (error "This key has no function outside structure elements"))
7310 (defun orgstruct-setup ()
7311 "Setup orgstruct keymaps."
7312 (let ((nfunc 0)
7313 (bindings
7314 (list
7315 '([(meta up)] org-metaup)
7316 '([(meta down)] org-metadown)
7317 '([(meta left)] org-metaleft)
7318 '([(meta right)] org-metaright)
7319 '([(meta shift up)] org-shiftmetaup)
7320 '([(meta shift down)] org-shiftmetadown)
7321 '([(meta shift left)] org-shiftmetaleft)
7322 '([(meta shift right)] org-shiftmetaright)
7323 '([?\e (up)] org-metaup)
7324 '([?\e (down)] org-metadown)
7325 '([?\e (left)] org-metaleft)
7326 '([?\e (right)] org-metaright)
7327 '([?\e (shift up)] org-shiftmetaup)
7328 '([?\e (shift down)] org-shiftmetadown)
7329 '([?\e (shift left)] org-shiftmetaleft)
7330 '([?\e (shift right)] org-shiftmetaright)
7331 '([(shift up)] org-shiftup)
7332 '([(shift down)] org-shiftdown)
7333 '([(shift left)] org-shiftleft)
7334 '([(shift right)] org-shiftright)
7335 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7336 '("\M-q" fill-paragraph)
7337 '("\C-c^" org-sort)
7338 '("\C-c-" org-cycle-list-bullet)))
7339 elt key fun cmd)
7340 (while (setq elt (pop bindings))
7341 (setq nfunc (1+ nfunc))
7342 (setq key (org-key (car elt))
7343 fun (nth 1 elt)
7344 cmd (orgstruct-make-binding fun nfunc key))
7345 (org-defkey orgstruct-mode-map key cmd))
7347 ;; Special treatment needed for TAB and RET
7348 (org-defkey orgstruct-mode-map [(tab)]
7349 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7350 (org-defkey orgstruct-mode-map "\C-i"
7351 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7353 (org-defkey orgstruct-mode-map "\M-\C-m"
7354 (orgstruct-make-binding 'org-insert-heading 105
7355 "\M-\C-m" [(meta return)]))
7356 (org-defkey orgstruct-mode-map [(meta return)]
7357 (orgstruct-make-binding 'org-insert-heading 106
7358 [(meta return)] "\M-\C-m"))
7360 (org-defkey orgstruct-mode-map [(shift meta return)]
7361 (orgstruct-make-binding 'org-insert-todo-heading 107
7362 [(meta return)] "\M-\C-m"))
7364 (org-defkey orgstruct-mode-map "\e\C-m"
7365 (orgstruct-make-binding 'org-insert-heading 108
7366 "\e\C-m" [?\e (return)]))
7367 (org-defkey orgstruct-mode-map [?\e (return)]
7368 (orgstruct-make-binding 'org-insert-heading 109
7369 [?\e (return)] "\e\C-m"))
7370 (org-defkey orgstruct-mode-map [?\e (shift return)]
7371 (orgstruct-make-binding 'org-insert-todo-heading 110
7372 [?\e (return)] "\e\C-m"))
7374 (unless org-local-vars
7375 (setq org-local-vars (org-get-local-variables)))
7379 (defun orgstruct-make-binding (fun n &rest keys)
7380 "Create a function for binding in the structure minor mode.
7381 FUN is the command to call inside a table. N is used to create a unique
7382 command name. KEYS are keys that should be checked in for a command
7383 to execute outside of tables."
7384 (eval
7385 (list 'defun
7386 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7387 '(arg)
7388 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7389 "Outside of structure, run the binding of `"
7390 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7391 "'.")
7392 '(interactive "p")
7393 (list 'if
7394 `(org-context-p 'headline 'item
7395 (and orgstruct-is-++
7396 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7397 'item-body))
7398 (list 'org-run-like-in-org-mode (list 'quote fun))
7399 (list 'let '(orgstruct-mode)
7400 (list 'call-interactively
7401 (append '(or)
7402 (mapcar (lambda (k)
7403 (list 'key-binding k))
7404 keys)
7405 '('orgstruct-error))))))))
7407 (defun org-context-p (&rest contexts)
7408 "Check if local context is any of CONTEXTS.
7409 Possible values in the list of contexts are `table', `headline', and `item'."
7410 (let ((pos (point)))
7411 (goto-char (point-at-bol))
7412 (prog1 (or (and (memq 'table contexts)
7413 (looking-at "[ \t]*|"))
7414 (and (memq 'headline contexts)
7415 ;;????????? (looking-at "\\*+"))
7416 (looking-at outline-regexp))
7417 (and (memq 'item contexts)
7418 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7419 (and (memq 'item-body contexts)
7420 (org-in-item-p)))
7421 (goto-char pos))))
7423 (defun org-get-local-variables ()
7424 "Return a list of all local variables in an org-mode buffer."
7425 (let (varlist)
7426 (with-current-buffer (get-buffer-create "*Org tmp*")
7427 (erase-buffer)
7428 (org-mode)
7429 (setq varlist (buffer-local-variables)))
7430 (kill-buffer "*Org tmp*")
7431 (delq nil
7432 (mapcar
7433 (lambda (x)
7434 (setq x
7435 (if (symbolp x)
7436 (list x)
7437 (list (car x) (list 'quote (cdr x)))))
7438 (if (string-match
7439 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7440 (symbol-name (car x)))
7441 x nil))
7442 varlist))))
7444 ;;;###autoload
7445 (defun org-run-like-in-org-mode (cmd)
7446 "Run a command, pretending that the current buffer is in Org-mode.
7447 This will temporarily bind local variables that are typically bound in
7448 Org-mode to the values they have in Org-mode, and then interactively
7449 call CMD."
7450 (org-load-modules-maybe)
7451 (unless org-local-vars
7452 (setq org-local-vars (org-get-local-variables)))
7453 (eval (list 'let org-local-vars
7454 (list 'call-interactively (list 'quote cmd)))))
7456 ;;;; Archiving
7458 (defun org-get-category (&optional pos)
7459 "Get the category applying to position POS."
7460 (get-text-property (or pos (point)) 'org-category))
7462 (defun org-refresh-category-properties ()
7463 "Refresh category text properties in the buffer."
7464 (let ((def-cat (cond
7465 ((null org-category)
7466 (if buffer-file-name
7467 (file-name-sans-extension
7468 (file-name-nondirectory buffer-file-name))
7469 "???"))
7470 ((symbolp org-category) (symbol-name org-category))
7471 (t org-category)))
7472 beg end cat pos optionp)
7473 (org-unmodified
7474 (save-excursion
7475 (save-restriction
7476 (widen)
7477 (goto-char (point-min))
7478 (put-text-property (point) (point-max) 'org-category def-cat)
7479 (while (re-search-forward
7480 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7481 (setq pos (match-end 0)
7482 optionp (equal (char-after (match-beginning 0)) ?#)
7483 cat (org-trim (match-string 2)))
7484 (if optionp
7485 (setq beg (point-at-bol) end (point-max))
7486 (org-back-to-heading t)
7487 (setq beg (point) end (org-end-of-subtree t t)))
7488 (put-text-property beg end 'org-category cat)
7489 (goto-char pos)))))))
7492 ;;;; Link Stuff
7494 ;;; Link abbreviations
7496 (defun org-link-expand-abbrev (link)
7497 "Apply replacements as defined in `org-link-abbrev-alist."
7498 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7499 (let* ((key (match-string 1 link))
7500 (as (or (assoc key org-link-abbrev-alist-local)
7501 (assoc key org-link-abbrev-alist)))
7502 (tag (and (match-end 2) (match-string 3 link)))
7503 rpl)
7504 (if (not as)
7505 link
7506 (setq rpl (cdr as))
7507 (cond
7508 ((symbolp rpl) (funcall rpl tag))
7509 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7510 ((string-match "%h" rpl)
7511 (replace-match (url-hexify-string (or tag "")) t t rpl))
7512 (t (concat rpl tag)))))
7513 link))
7515 ;;; Storing and inserting links
7517 (defvar org-insert-link-history nil
7518 "Minibuffer history for links inserted with `org-insert-link'.")
7520 (defvar org-stored-links nil
7521 "Contains the links stored with `org-store-link'.")
7523 (defvar org-store-link-plist nil
7524 "Plist with info about the most recently link created with `org-store-link'.")
7526 (defvar org-link-protocols nil
7527 "Link protocols added to Org-mode using `org-add-link-type'.")
7529 (defvar org-store-link-functions nil
7530 "List of functions that are called to create and store a link.
7531 Each function will be called in turn until one returns a non-nil
7532 value. Each function should check if it is responsible for creating
7533 this link (for example by looking at the major mode).
7534 If not, it must exit and return nil.
7535 If yes, it should return a non-nil value after a calling
7536 `org-store-link-props' with a list of properties and values.
7537 Special properties are:
7539 :type The link prefix. like \"http\". This must be given.
7540 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7541 This is obligatory as well.
7542 :description Optional default description for the second pair
7543 of brackets in an Org-mode link. The user can still change
7544 this when inserting this link into an Org-mode buffer.
7546 In addition to these, any additional properties can be specified
7547 and then used in remember templates.")
7549 (defun org-add-link-type (type &optional follow export)
7550 "Add TYPE to the list of `org-link-types'.
7551 Re-compute all regular expressions depending on `org-link-types'
7553 FOLLOW and EXPORT are two functions.
7555 FOLLOW should take the link path as the single argument and do whatever
7556 is necessary to follow the link, for example find a file or display
7557 a mail message.
7559 EXPORT should format the link path for export to one of the export formats.
7560 It should be a function accepting three arguments:
7562 path the path of the link, the text after the prefix (like \"http:\")
7563 desc the description of the link, if any, nil if there was no description
7564 format the export format, a symbol like `html' or `latex'.
7566 The function may use the FORMAT information to return different values
7567 depending on the format. The return value will be put literally into
7568 the exported file.
7569 Org-mode has a built-in default for exporting links. If you are happy with
7570 this default, there is no need to define an export function for the link
7571 type. For a simple example of an export function, see `org-bbdb.el'."
7572 (add-to-list 'org-link-types type t)
7573 (org-make-link-regexps)
7574 (if (assoc type org-link-protocols)
7575 (setcdr (assoc type org-link-protocols) (list follow export))
7576 (push (list type follow export) org-link-protocols)))
7578 (defvar org-agenda-buffer-name)
7580 ;;;###autoload
7581 (defun org-store-link (arg)
7582 "\\<org-mode-map>Store an org-link to the current location.
7583 This link is added to `org-stored-links' and can later be inserted
7584 into an org-buffer with \\[org-insert-link].
7586 For some link types, a prefix arg is interpreted:
7587 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7588 For file links, arg negates `org-context-in-file-links'."
7589 (interactive "P")
7590 (org-load-modules-maybe)
7591 (setq org-store-link-plist nil) ; reset
7592 (let ((outline-regexp (org-get-limited-outline-regexp))
7593 link cpltxt desc description search txt custom-id)
7594 (cond
7596 ((run-hook-with-args-until-success 'org-store-link-functions)
7597 (setq link (plist-get org-store-link-plist :link)
7598 desc (or (plist-get org-store-link-plist :description) link)))
7600 ((equal (buffer-name) "*Org Edit Src Example*")
7601 (let (label gc)
7602 (while (or (not label)
7603 (save-excursion
7604 (save-restriction
7605 (widen)
7606 (goto-char (point-min))
7607 (re-search-forward
7608 (regexp-quote (format org-coderef-label-format label))
7609 nil t))))
7610 (when label (message "Label exists already") (sit-for 2))
7611 (setq label (read-string "Code line label: " label)))
7612 (end-of-line 1)
7613 (setq link (format org-coderef-label-format label))
7614 (setq gc (- 79 (length link)))
7615 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7616 (insert link)
7617 (setq link (concat "(" label ")") desc nil)))
7619 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7620 ;; We are in the agenda, link to referenced location
7621 (let ((m (or (get-text-property (point) 'org-hd-marker)
7622 (get-text-property (point) 'org-marker))))
7623 (when m
7624 (org-with-point-at m
7625 (call-interactively 'org-store-link)))))
7627 ((eq major-mode 'calendar-mode)
7628 (let ((cd (calendar-cursor-to-date)))
7629 (setq link
7630 (format-time-string
7631 (car org-time-stamp-formats)
7632 (apply 'encode-time
7633 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7634 nil nil nil))))
7635 (org-store-link-props :type "calendar" :date cd)))
7637 ((eq major-mode 'w3-mode)
7638 (setq cpltxt (if (and (buffer-name)
7639 (not (string-match "Untitled" (buffer-name))))
7640 (buffer-name)
7641 (url-view-url t))
7642 link (org-make-link (url-view-url t)))
7643 (org-store-link-props :type "w3" :url (url-view-url t)))
7645 ((eq major-mode 'w3m-mode)
7646 (setq cpltxt (or w3m-current-title w3m-current-url)
7647 link (org-make-link w3m-current-url))
7648 (org-store-link-props :type "w3m" :url (url-view-url t)))
7650 ((setq search (run-hook-with-args-until-success
7651 'org-create-file-search-functions))
7652 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7653 "::" search))
7654 (setq cpltxt (or description link)))
7656 ((eq major-mode 'image-mode)
7657 (setq cpltxt (concat "file:"
7658 (abbreviate-file-name buffer-file-name))
7659 link (org-make-link cpltxt))
7660 (org-store-link-props :type "image" :file buffer-file-name))
7662 ((eq major-mode 'dired-mode)
7663 ;; link to the file in the current line
7664 (setq cpltxt (concat "file:"
7665 (abbreviate-file-name
7666 (expand-file-name
7667 (dired-get-filename nil t))))
7668 link (org-make-link cpltxt)))
7670 ((and buffer-file-name (org-mode-p))
7671 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7672 (cond
7673 ((org-in-regexp "<<\\(.*?\\)>>")
7674 (setq cpltxt
7675 (concat "file:"
7676 (abbreviate-file-name buffer-file-name)
7677 "::" (match-string 1))
7678 link (org-make-link cpltxt)))
7679 ((and (featurep 'org-id)
7680 (or (eq org-link-to-org-use-id t)
7681 (and (eq org-link-to-org-use-id 'create-if-interactive)
7682 (interactive-p))
7683 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7684 (interactive-p)
7685 (not custom-id))
7686 (and org-link-to-org-use-id
7687 (condition-case nil
7688 (org-entry-get nil "ID")
7689 (error nil)))))
7690 ;; We can make a link using the ID.
7691 (setq link (condition-case nil
7692 (prog1 (org-id-store-link)
7693 (setq desc (plist-get org-store-link-plist
7694 :description)))
7695 (error
7696 ;; probably before first headline, link to file only
7697 (concat "file:"
7698 (abbreviate-file-name buffer-file-name))))))
7700 ;; Just link to current headline
7701 (setq cpltxt (concat "file:"
7702 (abbreviate-file-name buffer-file-name)))
7703 ;; Add a context search string
7704 (when (org-xor org-context-in-file-links arg)
7705 (setq txt (cond
7706 ((org-on-heading-p) nil)
7707 ((org-region-active-p)
7708 (buffer-substring (region-beginning) (region-end)))
7709 (t nil)))
7710 (when (or (null txt) (string-match "\\S-" txt))
7711 (setq cpltxt
7712 (concat cpltxt "::"
7713 (condition-case nil
7714 (org-make-org-heading-search-string txt)
7715 (error "")))
7716 desc (or (nth 4 (ignore-errors
7717 (org-heading-components))) "NONE"))))
7718 (if (string-match "::\\'" cpltxt)
7719 (setq cpltxt (substring cpltxt 0 -2)))
7720 (setq link (org-make-link cpltxt)))))
7722 ((buffer-file-name (buffer-base-buffer))
7723 ;; Just link to this file here.
7724 (setq cpltxt (concat "file:"
7725 (abbreviate-file-name
7726 (buffer-file-name (buffer-base-buffer)))))
7727 ;; Add a context string
7728 (when (org-xor org-context-in-file-links arg)
7729 (setq txt (if (org-region-active-p)
7730 (buffer-substring (region-beginning) (region-end))
7731 (buffer-substring (point-at-bol) (point-at-eol))))
7732 ;; Only use search option if there is some text.
7733 (when (string-match "\\S-" txt)
7734 (setq cpltxt
7735 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7736 desc "NONE")))
7737 (setq link (org-make-link cpltxt)))
7739 ((interactive-p)
7740 (error "Cannot link to a buffer which is not visiting a file"))
7742 (t (setq link nil)))
7744 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7745 (setq link (or link cpltxt)
7746 desc (or desc cpltxt))
7747 (if (equal desc "NONE") (setq desc nil))
7749 (if (and (or (interactive-p) executing-kbd-macro) link)
7750 (progn
7751 (setq org-stored-links
7752 (cons (list link desc) org-stored-links))
7753 (message "Stored: %s" (or desc link))
7754 (when custom-id
7755 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7756 "::#" custom-id))
7757 (setq org-stored-links
7758 (cons (list link desc) org-stored-links))))
7759 (and link (org-make-link-string link desc)))))
7761 (defun org-store-link-props (&rest plist)
7762 "Store link properties, extract names and addresses."
7763 (let (x adr)
7764 (when (setq x (plist-get plist :from))
7765 (setq adr (mail-extract-address-components x))
7766 (setq plist (plist-put plist :fromname (car adr)))
7767 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7768 (when (setq x (plist-get plist :to))
7769 (setq adr (mail-extract-address-components x))
7770 (setq plist (plist-put plist :toname (car adr)))
7771 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7772 (let ((from (plist-get plist :from))
7773 (to (plist-get plist :to)))
7774 (when (and from to org-from-is-user-regexp)
7775 (setq plist
7776 (plist-put plist :fromto
7777 (if (string-match org-from-is-user-regexp from)
7778 (concat "to %t")
7779 (concat "from %f"))))))
7780 (setq org-store-link-plist plist))
7782 (defun org-add-link-props (&rest plist)
7783 "Add these properties to the link property list."
7784 (let (key value)
7785 (while plist
7786 (setq key (pop plist) value (pop plist))
7787 (setq org-store-link-plist
7788 (plist-put org-store-link-plist key value)))))
7790 (defun org-email-link-description (&optional fmt)
7791 "Return the description part of an email link.
7792 This takes information from `org-store-link-plist' and formats it
7793 according to FMT (default from `org-email-link-description-format')."
7794 (setq fmt (or fmt org-email-link-description-format))
7795 (let* ((p org-store-link-plist)
7796 (to (plist-get p :toaddress))
7797 (from (plist-get p :fromaddress))
7798 (table
7799 (list
7800 (cons "%c" (plist-get p :fromto))
7801 (cons "%F" (plist-get p :from))
7802 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7803 (cons "%T" (plist-get p :to))
7804 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7805 (cons "%s" (plist-get p :subject))
7806 (cons "%m" (plist-get p :message-id)))))
7807 (when (string-match "%c" fmt)
7808 ;; Check if the user wrote this message
7809 (if (and org-from-is-user-regexp from to
7810 (save-match-data (string-match org-from-is-user-regexp from)))
7811 (setq fmt (replace-match "to %t" t t fmt))
7812 (setq fmt (replace-match "from %f" t t fmt))))
7813 (org-replace-escapes fmt table)))
7815 (defun org-make-org-heading-search-string (&optional string heading)
7816 "Make search string for STRING or current headline."
7817 (interactive)
7818 (let ((s (or string (org-get-heading))))
7819 (unless (and string (not heading))
7820 ;; We are using a headline, clean up garbage in there.
7821 (if (string-match org-todo-regexp s)
7822 (setq s (replace-match "" t t s)))
7823 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7824 (setq s (replace-match "" t t s)))
7825 (setq s (org-trim s))
7826 (if (string-match (concat "^\\(" org-quote-string "\\|"
7827 org-comment-string "\\)") s)
7828 (setq s (replace-match "" t t s)))
7829 (while (string-match org-ts-regexp s)
7830 (setq s (replace-match "" t t s))))
7831 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7832 (setq s (replace-match " " t t s)))
7833 (or string (setq s (concat "*" s))) ; Add * for headlines
7834 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7836 (defun org-make-link (&rest strings)
7837 "Concatenate STRINGS."
7838 (apply 'concat strings))
7840 (defun org-make-link-string (link &optional description)
7841 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7842 (unless (string-match "\\S-" link)
7843 (error "Empty link"))
7844 (when (and description
7845 (stringp description)
7846 (not (string-match "\\S-" description)))
7847 (setq description nil))
7848 (when (stringp description)
7849 ;; Remove brackets from the description, they are fatal.
7850 (while (string-match "\\[" description)
7851 (setq description (replace-match "{" t t description)))
7852 (while (string-match "\\]" description)
7853 (setq description (replace-match "}" t t description))))
7854 (when (equal (org-link-escape link) description)
7855 ;; No description needed, it is identical
7856 (setq description nil))
7857 (when (and (not description)
7858 (not (equal link (org-link-escape link))))
7859 (setq description (org-extract-attributes link)))
7860 (concat "[[" (org-link-escape link) "]"
7861 (if description (concat "[" description "]") "")
7862 "]"))
7864 (defconst org-link-escape-chars
7865 '((?\ . "%20")
7866 (?\[ . "%5B")
7867 (?\] . "%5D")
7868 (?\340 . "%E0") ; `a
7869 (?\342 . "%E2") ; ^a
7870 (?\347 . "%E7") ; ,c
7871 (?\350 . "%E8") ; `e
7872 (?\351 . "%E9") ; 'e
7873 (?\352 . "%EA") ; ^e
7874 (?\356 . "%EE") ; ^i
7875 (?\364 . "%F4") ; ^o
7876 (?\371 . "%F9") ; `u
7877 (?\373 . "%FB") ; ^u
7878 (?\; . "%3B")
7879 (?? . "%3F")
7880 (?= . "%3D")
7881 (?+ . "%2B")
7883 "Association list of escapes for some characters problematic in links.
7884 This is the list that is used for internal purposes.")
7886 (defvar org-url-encoding-use-url-hexify nil)
7888 (defconst org-link-escape-chars-browser
7889 '((?\ . "%20")) ; 32 for the SPC char
7890 "Association list of escapes for some characters problematic in links.
7891 This is the list that is used before handing over to the browser.")
7893 (defun org-link-escape (text &optional table)
7894 "Escape characters in TEXT that are problematic for links."
7895 (if org-url-encoding-use-url-hexify
7896 (url-hexify-string text)
7897 (setq table (or table org-link-escape-chars))
7898 (when text
7899 (let ((re (mapconcat (lambda (x) (regexp-quote
7900 (char-to-string (car x))))
7901 table "\\|")))
7902 (while (string-match re text)
7903 (setq text
7904 (replace-match
7905 (cdr (assoc (string-to-char (match-string 0 text))
7906 table))
7907 t t text)))
7908 text))))
7910 (defun org-link-unescape (text &optional table)
7911 "Reverse the action of `org-link-escape'."
7912 (if org-url-encoding-use-url-hexify
7913 (url-unhex-string text)
7914 (setq table (or table org-link-escape-chars))
7915 (when text
7916 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7917 table "\\|")))
7918 (while (string-match re text)
7919 (setq text
7920 (replace-match
7921 (char-to-string (car (rassoc (match-string 0 text) table)))
7922 t t text)))
7923 text))))
7925 (defun org-xor (a b)
7926 "Exclusive or."
7927 (if a (not b) b))
7929 (defun org-fixup-message-id-for-http (s)
7930 "Replace special characters in a message id, so it can be used in an http query."
7931 (while (string-match "<" s)
7932 (setq s (replace-match "%3C" t t s)))
7933 (while (string-match ">" s)
7934 (setq s (replace-match "%3E" t t s)))
7935 (while (string-match "@" s)
7936 (setq s (replace-match "%40" t t s)))
7939 ;;;###autoload
7940 (defun org-insert-link-global ()
7941 "Insert a link like Org-mode does.
7942 This command can be called in any mode to insert a link in Org-mode syntax."
7943 (interactive)
7944 (org-load-modules-maybe)
7945 (org-run-like-in-org-mode 'org-insert-link))
7947 (defun org-insert-link (&optional complete-file link-location)
7948 "Insert a link. At the prompt, enter the link.
7950 Completion can be used to insert any of the link protocol prefixes like
7951 http or ftp in use.
7953 The history can be used to select a link previously stored with
7954 `org-store-link'. When the empty string is entered (i.e. if you just
7955 press RET at the prompt), the link defaults to the most recently
7956 stored link. As SPC triggers completion in the minibuffer, you need to
7957 use M-SPC or C-q SPC to force the insertion of a space character.
7959 You will also be prompted for a description, and if one is given, it will
7960 be displayed in the buffer instead of the link.
7962 If there is already a link at point, this command will allow you to edit link
7963 and description parts.
7965 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7966 be selected using completion. The path to the file will be relative to the
7967 current directory if the file is in the current directory or a subdirectory.
7968 Otherwise, the link will be the absolute path as completed in the minibuffer
7969 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7970 option `org-link-file-path-type'.
7972 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7973 the current directory or below.
7975 With three \\[universal-argument] prefixes, negate the meaning of
7976 `org-keep-stored-link-after-insertion'.
7978 If `org-make-link-description-function' is non-nil, this function will be
7979 called with the link target, and the result will be the default
7980 link description.
7982 If the LINK-LOCATION parameter is non-nil, this value will be
7983 used as the link location instead of reading one interactively."
7984 (interactive "P")
7985 (let* ((wcf (current-window-configuration))
7986 (region (if (org-region-active-p)
7987 (buffer-substring (region-beginning) (region-end))))
7988 (remove (and region (list (region-beginning) (region-end))))
7989 (desc region)
7990 tmphist ; byte-compile incorrectly complains about this
7991 (link link-location)
7992 entry file all-prefixes)
7993 (cond
7994 (link-location) ; specified by arg, just use it.
7995 ((org-in-regexp org-bracket-link-regexp 1)
7996 ;; We do have a link at point, and we are going to edit it.
7997 (setq remove (list (match-beginning 0) (match-end 0)))
7998 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7999 (setq link (read-string "Link: "
8000 (org-link-unescape
8001 (org-match-string-no-properties 1)))))
8002 ((or (org-in-regexp org-angle-link-re)
8003 (org-in-regexp org-plain-link-re))
8004 ;; Convert to bracket link
8005 (setq remove (list (match-beginning 0) (match-end 0))
8006 link (read-string "Link: "
8007 (org-remove-angle-brackets (match-string 0)))))
8008 ((member complete-file '((4) (16)))
8009 ;; Completing read for file names.
8010 (setq link (org-file-complete-link complete-file)))
8012 ;; Read link, with completion for stored links.
8013 (with-output-to-temp-buffer "*Org Links*"
8014 (princ "Insert a link.
8015 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8016 (when org-stored-links
8017 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8018 (princ (mapconcat
8019 (lambda (x)
8020 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8021 (reverse org-stored-links) "\n"))))
8022 (let ((cw (selected-window)))
8023 (select-window (get-buffer-window "*Org Links*"))
8024 (setq truncate-lines t)
8025 (unless (pos-visible-in-window-p (point-max))
8026 (org-fit-window-to-buffer))
8027 (and (window-live-p cw) (select-window cw)))
8028 ;; Fake a link history, containing the stored links.
8029 (setq tmphist (append (mapcar 'car org-stored-links)
8030 org-insert-link-history))
8031 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8032 (mapcar 'car org-link-abbrev-alist)
8033 org-link-types))
8034 (unwind-protect
8035 (progn
8036 (setq link
8037 (let ((org-completion-use-ido nil)
8038 (org-completion-use-iswitchb nil))
8039 (org-completing-read
8040 "Link: "
8041 (append
8042 (mapcar (lambda (x) (list (concat x ":")))
8043 all-prefixes)
8044 (mapcar 'car org-stored-links))
8045 nil nil nil
8046 'tmphist
8047 (car (car org-stored-links)))))
8048 (if (not (string-match "\\S-" link))
8049 (error "No link selected"))
8050 (if (or (member link all-prefixes)
8051 (and (equal ":" (substring link -1))
8052 (member (substring link 0 -1) all-prefixes)
8053 (setq link (substring link 0 -1))))
8054 (setq link (org-link-try-special-completion link))))
8055 (set-window-configuration wcf)
8056 (kill-buffer "*Org Links*"))
8057 (setq entry (assoc link org-stored-links))
8058 (or entry (push link org-insert-link-history))
8059 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8060 (not org-keep-stored-link-after-insertion))
8061 (setq org-stored-links (delq (assoc link org-stored-links)
8062 org-stored-links)))
8063 (setq desc (or desc (nth 1 entry)))))
8065 (if (string-match org-plain-link-re link)
8066 ;; URL-like link, normalize the use of angular brackets.
8067 (setq link (org-make-link (org-remove-angle-brackets link))))
8069 ;; Check if we are linking to the current file with a search option
8070 ;; If yes, simplify the link by using only the search option.
8071 (when (and buffer-file-name
8072 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8073 (let* ((path (match-string 1 link))
8074 (case-fold-search nil)
8075 (search (match-string 2 link)))
8076 (save-match-data
8077 (if (equal (file-truename buffer-file-name) (file-truename path))
8078 ;; We are linking to this same file, with a search option
8079 (setq link search)))))
8081 ;; Check if we can/should use a relative path. If yes, simplify the link
8082 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8083 (let* ((type (match-string 1 link))
8084 (path (match-string 2 link))
8085 (origpath path)
8086 (case-fold-search nil))
8087 (cond
8088 ((or (eq org-link-file-path-type 'absolute)
8089 (equal complete-file '(16)))
8090 (setq path (abbreviate-file-name (expand-file-name path))))
8091 ((eq org-link-file-path-type 'noabbrev)
8092 (setq path (expand-file-name path)))
8093 ((eq org-link-file-path-type 'relative)
8094 (setq path (file-relative-name path)))
8096 (save-match-data
8097 (if (string-match (concat "^" (regexp-quote
8098 (file-name-as-directory
8099 (expand-file-name "."))))
8100 (expand-file-name path))
8101 ;; We are linking a file with relative path name.
8102 (setq path (substring (expand-file-name path)
8103 (match-end 0)))
8104 (setq path (abbreviate-file-name (expand-file-name path)))))))
8105 (setq link (concat type path))
8106 (if (equal desc origpath)
8107 (setq desc path))))
8109 (if org-make-link-description-function
8110 (setq desc (funcall org-make-link-description-function link desc)))
8112 (setq desc (read-string "Description: " desc))
8113 (unless (string-match "\\S-" desc) (setq desc nil))
8114 (if remove (apply 'delete-region remove))
8115 (insert (org-make-link-string link desc))))
8117 (defun org-link-try-special-completion (type)
8118 "If there is completion support for link type TYPE, offer it."
8119 (let ((fun (intern (concat "org-" type "-complete-link"))))
8120 (if (functionp fun)
8121 (funcall fun)
8122 (read-string "Link (no completion support): " (concat type ":")))))
8124 (defun org-file-complete-link (&optional arg)
8125 "Create a file link using completion."
8126 (let (file link)
8127 (setq file (read-file-name "File: "))
8128 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8129 (pwd1 (file-name-as-directory (abbreviate-file-name
8130 (expand-file-name ".")))))
8131 (cond
8132 ((equal arg '(16))
8133 (setq link (org-make-link
8134 "file:"
8135 (abbreviate-file-name (expand-file-name file)))))
8136 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8137 (setq link (org-make-link "file:" (match-string 1 file))))
8138 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8139 (expand-file-name file))
8140 (setq link (org-make-link
8141 "file:" (match-string 1 (expand-file-name file)))))
8142 (t (setq link (org-make-link "file:" file)))))
8143 link))
8145 (defun org-completing-read (&rest args)
8146 "Completing-read with SPACE being a normal character."
8147 (let ((minibuffer-local-completion-map
8148 (copy-keymap minibuffer-local-completion-map)))
8149 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8150 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8151 (apply 'org-icompleting-read args)))
8153 (defun org-completing-read-no-i (&rest args)
8154 (let (org-completion-use-ido org-completion-use-iswitchb)
8155 (apply 'org-completing-read args)))
8157 (defun org-iswitchb-completing-read (prompt choices &rest args)
8158 "Use iswitch as a completing-read replacement to choose from choices.
8159 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8160 from."
8161 (let* ((iswitchb-use-virtual-buffers nil)
8162 (iswitchb-make-buflist-hook
8163 (lambda ()
8164 (setq iswitchb-temp-buflist choices))))
8165 (iswitchb-read-buffer prompt)))
8167 (defun org-icompleting-read (&rest args)
8168 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8169 (org-without-partial-completion
8170 (if (and org-completion-use-ido
8171 (fboundp 'ido-completing-read)
8172 (boundp 'ido-mode) ido-mode
8173 (listp (second args)))
8174 (let ((ido-enter-matching-directory nil))
8175 (apply 'ido-completing-read (concat (car args))
8176 (if (consp (car (nth 1 args)))
8177 (mapcar (lambda (x) (car x)) (nth 1 args))
8178 (nth 1 args))
8179 (cddr args)))
8180 (if (and org-completion-use-iswitchb
8181 (boundp 'iswitchb-mode) iswitchb-mode
8182 (listp (second args)))
8183 (apply 'org-iswitchb-completing-read (concat (car args))
8184 (if (consp (car (nth 1 args)))
8185 (mapcar (lambda (x) (car x)) (nth 1 args))
8186 (nth 1 args))
8187 (cddr args))
8188 (apply 'completing-read args)))))
8190 (defun org-extract-attributes (s)
8191 "Extract the attributes cookie from a string and set as text property."
8192 (let (a attr (start 0) key value)
8193 (save-match-data
8194 (when (string-match "{{\\([^}]+\\)}}$" s)
8195 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8196 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8197 (setq key (match-string 1 a) value (match-string 2 a)
8198 start (match-end 0)
8199 attr (plist-put attr (intern key) value))))
8200 (org-add-props s nil 'org-attr attr))
8203 (defun org-extract-attributes-from-string (tag)
8204 (let (key value attr)
8205 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8206 (setq key (match-string 1 tag) value (match-string 2 tag)
8207 tag (replace-match "" t t tag)
8208 attr (plist-put attr (intern key) value)))
8209 (cons tag attr)))
8211 (defun org-attributes-to-string (plist)
8212 "Format a property list into an HTML attribute list."
8213 (let ((s "") key value)
8214 (while plist
8215 (setq key (pop plist) value (pop plist))
8216 (and value
8217 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8220 ;;; Opening/following a link
8222 (defvar org-link-search-failed nil)
8224 (defvar org-open-link-functions nil
8225 "Hook for functions finding a plain text link.
8226 These functions must take a single argument, the link content.
8227 They will be called for links that look like [[link text][description]]
8228 when LINK TEXT does not have a protocol like \"http:\" and does not look
8229 like a filename (e.g. \"./blue.png\").
8231 These functions will be called *before* Org attempts to resolve the
8232 link by doing text searches in the current buffer - so if you want a
8233 link \"[[target]]\" to still find \"<<target>>\", your function should
8234 handle this as a special case.
8236 When the function does handle the link, it must return a non-nil value.
8237 If it decides that it is not responsible for this link, it must return
8238 nil to indicate that that Org-mode can continue with other options
8239 like exact and fuzzy text search.")
8241 (defun org-next-link ()
8242 "Move forward to the next link.
8243 If the link is in hidden text, expose it."
8244 (interactive)
8245 (when (and org-link-search-failed (eq this-command last-command))
8246 (goto-char (point-min))
8247 (message "Link search wrapped back to beginning of buffer"))
8248 (setq org-link-search-failed nil)
8249 (let* ((pos (point))
8250 (ct (org-context))
8251 (a (assoc :link ct)))
8252 (if a (goto-char (nth 2 a)))
8253 (if (re-search-forward org-any-link-re nil t)
8254 (progn
8255 (goto-char (match-beginning 0))
8256 (if (org-invisible-p) (org-show-context)))
8257 (goto-char pos)
8258 (setq org-link-search-failed t)
8259 (error "No further link found"))))
8261 (defun org-previous-link ()
8262 "Move backward to the previous link.
8263 If the link is in hidden text, expose it."
8264 (interactive)
8265 (when (and org-link-search-failed (eq this-command last-command))
8266 (goto-char (point-max))
8267 (message "Link search wrapped back to end of buffer"))
8268 (setq org-link-search-failed nil)
8269 (let* ((pos (point))
8270 (ct (org-context))
8271 (a (assoc :link ct)))
8272 (if a (goto-char (nth 1 a)))
8273 (if (re-search-backward org-any-link-re nil t)
8274 (progn
8275 (goto-char (match-beginning 0))
8276 (if (org-invisible-p) (org-show-context)))
8277 (goto-char pos)
8278 (setq org-link-search-failed t)
8279 (error "No further link found"))))
8281 (defun org-translate-link (s)
8282 "Translate a link string if a translation function has been defined."
8283 (if (and org-link-translation-function
8284 (fboundp org-link-translation-function)
8285 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8286 (progn
8287 (setq s (funcall org-link-translation-function
8288 (match-string 1) (match-string 2)))
8289 (concat (car s) ":" (cdr s)))
8292 (defun org-translate-link-from-planner (type path)
8293 "Translate a link from Emacs Planner syntax so that Org can follow it.
8294 This is still an experimental function, your mileage may vary."
8295 (cond
8296 ((member type '("http" "https" "news" "ftp"))
8297 ;; standard Internet links are the same.
8298 nil)
8299 ((and (equal type "irc") (string-match "^//" path))
8300 ;; Planner has two / at the beginning of an irc link, we have 1.
8301 ;; We should have zero, actually....
8302 (setq path (substring path 1)))
8303 ((and (equal type "lisp") (string-match "^/" path))
8304 ;; Planner has a slash, we do not.
8305 (setq type "elisp" path (substring path 1)))
8306 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8307 ;; A typical message link. Planner has the id after the final slash,
8308 ;; we separate it with a hash mark
8309 (setq path (concat (match-string 1 path) "#"
8310 (org-remove-angle-brackets (match-string 2 path)))))
8312 (cons type path))
8314 (defun org-find-file-at-mouse (ev)
8315 "Open file link or URL at mouse."
8316 (interactive "e")
8317 (mouse-set-point ev)
8318 (org-open-at-point 'in-emacs))
8320 (defun org-open-at-mouse (ev)
8321 "Open file link or URL at mouse."
8322 (interactive "e")
8323 (mouse-set-point ev)
8324 (if (eq major-mode 'org-agenda-mode)
8325 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8326 (org-open-at-point))
8328 (defvar org-window-config-before-follow-link nil
8329 "The window configuration before following a link.
8330 This is saved in case the need arises to restore it.")
8332 (defvar org-open-link-marker (make-marker)
8333 "Marker pointing to the location where `org-open-at-point; was called.")
8335 ;;;###autoload
8336 (defun org-open-at-point-global ()
8337 "Follow a link like Org-mode does.
8338 This command can be called in any mode to follow a link that has
8339 Org-mode syntax."
8340 (interactive)
8341 (org-run-like-in-org-mode 'org-open-at-point))
8343 ;;;###autoload
8344 (defun org-open-link-from-string (s &optional arg reference-buffer)
8345 "Open a link in the string S, as if it was in Org-mode."
8346 (interactive "sLink: \nP")
8347 (let ((reference-buffer (or reference-buffer (current-buffer))))
8348 (with-temp-buffer
8349 (let ((org-inhibit-startup t))
8350 (org-mode)
8351 (insert s)
8352 (goto-char (point-min))
8353 (org-open-at-point arg reference-buffer)))))
8355 (defun org-open-at-point (&optional in-emacs reference-buffer)
8356 "Open link at or after point.
8357 If there is no link at point, this function will search forward up to
8358 the end of the current line.
8359 Normally, files will be opened by an appropriate application. If the
8360 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8361 With a double prefix argument, try to open outside of Emacs, in the
8362 application the system uses for this file type."
8363 (interactive "P")
8364 (org-load-modules-maybe)
8365 (move-marker org-open-link-marker (point))
8366 (setq org-window-config-before-follow-link (current-window-configuration))
8367 (org-remove-occur-highlights nil nil t)
8368 (cond
8369 ((and (org-on-heading-p)
8370 (not (org-in-regexp
8371 (concat org-plain-link-re "\\|"
8372 org-bracket-link-regexp "\\|"
8373 org-angle-link-re "\\|"
8374 "[ \t]:[^ \t\n]+:[ \t]*$"))))
8375 (or (org-offer-links-in-entry in-emacs)
8376 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8377 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8378 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8379 (org-footnote-action))
8381 (let (type path link line search (pos (point)))
8382 (catch 'match
8383 (save-excursion
8384 (skip-chars-forward "^]\n\r")
8385 (when (org-in-regexp org-bracket-link-regexp 1)
8386 (setq link (org-extract-attributes
8387 (org-link-unescape (org-match-string-no-properties 1))))
8388 (while (string-match " *\n *" link)
8389 (setq link (replace-match " " t t link)))
8390 (setq link (org-link-expand-abbrev link))
8391 (cond
8392 ((or (file-name-absolute-p link)
8393 (string-match "^\\.\\.?/" link))
8394 (setq type "file" path link))
8395 ((string-match org-link-re-with-space3 link)
8396 (setq type (match-string 1 link) path (match-string 2 link)))
8397 (t (setq type "thisfile" path link)))
8398 (throw 'match t)))
8400 (when (get-text-property (point) 'org-linked-text)
8401 (setq type "thisfile"
8402 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8403 (1+ (point)) (point))
8404 path (buffer-substring
8405 (previous-single-property-change pos 'org-linked-text)
8406 (next-single-property-change pos 'org-linked-text)))
8407 (throw 'match t))
8409 (save-excursion
8410 (when (or (org-in-regexp org-angle-link-re)
8411 (org-in-regexp org-plain-link-re))
8412 (setq type (match-string 1) path (match-string 2))
8413 (throw 'match t)))
8414 (save-excursion
8415 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8416 (setq type "tags"
8417 path (match-string 1))
8418 (while (string-match ":" path)
8419 (setq path (replace-match "+" t t path)))
8420 (throw 'match t)))
8421 (when (org-in-regexp "<\\([^><\n]+\\)>")
8422 (setq type "tree-match"
8423 path (match-string 1))
8424 (throw 'match t)))
8425 (unless path
8426 (error "No link found"))
8428 ;; switch back to reference buffer
8429 ;; needed when if called in a temporary buffer through
8430 ;; org-open-link-from-string
8431 (with-current-buffer (or reference-buffer (current-buffer))
8433 ;; Remove any trailing spaces in path
8434 (if (string-match " +\\'" path)
8435 (setq path (replace-match "" t t path)))
8436 (if (and org-link-translation-function
8437 (fboundp org-link-translation-function))
8438 ;; Check if we need to translate the link
8439 (let ((tmp (funcall org-link-translation-function type path)))
8440 (setq type (car tmp) path (cdr tmp))))
8442 (cond
8444 ((assoc type org-link-protocols)
8445 (funcall (nth 1 (assoc type org-link-protocols)) path))
8447 ((equal type "mailto")
8448 (let ((cmd (car org-link-mailto-program))
8449 (args (cdr org-link-mailto-program)) args1
8450 (address path) (subject "") a)
8451 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8452 (setq address (match-string 1 path)
8453 subject (org-link-escape (match-string 2 path))))
8454 (while args
8455 (cond
8456 ((not (stringp (car args))) (push (pop args) args1))
8457 (t (setq a (pop args))
8458 (if (string-match "%a" a)
8459 (setq a (replace-match address t t a)))
8460 (if (string-match "%s" a)
8461 (setq a (replace-match subject t t a)))
8462 (push a args1))))
8463 (apply cmd (nreverse args1))))
8465 ((member type '("http" "https" "ftp" "news"))
8466 (browse-url (concat type ":" (org-link-escape
8467 path org-link-escape-chars-browser))))
8469 ((member type '("message"))
8470 (browse-url (concat type ":" path)))
8472 ((string= type "tags")
8473 (org-tags-view in-emacs path))
8475 ((string= type "tree-match")
8476 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8478 ((string= type "file")
8479 (if (string-match "::\\([0-9]+\\)\\'" path)
8480 (setq line (string-to-number (match-string 1 path))
8481 path (substring path 0 (match-beginning 0)))
8482 (if (string-match "::\\(.+\\)\\'" path)
8483 (setq search (match-string 1 path)
8484 path (substring path 0 (match-beginning 0)))))
8485 (if (string-match "[*?{]" (file-name-nondirectory path))
8486 (dired path)
8487 (org-open-file path in-emacs line search)))
8489 ((string= type "news")
8490 (require 'org-gnus)
8491 (org-gnus-follow-link path))
8493 ((string= type "shell")
8494 (let ((cmd path))
8495 (if (or (not org-confirm-shell-link-function)
8496 (funcall org-confirm-shell-link-function
8497 (format "Execute \"%s\" in shell? "
8498 (org-add-props cmd nil
8499 'face 'org-warning))))
8500 (progn
8501 (message "Executing %s" cmd)
8502 (shell-command cmd))
8503 (error "Abort"))))
8505 ((string= type "elisp")
8506 (let ((cmd path))
8507 (if (or (not org-confirm-elisp-link-function)
8508 (funcall org-confirm-elisp-link-function
8509 (format "Execute \"%s\" as elisp? "
8510 (org-add-props cmd nil
8511 'face 'org-warning))))
8512 (message "%s => %s" cmd
8513 (if (equal (string-to-char cmd) ?\()
8514 (eval (read cmd))
8515 (call-interactively (read cmd))))
8516 (error "Abort"))))
8518 ((and (string= type "thisfile")
8519 (run-hook-with-args-until-success
8520 'org-open-link-functions path)))
8522 ((string= type "thisfile")
8523 (if in-emacs
8524 (switch-to-buffer-other-window
8525 (org-get-buffer-for-internal-link (current-buffer)))
8526 (org-mark-ring-push))
8527 (let ((cmd `(org-link-search
8528 ,path
8529 ,(cond ((equal in-emacs '(4)) 'occur)
8530 ((equal in-emacs '(16)) 'org-occur)
8531 (t nil))
8532 ,pos)))
8533 (condition-case nil (eval cmd)
8534 (error (progn (widen) (eval cmd))))))
8537 (browse-url-at-point)))))))
8538 (move-marker org-open-link-marker nil)
8539 (run-hook-with-args 'org-follow-link-hook))
8541 (defun org-offer-links-in-entry (&optional nth zero)
8542 "Offer links in the current entry and follow the selected link.
8543 If there is only one link, follow it immediately as well.
8544 If NTH is an integer, immediately pick the NTH link found.
8545 If ZERO is a string, check also this string for a link, and if
8546 there is one, offer it as link number zero."
8547 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8548 "\\(" org-angle-link-re "\\)\\|"
8549 "\\(" org-plain-link-re "\\)"))
8550 (cnt ?0)
8551 (in-emacs (if (integerp nth) nil nth))
8552 have-zero end links link c)
8553 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8554 (push (match-string 0 zero) links)
8555 (setq cnt (1- cnt) have-zero t))
8556 (save-excursion
8557 (org-back-to-heading t)
8558 (setq end (save-excursion (outline-next-heading) (point)))
8559 (while (re-search-forward re end t)
8560 (push (match-string 0) links))
8561 (setq links (org-uniquify (reverse links))))
8563 (cond
8564 ((null links)
8565 (message "No links"))
8566 ((equal (length links) 1)
8567 (setq link (car links)))
8568 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8569 (setq link (nth (if have-zero nth (1- nth)) links)))
8570 (t ; we have to select a link
8571 (save-excursion
8572 (save-window-excursion
8573 (delete-other-windows)
8574 (with-output-to-temp-buffer "*Select Link*"
8575 (mapc (lambda (l)
8576 (if (not (string-match org-bracket-link-regexp l))
8577 (princ (format "[%c] %s\n" (incf cnt)
8578 (org-remove-angle-brackets l)))
8579 (if (match-end 3)
8580 (princ (format "[%c] %s (%s)\n" (incf cnt)
8581 (match-string 3 l) (match-string 1 l)))
8582 (princ (format "[%c] %s\n" (incf cnt)
8583 (match-string 1 l))))))
8584 links))
8585 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8586 (message "Select link to open, RET to open all:")
8587 (setq c (read-char-exclusive))
8588 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8589 (when (equal c ?q) (error "Abort"))
8590 (if (equal c ?\C-m)
8591 (setq link links)
8592 (setq nth (- c ?0))
8593 (if have-zero (setq nth (1+ nth)))
8594 (unless (and (integerp nth) (>= (length links) nth))
8595 (error "Invalid link selection"))
8596 (setq link (list (nth (1- nth) links))))))
8597 (if link
8598 (let ((buf (current-buffer)))
8599 (dolist (l link)
8600 (org-open-link-from-string l in-emacs buf))
8602 nil)))
8604 ;; Add special file links that specify the way of opening
8606 (org-add-link-type "file+sys" 'org-open-file-with-system)
8607 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
8608 (defun org-open-file-with-system (path)
8609 "Open file at PATH using the system way of opeing it."
8610 (org-open-file path 'system))
8611 (defun org-open-file-with-emacs (path)
8612 "Open file at PATH in emacs."
8613 (org-open-file path 'emacs))
8614 (defun org-remove-file-link-modifiers ()
8615 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
8616 (goto-char (point-min))
8617 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
8618 (org-if-unprotected
8619 (replace-match "file:" t t))))
8620 (eval-after-load "org-exp"
8621 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
8622 'org-remove-file-link-modifiers))
8624 ;;;; Time estimates
8626 (defun org-get-effort (&optional pom)
8627 "Get the effort estimate for the current entry."
8628 (org-entry-get pom org-effort-property))
8630 ;;; File search
8632 (defvar org-create-file-search-functions nil
8633 "List of functions to construct the right search string for a file link.
8634 These functions are called in turn with point at the location to
8635 which the link should point.
8637 A function in the hook should first test if it would like to
8638 handle this file type, for example by checking the major-mode or
8639 the file extension. If it decides not to handle this file, it
8640 should just return nil to give other functions a chance. If it
8641 does handle the file, it must return the search string to be used
8642 when following the link. The search string will be part of the
8643 file link, given after a double colon, and `org-open-at-point'
8644 will automatically search for it. If special measures must be
8645 taken to make the search successful, another function should be
8646 added to the companion hook `org-execute-file-search-functions',
8647 which see.
8649 A function in this hook may also use `setq' to set the variable
8650 `description' to provide a suggestion for the descriptive text to
8651 be used for this link when it gets inserted into an Org-mode
8652 buffer with \\[org-insert-link].")
8654 (defvar org-execute-file-search-functions nil
8655 "List of functions to execute a file search triggered by a link.
8657 Functions added to this hook must accept a single argument, the
8658 search string that was part of the file link, the part after the
8659 double colon. The function must first check if it would like to
8660 handle this search, for example by checking the major-mode or the
8661 file extension. If it decides not to handle this search, it
8662 should just return nil to give other functions a chance. If it
8663 does handle the search, it must return a non-nil value to keep
8664 other functions from trying.
8666 Each function can access the current prefix argument through the
8667 variable `current-prefix-argument'. Note that a single prefix is
8668 used to force opening a link in Emacs, so it may be good to only
8669 use a numeric or double prefix to guide the search function.
8671 In case this is needed, a function in this hook can also restore
8672 the window configuration before `org-open-at-point' was called using:
8674 (set-window-configuration org-window-config-before-follow-link)")
8676 (defun org-link-search (s &optional type avoid-pos)
8677 "Search for a link search option.
8678 If S is surrounded by forward slashes, it is interpreted as a
8679 regular expression. In org-mode files, this will create an `org-occur'
8680 sparse tree. In ordinary files, `occur' will be used to list matches.
8681 If the current buffer is in `dired-mode', grep will be used to search
8682 in all files. If AVOID-POS is given, ignore matches near that position."
8683 (let ((case-fold-search t)
8684 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8685 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8686 (append '(("") (" ") ("\t") ("\n"))
8687 org-emphasis-alist)
8688 "\\|") "\\)"))
8689 (pos (point))
8690 (pre nil) (post nil)
8691 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8692 (cond
8693 ;; First check if there are any special
8694 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8695 ;; Now try the builtin stuff
8696 ((and (equal (string-to-char s0) ?#)
8697 (> (length s0) 1)
8698 (save-excursion
8699 (goto-char (point-min))
8700 (and
8701 (re-search-forward
8702 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8703 (setq type 'dedicated
8704 pos (match-beginning 0))))
8705 ;; There is an exact target for this
8706 (goto-char pos)
8707 (org-back-to-heading t)))
8708 ((save-excursion
8709 (goto-char (point-min))
8710 (and
8711 (re-search-forward
8712 (concat "<<" (regexp-quote s0) ">>") nil t)
8713 (setq type 'dedicated
8714 pos (match-beginning 0))))
8715 ;; There is an exact target for this
8716 (goto-char pos))
8717 ((and (string-match "^(\\(.*\\))$" s0)
8718 (save-excursion
8719 (goto-char (point-min))
8720 (and
8721 (re-search-forward
8722 (concat "[^[]" (regexp-quote
8723 (format org-coderef-label-format
8724 (match-string 1 s0))))
8725 nil t)
8726 (setq type 'dedicated
8727 pos (1+ (match-beginning 0))))))
8728 ;; There is a coderef target for this
8729 (goto-char pos))
8730 ((string-match "^/\\(.*\\)/$" s)
8731 ;; A regular expression
8732 (cond
8733 ((org-mode-p)
8734 (org-occur (match-string 1 s)))
8735 ;;((eq major-mode 'dired-mode)
8736 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8737 (t (org-do-occur (match-string 1 s)))))
8739 ;; A normal search strings
8740 (when (equal (string-to-char s) ?*)
8741 ;; Anchor on headlines, post may include tags.
8742 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8743 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8744 s (substring s 1)))
8745 (remove-text-properties
8746 0 (length s)
8747 '(face nil mouse-face nil keymap nil fontified nil) s)
8748 ;; Make a series of regular expressions to find a match
8749 (setq words (org-split-string s "[ \n\r\t]+")
8751 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8752 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8753 "\\)" markers)
8754 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8755 re2a (concat "[ \t\r\n]" re2a_)
8756 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8757 re4 (concat "[^a-zA-Z_]" re4_)
8759 re1 (concat pre re2 post)
8760 re3 (concat pre (if pre re4_ re4) post)
8761 re5 (concat pre ".*" re4)
8762 re2 (concat pre re2)
8763 re2a (concat pre (if pre re2a_ re2a))
8764 re4 (concat pre (if pre re4_ re4))
8765 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8766 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8767 re5 "\\)"
8769 (cond
8770 ((eq type 'org-occur) (org-occur reall))
8771 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8772 (t (goto-char (point-min))
8773 (setq type 'fuzzy)
8774 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8775 (org-search-not-self 1 re1 nil t)
8776 (org-search-not-self 1 re2 nil t)
8777 (org-search-not-self 1 re2a nil t)
8778 (org-search-not-self 1 re3 nil t)
8779 (org-search-not-self 1 re4 nil t)
8780 (org-search-not-self 1 re5 nil t)
8782 (goto-char (match-beginning 1))
8783 (goto-char pos)
8784 (error "No match")))))
8786 ;; Normal string-search
8787 (goto-char (point-min))
8788 (if (search-forward s nil t)
8789 (goto-char (match-beginning 0))
8790 (error "No match"))))
8791 (and (org-mode-p) (org-show-context 'link-search))
8792 type))
8794 (defun org-search-not-self (group &rest args)
8795 "Execute `re-search-forward', but only accept matches that do not
8796 enclose the position of `org-open-link-marker'."
8797 (let ((m org-open-link-marker))
8798 (catch 'exit
8799 (while (apply 're-search-forward args)
8800 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8801 (goto-char (match-end group))
8802 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8803 (> (match-beginning 0) (marker-position m))
8804 (< (match-end 0) (marker-position m)))
8805 (save-match-data
8806 (or (not (org-in-regexp
8807 org-bracket-link-analytic-regexp 1))
8808 (not (match-end 4)) ; no description
8809 (and (<= (match-beginning 4) (point))
8810 (>= (match-end 4) (point))))))
8811 (throw 'exit (point))))))))
8813 (defun org-get-buffer-for-internal-link (buffer)
8814 "Return a buffer to be used for displaying the link target of internal links."
8815 (cond
8816 ((not org-display-internal-link-with-indirect-buffer)
8817 buffer)
8818 ((string-match "(Clone)$" (buffer-name buffer))
8819 (message "Buffer is already a clone, not making another one")
8820 ;; we also do not modify visibility in this case
8821 buffer)
8822 (t ; make a new indirect buffer for displaying the link
8823 (let* ((bn (buffer-name buffer))
8824 (ibn (concat bn "(Clone)"))
8825 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8826 (with-current-buffer ib (org-overview))
8827 ib))))
8829 (defun org-do-occur (regexp &optional cleanup)
8830 "Call the Emacs command `occur'.
8831 If CLEANUP is non-nil, remove the printout of the regular expression
8832 in the *Occur* buffer. This is useful if the regex is long and not useful
8833 to read."
8834 (occur regexp)
8835 (when cleanup
8836 (let ((cwin (selected-window)) win beg end)
8837 (when (setq win (get-buffer-window "*Occur*"))
8838 (select-window win))
8839 (goto-char (point-min))
8840 (when (re-search-forward "match[a-z]+" nil t)
8841 (setq beg (match-end 0))
8842 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8843 (setq end (1- (match-beginning 0)))))
8844 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8845 (goto-char (point-min))
8846 (select-window cwin))))
8848 ;;; The mark ring for links jumps
8850 (defvar org-mark-ring nil
8851 "Mark ring for positions before jumps in Org-mode.")
8852 (defvar org-mark-ring-last-goto nil
8853 "Last position in the mark ring used to go back.")
8854 ;; Fill and close the ring
8855 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8856 (loop for i from 1 to org-mark-ring-length do
8857 (push (make-marker) org-mark-ring))
8858 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8859 org-mark-ring)
8861 (defun org-mark-ring-push (&optional pos buffer)
8862 "Put the current position or POS into the mark ring and rotate it."
8863 (interactive)
8864 (setq pos (or pos (point)))
8865 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8866 (move-marker (car org-mark-ring)
8867 (or pos (point))
8868 (or buffer (current-buffer)))
8869 (message "%s"
8870 (substitute-command-keys
8871 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8873 (defun org-mark-ring-goto (&optional n)
8874 "Jump to the previous position in the mark ring.
8875 With prefix arg N, jump back that many stored positions. When
8876 called several times in succession, walk through the entire ring.
8877 Org-mode commands jumping to a different position in the current file,
8878 or to another Org-mode file, automatically push the old position
8879 onto the ring."
8880 (interactive "p")
8881 (let (p m)
8882 (if (eq last-command this-command)
8883 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8884 (setq p org-mark-ring))
8885 (setq org-mark-ring-last-goto p)
8886 (setq m (car p))
8887 (switch-to-buffer (marker-buffer m))
8888 (goto-char m)
8889 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8891 (defun org-remove-angle-brackets (s)
8892 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8893 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8895 (defun org-add-angle-brackets (s)
8896 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8897 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8899 (defun org-remove-double-quotes (s)
8900 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8901 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8904 ;;; Following specific links
8906 (defun org-follow-timestamp-link ()
8907 (cond
8908 ((org-at-date-range-p t)
8909 (let ((org-agenda-start-on-weekday)
8910 (t1 (match-string 1))
8911 (t2 (match-string 2)))
8912 (setq t1 (time-to-days (org-time-string-to-time t1))
8913 t2 (time-to-days (org-time-string-to-time t2)))
8914 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8915 ((org-at-timestamp-p t)
8916 (org-agenda-list nil (time-to-days (org-time-string-to-time
8917 (substring (match-string 1) 0 10)))
8919 (t (error "This should not happen"))))
8922 ;;; Following file links
8923 (defvar org-wait nil)
8924 (defun org-open-file (path &optional in-emacs line search)
8925 "Open the file at PATH.
8926 First, this expands any special file name abbreviations. Then the
8927 configuration variable `org-file-apps' is checked if it contains an
8928 entry for this file type, and if yes, the corresponding command is launched.
8930 If no application is found, Emacs simply visits the file.
8932 With optional prefix argument IN-EMACS, Emacs will visit the file.
8933 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8934 and to use an external application to visit the file.
8936 Optional LINE specifies a line to go to, optional SEARCH a string to
8937 search for. If LINE or SEARCH is given, the file will always be
8938 opened in Emacs.
8939 If the file does not exist, an error is thrown."
8940 (setq in-emacs (or in-emacs line search))
8941 (let* ((file (if (equal path "")
8942 buffer-file-name
8943 (substitute-in-file-name (expand-file-name path))))
8944 (apps (append org-file-apps (org-default-apps)))
8945 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8946 (dirp (if remp nil (file-directory-p file)))
8947 (file (if (and dirp org-open-directory-means-index-dot-org)
8948 (concat (file-name-as-directory file) "index.org")
8949 file))
8950 (a-m-a-p (assq 'auto-mode apps))
8951 (dfile (downcase file))
8952 (old-buffer (current-buffer))
8953 (old-pos (point))
8954 (old-mode major-mode)
8955 ext cmd)
8956 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8957 (setq ext (match-string 1 dfile))
8958 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8959 (setq ext (match-string 1 dfile))))
8960 (cond
8961 ((member in-emacs '((16) system))
8962 (setq cmd (cdr (assoc 'system apps))))
8963 (in-emacs (setq cmd 'emacs))
8965 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8966 (and dirp (cdr (assoc 'directory apps)))
8967 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8968 'string-match)
8969 (cdr (assoc ext apps))
8970 (cdr (assoc t apps))))))
8971 (when (eq cmd 'system)
8972 (setq cmd (cdr (assoc 'system apps))))
8973 (when (eq cmd 'default)
8974 (setq cmd (cdr (assoc t apps))))
8975 (when (eq cmd 'mailcap)
8976 (require 'mailcap)
8977 (mailcap-parse-mailcaps)
8978 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8979 (command (mailcap-mime-info mime-type)))
8980 (if (stringp command)
8981 (setq cmd command)
8982 (setq cmd 'emacs))))
8983 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8984 (not (file-exists-p file))
8985 (not org-open-non-existing-files))
8986 (error "No such file: %s" file))
8987 (cond
8988 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8989 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8990 (while (string-match "['\"]%s['\"]" cmd)
8991 (setq cmd (replace-match "%s" t t cmd)))
8992 (while (string-match "%s" cmd)
8993 (setq cmd (replace-match
8994 (save-match-data
8995 (shell-quote-argument
8996 (convert-standard-filename file)))
8997 t t cmd)))
8998 (save-window-excursion
8999 (start-process-shell-command cmd nil cmd)
9000 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9002 ((or (stringp cmd)
9003 (eq cmd 'emacs))
9004 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9005 (widen)
9006 (if line (org-goto-line line)
9007 (if search (org-link-search search))))
9008 ((consp cmd)
9009 (let ((file (convert-standard-filename file)))
9010 (eval cmd)))
9011 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9012 (and (org-mode-p) (eq old-mode 'org-mode)
9013 (or (not (equal old-buffer (current-buffer)))
9014 (not (equal old-pos (point))))
9015 (org-mark-ring-push old-pos old-buffer))))
9017 (defun org-default-apps ()
9018 "Return the default applications for this operating system."
9019 (cond
9020 ((eq system-type 'darwin)
9021 org-file-apps-defaults-macosx)
9022 ((eq system-type 'windows-nt)
9023 org-file-apps-defaults-windowsnt)
9024 (t org-file-apps-defaults-gnu)))
9026 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9027 "Convert extensions to regular expressions in the cars of LIST.
9028 Also, weed out any non-string entries, because the return value is used
9029 only for regexp matching.
9030 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9031 point to the symbol `emacs', indicating that the file should
9032 be opened in Emacs."
9033 (append
9034 (delq nil
9035 (mapcar (lambda (x)
9036 (if (not (stringp (car x)))
9038 (if (string-match "\\W" (car x))
9040 (cons (concat "\\." (car x) "\\'") (cdr x)))))
9041 list))
9042 (if add-auto-mode
9043 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9045 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9046 (defun org-file-remote-p (file)
9047 "Test whether FILE specifies a location on a remote system.
9048 Return non-nil if the location is indeed remote.
9050 For example, the filename \"/user@host:/foo\" specifies a location
9051 on the system \"/user@host:\"."
9052 (cond ((fboundp 'file-remote-p)
9053 (file-remote-p file))
9054 ((fboundp 'tramp-handle-file-remote-p)
9055 (tramp-handle-file-remote-p file))
9056 ((and (boundp 'ange-ftp-name-format)
9057 (string-match (car ange-ftp-name-format) file))
9059 (t nil)))
9062 ;;;; Refiling
9064 (defun org-get-org-file ()
9065 "Read a filename, with default directory `org-directory'."
9066 (let ((default (or org-default-notes-file remember-data-file)))
9067 (read-file-name (format "File name [%s]: " default)
9068 (file-name-as-directory org-directory)
9069 default)))
9071 (defun org-notes-order-reversed-p ()
9072 "Check if the current file should receive notes in reversed order."
9073 (cond
9074 ((not org-reverse-note-order) nil)
9075 ((eq t org-reverse-note-order) t)
9076 ((not (listp org-reverse-note-order)) nil)
9077 (t (catch 'exit
9078 (let ((all org-reverse-note-order)
9079 entry)
9080 (while (setq entry (pop all))
9081 (if (string-match (car entry) buffer-file-name)
9082 (throw 'exit (cdr entry))))
9083 nil)))))
9085 (defvar org-refile-target-table nil
9086 "The list of refile targets, created by `org-refile'.")
9088 (defvar org-agenda-new-buffers nil
9089 "Buffers created to visit agenda files.")
9091 (defun org-get-refile-targets (&optional default-buffer)
9092 "Produce a table with refile targets."
9093 (let ((case-fold-search nil)
9094 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9095 (entries (or org-refile-targets '((nil . (:level . 1)))))
9096 targets txt re files f desc descre fast-path-p level pos0)
9097 (message "Getting targets...")
9098 (with-current-buffer (or default-buffer (current-buffer))
9099 (while (setq entry (pop entries))
9100 (setq files (car entry) desc (cdr entry))
9101 (setq fast-path-p nil)
9102 (cond
9103 ((null files) (setq files (list (current-buffer))))
9104 ((eq files 'org-agenda-files)
9105 (setq files (org-agenda-files 'unrestricted)))
9106 ((and (symbolp files) (fboundp files))
9107 (setq files (funcall files)))
9108 ((and (symbolp files) (boundp files))
9109 (setq files (symbol-value files))))
9110 (if (stringp files) (setq files (list files)))
9111 (cond
9112 ((eq (car desc) :tag)
9113 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9114 ((eq (car desc) :todo)
9115 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9116 ((eq (car desc) :regexp)
9117 (setq descre (cdr desc)))
9118 ((eq (car desc) :level)
9119 (setq descre (concat "^\\*\\{" (number-to-string
9120 (if org-odd-levels-only
9121 (1- (* 2 (cdr desc)))
9122 (cdr desc)))
9123 "\\}[ \t]")))
9124 ((eq (car desc) :maxlevel)
9125 (setq fast-path-p t)
9126 (setq descre (concat "^\\*\\{1," (number-to-string
9127 (if org-odd-levels-only
9128 (1- (* 2 (cdr desc)))
9129 (cdr desc)))
9130 "\\}[ \t]")))
9131 (t (error "Bad refiling target description %s" desc)))
9132 (while (setq f (pop files))
9133 (with-current-buffer
9134 (if (bufferp f) f (org-get-agenda-file-buffer f))
9135 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
9136 (setq f (and f (expand-file-name f)))
9137 (if (eq org-refile-use-outline-path 'file)
9138 (push (list (file-name-nondirectory f) f nil nil) targets))
9139 (save-excursion
9140 (save-restriction
9141 (widen)
9142 (goto-char (point-min))
9143 (while (re-search-forward descre nil t)
9144 (goto-char (setq pos0 (point-at-bol)))
9145 (catch 'next
9146 (when org-refile-target-verify-function
9147 (save-match-data
9148 (or (funcall org-refile-target-verify-function)
9149 (throw 'next t))))
9150 (when (looking-at org-complex-heading-regexp)
9151 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
9152 txt (org-link-display-format (match-string 4))
9153 re (concat "^" (regexp-quote
9154 (buffer-substring (match-beginning 1)
9155 (match-end 4)))))
9156 (if (match-end 5) (setq re (concat re "[ \t]+"
9157 (regexp-quote
9158 (match-string 5)))))
9159 (setq re (concat re "[ \t]*$"))
9160 (when org-refile-use-outline-path
9161 (setq txt (mapconcat 'org-protect-slash
9162 (append
9163 (if (eq org-refile-use-outline-path 'file)
9164 (list (file-name-nondirectory
9165 (buffer-file-name (buffer-base-buffer))))
9166 (if (eq org-refile-use-outline-path 'full-file-path)
9167 (list (buffer-file-name (buffer-base-buffer)))))
9168 (org-get-outline-path fast-path-p level txt)
9169 (list txt))
9170 "/")))
9171 (push (list txt f re (point)) targets)))
9172 (when (= (point) pos0)
9173 ;; verification function has not moved point
9174 (goto-char (point-at-eol))))))))))
9175 (message "Getting targets...done")
9176 (nreverse targets)))
9178 (defun org-protect-slash (s)
9179 (while (string-match "/" s)
9180 (setq s (replace-match "\\" t t s)))
9183 (defvar org-olpa (make-vector 20 nil))
9185 (defun org-get-outline-path (&optional fastp level heading)
9186 "Return the outline path to the current entry, as a list.
9187 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9188 routine which makes outline path derivations for an entire file,
9189 avoiding backtracing."
9190 (if fastp
9191 (progn
9192 (if (> level 19)
9193 (error "Outline path failure, more than 19 levels."))
9194 (loop for i from level upto 19 do
9195 (aset org-olpa i nil))
9196 (prog1
9197 (delq nil (append org-olpa nil))
9198 (aset org-olpa level heading)))
9199 (let (rtn case-fold-search)
9200 (save-excursion
9201 (save-restriction
9202 (widen)
9203 (while (org-up-heading-safe)
9204 (when (looking-at org-complex-heading-regexp)
9205 (push (org-match-string-no-properties 4) rtn)))
9206 rtn)))))
9208 (defun org-format-outline-path (path &optional width prefix)
9209 "Format the outlie path PATH for display.
9210 Width is the maximum number of characters that is available.
9211 Prefix is a prefix to be included in the returned string,
9212 such as the file name."
9213 (setq width (or width 79))
9214 (if prefix (setq width (- width (length prefix))))
9215 (if (not path)
9216 (or prefix "")
9217 (let* ((nsteps (length path))
9218 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9219 (maxwidth (if (<= total-width width)
9220 10000 ;; everything fits
9221 ;; we need to shorten the level headings
9222 (/ (- width nsteps) nsteps)))
9223 (org-odd-levels-only nil)
9224 (n 0)
9225 (total (1+ (length prefix))))
9226 (setq maxwidth (max maxwidth 10))
9227 (concat prefix
9228 (mapconcat
9229 (lambda (h)
9230 (setq n (1+ n))
9231 (if (and (= n nsteps) (< maxwidth 10000))
9232 (setq maxwidth (- total-width total)))
9233 (if (< (length h) maxwidth)
9234 (progn (setq total (+ total (length h) 1)) h)
9235 (setq h (substring h 0 (- maxwidth 2))
9236 total (+ total maxwidth 1))
9237 (if (string-match "[ \t]+\\'" h)
9238 (setq h (substring h 0 (match-beginning 0))))
9239 (setq h (concat h "..")))
9240 (org-add-props h nil 'face
9241 (nth (% (1- n) org-n-level-faces)
9242 org-level-faces))
9244 path "/")))))
9246 (defun org-display-outline-path (&optional file current)
9247 "Display the current outline path in the echo area."
9248 (interactive "P")
9249 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
9250 (case-fold-search nil)
9251 (path (and (org-mode-p) (org-get-outline-path))))
9252 (if current (setq path (append path
9253 (save-excursion
9254 (org-back-to-heading t)
9255 (if (looking-at org-complex-heading-regexp)
9256 (list (match-string 4)))))))
9257 (message "%s"
9258 (org-format-outline-path
9259 path
9260 (1- (frame-width))
9261 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9263 (defvar org-refile-history nil
9264 "History for refiling operations.")
9266 (defvar org-after-refile-insert-hook nil
9267 "Hook run after `org-refile' has inserted its stuff at the new location.
9268 Note that this is still *before* the stuff will be removed from
9269 the *old* location.")
9271 (defun org-refile (&optional goto default-buffer rfloc)
9272 "Move the entry at point to another heading.
9273 The list of target headings is compiled using the information in
9274 `org-refile-targets', which see. This list is created before each use
9275 and will therefore always be up-to-date.
9277 At the target location, the entry is filed as a subitem of the target heading.
9278 Depending on `org-reverse-note-order', the new subitem will either be the
9279 first or the last subitem.
9281 If there is an active region, all entries in that region will be moved.
9282 However, the region must fulfil the requirement that the first heading
9283 is the first one sets the top-level of the moved text - at most siblings
9284 below it are allowed.
9286 With prefix arg GOTO, the command will only visit the target location,
9287 not actually move anything.
9288 With a double prefix `C-u C-u', go to the location where the last refiling
9289 operation has put the subtree.
9290 With a prefix argument of `2', refile to the running clock.
9292 RFLOC can be a refile location obtained in a different way.
9294 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9295 (interactive "P")
9296 (let* ((cbuf (current-buffer))
9297 (regionp (org-region-active-p))
9298 (region-start (and regionp (region-beginning)))
9299 (region-end (and regionp (region-end)))
9300 (region-length (and regionp (- region-end region-start)))
9301 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9302 pos it nbuf file re level reversed)
9303 (setq last-command nil)
9304 (when regionp
9305 (goto-char region-start)
9306 (or (bolp) (goto-char (point-at-bol)))
9307 (setq region-start (point))
9308 (unless (org-kill-is-subtree-p
9309 (buffer-substring region-start region-end))
9310 (error "The region is not a (sequence of) subtree(s)")))
9311 (if (equal goto '(16))
9312 (org-refile-goto-last-stored)
9313 (when (or
9314 (and (equal goto 2)
9315 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9316 (prog1
9317 (setq it (list (or org-clock-heading "running clock")
9318 (buffer-file-name
9319 (marker-buffer org-clock-hd-marker))
9321 (marker-position org-clock-hd-marker)))
9322 (setq goto nil)))
9323 (setq it (or rfloc
9324 (save-excursion
9325 (org-refile-get-location
9326 (if goto "Goto: " "Refile to: ") default-buffer
9327 org-refile-allow-creating-parent-nodes)))))
9328 (setq file (nth 1 it)
9329 re (nth 2 it)
9330 pos (nth 3 it))
9331 (if (and (not goto)
9333 (equal (buffer-file-name) file)
9334 (if regionp
9335 (and (>= pos region-start)
9336 (<= pos region-end))
9337 (and (>= pos (point))
9338 (< pos (save-excursion
9339 (org-end-of-subtree t t))))))
9340 (error "Cannot refile to position inside the tree or region"))
9342 (setq nbuf (or (find-buffer-visiting file)
9343 (find-file-noselect file)))
9344 (if goto
9345 (progn
9346 (switch-to-buffer nbuf)
9347 (goto-char pos)
9348 (org-show-context 'org-goto))
9349 (if regionp
9350 (progn
9351 (org-kill-new (buffer-substring region-start region-end))
9352 (org-save-markers-in-region region-start region-end))
9353 (org-copy-subtree 1 nil t))
9354 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9355 (find-file-noselect file)))
9356 (setq reversed (org-notes-order-reversed-p))
9357 (save-excursion
9358 (save-restriction
9359 (widen)
9360 (if pos
9361 (progn
9362 (goto-char pos)
9363 (looking-at outline-regexp)
9364 (setq level (org-get-valid-level (funcall outline-level) 1))
9365 (goto-char
9366 (if reversed
9367 (or (outline-next-heading) (point-max))
9368 (or (save-excursion (org-get-next-sibling))
9369 (org-end-of-subtree t t)
9370 (point-max)))))
9371 (setq level 1)
9372 (if (not reversed)
9373 (goto-char (point-max))
9374 (goto-char (point-min))
9375 (or (outline-next-heading) (goto-char (point-max)))))
9376 (if (not (bolp)) (newline))
9377 (bookmark-set "org-refile-last-stored")
9378 (org-paste-subtree level)
9379 (if (fboundp 'deactivate-mark) (deactivate-mark))
9380 (run-hooks 'org-after-refile-insert-hook))))
9381 (if regionp
9382 (delete-region (point) (+ (point) region-length))
9383 (org-cut-subtree))
9384 (when (featurep 'org-inlinetask)
9385 (org-inlinetask-remove-END-maybe))
9386 (setq org-markers-to-move nil)
9387 (message "Refiled to \"%s\"" (car it))))))
9388 (org-reveal))
9390 (defun org-refile-goto-last-stored ()
9391 "Go to the location where the last refile was stored."
9392 (interactive)
9393 (bookmark-jump "org-refile-last-stored")
9394 (message "This is the location of the last refile"))
9396 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9397 "Prompt the user for a refile location, using PROMPT."
9398 (let ((org-refile-targets org-refile-targets)
9399 (org-refile-use-outline-path org-refile-use-outline-path))
9400 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9401 (unless org-refile-target-table
9402 (error "No refile targets"))
9403 (let* ((cbuf (current-buffer))
9404 (partial-completion-mode nil)
9405 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9406 (cfunc (if (and org-refile-use-outline-path
9407 org-outline-path-complete-in-steps)
9408 'org-olpath-completing-read
9409 'org-icompleting-read))
9410 (extra (if org-refile-use-outline-path "/" ""))
9411 (filename (and cfn (expand-file-name cfn)))
9412 (tbl (mapcar
9413 (lambda (x)
9414 (if (and (not (member org-refile-use-outline-path
9415 '(file full-file-path)))
9416 (not (equal filename (nth 1 x))))
9417 (cons (concat (car x) extra " ("
9418 (file-name-nondirectory (nth 1 x)) ")")
9419 (cdr x))
9420 (cons (concat (car x) extra) (cdr x))))
9421 org-refile-target-table))
9422 (completion-ignore-case t)
9423 pa answ parent-target child parent old-hist)
9424 (setq old-hist org-refile-history)
9425 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9426 nil 'org-refile-history))
9427 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9428 (if pa
9429 (progn
9430 (when (or (not org-refile-history)
9431 (not (eq old-hist org-refile-history))
9432 (not (equal (car pa) (car org-refile-history))))
9433 (setq org-refile-history
9434 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9435 org-refile-history
9436 (cdr org-refile-history))))
9437 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9438 (pop org-refile-history)))
9440 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9441 (setq parent (match-string 1 answ)
9442 child (match-string 2 answ))
9443 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
9444 (when (and parent-target
9445 (or (eq new-nodes t)
9446 (and (eq new-nodes 'confirm)
9447 (y-or-n-p (format "Create new node \"%s\"? " child)))))
9448 (org-refile-new-child parent-target child))))))
9450 (defun org-refile-new-child (parent-target child)
9451 "Use refile target PARENT-TARGET to add new CHILD below it."
9452 (unless parent-target
9453 (error "Cannot find parent for new node"))
9454 (let ((file (nth 1 parent-target))
9455 (pos (nth 3 parent-target))
9456 level)
9457 (with-current-buffer (or (find-buffer-visiting file)
9458 (find-file-noselect file))
9459 (save-excursion
9460 (save-restriction
9461 (widen)
9462 (if pos
9463 (goto-char pos)
9464 (goto-char (point-max))
9465 (if (not (bolp)) (newline)))
9466 (when (looking-at outline-regexp)
9467 (setq level (funcall outline-level))
9468 (org-end-of-subtree t t))
9469 (org-back-over-empty-lines)
9470 (insert "\n" (make-string
9471 (if pos (org-get-valid-level level 1) 1) ?*)
9472 " " child "\n")
9473 (beginning-of-line 0)
9474 (list (concat (car parent-target) "/" child) file "" (point)))))))
9476 (defun org-olpath-completing-read (prompt collection &rest args)
9477 "Read an outline path like a file name."
9478 (let ((thetable collection)
9479 (org-completion-use-ido nil) ; does not work with ido.
9480 (org-completion-use-iswitchb nil)) ; or iswitchb
9481 (apply
9482 'org-icompleting-read prompt
9483 (lambda (string predicate &optional flag)
9484 (let (rtn r f (l (length string)))
9485 (cond
9486 ((eq flag nil)
9487 ;; try completion
9488 (try-completion string thetable))
9489 ((eq flag t)
9490 ;; all-completions
9491 (setq rtn (all-completions string thetable predicate))
9492 (mapcar
9493 (lambda (x)
9494 (setq r (substring x l))
9495 (if (string-match " ([^)]*)$" x)
9496 (setq f (match-string 0 x))
9497 (setq f ""))
9498 (if (string-match "/" r)
9499 (concat string (substring r 0 (match-end 0)) f)
9501 rtn))
9502 ((eq flag 'lambda)
9503 ;; exact match?
9504 (assoc string thetable)))
9506 args)))
9508 ;;;; Dynamic blocks
9510 (defun org-find-dblock (name)
9511 "Find the first dynamic block with name NAME in the buffer.
9512 If not found, stay at current position and return nil."
9513 (let (pos)
9514 (save-excursion
9515 (goto-char (point-min))
9516 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9517 nil t)
9518 (match-beginning 0))))
9519 (if pos (goto-char pos))
9520 pos))
9522 (defconst org-dblock-start-re
9523 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9524 "Matches the start line of a dynamic block, with parameters.")
9526 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9527 "Matches the end of a dynamic block.")
9529 (defun org-create-dblock (plist)
9530 "Create a dynamic block section, with parameters taken from PLIST.
9531 PLIST must contain a :name entry which is used as name of the block."
9532 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9533 (end-of-line 1)
9534 (newline))
9535 (let ((col (current-column))
9536 (name (plist-get plist :name)))
9537 (insert "#+BEGIN: " name)
9538 (while plist
9539 (if (eq (car plist) :name)
9540 (setq plist (cddr plist))
9541 (insert " " (prin1-to-string (pop plist)))))
9542 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9543 (beginning-of-line -2)))
9545 (defun org-prepare-dblock ()
9546 "Prepare dynamic block for refresh.
9547 This empties the block, puts the cursor at the insert position and returns
9548 the property list including an extra property :name with the block name."
9549 (unless (looking-at org-dblock-start-re)
9550 (error "Not at a dynamic block"))
9551 (let* ((begdel (1+ (match-end 0)))
9552 (name (org-no-properties (match-string 1)))
9553 (params (append (list :name name)
9554 (read (concat "(" (match-string 3) ")")))))
9555 (save-excursion
9556 (beginning-of-line 1)
9557 (skip-chars-forward " \t")
9558 (setq params (plist-put params :indentation-column (current-column))))
9559 (unless (re-search-forward org-dblock-end-re nil t)
9560 (error "Dynamic block not terminated"))
9561 (setq params
9562 (append params
9563 (list :content (buffer-substring
9564 begdel (match-beginning 0)))))
9565 (delete-region begdel (match-beginning 0))
9566 (goto-char begdel)
9567 (open-line 1)
9568 params))
9570 (defun org-map-dblocks (&optional command)
9571 "Apply COMMAND to all dynamic blocks in the current buffer.
9572 If COMMAND is not given, use `org-update-dblock'."
9573 (let ((cmd (or command 'org-update-dblock))
9574 pos)
9575 (save-excursion
9576 (goto-char (point-min))
9577 (while (re-search-forward org-dblock-start-re nil t)
9578 (goto-char (setq pos (match-beginning 0)))
9579 (condition-case nil
9580 (funcall cmd)
9581 (error (message "Error during update of dynamic block")))
9582 (goto-char pos)
9583 (unless (re-search-forward org-dblock-end-re nil t)
9584 (error "Dynamic block not terminated"))))))
9586 (defun org-dblock-update (&optional arg)
9587 "User command for updating dynamic blocks.
9588 Update the dynamic block at point. With prefix ARG, update all dynamic
9589 blocks in the buffer."
9590 (interactive "P")
9591 (if arg
9592 (org-update-all-dblocks)
9593 (or (looking-at org-dblock-start-re)
9594 (org-beginning-of-dblock))
9595 (org-update-dblock)))
9597 (defun org-update-dblock ()
9598 "Update the dynamic block at point
9599 This means to empty the block, parse for parameters and then call
9600 the correct writing function."
9601 (save-window-excursion
9602 (let* ((pos (point))
9603 (line (org-current-line))
9604 (params (org-prepare-dblock))
9605 (name (plist-get params :name))
9606 (indent (plist-get params :indentation-column))
9607 (cmd (intern (concat "org-dblock-write:" name))))
9608 (message "Updating dynamic block `%s' at line %d..." name line)
9609 (funcall cmd params)
9610 (message "Updating dynamic block `%s' at line %d...done" name line)
9611 (goto-char pos)
9612 (when (and indent (> indent 0))
9613 (setq indent (make-string indent ?\ ))
9614 (save-excursion
9615 (org-beginning-of-dblock)
9616 (forward-line 1)
9617 (while (not (looking-at org-dblock-end-re))
9618 (insert indent)
9619 (beginning-of-line 2))
9620 (when (looking-at org-dblock-end-re)
9621 (and (looking-at "[ \t]+")
9622 (replace-match ""))
9623 (insert indent)))))))
9625 (defun org-beginning-of-dblock ()
9626 "Find the beginning of the dynamic block at point.
9627 Error if there is no such block at point."
9628 (let ((pos (point))
9629 beg)
9630 (end-of-line 1)
9631 (if (and (re-search-backward org-dblock-start-re nil t)
9632 (setq beg (match-beginning 0))
9633 (re-search-forward org-dblock-end-re nil t)
9634 (> (match-end 0) pos))
9635 (goto-char beg)
9636 (goto-char pos)
9637 (error "Not in a dynamic block"))))
9639 (defun org-update-all-dblocks ()
9640 "Update all dynamic blocks in the buffer.
9641 This function can be used in a hook."
9642 (when (org-mode-p)
9643 (org-map-dblocks 'org-update-dblock)))
9646 ;;;; Completion
9648 (defconst org-additional-option-like-keywords
9649 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9650 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9651 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
9652 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
9653 "BEGIN:" "END:"
9654 "ORGTBL" "TBLFM:" "TBLNAME:"
9655 "BEGIN_EXAMPLE" "END_EXAMPLE"
9656 "BEGIN_QUOTE" "END_QUOTE"
9657 "BEGIN_VERSE" "END_VERSE"
9658 "BEGIN_CENTER" "END_CENTER"
9659 "BEGIN_SRC" "END_SRC"
9660 "CATEGORY" "COLUMNS"
9661 "CAPTION" "LABEL"
9662 "SETUPFILE"
9663 "BIND"
9664 "MACRO"))
9666 (defcustom org-structure-template-alist
9668 ("s" "#+begin_src ?\n\n#+end_src"
9669 "<src lang=\"?\">\n\n</src>")
9670 ("e" "#+begin_example\n?\n#+end_example"
9671 "<example>\n?\n</example>")
9672 ("q" "#+begin_quote\n?\n#+end_quote"
9673 "<quote>\n?\n</quote>")
9674 ("v" "#+begin_verse\n?\n#+end_verse"
9675 "<verse>\n?\n/verse>")
9676 ("c" "#+begin_center\n?\n#+end_center"
9677 "<center>\n?\n/center>")
9678 ("l" "#+begin_latex\n?\n#+end_latex"
9679 "<literal style=\"latex\">\n?\n</literal>")
9680 ("L" "#+latex: "
9681 "<literal style=\"latex\">?</literal>")
9682 ("h" "#+begin_html\n?\n#+end_html"
9683 "<literal style=\"html\">\n?\n</literal>")
9684 ("H" "#+html: "
9685 "<literal style=\"html\">?</literal>")
9686 ("a" "#+begin_ascii\n?\n#+end_ascii")
9687 ("A" "#+ascii: ")
9688 ("i" "#+include %file ?"
9689 "<include file=%file markup=\"?\">")
9691 "Structure completion elements.
9692 This is a list of abbreviation keys and values. The value gets inserted
9693 it you type @samp{.} followed by the key and then the completion key,
9694 usually `M-TAB'. %file will be replaced by a file name after prompting
9695 for the file using completion.
9696 There are two templates for each key, the first uses the original Org syntax,
9697 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9698 the default when the /org-mtags.el/ module has been loaded. See also the
9699 variable `org-mtags-prefer-muse-templates'.
9700 This is an experimental feature, it is undecided if it is going to stay in."
9701 :group 'org-completion
9702 :type '(repeat
9703 (string :tag "Key")
9704 (string :tag "Template")
9705 (string :tag "Muse Template")))
9707 (defun org-try-structure-completion ()
9708 "Try to complete a structure template before point.
9709 This looks for strings like \"<e\" on an otherwise empty line and
9710 expands them."
9711 (let ((l (buffer-substring (point-at-bol) (point)))
9713 (when (and (looking-at "[ \t]*$")
9714 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9715 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9716 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9717 (match-beginning 1)) a)
9718 t)))
9720 (defun org-complete-expand-structure-template (start cell)
9721 "Expand a structure template."
9722 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9723 (rpl (nth (if musep 2 1) cell))
9724 (ind ""))
9725 (delete-region start (point))
9726 (when (string-match "\\`#\\+" rpl)
9727 (cond
9728 ((bolp))
9729 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9730 (setq ind (buffer-substring (point-at-bol) (point))))
9731 (t (newline))))
9732 (setq start (point))
9733 (if (string-match "%file" rpl)
9734 (setq rpl (replace-match
9735 (concat
9736 "\""
9737 (save-match-data
9738 (abbreviate-file-name (read-file-name "Include file: ")))
9739 "\"")
9740 t t rpl)))
9741 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9742 (concat "\n" ind)))
9743 (insert rpl)
9744 (if (re-search-backward "\\?" start t) (delete-char 1))))
9747 (defun org-complete (&optional arg)
9748 "Perform completion on word at point.
9749 At the beginning of a headline, this completes TODO keywords as given in
9750 `org-todo-keywords'.
9751 If the current word is preceded by a backslash, completes the TeX symbols
9752 that are supported for HTML support.
9753 If the current word is preceded by \"#+\", completes special words for
9754 setting file options.
9755 In the line after \"#+STARTUP:, complete valid keywords.\"
9756 At all other locations, this simply calls the value of
9757 `org-completion-fallback-command'."
9758 (interactive "P")
9759 (org-without-partial-completion
9760 (catch 'exit
9761 (let* ((a nil)
9762 (end (point))
9763 (beg1 (save-excursion
9764 (skip-chars-backward (org-re "[:alnum:]_@"))
9765 (point)))
9766 (beg (save-excursion
9767 (skip-chars-backward "a-zA-Z0-9_:$")
9768 (point)))
9769 (confirm (lambda (x) (stringp (car x))))
9770 (searchhead (equal (char-before beg) ?*))
9771 (struct
9772 (when (and (member (char-before beg1) '(?. ?<))
9773 (setq a (assoc (buffer-substring beg1 (point))
9774 org-structure-template-alist)))
9775 (org-complete-expand-structure-template (1- beg1) a)
9776 (throw 'exit t)))
9777 (tag (and (equal (char-before beg1) ?:)
9778 (equal (char-after (point-at-bol)) ?*)))
9779 (prop (and (equal (char-before beg1) ?:)
9780 (not (equal (char-after (point-at-bol)) ?*))))
9781 (texp (equal (char-before beg) ?\\))
9782 (link (equal (char-before beg) ?\[))
9783 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9784 beg)
9785 "#+"))
9786 (startup (string-match "^#\\+STARTUP:.*"
9787 (buffer-substring (point-at-bol) (point))))
9788 (completion-ignore-case opt)
9789 (type nil)
9790 (tbl nil)
9791 (table (cond
9792 (opt
9793 (setq type :opt)
9794 (require 'org-exp)
9795 (append
9796 (delq nil
9797 (mapcar
9798 (lambda (x)
9799 (if (string-match
9800 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9801 (cons (match-string 2 x)
9802 (match-string 1 x))))
9803 (org-split-string (org-get-current-options) "\n")))
9804 (mapcar 'list org-additional-option-like-keywords)))
9805 (startup
9806 (setq type :startup)
9807 org-startup-options)
9808 (link (append org-link-abbrev-alist-local
9809 org-link-abbrev-alist))
9810 (texp
9811 (setq type :tex)
9812 org-html-entities)
9813 ((string-match "\\`\\*+[ \t]+\\'"
9814 (buffer-substring (point-at-bol) beg))
9815 (setq type :todo)
9816 (mapcar 'list org-todo-keywords-1))
9817 (searchhead
9818 (setq type :searchhead)
9819 (save-excursion
9820 (goto-char (point-min))
9821 (while (re-search-forward org-todo-line-regexp nil t)
9822 (push (list
9823 (org-make-org-heading-search-string
9824 (match-string 3) t))
9825 tbl)))
9826 tbl)
9827 (tag (setq type :tag beg beg1)
9828 (or org-tag-alist (org-get-buffer-tags)))
9829 (prop (setq type :prop beg beg1)
9830 (mapcar 'list (org-buffer-property-keys nil t t)))
9831 (t (progn
9832 (call-interactively org-completion-fallback-command)
9833 (throw 'exit nil)))))
9834 (pattern (buffer-substring-no-properties beg end))
9835 (completion (try-completion pattern table confirm)))
9836 (cond ((eq completion t)
9837 (if (not (assoc (upcase pattern) table))
9838 (message "Already complete")
9839 (if (and (equal type :opt)
9840 (not (member (car (assoc (upcase pattern) table))
9841 org-additional-option-like-keywords)))
9842 (insert (substring (cdr (assoc (upcase pattern) table))
9843 (length pattern)))
9844 (if (memq type '(:tag :prop)) (insert ":")))))
9845 ((null completion)
9846 (message "Can't find completion for \"%s\"" pattern)
9847 (ding))
9848 ((not (string= pattern completion))
9849 (delete-region beg end)
9850 (if (string-match " +$" completion)
9851 (setq completion (replace-match "" t t completion)))
9852 (insert completion)
9853 (if (get-buffer-window "*Completions*")
9854 (delete-window (get-buffer-window "*Completions*")))
9855 (if (assoc completion table)
9856 (if (eq type :todo) (insert " ")
9857 (if (memq type '(:tag :prop)) (insert ":"))))
9858 (if (and (equal type :opt) (assoc completion table))
9859 (message "%s" (substitute-command-keys
9860 "Press \\[org-complete] again to insert example settings"))))
9862 (message "Making completion list...")
9863 (let ((list (sort (all-completions pattern table confirm)
9864 'string<)))
9865 (with-output-to-temp-buffer "*Completions*"
9866 (condition-case nil
9867 ;; Protection needed for XEmacs and emacs 21
9868 (display-completion-list list pattern)
9869 (error (display-completion-list list)))))
9870 (message "Making completion list...%s" "done")))))))
9872 ;;;; TODO, DEADLINE, Comments
9874 (defun org-toggle-comment ()
9875 "Change the COMMENT state of an entry."
9876 (interactive)
9877 (save-excursion
9878 (org-back-to-heading)
9879 (let (case-fold-search)
9880 (if (looking-at (concat outline-regexp
9881 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9882 (replace-match "" t t nil 1)
9883 (if (looking-at outline-regexp)
9884 (progn
9885 (goto-char (match-end 0))
9886 (insert org-comment-string " ")))))))
9888 (defvar org-last-todo-state-is-todo nil
9889 "This is non-nil when the last TODO state change led to a TODO state.
9890 If the last change removed the TODO tag or switched to DONE, then
9891 this is nil.")
9893 (defvar org-setting-tags nil) ; dynamically skipped
9895 (defun org-parse-local-options (string var)
9896 "Parse STRING for startup setting relevant for variable VAR."
9897 (let ((rtn (symbol-value var))
9898 e opts)
9899 (save-match-data
9900 (if (or (not string) (not (string-match "\\S-" string)))
9902 (setq opts (delq nil (mapcar (lambda (x)
9903 (setq e (assoc x org-startup-options))
9904 (if (eq (nth 1 e) var) e nil))
9905 (org-split-string string "[ \t]+"))))
9906 (if (not opts)
9908 (setq rtn nil)
9909 (while (setq e (pop opts))
9910 (if (not (nth 3 e))
9911 (setq rtn (nth 2 e))
9912 (if (not (listp rtn)) (setq rtn nil))
9913 (push (nth 2 e) rtn)))
9914 rtn)))))
9916 (defvar org-todo-setup-filter-hook nil
9917 "Hook for functions that pre-filter todo specs.
9919 Each function takes a todo spec and returns either `nil' or the spec
9920 transformed into canonical form." )
9922 (defvar org-todo-get-default-hook nil
9923 "Hook for functions that get a default item for todo.
9925 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9926 `nil' or a string to be used for the todo mark." )
9928 (defvar org-agenda-headline-snapshot-before-repeat)
9930 (defun org-todo (&optional arg)
9931 "Change the TODO state of an item.
9932 The state of an item is given by a keyword at the start of the heading,
9933 like
9934 *** TODO Write paper
9935 *** DONE Call mom
9937 The different keywords are specified in the variable `org-todo-keywords'.
9938 By default the available states are \"TODO\" and \"DONE\".
9939 So for this example: when the item starts with TODO, it is changed to DONE.
9940 When it starts with DONE, the DONE is removed. And when neither TODO nor
9941 DONE are present, add TODO at the beginning of the heading.
9943 With C-u prefix arg, use completion to determine the new state.
9944 With numeric prefix arg, switch to that state.
9945 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9946 With a triple C-u prefix, circumvent any state blocking.
9948 For calling through lisp, arg is also interpreted in the following way:
9949 'none -> empty state
9950 \"\"(empty string) -> switch to empty state
9951 'done -> switch to DONE
9952 'nextset -> switch to the next set of keywords
9953 'previousset -> switch to the previous set of keywords
9954 \"WAITING\" -> switch to the specified keyword, but only if it
9955 really is a member of `org-todo-keywords'."
9956 (interactive "P")
9957 (if (equal arg '(16)) (setq arg 'nextset))
9958 (let ((org-blocker-hook org-blocker-hook)
9959 (case-fold-search nil))
9960 (when (equal arg '(64))
9961 (setq arg nil org-blocker-hook nil))
9962 (when (and org-blocker-hook
9963 (or org-inhibit-blocking
9964 (org-entry-get nil "NOBLOCKING")))
9965 (setq org-blocker-hook nil))
9966 (save-excursion
9967 (catch 'exit
9968 (org-back-to-heading t)
9969 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9970 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9971 (looking-at " *"))
9972 (let* ((match-data (match-data))
9973 (startpos (point-at-bol))
9974 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9975 (org-log-done org-log-done)
9976 (org-log-repeat org-log-repeat)
9977 (org-todo-log-states org-todo-log-states)
9978 (this (match-string 1))
9979 (hl-pos (match-beginning 0))
9980 (head (org-get-todo-sequence-head this))
9981 (ass (assoc head org-todo-kwd-alist))
9982 (interpret (nth 1 ass))
9983 (done-word (nth 3 ass))
9984 (final-done-word (nth 4 ass))
9985 (last-state (or this ""))
9986 (completion-ignore-case t)
9987 (member (member this org-todo-keywords-1))
9988 (tail (cdr member))
9989 (state (cond
9990 ((and org-todo-key-trigger
9991 (or (and (equal arg '(4))
9992 (eq org-use-fast-todo-selection 'prefix))
9993 (and (not arg) org-use-fast-todo-selection
9994 (not (eq org-use-fast-todo-selection
9995 'prefix)))))
9996 ;; Use fast selection
9997 (org-fast-todo-selection))
9998 ((and (equal arg '(4))
9999 (or (not org-use-fast-todo-selection)
10000 (not org-todo-key-trigger)))
10001 ;; Read a state with completion
10002 (org-icompleting-read
10003 "State: " (mapcar (lambda(x) (list x))
10004 org-todo-keywords-1)
10005 nil t))
10006 ((eq arg 'right)
10007 (if this
10008 (if tail (car tail) nil)
10009 (car org-todo-keywords-1)))
10010 ((eq arg 'left)
10011 (if (equal member org-todo-keywords-1)
10013 (if this
10014 (nth (- (length org-todo-keywords-1)
10015 (length tail) 2)
10016 org-todo-keywords-1)
10017 (org-last org-todo-keywords-1))))
10018 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10019 (setq arg nil))) ; hack to fall back to cycling
10020 (arg
10021 ;; user or caller requests a specific state
10022 (cond
10023 ((equal arg "") nil)
10024 ((eq arg 'none) nil)
10025 ((eq arg 'done) (or done-word (car org-done-keywords)))
10026 ((eq arg 'nextset)
10027 (or (car (cdr (member head org-todo-heads)))
10028 (car org-todo-heads)))
10029 ((eq arg 'previousset)
10030 (let ((org-todo-heads (reverse org-todo-heads)))
10031 (or (car (cdr (member head org-todo-heads)))
10032 (car org-todo-heads))))
10033 ((car (member arg org-todo-keywords-1)))
10034 ((stringp arg)
10035 (error "State `%s' not valid in this file" arg))
10036 ((nth (1- (prefix-numeric-value arg))
10037 org-todo-keywords-1))))
10038 ((null member) (or head (car org-todo-keywords-1)))
10039 ((equal this final-done-word) nil) ;; -> make empty
10040 ((null tail) nil) ;; -> first entry
10041 ((memq interpret '(type priority))
10042 (if (eq this-command last-command)
10043 (car tail)
10044 (if (> (length tail) 0)
10045 (or done-word (car org-done-keywords))
10046 nil)))
10048 (car tail))))
10049 (state (or
10050 (run-hook-with-args-until-success
10051 'org-todo-get-default-hook state last-state)
10052 state))
10053 (next (if state (concat " " state " ") " "))
10054 (change-plist (list :type 'todo-state-change :from this :to state
10055 :position startpos))
10056 dolog now-done-p)
10057 (when org-blocker-hook
10058 (setq org-last-todo-state-is-todo
10059 (not (member this org-done-keywords)))
10060 (unless (save-excursion
10061 (save-match-data
10062 (run-hook-with-args-until-failure
10063 'org-blocker-hook change-plist)))
10064 (if (interactive-p)
10065 (error "TODO state change from %s to %s blocked" this state)
10066 ;; fail silently
10067 (message "TODO state change from %s to %s blocked" this state)
10068 (throw 'exit nil))))
10069 (store-match-data match-data)
10070 (replace-match next t t)
10071 (unless (pos-visible-in-window-p hl-pos)
10072 (message "TODO state changed to %s" (org-trim next)))
10073 (unless head
10074 (setq head (org-get-todo-sequence-head state)
10075 ass (assoc head org-todo-kwd-alist)
10076 interpret (nth 1 ass)
10077 done-word (nth 3 ass)
10078 final-done-word (nth 4 ass)))
10079 (when (memq arg '(nextset previousset))
10080 (message "Keyword-Set %d/%d: %s"
10081 (- (length org-todo-sets) -1
10082 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10083 (length org-todo-sets)
10084 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10085 (setq org-last-todo-state-is-todo
10086 (not (member state org-done-keywords)))
10087 (setq now-done-p (and (member state org-done-keywords)
10088 (not (member this org-done-keywords))))
10089 (and logging (org-local-logging logging))
10090 (when (and (or org-todo-log-states org-log-done)
10091 (not (eq org-inhibit-logging t))
10092 (not (memq arg '(nextset previousset))))
10093 ;; we need to look at recording a time and note
10094 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10095 (nth 2 (assoc this org-todo-log-states))))
10096 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10097 (setq dolog 'time))
10098 (when (and state
10099 (member state org-not-done-keywords)
10100 (not (member this org-not-done-keywords)))
10101 ;; This is now a todo state and was not one before
10102 ;; If there was a CLOSED time stamp, get rid of it.
10103 (org-add-planning-info nil nil 'closed))
10104 (when (and now-done-p org-log-done)
10105 ;; It is now done, and it was not done before
10106 (org-add-planning-info 'closed (org-current-time))
10107 (if (and (not dolog) (eq 'note org-log-done))
10108 (org-add-log-setup 'done state this 'findpos 'note)))
10109 (when (and state dolog)
10110 ;; This is a non-nil state, and we need to log it
10111 (org-add-log-setup 'state state this 'findpos dolog)))
10112 ;; Fixup tag positioning
10113 (org-todo-trigger-tag-changes state)
10114 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10115 (when org-provide-todo-statistics
10116 (org-update-parent-todo-statistics))
10117 (run-hooks 'org-after-todo-state-change-hook)
10118 (if (and arg (not (member state org-done-keywords)))
10119 (setq head (org-get-todo-sequence-head state)))
10120 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10121 ;; Do we need to trigger a repeat?
10122 (when now-done-p
10123 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10124 ;; This is for the agenda, take a snapshot of the headline.
10125 (save-match-data
10126 (setq org-agenda-headline-snapshot-before-repeat
10127 (org-get-heading))))
10128 (org-auto-repeat-maybe state))
10129 ;; Fixup cursor location if close to the keyword
10130 (if (and (outline-on-heading-p)
10131 (not (bolp))
10132 (save-excursion (beginning-of-line 1)
10133 (looking-at org-todo-line-regexp))
10134 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10135 (progn
10136 (goto-char (or (match-end 2) (match-end 1)))
10137 (and (looking-at " ") (just-one-space))))
10138 (when org-trigger-hook
10139 (save-excursion
10140 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10142 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10143 "Block turning an entry into a TODO, using the hierarchy.
10144 This checks whether the current task should be blocked from state
10145 changes. Such blocking occurs when:
10147 1. The task has children which are not all in a completed state.
10149 2. A task has a parent with the property :ORDERED:, and there
10150 are siblings prior to the current task with incomplete
10151 status.
10153 3. The parent of the task is blocked because it has siblings that should
10154 be done first, or is child of a block grandparent TODO entry."
10156 (catch 'dont-block
10157 ;; If this is not a todo state change, or if this entry is already DONE,
10158 ;; do not block
10159 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10160 (member (plist-get change-plist :from)
10161 (cons 'done org-done-keywords))
10162 (member (plist-get change-plist :to)
10163 (cons 'todo org-not-done-keywords))
10164 (not (plist-get change-plist :to)))
10165 (throw 'dont-block t))
10166 ;; If this task has children, and any are undone, it's blocked
10167 (save-excursion
10168 (org-back-to-heading t)
10169 (let ((this-level (funcall outline-level)))
10170 (outline-next-heading)
10171 (let ((child-level (funcall outline-level)))
10172 (while (and (not (eobp))
10173 (> child-level this-level))
10174 ;; this todo has children, check whether they are all
10175 ;; completed
10176 (if (and (not (org-entry-is-done-p))
10177 (org-entry-is-todo-p))
10178 (throw 'dont-block nil))
10179 (outline-next-heading)
10180 (setq child-level (funcall outline-level))))))
10181 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10182 ;; any previous siblings are undone, it's blocked
10183 (save-excursion
10184 (org-back-to-heading t)
10185 (let* ((pos (point))
10186 (parent-pos (and (org-up-heading-safe) (point))))
10187 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10188 (when (and (org-entry-get (point) "ORDERED")
10189 (forward-line 1)
10190 (re-search-forward org-not-done-heading-regexp pos t))
10191 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10192 ;; Search further up the hierarchy, to see if an anchestor is blocked
10193 (while t
10194 (goto-char parent-pos)
10195 (if (not (looking-at org-not-done-heading-regexp))
10196 (throw 'dont-block t)) ; do not block, parent is not a TODO
10197 (setq pos (point))
10198 (setq parent-pos (and (org-up-heading-safe) (point)))
10199 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10200 (when (and (org-entry-get (point) "ORDERED")
10201 (forward-line 1)
10202 (re-search-forward org-not-done-heading-regexp pos t))
10203 (throw 'dont-block nil))))))) ; block, older sibling not done.
10205 (defcustom org-track-ordered-property-with-tag nil
10206 "Should the ORDERED property also be shown as a tag?
10207 The ORDERED property decides if an entry should require subtasks to be
10208 completed in sequence. Since a property is not very visible, setting
10209 this option means that toggling the ORDERED property with the command
10210 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10211 not relevant for the behavior, but it makes things more visible.
10213 Note that toggling the tag with tags commands will not change the property
10214 and therefore not influence behavior!
10216 This can be t, meaning the tag ORDERED should be used, It can also be a
10217 string to select a different tag for this task."
10218 :group 'org-todo
10219 :type '(choice
10220 (const :tag "No tracking" nil)
10221 (const :tag "Track with ORDERED tag" t)
10222 (string :tag "Use other tag")))
10224 (defun org-toggle-ordered-property ()
10225 "Toggle the ORDERED property of the current entry.
10226 For better visibility, you can track the value of this property with a tag.
10227 See variable `org-track-ordered-property-with-tag'."
10228 (interactive)
10229 (let* ((t1 org-track-ordered-property-with-tag)
10230 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10231 (save-excursion
10232 (org-back-to-heading)
10233 (if (org-entry-get nil "ORDERED")
10234 (progn
10235 (org-delete-property "ORDERED")
10236 (and tag (org-toggle-tag tag 'off))
10237 (message "Subtasks can be completed in arbitrary order"))
10238 (org-entry-put nil "ORDERED" "t")
10239 (and tag (org-toggle-tag tag 'on))
10240 (message "Subtasks must be completed in sequence")))))
10242 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10243 (defun org-block-todo-from-checkboxes (change-plist)
10244 "Block turning an entry into a TODO, using checkboxes.
10245 This checks whether the current task should be blocked from state
10246 changes because there are unchecked boxes in this entry."
10247 (catch 'dont-block
10248 ;; If this is not a todo state change, or if this entry is already DONE,
10249 ;; do not block
10250 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10251 (member (plist-get change-plist :from)
10252 (cons 'done org-done-keywords))
10253 (member (plist-get change-plist :to)
10254 (cons 'todo org-not-done-keywords))
10255 (not (plist-get change-plist :to)))
10256 (throw 'dont-block t))
10257 ;; If this task has checkboxes that are not checked, it's blocked
10258 (save-excursion
10259 (org-back-to-heading t)
10260 (let ((beg (point)) end)
10261 (outline-next-heading)
10262 (setq end (point))
10263 (goto-char beg)
10264 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10265 end t)
10266 (progn
10267 (if (boundp 'org-blocked-by-checkboxes)
10268 (setq org-blocked-by-checkboxes t))
10269 (throw 'dont-block nil)))))
10270 t)) ; do not block
10272 (defun org-entry-blocked-p ()
10273 "Is the current entry blocked?"
10274 (if (org-entry-get nil "NOBLOCKING")
10275 nil ;; Never block this entry
10276 (not
10277 (run-hook-with-args-until-failure
10278 'org-blocker-hook
10279 (list :type 'todo-state-change
10280 :position (point)
10281 :from 'todo
10282 :to 'done)))))
10284 (defun org-update-statistics-cookies (all)
10285 "Update the statistics cookie, either from TODO or from checkboxes.
10286 This should be called with the cursor in a line with a statistics cookie."
10287 (interactive "P")
10288 (if all
10289 (progn
10290 (org-update-checkbox-count 'all)
10291 (org-map-entries 'org-update-parent-todo-statistics))
10292 (if (not (org-on-heading-p))
10293 (org-update-checkbox-count)
10294 (let ((pos (move-marker (make-marker) (point)))
10295 end l1 l2)
10296 (ignore-errors (org-back-to-heading t))
10297 (if (not (org-on-heading-p))
10298 (org-update-checkbox-count)
10299 (setq l1 (org-outline-level))
10300 (setq end (save-excursion
10301 (outline-next-heading)
10302 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10303 (point)))
10304 (if (and (save-excursion (re-search-forward
10305 "^[ \t]*[-+*] \\[[- X]\\]" end t))
10306 (not (save-excursion (re-search-forward
10307 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10308 (org-update-checkbox-count)
10309 (if (and l2 (> l2 l1))
10310 (progn
10311 (goto-char end)
10312 (org-update-parent-todo-statistics))
10313 (goto-char pos)
10314 (beginning-of-line 1)
10315 (while (re-search-forward
10316 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
10317 (point-at-eol) t)
10318 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
10319 (goto-char pos)
10320 (move-marker pos nil)))))
10322 (defvar org-entry-property-inherited-from) ;; defined below
10323 (defun org-update-parent-todo-statistics ()
10324 "Update any statistics cookie in the parent of the current headline.
10325 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10326 the entire subtree and this will travel up the hierarchy and update
10327 statistics everywhere."
10328 (interactive)
10329 (let* ((lim 0) prop
10330 (recursive (or (not org-hierarchical-todo-statistics)
10331 (string-match
10332 "\\<recursive\\>"
10333 (or (setq prop (org-entry-get
10334 nil "COOKIE_DATA" 'inherit)) ""))))
10335 (lim (or (and prop (marker-position
10336 org-entry-property-inherited-from))
10337 lim))
10338 (first t)
10339 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10340 level ltoggle l1 new ndel
10341 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10342 (catch 'exit
10343 (save-excursion
10344 (beginning-of-line 1)
10345 (if (org-at-heading-p)
10346 (setq ltoggle (funcall outline-level))
10347 (error "This should not happen"))
10348 (while (and (setq level (org-up-heading-safe))
10349 (or recursive first)
10350 (>= (point) lim))
10351 (setq first nil cookie-present nil)
10352 (unless (and level
10353 (not (string-match
10354 "\\<checkbox\\>"
10355 (downcase
10356 (or (org-entry-get
10357 nil "COOKIE_DATA")
10358 "")))))
10359 (throw 'exit nil))
10360 (while (re-search-forward box-re (point-at-eol) t)
10361 (setq cnt-all 0 cnt-done 0 cookie-present t)
10362 (setq is-percent (match-end 2))
10363 (save-match-data
10364 (unless (outline-next-heading) (throw 'exit nil))
10365 (while (and (looking-at org-complex-heading-regexp)
10366 (> (setq l1 (length (match-string 1))) level))
10367 (setq kwd (and (or recursive (= l1 ltoggle))
10368 (match-string 2)))
10369 (if (or (eq org-provide-todo-statistics 'all-headlines)
10370 (and (listp org-provide-todo-statistics)
10371 (or (member kwd org-provide-todo-statistics)
10372 (member kwd org-done-keywords))))
10373 (setq cnt-all (1+ cnt-all))
10374 (if (eq org-provide-todo-statistics t)
10375 (and kwd (setq cnt-all (1+ cnt-all)))))
10376 (and (member kwd org-done-keywords)
10377 (setq cnt-done (1+ cnt-done)))
10378 (outline-next-heading)))
10379 (setq new
10380 (if is-percent
10381 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10382 (format "[%d/%d]" cnt-done cnt-all))
10383 ndel (- (match-end 0) (match-beginning 0)))
10384 (goto-char (match-beginning 0))
10385 (insert new)
10386 (delete-region (point) (+ (point) ndel)))
10387 (when cookie-present
10388 (run-hook-with-args 'org-after-todo-statistics-hook
10389 cnt-done (- cnt-all cnt-done))))))
10390 (run-hooks 'org-todo-statistics-hook)))
10392 (defvar org-after-todo-statistics-hook nil
10393 "Hook that is called after a TODO statistics cookie has been updated.
10394 Each function is called with two arguments: the number of not-done entries
10395 and the number of done entries.
10397 For example, the following function, when added to this hook, will switch
10398 an entry to DONE when all children are done, and back to TODO when new
10399 entries are set to a TODO status. Note that this hook is only called
10400 when there is a statistics cookie in the headline!
10402 (defun org-summary-todo (n-done n-not-done)
10403 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10404 (let (org-log-done org-log-states) ; turn off logging
10405 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10408 (defvar org-todo-statistics-hook nil
10409 "Hook that is run whenever Org thinks TODO statistics should be updated.
10410 This hook runs even if there is no statistics cookie present, in which case
10411 `org-after-todo-statistics-hook' would not run.")
10413 (defun org-todo-trigger-tag-changes (state)
10414 "Apply the changes defined in `org-todo-state-tags-triggers'."
10415 (let ((l org-todo-state-tags-triggers)
10416 changes)
10417 (when (or (not state) (equal state ""))
10418 (setq changes (append changes (cdr (assoc "" l)))))
10419 (when (and (stringp state) (> (length state) 0))
10420 (setq changes (append changes (cdr (assoc state l)))))
10421 (when (member state org-not-done-keywords)
10422 (setq changes (append changes (cdr (assoc 'todo l)))))
10423 (when (member state org-done-keywords)
10424 (setq changes (append changes (cdr (assoc 'done l)))))
10425 (dolist (c changes)
10426 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10428 (defun org-local-logging (value)
10429 "Get logging settings from a property VALUE."
10430 (let* (words w a)
10431 ;; directly set the variables, they are already local.
10432 (setq org-log-done nil
10433 org-log-repeat nil
10434 org-todo-log-states nil)
10435 (setq words (org-split-string value))
10436 (while (setq w (pop words))
10437 (cond
10438 ((setq a (assoc w org-startup-options))
10439 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10440 (set (nth 1 a) (nth 2 a))))
10441 ((setq a (org-extract-log-state-settings w))
10442 (and (member (car a) org-todo-keywords-1)
10443 (push a org-todo-log-states)))))))
10445 (defun org-get-todo-sequence-head (kwd)
10446 "Return the head of the TODO sequence to which KWD belongs.
10447 If KWD is not set, check if there is a text property remembering the
10448 right sequence."
10449 (let (p)
10450 (cond
10451 ((not kwd)
10452 (or (get-text-property (point-at-bol) 'org-todo-head)
10453 (progn
10454 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10455 nil (point-at-eol)))
10456 (get-text-property p 'org-todo-head))))
10457 ((not (member kwd org-todo-keywords-1))
10458 (car org-todo-keywords-1))
10459 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10461 (defun org-fast-todo-selection ()
10462 "Fast TODO keyword selection with single keys.
10463 Returns the new TODO keyword, or nil if no state change should occur."
10464 (let* ((fulltable org-todo-key-alist)
10465 (done-keywords org-done-keywords) ;; needed for the faces.
10466 (maxlen (apply 'max (mapcar
10467 (lambda (x)
10468 (if (stringp (car x)) (string-width (car x)) 0))
10469 fulltable)))
10470 (expert nil)
10471 (fwidth (+ maxlen 3 1 3))
10472 (ncol (/ (- (window-width) 4) fwidth))
10473 tg cnt e c tbl
10474 groups ingroup)
10475 (save-excursion
10476 (save-window-excursion
10477 (if expert
10478 (set-buffer (get-buffer-create " *Org todo*"))
10479 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10480 (erase-buffer)
10481 (org-set-local 'org-done-keywords done-keywords)
10482 (setq tbl fulltable cnt 0)
10483 (while (setq e (pop tbl))
10484 (cond
10485 ((equal e '(:startgroup))
10486 (push '() groups) (setq ingroup t)
10487 (when (not (= cnt 0))
10488 (setq cnt 0)
10489 (insert "\n"))
10490 (insert "{ "))
10491 ((equal e '(:endgroup))
10492 (setq ingroup nil cnt 0)
10493 (insert "}\n"))
10494 ((equal e '(:newline))
10495 (when (not (= cnt 0))
10496 (setq cnt 0)
10497 (insert "\n")
10498 (setq e (car tbl))
10499 (while (equal (car tbl) '(:newline))
10500 (insert "\n")
10501 (setq tbl (cdr tbl)))))
10503 (setq tg (car e) c (cdr e))
10504 (if ingroup (push tg (car groups)))
10505 (setq tg (org-add-props tg nil 'face
10506 (org-get-todo-face tg)))
10507 (if (and (= cnt 0) (not ingroup)) (insert " "))
10508 (insert "[" c "] " tg (make-string
10509 (- fwidth 4 (length tg)) ?\ ))
10510 (when (= (setq cnt (1+ cnt)) ncol)
10511 (insert "\n")
10512 (if ingroup (insert " "))
10513 (setq cnt 0)))))
10514 (insert "\n")
10515 (goto-char (point-min))
10516 (if (not expert) (org-fit-window-to-buffer))
10517 (message "[a-z..]:Set [SPC]:clear")
10518 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10519 (cond
10520 ((or (= c ?\C-g)
10521 (and (= c ?q) (not (rassoc c fulltable))))
10522 (setq quit-flag t))
10523 ((= c ?\ ) nil)
10524 ((setq e (rassoc c fulltable) tg (car e))
10526 (t (setq quit-flag t)))))))
10528 (defun org-entry-is-todo-p ()
10529 (member (org-get-todo-state) org-not-done-keywords))
10531 (defun org-entry-is-done-p ()
10532 (member (org-get-todo-state) org-done-keywords))
10534 (defun org-get-todo-state ()
10535 (save-excursion
10536 (org-back-to-heading t)
10537 (and (looking-at org-todo-line-regexp)
10538 (match-end 2)
10539 (match-string 2))))
10541 (defun org-at-date-range-p (&optional inactive-ok)
10542 "Is the cursor inside a date range?"
10543 (interactive)
10544 (save-excursion
10545 (catch 'exit
10546 (let ((pos (point)))
10547 (skip-chars-backward "^[<\r\n")
10548 (skip-chars-backward "<[")
10549 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10550 (>= (match-end 0) pos)
10551 (throw 'exit t))
10552 (skip-chars-backward "^<[\r\n")
10553 (skip-chars-backward "<[")
10554 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10555 (>= (match-end 0) pos)
10556 (throw 'exit t)))
10557 nil)))
10559 (defun org-get-repeat (&optional tagline)
10560 "Check if there is a deadline/schedule with repeater in this entry."
10561 (save-match-data
10562 (save-excursion
10563 (org-back-to-heading t)
10564 (and (re-search-forward (if tagline
10565 (concat tagline "\\s-*" org-repeat-re)
10566 org-repeat-re)
10567 (org-entry-end-position) t)
10568 (match-string-no-properties 1)))))
10570 (defvar org-last-changed-timestamp)
10571 (defvar org-last-inserted-timestamp)
10572 (defvar org-log-post-message)
10573 (defvar org-log-note-purpose)
10574 (defvar org-log-note-how)
10575 (defvar org-log-note-extra)
10576 (defun org-auto-repeat-maybe (done-word)
10577 "Check if the current headline contains a repeated deadline/schedule.
10578 If yes, set TODO state back to what it was and change the base date
10579 of repeating deadline/scheduled time stamps to new date.
10580 This function is run automatically after each state change to a DONE state."
10581 ;; last-state is dynamically scoped into this function
10582 (let* ((repeat (org-get-repeat))
10583 (aa (assoc last-state org-todo-kwd-alist))
10584 (interpret (nth 1 aa))
10585 (head (nth 2 aa))
10586 (whata '(("d" . day) ("m" . month) ("y" . year)))
10587 (msg "Entry repeats: ")
10588 (org-log-done nil)
10589 (org-todo-log-states nil)
10590 (nshiftmax 10) (nshift 0)
10591 re type n what ts time)
10592 (when repeat
10593 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10594 (org-todo (if (eq interpret 'type) last-state head))
10595 (org-entry-put nil "LAST_REPEAT" (format-time-string
10596 (org-time-stamp-format t t)))
10597 (when org-log-repeat
10598 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10599 (memq 'org-add-log-note post-command-hook))
10600 ;; OK, we are already setup for some record
10601 (if (eq org-log-repeat 'note)
10602 ;; make sure we take a note, not only a time stamp
10603 (setq org-log-note-how 'note))
10604 ;; Set up for taking a record
10605 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10606 last-state
10607 'findpos org-log-repeat)))
10608 (org-back-to-heading t)
10609 (org-add-planning-info nil nil 'closed)
10610 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10611 org-deadline-time-regexp "\\)\\|\\("
10612 org-ts-regexp "\\)"))
10613 (while (re-search-forward
10614 re (save-excursion (outline-next-heading) (point)) t)
10615 (setq type (if (match-end 1) org-scheduled-string
10616 (if (match-end 3) org-deadline-string "Plain:"))
10617 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10618 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10619 (setq n (string-to-number (match-string 2 ts))
10620 what (match-string 3 ts))
10621 (if (equal what "w") (setq n (* n 7) what "d"))
10622 ;; Preparation, see if we need to modify the start date for the change
10623 (when (match-end 1)
10624 (setq time (save-match-data (org-time-string-to-time ts)))
10625 (cond
10626 ((equal (match-string 1 ts) ".")
10627 ;; Shift starting date to today
10628 (org-timestamp-change
10629 (- (time-to-days (current-time)) (time-to-days time))
10630 'day))
10631 ((equal (match-string 1 ts) "+")
10632 (while (or (= nshift 0)
10633 (<= (time-to-days time) (time-to-days (current-time))))
10634 (when (= (incf nshift) nshiftmax)
10635 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10636 (error "Abort")))
10637 (org-timestamp-change n (cdr (assoc what whata)))
10638 (org-at-timestamp-p t)
10639 (setq ts (match-string 1))
10640 (setq time (save-match-data (org-time-string-to-time ts))))
10641 (org-timestamp-change (- n) (cdr (assoc what whata)))
10642 ;; rematch, so that we have everything in place for the real shift
10643 (org-at-timestamp-p t)
10644 (setq ts (match-string 1))
10645 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10646 (org-timestamp-change n (cdr (assoc what whata)))
10647 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10648 (setq org-log-post-message msg)
10649 (message "%s" msg))))
10651 (defun org-show-todo-tree (arg)
10652 "Make a compact tree which shows all headlines marked with TODO.
10653 The tree will show the lines where the regexp matches, and all higher
10654 headlines above the match.
10655 With a \\[universal-argument] prefix, prompt for a regexp to match.
10656 With a numeric prefix N, construct a sparse tree for the Nth element
10657 of `org-todo-keywords-1'."
10658 (interactive "P")
10659 (let ((case-fold-search nil)
10660 (kwd-re
10661 (cond ((null arg) org-not-done-regexp)
10662 ((equal arg '(4))
10663 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10664 (mapcar 'list org-todo-keywords-1))))
10665 (concat "\\("
10666 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10667 "\\)\\>")))
10668 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10669 (regexp-quote (nth (1- (prefix-numeric-value arg))
10670 org-todo-keywords-1)))
10671 (t (error "Invalid prefix argument: %s" arg)))))
10672 (message "%d TODO entries found"
10673 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10675 (defun org-deadline (&optional remove time)
10676 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10677 With argument REMOVE, remove any deadline from the item.
10678 When TIME is set, it should be an internal time specification, and the
10679 scheduling will use the corresponding date."
10680 (interactive "P")
10681 (let ((old-date (org-entry-get nil "DEADLINE")))
10682 (if remove
10683 (progn
10684 (when (and old-date org-log-redeadline)
10685 (org-add-log-setup 'deldeadline nil old-date 'findpos
10686 org-log-redeadline))
10687 (org-remove-timestamp-with-keyword org-deadline-string)
10688 (message "Item no longer has a deadline."))
10689 (if (org-get-repeat)
10690 (error "Cannot change deadline on task with repeater, please do that by hand")
10691 (org-add-planning-info 'deadline time 'closed)
10692 (when (and old-date org-log-redeadline
10693 (not (equal old-date
10694 (substring org-last-inserted-timestamp 1 -1))))
10695 (org-add-log-setup 'redeadline nil old-date 'findpos
10696 org-log-redeadline))
10697 (message "Deadline on %s" org-last-inserted-timestamp)))))
10699 (defun org-schedule (&optional remove time)
10700 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10701 With argument REMOVE, remove any scheduling date from the item.
10702 When TIME is set, it should be an internal time specification, and the
10703 scheduling will use the corresponding date."
10704 (interactive "P")
10705 (let ((old-date (org-entry-get nil "SCHEDULED")))
10706 (if remove
10707 (progn
10708 (when (and old-date org-log-reschedule)
10709 (org-add-log-setup 'delschedule nil old-date 'findpos
10710 org-log-reschedule))
10711 (org-remove-timestamp-with-keyword org-scheduled-string)
10712 (message "Item is no longer scheduled."))
10713 (if (org-get-repeat)
10714 (error "Cannot reschedule task with repeater, please do that by hand")
10715 (org-add-planning-info 'scheduled time 'closed)
10716 (when (and old-date org-log-reschedule
10717 (not (equal old-date
10718 (substring org-last-inserted-timestamp 1 -1))))
10719 (org-add-log-setup 'reschedule nil old-date 'findpos
10720 org-log-reschedule))
10721 (message "Scheduled to %s" org-last-inserted-timestamp)))))
10723 (defun org-get-scheduled-time (pom &optional inherit)
10724 "Get the scheduled time as a time tuple, of a format suitable
10725 for calling org-schedule with, or if there is no scheduling,
10726 returns nil."
10727 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10728 (when time
10729 (apply 'encode-time (org-parse-time-string time)))))
10731 (defun org-get-deadline-time (pom &optional inherit)
10732 "Get the deadine as a time tuple, of a format suitable for
10733 calling org-deadline with, or if there is no scheduling, returns
10734 nil."
10735 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10736 (when time
10737 (apply 'encode-time (org-parse-time-string time)))))
10739 (defun org-remove-timestamp-with-keyword (keyword)
10740 "Remove all time stamps with KEYWORD in the current entry."
10741 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10742 beg)
10743 (save-excursion
10744 (org-back-to-heading t)
10745 (setq beg (point))
10746 (outline-next-heading)
10747 (while (re-search-backward re beg t)
10748 (replace-match "")
10749 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10750 (equal (char-before) ?\ ))
10751 (backward-delete-char 1)
10752 (if (string-match "^[ \t]*$" (buffer-substring
10753 (point-at-bol) (point-at-eol)))
10754 (delete-region (point-at-bol)
10755 (min (point-max) (1+ (point-at-eol))))))))))
10757 (defun org-add-planning-info (what &optional time &rest remove)
10758 "Insert new timestamp with keyword in the line directly after the headline.
10759 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10760 If non is given, the user is prompted for a date.
10761 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10762 be removed."
10763 (interactive)
10764 (let (org-time-was-given org-end-time-was-given ts
10765 end default-time default-input)
10767 (catch 'exit
10768 (when (and (not time) (memq what '(scheduled deadline)))
10769 ;; Try to get a default date/time from existing timestamp
10770 (save-excursion
10771 (org-back-to-heading t)
10772 (setq end (save-excursion (outline-next-heading) (point)))
10773 (when (re-search-forward (if (eq what 'scheduled)
10774 org-scheduled-time-regexp
10775 org-deadline-time-regexp)
10776 end t)
10777 (setq ts (match-string 1)
10778 default-time
10779 (apply 'encode-time (org-parse-time-string ts))
10780 default-input (and ts (org-get-compact-tod ts))))))
10781 (when what
10782 ;; If necessary, get the time from the user
10783 (setq time (or time (org-read-date nil 'to-time nil nil
10784 default-time default-input))))
10786 (when (and org-insert-labeled-timestamps-at-point
10787 (member what '(scheduled deadline)))
10788 (insert
10789 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10790 (org-insert-time-stamp time org-time-was-given
10791 nil nil nil (list org-end-time-was-given))
10792 (setq what nil))
10793 (save-excursion
10794 (save-restriction
10795 (let (col list elt ts buffer-invisibility-spec)
10796 (org-back-to-heading t)
10797 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10798 (goto-char (match-end 1))
10799 (setq col (current-column))
10800 (goto-char (match-end 0))
10801 (if (eobp) (insert "\n") (forward-char 1))
10802 (when (and (not what)
10803 (not (looking-at
10804 (concat "[ \t]*"
10805 org-keyword-time-not-clock-regexp))))
10806 ;; Nothing to add, nothing to remove...... :-)
10807 (throw 'exit nil))
10808 (if (and (not (looking-at outline-regexp))
10809 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10810 "[^\r\n]*"))
10811 (not (equal (match-string 1) org-clock-string)))
10812 (narrow-to-region (match-beginning 0) (match-end 0))
10813 (insert-before-markers "\n")
10814 (backward-char 1)
10815 (narrow-to-region (point) (point))
10816 (and org-adapt-indentation (org-indent-to-column col)))
10817 ;; Check if we have to remove something.
10818 (setq list (cons what remove))
10819 (while list
10820 (setq elt (pop list))
10821 (goto-char (point-min))
10822 (when (or (and (eq elt 'scheduled)
10823 (re-search-forward org-scheduled-time-regexp nil t))
10824 (and (eq elt 'deadline)
10825 (re-search-forward org-deadline-time-regexp nil t))
10826 (and (eq elt 'closed)
10827 (re-search-forward org-closed-time-regexp nil t)))
10828 (replace-match "")
10829 (if (looking-at "--+<[^>]+>") (replace-match ""))
10830 (skip-chars-backward " ")
10831 (if (looking-at " +") (replace-match ""))))
10832 (goto-char (point-max))
10833 (and org-adapt-indentation (bolp) (org-indent-to-column col))
10834 (when what
10835 (insert
10836 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10837 (cond ((eq what 'scheduled) org-scheduled-string)
10838 ((eq what 'deadline) org-deadline-string)
10839 ((eq what 'closed) org-closed-string))
10840 " ")
10841 (setq ts (org-insert-time-stamp
10842 time
10843 (or org-time-was-given
10844 (and (eq what 'closed) org-log-done-with-time))
10845 (eq what 'closed)
10846 nil nil (list org-end-time-was-given)))
10847 (end-of-line 1))
10848 (goto-char (point-min))
10849 (widen)
10850 (if (and (looking-at "[ \t]+\n")
10851 (equal (char-before) ?\n))
10852 (delete-region (1- (point)) (point-at-eol)))
10853 ts))))))
10855 (defvar org-log-note-marker (make-marker))
10856 (defvar org-log-note-purpose nil)
10857 (defvar org-log-note-state nil)
10858 (defvar org-log-note-previous-state nil)
10859 (defvar org-log-note-how nil)
10860 (defvar org-log-note-extra nil)
10861 (defvar org-log-note-window-configuration nil)
10862 (defvar org-log-note-return-to (make-marker))
10863 (defvar org-log-post-message nil
10864 "Message to be displayed after a log note has been stored.
10865 The auto-repeater uses this.")
10867 (defun org-add-note ()
10868 "Add a note to the current entry.
10869 This is done in the same way as adding a state change note."
10870 (interactive)
10871 (org-add-log-setup 'note nil nil 'findpos nil))
10873 (defvar org-property-end-re)
10874 (defun org-add-log-setup (&optional purpose state prev-state
10875 findpos how &optional extra)
10876 "Set up the post command hook to take a note.
10877 If this is about to TODO state change, the new state is expected in STATE.
10878 When FINDPOS is non-nil, find the correct position for the note in
10879 the current entry. If not, assume that it can be inserted at point.
10880 HOW is an indicator what kind of note should be created.
10881 EXTRA is additional text that will be inserted into the notes buffer."
10882 (let* ((org-log-into-drawer (org-log-into-drawer))
10883 (drawer (cond ((stringp org-log-into-drawer)
10884 org-log-into-drawer)
10885 (org-log-into-drawer "LOGBOOK")
10886 (t nil))))
10887 (save-restriction
10888 (save-excursion
10889 (when findpos
10890 (org-back-to-heading t)
10891 (narrow-to-region (point) (save-excursion
10892 (outline-next-heading) (point)))
10893 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10894 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10895 "[^\r\n]*\\)?"))
10896 (goto-char (match-end 0))
10897 (cond
10898 (drawer
10899 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10900 nil t)
10901 (progn
10902 (goto-char (match-end 0))
10903 (or org-log-states-order-reversed
10904 (and (re-search-forward org-property-end-re nil t)
10905 (goto-char (1- (match-beginning 0))))))
10906 (insert "\n:" drawer ":\n:END:")
10907 (beginning-of-line 0)
10908 (org-indent-line-function)
10909 (beginning-of-line 2)
10910 (org-indent-line-function)
10911 (end-of-line 0)))
10912 ((and org-log-state-notes-insert-after-drawers
10913 (save-excursion
10914 (forward-line) (looking-at org-drawer-regexp)))
10915 (forward-line)
10916 (while (looking-at org-drawer-regexp)
10917 (goto-char (match-end 0))
10918 (re-search-forward org-property-end-re (point-max) t)
10919 (forward-line))
10920 (forward-line -1)))
10921 (unless org-log-states-order-reversed
10922 (and (= (char-after) ?\n) (forward-char 1))
10923 (org-skip-over-state-notes)
10924 (skip-chars-backward " \t\n\r")))
10925 (move-marker org-log-note-marker (point))
10926 (setq org-log-note-purpose purpose
10927 org-log-note-state state
10928 org-log-note-previous-state prev-state
10929 org-log-note-how how
10930 org-log-note-extra extra)
10931 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10933 (defun org-skip-over-state-notes ()
10934 "Skip past the list of State notes in an entry."
10935 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10936 (while (looking-at "[ \t]*- State")
10937 (condition-case nil
10938 (org-next-item)
10939 (error (org-end-of-item)))))
10941 (defun org-add-log-note (&optional purpose)
10942 "Pop up a window for taking a note, and add this note later at point."
10943 (remove-hook 'post-command-hook 'org-add-log-note)
10944 (setq org-log-note-window-configuration (current-window-configuration))
10945 (delete-other-windows)
10946 (move-marker org-log-note-return-to (point))
10947 (switch-to-buffer (marker-buffer org-log-note-marker))
10948 (goto-char org-log-note-marker)
10949 (org-switch-to-buffer-other-window "*Org Note*")
10950 (erase-buffer)
10951 (if (memq org-log-note-how '(time state))
10952 (let (current-prefix-arg) (org-store-log-note))
10953 (let ((org-inhibit-startup t)) (org-mode))
10954 (insert (format "# Insert note for %s.
10955 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10956 (cond
10957 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10958 ((eq org-log-note-purpose 'done) "closed todo item")
10959 ((eq org-log-note-purpose 'state)
10960 (format "state change from \"%s\" to \"%s\""
10961 (or org-log-note-previous-state "")
10962 (or org-log-note-state "")))
10963 ((eq org-log-note-purpose 'reschedule)
10964 "rescheduling")
10965 ((eq org-log-note-purpose 'delschedule)
10966 "no longer scheduled")
10967 ((eq org-log-note-purpose 'redeadline)
10968 "changing deadline")
10969 ((eq org-log-note-purpose 'deldeadline)
10970 "removing deadline")
10971 ((eq org-log-note-purpose 'note)
10972 "this entry")
10973 (t (error "This should not happen")))))
10974 (if org-log-note-extra (insert org-log-note-extra))
10975 (org-set-local 'org-finish-function 'org-store-log-note)))
10977 (defvar org-note-abort nil) ; dynamically scoped
10978 (defun org-store-log-note ()
10979 "Finish taking a log note, and insert it to where it belongs."
10980 (let ((txt (buffer-string))
10981 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10982 lines ind)
10983 (kill-buffer (current-buffer))
10984 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10985 (setq txt (replace-match "" t t txt)))
10986 (if (string-match "\\s-+\\'" txt)
10987 (setq txt (replace-match "" t t txt)))
10988 (setq lines (org-split-string txt "\n"))
10989 (when (and note (string-match "\\S-" note))
10990 (setq note
10991 (org-replace-escapes
10992 note
10993 (list (cons "%u" (user-login-name))
10994 (cons "%U" user-full-name)
10995 (cons "%t" (format-time-string
10996 (org-time-stamp-format 'long 'inactive)
10997 (current-time)))
10998 (cons "%s" (if org-log-note-state
10999 (concat "\"" org-log-note-state "\"")
11000 ""))
11001 (cons "%S" (if org-log-note-previous-state
11002 (concat "\"" org-log-note-previous-state "\"")
11003 "\"\"")))))
11004 (if lines (setq note (concat note " \\\\")))
11005 (push note lines))
11006 (when (or current-prefix-arg org-note-abort)
11007 (when org-log-into-drawer
11008 (org-remove-empty-drawer-at
11009 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11010 org-log-note-marker))
11011 (setq lines nil))
11012 (when lines
11013 (with-current-buffer (marker-buffer org-log-note-marker)
11014 (save-excursion
11015 (goto-char org-log-note-marker)
11016 (move-marker org-log-note-marker nil)
11017 (end-of-line 1)
11018 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11019 (insert "- " (pop lines))
11020 (org-indent-line-function)
11021 (beginning-of-line 1)
11022 (looking-at "[ \t]*")
11023 (setq ind (concat (match-string 0) " "))
11024 (end-of-line 1)
11025 (while lines (insert "\n" ind (pop lines)))
11026 (message "Note stored")
11027 (org-back-to-heading t)
11028 (org-cycle-hide-drawers 'children)))))
11029 (set-window-configuration org-log-note-window-configuration)
11030 (with-current-buffer (marker-buffer org-log-note-return-to)
11031 (goto-char org-log-note-return-to))
11032 (move-marker org-log-note-return-to nil)
11033 (and org-log-post-message (message "%s" org-log-post-message)))
11035 (defun org-remove-empty-drawer-at (drawer pos)
11036 "Remove an empty drawer DRAWER at position POS.
11037 POS may also be a marker."
11038 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11039 (save-excursion
11040 (save-restriction
11041 (widen)
11042 (goto-char pos)
11043 (if (org-in-regexp
11044 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11045 (replace-match ""))))))
11047 (defun org-sparse-tree (&optional arg)
11048 "Create a sparse tree, prompt for the details.
11049 This command can create sparse trees. You first need to select the type
11050 of match used to create the tree:
11052 t Show entries with a specific TODO keyword.
11053 m Show entries selected by a tags/property match.
11054 p Enter a property name and its value (both with completion on existing
11055 names/values) and show entries with that property.
11056 / Show entries matching a regular expression (`r' can be used as well)
11057 d Show deadlines due within `org-deadline-warning-days'.
11058 b Show deadlines and scheduled items before a date.
11059 a Show deadlines and scheduled items after a date."
11060 (interactive "P")
11061 (let (ans kwd value)
11062 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
11063 (setq ans (read-char-exclusive))
11064 (cond
11065 ((equal ans ?d)
11066 (call-interactively 'org-check-deadlines))
11067 ((equal ans ?b)
11068 (call-interactively 'org-check-before-date))
11069 ((equal ans ?a)
11070 (call-interactively 'org-check-after-date))
11071 ((equal ans ?t)
11072 (org-show-todo-tree '(4)))
11073 ((member ans '(?T ?m))
11074 (call-interactively 'org-match-sparse-tree))
11075 ((member ans '(?p ?P))
11076 (setq kwd (org-icompleting-read "Property: "
11077 (mapcar 'list (org-buffer-property-keys))))
11078 (setq value (org-icompleting-read "Value: "
11079 (mapcar 'list (org-property-values kwd))))
11080 (unless (string-match "\\`{.*}\\'" value)
11081 (setq value (concat "\"" value "\"")))
11082 (org-match-sparse-tree arg (concat kwd "=" value)))
11083 ((member ans '(?r ?R ?/))
11084 (call-interactively 'org-occur))
11085 (t (error "No such sparse tree command \"%c\"" ans)))))
11087 (defvar org-occur-highlights nil
11088 "List of overlays used for occur matches.")
11089 (make-variable-buffer-local 'org-occur-highlights)
11090 (defvar org-occur-parameters nil
11091 "Parameters of the active org-occur calls.
11092 This is a list, each call to org-occur pushes as cons cell,
11093 containing the regular expression and the callback, onto the list.
11094 The list can contain several entries if `org-occur' has been called
11095 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11096 will only contain one set of parameters. When the highlights are
11097 removed (for example with `C-c C-c', or with the next edit (depending
11098 on `org-remove-highlights-with-change'), this variable is emptied
11099 as well.")
11100 (make-variable-buffer-local 'org-occur-parameters)
11102 (defun org-occur (regexp &optional keep-previous callback)
11103 "Make a compact tree which shows all matches of REGEXP.
11104 The tree will show the lines where the regexp matches, and all higher
11105 headlines above the match. It will also show the heading after the match,
11106 to make sure editing the matching entry is easy.
11107 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11108 call to `org-occur' will be kept, to allow stacking of calls to this
11109 command.
11110 If CALLBACK is non-nil, it is a function which is called to confirm
11111 that the match should indeed be shown."
11112 (interactive "sRegexp: \nP")
11113 (when (equal regexp "")
11114 (error "Regexp cannot be empty"))
11115 (unless keep-previous
11116 (org-remove-occur-highlights nil nil t))
11117 (push (cons regexp callback) org-occur-parameters)
11118 (let ((cnt 0))
11119 (save-excursion
11120 (goto-char (point-min))
11121 (if (or (not keep-previous) ; do not want to keep
11122 (not org-occur-highlights)) ; no previous matches
11123 ;; hide everything
11124 (org-overview))
11125 (while (re-search-forward regexp nil t)
11126 (when (or (not callback)
11127 (save-match-data (funcall callback)))
11128 (setq cnt (1+ cnt))
11129 (when org-highlight-sparse-tree-matches
11130 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11131 (org-show-context 'occur-tree))))
11132 (when org-remove-highlights-with-change
11133 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11134 nil 'local))
11135 (unless org-sparse-tree-open-archived-trees
11136 (org-hide-archived-subtrees (point-min) (point-max)))
11137 (run-hooks 'org-occur-hook)
11138 (if (interactive-p)
11139 (message "%d match(es) for regexp %s" cnt regexp))
11140 cnt))
11142 (defun org-show-context (&optional key)
11143 "Make sure point and context and visible.
11144 How much context is shown depends upon the variables
11145 `org-show-hierarchy-above', `org-show-following-heading'. and
11146 `org-show-siblings'."
11147 (let ((heading-p (org-on-heading-p t))
11148 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11149 (following-p (org-get-alist-option org-show-following-heading key))
11150 (entry-p (org-get-alist-option org-show-entry-below key))
11151 (siblings-p (org-get-alist-option org-show-siblings key)))
11152 (catch 'exit
11153 ;; Show heading or entry text
11154 (if (and heading-p (not entry-p))
11155 (org-flag-heading nil) ; only show the heading
11156 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11157 (org-show-hidden-entry))) ; show entire entry
11158 (when following-p
11159 ;; Show next sibling, or heading below text
11160 (save-excursion
11161 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11162 (org-flag-heading nil))))
11163 (when siblings-p (org-show-siblings))
11164 (when hierarchy-p
11165 ;; show all higher headings, possibly with siblings
11166 (save-excursion
11167 (while (and (condition-case nil
11168 (progn (org-up-heading-all 1) t)
11169 (error nil))
11170 (not (bobp)))
11171 (org-flag-heading nil)
11172 (when siblings-p (org-show-siblings))))))))
11174 (defun org-reveal (&optional siblings)
11175 "Show current entry, hierarchy above it, and the following headline.
11176 This can be used to show a consistent set of context around locations
11177 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11178 not t for the search context.
11180 With optional argument SIBLINGS, on each level of the hierarchy all
11181 siblings are shown. This repairs the tree structure to what it would
11182 look like when opened with hierarchical calls to `org-cycle'."
11183 (interactive "P")
11184 (let ((org-show-hierarchy-above t)
11185 (org-show-following-heading t)
11186 (org-show-siblings (if siblings t org-show-siblings)))
11187 (org-show-context nil)))
11189 (defun org-highlight-new-match (beg end)
11190 "Highlight from BEG to END and mark the highlight is an occur headline."
11191 (let ((ov (org-make-overlay beg end)))
11192 (org-overlay-put ov 'face 'secondary-selection)
11193 (push ov org-occur-highlights)))
11195 (defun org-remove-occur-highlights (&optional beg end noremove)
11196 "Remove the occur highlights from the buffer.
11197 BEG and END are ignored. If NOREMOVE is nil, remove this function
11198 from the `before-change-functions' in the current buffer."
11199 (interactive)
11200 (unless org-inhibit-highlight-removal
11201 (mapc 'org-delete-overlay org-occur-highlights)
11202 (setq org-occur-highlights nil)
11203 (setq org-occur-parameters nil)
11204 (unless noremove
11205 (remove-hook 'before-change-functions
11206 'org-remove-occur-highlights 'local))))
11208 ;;;; Priorities
11210 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11211 "Regular expression matching the priority indicator.")
11213 (defvar org-remove-priority-next-time nil)
11215 (defun org-priority-up ()
11216 "Increase the priority of the current item."
11217 (interactive)
11218 (org-priority 'up))
11220 (defun org-priority-down ()
11221 "Decrease the priority of the current item."
11222 (interactive)
11223 (org-priority 'down))
11225 (defun org-priority (&optional action)
11226 "Change the priority of an item by ARG.
11227 ACTION can be `set', `up', `down', or a character."
11228 (interactive)
11229 (unless org-enable-priority-commands
11230 (error "Priority commands are disabled"))
11231 (setq action (or action 'set))
11232 (let (current new news have remove)
11233 (save-excursion
11234 (org-back-to-heading t)
11235 (if (looking-at org-priority-regexp)
11236 (setq current (string-to-char (match-string 2))
11237 have t)
11238 (setq current org-default-priority))
11239 (cond
11240 ((eq action 'remove)
11241 (setq remove t new ?\ ))
11242 ((or (eq action 'set)
11243 (if (featurep 'xemacs) (characterp action) (integerp action)))
11244 (if (not (eq action 'set))
11245 (setq new action)
11246 (message "Priority %c-%c, SPC to remove: "
11247 org-highest-priority org-lowest-priority)
11248 (setq new (read-char-exclusive)))
11249 (if (and (= (upcase org-highest-priority) org-highest-priority)
11250 (= (upcase org-lowest-priority) org-lowest-priority))
11251 (setq new (upcase new)))
11252 (cond ((equal new ?\ ) (setq remove t))
11253 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11254 (error "Priority must be between `%c' and `%c'"
11255 org-highest-priority org-lowest-priority))))
11256 ((eq action 'up)
11257 (if (and (not have) (eq last-command this-command))
11258 (setq new org-lowest-priority)
11259 (setq new (if (and org-priority-start-cycle-with-default (not have))
11260 org-default-priority (1- current)))))
11261 ((eq action 'down)
11262 (if (and (not have) (eq last-command this-command))
11263 (setq new org-highest-priority)
11264 (setq new (if (and org-priority-start-cycle-with-default (not have))
11265 org-default-priority (1+ current)))))
11266 (t (error "Invalid action")))
11267 (if (or (< (upcase new) org-highest-priority)
11268 (> (upcase new) org-lowest-priority))
11269 (setq remove t))
11270 (setq news (format "%c" new))
11271 (if have
11272 (if remove
11273 (replace-match "" t t nil 1)
11274 (replace-match news t t nil 2))
11275 (if remove
11276 (error "No priority cookie found in line")
11277 (let ((case-fold-search nil))
11278 (looking-at org-todo-line-regexp))
11279 (if (match-end 2)
11280 (progn
11281 (goto-char (match-end 2))
11282 (insert " [#" news "]"))
11283 (goto-char (match-beginning 3))
11284 (insert "[#" news "] "))))
11285 (org-preserve-lc (org-set-tags nil 'align)))
11286 (if remove
11287 (message "Priority removed")
11288 (message "Priority of current item set to %s" news))))
11290 (defun org-get-priority (s)
11291 "Find priority cookie and return priority."
11292 (save-match-data
11293 (if (not (string-match org-priority-regexp s))
11294 (* 1000 (- org-lowest-priority org-default-priority))
11295 (* 1000 (- org-lowest-priority
11296 (string-to-char (match-string 2 s)))))))
11298 ;;;; Tags
11300 (defvar org-agenda-archives-mode)
11301 (defvar org-map-continue-from nil
11302 "Position from where mapping should continue.
11303 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11305 (defvar org-scanner-tags nil
11306 "The current tag list while the tags scanner is running.")
11307 (defvar org-trust-scanner-tags nil
11308 "Should `org-get-tags-at' use the tags fro the scanner.
11309 This is for internal dynamical scoping only.
11310 When this is non-nil, the function `org-get-tags-at' will return the value
11311 of `org-scanner-tags' instead of building the list by itself. This
11312 can lead to large speed-ups when the tags scanner is used in a file with
11313 many entries, and when the list of tags is retrieved, for example to
11314 obtain a list of properties. Building the tags list for each entry in such
11315 a file becomes an N^2 operation - but with this variable set, it scales
11316 as N.")
11318 (defun org-scan-tags (action matcher &optional todo-only)
11319 "Scan headline tags with inheritance and produce output ACTION.
11321 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11322 or `agenda' to produce an entry list for an agenda view. It can also be
11323 a Lisp form or a function that should be called at each matched headline, in
11324 this case the return value is a list of all return values from these calls.
11326 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11327 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11328 only lines with a TODO keyword are included in the output."
11329 (require 'org-agenda)
11330 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11331 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11332 (org-re
11333 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11334 (props (list 'face 'default
11335 'done-face 'org-agenda-done
11336 'undone-face 'default
11337 'mouse-face 'highlight
11338 'org-not-done-regexp org-not-done-regexp
11339 'org-todo-regexp org-todo-regexp
11340 'help-echo
11341 (format "mouse-2 or RET jump to org file %s"
11342 (abbreviate-file-name
11343 (or (buffer-file-name (buffer-base-buffer))
11344 (buffer-name (buffer-base-buffer)))))))
11345 (case-fold-search nil)
11346 (org-map-continue-from nil)
11347 lspos tags tags-list
11348 (tags-alist (list (cons 0 org-file-tags)))
11349 (llast 0) rtn rtn1 level category i txt
11350 todo marker entry priority)
11351 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11352 (setq action (list 'lambda nil action)))
11353 (save-excursion
11354 (goto-char (point-min))
11355 (when (eq action 'sparse-tree)
11356 (org-overview)
11357 (org-remove-occur-highlights))
11358 (while (re-search-forward re nil t)
11359 (catch :skip
11360 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11361 tags (if (match-end 4) (org-match-string-no-properties 4)))
11362 (goto-char (setq lspos (match-beginning 0)))
11363 (setq level (org-reduced-level (funcall outline-level))
11364 category (org-get-category))
11365 (setq i llast llast level)
11366 ;; remove tag lists from same and sublevels
11367 (while (>= i level)
11368 (when (setq entry (assoc i tags-alist))
11369 (setq tags-alist (delete entry tags-alist)))
11370 (setq i (1- i)))
11371 ;; add the next tags
11372 (when tags
11373 (setq tags (org-split-string tags ":")
11374 tags-alist
11375 (cons (cons level tags) tags-alist)))
11376 ;; compile tags for current headline
11377 (setq tags-list
11378 (if org-use-tag-inheritance
11379 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11380 tags)
11381 org-scanner-tags tags-list)
11382 (when org-use-tag-inheritance
11383 (setcdr (car tags-alist)
11384 (mapcar (lambda (x)
11385 (setq x (copy-sequence x))
11386 (org-add-prop-inherited x))
11387 (cdar tags-alist))))
11388 (when (and tags org-use-tag-inheritance
11389 (or (not (eq t org-use-tag-inheritance))
11390 org-tags-exclude-from-inheritance))
11391 ;; selective inheritance, remove uninherited ones
11392 (setcdr (car tags-alist)
11393 (org-remove-uniherited-tags (cdar tags-alist))))
11394 (when (and (or (not todo-only)
11395 (and (member todo org-not-done-keywords)
11396 (or (not org-agenda-tags-todo-honor-ignore-options)
11397 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11398 (let ((case-fold-search t)) (eval matcher))
11400 (not (member org-archive-tag tags-list))
11401 ;; we have an archive tag, should we use this anyway?
11402 (or (not org-agenda-skip-archived-trees)
11403 (and (eq action 'agenda) org-agenda-archives-mode))))
11404 (unless (eq action 'sparse-tree) (org-agenda-skip))
11406 ;; select this headline
11408 (cond
11409 ((eq action 'sparse-tree)
11410 (and org-highlight-sparse-tree-matches
11411 (org-get-heading) (match-end 0)
11412 (org-highlight-new-match
11413 (match-beginning 0) (match-beginning 1)))
11414 (org-show-context 'tags-tree))
11415 ((eq action 'agenda)
11416 (setq txt (org-format-agenda-item
11418 (concat
11419 (if (eq org-tags-match-list-sublevels 'indented)
11420 (make-string (1- level) ?.) "")
11421 (org-get-heading))
11422 category
11423 tags-list
11425 priority (org-get-priority txt))
11426 (goto-char lspos)
11427 (setq marker (org-agenda-new-marker))
11428 (org-add-props txt props
11429 'org-marker marker 'org-hd-marker marker 'org-category category
11430 'todo-state todo
11431 'priority priority 'type "tagsmatch")
11432 (push txt rtn))
11433 ((functionp action)
11434 (setq org-map-continue-from nil)
11435 (save-excursion
11436 (setq rtn1 (funcall action))
11437 (push rtn1 rtn)))
11438 (t (error "Invalid action")))
11440 ;; if we are to skip sublevels, jump to end of subtree
11441 (unless org-tags-match-list-sublevels
11442 (org-end-of-subtree t)
11443 (backward-char 1))))
11444 ;; Get the correct position from where to continue
11445 (if org-map-continue-from
11446 (goto-char org-map-continue-from)
11447 (and (= (point) lspos) (end-of-line 1)))))
11448 (when (and (eq action 'sparse-tree)
11449 (not org-sparse-tree-open-archived-trees))
11450 (org-hide-archived-subtrees (point-min) (point-max)))
11451 (nreverse rtn)))
11453 (defun org-remove-uniherited-tags (tags)
11454 "Remove all tags that are not inherited from the list TAGS."
11455 (cond
11456 ((eq org-use-tag-inheritance t)
11457 (if org-tags-exclude-from-inheritance
11458 (org-delete-all org-tags-exclude-from-inheritance tags)
11459 tags))
11460 ((not org-use-tag-inheritance) nil)
11461 ((stringp org-use-tag-inheritance)
11462 (delq nil (mapcar
11463 (lambda (x)
11464 (if (and (string-match org-use-tag-inheritance x)
11465 (not (member x org-tags-exclude-from-inheritance)))
11466 x nil))
11467 tags)))
11468 ((listp org-use-tag-inheritance)
11469 (delq nil (mapcar
11470 (lambda (x)
11471 (if (member x org-use-tag-inheritance) x nil))
11472 tags)))))
11474 (defvar todo-only) ;; dynamically scoped
11476 (defun org-match-sparse-tree (&optional todo-only match)
11477 "Create a sparse tree according to tags string MATCH.
11478 MATCH can contain positive and negative selection of tags, like
11479 \"+WORK+URGENT-WITHBOSS\".
11480 If optional argument TODO-ONLY is non-nil, only select lines that are
11481 also TODO lines."
11482 (interactive "P")
11483 (org-prepare-agenda-buffers (list (current-buffer)))
11484 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11486 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11488 (defvar org-cached-props nil)
11489 (defun org-cached-entry-get (pom property)
11490 (if (or (eq t org-use-property-inheritance)
11491 (and (stringp org-use-property-inheritance)
11492 (string-match org-use-property-inheritance property))
11493 (and (listp org-use-property-inheritance)
11494 (member property org-use-property-inheritance)))
11495 ;; Caching is not possible, check it directly
11496 (org-entry-get pom property 'inherit)
11497 ;; Get all properties, so that we can do complicated checks easily
11498 (cdr (assoc property (or org-cached-props
11499 (setq org-cached-props
11500 (org-entry-properties pom)))))))
11502 (defun org-global-tags-completion-table (&optional files)
11503 "Return the list of all tags in all agenda buffer/files."
11504 (save-excursion
11505 (org-uniquify
11506 (delq nil
11507 (apply 'append
11508 (mapcar
11509 (lambda (file)
11510 (set-buffer (find-file-noselect file))
11511 (append (org-get-buffer-tags)
11512 (mapcar (lambda (x) (if (stringp (car-safe x))
11513 (list (car-safe x)) nil))
11514 org-tag-alist)))
11515 (if (and files (car files))
11516 files
11517 (org-agenda-files))))))))
11519 (defun org-make-tags-matcher (match)
11520 "Create the TAGS//TODO matcher form for the selection string MATCH."
11521 ;; todo-only is scoped dynamically into this function, and the function
11522 ;; may change it if the matcher asks for it.
11523 (unless match
11524 ;; Get a new match request, with completion
11525 (let ((org-last-tags-completion-table
11526 (org-global-tags-completion-table)))
11527 (setq match (org-completing-read-no-i
11528 "Match: " 'org-tags-completion-function nil nil nil
11529 'org-tags-history))))
11531 ;; Parse the string and create a lisp form
11532 (let ((match0 match)
11533 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11534 minus tag mm
11535 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11536 orterms term orlist re-p str-p level-p level-op time-p
11537 prop-p pn pv po cat-p gv rest)
11538 (if (string-match "/+" match)
11539 ;; match contains also a todo-matching request
11540 (progn
11541 (setq tagsmatch (substring match 0 (match-beginning 0))
11542 todomatch (substring match (match-end 0)))
11543 (if (string-match "^!" todomatch)
11544 (setq todo-only t todomatch (substring todomatch 1)))
11545 (if (string-match "^\\s-*$" todomatch)
11546 (setq todomatch nil)))
11547 ;; only matching tags
11548 (setq tagsmatch match todomatch nil))
11550 ;; Make the tags matcher
11551 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11552 (setq tagsmatcher t)
11553 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11554 (while (setq term (pop orterms))
11555 (while (and (equal (substring term -1) "\\") orterms)
11556 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11557 (while (string-match re term)
11558 (setq rest (substring term (match-end 0))
11559 minus (and (match-end 1)
11560 (equal (match-string 1 term) "-"))
11561 tag (match-string 2 term)
11562 re-p (equal (string-to-char tag) ?{)
11563 level-p (match-end 4)
11564 prop-p (match-end 5)
11565 mm (cond
11566 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11567 (level-p
11568 (setq level-op (org-op-to-function (match-string 3 term)))
11569 `(,level-op level ,(string-to-number
11570 (match-string 4 term))))
11571 (prop-p
11572 (setq pn (match-string 5 term)
11573 po (match-string 6 term)
11574 pv (match-string 7 term)
11575 cat-p (equal pn "CATEGORY")
11576 re-p (equal (string-to-char pv) ?{)
11577 str-p (equal (string-to-char pv) ?\")
11578 time-p (save-match-data
11579 (string-match "^\"[[<].*[]>]\"$" pv))
11580 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11581 (if time-p (setq pv (org-matcher-time pv)))
11582 (setq po (org-op-to-function po (if time-p 'time str-p)))
11583 (cond
11584 ((equal pn "CATEGORY")
11585 (setq gv '(get-text-property (point) 'org-category)))
11586 ((equal pn "TODO")
11587 (setq gv 'todo))
11589 (setq gv `(org-cached-entry-get nil ,pn))))
11590 (if re-p
11591 (if (eq po 'org<>)
11592 `(not (string-match ,pv (or ,gv "")))
11593 `(string-match ,pv (or ,gv "")))
11594 (if str-p
11595 `(,po (or ,gv "") ,pv)
11596 `(,po (string-to-number (or ,gv ""))
11597 ,(string-to-number pv) ))))
11598 (t `(member ,tag tags-list)))
11599 mm (if minus (list 'not mm) mm)
11600 term rest)
11601 (push mm tagsmatcher))
11602 (push (if (> (length tagsmatcher) 1)
11603 (cons 'and tagsmatcher)
11604 (car tagsmatcher))
11605 orlist)
11606 (setq tagsmatcher nil))
11607 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11608 (setq tagsmatcher
11609 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11610 ;; Make the todo matcher
11611 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11612 (setq todomatcher t)
11613 (setq orterms (org-split-string todomatch "|") orlist nil)
11614 (while (setq term (pop orterms))
11615 (while (string-match re term)
11616 (setq minus (and (match-end 1)
11617 (equal (match-string 1 term) "-"))
11618 kwd (match-string 2 term)
11619 re-p (equal (string-to-char kwd) ?{)
11620 term (substring term (match-end 0))
11621 mm (if re-p
11622 `(string-match ,(substring kwd 1 -1) todo)
11623 (list 'equal 'todo kwd))
11624 mm (if minus (list 'not mm) mm))
11625 (push mm todomatcher))
11626 (push (if (> (length todomatcher) 1)
11627 (cons 'and todomatcher)
11628 (car todomatcher))
11629 orlist)
11630 (setq todomatcher nil))
11631 (setq todomatcher (if (> (length orlist) 1)
11632 (cons 'or orlist) (car orlist))))
11634 ;; Return the string and lisp forms of the matcher
11635 (setq matcher (if todomatcher
11636 (list 'and tagsmatcher todomatcher)
11637 tagsmatcher))
11638 (cons match0 matcher)))
11640 (defun org-op-to-function (op &optional stringp)
11641 "Turn an operator into the appropriate function."
11642 (setq op
11643 (cond
11644 ((equal op "<" ) '(< string< org-time<))
11645 ((equal op ">" ) '(> org-string> org-time>))
11646 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11647 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11648 ((member op '("=" "==")) '(= string= org-time=))
11649 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11650 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11652 (defun org<> (a b) (not (= a b)))
11653 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11654 (defun org-string>= (a b) (not (string< a b)))
11655 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11656 (defun org-string<> (a b) (not (string= a b)))
11657 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= 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) (org<> a b)))
11663 (defun org-2ft (s)
11664 "Convert S to a floating point time.
11665 If S is already a number, just return it. If it is a string, parse
11666 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11667 (cond
11668 ((numberp s) s)
11669 ((stringp s)
11670 (condition-case nil
11671 (float-time (apply 'encode-time (org-parse-time-string s)))
11672 (error 0.)))
11673 (t 0.)))
11675 (defun org-time-today ()
11676 "Time in seconds today at 0:00.
11677 Returns the float number of seconds since the beginning of the
11678 epoch to the beginning of today (00:00)."
11679 (float-time (apply 'encode-time
11680 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11682 (defun org-matcher-time (s)
11683 "Interpret a time comparison value."
11684 (save-match-data
11685 (cond
11686 ((string= s "<now>") (float-time))
11687 ((string= s "<today>") (org-time-today))
11688 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11689 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11690 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11691 (+ (org-time-today)
11692 (* (string-to-number (match-string 1 s))
11693 (cdr (assoc (match-string 2 s)
11694 '(("d" . 86400.0) ("w" . 604800.0)
11695 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11696 (t (org-2ft s)))))
11698 (defun org-match-any-p (re list)
11699 "Does re match any element of list?"
11700 (setq list (mapcar (lambda (x) (string-match re x)) list))
11701 (delq nil list))
11703 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11704 (defvar org-tags-overlay (org-make-overlay 1 1))
11705 (org-detach-overlay org-tags-overlay)
11707 (defun org-get-local-tags-at (&optional pos)
11708 "Get a list of tags defined in the current headline."
11709 (org-get-tags-at pos 'local))
11711 (defun org-get-local-tags ()
11712 "Get a list of tags defined in the current headline."
11713 (org-get-tags-at nil 'local))
11715 (defun org-get-tags-at (&optional pos local)
11716 "Get a list of all headline tags applicable at POS.
11717 POS defaults to point. If tags are inherited, the list contains
11718 the targets in the same sequence as the headlines appear, i.e.
11719 the tags of the current headline come last.
11720 When LOCAL is non-nil, only return tags from the current headline,
11721 ignore inherited ones."
11722 (interactive)
11723 (if (and org-trust-scanner-tags
11724 (or (not pos) (equal pos (point)))
11725 (not local))
11726 org-scanner-tags
11727 (let (tags ltags lastpos parent)
11728 (save-excursion
11729 (save-restriction
11730 (widen)
11731 (goto-char (or pos (point)))
11732 (save-match-data
11733 (catch 'done
11734 (condition-case nil
11735 (progn
11736 (org-back-to-heading t)
11737 (while (not (equal lastpos (point)))
11738 (setq lastpos (point))
11739 (when (looking-at
11740 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11741 (setq ltags (org-split-string
11742 (org-match-string-no-properties 1) ":"))
11743 (when parent
11744 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11745 (setq tags (append
11746 (if parent
11747 (org-remove-uniherited-tags ltags)
11748 ltags)
11749 tags)))
11750 (or org-use-tag-inheritance (throw 'done t))
11751 (if local (throw 'done t))
11752 (or (org-up-heading-safe) (error nil))
11753 (setq parent t)))
11754 (error nil)))))
11755 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11757 (defun org-add-prop-inherited (s)
11758 (add-text-properties 0 (length s) '(inherited t) s)
11761 (defun org-toggle-tag (tag &optional onoff)
11762 "Toggle the tag TAG for the current line.
11763 If ONOFF is `on' or `off', don't toggle but set to this state."
11764 (let (res current)
11765 (save-excursion
11766 (org-back-to-heading t)
11767 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11768 (point-at-eol) t)
11769 (progn
11770 (setq current (match-string 1))
11771 (replace-match ""))
11772 (setq current ""))
11773 (setq current (nreverse (org-split-string current ":")))
11774 (cond
11775 ((eq onoff 'on)
11776 (setq res t)
11777 (or (member tag current) (push tag current)))
11778 ((eq onoff 'off)
11779 (or (not (member tag current)) (setq current (delete tag current))))
11780 (t (if (member tag current)
11781 (setq current (delete tag current))
11782 (setq res t)
11783 (push tag current))))
11784 (end-of-line 1)
11785 (if current
11786 (progn
11787 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11788 (org-set-tags nil t))
11789 (delete-horizontal-space))
11790 (run-hooks 'org-after-tags-change-hook))
11791 res))
11793 (defun org-align-tags-here (to-col)
11794 ;; Assumes that this is a headline
11795 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11796 (beginning-of-line 1)
11797 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11798 (< pos (match-beginning 2)))
11799 (progn
11800 (setq tags-l (- (match-end 2) (match-beginning 2)))
11801 (goto-char (match-beginning 1))
11802 (insert " ")
11803 (delete-region (point) (1+ (match-beginning 2)))
11804 (setq ncol (max (1+ (current-column))
11805 (1+ col)
11806 (if (> to-col 0)
11807 to-col
11808 (- (abs to-col) tags-l))))
11809 (setq p (point))
11810 (insert (make-string (- ncol (current-column)) ?\ ))
11811 (setq ncol (current-column))
11812 (when indent-tabs-mode (tabify p (point-at-eol)))
11813 (org-move-to-column (min ncol col) t))
11814 (goto-char pos))))
11816 (defun org-set-tags-command (&optional arg just-align)
11817 "Call the set-tags command for the current entry."
11818 (interactive "P")
11819 (if (org-on-heading-p)
11820 (org-set-tags arg just-align)
11821 (save-excursion
11822 (org-back-to-heading t)
11823 (org-set-tags arg just-align))))
11825 (defun org-set-tags-to (data)
11826 "Set the tags of the current entry to DATA, replacing the current tags.
11827 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11828 If DATA is nil or the empty string, any tags will be removed."
11829 (interactive "sTags: ")
11830 (setq data
11831 (cond
11832 ((eq data nil) "")
11833 ((equal data "") "")
11834 ((stringp data)
11835 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11836 ":"))
11837 ((listp data)
11838 (concat ":" (mapconcat 'identity data ":") ":"))
11839 (t nil)))
11840 (when data
11841 (save-excursion
11842 (org-back-to-heading t)
11843 (when (looking-at org-complex-heading-regexp)
11844 (if (match-end 5)
11845 (progn
11846 (goto-char (match-beginning 5))
11847 (insert data)
11848 (delete-region (point) (point-at-eol))
11849 (org-set-tags nil 'align))
11850 (goto-char (point-at-eol))
11851 (insert " " data)
11852 (org-set-tags nil 'align)))
11853 (beginning-of-line 1)
11854 (if (looking-at ".*?\\([ \t]+\\)$")
11855 (delete-region (match-beginning 1) (match-end 1))))))
11857 (defun org-set-tags (&optional arg just-align)
11858 "Set the tags for the current headline.
11859 With prefix ARG, realign all tags in headings in the current buffer."
11860 (interactive "P")
11861 (let* ((re (concat "^" outline-regexp))
11862 (current (org-get-tags-string))
11863 (col (current-column))
11864 (org-setting-tags t)
11865 table current-tags inherited-tags ; computed below when needed
11866 tags p0 c0 c1 rpl)
11867 (if arg
11868 (save-excursion
11869 (goto-char (point-min))
11870 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11871 (while (re-search-forward re nil t)
11872 (org-set-tags nil t)
11873 (end-of-line 1)))
11874 (message "All tags realigned to column %d" org-tags-column))
11875 (if just-align
11876 (setq tags current)
11877 ;; Get a new set of tags from the user
11878 (save-excursion
11879 (setq table (append org-tag-persistent-alist
11880 (or org-tag-alist (org-get-buffer-tags))
11881 (and org-complete-tags-always-offer-all-agenda-tags
11882 (org-global-tags-completion-table (org-agenda-files))))
11883 org-last-tags-completion-table table
11884 current-tags (org-split-string current ":")
11885 inherited-tags (nreverse
11886 (nthcdr (length current-tags)
11887 (nreverse (org-get-tags-at))))
11888 tags
11889 (if (or (eq t org-use-fast-tag-selection)
11890 (and org-use-fast-tag-selection
11891 (delq nil (mapcar 'cdr table))))
11892 (org-fast-tag-selection
11893 current-tags inherited-tags table
11894 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11895 (let ((org-add-colon-after-tag-completion t))
11896 (org-trim
11897 (org-without-partial-completion
11898 (org-icompleting-read "Tags: " 'org-tags-completion-function
11899 nil nil current 'org-tags-history)))))))
11900 (while (string-match "[-+&]+" tags)
11901 ;; No boolean logic, just a list
11902 (setq tags (replace-match ":" t t tags))))
11904 (if org-tags-sort-function
11905 (setq tags (mapconcat 'identity
11906 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11907 org-tags-sort-function) ":")))
11909 (if (string-match "\\`[\t ]*\\'" tags)
11910 (setq tags "")
11911 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11912 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11914 ;; Insert new tags at the correct column
11915 (beginning-of-line 1)
11916 (cond
11917 ((and (equal current "") (equal tags "")))
11918 ((re-search-forward
11919 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11920 (point-at-eol) t)
11921 (if (equal tags "")
11922 (setq rpl "")
11923 (goto-char (match-beginning 0))
11924 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
11925 (1+ (point)) (point))
11926 c1 (max (1+ c0) (if (> org-tags-column 0)
11927 org-tags-column
11928 (- (- org-tags-column) (length tags))))
11929 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11930 (replace-match rpl t t)
11931 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11932 tags)
11933 (t (error "Tags alignment failed")))
11934 (org-move-to-column col)
11935 (unless just-align
11936 (run-hooks 'org-after-tags-change-hook)))))
11938 (defun org-change-tag-in-region (beg end tag off)
11939 "Add or remove TAG for each entry in the region.
11940 This works in the agenda, and also in an org-mode buffer."
11941 (interactive
11942 (list (region-beginning) (region-end)
11943 (let ((org-last-tags-completion-table
11944 (if (org-mode-p)
11945 (org-get-buffer-tags)
11946 (org-global-tags-completion-table))))
11947 (org-icompleting-read
11948 "Tag: " 'org-tags-completion-function nil nil nil
11949 'org-tags-history))
11950 (progn
11951 (message "[s]et or [r]emove? ")
11952 (equal (read-char-exclusive) ?r))))
11953 (if (fboundp 'deactivate-mark) (deactivate-mark))
11954 (let ((agendap (equal major-mode 'org-agenda-mode))
11955 l1 l2 m buf pos newhead (cnt 0))
11956 (goto-char end)
11957 (setq l2 (1- (org-current-line)))
11958 (goto-char beg)
11959 (setq l1 (org-current-line))
11960 (loop for l from l1 to l2 do
11961 (org-goto-line l)
11962 (setq m (get-text-property (point) 'org-hd-marker))
11963 (when (or (and (org-mode-p) (org-on-heading-p))
11964 (and agendap m))
11965 (setq buf (if agendap (marker-buffer m) (current-buffer))
11966 pos (if agendap m (point)))
11967 (with-current-buffer buf
11968 (save-excursion
11969 (save-restriction
11970 (goto-char pos)
11971 (setq cnt (1+ cnt))
11972 (org-toggle-tag tag (if off 'off 'on))
11973 (setq newhead (org-get-heading)))))
11974 (and agendap (org-agenda-change-all-lines newhead m))))
11975 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11977 (defun org-tags-completion-function (string predicate &optional flag)
11978 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11979 (confirm (lambda (x) (stringp (car x)))))
11980 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11981 (setq s1 (match-string 1 string)
11982 s2 (match-string 2 string))
11983 (setq s1 "" s2 string))
11984 (cond
11985 ((eq flag nil)
11986 ;; try completion
11987 (setq rtn (try-completion s2 ctable confirm))
11988 (if (stringp rtn)
11989 (setq rtn
11990 (concat s1 s2 (substring rtn (length s2))
11991 (if (and org-add-colon-after-tag-completion
11992 (assoc rtn ctable))
11993 ":" ""))))
11994 rtn)
11995 ((eq flag t)
11996 ;; all-completions
11997 (all-completions s2 ctable confirm)
11999 ((eq flag 'lambda)
12000 ;; exact match?
12001 (assoc s2 ctable)))
12004 (defun org-fast-tag-insert (kwd tags face &optional end)
12005 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12006 (insert (format "%-12s" (concat kwd ":"))
12007 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12008 (or end "")))
12010 (defun org-fast-tag-show-exit (flag)
12011 (save-excursion
12012 (org-goto-line 3)
12013 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12014 (replace-match ""))
12015 (when flag
12016 (end-of-line 1)
12017 (org-move-to-column (- (window-width) 19) t)
12018 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12020 (defun org-set-current-tags-overlay (current prefix)
12021 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12022 (if (featurep 'xemacs)
12023 (org-overlay-display org-tags-overlay (concat prefix s)
12024 'secondary-selection)
12025 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12026 (org-overlay-display org-tags-overlay (concat prefix s)))))
12028 (defvar org-last-tag-selection-key nil)
12029 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12030 "Fast tag selection with single keys.
12031 CURRENT is the current list of tags in the headline, INHERITED is the
12032 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12033 possibly with grouping information. TODO-TABLE is a similar table with
12034 TODO keywords, should these have keys assigned to them.
12035 If the keys are nil, a-z are automatically assigned.
12036 Returns the new tags string, or nil to not change the current settings."
12037 (let* ((fulltable (append table todo-table))
12038 (maxlen (apply 'max (mapcar
12039 (lambda (x)
12040 (if (stringp (car x)) (string-width (car x)) 0))
12041 fulltable)))
12042 (buf (current-buffer))
12043 (expert (eq org-fast-tag-selection-single-key 'expert))
12044 (buffer-tags nil)
12045 (fwidth (+ maxlen 3 1 3))
12046 (ncol (/ (- (window-width) 4) fwidth))
12047 (i-face 'org-done)
12048 (c-face 'org-todo)
12049 tg cnt e c char c1 c2 ntable tbl rtn
12050 ov-start ov-end ov-prefix
12051 (exit-after-next org-fast-tag-selection-single-key)
12052 (done-keywords org-done-keywords)
12053 groups ingroup)
12054 (save-excursion
12055 (beginning-of-line 1)
12056 (if (looking-at
12057 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12058 (setq ov-start (match-beginning 1)
12059 ov-end (match-end 1)
12060 ov-prefix "")
12061 (setq ov-start (1- (point-at-eol))
12062 ov-end (1+ ov-start))
12063 (skip-chars-forward "^\n\r")
12064 (setq ov-prefix
12065 (concat
12066 (buffer-substring (1- (point)) (point))
12067 (if (> (current-column) org-tags-column)
12069 (make-string (- org-tags-column (current-column)) ?\ ))))))
12070 (org-move-overlay org-tags-overlay ov-start ov-end)
12071 (save-window-excursion
12072 (if expert
12073 (set-buffer (get-buffer-create " *Org tags*"))
12074 (delete-other-windows)
12075 (split-window-vertically)
12076 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12077 (erase-buffer)
12078 (org-set-local 'org-done-keywords done-keywords)
12079 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12080 (org-fast-tag-insert "Current" current c-face "\n\n")
12081 (org-fast-tag-show-exit exit-after-next)
12082 (org-set-current-tags-overlay current ov-prefix)
12083 (setq tbl fulltable char ?a cnt 0)
12084 (while (setq e (pop tbl))
12085 (cond
12086 ((equal (car e) :startgroup)
12087 (push '() groups) (setq ingroup t)
12088 (when (not (= cnt 0))
12089 (setq cnt 0)
12090 (insert "\n"))
12091 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12092 ((equal (car e) :endgroup)
12093 (setq ingroup nil cnt 0)
12094 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12095 ((equal e '(:newline))
12096 (when (not (= cnt 0))
12097 (setq cnt 0)
12098 (insert "\n")
12099 (setq e (car tbl))
12100 (while (equal (car tbl) '(:newline))
12101 (insert "\n")
12102 (setq tbl (cdr tbl)))))
12104 (setq tg (copy-sequence (car e)) c2 nil)
12105 (if (cdr e)
12106 (setq c (cdr e))
12107 ;; automatically assign a character.
12108 (setq c1 (string-to-char
12109 (downcase (substring
12110 tg (if (= (string-to-char tg) ?@) 1 0)))))
12111 (if (or (rassoc c1 ntable) (rassoc c1 table))
12112 (while (or (rassoc char ntable) (rassoc char table))
12113 (setq char (1+ char)))
12114 (setq c2 c1))
12115 (setq c (or c2 char)))
12116 (if ingroup (push tg (car groups)))
12117 (setq tg (org-add-props tg nil 'face
12118 (cond
12119 ((not (assoc tg table))
12120 (org-get-todo-face tg))
12121 ((member tg current) c-face)
12122 ((member tg inherited) i-face)
12123 (t nil))))
12124 (if (and (= cnt 0) (not ingroup)) (insert " "))
12125 (insert "[" c "] " tg (make-string
12126 (- fwidth 4 (length tg)) ?\ ))
12127 (push (cons tg c) ntable)
12128 (when (= (setq cnt (1+ cnt)) ncol)
12129 (insert "\n")
12130 (if ingroup (insert " "))
12131 (setq cnt 0)))))
12132 (setq ntable (nreverse ntable))
12133 (insert "\n")
12134 (goto-char (point-min))
12135 (if (not expert) (org-fit-window-to-buffer))
12136 (setq rtn
12137 (catch 'exit
12138 (while t
12139 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12140 (if (not groups) "no " "")
12141 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12142 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12143 (setq org-last-tag-selection-key c)
12144 (cond
12145 ((= c ?\r) (throw 'exit t))
12146 ((= c ?!)
12147 (setq groups (not groups))
12148 (goto-char (point-min))
12149 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12150 ((= c ?\C-c)
12151 (if (not expert)
12152 (org-fast-tag-show-exit
12153 (setq exit-after-next (not exit-after-next)))
12154 (setq expert nil)
12155 (delete-other-windows)
12156 (split-window-vertically)
12157 (org-switch-to-buffer-other-window " *Org tags*")
12158 (org-fit-window-to-buffer)))
12159 ((or (= c ?\C-g)
12160 (and (= c ?q) (not (rassoc c ntable))))
12161 (org-detach-overlay org-tags-overlay)
12162 (setq quit-flag t))
12163 ((= c ?\ )
12164 (setq current nil)
12165 (if exit-after-next (setq exit-after-next 'now)))
12166 ((= c ?\t)
12167 (condition-case nil
12168 (setq tg (org-icompleting-read
12169 "Tag: "
12170 (or buffer-tags
12171 (with-current-buffer buf
12172 (org-get-buffer-tags)))))
12173 (quit (setq tg "")))
12174 (when (string-match "\\S-" tg)
12175 (add-to-list 'buffer-tags (list tg))
12176 (if (member tg current)
12177 (setq current (delete tg current))
12178 (push tg current)))
12179 (if exit-after-next (setq exit-after-next 'now)))
12180 ((setq e (rassoc c todo-table) tg (car e))
12181 (with-current-buffer buf
12182 (save-excursion (org-todo tg)))
12183 (if exit-after-next (setq exit-after-next 'now)))
12184 ((setq e (rassoc c ntable) tg (car e))
12185 (if (member tg current)
12186 (setq current (delete tg current))
12187 (loop for g in groups do
12188 (if (member tg g)
12189 (mapc (lambda (x)
12190 (setq current (delete x current)))
12191 g)))
12192 (push tg current))
12193 (if exit-after-next (setq exit-after-next 'now))))
12195 ;; Create a sorted list
12196 (setq current
12197 (sort current
12198 (lambda (a b)
12199 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12200 (if (eq exit-after-next 'now) (throw 'exit t))
12201 (goto-char (point-min))
12202 (beginning-of-line 2)
12203 (delete-region (point) (point-at-eol))
12204 (org-fast-tag-insert "Current" current c-face)
12205 (org-set-current-tags-overlay current ov-prefix)
12206 (while (re-search-forward
12207 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12208 (setq tg (match-string 1))
12209 (add-text-properties
12210 (match-beginning 1) (match-end 1)
12211 (list 'face
12212 (cond
12213 ((member tg current) c-face)
12214 ((member tg inherited) i-face)
12215 (t (get-text-property (match-beginning 1) 'face))))))
12216 (goto-char (point-min)))))
12217 (org-detach-overlay org-tags-overlay)
12218 (if rtn
12219 (mapconcat 'identity current ":")
12220 nil))))
12222 (defun org-get-tags-string ()
12223 "Get the TAGS string in the current headline."
12224 (unless (org-on-heading-p t)
12225 (error "Not on a heading"))
12226 (save-excursion
12227 (beginning-of-line 1)
12228 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12229 (org-match-string-no-properties 1)
12230 "")))
12232 (defun org-get-tags ()
12233 "Get the list of tags specified in the current headline."
12234 (org-split-string (org-get-tags-string) ":"))
12236 (defun org-get-buffer-tags ()
12237 "Get a table of all tags used in the buffer, for completion."
12238 (let (tags)
12239 (save-excursion
12240 (goto-char (point-min))
12241 (while (re-search-forward
12242 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12243 (when (equal (char-after (point-at-bol 0)) ?*)
12244 (mapc (lambda (x) (add-to-list 'tags x))
12245 (org-split-string (org-match-string-no-properties 1) ":")))))
12246 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12247 (mapcar 'list tags)))
12249 ;;;; The mapping API
12251 ;;;###autoload
12252 (defun org-map-entries (func &optional match scope &rest skip)
12253 "Call FUNC at each headline selected by MATCH in SCOPE.
12255 FUNC is a function or a lisp form. The function will be called without
12256 arguments, with the cursor positioned at the beginning of the headline.
12257 The return values of all calls to the function will be collected and
12258 returned as a list.
12260 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12261 does not need to preserve point. After evaluation, the cursor will be
12262 moved to the end of the line (presumably of the headline of the
12263 processed entry) and search continues from there. Under some
12264 circumstances, this may not produce the wanted results. For example,
12265 if you have removed (e.g. archived) the current (sub)tree it could
12266 mean that the next entry will be skipped entirely. In such cases, you
12267 can specify the position from where search should continue by making
12268 FUNC set the variable `org-map-continue-from' to the desired buffer
12269 position.
12271 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12272 Only headlines that are matched by this query will be considered during
12273 the iteration. When MATCH is nil or t, all headlines will be
12274 visited by the iteration.
12276 SCOPE determines the scope of this command. It can be any of:
12278 nil The current buffer, respecting the restriction if any
12279 tree The subtree started with the entry at point
12280 file The current buffer, without restriction
12281 file-with-archives
12282 The current buffer, and any archives associated with it
12283 agenda All agenda files
12284 agenda-with-archives
12285 All agenda files with any archive files associated with them
12286 \(file1 file2 ...)
12287 If this is a list, all files in the list will be scanned
12289 The remaining args are treated as settings for the skipping facilities of
12290 the scanner. The following items can be given here:
12292 archive skip trees with the archive tag.
12293 comment skip trees with the COMMENT keyword
12294 function or Emacs Lisp form:
12295 will be used as value for `org-agenda-skip-function', so whenever
12296 the function returns t, FUNC will not be called for that
12297 entry and search will continue from the point where the
12298 function leaves it.
12300 If your function needs to retrieve the tags including inherited tags
12301 at the *current* entry, you can use the value of the variable
12302 `org-scanner-tags' which will be much faster than getting the value
12303 with `org-get-tags-at'. If your function gets properties with
12304 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12305 to t around the call to `org-entry-properties' to get the same speedup.
12306 Note that if your function moves around to retrieve tags and properties at
12307 a *different* entry, you cannot use these techniques."
12308 (let* ((org-agenda-archives-mode nil) ; just to make sure
12309 (org-agenda-skip-archived-trees (memq 'archive skip))
12310 (org-agenda-skip-comment-trees (memq 'comment skip))
12311 (org-agenda-skip-function
12312 (car (org-delete-all '(comment archive) skip)))
12313 (org-tags-match-list-sublevels t)
12314 matcher file res
12315 org-todo-keywords-for-agenda
12316 org-done-keywords-for-agenda
12317 org-todo-keyword-alist-for-agenda
12318 org-drawers-for-agenda
12319 org-tag-alist-for-agenda)
12321 (cond
12322 ((eq match t) (setq matcher t))
12323 ((eq match nil) (setq matcher t))
12324 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12326 (save-excursion
12327 (save-restriction
12328 (when (eq scope 'tree)
12329 (org-back-to-heading t)
12330 (org-narrow-to-subtree)
12331 (setq scope nil))
12333 (if (not scope)
12334 (progn
12335 (org-prepare-agenda-buffers
12336 (list (buffer-file-name (current-buffer))))
12337 (setq res (org-scan-tags func matcher)))
12338 ;; Get the right scope
12339 (cond
12340 ((and scope (listp scope) (symbolp (car scope)))
12341 (setq scope (eval scope)))
12342 ((eq scope 'agenda)
12343 (setq scope (org-agenda-files t)))
12344 ((eq scope 'agenda-with-archives)
12345 (setq scope (org-agenda-files t))
12346 (setq scope (org-add-archive-files scope)))
12347 ((eq scope 'file)
12348 (setq scope (list (buffer-file-name))))
12349 ((eq scope 'file-with-archives)
12350 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12351 (org-prepare-agenda-buffers scope)
12352 (while (setq file (pop scope))
12353 (with-current-buffer (org-find-base-buffer-visiting file)
12354 (save-excursion
12355 (save-restriction
12356 (widen)
12357 (goto-char (point-min))
12358 (setq res (append res (org-scan-tags func matcher))))))))))
12359 res))
12361 ;;;; Properties
12363 ;;; Setting and retrieving properties
12365 (defconst org-special-properties
12366 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12367 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
12368 "The special properties valid in Org-mode.
12370 These are properties that are not defined in the property drawer,
12371 but in some other way.")
12373 (defconst org-default-properties
12374 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12375 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12376 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12377 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12378 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12379 "CLOCK_MODELINE_TOTAL" "STYLE")
12380 "Some properties that are used by Org-mode for various purposes.
12381 Being in this list makes sure that they are offered for completion.")
12383 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12384 "Regular expression matching the first line of a property drawer.")
12386 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12387 "Regular expression matching the first line of a property drawer.")
12389 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12390 "Regular expression matching the first line of a property drawer.")
12392 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12393 "Regular expression matching the first line of a property drawer.")
12395 (defconst org-property-drawer-re
12396 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12397 org-property-end-re "\\)\n?")
12398 "Matches an entire property drawer.")
12400 (defconst org-clock-drawer-re
12401 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12402 org-property-end-re "\\)\n?")
12403 "Matches an entire clock drawer.")
12405 (defun org-property-action ()
12406 "Do an action on properties."
12407 (interactive)
12408 (let (c)
12409 (org-at-property-p)
12410 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12411 (setq c (read-char-exclusive))
12412 (cond
12413 ((equal c ?s)
12414 (call-interactively 'org-set-property))
12415 ((equal c ?d)
12416 (call-interactively 'org-delete-property))
12417 ((equal c ?D)
12418 (call-interactively 'org-delete-property-globally))
12419 ((equal c ?c)
12420 (call-interactively 'org-compute-property-at-point))
12421 (t (error "No such property action %c" c)))))
12423 (defun org-set-effort (&optional value)
12424 "Set the effort property of the current entry.
12425 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12426 allowed value."
12427 (interactive "P")
12428 (if (equal value 0) (setq value 10))
12429 (let* ((completion-ignore-case t)
12430 (prop org-effort-property)
12431 (cur (org-entry-get nil prop))
12432 (allowed (org-property-get-allowed-values nil prop 'table))
12433 (existing (mapcar 'list (org-property-values prop)))
12435 (val (cond
12436 ((stringp value) value)
12437 ((and allowed (integerp value))
12438 (or (car (nth (1- value) allowed))
12439 (car (org-last allowed))))
12440 (allowed
12441 (message "Select 1-9,0, [RET%s]: %s"
12442 (if cur (concat "=" cur) "")
12443 (mapconcat 'car allowed " "))
12444 (setq rpl (read-char-exclusive))
12445 (if (equal rpl ?\r)
12447 (setq rpl (- rpl ?0))
12448 (if (equal rpl 0) (setq rpl 10))
12449 (if (and (> rpl 0) (<= rpl (length allowed)))
12450 (car (nth (1- rpl) allowed))
12451 (org-completing-read "Effort: " allowed nil))))
12453 (let (org-completion-use-ido org-completion-use-iswitchb)
12454 (org-completing-read
12455 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12456 (concat "[" cur "]") "")
12457 ": ")
12458 existing nil nil "" nil cur))))))
12459 (unless (equal (org-entry-get nil prop) val)
12460 (org-entry-put nil prop val))
12461 (message "%s is now %s" prop val)))
12463 (defun org-at-property-p ()
12464 "Is the cursor in a property line?"
12465 ;; FIXME: Does not check if we are actually in the drawer.
12466 ;; FIXME: also returns true on any drawers.....
12467 ;; This is used by C-c C-c for property action.
12468 (save-excursion
12469 (beginning-of-line 1)
12470 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
12472 (defun org-get-property-block (&optional beg end force)
12473 "Return the (beg . end) range of the body of the property drawer.
12474 BEG and END can be beginning and end of subtree, if not given
12475 they will be found.
12476 If the drawer does not exist and FORCE is non-nil, create the drawer."
12477 (catch 'exit
12478 (save-excursion
12479 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12480 (end (or end (progn (outline-next-heading) (point)))))
12481 (goto-char beg)
12482 (if (re-search-forward org-property-start-re end t)
12483 (setq beg (1+ (match-end 0)))
12484 (if force
12485 (save-excursion
12486 (org-insert-property-drawer)
12487 (setq end (progn (outline-next-heading) (point))))
12488 (throw 'exit nil))
12489 (goto-char beg)
12490 (if (re-search-forward org-property-start-re end t)
12491 (setq beg (1+ (match-end 0)))))
12492 (if (re-search-forward org-property-end-re end t)
12493 (setq end (match-beginning 0))
12494 (or force (throw 'exit nil))
12495 (goto-char beg)
12496 (setq end beg)
12497 (org-indent-line-function)
12498 (insert ":END:\n"))
12499 (cons beg end)))))
12501 (defun org-entry-properties (&optional pom which specific)
12502 "Get all properties of the entry at point-or-marker POM.
12503 This includes the TODO keyword, the tags, time strings for deadline,
12504 scheduled, and clocking, and any additional properties defined in the
12505 entry. The return value is an alist, keys may occur multiple times
12506 if the property key was used several times.
12507 POM may also be nil, in which case the current entry is used.
12508 If WHICH is nil or `all', get all properties. If WHICH is
12509 `special' or `standard', only get that subclass. If WHICH
12510 is a string only get exactly this property. Specific can be a sting, the
12511 specific property we are interested in. Specifying it can speed
12512 things up because then unnecessary parsing is avoided."
12513 (setq which (or which 'all))
12514 (org-with-point-at pom
12515 (let ((clockstr (substring org-clock-string 0 -1))
12516 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
12517 beg end range props sum-props key value string clocksum)
12518 (save-excursion
12519 (when (condition-case nil
12520 (and (org-mode-p) (org-back-to-heading t))
12521 (error nil))
12522 (setq beg (point))
12523 (setq sum-props (get-text-property (point) 'org-summaries))
12524 (setq clocksum (get-text-property (point) :org-clock-minutes))
12525 (outline-next-heading)
12526 (setq end (point))
12527 (when (memq which '(all special))
12528 ;; Get the special properties, like TODO and tags
12529 (goto-char beg)
12530 (when (and (or (not specific) (string= specific "TODO"))
12531 (looking-at org-todo-line-regexp) (match-end 2))
12532 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12533 (when (and (or (not specific) (string= specific "PRIORITY"))
12534 (looking-at org-priority-regexp))
12535 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12536 (when (and (or (not specific) (string= specific "TAGS"))
12537 (setq value (org-get-tags-string))
12538 (string-match "\\S-" value))
12539 (push (cons "TAGS" value) props))
12540 (when (and (or (not specific) (string= specific "TAGS"))
12541 (setq value (org-get-tags-at)))
12542 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
12543 ":"))
12544 props))
12545 (when (or (not specific) (string= specific "TAGS"))
12546 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
12547 (when (or (not specific)
12548 (member specific org-all-time-keywords)
12549 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
12550 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12551 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12552 string (if (equal key clockstr)
12553 (org-no-properties
12554 (org-trim
12555 (buffer-substring
12556 (match-beginning 3) (goto-char (point-at-eol)))))
12557 (substring (org-match-string-no-properties 3) 1 -1)))
12558 (unless key
12559 (if (= (char-after (match-beginning 3)) ?\[)
12560 (setq key "TIMESTAMP_IA")
12561 (setq key "TIMESTAMP")))
12562 (when (or (equal key clockstr) (not (assoc key props)))
12563 (push (cons key string) props))))
12567 (when (memq which '(all standard))
12568 ;; Get the standard properties, like :PROP: ...
12569 (setq range (org-get-property-block beg end))
12570 (when range
12571 (goto-char (car range))
12572 (while (re-search-forward
12573 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12574 (cdr range) t)
12575 (setq key (org-match-string-no-properties 1)
12576 value (org-trim (or (org-match-string-no-properties 2) "")))
12577 (unless (member key excluded)
12578 (push (cons key (or value "")) props)))))
12579 (if clocksum
12580 (push (cons "CLOCKSUM"
12581 (org-columns-number-to-string (/ (float clocksum) 60.)
12582 'add_times))
12583 props))
12584 (unless (assoc "CATEGORY" props)
12585 (setq value (or (org-get-category)
12586 (progn (org-refresh-category-properties)
12587 (org-get-category))))
12588 (push (cons "CATEGORY" value) props))
12589 (append sum-props (nreverse props)))))))
12591 (defun org-entry-get (pom property &optional inherit)
12592 "Get value of PROPERTY for entry at point-or-marker POM.
12593 If INHERIT is non-nil and the entry does not have the property,
12594 then also check higher levels of the hierarchy.
12595 If INHERIT is the symbol `selective', use inheritance only if the setting
12596 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12597 If the property is present but empty, the return value is the empty string.
12598 If the property is not present at all, nil is returned."
12599 (org-with-point-at pom
12600 (if (and inherit (if (eq inherit 'selective)
12601 (org-property-inherit-p property)
12603 (org-entry-get-with-inheritance property)
12604 (if (member property org-special-properties)
12605 ;; We need a special property. Use `org-entry-properties' to
12606 ;; retrieve it, but specify the wanted property
12607 (cdr (assoc property (org-entry-properties nil 'special property)))
12608 (let ((range (org-get-property-block)))
12609 (if (and range
12610 (goto-char (car range))
12611 (re-search-forward
12612 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12613 (cdr range) t))
12614 ;; Found the property, return it.
12615 (if (match-end 1)
12616 (org-match-string-no-properties 1)
12617 "")))))))
12619 (defun org-property-or-variable-value (var &optional inherit)
12620 "Check if there is a property fixing the value of VAR.
12621 If yes, return this value. If not, return the current value of the variable."
12622 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12623 (if (and prop (stringp prop) (string-match "\\S-" prop))
12624 (read prop)
12625 (symbol-value var))))
12627 (defun org-entry-delete (pom property)
12628 "Delete the property PROPERTY from entry at point-or-marker POM."
12629 (org-with-point-at pom
12630 (if (member property org-special-properties)
12631 nil ; cannot delete these properties.
12632 (let ((range (org-get-property-block)))
12633 (if (and range
12634 (goto-char (car range))
12635 (re-search-forward
12636 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12637 (cdr range) t))
12638 (progn
12639 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12641 nil)))))
12643 ;; Multi-values properties are properties that contain multiple values
12644 ;; These values are assumed to be single words, separated by whitespace.
12645 (defun org-entry-add-to-multivalued-property (pom property value)
12646 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12647 (let* ((old (org-entry-get pom property))
12648 (values (and old (org-split-string old "[ \t]"))))
12649 (setq value (org-entry-protect-space value))
12650 (unless (member value values)
12651 (setq values (cons value values))
12652 (org-entry-put pom property
12653 (mapconcat 'identity values " ")))))
12655 (defun org-entry-remove-from-multivalued-property (pom property value)
12656 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12657 (let* ((old (org-entry-get pom property))
12658 (values (and old (org-split-string old "[ \t]"))))
12659 (setq value (org-entry-protect-space value))
12660 (when (member value values)
12661 (setq values (delete value values))
12662 (org-entry-put pom property
12663 (mapconcat 'identity values " ")))))
12665 (defun org-entry-member-in-multivalued-property (pom property value)
12666 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12667 (let* ((old (org-entry-get pom property))
12668 (values (and old (org-split-string old "[ \t]"))))
12669 (setq value (org-entry-protect-space value))
12670 (member value values)))
12672 (defun org-entry-get-multivalued-property (pom property)
12673 "Return a list of values in a multivalued property."
12674 (let* ((value (org-entry-get pom property))
12675 (values (and value (org-split-string value "[ \t]"))))
12676 (mapcar 'org-entry-restore-space values)))
12678 (defun org-entry-put-multivalued-property (pom property &rest values)
12679 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12680 VALUES should be a list of strings. Spaces will be protected."
12681 (org-entry-put pom property
12682 (mapconcat 'org-entry-protect-space values " "))
12683 (let* ((value (org-entry-get pom property))
12684 (values (and value (org-split-string value "[ \t]"))))
12685 (mapcar 'org-entry-restore-space values)))
12687 (defun org-entry-protect-space (s)
12688 "Protect spaces and newline in string S."
12689 (while (string-match " " s)
12690 (setq s (replace-match "%20" t t s)))
12691 (while (string-match "\n" s)
12692 (setq s (replace-match "%0A" t t s)))
12695 (defun org-entry-restore-space (s)
12696 "Restore spaces and newline in string S."
12697 (while (string-match "%20" s)
12698 (setq s (replace-match " " t t s)))
12699 (while (string-match "%0A" s)
12700 (setq s (replace-match "\n" t t s)))
12703 (defvar org-entry-property-inherited-from (make-marker)
12704 "Marker pointing to the entry from where a property was inherited.
12705 Each call to `org-entry-get-with-inheritance' will set this marker to the
12706 location of the entry where the inheritance search matched. If there was
12707 no match, the marker will point nowhere.
12708 Note that also `org-entry-get' calls this function, if the INHERIT flag
12709 is set.")
12711 (defun org-entry-get-with-inheritance (property)
12712 "Get entry property, and search higher levels if not present."
12713 (move-marker org-entry-property-inherited-from nil)
12714 (let (tmp)
12715 (save-excursion
12716 (save-restriction
12717 (widen)
12718 (catch 'ex
12719 (while t
12720 (when (setq tmp (org-entry-get nil property))
12721 (org-back-to-heading t)
12722 (move-marker org-entry-property-inherited-from (point))
12723 (throw 'ex tmp))
12724 (or (org-up-heading-safe) (throw 'ex nil)))))
12725 (or tmp
12726 (cdr (assoc property org-file-properties))
12727 (cdr (assoc property org-global-properties))
12728 (cdr (assoc property org-global-properties-fixed))))))
12730 (defvar org-property-changed-functions nil
12731 "Hook called when the value of a property has changed.
12732 Each hook function should accept two arguments, the name of the property
12733 and the new value.")
12735 (defun org-entry-put (pom property value)
12736 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12737 (org-with-point-at pom
12738 (org-back-to-heading t)
12739 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12740 range)
12741 (cond
12742 ((equal property "TODO")
12743 (when (and (stringp value) (string-match "\\S-" value)
12744 (not (member value org-todo-keywords-1)))
12745 (error "\"%s\" is not a valid TODO state" value))
12746 (if (or (not value)
12747 (not (string-match "\\S-" value)))
12748 (setq value 'none))
12749 (org-todo value)
12750 (org-set-tags nil 'align))
12751 ((equal property "PRIORITY")
12752 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12753 (string-to-char value) ?\ ))
12754 (org-set-tags nil 'align))
12755 ((equal property "SCHEDULED")
12756 (if (re-search-forward org-scheduled-time-regexp end t)
12757 (cond
12758 ((eq value 'earlier) (org-timestamp-change -1 'day))
12759 ((eq value 'later) (org-timestamp-change 1 'day))
12760 (t (call-interactively 'org-schedule)))
12761 (call-interactively 'org-schedule)))
12762 ((equal property "DEADLINE")
12763 (if (re-search-forward org-deadline-time-regexp end t)
12764 (cond
12765 ((eq value 'earlier) (org-timestamp-change -1 'day))
12766 ((eq value 'later) (org-timestamp-change 1 'day))
12767 (t (call-interactively 'org-deadline)))
12768 (call-interactively 'org-deadline)))
12769 ((member property org-special-properties)
12770 (error "The %s property can not yet be set with `org-entry-put'"
12771 property))
12772 (t ; a non-special property
12773 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12774 (setq range (org-get-property-block beg end 'force))
12775 (goto-char (car range))
12776 (if (re-search-forward
12777 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12778 (progn
12779 (delete-region (match-beginning 1) (match-end 1))
12780 (goto-char (match-beginning 1)))
12781 (goto-char (cdr range))
12782 (insert "\n")
12783 (backward-char 1)
12784 (org-indent-line-function)
12785 (insert ":" property ":"))
12786 (and value (insert " " value))
12787 (org-indent-line-function)))))
12788 (run-hook-with-args 'org-property-changed-functions property value)))
12790 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12791 "Get all property keys in the current buffer.
12792 With INCLUDE-SPECIALS, also list the special properties that reflect things
12793 like tags and TODO state.
12794 With INCLUDE-DEFAULTS, also include properties that has special meaning
12795 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12796 With INCLUDE-COLUMNS, also include property names given in COLUMN
12797 formats in the current buffer."
12798 (let (rtn range cfmt s p)
12799 (save-excursion
12800 (save-restriction
12801 (widen)
12802 (goto-char (point-min))
12803 (while (re-search-forward org-property-start-re nil t)
12804 (setq range (org-get-property-block))
12805 (goto-char (car range))
12806 (while (re-search-forward
12807 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12808 (cdr range) t)
12809 (add-to-list 'rtn (org-match-string-no-properties 1)))
12810 (outline-next-heading))))
12812 (when include-specials
12813 (setq rtn (append org-special-properties rtn)))
12815 (when include-defaults
12816 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12817 (add-to-list 'rtn org-effort-property))
12819 (when include-columns
12820 (save-excursion
12821 (save-restriction
12822 (widen)
12823 (goto-char (point-min))
12824 (while (re-search-forward
12825 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12826 nil t)
12827 (setq cfmt (match-string 2) s 0)
12828 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12829 cfmt s)
12830 (setq s (match-end 0)
12831 p (match-string 1 cfmt))
12832 (unless (or (equal p "ITEM")
12833 (member p org-special-properties))
12834 (add-to-list 'rtn (match-string 1 cfmt))))))))
12836 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12838 (defun org-property-values (key)
12839 "Return a list of all values of property KEY."
12840 (save-excursion
12841 (save-restriction
12842 (widen)
12843 (goto-char (point-min))
12844 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12845 values)
12846 (while (re-search-forward re nil t)
12847 (add-to-list 'values (org-trim (match-string 1))))
12848 (delete "" values)))))
12850 (defun org-insert-property-drawer ()
12851 "Insert a property drawer into the current entry."
12852 (interactive)
12853 (org-back-to-heading t)
12854 (looking-at outline-regexp)
12855 (let ((indent (if org-adapt-indentation
12856 (- (match-end 0)(match-beginning 0))
12858 (beg (point))
12859 (re (concat "^[ \t]*" org-keyword-time-regexp))
12860 end hiddenp)
12861 (outline-next-heading)
12862 (setq end (point))
12863 (goto-char beg)
12864 (while (re-search-forward re end t))
12865 (setq hiddenp (org-invisible-p))
12866 (end-of-line 1)
12867 (and (equal (char-after) ?\n) (forward-char 1))
12868 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12869 (if (member (match-string 1) '("CLOCK:" ":END:"))
12870 ;; just skip this line
12871 (beginning-of-line 2)
12872 ;; Drawer start, find the end
12873 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12874 (beginning-of-line 1)))
12875 (org-skip-over-state-notes)
12876 (skip-chars-backward " \t\n\r")
12877 (if (eq (char-before) ?*) (forward-char 1))
12878 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12879 (beginning-of-line 0)
12880 (org-indent-to-column indent)
12881 (beginning-of-line 2)
12882 (org-indent-to-column indent)
12883 (beginning-of-line 0)
12884 (if hiddenp
12885 (save-excursion
12886 (org-back-to-heading t)
12887 (hide-entry))
12888 (org-flag-drawer t))))
12890 (defun org-set-property (property value)
12891 "In the current entry, set PROPERTY to VALUE.
12892 When called interactively, this will prompt for a property name, offering
12893 completion on existing and default properties. And then it will prompt
12894 for a value, offering completion either on allowed values (via an inherited
12895 xxx_ALL property) or on existing values in other instances of this property
12896 in the current file."
12897 (interactive
12898 (let* ((completion-ignore-case t)
12899 (keys (org-buffer-property-keys nil t t))
12900 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12901 (prop (if (member prop0 keys)
12902 prop0
12903 (or (cdr (assoc (downcase prop0)
12904 (mapcar (lambda (x) (cons (downcase x) x))
12905 keys)))
12906 prop0)))
12907 (cur (org-entry-get nil prop))
12908 (allowed (org-property-get-allowed-values nil prop 'table))
12909 (existing (mapcar 'list (org-property-values prop)))
12910 (val (if allowed
12911 (org-completing-read "Value: " allowed nil
12912 (not (get-text-property 0 'org-unrestricted
12913 (caar allowed))))
12914 (let (org-completion-use-ido org-completion-use-iswitchb)
12915 (org-completing-read
12916 (concat "Value " (if (and cur (string-match "\\S-" cur))
12917 (concat "[" cur "]") "")
12918 ": ")
12919 existing nil nil "" nil cur)))))
12920 (list prop (if (equal val "") cur val))))
12921 (unless (equal (org-entry-get nil property) value)
12922 (org-entry-put nil property value)))
12924 (defun org-delete-property (property)
12925 "In the current entry, delete PROPERTY."
12926 (interactive
12927 (let* ((completion-ignore-case t)
12928 (prop (org-icompleting-read
12929 "Property: " (org-entry-properties nil 'standard))))
12930 (list prop)))
12931 (message "Property %s %s" property
12932 (if (org-entry-delete nil property)
12933 "deleted"
12934 "was not present in the entry")))
12936 (defun org-delete-property-globally (property)
12937 "Remove PROPERTY globally, from all entries."
12938 (interactive
12939 (let* ((completion-ignore-case t)
12940 (prop (org-icompleting-read
12941 "Globally remove property: "
12942 (mapcar 'list (org-buffer-property-keys)))))
12943 (list prop)))
12944 (save-excursion
12945 (save-restriction
12946 (widen)
12947 (goto-char (point-min))
12948 (let ((cnt 0))
12949 (while (re-search-forward
12950 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12951 nil t)
12952 (setq cnt (1+ cnt))
12953 (replace-match ""))
12954 (message "Property \"%s\" removed from %d entries" property cnt)))))
12956 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12958 (defun org-compute-property-at-point ()
12959 "Compute the property at point.
12960 This looks for an enclosing column format, extracts the operator and
12961 then applies it to the property in the column format's scope."
12962 (interactive)
12963 (unless (org-at-property-p)
12964 (error "Not at a property"))
12965 (let ((prop (org-match-string-no-properties 2)))
12966 (org-columns-get-format-and-top-level)
12967 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12968 (error "No operator defined for property %s" prop))
12969 (org-columns-compute prop)))
12971 (defvar org-property-allowed-value-functions nil
12972 "Hook for functions supplying allowed values for specific.
12973 The functions must take a single argument, the name of the property, and
12974 return a flat list of allowed values. If \":ETC\" is one of
12975 the values, this means that these values are intended as defaults for
12976 completion, but that other values should be allowed too.
12977 The functions must return nil if they are now responsible for this
12978 prioerty.")
12980 (defun org-property-get-allowed-values (pom property &optional table)
12981 "Get allowed values for the property PROPERTY.
12982 When TABLE is non-nil, return an alist that can directly be used for
12983 completion."
12984 (let (vals)
12985 (cond
12986 ((equal property "TODO")
12987 (setq vals (org-with-point-at pom
12988 (append org-todo-keywords-1 '("")))))
12989 ((equal property "PRIORITY")
12990 (let ((n org-lowest-priority))
12991 (while (>= n org-highest-priority)
12992 (push (char-to-string n) vals)
12993 (setq n (1- n)))))
12994 ((member property org-special-properties))
12995 ((setq vals (run-hook-with-args-until-success
12996 'org-property-allowed-value-functions property)))
12998 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12999 (when (and vals (string-match "\\S-" vals))
13000 (setq vals (car (read-from-string (concat "(" vals ")"))))
13001 (setq vals (mapcar (lambda (x)
13002 (cond ((stringp x) x)
13003 ((numberp x) (number-to-string x))
13004 ((symbolp x) (symbol-name x))
13005 (t "???")))
13006 vals)))))
13007 (when (member ":ETC" vals)
13008 (setq vals (remove ":ETC" vals))
13009 (org-add-props (car vals) '(org-unrestricted t)))
13010 (if table (mapcar 'list vals) vals)))
13012 (defun org-property-previous-allowed-value (&optional previous)
13013 "Switch to the next allowed value for this property."
13014 (interactive)
13015 (org-property-next-allowed-value t))
13017 (defun org-property-next-allowed-value (&optional previous)
13018 "Switch to the next allowed value for this property."
13019 (interactive)
13020 (unless (org-at-property-p)
13021 (error "Not at a property"))
13022 (let* ((key (match-string 2))
13023 (value (match-string 3))
13024 (allowed (or (org-property-get-allowed-values (point) key)
13025 (and (member value '("[ ]" "[-]" "[X]"))
13026 '("[ ]" "[X]"))))
13027 nval)
13028 (unless allowed
13029 (error "Allowed values for this property have not been defined"))
13030 (if previous (setq allowed (reverse allowed)))
13031 (if (member value allowed)
13032 (setq nval (car (cdr (member value allowed)))))
13033 (setq nval (or nval (car allowed)))
13034 (if (equal nval value)
13035 (error "Only one allowed value for this property"))
13036 (org-at-property-p)
13037 (replace-match (concat " :" key ": " nval) t t)
13038 (org-indent-line-function)
13039 (beginning-of-line 1)
13040 (skip-chars-forward " \t")
13041 (run-hook-with-args 'org-property-changed-functions key nval)))
13043 (defun org-find-entry-with-id (ident)
13044 "Locate the entry that contains the ID property with exact value IDENT.
13045 IDENT can be a string, a symbol or a number, this function will search for
13046 the string representation of it.
13047 Return the position where this entry starts, or nil if there is no such entry."
13048 (interactive "sID: ")
13049 (let ((id (cond
13050 ((stringp ident) ident)
13051 ((symbol-name ident) (symbol-name ident))
13052 ((numberp ident) (number-to-string ident))
13053 (t (error "IDENT %s must be a string, symbol or number" ident))))
13054 (case-fold-search nil))
13055 (save-excursion
13056 (save-restriction
13057 (widen)
13058 (goto-char (point-min))
13059 (when (re-search-forward
13060 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13061 nil t)
13062 (org-back-to-heading t)
13063 (point))))))
13065 ;;;; Timestamps
13067 (defvar org-last-changed-timestamp nil)
13068 (defvar org-last-inserted-timestamp nil
13069 "The last time stamp inserted with `org-insert-time-stamp'.")
13070 (defvar org-time-was-given) ; dynamically scoped parameter
13071 (defvar org-end-time-was-given) ; dynamically scoped parameter
13072 (defvar org-ts-what) ; dynamically scoped parameter
13074 (defun org-time-stamp (arg &optional inactive)
13075 "Prompt for a date/time and insert a time stamp.
13076 If the user specifies a time like HH:MM, or if this command is called
13077 with a prefix argument, the time stamp will contain date and time.
13078 Otherwise, only the date will be included. All parts of a date not
13079 specified by the user will be filled in from the current date/time.
13080 So if you press just return without typing anything, the time stamp
13081 will represent the current date/time. If there is already a timestamp
13082 at the cursor, it will be modified."
13083 (interactive "P")
13084 (let* ((ts nil)
13085 (default-time
13086 ;; Default time is either today, or, when entering a range,
13087 ;; the range start.
13088 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13089 (save-excursion
13090 (re-search-backward
13091 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13092 (- (point) 20) t)))
13093 (apply 'encode-time (org-parse-time-string (match-string 1)))
13094 (current-time)))
13095 (default-input (and ts (org-get-compact-tod ts)))
13096 org-time-was-given org-end-time-was-given time)
13097 (cond
13098 ((and (org-at-timestamp-p t)
13099 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13100 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13101 (insert "--")
13102 (setq time (let ((this-command this-command))
13103 (org-read-date arg 'totime nil nil
13104 default-time default-input)))
13105 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13106 ((org-at-timestamp-p t)
13107 (setq time (let ((this-command this-command))
13108 (org-read-date arg 'totime nil nil default-time default-input)))
13109 (when (org-at-timestamp-p t) ; just to get the match data
13110 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13111 (replace-match "")
13112 (setq org-last-changed-timestamp
13113 (org-insert-time-stamp
13114 time (or org-time-was-given arg)
13115 inactive nil nil (list org-end-time-was-given))))
13116 (message "Timestamp updated"))
13118 (setq time (let ((this-command this-command))
13119 (org-read-date arg 'totime nil nil default-time default-input)))
13120 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13121 nil nil (list org-end-time-was-given))))))
13123 ;; FIXME: can we use this for something else, like computing time differences?
13124 (defun org-get-compact-tod (s)
13125 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13126 (let* ((t1 (match-string 1 s))
13127 (h1 (string-to-number (match-string 2 s)))
13128 (m1 (string-to-number (match-string 3 s)))
13129 (t2 (and (match-end 4) (match-string 5 s)))
13130 (h2 (and t2 (string-to-number (match-string 6 s))))
13131 (m2 (and t2 (string-to-number (match-string 7 s))))
13132 dh dm)
13133 (if (not t2)
13135 (setq dh (- h2 h1) dm (- m2 m1))
13136 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13137 (concat t1 "+" (number-to-string dh)
13138 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13140 (defun org-time-stamp-inactive (&optional arg)
13141 "Insert an inactive time stamp.
13142 An inactive time stamp is enclosed in square brackets instead of angle
13143 brackets. It is inactive in the sense that it does not trigger agenda entries,
13144 does not link to the calendar and cannot be changed with the S-cursor keys.
13145 So these are more for recording a certain time/date."
13146 (interactive "P")
13147 (org-time-stamp arg 'inactive))
13149 (defvar org-date-ovl (org-make-overlay 1 1))
13150 (org-overlay-put org-date-ovl 'face 'org-warning)
13151 (org-detach-overlay org-date-ovl)
13153 (defvar org-ans1) ; dynamically scoped parameter
13154 (defvar org-ans2) ; dynamically scoped parameter
13156 (defvar org-plain-time-of-day-regexp) ; defined below
13158 (defvar org-overriding-default-time nil) ; dynamically scoped
13159 (defvar org-read-date-overlay nil)
13160 (defvar org-dcst nil) ; dynamically scoped
13161 (defvar org-read-date-history nil)
13162 (defvar org-read-date-final-answer nil)
13164 (defun org-read-date (&optional with-time to-time from-string prompt
13165 default-time default-input)
13166 "Read a date, possibly a time, and make things smooth for the user.
13167 The prompt will suggest to enter an ISO date, but you can also enter anything
13168 which will at least partially be understood by `parse-time-string'.
13169 Unrecognized parts of the date will default to the current day, month, year,
13170 hour and minute. If this command is called to replace a timestamp at point,
13171 of to enter the second timestamp of a range, the default time is taken from the
13172 existing stamp. For example,
13173 3-2-5 --> 2003-02-05
13174 feb 15 --> currentyear-02-15
13175 sep 12 9 --> 2009-09-12
13176 12:45 --> today 12:45
13177 22 sept 0:34 --> currentyear-09-22 0:34
13178 12 --> currentyear-currentmonth-12
13179 Fri --> nearest Friday (today or later)
13180 etc.
13182 Furthermore you can specify a relative date by giving, as the *first* thing
13183 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13184 change in days weeks, months, years.
13185 With a single plus or minus, the date is relative to today. With a double
13186 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13187 +4d --> four days from today
13188 +4 --> same as above
13189 +2w --> two weeks from today
13190 ++5 --> five days from default date
13192 The function understands only English month and weekday abbreviations,
13193 but this can be configured with the variables `parse-time-months' and
13194 `parse-time-weekdays'.
13196 While prompting, a calendar is popped up - you can also select the
13197 date with the mouse (button 1). The calendar shows a period of three
13198 months. To scroll it to other months, use the keys `>' and `<'.
13199 If you don't like the calendar, turn it off with
13200 \(setq org-read-date-popup-calendar nil)
13202 With optional argument TO-TIME, the date will immediately be converted
13203 to an internal time.
13204 With an optional argument WITH-TIME, the prompt will suggest to also
13205 insert a time. Note that when WITH-TIME is not set, you can still
13206 enter a time, and this function will inform the calling routine about
13207 this change. The calling routine may then choose to change the format
13208 used to insert the time stamp into the buffer to include the time.
13209 With optional argument FROM-STRING, read from this string instead from
13210 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13211 the time/date that is used for everything that is not specified by the
13212 user."
13213 (require 'parse-time)
13214 (let* ((org-time-stamp-rounding-minutes
13215 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13216 (org-dcst org-display-custom-times)
13217 (ct (org-current-time))
13218 (def (or org-overriding-default-time default-time ct))
13219 (defdecode (decode-time def))
13220 (dummy (progn
13221 (when (< (nth 2 defdecode) org-extend-today-until)
13222 (setcar (nthcdr 2 defdecode) -1)
13223 (setcar (nthcdr 1 defdecode) 59)
13224 (setq def (apply 'encode-time defdecode)
13225 defdecode (decode-time def)))))
13226 (calendar-frame-setup nil)
13227 (calendar-move-hook nil)
13228 (calendar-view-diary-initially-flag nil)
13229 (view-diary-entries-initially nil)
13230 (calendar-view-holidays-initially-flag nil)
13231 (view-calendar-holidays-initially nil)
13232 (timestr (format-time-string
13233 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
13234 (prompt (concat (if prompt (concat prompt " ") "")
13235 (format "Date+time [%s]: " timestr)))
13236 ans (org-ans0 "") org-ans1 org-ans2 final)
13238 (cond
13239 (from-string (setq ans from-string))
13240 (org-read-date-popup-calendar
13241 (save-excursion
13242 (save-window-excursion
13243 (calendar)
13244 (calendar-forward-day (- (time-to-days def)
13245 (calendar-absolute-from-gregorian
13246 (calendar-current-date))))
13247 (org-eval-in-calendar nil t)
13248 (let* ((old-map (current-local-map))
13249 (map (copy-keymap calendar-mode-map))
13250 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13251 (org-defkey map (kbd "RET") 'org-calendar-select)
13252 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
13253 'org-calendar-select-mouse)
13254 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
13255 'org-calendar-select-mouse)
13256 (org-defkey minibuffer-local-map [(meta shift left)]
13257 (lambda () (interactive)
13258 (org-eval-in-calendar '(calendar-backward-month 1))))
13259 (org-defkey minibuffer-local-map [(meta shift right)]
13260 (lambda () (interactive)
13261 (org-eval-in-calendar '(calendar-forward-month 1))))
13262 (org-defkey minibuffer-local-map [(meta shift up)]
13263 (lambda () (interactive)
13264 (org-eval-in-calendar '(calendar-backward-year 1))))
13265 (org-defkey minibuffer-local-map [(meta shift down)]
13266 (lambda () (interactive)
13267 (org-eval-in-calendar '(calendar-forward-year 1))))
13268 (org-defkey minibuffer-local-map [?\e (shift left)]
13269 (lambda () (interactive)
13270 (org-eval-in-calendar '(calendar-backward-month 1))))
13271 (org-defkey minibuffer-local-map [?\e (shift right)]
13272 (lambda () (interactive)
13273 (org-eval-in-calendar '(calendar-forward-month 1))))
13274 (org-defkey minibuffer-local-map [?\e (shift up)]
13275 (lambda () (interactive)
13276 (org-eval-in-calendar '(calendar-backward-year 1))))
13277 (org-defkey minibuffer-local-map [?\e (shift down)]
13278 (lambda () (interactive)
13279 (org-eval-in-calendar '(calendar-forward-year 1))))
13280 (org-defkey minibuffer-local-map [(shift up)]
13281 (lambda () (interactive)
13282 (org-eval-in-calendar '(calendar-backward-week 1))))
13283 (org-defkey minibuffer-local-map [(shift down)]
13284 (lambda () (interactive)
13285 (org-eval-in-calendar '(calendar-forward-week 1))))
13286 (org-defkey minibuffer-local-map [(shift left)]
13287 (lambda () (interactive)
13288 (org-eval-in-calendar '(calendar-backward-day 1))))
13289 (org-defkey minibuffer-local-map [(shift right)]
13290 (lambda () (interactive)
13291 (org-eval-in-calendar '(calendar-forward-day 1))))
13292 (org-defkey minibuffer-local-map ">"
13293 (lambda () (interactive)
13294 (org-eval-in-calendar '(scroll-calendar-left 1))))
13295 (org-defkey minibuffer-local-map "<"
13296 (lambda () (interactive)
13297 (org-eval-in-calendar '(scroll-calendar-right 1))))
13298 (run-hooks 'org-read-date-minibuffer-setup-hook)
13299 (unwind-protect
13300 (progn
13301 (use-local-map map)
13302 (add-hook 'post-command-hook 'org-read-date-display)
13303 (setq org-ans0 (read-string prompt default-input
13304 'org-read-date-history nil))
13305 ;; org-ans0: from prompt
13306 ;; org-ans1: from mouse click
13307 ;; org-ans2: from calendar motion
13308 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13309 (remove-hook 'post-command-hook 'org-read-date-display)
13310 (use-local-map old-map)
13311 (when org-read-date-overlay
13312 (org-delete-overlay org-read-date-overlay)
13313 (setq org-read-date-overlay nil)))))))
13315 (t ; Naked prompt only
13316 (unwind-protect
13317 (setq ans (read-string prompt default-input
13318 'org-read-date-history timestr))
13319 (when org-read-date-overlay
13320 (org-delete-overlay org-read-date-overlay)
13321 (setq org-read-date-overlay nil)))))
13323 (setq final (org-read-date-analyze ans def defdecode))
13324 (setq org-read-date-final-answer ans)
13326 (if to-time
13327 (apply 'encode-time final)
13328 (if (and (boundp 'org-time-was-given) org-time-was-given)
13329 (format "%04d-%02d-%02d %02d:%02d"
13330 (nth 5 final) (nth 4 final) (nth 3 final)
13331 (nth 2 final) (nth 1 final))
13332 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13334 (defvar def)
13335 (defvar defdecode)
13336 (defvar with-time)
13337 (defvar org-read-date-analyze-futurep nil)
13338 (defun org-read-date-display ()
13339 "Display the current date prompt interpretation in the minibuffer."
13340 (when org-read-date-display-live
13341 (when org-read-date-overlay
13342 (org-delete-overlay org-read-date-overlay))
13343 (let ((p (point)))
13344 (end-of-line 1)
13345 (while (not (equal (buffer-substring
13346 (max (point-min) (- (point) 4)) (point))
13347 " "))
13348 (insert " "))
13349 (goto-char p))
13350 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13351 " " (or org-ans1 org-ans2)))
13352 (org-end-time-was-given nil)
13353 (f (org-read-date-analyze ans def defdecode))
13354 (fmts (if org-dcst
13355 org-time-stamp-custom-formats
13356 org-time-stamp-formats))
13357 (fmt (if (or with-time
13358 (and (boundp 'org-time-was-given) org-time-was-given))
13359 (cdr fmts)
13360 (car fmts)))
13361 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13362 (when (and org-end-time-was-given
13363 (string-match org-plain-time-of-day-regexp txt))
13364 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13365 org-end-time-was-given
13366 (substring txt (match-end 0)))))
13367 (when org-read-date-analyze-futurep
13368 (setq txt (concat txt " (=>F)")))
13369 (setq org-read-date-overlay
13370 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13371 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13373 (defun org-read-date-analyze (ans def defdecode)
13374 "Analyse the combined answer of the date prompt."
13375 ;; FIXME: cleanup and comment
13376 (let ((nowdecode (decode-time (current-time)))
13377 delta deltan deltaw deltadef year month day
13378 hour minute second wday pm h2 m2 tl wday1
13379 iso-year iso-weekday iso-week iso-year iso-date futurep)
13380 (setq org-read-date-analyze-futurep nil)
13381 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13382 (setq ans "+0"))
13384 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13385 (setq ans (replace-match "" t t ans)
13386 deltan (car delta)
13387 deltaw (nth 1 delta)
13388 deltadef (nth 2 delta)))
13390 ;; Check if there is an iso week date in there
13391 ;; If yes, store the info and postpone interpreting it until the rest
13392 ;; of the parsing is done
13393 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13394 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
13395 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
13396 iso-week (string-to-number (match-string 2 ans)))
13397 (setq ans (replace-match "" t t ans)))
13399 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
13400 (when (string-match
13401 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13402 (setq year (if (match-end 2)
13403 (string-to-number (match-string 2 ans))
13404 (string-to-number (format-time-string "%Y")))
13405 month (string-to-number (match-string 3 ans))
13406 day (string-to-number (match-string 4 ans)))
13407 (if (< year 100) (setq year (+ 2000 year)))
13408 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13409 t nil ans)))
13410 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13411 ;; If there is a time with am/pm, and *no* time without it, we convert
13412 ;; so that matching will be successful.
13413 (loop for i from 1 to 2 do ; twice, for end time as well
13414 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13415 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13416 (setq hour (string-to-number (match-string 1 ans))
13417 minute (if (match-end 3)
13418 (string-to-number (match-string 3 ans))
13420 pm (equal ?p
13421 (string-to-char (downcase (match-string 4 ans)))))
13422 (if (and (= hour 12) (not pm))
13423 (setq hour 0)
13424 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13425 (setq ans (replace-match (format "%02d:%02d" hour minute)
13426 t t ans))))
13428 ;; Check if a time range is given as a duration
13429 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13430 (setq hour (string-to-number (match-string 1 ans))
13431 h2 (+ hour (string-to-number (match-string 3 ans)))
13432 minute (string-to-number (match-string 2 ans))
13433 m2 (+ minute (if (match-end 5) (string-to-number
13434 (match-string 5 ans))0)))
13435 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13436 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13437 t t ans)))
13439 ;; Check if there is a time range
13440 (when (boundp 'org-end-time-was-given)
13441 (setq org-time-was-given nil)
13442 (when (and (string-match org-plain-time-of-day-regexp ans)
13443 (match-end 8))
13444 (setq org-end-time-was-given (match-string 8 ans))
13445 (setq ans (concat (substring ans 0 (match-beginning 7))
13446 (substring ans (match-end 7))))))
13448 (setq tl (parse-time-string ans)
13449 day (or (nth 3 tl) (nth 3 defdecode))
13450 month (or (nth 4 tl)
13451 (if (and org-read-date-prefer-future
13452 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
13453 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
13454 (nth 4 defdecode)))
13455 year (or (nth 5 tl)
13456 (if (and org-read-date-prefer-future
13457 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
13458 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
13459 (nth 5 defdecode)))
13460 hour (or (nth 2 tl) (nth 2 defdecode))
13461 minute (or (nth 1 tl) (nth 1 defdecode))
13462 second (or (nth 0 tl) 0)
13463 wday (nth 6 tl))
13465 (when (and (eq org-read-date-prefer-future 'time)
13466 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13467 (equal day (nth 3 nowdecode))
13468 (equal month (nth 4 nowdecode))
13469 (equal year (nth 5 nowdecode))
13470 (nth 2 tl)
13471 (or (< (nth 2 tl) (nth 2 nowdecode))
13472 (and (= (nth 2 tl) (nth 2 nowdecode))
13473 (nth 1 tl)
13474 (< (nth 1 tl) (nth 1 nowdecode)))))
13475 (setq day (1+ day)
13476 futurep t))
13478 ;; Special date definitions below
13479 (cond
13480 (iso-week
13481 ;; There was an iso week
13482 (setq futurep nil)
13483 (setq year (or iso-year year)
13484 day (or iso-weekday wday 1)
13485 wday nil ; to make sure that the trigger below does not match
13486 iso-date (calendar-gregorian-from-absolute
13487 (calendar-absolute-from-iso
13488 (list iso-week day year))))
13489 ; FIXME: Should we also push ISO weeks into the future?
13490 ; (when (and org-read-date-prefer-future
13491 ; (not iso-year)
13492 ; (< (calendar-absolute-from-gregorian iso-date)
13493 ; (time-to-days (current-time))))
13494 ; (setq year (1+ year)
13495 ; iso-date (calendar-gregorian-from-absolute
13496 ; (calendar-absolute-from-iso
13497 ; (list iso-week day year)))))
13498 (setq month (car iso-date)
13499 year (nth 2 iso-date)
13500 day (nth 1 iso-date)))
13501 (deltan
13502 (setq futurep nil)
13503 (unless deltadef
13504 (let ((now (decode-time (current-time))))
13505 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13506 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13507 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13508 ((equal deltaw "m") (setq month (+ month deltan)))
13509 ((equal deltaw "y") (setq year (+ year deltan)))))
13510 ((and wday (not (nth 3 tl)))
13511 (setq futurep nil)
13512 ;; Weekday was given, but no day, so pick that day in the week
13513 ;; on or after the derived date.
13514 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13515 (unless (equal wday wday1)
13516 (setq day (+ day (% (- wday wday1 -7) 7))))))
13517 (if (and (boundp 'org-time-was-given)
13518 (nth 2 tl))
13519 (setq org-time-was-given t))
13520 (if (< year 100) (setq year (+ 2000 year)))
13521 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13522 (setq org-read-date-analyze-futurep futurep)
13523 (list second minute hour day month year)))
13525 (defvar parse-time-weekdays)
13527 (defun org-read-date-get-relative (s today default)
13528 "Check string S for special relative date string.
13529 TODAY and DEFAULT are internal times, for today and for a default.
13530 Return shift list (N what def-flag)
13531 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13532 N is the number of WHATs to shift.
13533 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13534 the DEFAULT date rather than TODAY."
13535 (when (and
13536 (string-match
13537 (concat
13538 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13539 "\\([0-9]+\\)?"
13540 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13541 "\\([ \t]\\|$\\)") s)
13542 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13543 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13544 (string-to-char (substring (match-string 1 s) -1))
13545 ?+))
13546 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13547 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13548 (what (if (match-end 3) (match-string 3 s) "d"))
13549 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13550 (date (if rel default today))
13551 (wday (nth 6 (decode-time date)))
13552 delta)
13553 (if wday1
13554 (progn
13555 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13556 (if (= dir ?-) (setq delta (- delta 7)))
13557 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13558 (list delta "d" rel))
13559 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13561 (defun org-eval-in-calendar (form &optional keepdate)
13562 "Eval FORM in the calendar window and return to current window.
13563 Also, store the cursor date in variable org-ans2."
13564 (let ((sf (selected-frame))
13565 (sw (selected-window)))
13566 (select-window (get-buffer-window "*Calendar*" t))
13567 (eval form)
13568 (when (and (not keepdate) (calendar-cursor-to-date))
13569 (let* ((date (calendar-cursor-to-date))
13570 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13571 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13572 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13573 (select-window sw)
13574 (org-select-frame-set-input-focus sf)))
13576 (defun org-calendar-select ()
13577 "Return to `org-read-date' with the date currently selected.
13578 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13579 (interactive)
13580 (when (calendar-cursor-to-date)
13581 (let* ((date (calendar-cursor-to-date))
13582 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13583 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13584 (if (active-minibuffer-window) (exit-minibuffer))))
13586 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13587 "Insert a date stamp for the date given by the internal TIME.
13588 WITH-HM means, use the stamp format that includes the time of the day.
13589 INACTIVE means use square brackets instead of angular ones, so that the
13590 stamp will not contribute to the agenda.
13591 PRE and POST are optional strings to be inserted before and after the
13592 stamp.
13593 The command returns the inserted time stamp."
13594 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13595 stamp)
13596 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13597 (insert-before-markers (or pre ""))
13598 (insert-before-markers (setq stamp (format-time-string fmt time)))
13599 (when (listp extra)
13600 (setq extra (car extra))
13601 (if (and (stringp extra)
13602 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13603 (setq extra (format "-%02d:%02d"
13604 (string-to-number (match-string 1 extra))
13605 (string-to-number (match-string 2 extra))))
13606 (setq extra nil)))
13607 (when extra
13608 (backward-char 1)
13609 (insert-before-markers extra)
13610 (forward-char 1))
13611 (insert-before-markers (or post ""))
13612 (setq org-last-inserted-timestamp stamp)))
13614 (defun org-toggle-time-stamp-overlays ()
13615 "Toggle the use of custom time stamp formats."
13616 (interactive)
13617 (setq org-display-custom-times (not org-display-custom-times))
13618 (unless org-display-custom-times
13619 (let ((p (point-min)) (bmp (buffer-modified-p)))
13620 (while (setq p (next-single-property-change p 'display))
13621 (if (and (get-text-property p 'display)
13622 (eq (get-text-property p 'face) 'org-date))
13623 (remove-text-properties
13624 p (setq p (next-single-property-change p 'display))
13625 '(display t))))
13626 (set-buffer-modified-p bmp)))
13627 (if (featurep 'xemacs)
13628 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13629 (org-restart-font-lock)
13630 (setq org-table-may-need-update t)
13631 (if org-display-custom-times
13632 (message "Time stamps are overlayed with custom format")
13633 (message "Time stamp overlays removed")))
13635 (defun org-display-custom-time (beg end)
13636 "Overlay modified time stamp format over timestamp between BEG and END."
13637 (let* ((ts (buffer-substring beg end))
13638 t1 w1 with-hm tf time str w2 (off 0))
13639 (save-match-data
13640 (setq t1 (org-parse-time-string ts t))
13641 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13642 (setq off (- (match-end 0) (match-beginning 0)))))
13643 (setq end (- end off))
13644 (setq w1 (- end beg)
13645 with-hm (and (nth 1 t1) (nth 2 t1))
13646 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13647 time (org-fix-decoded-time t1)
13648 str (org-add-props
13649 (format-time-string
13650 (substring tf 1 -1) (apply 'encode-time time))
13651 nil 'mouse-face 'highlight)
13652 w2 (length str))
13653 (if (not (= w2 w1))
13654 (add-text-properties (1+ beg) (+ 2 beg)
13655 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13656 (if (featurep 'xemacs)
13657 (progn
13658 (put-text-property beg end 'invisible t)
13659 (put-text-property beg end 'end-glyph (make-glyph str)))
13660 (put-text-property beg end 'display str))))
13662 (defun org-translate-time (string)
13663 "Translate all timestamps in STRING to custom format.
13664 But do this only if the variable `org-display-custom-times' is set."
13665 (when org-display-custom-times
13666 (save-match-data
13667 (let* ((start 0)
13668 (re org-ts-regexp-both)
13669 t1 with-hm inactive tf time str beg end)
13670 (while (setq start (string-match re string start))
13671 (setq beg (match-beginning 0)
13672 end (match-end 0)
13673 t1 (save-match-data
13674 (org-parse-time-string (substring string beg end) t))
13675 with-hm (and (nth 1 t1) (nth 2 t1))
13676 inactive (equal (substring string beg (1+ beg)) "[")
13677 tf (funcall (if with-hm 'cdr 'car)
13678 org-time-stamp-custom-formats)
13679 time (org-fix-decoded-time t1)
13680 str (format-time-string
13681 (concat
13682 (if inactive "[" "<") (substring tf 1 -1)
13683 (if inactive "]" ">"))
13684 (apply 'encode-time time))
13685 string (replace-match str t t string)
13686 start (+ start (length str)))))))
13687 string)
13689 (defun org-fix-decoded-time (time)
13690 "Set 0 instead of nil for the first 6 elements of time.
13691 Don't touch the rest."
13692 (let ((n 0))
13693 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13695 (defun org-days-to-time (timestamp-string)
13696 "Difference between TIMESTAMP-STRING and now in days."
13697 (- (time-to-days (org-time-string-to-time timestamp-string))
13698 (time-to-days (current-time))))
13700 (defun org-deadline-close (timestamp-string &optional ndays)
13701 "Is the time in TIMESTAMP-STRING close to the current date?"
13702 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13703 (and (< (org-days-to-time timestamp-string) ndays)
13704 (not (org-entry-is-done-p))))
13706 (defun org-get-wdays (ts)
13707 "Get the deadline lead time appropriate for timestring TS."
13708 (cond
13709 ((<= org-deadline-warning-days 0)
13710 ;; 0 or negative, enforce this value no matter what
13711 (- org-deadline-warning-days))
13712 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13713 ;; lead time is specified.
13714 (floor (* (string-to-number (match-string 1 ts))
13715 (cdr (assoc (match-string 2 ts)
13716 '(("d" . 1) ("w" . 7)
13717 ("m" . 30.4) ("y" . 365.25)))))))
13718 ;; go for the default.
13719 (t org-deadline-warning-days)))
13721 (defun org-calendar-select-mouse (ev)
13722 "Return to `org-read-date' with the date currently selected.
13723 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13724 (interactive "e")
13725 (mouse-set-point ev)
13726 (when (calendar-cursor-to-date)
13727 (let* ((date (calendar-cursor-to-date))
13728 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13729 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13730 (if (active-minibuffer-window) (exit-minibuffer))))
13732 (defun org-check-deadlines (ndays)
13733 "Check if there are any deadlines due or past due.
13734 A deadline is considered due if it happens within `org-deadline-warning-days'
13735 days from today's date. If the deadline appears in an entry marked DONE,
13736 it is not shown. The prefix arg NDAYS can be used to test that many
13737 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13738 (interactive "P")
13739 (let* ((org-warn-days
13740 (cond
13741 ((equal ndays '(4)) 100000)
13742 (ndays (prefix-numeric-value ndays))
13743 (t (abs org-deadline-warning-days))))
13744 (case-fold-search nil)
13745 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13746 (callback
13747 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13749 (message "%d deadlines past-due or due within %d days"
13750 (org-occur regexp nil callback)
13751 org-warn-days)))
13753 (defun org-check-before-date (date)
13754 "Check if there are deadlines or scheduled entries before DATE."
13755 (interactive (list (org-read-date)))
13756 (let ((case-fold-search nil)
13757 (regexp (concat "\\<\\(" org-deadline-string
13758 "\\|" org-scheduled-string
13759 "\\) *<\\([^>]+\\)>"))
13760 (callback
13761 (lambda () (time-less-p
13762 (org-time-string-to-time (match-string 2))
13763 (org-time-string-to-time date)))))
13764 (message "%d entries before %s"
13765 (org-occur regexp nil callback) date)))
13767 (defun org-check-after-date (date)
13768 "Check if there are deadlines or scheduled entries after DATE."
13769 (interactive (list (org-read-date)))
13770 (let ((case-fold-search nil)
13771 (regexp (concat "\\<\\(" org-deadline-string
13772 "\\|" org-scheduled-string
13773 "\\) *<\\([^>]+\\)>"))
13774 (callback
13775 (lambda () (not
13776 (time-less-p
13777 (org-time-string-to-time (match-string 2))
13778 (org-time-string-to-time date))))))
13779 (message "%d entries after %s"
13780 (org-occur regexp nil callback) date)))
13782 (defun org-evaluate-time-range (&optional to-buffer)
13783 "Evaluate a time range by computing the difference between start and end.
13784 Normally the result is just printed in the echo area, but with prefix arg
13785 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13786 If the time range is actually in a table, the result is inserted into the
13787 next column.
13788 For time difference computation, a year is assumed to be exactly 365
13789 days in order to avoid rounding problems."
13790 (interactive "P")
13792 (org-clock-update-time-maybe)
13793 (save-excursion
13794 (unless (org-at-date-range-p t)
13795 (goto-char (point-at-bol))
13796 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13797 (if (not (org-at-date-range-p t))
13798 (error "Not at a time-stamp range, and none found in current line")))
13799 (let* ((ts1 (match-string 1))
13800 (ts2 (match-string 2))
13801 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13802 (match-end (match-end 0))
13803 (time1 (org-time-string-to-time ts1))
13804 (time2 (org-time-string-to-time ts2))
13805 (t1 (org-float-time time1))
13806 (t2 (org-float-time time2))
13807 (diff (abs (- t2 t1)))
13808 (negative (< (- t2 t1) 0))
13809 ;; (ys (floor (* 365 24 60 60)))
13810 (ds (* 24 60 60))
13811 (hs (* 60 60))
13812 (fy "%dy %dd %02d:%02d")
13813 (fy1 "%dy %dd")
13814 (fd "%dd %02d:%02d")
13815 (fd1 "%dd")
13816 (fh "%02d:%02d")
13817 y d h m align)
13818 (if havetime
13819 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13821 d (floor (/ diff ds)) diff (mod diff ds)
13822 h (floor (/ diff hs)) diff (mod diff hs)
13823 m (floor (/ diff 60)))
13824 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13826 d (floor (+ (/ diff ds) 0.5))
13827 h 0 m 0))
13828 (if (not to-buffer)
13829 (message "%s" (org-make-tdiff-string y d h m))
13830 (if (org-at-table-p)
13831 (progn
13832 (goto-char match-end)
13833 (setq align t)
13834 (and (looking-at " *|") (goto-char (match-end 0))))
13835 (goto-char match-end))
13836 (if (looking-at
13837 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13838 (replace-match ""))
13839 (if negative (insert " -"))
13840 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13841 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13842 (insert " " (format fh h m))))
13843 (if align (org-table-align))
13844 (message "Time difference inserted")))))
13846 (defun org-make-tdiff-string (y d h m)
13847 (let ((fmt "")
13848 (l nil))
13849 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13850 l (push y l)))
13851 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13852 l (push d l)))
13853 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13854 l (push h l)))
13855 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13856 l (push m l)))
13857 (apply 'format fmt (nreverse l))))
13859 (defun org-time-string-to-time (s)
13860 (apply 'encode-time (org-parse-time-string s)))
13861 (defun org-time-string-to-seconds (s)
13862 (org-float-time (org-time-string-to-time s)))
13864 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13865 "Convert a time stamp to an absolute day number.
13866 If there is a specifyer for a cyclic time stamp, get the closest date to
13867 DAYNR.
13868 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13869 the variable date is bound by the calendar when this is called."
13870 (cond
13871 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13872 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13873 daynr
13874 (+ daynr 1000)))
13875 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13876 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13877 (time-to-days (current-time))) (match-string 0 s)
13878 prefer show-all))
13879 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13881 (defun org-days-to-iso-week (days)
13882 "Return the iso week number."
13883 (require 'cal-iso)
13884 (car (calendar-iso-from-absolute days)))
13886 (defun org-small-year-to-year (year)
13887 "Convert 2-digit years into 4-digit years.
13888 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13889 The year 2000 cannot be abbreviated. Any year larger than 99
13890 is returned unchanged."
13891 (if (< year 38)
13892 (setq year (+ 2000 year))
13893 (if (< year 100)
13894 (setq year (+ 1900 year))))
13895 year)
13897 (defun org-time-from-absolute (d)
13898 "Return the time corresponding to date D.
13899 D may be an absolute day number, or a calendar-type list (month day year)."
13900 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13901 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13903 (defun org-calendar-holiday ()
13904 "List of holidays, for Diary display in Org-mode."
13905 (require 'holidays)
13906 (let ((hl (funcall
13907 (if (fboundp 'calendar-check-holidays)
13908 'calendar-check-holidays 'check-calendar-holidays) date)))
13909 (if hl (mapconcat 'identity hl "; "))))
13911 (defun org-diary-sexp-entry (sexp entry date)
13912 "Process a SEXP diary ENTRY for DATE."
13913 (require 'diary-lib)
13914 (let ((result (if calendar-debug-sexp
13915 (let ((stack-trace-on-error t))
13916 (eval (car (read-from-string sexp))))
13917 (condition-case nil
13918 (eval (car (read-from-string sexp)))
13919 (error
13920 (beep)
13921 (message "Bad sexp at line %d in %s: %s"
13922 (org-current-line)
13923 (buffer-file-name) sexp)
13924 (sleep-for 2))))))
13925 (cond ((stringp result) result)
13926 ((and (consp result)
13927 (stringp (cdr result))) (cdr result))
13928 (result entry)
13929 (t nil))))
13931 (defun org-diary-to-ical-string (frombuf)
13932 "Get iCalendar entries from diary entries in buffer FROMBUF.
13933 This uses the icalendar.el library."
13934 (let* ((tmpdir (if (featurep 'xemacs)
13935 (temp-directory)
13936 temporary-file-directory))
13937 (tmpfile (make-temp-name
13938 (expand-file-name "orgics" tmpdir)))
13939 buf rtn b e)
13940 (with-current-buffer frombuf
13941 (icalendar-export-region (point-min) (point-max) tmpfile)
13942 (setq buf (find-buffer-visiting tmpfile))
13943 (set-buffer buf)
13944 (goto-char (point-min))
13945 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13946 (setq b (match-beginning 0)))
13947 (goto-char (point-max))
13948 (if (re-search-backward "^END:VEVENT" nil t)
13949 (setq e (match-end 0)))
13950 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13951 (kill-buffer buf)
13952 (delete-file tmpfile)
13953 rtn))
13955 (defun org-closest-date (start current change prefer show-all)
13956 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13957 When PREFER is `past' return a date that is either CURRENT or past.
13958 When PREFER is `future', return a date that is either CURRENT or future.
13959 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13960 ;; Make the proper lists from the dates
13961 (catch 'exit
13962 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13963 dn dw sday cday n1 n2 n0
13964 d m y y1 y2 date1 date2 nmonths nm ny m2)
13966 (setq start (org-date-to-gregorian start)
13967 current (org-date-to-gregorian
13968 (if show-all
13969 current
13970 (time-to-days (current-time))))
13971 sday (calendar-absolute-from-gregorian start)
13972 cday (calendar-absolute-from-gregorian current))
13974 (if (<= cday sday) (throw 'exit sday))
13976 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13977 (setq dn (string-to-number (match-string 1 change))
13978 dw (cdr (assoc (match-string 2 change) a1)))
13979 (error "Invalid change specifyer: %s" change))
13980 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13981 (cond
13982 ((eq dw 'day)
13983 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13984 n2 (+ n1 dn)))
13985 ((eq dw 'year)
13986 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13987 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13988 (setq date1 (list m d y1)
13989 n1 (calendar-absolute-from-gregorian date1)
13990 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13991 n2 (calendar-absolute-from-gregorian date2)))
13992 ((eq dw 'month)
13993 ;; approx number of month between the two dates
13994 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13995 ;; How often does dn fit in there?
13996 (setq d (nth 1 start) m (car start) y (nth 2 start)
13997 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13998 m (+ m nm)
13999 ny (floor (/ m 12))
14000 y (+ y ny)
14001 m (- m (* ny 12)))
14002 (while (> m 12) (setq m (- m 12) y (1+ y)))
14003 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14004 (setq m2 (+ m dn) y2 y)
14005 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14006 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14007 (while (<= n2 cday)
14008 (setq n1 n2 m m2 y y2)
14009 (setq m2 (+ m dn) y2 y)
14010 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14011 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14012 ;; Make sure n1 is the earlier date
14013 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14014 (if show-all
14015 (cond
14016 ((eq prefer 'past) (if (= cday n2) n2 n1))
14017 ((eq prefer 'future) (if (= cday n1) n1 n2))
14018 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14019 (cond
14020 ((eq prefer 'past) (if (= cday n2) n2 n1))
14021 ((eq prefer 'future) (if (= cday n1) n1 n2))
14022 (t (if (= cday n1) n1 n2)))))))
14024 (defun org-date-to-gregorian (date)
14025 "Turn any specification of DATE into a gregorian date for the calendar."
14026 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14027 ((and (listp date) (= (length date) 3)) date)
14028 ((stringp date)
14029 (setq date (org-parse-time-string date))
14030 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14031 ((listp date)
14032 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14034 (defun org-parse-time-string (s &optional nodefault)
14035 "Parse the standard Org-mode time string.
14036 This should be a lot faster than the normal `parse-time-string'.
14037 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14038 hour and minute fields will be nil if not given."
14039 (if (string-match org-ts-regexp0 s)
14040 (list 0
14041 (if (or (match-beginning 8) (not nodefault))
14042 (string-to-number (or (match-string 8 s) "0")))
14043 (if (or (match-beginning 7) (not nodefault))
14044 (string-to-number (or (match-string 7 s) "0")))
14045 (string-to-number (match-string 4 s))
14046 (string-to-number (match-string 3 s))
14047 (string-to-number (match-string 2 s))
14048 nil nil nil)
14049 (error "Not a standard Org-mode time string: %s" s)))
14051 (defun org-timestamp-up (&optional arg)
14052 "Increase the date item at the cursor by one.
14053 If the cursor is on the year, change the year. If it is on the month or
14054 the day, change that.
14055 With prefix ARG, change by that many units."
14056 (interactive "p")
14057 (org-timestamp-change (prefix-numeric-value arg)))
14059 (defun org-timestamp-down (&optional arg)
14060 "Decrease the date item at the cursor by one.
14061 If the cursor is on the year, change the year. If it is on the month or
14062 the day, change that.
14063 With prefix ARG, change by that many units."
14064 (interactive "p")
14065 (org-timestamp-change (- (prefix-numeric-value arg))))
14067 (defun org-timestamp-up-day (&optional arg)
14068 "Increase the date in the time stamp by one day.
14069 With prefix ARG, change that many days."
14070 (interactive "p")
14071 (if (and (not (org-at-timestamp-p t))
14072 (org-on-heading-p))
14073 (org-todo 'up)
14074 (org-timestamp-change (prefix-numeric-value arg) 'day)))
14076 (defun org-timestamp-down-day (&optional arg)
14077 "Decrease the date in the time stamp by one day.
14078 With prefix ARG, change that many days."
14079 (interactive "p")
14080 (if (and (not (org-at-timestamp-p t))
14081 (org-on-heading-p))
14082 (org-todo 'down)
14083 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
14085 (defun org-at-timestamp-p (&optional inactive-ok)
14086 "Determine if the cursor is in or at a timestamp."
14087 (interactive)
14088 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
14089 (pos (point))
14090 (ans (or (looking-at tsr)
14091 (save-excursion
14092 (skip-chars-backward "^[<\n\r\t")
14093 (if (> (point) (point-min)) (backward-char 1))
14094 (and (looking-at tsr)
14095 (> (- (match-end 0) pos) -1))))))
14096 (and ans
14097 (boundp 'org-ts-what)
14098 (setq org-ts-what
14099 (cond
14100 ((= pos (match-beginning 0)) 'bracket)
14101 ((= pos (1- (match-end 0))) 'bracket)
14102 ((org-pos-in-match-range pos 2) 'year)
14103 ((org-pos-in-match-range pos 3) 'month)
14104 ((org-pos-in-match-range pos 7) 'hour)
14105 ((org-pos-in-match-range pos 8) 'minute)
14106 ((or (org-pos-in-match-range pos 4)
14107 (org-pos-in-match-range pos 5)) 'day)
14108 ((and (> pos (or (match-end 8) (match-end 5)))
14109 (< pos (match-end 0)))
14110 (- pos (or (match-end 8) (match-end 5))))
14111 (t 'day))))
14112 ans))
14114 (defun org-toggle-timestamp-type ()
14115 "Toggle the type (<active> or [inactive]) of a time stamp."
14116 (interactive)
14117 (when (org-at-timestamp-p t)
14118 (let ((beg (match-beginning 0)) (end (match-end 0))
14119 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14120 (save-excursion
14121 (goto-char beg)
14122 (while (re-search-forward "[][<>]" end t)
14123 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14124 t t)))
14125 (message "Timestamp is now %sactive"
14126 (if (equal (char-after beg) ?<) "" "in")))))
14128 (defun org-timestamp-change (n &optional what)
14129 "Change the date in the time stamp at point.
14130 The date will be changed by N times WHAT. WHAT can be `day', `month',
14131 `year', `minute', `second'. If WHAT is not given, the cursor position
14132 in the timestamp determines what will be changed."
14133 (let ((pos (point))
14134 with-hm inactive
14135 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14136 org-ts-what
14137 extra rem
14138 ts time time0)
14139 (if (not (org-at-timestamp-p t))
14140 (error "Not at a timestamp"))
14141 (if (and (not what) (eq org-ts-what 'bracket))
14142 (org-toggle-timestamp-type)
14143 (if (and (not what) (not (eq org-ts-what 'day))
14144 org-display-custom-times
14145 (get-text-property (point) 'display)
14146 (not (get-text-property (1- (point)) 'display)))
14147 (setq org-ts-what 'day))
14148 (setq org-ts-what (or what org-ts-what)
14149 inactive (= (char-after (match-beginning 0)) ?\[)
14150 ts (match-string 0))
14151 (replace-match "")
14152 (if (string-match
14153 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14155 (setq extra (match-string 1 ts)))
14156 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14157 (setq with-hm t))
14158 (setq time0 (org-parse-time-string ts))
14159 (when (and (eq org-ts-what 'minute)
14160 (eq current-prefix-arg nil))
14161 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14162 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14163 (setcar (cdr time0) (+ (nth 1 time0)
14164 (if (> n 0) (- rem) (- dm rem))))))
14165 (setq time
14166 (encode-time (or (car time0) 0)
14167 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14168 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14169 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14170 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14171 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14172 (nthcdr 6 time0)))
14173 (when (and (member org-ts-what '(hour minute))
14174 extra
14175 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14176 (setq extra (org-modify-ts-extra
14177 extra
14178 (if (eq org-ts-what 'hour) 2 5)
14179 n dm)))
14180 (when (integerp org-ts-what)
14181 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14182 (if (eq what 'calendar)
14183 (let ((cal-date (org-get-date-from-calendar)))
14184 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14185 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14186 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14187 (setcar time0 (or (car time0) 0))
14188 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
14189 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
14190 (setq time (apply 'encode-time time0))))
14191 (setq org-last-changed-timestamp
14192 (org-insert-time-stamp time with-hm inactive nil nil extra))
14193 (org-clock-update-time-maybe)
14194 (goto-char pos)
14195 ;; Try to recenter the calendar window, if any
14196 (if (and org-calendar-follow-timestamp-change
14197 (get-buffer-window "*Calendar*" t)
14198 (memq org-ts-what '(day month year)))
14199 (org-recenter-calendar (time-to-days time))))))
14201 (defun org-modify-ts-extra (s pos n dm)
14202 "Change the different parts of the lead-time and repeat fields in timestamp."
14203 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
14204 ng h m new rem)
14205 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
14206 (cond
14207 ((or (org-pos-in-match-range pos 2)
14208 (org-pos-in-match-range pos 3))
14209 (setq m (string-to-number (match-string 3 s))
14210 h (string-to-number (match-string 2 s)))
14211 (if (org-pos-in-match-range pos 2)
14212 (setq h (+ h n))
14213 (setq n (* dm (org-no-warnings (signum n))))
14214 (when (not (= 0 (setq rem (% m dm))))
14215 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
14216 (setq m (+ m n)))
14217 (if (< m 0) (setq m (+ m 60) h (1- h)))
14218 (if (> m 59) (setq m (- m 60) h (1+ h)))
14219 (setq h (min 24 (max 0 h)))
14220 (setq ng 1 new (format "-%02d:%02d" h m)))
14221 ((org-pos-in-match-range pos 6)
14222 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
14223 ((org-pos-in-match-range pos 5)
14224 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
14226 ((org-pos-in-match-range pos 9)
14227 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
14228 ((org-pos-in-match-range pos 8)
14229 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
14231 (when ng
14232 (setq s (concat
14233 (substring s 0 (match-beginning ng))
14235 (substring s (match-end ng))))))
14238 (defun org-recenter-calendar (date)
14239 "If the calendar is visible, recenter it to DATE."
14240 (let* ((win (selected-window))
14241 (cwin (get-buffer-window "*Calendar*" t))
14242 (calendar-move-hook nil))
14243 (when cwin
14244 (select-window cwin)
14245 (calendar-goto-date (if (listp date) date
14246 (calendar-gregorian-from-absolute date)))
14247 (select-window win))))
14249 (defun org-goto-calendar (&optional arg)
14250 "Go to the Emacs calendar at the current date.
14251 If there is a time stamp in the current line, go to that date.
14252 A prefix ARG can be used to force the current date."
14253 (interactive "P")
14254 (let ((tsr org-ts-regexp) diff
14255 (calendar-move-hook nil)
14256 (calendar-view-holidays-initially-flag nil)
14257 (view-calendar-holidays-initially nil)
14258 (calendar-view-diary-initially-flag nil)
14259 (view-diary-entries-initially nil))
14260 (if (or (org-at-timestamp-p)
14261 (save-excursion
14262 (beginning-of-line 1)
14263 (looking-at (concat ".*" tsr))))
14264 (let ((d1 (time-to-days (current-time)))
14265 (d2 (time-to-days
14266 (org-time-string-to-time (match-string 1)))))
14267 (setq diff (- d2 d1))))
14268 (calendar)
14269 (calendar-goto-today)
14270 (if (and diff (not arg)) (calendar-forward-day diff))))
14272 (defun org-get-date-from-calendar ()
14273 "Return a list (month day year) of date at point in calendar."
14274 (with-current-buffer "*Calendar*"
14275 (save-match-data
14276 (calendar-cursor-to-date))))
14278 (defun org-date-from-calendar ()
14279 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14280 If there is already a time stamp at the cursor position, update it."
14281 (interactive)
14282 (if (org-at-timestamp-p t)
14283 (org-timestamp-change 0 'calendar)
14284 (let ((cal-date (org-get-date-from-calendar)))
14285 (org-insert-time-stamp
14286 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14288 (defun org-minutes-to-hh:mm-string (m)
14289 "Compute H:MM from a number of minutes."
14290 (let ((h (/ m 60)))
14291 (setq m (- m (* 60 h)))
14292 (format org-time-clocksum-format h m)))
14294 (defun org-hh:mm-string-to-minutes (s)
14295 "Convert a string H:MM to a number of minutes.
14296 If the string is just a number, interpret it as minutes.
14297 In fact, the first hh:mm or number in the string will be taken,
14298 there can be extra stuff in the string.
14299 If no number is found, the return value is 0."
14300 (cond
14301 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14302 (+ (* (string-to-number (match-string 1 s)) 60)
14303 (string-to-number (match-string 2 s))))
14304 ((string-match "\\([0-9]+\\)" s)
14305 (string-to-number (match-string 1 s)))
14306 (t 0)))
14308 ;;;; Files
14310 (defun org-save-all-org-buffers ()
14311 "Save all Org-mode buffers without user confirmation."
14312 (interactive)
14313 (message "Saving all Org-mode buffers...")
14314 (save-some-buffers t 'org-mode-p)
14315 (when (featurep 'org-id) (org-id-locations-save))
14316 (message "Saving all Org-mode buffers... done"))
14318 (defun org-revert-all-org-buffers ()
14319 "Revert all Org-mode buffers.
14320 Prompt for confirmation when there are unsaved changes.
14321 Be sure you know what you are doing before letting this function
14322 overwrite your changes.
14324 This function is useful in a setup where one tracks org files
14325 with a version control system, to revert on one machine after pulling
14326 changes from another. I believe the procedure must be like this:
14328 1. M-x org-save-all-org-buffers
14329 2. Pull changes from the other machine, resolve conflicts
14330 3. M-x org-revert-all-org-buffers"
14331 (interactive)
14332 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14333 (error "Abort"))
14334 (save-excursion
14335 (save-window-excursion
14336 (mapc
14337 (lambda (b)
14338 (when (and (with-current-buffer b (org-mode-p))
14339 (with-current-buffer b buffer-file-name))
14340 (switch-to-buffer b)
14341 (revert-buffer t 'no-confirm)))
14342 (buffer-list))
14343 (when (and (featurep 'org-id) org-id-track-globally)
14344 (org-id-locations-load)))))
14346 ;;;; Agenda files
14348 ;;;###autoload
14349 (defun org-iswitchb (&optional arg)
14350 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14351 With a prefix argument, restrict available to files.
14352 With two prefix arguments, restrict available buffers to agenda files."
14353 (interactive "P")
14354 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14355 ((equal arg '(16)) (org-buffer-list 'agenda))
14356 (t (org-buffer-list)))))
14357 (switch-to-buffer
14358 (org-icompleting-read "Org buffer: "
14359 (mapcar 'list (mapcar 'buffer-name blist))
14360 nil t))))
14362 ;;;###autoload
14363 (defalias 'org-ido-switchb 'org-iswitchb)
14365 (defun org-buffer-list (&optional predicate exclude-tmp)
14366 "Return a list of Org buffers.
14367 PREDICATE can be `export', `files' or `agenda'.
14369 export restrict the list to Export buffers.
14370 files restrict the list to buffers visiting Org files.
14371 agenda restrict the list to buffers visiting agenda files.
14373 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14374 (let* ((bfn nil)
14375 (agenda-files (and (eq predicate 'agenda)
14376 (mapcar 'file-truename (org-agenda-files t))))
14377 (filter
14378 (cond
14379 ((eq predicate 'files)
14380 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14381 ((eq predicate 'export)
14382 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14383 ((eq predicate 'agenda)
14384 (lambda (b)
14385 (with-current-buffer b
14386 (and (eq major-mode 'org-mode)
14387 (setq bfn (buffer-file-name b))
14388 (member (file-truename bfn) agenda-files)))))
14389 (t (lambda (b) (with-current-buffer b
14390 (or (eq major-mode 'org-mode)
14391 (string-match "\*Org .*Export"
14392 (buffer-name b)))))))))
14393 (delq nil
14394 (mapcar
14395 (lambda(b)
14396 (if (and (funcall filter b)
14397 (or (not exclude-tmp)
14398 (not (string-match "tmp" (buffer-name b)))))
14400 nil))
14401 (buffer-list)))))
14403 (defun org-agenda-files (&optional unrestricted archives)
14404 "Get the list of agenda files.
14405 Optional UNRESTRICTED means return the full list even if a restriction
14406 is currently in place.
14407 When ARCHIVES is t, include all archive files hat are really being
14408 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14409 `org-agenda-archives-mode' is t."
14410 (let ((files
14411 (cond
14412 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14413 ((stringp org-agenda-files) (org-read-agenda-file-list))
14414 ((listp org-agenda-files) org-agenda-files)
14415 (t (error "Invalid value of `org-agenda-files'")))))
14416 (setq files (apply 'append
14417 (mapcar (lambda (f)
14418 (if (file-directory-p f)
14419 (directory-files
14420 f t org-agenda-file-regexp)
14421 (list f)))
14422 files)))
14423 (when org-agenda-skip-unavailable-files
14424 (setq files (delq nil
14425 (mapcar (function
14426 (lambda (file)
14427 (and (file-readable-p file) file)))
14428 files))))
14429 (when (or (eq archives t)
14430 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14431 (setq files (org-add-archive-files files)))
14432 files))
14434 (defun org-edit-agenda-file-list ()
14435 "Edit the list of agenda files.
14436 Depending on setup, this either uses customize to edit the variable
14437 `org-agenda-files', or it visits the file that is holding the list. In the
14438 latter case, the buffer is set up in a way that saving it automatically kills
14439 the buffer and restores the previous window configuration."
14440 (interactive)
14441 (if (stringp org-agenda-files)
14442 (let ((cw (current-window-configuration)))
14443 (find-file org-agenda-files)
14444 (org-set-local 'org-window-configuration cw)
14445 (org-add-hook 'after-save-hook
14446 (lambda ()
14447 (set-window-configuration
14448 (prog1 org-window-configuration
14449 (kill-buffer (current-buffer))))
14450 (org-install-agenda-files-menu)
14451 (message "New agenda file list installed"))
14452 nil 'local)
14453 (message "%s" (substitute-command-keys
14454 "Edit list and finish with \\[save-buffer]")))
14455 (customize-variable 'org-agenda-files)))
14457 (defun org-store-new-agenda-file-list (list)
14458 "Set new value for the agenda file list and save it correctly."
14459 (if (stringp org-agenda-files)
14460 (let ((f org-agenda-files) b)
14461 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14462 (with-temp-file f
14463 (insert (mapconcat 'identity list "\n") "\n")))
14464 (let ((org-mode-hook nil) (org-inhibit-startup t)
14465 (org-insert-mode-line-in-empty-file nil))
14466 (setq org-agenda-files list)
14467 (customize-save-variable 'org-agenda-files org-agenda-files))))
14469 (defun org-read-agenda-file-list ()
14470 "Read the list of agenda files from a file."
14471 (when (file-directory-p org-agenda-files)
14472 (error "`org-agenda-files' cannot be a single directory"))
14473 (when (stringp org-agenda-files)
14474 (with-temp-buffer
14475 (insert-file-contents org-agenda-files)
14476 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14479 ;;;###autoload
14480 (defun org-cycle-agenda-files ()
14481 "Cycle through the files in `org-agenda-files'.
14482 If the current buffer visits an agenda file, find the next one in the list.
14483 If the current buffer does not, find the first agenda file."
14484 (interactive)
14485 (let* ((fs (org-agenda-files t))
14486 (files (append fs (list (car fs))))
14487 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14488 file)
14489 (unless files (error "No agenda files"))
14490 (catch 'exit
14491 (while (setq file (pop files))
14492 (if (equal (file-truename file) tcf)
14493 (when (car files)
14494 (find-file (car files))
14495 (throw 'exit t))))
14496 (find-file (car fs)))
14497 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14499 (defun org-agenda-file-to-front (&optional to-end)
14500 "Move/add the current file to the top of the agenda file list.
14501 If the file is not present in the list, it is added to the front. If it is
14502 present, it is moved there. With optional argument TO-END, add/move to the
14503 end of the list."
14504 (interactive "P")
14505 (let ((org-agenda-skip-unavailable-files nil)
14506 (file-alist (mapcar (lambda (x)
14507 (cons (file-truename x) x))
14508 (org-agenda-files t)))
14509 (ctf (file-truename buffer-file-name))
14510 x had)
14511 (setq x (assoc ctf file-alist) had x)
14513 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14514 (if to-end
14515 (setq file-alist (append (delq x file-alist) (list x)))
14516 (setq file-alist (cons x (delq x file-alist))))
14517 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14518 (org-install-agenda-files-menu)
14519 (message "File %s to %s of agenda file list"
14520 (if had "moved" "added") (if to-end "end" "front"))))
14522 (defun org-remove-file (&optional file)
14523 "Remove current file from the list of files in variable `org-agenda-files'.
14524 These are the files which are being checked for agenda entries.
14525 Optional argument FILE means, use this file instead of the current."
14526 (interactive)
14527 (let* ((org-agenda-skip-unavailable-files nil)
14528 (file (or file buffer-file-name))
14529 (true-file (file-truename file))
14530 (afile (abbreviate-file-name file))
14531 (files (delq nil (mapcar
14532 (lambda (x)
14533 (if (equal true-file
14534 (file-truename x))
14535 nil x))
14536 (org-agenda-files t)))))
14537 (if (not (= (length files) (length (org-agenda-files t))))
14538 (progn
14539 (org-store-new-agenda-file-list files)
14540 (org-install-agenda-files-menu)
14541 (message "Removed file: %s" afile))
14542 (message "File was not in list: %s (not removed)" afile))))
14544 (defun org-file-menu-entry (file)
14545 (vector file (list 'find-file file) t))
14547 (defun org-check-agenda-file (file)
14548 "Make sure FILE exists. If not, ask user what to do."
14549 (when (not (file-exists-p file))
14550 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14551 (abbreviate-file-name file))
14552 (let ((r (downcase (read-char-exclusive))))
14553 (cond
14554 ((equal r ?r)
14555 (org-remove-file file)
14556 (throw 'nextfile t))
14557 (t (error "Abort"))))))
14559 (defun org-get-agenda-file-buffer (file)
14560 "Get a buffer visiting FILE. If the buffer needs to be created, add
14561 it to the list of buffers which might be released later."
14562 (let ((buf (org-find-base-buffer-visiting file)))
14563 (if buf
14564 buf ; just return it
14565 ;; Make a new buffer and remember it
14566 (setq buf (find-file-noselect file))
14567 (if buf (push buf org-agenda-new-buffers))
14568 buf)))
14570 (defun org-release-buffers (blist)
14571 "Release all buffers in list, asking the user for confirmation when needed.
14572 When a buffer is unmodified, it is just killed. When modified, it is saved
14573 \(if the user agrees) and then killed."
14574 (let (buf file)
14575 (while (setq buf (pop blist))
14576 (setq file (buffer-file-name buf))
14577 (when (and (buffer-modified-p buf)
14578 file
14579 (y-or-n-p (format "Save file %s? " file)))
14580 (with-current-buffer buf (save-buffer)))
14581 (kill-buffer buf))))
14583 (defun org-prepare-agenda-buffers (files)
14584 "Create buffers for all agenda files, protect archived trees and comments."
14585 (interactive)
14586 (let ((pa '(:org-archived t))
14587 (pc '(:org-comment t))
14588 (pall '(:org-archived t :org-comment t))
14589 (inhibit-read-only t)
14590 (rea (concat ":" org-archive-tag ":"))
14591 bmp file re)
14592 (save-excursion
14593 (save-restriction
14594 (while (setq file (pop files))
14595 (catch 'nextfile
14596 (if (bufferp file)
14597 (set-buffer file)
14598 (org-check-agenda-file file)
14599 (set-buffer (org-get-agenda-file-buffer file)))
14600 (widen)
14601 (setq bmp (buffer-modified-p))
14602 (org-refresh-category-properties)
14603 (setq org-todo-keywords-for-agenda
14604 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14605 (setq org-done-keywords-for-agenda
14606 (append org-done-keywords-for-agenda org-done-keywords))
14607 (setq org-todo-keyword-alist-for-agenda
14608 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14609 (setq org-drawers-for-agenda
14610 (append org-drawers-for-agenda org-drawers))
14611 (setq org-tag-alist-for-agenda
14612 (append org-tag-alist-for-agenda org-tag-alist))
14614 (save-excursion
14615 (remove-text-properties (point-min) (point-max) pall)
14616 (when org-agenda-skip-archived-trees
14617 (goto-char (point-min))
14618 (while (re-search-forward rea nil t)
14619 (if (org-on-heading-p t)
14620 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14621 (goto-char (point-min))
14622 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14623 (while (re-search-forward re nil t)
14624 (add-text-properties
14625 (match-beginning 0) (org-end-of-subtree t) pc)))
14626 (set-buffer-modified-p bmp)))))
14627 (setq org-todo-keyword-alist-for-agenda
14628 (org-uniquify org-todo-keyword-alist-for-agenda)
14629 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14631 ;;;; Embedded LaTeX
14633 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14634 "Keymap for the minor `org-cdlatex-mode'.")
14636 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14637 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14638 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14639 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14640 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14642 (defvar org-cdlatex-texmathp-advice-is-done nil
14643 "Flag remembering if we have applied the advice to texmathp already.")
14645 (define-minor-mode org-cdlatex-mode
14646 "Toggle the minor `org-cdlatex-mode'.
14647 This mode supports entering LaTeX environment and math in LaTeX fragments
14648 in Org-mode.
14649 \\{org-cdlatex-mode-map}"
14650 nil " OCDL" nil
14651 (when org-cdlatex-mode (require 'cdlatex))
14652 (unless org-cdlatex-texmathp-advice-is-done
14653 (setq org-cdlatex-texmathp-advice-is-done t)
14654 (defadvice texmathp (around org-math-always-on activate)
14655 "Always return t in org-mode buffers.
14656 This is because we want to insert math symbols without dollars even outside
14657 the LaTeX math segments. If Orgmode thinks that point is actually inside
14658 an embedded LaTeX fragment, let texmathp do its job.
14659 \\[org-cdlatex-mode-map]"
14660 (interactive)
14661 (let (p)
14662 (cond
14663 ((not (org-mode-p)) ad-do-it)
14664 ((eq this-command 'cdlatex-math-symbol)
14665 (setq ad-return-value t
14666 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14668 (let ((p (org-inside-LaTeX-fragment-p)))
14669 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14670 (setq ad-return-value t
14671 texmathp-why '("Org-mode embedded math" . 0))
14672 (if p ad-do-it)))))))))
14674 (defun turn-on-org-cdlatex ()
14675 "Unconditionally turn on `org-cdlatex-mode'."
14676 (org-cdlatex-mode 1))
14678 (defun org-inside-LaTeX-fragment-p ()
14679 "Test if point is inside a LaTeX fragment.
14680 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14681 sequence appearing also before point.
14682 Even though the matchers for math are configurable, this function assumes
14683 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14684 delimiters are skipped when they have been removed by customization.
14685 The return value is nil, or a cons cell with the delimiter and
14686 and the position of this delimiter.
14688 This function does a reasonably good job, but can locally be fooled by
14689 for example currency specifications. For example it will assume being in
14690 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14691 fragments that are properly closed, but during editing, we have to live
14692 with the uncertainty caused by missing closing delimiters. This function
14693 looks only before point, not after."
14694 (catch 'exit
14695 (let ((pos (point))
14696 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14697 (lim (progn
14698 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14699 (point)))
14700 dd-on str (start 0) m re)
14701 (goto-char pos)
14702 (when dodollar
14703 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14704 re (nth 1 (assoc "$" org-latex-regexps)))
14705 (while (string-match re str start)
14706 (cond
14707 ((= (match-end 0) (length str))
14708 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14709 ((= (match-end 0) (- (length str) 5))
14710 (throw 'exit nil))
14711 (t (setq start (match-end 0))))))
14712 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14713 (goto-char pos)
14714 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14715 (and (match-beginning 2) (throw 'exit nil))
14716 ;; count $$
14717 (while (re-search-backward "\\$\\$" lim t)
14718 (setq dd-on (not dd-on)))
14719 (goto-char pos)
14720 (if dd-on (cons "$$" m))))))
14722 (defun org-inside-latex-macro-p ()
14723 "Is point inside a LaTeX macro or its arguments?"
14724 (save-match-data
14725 (org-in-regexp
14726 "\\\\[a-zA-Z]+\\*?\\(\\[[^][\n{}]*\\]\\)?\\({[^{}\n]*}\\)?")))
14728 (defun org-try-cdlatex-tab ()
14729 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14730 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14731 - inside a LaTeX fragment, or
14732 - after the first word in a line, where an abbreviation expansion could
14733 insert a LaTeX environment."
14734 (when org-cdlatex-mode
14735 (cond
14736 ((save-excursion
14737 (skip-chars-backward "a-zA-Z0-9*")
14738 (skip-chars-backward " \t")
14739 (bolp))
14740 (cdlatex-tab) t)
14741 ((org-inside-LaTeX-fragment-p)
14742 (cdlatex-tab) t)
14743 (t nil))))
14745 (defun org-cdlatex-underscore-caret (&optional arg)
14746 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14747 Revert to the normal definition outside of these fragments."
14748 (interactive "P")
14749 (if (org-inside-LaTeX-fragment-p)
14750 (call-interactively 'cdlatex-sub-superscript)
14751 (let (org-cdlatex-mode)
14752 (call-interactively (key-binding (vector last-input-event))))))
14754 (defun org-cdlatex-math-modify (&optional arg)
14755 "Execute `cdlatex-math-modify' in LaTeX fragments.
14756 Revert to the normal definition outside of these fragments."
14757 (interactive "P")
14758 (if (org-inside-LaTeX-fragment-p)
14759 (call-interactively 'cdlatex-math-modify)
14760 (let (org-cdlatex-mode)
14761 (call-interactively (key-binding (vector last-input-event))))))
14763 (defvar org-latex-fragment-image-overlays nil
14764 "List of overlays carrying the images of latex fragments.")
14765 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14767 (defun org-remove-latex-fragment-image-overlays ()
14768 "Remove all overlays with LaTeX fragment images in current buffer."
14769 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14770 (setq org-latex-fragment-image-overlays nil))
14772 (defun org-preview-latex-fragment (&optional subtree)
14773 "Preview the LaTeX fragment at point, or all locally or globally.
14774 If the cursor is in a LaTeX fragment, create the image and overlay
14775 it over the source code. If there is no fragment at point, display
14776 all fragments in the current text, from one headline to the next. With
14777 prefix SUBTREE, display all fragments in the current subtree. With a
14778 double prefix `C-u C-u', or when the cursor is before the first headline,
14779 display all fragments in the buffer.
14780 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14781 (interactive "P")
14782 (org-remove-latex-fragment-image-overlays)
14783 (save-excursion
14784 (save-restriction
14785 (let (beg end at msg)
14786 (cond
14787 ((or (equal subtree '(16))
14788 (not (save-excursion
14789 (re-search-backward (concat "^" outline-regexp) nil t))))
14790 (setq beg (point-min) end (point-max)
14791 msg "Creating images for buffer...%s"))
14792 ((equal subtree '(4))
14793 (org-back-to-heading)
14794 (setq beg (point) end (org-end-of-subtree t)
14795 msg "Creating images for subtree...%s"))
14797 (if (setq at (org-inside-LaTeX-fragment-p))
14798 (goto-char (max (point-min) (- (cdr at) 2)))
14799 (org-back-to-heading))
14800 (setq beg (point) end (progn (outline-next-heading) (point))
14801 msg (if at "Creating image...%s"
14802 "Creating images for entry...%s"))))
14803 (message msg "")
14804 (narrow-to-region beg end)
14805 (goto-char beg)
14806 (org-format-latex
14807 (concat "ltxpng/" (file-name-sans-extension
14808 (file-name-nondirectory
14809 buffer-file-name)))
14810 default-directory 'overlays msg at 'forbuffer)
14811 (message msg "done. Use `C-c C-c' to remove images.")))))
14813 (defvar org-latex-regexps
14814 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14815 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14816 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14817 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14818 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14819 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14820 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14821 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14822 "Regular expressions for matching embedded LaTeX.")
14824 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14825 "Replace LaTeX fragments with links to an image, and produce images.
14826 Some of the options can be changed using the variable
14827 `org-format-latex-options'."
14828 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14829 (let* ((prefixnodir (file-name-nondirectory prefix))
14830 (absprefix (expand-file-name prefix dir))
14831 (todir (file-name-directory absprefix))
14832 (opt org-format-latex-options)
14833 (matchers (plist-get opt :matchers))
14834 (re-list org-latex-regexps)
14835 (org-format-latex-header-extra
14836 (plist-get (org-infile-export-plist) :latex-header-extra))
14837 (cnt 0) txt hash link beg end re e checkdir
14838 executables-checked
14839 m n block linkfile movefile ov)
14840 ;; Check the different regular expressions
14841 (while (setq e (pop re-list))
14842 (setq m (car e) re (nth 1 e) n (nth 2 e)
14843 block (if (nth 3 e) "\n\n" ""))
14844 (when (member m matchers)
14845 (goto-char (point-min))
14846 (while (re-search-forward re nil t)
14847 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14848 (not (get-text-property (match-beginning n)
14849 'org-protected))
14850 (or (not overlays)
14851 (not (eq (get-char-property (match-beginning n)
14852 'org-overlay-type)
14853 'org-latex-overlay))))
14854 (setq txt (match-string n)
14855 beg (match-beginning n) end (match-end n)
14856 cnt (1+ cnt))
14857 (let (print-length print-level) ; make sure full list is printed
14858 (setq hash (sha1 (prin1-to-string
14859 (list org-format-latex-header
14860 org-format-latex-header-extra
14861 org-export-latex-packages-alist
14862 org-format-latex-options
14863 forbuffer txt)))
14864 linkfile (format "%s_%s.png" prefix hash)
14865 movefile (format "%s_%s.png" absprefix hash)))
14866 (setq link (concat block "[[file:" linkfile "]]" block))
14867 (if msg (message msg cnt))
14868 (goto-char beg)
14869 (unless checkdir ; make sure the directory exists
14870 (setq checkdir t)
14871 (or (file-directory-p todir) (make-directory todir)))
14873 (unless executables-checked
14874 (org-check-external-command
14875 "latex" "needed to convert LaTeX fragments to images")
14876 (org-check-external-command
14877 "dvipng" "needed to convert LaTeX fragments to images")
14878 (setq executables-checked t))
14880 (unless (file-exists-p movefile)
14881 (org-create-formula-image
14882 txt movefile opt forbuffer))
14883 (if overlays
14884 (progn
14885 (mapc (lambda (o)
14886 (if (eq (org-overlay-get o 'org-overlay-type)
14887 'org-latex-overlay)
14888 (org-delete-overlay o)))
14889 (org-overlays-in beg end))
14890 (setq ov (org-make-overlay beg end))
14891 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14892 (if (featurep 'xemacs)
14893 (progn
14894 (org-overlay-put ov 'invisible t)
14895 (org-overlay-put
14896 ov 'end-glyph
14897 (make-glyph (vector 'png :file movefile))))
14898 (org-overlay-put
14899 ov 'display
14900 (list 'image :type 'png :file movefile :ascent 'center)))
14901 (push ov org-latex-fragment-image-overlays)
14902 (goto-char end))
14903 (delete-region beg end)
14904 (insert link))))))))
14906 ;; This function borrows from Ganesh Swami's latex2png.el
14907 (defun org-create-formula-image (string tofile options buffer)
14908 "This calls dvipng."
14909 (require 'org-latex)
14910 (let* ((tmpdir (if (featurep 'xemacs)
14911 (temp-directory)
14912 temporary-file-directory))
14913 (texfilebase (make-temp-name
14914 (expand-file-name "orgtex" tmpdir)))
14915 (texfile (concat texfilebase ".tex"))
14916 (dvifile (concat texfilebase ".dvi"))
14917 (pngfile (concat texfilebase ".png"))
14918 (fnh (if (featurep 'xemacs)
14919 (font-height (get-face-font 'default))
14920 (face-attribute 'default :height nil)))
14921 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14922 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14923 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14924 "Black"))
14925 (bg (or (plist-get options (if buffer :background :html-background))
14926 "Transparent")))
14927 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14928 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14929 (with-temp-file texfile
14930 (insert org-format-latex-header
14931 (if org-export-latex-packages-alist
14932 (concat "\n"
14933 (mapconcat (lambda(p)
14934 (if (equal "" (car p))
14935 (format "\\usepackage{%s}" (cadr p))
14936 (format "\\usepackage[%s]{%s}"
14937 (car p) (cadr p))))
14938 org-export-latex-packages-alist "\n"))
14940 (if org-format-latex-header-extra
14941 (concat "\n" org-format-latex-header-extra)
14943 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14944 (let ((dir default-directory))
14945 (condition-case nil
14946 (progn
14947 (cd tmpdir)
14948 (call-process "latex" nil nil nil texfile))
14949 (error nil))
14950 (cd dir))
14951 (if (not (file-exists-p dvifile))
14952 (progn (message "Failed to create dvi file from %s" texfile) nil)
14953 (condition-case nil
14954 (call-process "dvipng" nil nil nil
14955 "-fg" fg "-bg" bg
14956 "-D" dpi
14957 ;;"-x" scale "-y" scale
14958 "-T" "tight"
14959 "-o" pngfile
14960 dvifile)
14961 (error nil))
14962 (if (not (file-exists-p pngfile))
14963 (progn (message "Failed to create png file from %s" texfile) nil)
14964 ;; Use the requested file name and clean up
14965 (copy-file pngfile tofile 'replace)
14966 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14967 (delete-file (concat texfilebase e)))
14968 pngfile))))
14970 (defun org-dvipng-color (attr)
14971 "Return an rgb color specification for dvipng."
14972 (apply 'format "rgb %s %s %s"
14973 (mapcar 'org-normalize-color
14974 (color-values (face-attribute 'default attr nil)))))
14976 (defun org-normalize-color (value)
14977 "Return string to be used as color value for an RGB component."
14978 (format "%g" (/ value 65535.0)))
14980 ;;;; Key bindings
14982 ;; Make `C-c C-x' a prefix key
14983 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14985 ;; TAB key with modifiers
14986 (org-defkey org-mode-map "\C-i" 'org-cycle)
14987 (org-defkey org-mode-map [(tab)] 'org-cycle)
14988 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14989 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14990 (org-defkey org-mode-map "\M-\t" 'org-complete)
14991 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14992 ;; The following line is necessary under Suse GNU/Linux
14993 (unless (featurep 'xemacs)
14994 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14995 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14996 (define-key org-mode-map [backtab] 'org-shifttab)
14998 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14999 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15000 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
15002 ;; Cursor keys with modifiers
15003 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
15004 (org-defkey org-mode-map [(meta right)] 'org-metaright)
15005 (org-defkey org-mode-map [(meta up)] 'org-metaup)
15006 (org-defkey org-mode-map [(meta down)] 'org-metadown)
15008 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15009 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
15010 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
15011 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
15013 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
15014 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
15015 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
15016 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
15018 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
15019 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
15021 ;;; Extra keys for tty access.
15022 ;; We only set them when really needed because otherwise the
15023 ;; menus don't show the simple keys
15025 (when (or org-use-extra-keys
15026 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
15027 (not window-system))
15028 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
15029 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
15030 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
15031 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
15032 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
15033 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
15034 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
15035 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
15036 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
15037 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
15038 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
15039 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
15040 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
15041 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
15042 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
15043 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
15044 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
15045 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
15046 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
15047 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
15048 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
15049 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
15050 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
15051 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
15052 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
15053 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
15054 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
15055 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
15057 ;; All the other keys
15059 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15060 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
15061 (if (boundp 'narrow-map)
15062 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
15063 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
15064 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
15065 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
15066 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
15067 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
15068 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
15069 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
15070 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
15071 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
15072 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
15073 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
15074 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
15075 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
15076 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
15077 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
15078 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15079 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
15080 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
15081 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
15082 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
15083 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
15084 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
15085 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
15086 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
15087 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
15088 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
15089 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
15090 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
15091 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
15092 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
15093 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
15094 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15095 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15096 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15097 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15098 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
15099 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
15100 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15101 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
15102 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
15103 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
15104 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
15105 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15106 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
15107 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
15108 (org-defkey org-mode-map "\C-c^" 'org-sort)
15109 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15110 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
15111 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
15112 (org-defkey org-mode-map "\C-m" 'org-return)
15113 (org-defkey org-mode-map "\C-j" 'org-return-indent)
15114 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
15115 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
15116 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
15117 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
15118 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
15119 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
15120 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15121 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15122 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
15123 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
15124 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
15125 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
15126 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
15127 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15128 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
15129 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
15130 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
15131 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
15132 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
15133 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
15135 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
15136 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15137 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15138 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15140 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
15141 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15142 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15143 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
15144 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15145 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15146 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15147 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15148 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15149 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15150 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
15151 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
15152 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
15153 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
15154 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
15156 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
15157 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
15158 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
15159 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
15161 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
15163 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
15165 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
15166 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
15168 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
15171 (when (featurep 'xemacs)
15172 (org-defkey org-mode-map 'button3 'popup-mode-menu))
15175 (defconst org-speed-commands-default
15177 ("Outline Navigation")
15178 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
15179 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
15180 ("f" . (org-speed-move-safe 'org-forward-same-level))
15181 ("b" . (org-speed-move-safe 'org-backward-same-level))
15182 ("u" . (org-speed-move-safe 'outline-up-heading))
15183 ("j" . org-goto)
15184 ("g" . (org-refile t))
15185 ("Outline Visibility")
15186 ("c" . org-cycle)
15187 ("C" . org-shifttab)
15188 (" " . org-display-outline-path)
15189 ("Outline Structure Editing")
15190 ("U" . org-shiftmetaup)
15191 ("D" . org-shiftmetadown)
15192 ("r" . org-metaright)
15193 ("l" . org-metaleft)
15194 ("R" . org-shiftmetaright)
15195 ("L" . org-shiftmetaleft)
15196 ("i" . (progn (forward-char 1) (call-interactively
15197 'org-insert-heading-respect-content)))
15198 ("^" . org-sort)
15199 ("w" . org-refile)
15200 ("a" . org-archive-subtree-default-with-confirmation)
15201 ("." . outline-mark-subtree)
15202 ("Clock Commands")
15203 ("I" . org-clock-in)
15204 ("O" . org-clock-out)
15205 ("Meta Data Editing")
15206 ("t" . org-todo)
15207 ("0" . (org-priority ?\ ))
15208 ("1" . (org-priority ?A))
15209 ("2" . (org-priority ?B))
15210 ("3" . (org-priority ?C))
15211 (";" . org-set-tags-command)
15212 ("e" . org-set-effort)
15213 ("Agenda Views etc")
15214 ("v" . org-agenda)
15215 ("/" . org-sparse-tree)
15216 ("Misc")
15217 ("o" . org-open-at-point)
15218 ("?" . org-speed-command-help)
15220 "The default speed commands.")
15222 (defun org-print-speed-command (e)
15223 (if (> (length (car e)) 1)
15224 (progn
15225 (princ "\n")
15226 (princ (car e))
15227 (princ "\n")
15228 (princ (make-string (length (car e)) ?-))
15229 (princ "\n"))
15230 (princ (car e))
15231 (princ " ")
15232 (if (symbolp (cdr e))
15233 (princ (symbol-name (cdr e)))
15234 (prin1 (cdr e)))
15235 (princ "\n")))
15237 (defun org-speed-command-help ()
15238 "Show the available speed commands."
15239 (interactive)
15240 (if (not org-use-speed-commands)
15241 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
15242 (with-output-to-temp-buffer "*Help*"
15243 (princ "User-defined Speed commands\n===========================\n")
15244 (mapc 'org-print-speed-command org-speed-commands-user)
15245 (princ "\n")
15246 (princ "Built-in Speed commands\n=======================\n")
15247 (mapc 'org-print-speed-command org-speed-commands-default))
15248 (with-current-buffer "*Help*"
15249 (setq truncate-lines t))))
15251 (defun org-speed-move-safe (cmd)
15252 "Execute CMD, but make sure that the cursor always ends up in a headline.
15253 If not, return to the original position and throw an error."
15254 (interactive)
15255 (let ((pos (point)))
15256 (call-interactively cmd)
15257 (unless (and (bolp) (org-on-heading-p))
15258 (goto-char pos)
15259 (error "Boundary reached while executing %s" cmd))))
15261 (defvar org-self-insert-command-undo-counter 0)
15263 (defvar org-table-auto-blank-field) ; defined in org-table.el
15264 (defvar org-speed-command nil)
15265 (defun org-self-insert-command (N)
15266 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15267 If the cursor is in a table looking at whitespace, the whitespace is
15268 overwritten, and the table is not marked as requiring realignment."
15269 (interactive "p")
15270 (cond
15271 ((and org-use-speed-commands
15272 (or (and (bolp) (looking-at outline-regexp))
15273 (and (functionp org-use-speed-commands)
15274 (funcall org-use-speed-commands)))
15275 (setq
15276 org-speed-command
15277 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15278 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15279 (cond
15280 ((commandp org-speed-command)
15281 (setq this-command org-speed-command)
15282 (call-interactively org-speed-command))
15283 ((functionp org-speed-command)
15284 (funcall org-speed-command))
15285 ((and org-speed-command (listp org-speed-command))
15286 (eval org-speed-command))
15287 (t (let (org-use-speed-commands)
15288 (call-interactively 'org-self-insert-command)))))
15289 ((and
15290 (org-table-p)
15291 (progn
15292 ;; check if we blank the field, and if that triggers align
15293 (and (featurep 'org-table) org-table-auto-blank-field
15294 (member last-command
15295 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15296 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15297 ;; got extra space, this field does not determine column width
15298 (let (org-table-may-need-update) (org-table-blank-field))
15299 ;; no extra space, this field may determine column width
15300 (org-table-blank-field)))
15302 (eq N 1)
15303 (looking-at "[^|\n]* |"))
15304 (let (org-table-may-need-update)
15305 (goto-char (1- (match-end 0)))
15306 (delete-backward-char 1)
15307 (goto-char (match-beginning 0))
15308 (self-insert-command N)))
15310 (setq org-table-may-need-update t)
15311 (self-insert-command N)
15312 (org-fix-tags-on-the-fly)
15313 (if org-self-insert-cluster-for-undo
15314 (if (not (eq last-command 'org-self-insert-command))
15315 (setq org-self-insert-command-undo-counter 1)
15316 (if (>= org-self-insert-command-undo-counter 20)
15317 (setq org-self-insert-command-undo-counter 1)
15318 (and (> org-self-insert-command-undo-counter 0)
15319 buffer-undo-list
15320 (not (cadr buffer-undo-list)) ; remove nil entry
15321 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15322 (setq org-self-insert-command-undo-counter
15323 (1+ org-self-insert-command-undo-counter))))))))
15325 (defun org-fix-tags-on-the-fly ()
15326 (when (and (equal (char-after (point-at-bol)) ?*)
15327 (org-on-heading-p))
15328 (org-align-tags-here org-tags-column)))
15330 (defun org-delete-backward-char (N)
15331 "Like `delete-backward-char', insert whitespace at field end in tables.
15332 When deleting backwards, in tables this function will insert whitespace in
15333 front of the next \"|\" separator, to keep the table aligned. The table will
15334 still be marked for re-alignment if the field did fill the entire column,
15335 because, in this case the deletion might narrow the column."
15336 (interactive "p")
15337 (if (and (org-table-p)
15338 (eq N 1)
15339 (string-match "|" (buffer-substring (point-at-bol) (point)))
15340 (looking-at ".*?|"))
15341 (let ((pos (point))
15342 (noalign (looking-at "[^|\n\r]* |"))
15343 (c org-table-may-need-update))
15344 (backward-delete-char N)
15345 (skip-chars-forward "^|")
15346 (insert " ")
15347 (goto-char (1- pos))
15348 ;; noalign: if there were two spaces at the end, this field
15349 ;; does not determine the width of the column.
15350 (if noalign (setq org-table-may-need-update c)))
15351 (backward-delete-char N)
15352 (org-fix-tags-on-the-fly)))
15354 (defun org-delete-char (N)
15355 "Like `delete-char', but insert whitespace at field end in tables.
15356 When deleting characters, in tables this function will insert whitespace in
15357 front of the next \"|\" separator, to keep the table aligned. The table will
15358 still be marked for re-alignment if the field did fill the entire column,
15359 because, in this case the deletion might narrow the column."
15360 (interactive "p")
15361 (if (and (org-table-p)
15362 (not (bolp))
15363 (not (= (char-after) ?|))
15364 (eq N 1))
15365 (if (looking-at ".*?|")
15366 (let ((pos (point))
15367 (noalign (looking-at "[^|\n\r]* |"))
15368 (c org-table-may-need-update))
15369 (replace-match (concat
15370 (substring (match-string 0) 1 -1)
15371 " |"))
15372 (goto-char pos)
15373 ;; noalign: if there were two spaces at the end, this field
15374 ;; does not determine the width of the column.
15375 (if noalign (setq org-table-may-need-update c)))
15376 (delete-char N))
15377 (delete-char N)
15378 (org-fix-tags-on-the-fly)))
15380 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15381 (put 'org-self-insert-command 'delete-selection t)
15382 (put 'orgtbl-self-insert-command 'delete-selection t)
15383 (put 'org-delete-char 'delete-selection 'supersede)
15384 (put 'org-delete-backward-char 'delete-selection 'supersede)
15385 (put 'org-yank 'delete-selection 'yank)
15387 ;; Make `flyspell-mode' delay after some commands
15388 (put 'org-self-insert-command 'flyspell-delayed t)
15389 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15390 (put 'org-delete-char 'flyspell-delayed t)
15391 (put 'org-delete-backward-char 'flyspell-delayed t)
15393 ;; Make pabbrev-mode expand after org-mode commands
15394 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15395 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15397 ;; How to do this: Measure non-white length of current string
15398 ;; If equal to column width, we should realign.
15400 (defun org-remap (map &rest commands)
15401 "In MAP, remap the functions given in COMMANDS.
15402 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15403 (let (new old)
15404 (while commands
15405 (setq old (pop commands) new (pop commands))
15406 (if (fboundp 'command-remapping)
15407 (org-defkey map (vector 'remap old) new)
15408 (substitute-key-definition old new map global-map)))))
15410 (when (eq org-enable-table-editor 'optimized)
15411 ;; If the user wants maximum table support, we need to hijack
15412 ;; some standard editing functions
15413 (org-remap org-mode-map
15414 'self-insert-command 'org-self-insert-command
15415 'delete-char 'org-delete-char
15416 'delete-backward-char 'org-delete-backward-char)
15417 (org-defkey org-mode-map "|" 'org-force-self-insert))
15419 (defvar org-ctrl-c-ctrl-c-hook nil
15420 "Hook for functions attaching themselves to `C-c C-c'.
15421 This can be used to add additional functionality to the C-c C-c key which
15422 executes context-dependent commands.
15423 Each function will be called with no arguments. The function must check
15424 if the context is appropriate for it to act. If yes, it should do its
15425 thing and then return a non-nil value. If the context is wrong,
15426 just do nothing and return nil.")
15428 (defvar org-tab-first-hook nil
15429 "Hook for functions to attach themselves to TAB.
15430 See `org-ctrl-c-ctrl-c-hook' for more information.
15431 This hook runs as the first action when TAB is pressed, even before
15432 `org-cycle' messes around with the `outline-regexp' to cater for
15433 inline tasks and plain list item folding.
15434 If any function in this hook returns t, not other actions like table
15435 field motion visibility cycling will be done.")
15437 (defvar org-tab-after-check-for-table-hook nil
15438 "Hook for functions to attach themselves to TAB.
15439 See `org-ctrl-c-ctrl-c-hook' for more information.
15440 This hook runs after it has been established that the cursor is not in a
15441 table, but before checking if the cursor is in a headline or if global cycling
15442 should be done.
15443 If any function in this hook returns t, not other actions like visibility
15444 cycling will be done.")
15446 (defvar org-tab-after-check-for-cycling-hook nil
15447 "Hook for functions to attach themselves to TAB.
15448 See `org-ctrl-c-ctrl-c-hook' for more information.
15449 This hook runs after it has been established that not table field motion and
15450 not visibility should be done because of current context. This is probably
15451 the place where a package like yasnippets can hook in.")
15453 (defvar org-tab-before-tab-emulation-hook nil
15454 "Hook for functions to attach themselves to TAB.
15455 See `org-ctrl-c-ctrl-c-hook' for more information.
15456 This hook runs after every other options for TAB have been exhausted, but
15457 before indentation and \t insertion takes place.")
15459 (defvar org-metaleft-hook nil
15460 "Hook for functions attaching themselves to `M-left'.
15461 See `org-ctrl-c-ctrl-c-hook' for more information.")
15462 (defvar org-metaright-hook nil
15463 "Hook for functions attaching themselves to `M-right'.
15464 See `org-ctrl-c-ctrl-c-hook' for more information.")
15465 (defvar org-metaup-hook nil
15466 "Hook for functions attaching themselves to `M-up'.
15467 See `org-ctrl-c-ctrl-c-hook' for more information.")
15468 (defvar org-metadown-hook nil
15469 "Hook for functions attaching themselves to `M-down'.
15470 See `org-ctrl-c-ctrl-c-hook' for more information.")
15471 (defvar org-shiftmetaleft-hook nil
15472 "Hook for functions attaching themselves to `M-S-left'.
15473 See `org-ctrl-c-ctrl-c-hook' for more information.")
15474 (defvar org-shiftmetaright-hook nil
15475 "Hook for functions attaching themselves to `M-S-right'.
15476 See `org-ctrl-c-ctrl-c-hook' for more information.")
15477 (defvar org-shiftmetaup-hook nil
15478 "Hook for functions attaching themselves to `M-S-up'.
15479 See `org-ctrl-c-ctrl-c-hook' for more information.")
15480 (defvar org-shiftmetadown-hook nil
15481 "Hook for functions attaching themselves to `M-S-down'.
15482 See `org-ctrl-c-ctrl-c-hook' for more information.")
15483 (defvar org-metareturn-hook nil
15484 "Hook for functions attaching themselves to `M-RET'.
15485 See `org-ctrl-c-ctrl-c-hook' for more information.")
15487 (defun org-modifier-cursor-error ()
15488 "Throw an error, a modified cursor command was applied in wrong context."
15489 (error "This command is active in special context like tables, headlines or items"))
15491 (defun org-shiftselect-error ()
15492 "Throw an error because Shift-Cursor command was applied in wrong context."
15493 (if (and (boundp 'shift-select-mode) shift-select-mode)
15494 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15495 (error "This command works only in special context like headlines or timestamps")))
15497 (defun org-call-for-shift-select (cmd)
15498 (let ((this-command-keys-shift-translated t))
15499 (call-interactively cmd)))
15501 (defun org-shifttab (&optional arg)
15502 "Global visibility cycling or move to previous table field.
15503 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15504 on context.
15505 See the individual commands for more information."
15506 (interactive "P")
15507 (cond
15508 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15509 ((integerp arg)
15510 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15511 (message "Content view to level: %d" arg)
15512 (org-content (prefix-numeric-value arg2))
15513 (setq org-cycle-global-status 'overview)))
15514 (t (call-interactively 'org-global-cycle))))
15516 (defun org-shiftmetaleft ()
15517 "Promote subtree or delete table column.
15518 Calls `org-promote-subtree', `org-outdent-item',
15519 or `org-table-delete-column', depending on context.
15520 See the individual commands for more information."
15521 (interactive)
15522 (cond
15523 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15524 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15525 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15526 ((org-at-item-p) (call-interactively 'org-outdent-item))
15527 (t (org-modifier-cursor-error))))
15529 (defun org-shiftmetaright ()
15530 "Demote subtree or insert table column.
15531 Calls `org-demote-subtree', `org-indent-item',
15532 or `org-table-insert-column', depending on context.
15533 See the individual commands for more information."
15534 (interactive)
15535 (cond
15536 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15537 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15538 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15539 ((org-at-item-p) (call-interactively 'org-indent-item))
15540 (t (org-modifier-cursor-error))))
15542 (defun org-shiftmetaup (&optional arg)
15543 "Move subtree up or kill table row.
15544 Calls `org-move-subtree-up' or `org-table-kill-row' or
15545 `org-move-item-up' depending on context. See the individual commands
15546 for more information."
15547 (interactive "P")
15548 (cond
15549 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15550 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15551 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15552 ((org-at-item-p) (call-interactively 'org-move-item-up))
15553 (t (org-modifier-cursor-error))))
15555 (defun org-shiftmetadown (&optional arg)
15556 "Move subtree down or insert table row.
15557 Calls `org-move-subtree-down' or `org-table-insert-row' or
15558 `org-move-item-down', depending on context. See the individual
15559 commands for more information."
15560 (interactive "P")
15561 (cond
15562 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15563 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15564 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15565 ((org-at-item-p) (call-interactively 'org-move-item-down))
15566 (t (org-modifier-cursor-error))))
15568 (defun org-metaleft (&optional arg)
15569 "Promote heading or move table column to left.
15570 Calls `org-do-promote' or `org-table-move-column', depending on context.
15571 With no specific context, calls the Emacs default `backward-word'.
15572 See the individual commands for more information."
15573 (interactive "P")
15574 (cond
15575 ((run-hook-with-args-until-success 'org-metaleft-hook))
15576 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15577 ((or (org-on-heading-p)
15578 (and (org-region-active-p)
15579 (save-excursion
15580 (goto-char (region-beginning))
15581 (org-on-heading-p))))
15582 (call-interactively 'org-do-promote))
15583 ((or (org-at-item-p)
15584 (and (org-region-active-p)
15585 (save-excursion
15586 (goto-char (region-beginning))
15587 (org-at-item-p))))
15588 (call-interactively 'org-outdent-item))
15589 (t (call-interactively 'backward-word))))
15591 (defun org-metaright (&optional arg)
15592 "Demote subtree or move table column to right.
15593 Calls `org-do-demote' or `org-table-move-column', depending on context.
15594 With no specific context, calls the Emacs default `forward-word'.
15595 See the individual commands for more information."
15596 (interactive "P")
15597 (cond
15598 ((run-hook-with-args-until-success 'org-metaright-hook))
15599 ((org-at-table-p) (call-interactively 'org-table-move-column))
15600 ((or (org-on-heading-p)
15601 (and (org-region-active-p)
15602 (save-excursion
15603 (goto-char (region-beginning))
15604 (org-on-heading-p))))
15605 (call-interactively 'org-do-demote))
15606 ((or (org-at-item-p)
15607 (and (org-region-active-p)
15608 (save-excursion
15609 (goto-char (region-beginning))
15610 (org-at-item-p))))
15611 (call-interactively 'org-indent-item))
15612 (t (call-interactively 'forward-word))))
15614 (defun org-metaup (&optional arg)
15615 "Move subtree up or move table row up.
15616 Calls `org-move-subtree-up' or `org-table-move-row' or
15617 `org-move-item-up', depending on context. See the individual commands
15618 for more information."
15619 (interactive "P")
15620 (cond
15621 ((run-hook-with-args-until-success 'org-metaup-hook))
15622 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15623 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15624 ((org-at-item-p) (call-interactively 'org-move-item-up))
15625 (t (transpose-lines 1) (beginning-of-line -1))))
15627 (defun org-metadown (&optional arg)
15628 "Move subtree down or move table row down.
15629 Calls `org-move-subtree-down' or `org-table-move-row' or
15630 `org-move-item-down', depending on context. See the individual
15631 commands for more information."
15632 (interactive "P")
15633 (cond
15634 ((run-hook-with-args-until-success 'org-metadown-hook))
15635 ((org-at-table-p) (call-interactively 'org-table-move-row))
15636 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15637 ((org-at-item-p) (call-interactively 'org-move-item-down))
15638 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15640 (defun org-shiftup (&optional arg)
15641 "Increase item in timestamp or increase priority of current headline.
15642 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15643 depending on context. See the individual commands for more information."
15644 (interactive "P")
15645 (cond
15646 ((and org-support-shift-select (org-region-active-p))
15647 (org-call-for-shift-select 'previous-line))
15648 ((org-at-timestamp-p t)
15649 (call-interactively (if org-edit-timestamp-down-means-later
15650 'org-timestamp-down 'org-timestamp-up)))
15651 ((and (not (eq org-support-shift-select 'always))
15652 org-enable-priority-commands
15653 (org-on-heading-p))
15654 (call-interactively 'org-priority-up))
15655 ((and (not org-support-shift-select) (org-at-item-p))
15656 (call-interactively 'org-previous-item))
15657 ((org-clocktable-try-shift 'up arg))
15658 (org-support-shift-select
15659 (org-call-for-shift-select 'previous-line))
15660 (t (org-shiftselect-error))))
15662 (defun org-shiftdown (&optional arg)
15663 "Decrease item in timestamp or decrease priority of current headline.
15664 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15665 depending on context. See the individual commands for more information."
15666 (interactive "P")
15667 (cond
15668 ((and org-support-shift-select (org-region-active-p))
15669 (org-call-for-shift-select 'next-line))
15670 ((org-at-timestamp-p t)
15671 (call-interactively (if org-edit-timestamp-down-means-later
15672 'org-timestamp-up 'org-timestamp-down)))
15673 ((and (not (eq org-support-shift-select 'always))
15674 org-enable-priority-commands
15675 (org-on-heading-p))
15676 (call-interactively 'org-priority-down))
15677 ((and (not org-support-shift-select) (org-at-item-p))
15678 (call-interactively 'org-next-item))
15679 ((org-clocktable-try-shift 'down arg))
15680 (org-support-shift-select
15681 (org-call-for-shift-select 'next-line))
15682 (t (org-shiftselect-error))))
15684 (defun org-shiftright (&optional arg)
15685 "Cycle the thing at point or in the current line, depending on context.
15686 Depending on context, this does one of the following:
15688 - switch a timestamp at point one day into the future
15689 - on a headline, switch to the next TODO keyword.
15690 - on an item, switch entire list to the next bullet type
15691 - on a property line, switch to the next allowed value
15692 - on a clocktable definition line, move time block into the future"
15693 (interactive "P")
15694 (cond
15695 ((and org-support-shift-select (org-region-active-p))
15696 (org-call-for-shift-select 'forward-char))
15697 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15698 ((and (not (eq org-support-shift-select 'always))
15699 (org-on-heading-p))
15700 (let ((org-inhibit-logging
15701 (not org-treat-S-cursor-todo-selection-as-state-change))
15702 (org-inhibit-blocking
15703 (not org-treat-S-cursor-todo-selection-as-state-change)))
15704 (org-call-with-arg 'org-todo 'right)))
15705 ((or (and org-support-shift-select
15706 (not (eq org-support-shift-select 'always))
15707 (org-at-item-bullet-p))
15708 (and (not org-support-shift-select) (org-at-item-p)))
15709 (org-call-with-arg 'org-cycle-list-bullet nil))
15710 ((and (not (eq org-support-shift-select 'always))
15711 (org-at-property-p))
15712 (call-interactively 'org-property-next-allowed-value))
15713 ((org-clocktable-try-shift 'right arg))
15714 (org-support-shift-select
15715 (org-call-for-shift-select 'forward-char))
15716 (t (org-shiftselect-error))))
15718 (defun org-shiftleft (&optional arg)
15719 "Cycle the thing at point or in the current line, depending on context.
15720 Depending on context, this does one of the following:
15722 - switch a timestamp at point one day into the past
15723 - on a headline, switch to the previous TODO keyword.
15724 - on an item, switch entire list to the previous bullet type
15725 - on a property line, switch to the previous allowed value
15726 - on a clocktable definition line, move time block into the past"
15727 (interactive "P")
15728 (cond
15729 ((and org-support-shift-select (org-region-active-p))
15730 (org-call-for-shift-select 'backward-char))
15731 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15732 ((and (not (eq org-support-shift-select 'always))
15733 (org-on-heading-p))
15734 (let ((org-inhibit-logging
15735 (not org-treat-S-cursor-todo-selection-as-state-change))
15736 (org-inhibit-blocking
15737 (not org-treat-S-cursor-todo-selection-as-state-change)))
15738 (org-call-with-arg 'org-todo 'left)))
15739 ((or (and org-support-shift-select
15740 (not (eq org-support-shift-select 'always))
15741 (org-at-item-bullet-p))
15742 (and (not org-support-shift-select) (org-at-item-p)))
15743 (org-call-with-arg 'org-cycle-list-bullet 'previous))
15744 ((and (not (eq org-support-shift-select 'always))
15745 (org-at-property-p))
15746 (call-interactively 'org-property-previous-allowed-value))
15747 ((org-clocktable-try-shift 'left arg))
15748 (org-support-shift-select
15749 (org-call-for-shift-select 'backward-char))
15750 (t (org-shiftselect-error))))
15752 (defun org-shiftcontrolright ()
15753 "Switch to next TODO set."
15754 (interactive)
15755 (cond
15756 ((and org-support-shift-select (org-region-active-p))
15757 (org-call-for-shift-select 'forward-word))
15758 ((and (not (eq org-support-shift-select 'always))
15759 (org-on-heading-p))
15760 (org-call-with-arg 'org-todo 'nextset))
15761 (org-support-shift-select
15762 (org-call-for-shift-select 'forward-word))
15763 (t (org-shiftselect-error))))
15765 (defun org-shiftcontrolleft ()
15766 "Switch to previous TODO set."
15767 (interactive)
15768 (cond
15769 ((and org-support-shift-select (org-region-active-p))
15770 (org-call-for-shift-select 'backward-word))
15771 ((and (not (eq org-support-shift-select 'always))
15772 (org-on-heading-p))
15773 (org-call-with-arg 'org-todo 'previousset))
15774 (org-support-shift-select
15775 (org-call-for-shift-select 'backward-word))
15776 (t (org-shiftselect-error))))
15778 (defun org-ctrl-c-ret ()
15779 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15780 (interactive)
15781 (cond
15782 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15783 (t (call-interactively 'org-insert-heading))))
15785 (defun org-copy-special ()
15786 "Copy region in table or copy current subtree.
15787 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15788 See the individual commands for more information."
15789 (interactive)
15790 (call-interactively
15791 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15793 (defun org-cut-special ()
15794 "Cut region in table or cut current subtree.
15795 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15796 See the individual commands for more information."
15797 (interactive)
15798 (call-interactively
15799 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15801 (defun org-paste-special (arg)
15802 "Paste rectangular region into table, or past subtree relative to level.
15803 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15804 See the individual commands for more information."
15805 (interactive "P")
15806 (if (org-at-table-p)
15807 (org-table-paste-rectangle)
15808 (org-paste-subtree arg)))
15810 (defun org-edit-special ()
15811 "Call a special editor for the stuff at point.
15812 When at a table, call the formula editor with `org-table-edit-formulas'.
15813 When at the first line of an src example, call `org-edit-src-code'.
15814 When in an #+include line, visit the include file. Otherwise call
15815 `ffap' to visit the file at point."
15816 (interactive)
15817 (cond
15818 ((org-at-table-p)
15819 (call-interactively 'org-table-edit-formulas))
15820 ((save-excursion
15821 (beginning-of-line 1)
15822 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
15823 (find-file (org-trim (match-string 1))))
15824 ((org-edit-src-code))
15825 ((org-edit-fixed-width-region))
15826 (t (call-interactively 'ffap))))
15829 (defun org-ctrl-c-ctrl-c (&optional arg)
15830 "Set tags in headline, or update according to changed information at point.
15832 This command does many different things, depending on context:
15834 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15835 this is what we do.
15837 - If the cursor is on a statistics cookie, update it.
15839 - If the cursor is in a headline, prompt for tags and insert them
15840 into the current line, aligned to `org-tags-column'. When called
15841 with prefix arg, realign all tags in the current buffer.
15843 - If the cursor is in one of the special #+KEYWORD lines, this
15844 triggers scanning the buffer for these lines and updating the
15845 information.
15847 - If the cursor is inside a table, realign the table. This command
15848 works even if the automatic table editor has been turned off.
15850 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15851 the entire table.
15853 - If the cursor is at a footnote reference or definition, jump to
15854 the corresponding definition or references, respectively.
15856 - If the cursor is a the beginning of a dynamic block, update it.
15858 - If the cursor is inside a table created by the table.el package,
15859 activate that table.
15861 - If the current buffer is a remember buffer, close note and file
15862 it. A prefix argument of 1 files to the default location
15863 without further interaction. A prefix argument of 2 files to
15864 the currently clocking task.
15866 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15867 links in this buffer.
15869 - If the cursor is on a numbered item in a plain list, renumber the
15870 ordered list.
15872 - If the cursor is on a checkbox, toggle it."
15873 (interactive "P")
15874 (let ((org-enable-table-editor t))
15875 (cond
15876 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15877 org-occur-highlights
15878 org-latex-fragment-image-overlays)
15879 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15880 (org-remove-occur-highlights)
15881 (org-remove-latex-fragment-image-overlays)
15882 (message "Temporary highlights/overlays removed from current buffer"))
15883 ((and (local-variable-p 'org-finish-function (current-buffer))
15884 (fboundp org-finish-function))
15885 (funcall org-finish-function))
15886 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15887 ((org-at-property-p)
15888 (call-interactively 'org-property-action))
15889 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15890 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15891 (or (org-on-heading-p) (org-at-item-p)))
15892 (call-interactively 'org-update-statistics-cookies))
15893 ((org-on-heading-p) (call-interactively 'org-set-tags))
15894 ((org-at-table.el-p)
15895 (require 'table)
15896 (beginning-of-line 1)
15897 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15898 (call-interactively 'table-recognize-table))
15899 ((org-at-table-p)
15900 (org-table-maybe-eval-formula)
15901 (if arg
15902 (call-interactively 'org-table-recalculate)
15903 (org-table-maybe-recalculate-line))
15904 (call-interactively 'org-table-align))
15905 ((or (org-footnote-at-reference-p)
15906 (org-footnote-at-definition-p))
15907 (call-interactively 'org-footnote-action))
15908 ((org-at-item-checkbox-p)
15909 (call-interactively 'org-toggle-checkbox))
15910 ((org-at-item-p)
15911 (if arg
15912 (call-interactively 'org-toggle-checkbox)
15913 (call-interactively 'org-maybe-renumber-ordered-list)))
15914 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15915 ;; Dynamic block
15916 (beginning-of-line 1)
15917 (save-excursion (org-update-dblock)))
15918 ((save-excursion
15919 (beginning-of-line 1)
15920 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15921 (cond
15922 ((equal (match-string 1) "TBLFM")
15923 ;; Recalculate the table before this line
15924 (save-excursion
15925 (beginning-of-line 1)
15926 (skip-chars-backward " \r\n\t")
15927 (if (org-at-table-p)
15928 (org-call-with-arg 'org-table-recalculate (or arg t)))))
15930 (let ((org-inhibit-startup-visibility-stuff t)
15931 (org-startup-align-all-tables nil))
15932 (org-save-outline-visibility 'use-markers (org-mode-restart)))
15933 (message "Local setup has been refreshed"))))
15934 ((org-clock-update-time-maybe))
15935 (t (error "C-c C-c can do nothing useful at this location")))))
15937 (defun org-mode-restart ()
15938 "Restart Org-mode, to scan again for special lines.
15939 Also updates the keyword regular expressions."
15940 (interactive)
15941 (org-mode)
15942 (message "Org-mode restarted"))
15944 (defun org-kill-note-or-show-branches ()
15945 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15946 (interactive)
15947 (if (not org-finish-function)
15948 (call-interactively 'show-branches)
15949 (let ((org-note-abort t))
15950 (funcall org-finish-function))))
15952 (defun org-return (&optional indent)
15953 "Goto next table row or insert a newline.
15954 Calls `org-table-next-row' or `newline', depending on context.
15955 See the individual commands for more information."
15956 (interactive)
15957 (cond
15958 ((bobp) (if indent (newline-and-indent) (newline)))
15959 ((org-at-table-p)
15960 (org-table-justify-field-maybe)
15961 (call-interactively 'org-table-next-row))
15962 ((and org-return-follows-link
15963 (eq (get-text-property (point) 'face) 'org-link))
15964 (call-interactively 'org-open-at-point))
15965 ((and (org-at-heading-p)
15966 (looking-at
15967 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15968 (org-show-entry)
15969 (end-of-line 1)
15970 (newline))
15971 (t (if indent (newline-and-indent) (newline)))))
15973 (defun org-return-indent ()
15974 "Goto next table row or insert a newline and indent.
15975 Calls `org-table-next-row' or `newline-and-indent', depending on
15976 context. See the individual commands for more information."
15977 (interactive)
15978 (org-return t))
15980 (defun org-ctrl-c-star ()
15981 "Compute table, or change heading status of lines.
15982 Calls `org-table-recalculate' or `org-toggle-heading',
15983 depending on context."
15984 (interactive)
15985 (cond
15986 ((org-at-table-p)
15987 (call-interactively 'org-table-recalculate))
15989 ;; Convert all lines in region to list items
15990 (call-interactively 'org-toggle-heading))))
15992 (defun org-ctrl-c-minus ()
15993 "Insert separator line in table or modify bullet status of line.
15994 Also turns a plain line or a region of lines into list items.
15995 Calls `org-table-insert-hline', `org-toggle-item', or
15996 `org-cycle-list-bullet', depending on context."
15997 (interactive)
15998 (cond
15999 ((org-at-table-p)
16000 (call-interactively 'org-table-insert-hline))
16001 ((org-region-active-p)
16002 (call-interactively 'org-toggle-item))
16003 ((org-in-item-p)
16004 (call-interactively 'org-cycle-list-bullet))
16006 (call-interactively 'org-toggle-item))))
16008 (defun org-toggle-item ()
16009 "Convert headings or normal lines to items, items to normal lines.
16010 If there is no active region, only the current line is considered.
16012 If the first line in the region is a headline, convert all headlines to items.
16014 If the first line in the region is an item, convert all items to normal lines.
16016 If the first line is normal text, add an item bullet to each line."
16017 (interactive)
16018 (let (l2 l beg end)
16019 (if (org-region-active-p)
16020 (setq beg (region-beginning) end (region-end))
16021 (setq beg (point-at-bol)
16022 end (min (1+ (point-at-eol)) (point-max))))
16023 (save-excursion
16024 (goto-char end)
16025 (setq l2 (org-current-line))
16026 (goto-char beg)
16027 (beginning-of-line 1)
16028 (setq l (1- (org-current-line)))
16029 (if (org-at-item-p)
16030 ;; We already have items, de-itemize
16031 (while (< (setq l (1+ l)) l2)
16032 (when (org-at-item-p)
16033 (goto-char (match-beginning 2))
16034 (delete-region (match-beginning 2) (match-end 2))
16035 (and (looking-at "[ \t]+") (replace-match "")))
16036 (beginning-of-line 2))
16037 (if (org-on-heading-p)
16038 ;; Headings, convert to items
16039 (while (< (setq l (1+ l)) l2)
16040 (if (looking-at org-outline-regexp)
16041 (replace-match "- " t t))
16042 (beginning-of-line 2))
16043 ;; normal lines, turn them into items
16044 (while (< (setq l (1+ l)) l2)
16045 (unless (org-at-item-p)
16046 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16047 (replace-match "\\1- \\2")))
16048 (beginning-of-line 2)))))))
16050 (defun org-toggle-heading (&optional nstars)
16051 "Convert headings to normal text, or items or text to headings.
16052 If there is no active region, only the current line is considered.
16054 If the first line is a heading, remove the stars from all headlines
16055 in the region.
16057 If the first line is a plain list item, turn all plain list items
16058 into headings.
16060 If the first line is a normal line, turn each and every line in the
16061 region into a heading.
16063 When converting a line into a heading, the number of stars is chosen
16064 such that the lines become children of the current entry. However,
16065 when a prefix argument is given, its value determines the number of
16066 stars to add."
16067 (interactive "P")
16068 (let (l2 l itemp beg end)
16069 (if (org-region-active-p)
16070 (setq beg (region-beginning) end (region-end))
16071 (setq beg (point-at-bol)
16072 end (min (1+ (point-at-eol)) (point-max))))
16073 (save-excursion
16074 (goto-char end)
16075 (setq l2 (org-current-line))
16076 (goto-char beg)
16077 (beginning-of-line 1)
16078 (setq l (1- (org-current-line)))
16079 (if (org-on-heading-p)
16080 ;; We already have headlines, de-star them
16081 (while (< (setq l (1+ l)) l2)
16082 (when (org-on-heading-p t)
16083 (and (looking-at outline-regexp) (replace-match "")))
16084 (beginning-of-line 2))
16085 (setq itemp (org-at-item-p))
16086 (let* ((stars
16087 (if nstars
16088 (make-string (prefix-numeric-value current-prefix-arg)
16090 (save-excursion
16091 (if (re-search-backward org-complex-heading-regexp nil t)
16092 (match-string 1) ""))))
16093 (add-stars (cond (nstars "")
16094 ((equal stars "") "*")
16095 (org-odd-levels-only "**")
16096 (t "*")))
16097 (rpl (concat stars add-stars " ")))
16098 (while (< (setq l (1+ l)) l2)
16099 (if itemp
16100 (and (org-at-item-p) (replace-match rpl t t))
16101 (unless (org-on-heading-p)
16102 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16103 (replace-match (concat rpl (match-string 2))))))
16104 (beginning-of-line 2)))))))
16106 (defun org-meta-return (&optional arg)
16107 "Insert a new heading or wrap a region in a table.
16108 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16109 See the individual commands for more information."
16110 (interactive "P")
16111 (cond
16112 ((run-hook-with-args-until-success 'org-metareturn-hook))
16113 ((org-at-table-p)
16114 (call-interactively 'org-table-wrap-region))
16115 (t (call-interactively 'org-insert-heading))))
16117 ;;; Menu entries
16119 ;; Define the Org-mode menus
16120 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16121 '("Tbl"
16122 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
16123 ["Next Field" org-cycle (org-at-table-p)]
16124 ["Previous Field" org-shifttab (org-at-table-p)]
16125 ["Next Row" org-return (org-at-table-p)]
16126 "--"
16127 ["Blank Field" org-table-blank-field (org-at-table-p)]
16128 ["Edit Field" org-table-edit-field (org-at-table-p)]
16129 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16130 "--"
16131 ("Column"
16132 ["Move Column Left" org-metaleft (org-at-table-p)]
16133 ["Move Column Right" org-metaright (org-at-table-p)]
16134 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16135 ["Insert Column" org-shiftmetaright (org-at-table-p)])
16136 ("Row"
16137 ["Move Row Up" org-metaup (org-at-table-p)]
16138 ["Move Row Down" org-metadown (org-at-table-p)]
16139 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16140 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16141 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16142 "--"
16143 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
16144 ("Rectangle"
16145 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16146 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16147 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16148 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16149 "--"
16150 ("Calculate"
16151 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16152 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16153 ["Edit Formulas" org-edit-special (org-at-table-p)]
16154 "--"
16155 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16156 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16157 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
16158 "--"
16159 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16160 "--"
16161 ["Sum Column/Rectangle" org-table-sum
16162 (or (org-at-table-p) (org-region-active-p))]
16163 ["Which Column?" org-table-current-column (org-at-table-p)])
16164 ["Debug Formulas"
16165 org-table-toggle-formula-debugger
16166 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
16167 ["Show Col/Row Numbers"
16168 org-table-toggle-coordinate-overlays
16169 :style toggle
16170 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
16171 "--"
16172 ["Create" org-table-create (and (not (org-at-table-p))
16173 org-enable-table-editor)]
16174 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16175 ["Import from File" org-table-import (not (org-at-table-p))]
16176 ["Export to File" org-table-export (org-at-table-p)]
16177 "--"
16178 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16180 (easy-menu-define org-org-menu org-mode-map "Org menu"
16181 '("Org"
16182 ("Show/Hide"
16183 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
16184 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
16185 ["Sparse Tree..." org-sparse-tree t]
16186 ["Reveal Context" org-reveal t]
16187 ["Show All" show-all t]
16188 "--"
16189 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
16190 "--"
16191 ["New Heading" org-insert-heading t]
16192 ("Navigate Headings"
16193 ["Up" outline-up-heading t]
16194 ["Next" outline-next-visible-heading t]
16195 ["Previous" outline-previous-visible-heading t]
16196 ["Next Same Level" outline-forward-same-level t]
16197 ["Previous Same Level" outline-backward-same-level t]
16198 "--"
16199 ["Jump" org-goto t])
16200 ("Edit Structure"
16201 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16202 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16203 "--"
16204 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16205 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16206 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16207 "--"
16208 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
16209 "--"
16210 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16211 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16212 ["Demote Heading" org-metaright (not (org-at-table-p))]
16213 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16214 "--"
16215 ["Sort Region/Children" org-sort (not (org-at-table-p))]
16216 "--"
16217 ["Convert to odd levels" org-convert-to-odd-levels t]
16218 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16219 ("Editing"
16220 ["Emphasis..." org-emphasize t]
16221 ["Edit Source Example" org-edit-special t]
16222 "--"
16223 ["Footnote new/jump" org-footnote-action t]
16224 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
16225 ("Archive"
16226 ["Archive (default method)" org-archive-subtree-default t]
16227 "--"
16228 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
16229 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16230 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
16232 "--"
16233 ("Hyperlinks"
16234 ["Store Link (Global)" org-store-link t]
16235 ["Find existing link to here" org-occur-link-in-agenda-files t]
16236 ["Insert Link" org-insert-link t]
16237 ["Follow Link" org-open-at-point t]
16238 "--"
16239 ["Next link" org-next-link t]
16240 ["Previous link" org-previous-link t]
16241 "--"
16242 ["Descriptive Links"
16243 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16244 :style radio
16245 :selected (member '(org-link) buffer-invisibility-spec)]
16246 ["Literal Links"
16247 (progn
16248 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16249 :style radio
16250 :selected (not (member '(org-link) buffer-invisibility-spec))])
16251 "--"
16252 ("TODO Lists"
16253 ["TODO/DONE/-" org-todo t]
16254 ("Select keyword"
16255 ["Next keyword" org-shiftright (org-on-heading-p)]
16256 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16257 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
16258 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
16259 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
16260 ["Show TODO Tree" org-show-todo-tree t]
16261 ["Global TODO list" org-todo-list t]
16262 "--"
16263 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
16264 :selected org-enforce-todo-dependencies :style toggle :active t]
16265 "Settings for tree at point"
16266 ["Do Children sequentially" org-toggle-ordered-property :style radio
16267 :selected (ignore-errors (org-entry-get nil "ORDERED"))
16268 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16269 ["Do Children parallel" org-toggle-ordered-property :style radio
16270 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
16271 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16272 "--"
16273 ["Set Priority" org-priority t]
16274 ["Priority Up" org-shiftup t]
16275 ["Priority Down" org-shiftdown t]
16276 "--"
16277 ["Get news from all feeds" org-feed-update-all t]
16278 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16279 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16280 ("TAGS and Properties"
16281 ["Set Tags" org-set-tags-command t]
16282 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16283 "--"
16284 ["Set property" org-set-property t]
16285 ["Column view of properties" org-columns t]
16286 ["Insert Column View DBlock" org-insert-columns-dblock t])
16287 ("Dates and Scheduling"
16288 ["Timestamp" org-time-stamp t]
16289 ["Timestamp (inactive)" org-time-stamp-inactive t]
16290 ("Change Date"
16291 ["1 Day Later" org-shiftright t]
16292 ["1 Day Earlier" org-shiftleft t]
16293 ["1 ... Later" org-shiftup t]
16294 ["1 ... Earlier" org-shiftdown t])
16295 ["Compute Time Range" org-evaluate-time-range t]
16296 ["Schedule Item" org-schedule t]
16297 ["Deadline" org-deadline t]
16298 "--"
16299 ["Custom time format" org-toggle-time-stamp-overlays
16300 :style radio :selected org-display-custom-times]
16301 "--"
16302 ["Goto Calendar" org-goto-calendar t]
16303 ["Date from Calendar" org-date-from-calendar t]
16304 "--"
16305 ["Start/Restart Timer" org-timer-start t]
16306 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16307 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16308 ["Insert Timer String" org-timer t]
16309 ["Insert Timer Item" org-timer-item t])
16310 ("Logging work"
16311 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16312 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16313 ["Clock out" org-clock-out t]
16314 ["Clock cancel" org-clock-cancel t]
16315 "--"
16316 ["Mark as default task" org-clock-mark-default-task t]
16317 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16318 ["Goto running clock" org-clock-goto t]
16319 "--"
16320 ["Display times" org-clock-display t]
16321 ["Create clock table" org-clock-report t]
16322 "--"
16323 ["Record DONE time"
16324 (progn (setq org-log-done (not org-log-done))
16325 (message "Switching to %s will %s record a timestamp"
16326 (car org-done-keywords)
16327 (if org-log-done "automatically" "not")))
16328 :style toggle :selected org-log-done])
16329 "--"
16330 ["Agenda Command..." org-agenda t]
16331 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16332 ("File List for Agenda")
16333 ("Special views current file"
16334 ["TODO Tree" org-show-todo-tree t]
16335 ["Check Deadlines" org-check-deadlines t]
16336 ["Timeline" org-timeline t]
16337 ["Tags/Property tree" org-match-sparse-tree t])
16338 "--"
16339 ["Export/Publish..." org-export t]
16340 ("LaTeX"
16341 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16342 :selected org-cdlatex-mode]
16343 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16344 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16345 ["Modify math symbol" org-cdlatex-math-modify
16346 (org-inside-LaTeX-fragment-p)]
16347 ["Insert citation" org-reftex-citation t]
16348 "--"
16349 ["Export LaTeX fragments as images"
16350 (if (featurep 'org-exp)
16351 (setq org-export-with-LaTeX-fragments
16352 (not org-export-with-LaTeX-fragments))
16353 (require 'org-exp))
16354 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16355 org-export-with-LaTeX-fragments)]
16356 "--"
16357 ["Template for BEAMER" org-beamer-settings-template t])
16358 "--"
16359 ("MobileOrg"
16360 ["Push Files and Views" org-mobile-push t]
16361 ["Get Captured and Flagged" org-mobile-pull t]
16362 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16363 "--"
16364 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16365 "--"
16366 ("Documentation"
16367 ["Show Version" org-version t]
16368 ["Info Documentation" org-info t])
16369 ("Customize"
16370 ["Browse Org Group" org-customize t]
16371 "--"
16372 ["Expand This Menu" org-create-customize-menu
16373 (fboundp 'customize-menu-create)])
16374 ["Send bug report" org-submit-bug-report t]
16375 "--"
16376 ("Refresh/Reload"
16377 ["Refresh setup current buffer" org-mode-restart t]
16378 ["Reload Org (after update)" org-reload t]
16379 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16382 (defun org-info (&optional node)
16383 "Read documentation for Org-mode in the info system.
16384 With optional NODE, go directly to that node."
16385 (interactive)
16386 (info (format "(org)%s" (or node ""))))
16388 ;;;###autoload
16389 (defun org-submit-bug-report ()
16390 "Submit a bug report on Org-mode via mail.
16392 Don't hesitate to report any problems or inaccurate documentation.
16394 If you don't have setup sending mail from (X)Emacs, please copy the
16395 output buffer into your mail program, as it gives us important
16396 information about your Org-mode version and configuration."
16397 (interactive)
16398 (require 'reporter)
16399 (org-load-modules-maybe)
16400 (org-require-autoloaded-modules)
16401 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16402 (reporter-submit-bug-report
16403 "emacs-orgmode@gnu.org"
16404 (org-version)
16405 (let (list)
16406 (save-window-excursion
16407 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16408 (delete-other-windows)
16409 (erase-buffer)
16410 (insert "You are about to submit a bug report to the Org-mode mailing list.
16412 We would like to add your full Org-mode and Outline configuration to the
16413 bug report. This greatly simplifies the work of the maintainer and
16414 other experts on the mailing list.
16416 HOWEVER, some variables you have customized may contain private
16417 information. The names of customers, colleagues, or friends, might
16418 appear in the form of file names, tags, todo states, or search strings.
16419 If you answer yes to the prompt, you might want to check and remove
16420 such private information before sending the email.")
16421 (add-text-properties (point-min) (point-max) '(face org-warning))
16422 (when (yes-or-no-p "Include your Org-mode configuration ")
16423 (mapatoms
16424 (lambda (v)
16425 (and (boundp v)
16426 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16427 (or (and (symbol-value v)
16428 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16429 (and
16430 (get v 'custom-type) (get v 'standard-value)
16431 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16432 (push v list)))))
16433 (kill-buffer (get-buffer "*Warn about privacy*"))
16434 list))
16435 nil nil
16436 "Remember to cover the basics, that is, what you expected to happen and
16437 what in fact did happen. You don't know how to make a good report? See
16439 http://orgmode.org/manual/Feedback.html#Feedback
16441 Your bug report will be posted to the Org-mode mailing list.
16442 ------------------------------------------------------------------------")
16443 (save-excursion
16444 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16445 (replace-match "\\1Bug: \\3 [\\2]")))))
16448 (defun org-install-agenda-files-menu ()
16449 (let ((bl (buffer-list)))
16450 (save-excursion
16451 (while bl
16452 (set-buffer (pop bl))
16453 (if (org-mode-p) (setq bl nil)))
16454 (when (org-mode-p)
16455 (easy-menu-change
16456 '("Org") "File List for Agenda"
16457 (append
16458 (list
16459 ["Edit File List" (org-edit-agenda-file-list) t]
16460 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16461 ["Remove Current File from List" org-remove-file t]
16462 ["Cycle through agenda files" org-cycle-agenda-files t]
16463 ["Occur in all agenda files" org-occur-in-agenda-files t]
16464 "--")
16465 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16467 ;;;; Documentation
16469 ;;;###autoload
16470 (defun org-require-autoloaded-modules ()
16471 (interactive)
16472 (mapc 'require
16473 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16474 org-docbook org-exp org-html org-icalendar
16475 org-id org-latex
16476 org-publish org-remember org-table
16477 org-timer org-xoxo)))
16479 ;;;###autoload
16480 (defun org-reload (&optional uncompiled)
16481 "Reload all org lisp files.
16482 With prefix arg UNCOMPILED, load the uncompiled versions."
16483 (interactive "P")
16484 (require 'find-func)
16485 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16486 (dir-org (file-name-directory (org-find-library-name "org")))
16487 (dir-org-contrib (ignore-errors
16488 (file-name-directory
16489 (org-find-library-name "org-contribdir"))))
16490 (files
16491 (append (directory-files dir-org t file-re)
16492 (and dir-org-contrib
16493 (directory-files dir-org-contrib t file-re))))
16494 (remove-re (concat (if (featurep 'xemacs)
16495 "org-colview" "org-colview-xemacs")
16496 "\\'")))
16497 (setq files (mapcar 'file-name-sans-extension files))
16498 (setq files (mapcar
16499 (lambda (x) (if (string-match remove-re x) nil x))
16500 files))
16501 (setq files (delq nil files))
16502 (mapc
16503 (lambda (f)
16504 (when (featurep (intern (file-name-nondirectory f)))
16505 (if (and (not uncompiled)
16506 (file-exists-p (concat f ".elc")))
16507 (load (concat f ".elc") nil nil t)
16508 (load (concat f ".el") nil nil t))))
16509 files))
16510 (org-version))
16512 ;;;###autoload
16513 (defun org-customize ()
16514 "Call the customize function with org as argument."
16515 (interactive)
16516 (org-load-modules-maybe)
16517 (org-require-autoloaded-modules)
16518 (customize-browse 'org))
16520 (defun org-create-customize-menu ()
16521 "Create a full customization menu for Org-mode, insert it into the menu."
16522 (interactive)
16523 (org-load-modules-maybe)
16524 (org-require-autoloaded-modules)
16525 (if (fboundp 'customize-menu-create)
16526 (progn
16527 (easy-menu-change
16528 '("Org") "Customize"
16529 `(["Browse Org group" org-customize t]
16530 "--"
16531 ,(customize-menu-create 'org)
16532 ["Set" Custom-set t]
16533 ["Save" Custom-save t]
16534 ["Reset to Current" Custom-reset-current t]
16535 ["Reset to Saved" Custom-reset-saved t]
16536 ["Reset to Standard Settings" Custom-reset-standard t]))
16537 (message "\"Org\"-menu now contains full customization menu"))
16538 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16540 ;;;; Miscellaneous stuff
16542 ;;; Generally useful functions
16544 (defun org-get-at-bol (property)
16545 "Get text property PROPERTY at beginning of line."
16546 (get-text-property (point-at-bol) property))
16548 (defun org-find-text-property-in-string (prop s)
16549 "Return the first non-nil value of property PROP in string S."
16550 (or (get-text-property 0 prop s)
16551 (get-text-property (or (next-single-property-change 0 prop s) 0)
16552 prop s)))
16554 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16555 "Display the given MESSAGE as a warning."
16556 (if (fboundp 'display-warning)
16557 (display-warning 'org message
16558 (if (featurep 'xemacs)
16559 'warning
16560 :warning))
16561 (let ((buf (get-buffer-create "*Org warnings*")))
16562 (with-current-buffer buf
16563 (goto-char (point-max))
16564 (insert "Warning (Org): " message)
16565 (unless (bolp)
16566 (newline)))
16567 (display-buffer buf)
16568 (sit-for 0))))
16570 (defun org-in-commented-line ()
16571 "Is point in a line starting with `#'?"
16572 (equal (char-after (point-at-bol)) ?#))
16574 (defun org-in-verbatim-emphasis ()
16575 (save-match-data
16576 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16578 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16579 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16580 (if (and marker (marker-buffer marker)
16581 (buffer-live-p (marker-buffer marker)))
16582 (progn
16583 (switch-to-buffer (marker-buffer marker))
16584 (if (or (> marker (point-max)) (< marker (point-min)))
16585 (widen))
16586 (goto-char marker)
16587 (org-show-context 'org-goto))
16588 (if bookmark
16589 (bookmark-jump bookmark)
16590 (error "Cannot find location"))))
16592 (defun org-quote-csv-field (s)
16593 "Quote field for inclusion in CSV material."
16594 (if (string-match "[\",]" s)
16595 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16598 (defun org-plist-delete (plist property)
16599 "Delete PROPERTY from PLIST.
16600 This is in contrast to merely setting it to 0."
16601 (let (p)
16602 (while plist
16603 (if (not (eq property (car plist)))
16604 (setq p (plist-put p (car plist) (nth 1 plist))))
16605 (setq plist (cddr plist)))
16608 (defun org-force-self-insert (N)
16609 "Needed to enforce self-insert under remapping."
16610 (interactive "p")
16611 (self-insert-command N))
16613 (defun org-string-width (s)
16614 "Compute width of string, ignoring invisible characters.
16615 This ignores character with invisibility property `org-link', and also
16616 characters with property `org-cwidth', because these will become invisible
16617 upon the next fontification round."
16618 (let (b l)
16619 (when (or (eq t buffer-invisibility-spec)
16620 (assq 'org-link buffer-invisibility-spec))
16621 (while (setq b (text-property-any 0 (length s)
16622 'invisible 'org-link s))
16623 (setq s (concat (substring s 0 b)
16624 (substring s (or (next-single-property-change
16625 b 'invisible s) (length s)))))))
16626 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16627 (setq s (concat (substring s 0 b)
16628 (substring s (or (next-single-property-change
16629 b 'org-cwidth s) (length s))))))
16630 (setq l (string-width s) b -1)
16631 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16632 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16635 (defun org-get-indentation (&optional line)
16636 "Get the indentation of the current line, interpreting tabs.
16637 When LINE is given, assume it represents a line and compute its indentation."
16638 (if line
16639 (if (string-match "^ *" (org-remove-tabs line))
16640 (match-end 0))
16641 (save-excursion
16642 (beginning-of-line 1)
16643 (skip-chars-forward " \t")
16644 (current-column))))
16646 (defun org-remove-tabs (s &optional width)
16647 "Replace tabulators in S with spaces.
16648 Assumes that s is a single line, starting in column 0."
16649 (setq width (or width tab-width))
16650 (while (string-match "\t" s)
16651 (setq s (replace-match
16652 (make-string
16653 (- (* width (/ (+ (match-beginning 0) width) width))
16654 (match-beginning 0)) ?\ )
16655 t t s)))
16658 (defun org-fix-indentation (line ind)
16659 "Fix indentation in LINE.
16660 IND is a cons cell with target and minimum indentation.
16661 If the current indentation in LINE is smaller than the minimum,
16662 leave it alone. If it is larger than ind, set it to the target."
16663 (let* ((l (org-remove-tabs line))
16664 (i (org-get-indentation l))
16665 (i1 (car ind)) (i2 (cdr ind)))
16666 (if (>= i i2) (setq l (substring line i2)))
16667 (if (> i1 0)
16668 (concat (make-string i1 ?\ ) l)
16669 l)))
16671 (defun org-remove-indentation (code &optional n)
16672 "Remove the maximum common indentation from the lines in CODE.
16673 N may optionally be the number of spaces to remove."
16674 (with-temp-buffer
16675 (insert code)
16676 (org-do-remove-indentation n)
16677 (buffer-string)))
16679 (defun org-do-remove-indentation (&optional n)
16680 "Remove the maximum common indentation from the buffer."
16681 (untabify (point-min) (point-max))
16682 (let ((min 10000) re)
16683 (if n
16684 (setq min n)
16685 (goto-char (point-min))
16686 (while (re-search-forward "^ *[^ \n]" nil t)
16687 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16688 (unless (or (= min 0) (= min 10000))
16689 (setq re (format "^ \\{%d\\}" min))
16690 (goto-char (point-min))
16691 (while (re-search-forward re nil t)
16692 (replace-match "")
16693 (end-of-line 1))
16694 min)))
16696 (defun org-fill-template (template alist)
16697 "Find each %key of ALIST in TEMPLATE and replace it."
16698 (let ((case-fold-search nil)
16699 entry key value)
16700 (setq alist (sort (copy-sequence alist)
16701 (lambda (a b) (< (length (car a)) (length (car b))))))
16702 (while (setq entry (pop alist))
16703 (setq template
16704 (replace-regexp-in-string
16705 (concat "%" (regexp-quote (car entry)))
16706 (cdr entry) template t t)))
16707 template))
16709 (defun org-base-buffer (buffer)
16710 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16711 (if (not buffer)
16712 buffer
16713 (or (buffer-base-buffer buffer)
16714 buffer)))
16716 (defun org-trim (s)
16717 "Remove whitespace at beginning and end of string."
16718 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
16719 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
16722 (defun org-wrap (string &optional width lines)
16723 "Wrap string to either a number of lines, or a width in characters.
16724 If WIDTH is non-nil, the string is wrapped to that width, however many lines
16725 that costs. If there is a word longer than WIDTH, the text is actually
16726 wrapped to the length of that word.
16727 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
16728 many lines, whatever width that takes.
16729 The return value is a list of lines, without newlines at the end."
16730 (let* ((words (org-split-string string "[ \t\n]+"))
16731 (maxword (apply 'max (mapcar 'org-string-width words)))
16732 w ll)
16733 (cond (width
16734 (org-do-wrap words (max maxword width)))
16735 (lines
16736 (setq w maxword)
16737 (setq ll (org-do-wrap words maxword))
16738 (if (<= (length ll) lines)
16740 (setq ll words)
16741 (while (> (length ll) lines)
16742 (setq w (1+ w))
16743 (setq ll (org-do-wrap words w)))
16744 ll))
16745 (t (error "Cannot wrap this")))))
16747 (defun org-do-wrap (words width)
16748 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
16749 (let (lines line)
16750 (while words
16751 (setq line (pop words))
16752 (while (and words (< (+ (length line) (length (car words))) width))
16753 (setq line (concat line " " (pop words))))
16754 (setq lines (push line lines)))
16755 (nreverse lines)))
16757 (defun org-split-string (string &optional separators)
16758 "Splits STRING into substrings at SEPARATORS.
16759 No empty strings are returned if there are matches at the beginning
16760 and end of string."
16761 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
16762 (start 0)
16763 notfirst
16764 (list nil))
16765 (while (and (string-match rexp string
16766 (if (and notfirst
16767 (= start (match-beginning 0))
16768 (< start (length string)))
16769 (1+ start) start))
16770 (< (match-beginning 0) (length string)))
16771 (setq notfirst t)
16772 (or (eq (match-beginning 0) 0)
16773 (and (eq (match-beginning 0) (match-end 0))
16774 (eq (match-beginning 0) start))
16775 (setq list
16776 (cons (substring string start (match-beginning 0))
16777 list)))
16778 (setq start (match-end 0)))
16779 (or (eq start (length string))
16780 (setq list
16781 (cons (substring string start)
16782 list)))
16783 (nreverse list)))
16785 (defun org-quote-vert (s)
16786 "Replace \"|\" with \"\\vert\"."
16787 (while (string-match "|" s)
16788 (setq s (replace-match "\\vert" t t s)))
16791 (defun org-uuidgen-p (s)
16792 "Is S an ID created by UUIDGEN?"
16793 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16795 (defun org-context ()
16796 "Return a list of contexts of the current cursor position.
16797 If several contexts apply, all are returned.
16798 Each context entry is a list with a symbol naming the context, and
16799 two positions indicating start and end of the context. Possible
16800 contexts are:
16802 :headline anywhere in a headline
16803 :headline-stars on the leading stars in a headline
16804 :todo-keyword on a TODO keyword (including DONE) in a headline
16805 :tags on the TAGS in a headline
16806 :priority on the priority cookie in a headline
16807 :item on the first line of a plain list item
16808 :item-bullet on the bullet/number of a plain list item
16809 :checkbox on the checkbox in a plain list item
16810 :table in an org-mode table
16811 :table-special on a special filed in a table
16812 :table-table in a table.el table
16813 :link on a hyperlink
16814 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16815 :target on a <<target>>
16816 :radio-target on a <<<radio-target>>>
16817 :latex-fragment on a LaTeX fragment
16818 :latex-preview on a LaTeX fragment with overlayed preview image
16820 This function expects the position to be visible because it uses font-lock
16821 faces as a help to recognize the following contexts: :table-special, :link,
16822 and :keyword."
16823 (let* ((f (get-text-property (point) 'face))
16824 (faces (if (listp f) f (list f)))
16825 (p (point)) clist o)
16826 ;; First the large context
16827 (cond
16828 ((org-on-heading-p t)
16829 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16830 (when (progn
16831 (beginning-of-line 1)
16832 (looking-at org-todo-line-tags-regexp))
16833 (push (org-point-in-group p 1 :headline-stars) clist)
16834 (push (org-point-in-group p 2 :todo-keyword) clist)
16835 (push (org-point-in-group p 4 :tags) clist))
16836 (goto-char p)
16837 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
16838 (if (looking-at "\\[#[A-Z0-9]\\]")
16839 (push (org-point-in-group p 0 :priority) clist)))
16841 ((org-at-item-p)
16842 (push (org-point-in-group p 2 :item-bullet) clist)
16843 (push (list :item (point-at-bol)
16844 (save-excursion (org-end-of-item) (point)))
16845 clist)
16846 (and (org-at-item-checkbox-p)
16847 (push (org-point-in-group p 0 :checkbox) clist)))
16849 ((org-at-table-p)
16850 (push (list :table (org-table-begin) (org-table-end)) clist)
16851 (if (memq 'org-formula faces)
16852 (push (list :table-special
16853 (previous-single-property-change p 'face)
16854 (next-single-property-change p 'face)) clist)))
16855 ((org-at-table-p 'any)
16856 (push (list :table-table) clist)))
16857 (goto-char p)
16859 ;; Now the small context
16860 (cond
16861 ((org-at-timestamp-p)
16862 (push (org-point-in-group p 0 :timestamp) clist))
16863 ((memq 'org-link faces)
16864 (push (list :link
16865 (previous-single-property-change p 'face)
16866 (next-single-property-change p 'face)) clist))
16867 ((memq 'org-special-keyword faces)
16868 (push (list :keyword
16869 (previous-single-property-change p 'face)
16870 (next-single-property-change p 'face)) clist))
16871 ((org-on-target-p)
16872 (push (org-point-in-group p 0 :target) clist)
16873 (goto-char (1- (match-beginning 0)))
16874 (if (looking-at org-radio-target-regexp)
16875 (push (org-point-in-group p 0 :radio-target) clist))
16876 (goto-char p))
16877 ((setq o (car (delq nil
16878 (mapcar
16879 (lambda (x)
16880 (if (memq x org-latex-fragment-image-overlays) x))
16881 (org-overlays-at (point))))))
16882 (push (list :latex-fragment
16883 (org-overlay-start o) (org-overlay-end o)) clist)
16884 (push (list :latex-preview
16885 (org-overlay-start o) (org-overlay-end o)) clist))
16886 ((org-inside-LaTeX-fragment-p)
16887 ;; FIXME: positions wrong.
16888 (push (list :latex-fragment (point) (point)) clist)))
16890 (setq clist (nreverse (delq nil clist)))
16891 clist))
16893 ;; FIXME: Compare with at-regexp-p Do we need both?
16894 (defun org-in-regexp (re &optional nlines visually)
16895 "Check if point is inside a match of regexp.
16896 Normally only the current line is checked, but you can include NLINES extra
16897 lines both before and after point into the search.
16898 If VISUALLY is set, require that the cursor is not after the match but
16899 really on, so that the block visually is on the match."
16900 (catch 'exit
16901 (let ((pos (point))
16902 (eol (point-at-eol (+ 1 (or nlines 0))))
16903 (inc (if visually 1 0)))
16904 (save-excursion
16905 (beginning-of-line (- 1 (or nlines 0)))
16906 (while (re-search-forward re eol t)
16907 (if (and (<= (match-beginning 0) pos)
16908 (>= (+ inc (match-end 0)) pos))
16909 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16911 (defun org-at-regexp-p (regexp)
16912 "Is point inside a match of REGEXP in the current line?"
16913 (catch 'exit
16914 (save-excursion
16915 (let ((pos (point)) (end (point-at-eol)))
16916 (beginning-of-line 1)
16917 (while (re-search-forward regexp end t)
16918 (if (and (<= (match-beginning 0) pos)
16919 (>= (match-end 0) pos))
16920 (throw 'exit t)))
16921 nil))))
16923 (defun org-occur-in-agenda-files (regexp &optional nlines)
16924 "Call `multi-occur' with buffers for all agenda files."
16925 (interactive "sOrg-files matching: \np")
16926 (let* ((files (org-agenda-files))
16927 (tnames (mapcar 'file-truename files))
16928 (extra org-agenda-text-search-extra-files)
16930 (when (eq (car extra) 'agenda-archives)
16931 (setq extra (cdr extra))
16932 (setq files (org-add-archive-files files)))
16933 (while (setq f (pop extra))
16934 (unless (member (file-truename f) tnames)
16935 (add-to-list 'files f 'append)
16936 (add-to-list 'tnames (file-truename f) 'append)))
16937 (multi-occur
16938 (mapcar (lambda (x)
16939 (with-current-buffer
16940 (or (get-file-buffer x) (find-file-noselect x))
16941 (widen)
16942 (current-buffer)))
16943 files)
16944 regexp)))
16946 (if (boundp 'occur-mode-find-occurrence-hook)
16947 ;; Emacs 23
16948 (add-hook 'occur-mode-find-occurrence-hook
16949 (lambda ()
16950 (when (org-mode-p)
16951 (org-reveal))))
16952 ;; Emacs 22
16953 (defadvice occur-mode-goto-occurrence
16954 (after org-occur-reveal activate)
16955 (and (org-mode-p) (org-reveal)))
16956 (defadvice occur-mode-goto-occurrence-other-window
16957 (after org-occur-reveal activate)
16958 (and (org-mode-p) (org-reveal)))
16959 (defadvice occur-mode-display-occurrence
16960 (after org-occur-reveal activate)
16961 (when (org-mode-p)
16962 (let ((pos (occur-mode-find-occurrence)))
16963 (with-current-buffer (marker-buffer pos)
16964 (save-excursion
16965 (goto-char pos)
16966 (org-reveal)))))))
16968 (defun org-occur-link-in-agenda-files ()
16969 "Create a link and search for it in the agendas.
16970 The link is not stored in `org-stored-links', it is just created
16971 for the search purpose."
16972 (interactive)
16973 (let ((link (condition-case nil
16974 (org-store-link nil)
16975 (error "Unable to create a link to here"))))
16976 (org-occur-in-agenda-files (regexp-quote link))))
16978 (defun org-uniquify (list)
16979 "Remove duplicate elements from LIST."
16980 (let (res)
16981 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16982 res))
16984 (defun org-delete-all (elts list)
16985 "Remove all elements in ELTS from LIST."
16986 (while elts
16987 (setq list (delete (pop elts) list)))
16988 list)
16990 (defun org-back-over-empty-lines ()
16991 "Move backwards over whitespace, to the beginning of the first empty line.
16992 Returns the number of empty lines passed."
16993 (let ((pos (point)))
16994 (skip-chars-backward " \t\n\r")
16995 (beginning-of-line 2)
16996 (goto-char (min (point) pos))
16997 (count-lines (point) pos)))
16999 (defun org-skip-whitespace ()
17000 (skip-chars-forward " \t\n\r"))
17002 (defun org-point-in-group (point group &optional context)
17003 "Check if POINT is in match-group GROUP.
17004 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
17005 match. If the match group does ot exist or point is not inside it,
17006 return nil."
17007 (and (match-beginning group)
17008 (>= point (match-beginning group))
17009 (<= point (match-end group))
17010 (if context
17011 (list context (match-beginning group) (match-end group))
17012 t)))
17014 (defun org-switch-to-buffer-other-window (&rest args)
17015 "Switch to buffer in a second window on the current frame.
17016 In particular, do not allow pop-up frames."
17017 (let (pop-up-frames special-display-buffer-names special-display-regexps
17018 special-display-function)
17019 (apply 'switch-to-buffer-other-window args)))
17021 (defun org-combine-plists (&rest plists)
17022 "Create a single property list from all plists in PLISTS.
17023 The process starts by copying the first list, and then setting properties
17024 from the other lists. Settings in the last list are the most significant
17025 ones and overrule settings in the other lists."
17026 (let ((rtn (copy-sequence (pop plists)))
17027 p v ls)
17028 (while plists
17029 (setq ls (pop plists))
17030 (while ls
17031 (setq p (pop ls) v (pop ls))
17032 (setq rtn (plist-put rtn p v))))
17033 rtn))
17035 (defun org-move-line-down (arg)
17036 "Move the current line down. With prefix argument, move it past ARG lines."
17037 (interactive "p")
17038 (let ((col (current-column))
17039 beg end pos)
17040 (beginning-of-line 1) (setq beg (point))
17041 (beginning-of-line 2) (setq end (point))
17042 (beginning-of-line (+ 1 arg))
17043 (setq pos (move-marker (make-marker) (point)))
17044 (insert (delete-and-extract-region beg end))
17045 (goto-char pos)
17046 (org-move-to-column col)))
17048 (defun org-move-line-up (arg)
17049 "Move the current line up. With prefix argument, move it past ARG lines."
17050 (interactive "p")
17051 (let ((col (current-column))
17052 beg end pos)
17053 (beginning-of-line 1) (setq beg (point))
17054 (beginning-of-line 2) (setq end (point))
17055 (beginning-of-line (- arg))
17056 (setq pos (move-marker (make-marker) (point)))
17057 (insert (delete-and-extract-region beg end))
17058 (goto-char pos)
17059 (org-move-to-column col)))
17061 (defun org-replace-escapes (string table)
17062 "Replace %-escapes in STRING with values in TABLE.
17063 TABLE is an association list with keys like \"%a\" and string values.
17064 The sequences in STRING may contain normal field width and padding information,
17065 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
17066 so values can contain further %-escapes if they are define later in TABLE."
17067 (let ((case-fold-search nil)
17068 e re rpl)
17069 (while (setq e (pop table))
17070 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
17071 (while (string-match re string)
17072 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
17073 (cdr e)))
17074 (setq string (replace-match rpl t t string))))
17075 string))
17078 (defun org-sublist (list start end)
17079 "Return a section of LIST, from START to END.
17080 Counting starts at 1."
17081 (let (rtn (c start))
17082 (setq list (nthcdr (1- start) list))
17083 (while (and list (<= c end))
17084 (push (pop list) rtn)
17085 (setq c (1+ c)))
17086 (nreverse rtn)))
17088 (defun org-find-base-buffer-visiting (file)
17089 "Like `find-buffer-visiting' but always return the base buffer and
17090 not an indirect buffer."
17091 (let ((buf (or (get-file-buffer file)
17092 (find-buffer-visiting file))))
17093 (if buf
17094 (or (buffer-base-buffer buf) buf)
17095 nil)))
17097 (defun org-image-file-name-regexp (&optional extensions)
17098 "Return regexp matching the file names of images.
17099 If EXTENSIONS is given, only match these."
17100 (if (and (not extensions) (fboundp 'image-file-name-regexp))
17101 (image-file-name-regexp)
17102 (let ((image-file-name-extensions
17103 (or extensions
17104 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
17105 "xbm" "xpm" "pbm" "pgm" "ppm"))))
17106 (concat "\\."
17107 (regexp-opt (nconc (mapcar 'upcase
17108 image-file-name-extensions)
17109 image-file-name-extensions)
17111 "\\'"))))
17113 (defun org-file-image-p (file &optional extensions)
17114 "Return non-nil if FILE is an image."
17115 (save-match-data
17116 (string-match (org-image-file-name-regexp extensions) file)))
17118 (defun org-get-cursor-date ()
17119 "Return the date at cursor in as a time.
17120 This works in the calendar and in the agenda, anywhere else it just
17121 returns the current time."
17122 (let (date day defd)
17123 (cond
17124 ((eq major-mode 'calendar-mode)
17125 (setq date (calendar-cursor-to-date)
17126 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17127 ((eq major-mode 'org-agenda-mode)
17128 (setq day (get-text-property (point) 'day))
17129 (if day
17130 (setq date (calendar-gregorian-from-absolute day)
17131 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
17132 (nth 2 date))))))
17133 (or defd (current-time))))
17135 (defvar org-agenda-action-marker (make-marker)
17136 "Marker pointing to the entry for the next agenda action.")
17138 (defun org-mark-entry-for-agenda-action ()
17139 "Mark the current entry as target of an agenda action.
17140 Agenda actions are actions executed from the agenda with the key `k',
17141 which make use of the date at the cursor."
17142 (interactive)
17143 (move-marker org-agenda-action-marker
17144 (save-excursion (org-back-to-heading t) (point))
17145 (current-buffer))
17146 (message
17147 "Entry marked for action; press `k' at desired date in agenda or calendar"))
17149 ;;; Paragraph filling stuff.
17150 ;; We want this to be just right, so use the full arsenal.
17152 (defun org-indent-line-function ()
17153 "Indent line like previous, but further if previous was headline or item."
17154 (interactive)
17155 (let* ((pos (point))
17156 (itemp (org-at-item-p))
17157 (case-fold-search t)
17158 (org-drawer-regexp (or org-drawer-regexp "\000"))
17159 column bpos bcol tpos tcol bullet btype bullet-type)
17160 ;; Find the previous relevant line
17161 (beginning-of-line 1)
17162 (cond
17163 ((looking-at "#") (setq column 0))
17164 ((looking-at "\\*+ ") (setq column 0))
17165 ((and (looking-at "[ \t]*:END:")
17166 (save-excursion (re-search-backward org-drawer-regexp nil t)))
17167 (save-excursion
17168 (goto-char (1- (match-beginning 1)))
17169 (setq column (current-column))))
17170 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
17171 (save-excursion
17172 (re-search-backward
17173 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
17174 (setq column (org-get-indentation (match-string 0))))
17176 (beginning-of-line 0)
17177 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
17178 (not (looking-at "[ \t]*:END:"))
17179 (not (looking-at org-drawer-regexp)))
17180 (beginning-of-line 0))
17181 (cond
17182 ((looking-at "\\*+[ \t]+")
17183 (if (not org-adapt-indentation)
17184 (setq column 0)
17185 (goto-char (match-end 0))
17186 (setq column (current-column))))
17187 ((looking-at org-drawer-regexp)
17188 (goto-char (1- (match-beginning 1)))
17189 (setq column (current-column)))
17190 ((looking-at "\\([ \t]*\\):END:")
17191 (goto-char (match-end 1))
17192 (setq column (current-column)))
17193 ((org-in-item-p)
17194 (org-beginning-of-item)
17195 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
17196 (setq bpos (match-beginning 1) tpos (match-end 0)
17197 bcol (progn (goto-char bpos) (current-column))
17198 tcol (progn (goto-char tpos) (current-column))
17199 bullet (match-string 1)
17200 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
17201 (if (> tcol (+ bcol org-description-max-indent))
17202 (setq tcol (+ bcol 5)))
17203 (if (not itemp)
17204 (setq column tcol)
17205 (goto-char pos)
17206 (beginning-of-line 1)
17207 (if (looking-at "\\S-")
17208 (progn
17209 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
17210 (setq bullet (match-string 1)
17211 btype (if (string-match "[0-9]" bullet) "n" bullet))
17212 (setq column (if (equal btype bullet-type) bcol tcol)))
17213 (setq column (org-get-indentation)))))
17214 (t (setq column (org-get-indentation))))))
17215 (goto-char pos)
17216 (if (<= (current-column) (current-indentation))
17217 (org-indent-line-to column)
17218 (save-excursion (org-indent-line-to column)))
17219 (setq column (current-column))
17220 (beginning-of-line 1)
17221 (if (looking-at
17222 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
17223 (replace-match (concat (match-string 1)
17224 (format org-property-format
17225 (match-string 2) (match-string 3)))
17226 t t))
17227 (org-move-to-column column)))
17229 (defun org-set-autofill-regexps ()
17230 (interactive)
17231 ;; In the paragraph separator we include headlines, because filling
17232 ;; text in a line directly attached to a headline would otherwise
17233 ;; fill the headline as well.
17234 (org-set-local 'comment-start-skip "^#+[ \t]*")
17235 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
17236 ;; The paragraph starter includes hand-formatted lists.
17237 (org-set-local
17238 'paragraph-start
17239 (concat
17240 "\f" "\\|"
17241 "[ ]*$" "\\|"
17242 "\\*+ " "\\|"
17243 "[ \t]*#" "\\|"
17244 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
17245 "[ \t]*[:|]" "\\|"
17246 "\\$\\$" "\\|"
17247 "\\\\\\(begin\\|end\\|[][]\\)"))
17248 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17249 ;; But only if the user has not turned off tables or fixed-width regions
17250 (org-set-local
17251 'auto-fill-inhibit-regexp
17252 (concat "\\*+ \\|#\\+"
17253 "\\|[ \t]*" org-keyword-time-regexp
17254 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17255 (concat
17256 "\\|[ \t]*["
17257 (if org-enable-table-editor "|" "")
17258 (if org-enable-fixed-width-editor ":" "")
17259 "]"))))
17260 ;; We use our own fill-paragraph function, to make sure that tables
17261 ;; and fixed-width regions are not wrapped. That function will pass
17262 ;; through to `fill-paragraph' when appropriate.
17263 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17264 ; Adaptive filling: To get full control, first make sure that
17265 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17266 (org-set-local 'adaptive-fill-regexp "\000")
17267 (org-set-local 'adaptive-fill-function
17268 'org-adaptive-fill-function)
17269 (org-set-local
17270 'align-mode-rules-list
17271 '((org-in-buffer-settings
17272 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
17273 (modes . '(org-mode))))))
17275 (defun org-fill-paragraph (&optional justify)
17276 "Re-align a table, pass through to fill-paragraph if no table."
17277 (let ((table-p (org-at-table-p))
17278 (table.el-p (org-at-table.el-p)))
17279 (cond ((and (equal (char-after (point-at-bol)) ?*)
17280 (save-excursion (goto-char (point-at-bol))
17281 (looking-at outline-regexp)))
17282 t) ; skip headlines
17283 (table.el-p t) ; skip table.el tables
17284 (table-p (org-table-align) t) ; align org-mode tables
17285 (t nil)))) ; call paragraph-fill
17287 ;; For reference, this is the default value of adaptive-fill-regexp
17288 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17290 (defun org-adaptive-fill-function ()
17291 "Return a fill prefix for org-mode files.
17292 In particular, this makes sure hanging paragraphs for hand-formatted lists
17293 work correctly."
17294 (cond ((looking-at "#[ \t]+")
17295 (match-string 0))
17296 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17297 (save-excursion
17298 (if (> (match-end 1) (+ (match-beginning 1)
17299 org-description-max-indent))
17300 (goto-char (+ (match-beginning 1) 5))
17301 (goto-char (match-end 0)))
17302 (make-string (current-column) ?\ )))
17303 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
17304 (save-excursion
17305 (goto-char (match-end 0))
17306 (make-string (current-column) ?\ )))
17307 (t nil)))
17309 ;;; Other stuff.
17311 (defun org-toggle-fixed-width-section (arg)
17312 "Toggle the fixed-width export.
17313 If there is no active region, the QUOTE keyword at the current headline is
17314 inserted or removed. When present, it causes the text between this headline
17315 and the next to be exported as fixed-width text, and unmodified.
17316 If there is an active region, this command adds or removes a colon as the
17317 first character of this line. If the first character of a line is a colon,
17318 this line is also exported in fixed-width font."
17319 (interactive "P")
17320 (let* ((cc 0)
17321 (regionp (org-region-active-p))
17322 (beg (if regionp (region-beginning) (point)))
17323 (end (if regionp (region-end)))
17324 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17325 (case-fold-search nil)
17326 (re "[ \t]*\\(: \\)")
17327 off)
17328 (if regionp
17329 (save-excursion
17330 (goto-char beg)
17331 (setq cc (current-column))
17332 (beginning-of-line 1)
17333 (setq off (looking-at re))
17334 (while (> nlines 0)
17335 (setq nlines (1- nlines))
17336 (beginning-of-line 1)
17337 (cond
17338 (arg
17339 (org-move-to-column cc t)
17340 (insert ": \n")
17341 (forward-line -1))
17342 ((and off (looking-at re))
17343 (replace-match "" t t nil 1))
17344 ((not off) (org-move-to-column cc t) (insert ": ")))
17345 (forward-line 1)))
17346 (save-excursion
17347 (org-back-to-heading)
17348 (if (looking-at (concat outline-regexp
17349 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17350 (replace-match "" t t nil 1)
17351 (if (looking-at outline-regexp)
17352 (progn
17353 (goto-char (match-end 0))
17354 (insert org-quote-string " "))))))))
17356 (defun org-reftex-citation ()
17357 "Use reftex-citation to insert a citation into the buffer.
17358 This looks for a line like
17360 #+BIBLIOGRAPHY: foo plain option:-d
17362 and derives from it that foo.bib is the bibliography file relevant
17363 for this document. It then installs the necessary environment for RefTeX
17364 to work in this buffer and calls `reftex-citation' to insert a citation
17365 into the buffer.
17367 Export of such citations to both LaTeX and HTML is handled by the contributed
17368 package org-exp-bibtex by Taru Karttunen."
17369 (interactive)
17370 (let ((reftex-docstruct-symbol 'rds)
17371 (reftex-cite-format "\\cite{%l}")
17372 rds bib)
17373 (save-excursion
17374 (save-restriction
17375 (widen)
17376 (let ((case-fold-search t)
17377 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17378 (if (not (save-excursion
17379 (or (re-search-forward re nil t)
17380 (re-search-backward re nil t))))
17381 (error "No bibliography defined in file")
17382 (setq bib (concat (match-string 1) ".bib")
17383 rds (list (list 'bib bib)))))))
17384 (call-interactively 'reftex-citation)))
17386 ;;;; Functions extending outline functionality
17388 (defun org-beginning-of-line (&optional arg)
17389 "Go to the beginning of the current line. If that is invisible, continue
17390 to a visible line beginning. This makes the function of C-a more intuitive.
17391 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17392 first attempt, and only move to after the tags when the cursor is already
17393 beyond the end of the headline."
17394 (interactive "P")
17395 (let ((pos (point))
17396 (special (if (consp org-special-ctrl-a/e)
17397 (car org-special-ctrl-a/e)
17398 org-special-ctrl-a/e))
17399 refpos)
17400 (if (org-bound-and-true-p line-move-visual)
17401 (beginning-of-visual-line 1)
17402 (beginning-of-line 1))
17403 (if (and arg (fboundp 'move-beginning-of-line))
17404 (call-interactively 'move-beginning-of-line)
17405 (if (bobp)
17407 (backward-char 1)
17408 (if (org-invisible-p)
17409 (while (and (not (bobp)) (org-invisible-p))
17410 (backward-char 1)
17411 (beginning-of-line 1))
17412 (forward-char 1))))
17413 (when special
17414 (cond
17415 ((and (looking-at org-complex-heading-regexp)
17416 (= (char-after (match-end 1)) ?\ ))
17417 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17418 (point-at-eol)))
17419 (goto-char
17420 (if (eq special t)
17421 (cond ((> pos refpos) refpos)
17422 ((= pos (point)) refpos)
17423 (t (point)))
17424 (cond ((> pos (point)) (point))
17425 ((not (eq last-command this-command)) (point))
17426 (t refpos)))))
17427 ((org-at-item-p)
17428 (goto-char
17429 (if (eq special t)
17430 (cond ((> pos (match-end 4)) (match-end 4))
17431 ((= pos (point)) (match-end 4))
17432 (t (point)))
17433 (cond ((> pos (point)) (point))
17434 ((not (eq last-command this-command)) (point))
17435 (t (match-end 4))))))))
17436 (org-no-warnings
17437 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17439 (defun org-end-of-line (&optional arg)
17440 "Go to the end of the line.
17441 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17442 first attempt, and only move to after the tags when the cursor is already
17443 beyond the end of the headline."
17444 (interactive "P")
17445 (let ((special (if (consp org-special-ctrl-a/e)
17446 (cdr org-special-ctrl-a/e)
17447 org-special-ctrl-a/e)))
17448 (if (or (not special)
17449 (not (org-on-heading-p))
17450 arg)
17451 (call-interactively
17452 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17453 ((fboundp 'move-end-of-line) 'move-end-of-line)
17454 (t 'end-of-line)))
17455 (let ((pos (point)))
17456 (beginning-of-line 1)
17457 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17458 (if (eq special t)
17459 (if (or (< pos (match-beginning 1))
17460 (= pos (match-end 0)))
17461 (goto-char (match-beginning 1))
17462 (goto-char (match-end 0)))
17463 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17464 (goto-char (match-end 0))
17465 (goto-char (match-beginning 1))))
17466 (call-interactively (if (fboundp 'move-end-of-line)
17467 'move-end-of-line
17468 'end-of-line)))))
17469 (org-no-warnings
17470 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17472 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17473 (define-key org-mode-map "\C-e" 'org-end-of-line)
17474 (define-key org-mode-map [home] 'org-beginning-of-line)
17475 (define-key org-mode-map [end] 'org-end-of-line)
17477 (defun org-backward-sentence (&optional arg)
17478 "Go to beginning of sentence, or beginning of table field.
17479 This will call `backward-sentence' or `org-table-beginning-of-field',
17480 depending on context."
17481 (interactive "P")
17482 (cond
17483 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17484 (t (call-interactively 'backward-sentence))))
17486 (defun org-forward-sentence (&optional arg)
17487 "Go to end of sentence, or end of table field.
17488 This will call `forward-sentence' or `org-table-end-of-field',
17489 depending on context."
17490 (interactive "P")
17491 (cond
17492 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17493 (t (call-interactively 'forward-sentence))))
17495 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17496 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17498 (defun org-kill-line (&optional arg)
17499 "Kill line, to tags or end of line."
17500 (interactive "P")
17501 (cond
17502 ((or (not org-special-ctrl-k)
17503 (bolp)
17504 (not (org-on-heading-p)))
17505 (call-interactively 'kill-line))
17506 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17507 (kill-region (point) (match-beginning 1))
17508 (org-set-tags nil t))
17509 (t (kill-region (point) (point-at-eol)))))
17511 (define-key org-mode-map "\C-k" 'org-kill-line)
17513 (defun org-yank (&optional arg)
17514 "Yank. If the kill is a subtree, treat it specially.
17515 This command will look at the current kill and check if is a single
17516 subtree, or a series of subtrees[1]. If it passes the test, and if the
17517 cursor is at the beginning of a line or after the stars of a currently
17518 empty headline, then the yank is handled specially. How exactly depends
17519 on the value of the following variables, both set by default.
17521 org-yank-folded-subtrees
17522 When set, the subtree(s) will be folded after insertion, but only
17523 if doing so would now swallow text after the yanked text.
17525 org-yank-adjusted-subtrees
17526 When set, the subtree will be promoted or demoted in order to
17527 fit into the local outline tree structure, which means that the level
17528 will be adjusted so that it becomes the smaller one of the two
17529 *visible* surrounding headings.
17531 Any prefix to this command will cause `yank' to be called directly with
17532 no special treatment. In particular, a simple `C-u' prefix will just
17533 plainly yank the text as it is.
17535 \[1] The test checks if the first non-white line is a heading
17536 and if there are no other headings with fewer stars."
17537 (interactive "P")
17538 (org-yank-generic 'yank arg))
17540 (defun org-yank-generic (command arg)
17541 "Perform some yank-like command.
17543 This function implements the behavior described in the `org-yank'
17544 documentation. However, it has been generalized to work for any
17545 interactive command with similar behavior."
17547 ;; pretend to be command COMMAND
17548 (setq this-command command)
17550 (if arg
17551 (call-interactively command)
17553 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17554 (and (org-kill-is-subtree-p)
17555 (or (bolp)
17556 (and (looking-at "[ \t]*$")
17557 (string-match
17558 "\\`\\*+\\'"
17559 (buffer-substring (point-at-bol) (point)))))))
17560 swallowp)
17561 (cond
17562 ((and subtreep org-yank-folded-subtrees)
17563 (let ((beg (point))
17564 end)
17565 (if (and subtreep org-yank-adjusted-subtrees)
17566 (org-paste-subtree nil nil 'for-yank)
17567 (call-interactively command))
17569 (setq end (point))
17570 (goto-char beg)
17571 (when (and (bolp) subtreep
17572 (not (setq swallowp
17573 (org-yank-folding-would-swallow-text beg end))))
17574 (or (looking-at outline-regexp)
17575 (re-search-forward (concat "^" outline-regexp) end t))
17576 (while (and (< (point) end) (looking-at outline-regexp))
17577 (hide-subtree)
17578 (org-cycle-show-empty-lines 'folded)
17579 (condition-case nil
17580 (outline-forward-same-level 1)
17581 (error (goto-char end)))))
17582 (when swallowp
17583 (message
17584 "Inserted text not folded because that would swallow text"))
17586 (goto-char end)
17587 (skip-chars-forward " \t\n\r")
17588 (beginning-of-line 1)
17589 (push-mark beg 'nomsg)))
17590 ((and subtreep org-yank-adjusted-subtrees)
17591 (let ((beg (point-at-bol)))
17592 (org-paste-subtree nil nil 'for-yank)
17593 (push-mark beg 'nomsg)))
17595 (call-interactively command))))))
17597 (defun org-yank-folding-would-swallow-text (beg end)
17598 "Would hide-subtree at BEG swallow any text after END?"
17599 (let (level)
17600 (save-excursion
17601 (goto-char beg)
17602 (when (or (looking-at outline-regexp)
17603 (re-search-forward (concat "^" outline-regexp) end t))
17604 (setq level (org-outline-level)))
17605 (goto-char end)
17606 (skip-chars-forward " \t\r\n\v\f")
17607 (if (or (eobp)
17608 (and (bolp) (looking-at org-outline-regexp)
17609 (<= (org-outline-level) level)))
17610 nil ; Nothing would be swallowed
17611 t)))) ; something would swallow
17613 (define-key org-mode-map "\C-y" 'org-yank)
17615 (defun org-invisible-p ()
17616 "Check if point is at a character currently not visible."
17617 ;; Early versions of noutline don't have `outline-invisible-p'.
17618 (if (fboundp 'outline-invisible-p)
17619 (outline-invisible-p)
17620 (get-char-property (point) 'invisible)))
17622 (defun org-invisible-p2 ()
17623 "Check if point is at a character currently not visible."
17624 (save-excursion
17625 (if (and (eolp) (not (bobp))) (backward-char 1))
17626 ;; Early versions of noutline don't have `outline-invisible-p'.
17627 (if (fboundp 'outline-invisible-p)
17628 (outline-invisible-p)
17629 (get-char-property (point) 'invisible))))
17631 (defun org-back-to-heading (&optional invisible-ok)
17632 "Call `outline-back-to-heading', but provide a better error message."
17633 (condition-case nil
17634 (outline-back-to-heading invisible-ok)
17635 (error (error "Before first headline at position %d in buffer %s"
17636 (point) (current-buffer)))))
17638 (defun org-before-first-heading-p ()
17639 "Before first heading?"
17640 (save-excursion
17641 (null (re-search-backward "^\\*+ " nil t))))
17643 (defun org-on-heading-p (&optional ignored)
17644 (outline-on-heading-p t))
17645 (defun org-at-heading-p (&optional ignored)
17646 (outline-on-heading-p t))
17648 (defun org-at-heading-or-item-p ()
17649 (or (org-on-heading-p) (org-at-item-p)))
17651 (defun org-on-target-p ()
17652 (or (org-in-regexp org-radio-target-regexp)
17653 (org-in-regexp org-target-regexp)))
17655 (defun org-up-heading-all (arg)
17656 "Move to the heading line of which the present line is a subheading.
17657 This function considers both visible and invisible heading lines.
17658 With argument, move up ARG levels."
17659 (if (fboundp 'outline-up-heading-all)
17660 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17661 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17663 (defun org-up-heading-safe ()
17664 "Move to the heading line of which the present line is a subheading.
17665 This version will not throw an error. It will return the level of the
17666 headline found, or nil if no higher level is found.
17668 Also, this function will be a lot faster than `outline-up-heading',
17669 because it relies on stars being the outline starters. This can really
17670 make a significant difference in outlines with very many siblings."
17671 (let (start-level re)
17672 (org-back-to-heading t)
17673 (setq start-level (funcall outline-level))
17674 (if (equal start-level 1)
17676 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17677 (if (re-search-backward re nil t)
17678 (funcall outline-level)))))
17680 (defun org-first-sibling-p ()
17681 "Is this heading the first child of its parents?"
17682 (interactive)
17683 (let ((re (concat "^" outline-regexp))
17684 level l)
17685 (unless (org-at-heading-p t)
17686 (error "Not at a heading"))
17687 (setq level (funcall outline-level))
17688 (save-excursion
17689 (if (not (re-search-backward re nil t))
17691 (setq l (funcall outline-level))
17692 (< l level)))))
17694 (defun org-goto-sibling (&optional previous)
17695 "Goto the next sibling, even if it is invisible.
17696 When PREVIOUS is set, go to the previous sibling instead. Returns t
17697 when a sibling was found. When none is found, return nil and don't
17698 move point."
17699 (let ((fun (if previous 're-search-backward 're-search-forward))
17700 (pos (point))
17701 (re (concat "^" outline-regexp))
17702 level l)
17703 (when (condition-case nil (org-back-to-heading t) (error nil))
17704 (setq level (funcall outline-level))
17705 (catch 'exit
17706 (or previous (forward-char 1))
17707 (while (funcall fun re nil t)
17708 (setq l (funcall outline-level))
17709 (when (< l level) (goto-char pos) (throw 'exit nil))
17710 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17711 (goto-char pos)
17712 nil))))
17714 (defun org-show-siblings ()
17715 "Show all siblings of the current headline."
17716 (save-excursion
17717 (while (org-goto-sibling) (org-flag-heading nil)))
17718 (save-excursion
17719 (while (org-goto-sibling 'previous)
17720 (org-flag-heading nil))))
17722 (defun org-show-hidden-entry ()
17723 "Show an entry where even the heading is hidden."
17724 (save-excursion
17725 (org-show-entry)))
17727 (defun org-flag-heading (flag &optional entry)
17728 "Flag the current heading. FLAG non-nil means make invisible.
17729 When ENTRY is non-nil, show the entire entry."
17730 (save-excursion
17731 (org-back-to-heading t)
17732 ;; Check if we should show the entire entry
17733 (if entry
17734 (progn
17735 (org-show-entry)
17736 (save-excursion
17737 (and (outline-next-heading)
17738 (org-flag-heading nil))))
17739 (outline-flag-region (max (point-min) (1- (point)))
17740 (save-excursion (outline-end-of-heading) (point))
17741 flag))))
17743 (defun org-get-next-sibling ()
17744 "Move to next heading of the same level, and return point.
17745 If there is no such heading, return nil.
17746 This is like outline-next-sibling, but invisible headings are ok."
17747 (let ((level (funcall outline-level)))
17748 (outline-next-heading)
17749 (while (and (not (eobp)) (> (funcall outline-level) level))
17750 (outline-next-heading))
17751 (if (or (eobp) (< (funcall outline-level) level))
17753 (point))))
17755 (defun org-get-last-sibling ()
17756 "Move to previous heading of the same level, and return point.
17757 If there is no such heading, return nil."
17758 (let ((opoint (point))
17759 (level (funcall outline-level)))
17760 (outline-previous-heading)
17761 (when (and (/= (point) opoint) (outline-on-heading-p t))
17762 (while (and (> (funcall outline-level) level)
17763 (not (bobp)))
17764 (outline-previous-heading))
17765 (if (< (funcall outline-level) level)
17767 (point)))))
17769 (defun org-end-of-subtree (&optional invisible-OK to-heading)
17770 ;; This contains an exact copy of the original function, but it uses
17771 ;; `org-back-to-heading', to make it work also in invisible
17772 ;; trees. And is uses an invisible-OK argument.
17773 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17774 ;; Furthermore, when used inside Org, finding the end of a large subtree
17775 ;; with many children and grandchildren etc, this can be much faster
17776 ;; than the outline version.
17777 (org-back-to-heading invisible-OK)
17778 (let ((first t)
17779 (level (funcall outline-level)))
17780 (if (and (org-mode-p) (< level 1000))
17781 ;; A true heading (not a plain list item), in Org-mode
17782 ;; This means we can easily find the end by looking
17783 ;; only for the right number of stars. Using a regexp to do
17784 ;; this is so much faster than using a Lisp loop.
17785 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
17786 (forward-char 1)
17787 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
17788 ;; something else, do it the slow way
17789 (while (and (not (eobp))
17790 (or first (> (funcall outline-level) level)))
17791 (setq first nil)
17792 (outline-next-heading)))
17793 (unless to-heading
17794 (if (memq (preceding-char) '(?\n ?\^M))
17795 (progn
17796 ;; Go to end of line before heading
17797 (forward-char -1)
17798 (if (memq (preceding-char) '(?\n ?\^M))
17799 ;; leave blank line before heading
17800 (forward-char -1))))))
17801 (point))
17803 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
17804 "Use Org version in org-mode, for dramatic speed-up."
17805 (if (eq major-mode 'org-mode)
17806 (progn
17807 (org-end-of-subtree nil t)
17808 (unless (eobp) (backward-char 1)))
17809 ad-do-it))
17811 (defun org-forward-same-level (arg &optional invisible-ok)
17812 "Move forward to the arg'th subheading at same level as this one.
17813 Stop at the first and last subheadings of a superior heading."
17814 (interactive "p")
17815 (org-back-to-heading invisible-ok)
17816 (org-on-heading-p)
17817 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17818 (re (format "^\\*\\{1,%d\\} " level))
17820 (forward-char 1)
17821 (while (> arg 0)
17822 (while (and (re-search-forward re nil 'move)
17823 (setq l (- (match-end 0) (match-beginning 0) 1))
17824 (= l level)
17825 (not invisible-ok)
17826 (progn (backward-char 1) (org-invisible-p)))
17827 (if (< l level) (setq arg 1)))
17828 (setq arg (1- arg)))
17829 (beginning-of-line 1)))
17831 (defun org-backward-same-level (arg &optional invisible-ok)
17832 "Move backward to the arg'th subheading at same level as this one.
17833 Stop at the first and last subheadings of a superior heading."
17834 (interactive "p")
17835 (org-back-to-heading)
17836 (org-on-heading-p)
17837 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17838 (re (format "^\\*\\{1,%d\\} " level))
17840 (while (> arg 0)
17841 (while (and (re-search-backward re nil 'move)
17842 (setq l (- (match-end 0) (match-beginning 0) 1))
17843 (= l level)
17844 (not invisible-ok)
17845 (org-invisible-p))
17846 (if (< l level) (setq arg 1)))
17847 (setq arg (1- arg)))))
17849 (defun org-show-subtree ()
17850 "Show everything after this heading at deeper levels."
17851 (outline-flag-region
17852 (point)
17853 (save-excursion
17854 (org-end-of-subtree t t))
17855 nil))
17857 (defun org-show-entry ()
17858 "Show the body directly following this heading.
17859 Show the heading too, if it is currently invisible."
17860 (interactive)
17861 (save-excursion
17862 (condition-case nil
17863 (progn
17864 (org-back-to-heading t)
17865 (outline-flag-region
17866 (max (point-min) (1- (point)))
17867 (save-excursion
17868 (if (re-search-forward
17869 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17870 (match-beginning 1)
17871 (point-max)))
17872 nil)
17873 (org-cycle-hide-drawers 'children))
17874 (error nil))))
17876 (defun org-make-options-regexp (kwds &optional extra)
17877 "Make a regular expression for keyword lines."
17878 (concat
17880 "#?[ \t]*\\+\\("
17881 (mapconcat 'regexp-quote kwds "\\|")
17882 (if extra (concat "\\|" extra))
17883 "\\):[ \t]*"
17884 "\\(.*\\)"))
17886 ;; Make isearch reveal the necessary context
17887 (defun org-isearch-end ()
17888 "Reveal context after isearch exits."
17889 (when isearch-success ; only if search was successful
17890 (if (featurep 'xemacs)
17891 ;; Under XEmacs, the hook is run in the correct place,
17892 ;; we directly show the context.
17893 (org-show-context 'isearch)
17894 ;; In Emacs the hook runs *before* restoring the overlays.
17895 ;; So we have to use a one-time post-command-hook to do this.
17896 ;; (Emacs 22 has a special variable, see function `org-mode')
17897 (unless (and (boundp 'isearch-mode-end-hook-quit)
17898 isearch-mode-end-hook-quit)
17899 ;; Only when the isearch was not quitted.
17900 (org-add-hook 'post-command-hook 'org-isearch-post-command
17901 'append 'local)))))
17903 (defun org-isearch-post-command ()
17904 "Remove self from hook, and show context."
17905 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17906 (org-show-context 'isearch))
17909 ;;;; Integration with and fixes for other packages
17911 ;;; Imenu support
17913 (defvar org-imenu-markers nil
17914 "All markers currently used by Imenu.")
17915 (make-variable-buffer-local 'org-imenu-markers)
17917 (defun org-imenu-new-marker (&optional pos)
17918 "Return a new marker for use by Imenu, and remember the marker."
17919 (let ((m (make-marker)))
17920 (move-marker m (or pos (point)))
17921 (push m org-imenu-markers)
17924 (defun org-imenu-get-tree ()
17925 "Produce the index for Imenu."
17926 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17927 (setq org-imenu-markers nil)
17928 (let* ((n org-imenu-depth)
17929 (re (concat "^" outline-regexp))
17930 (subs (make-vector (1+ n) nil))
17931 (last-level 0)
17932 m level head)
17933 (save-excursion
17934 (save-restriction
17935 (widen)
17936 (goto-char (point-max))
17937 (while (re-search-backward re nil t)
17938 (setq level (org-reduced-level (funcall outline-level)))
17939 (when (<= level n)
17940 (looking-at org-complex-heading-regexp)
17941 (setq head (org-link-display-format
17942 (org-match-string-no-properties 4))
17943 m (org-imenu-new-marker))
17944 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17945 (if (>= level last-level)
17946 (push (cons head m) (aref subs level))
17947 (push (cons head (aref subs (1+ level))) (aref subs level))
17948 (loop for i from (1+ level) to n do (aset subs i nil)))
17949 (setq last-level level)))))
17950 (aref subs 1)))
17952 (eval-after-load "imenu"
17953 '(progn
17954 (add-hook 'imenu-after-jump-hook
17955 (lambda ()
17956 (if (eq major-mode 'org-mode)
17957 (org-show-context 'org-goto))))))
17959 (defun org-link-display-format (link)
17960 "Replace a link with either the description, or the link target
17961 if no description is present"
17962 (save-match-data
17963 (if (string-match org-bracket-link-analytic-regexp link)
17964 (replace-match (if (match-end 5)
17965 (match-string 5 link)
17966 (concat (match-string 1 link)
17967 (match-string 3 link)))
17968 nil t link)
17969 link)))
17971 ;; Speedbar support
17973 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17974 "Overlay marking the agenda restriction line in speedbar.")
17975 (org-overlay-put org-speedbar-restriction-lock-overlay
17976 'face 'org-agenda-restriction-lock)
17977 (org-overlay-put org-speedbar-restriction-lock-overlay
17978 'help-echo "Agendas are currently limited to this item.")
17979 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17981 (defun org-speedbar-set-agenda-restriction ()
17982 "Restrict future agenda commands to the location at point in speedbar.
17983 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17984 (interactive)
17985 (require 'org-agenda)
17986 (let (p m tp np dir txt)
17987 (cond
17988 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17989 'org-imenu t))
17990 (setq m (get-text-property p 'org-imenu-marker))
17991 (with-current-buffer (marker-buffer m)
17992 (goto-char m)
17993 (org-agenda-set-restriction-lock 'subtree)))
17994 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17995 'speedbar-function 'speedbar-find-file))
17996 (setq tp (previous-single-property-change
17997 (1+ p) 'speedbar-function)
17998 np (next-single-property-change
17999 tp 'speedbar-function)
18000 dir (speedbar-line-directory)
18001 txt (buffer-substring-no-properties (or tp (point-min))
18002 (or np (point-max))))
18003 (with-current-buffer (find-file-noselect
18004 (let ((default-directory dir))
18005 (expand-file-name txt)))
18006 (unless (org-mode-p)
18007 (error "Cannot restrict to non-Org-mode file"))
18008 (org-agenda-set-restriction-lock 'file)))
18009 (t (error "Don't know how to restrict Org-mode's agenda")))
18010 (org-move-overlay org-speedbar-restriction-lock-overlay
18011 (point-at-bol) (point-at-eol))
18012 (setq current-prefix-arg nil)
18013 (org-agenda-maybe-redo)))
18015 (eval-after-load "speedbar"
18016 '(progn
18017 (speedbar-add-supported-extension ".org")
18018 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
18019 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
18020 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
18021 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18022 (add-hook 'speedbar-visiting-tag-hook
18023 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
18026 ;;; Fixes and Hacks for problems with other packages
18028 ;; Make flyspell not check words in links, to not mess up our keymap
18029 (defun org-mode-flyspell-verify ()
18030 "Don't let flyspell put overlays at active buttons."
18031 (and (not (get-text-property (point) 'keymap))
18032 (not (get-text-property (point) 'org-no-flyspell))))
18034 (defun org-remove-flyspell-overlays-in (beg end)
18035 "Remove flyspell overlays in region."
18036 (and (org-bound-and-true-p flyspell-mode)
18037 (fboundp 'flyspell-delete-region-overlays)
18038 (flyspell-delete-region-overlays beg end))
18039 (add-text-properties beg end '(org-no-flyspell t)))
18041 ;; Make `bookmark-jump' shows the jump location if it was hidden.
18042 (eval-after-load "bookmark"
18043 '(if (boundp 'bookmark-after-jump-hook)
18044 ;; We can use the hook
18045 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
18046 ;; Hook not available, use advice
18047 (defadvice bookmark-jump (after org-make-visible activate)
18048 "Make the position visible."
18049 (org-bookmark-jump-unhide))))
18051 ;; Make sure saveplace shows the location if it was hidden
18052 (eval-after-load "saveplace"
18053 '(defadvice save-place-find-file-hook (after org-make-visible activate)
18054 "Make the position visible."
18055 (org-bookmark-jump-unhide)))
18057 ;; Make sure ecb shows the location if it was hidden
18058 (eval-after-load "ecb"
18059 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
18060 "Make hierarchy visible when jumping into location from ECB tree buffer."
18061 (if (eq major-mode 'org-mode)
18062 (org-show-context))))
18064 (defun org-bookmark-jump-unhide ()
18065 "Unhide the current position, to show the bookmark location."
18066 (and (org-mode-p)
18067 (or (org-invisible-p)
18068 (save-excursion (goto-char (max (point-min) (1- (point))))
18069 (org-invisible-p)))
18070 (org-show-context 'bookmark-jump)))
18072 ;; Make session.el ignore our circular variable
18073 (eval-after-load "session"
18074 '(add-to-list 'session-globals-exclude 'org-mark-ring))
18076 ;;;; Experimental code
18078 (defun org-closed-in-range ()
18079 "Sparse tree of items closed in a certain time range.
18080 Still experimental, may disappear in the future."
18081 (interactive)
18082 ;; Get the time interval from the user.
18083 (let* ((time1 (org-float-time
18084 (org-read-date nil 'to-time nil "Starting date: ")))
18085 (time2 (org-float-time
18086 (org-read-date nil 'to-time nil "End date:")))
18087 ;; callback function
18088 (callback (lambda ()
18089 (let ((time
18090 (org-float-time
18091 (apply 'encode-time
18092 (org-parse-time-string
18093 (match-string 1))))))
18094 ;; check if time in interval
18095 (and (>= time time1) (<= time time2))))))
18096 ;; make tree, check each match with the callback
18097 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
18099 ;;;; Finish up
18101 (provide 'org)
18103 (run-hooks 'org-load-hook)
18105 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
18107 ;;; org.el ends here