Add the ChangeLog entries
[org-mode/org-tableheadings.git] / lisp / org.el
blobf6134ddeb8dc6d4822afdd055c231ed542e7449e
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.34trans
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-entities)
89 (require 'org-compat)
90 (require 'org-faces)
91 (require 'org-list)
92 (require 'org-src)
93 (require 'org-footnote)
95 ;;;; Customization variables
97 ;;; Version
99 (defconst org-version "6.34trans"
100 "The version number of the file org.el.")
102 (defun org-version (&optional here)
103 "Show the org-mode version in the echo area.
104 With prefix arg HERE, insert it at point."
105 (interactive "P")
106 (let* ((origin default-directory)
107 (version org-version)
108 (git-version)
109 (dir (concat (file-name-directory (locate-library "org")) "../" )))
110 (when (and (file-exists-p (expand-file-name ".git" dir))
111 (executable-find "git"))
112 (unwind-protect
113 (progn
114 (cd dir)
115 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
116 (with-current-buffer "*Shell Command Output*"
117 (goto-char (point-min))
118 (setq git-version (buffer-substring (point) (point-at-eol))))
119 (subst-char-in-string ?- ?. git-version t)
120 (when (string-match "\\S-"
121 (shell-command-to-string
122 "git diff-index --name-only HEAD --"))
123 (setq git-version (concat git-version ".dirty")))
124 (setq version (concat version " (" git-version ")"))))
125 (cd origin)))
126 (setq version (format "Org-mode version %s" version))
127 (if here (insert version))
128 (message version)))
130 ;;; Compatibility constants
132 ;;; The custom variables
134 (defgroup org nil
135 "Outline-based notes management and organizer."
136 :tag "Org"
137 :group 'outlines
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 registry: A registry for Org-mode links" org-registry)
235 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
236 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
237 (const :tag "C secretary: Team management with org-mode" org-secretary)
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-appearance
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: link. For
1467 backward compatibility, this can also be a string with only
1468 alphanumeric characters, which is then interpreted as an
1469 extension.
1470 `directory' Matches a directory
1471 `remote' Matches a remote file, accessible through tramp or efs.
1472 Remote files most likely should be visited through Emacs
1473 because external applications cannot handle such paths.
1474 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1475 so all files Emacs knows how to handle. Using this with
1476 command `emacs' will open most files in Emacs. Beware that this
1477 will also open html files inside Emacs, unless you add
1478 (\"html\" . default) to the list as well.
1479 t Default for files not matched by any of the other options.
1480 `system' The system command to open files, like `open' on Windows
1481 and Mac OS X, and mailcap under GNU/Linux. This is the command
1482 that will be selected if you call `C-c C-o' with a double
1483 `C-u C-u' prefix.
1485 Possible values for the command are:
1486 `emacs' The file will be visited by the current Emacs process.
1487 `default' Use the default application for this file type, which is the
1488 association for t in the list, most likely in the system-specific
1489 part.
1490 This can be used to overrule an unwanted setting in the
1491 system-specific variable.
1492 `system' Use the system command for opening files, like \"open\".
1493 This command is specified by the entry whose car is `system'.
1494 Most likely, the system-specific version of this variable
1495 does define this command, but you can overrule/replace it
1496 here.
1497 string A command to be executed by a shell; %s will be replaced
1498 by the path to the file. If the file identifier is a regex,
1499 %n will be replaced by the match of the nth match group.
1500 sexp A Lisp form which will be evaluated. The file path will
1501 be available in the Lisp variable `file', the link itself
1502 in the Lisp variable `link'. If the file identifier is a regex,
1503 the original match data will be restored, so subexpression
1504 matches are accessible using (match-string n link).
1505 For more examples, see the system specific constants
1506 `org-file-apps-defaults-macosx'
1507 `org-file-apps-defaults-windowsnt'
1508 `org-file-apps-defaults-gnu'."
1509 :group 'org-link-follow
1510 :type '(repeat
1511 (cons (choice :value ""
1512 (string :tag "Extension")
1513 (const :tag "System command to open files" system)
1514 (const :tag "Default for unrecognized files" t)
1515 (const :tag "Remote file" remote)
1516 (const :tag "Links to a directory" directory)
1517 (const :tag "Any files that have Emacs modes"
1518 auto-mode))
1519 (choice :value ""
1520 (const :tag "Visit with Emacs" emacs)
1521 (const :tag "Use default" default)
1522 (const :tag "Use the system command" system)
1523 (string :tag "Command")
1524 (sexp :tag "Lisp form")))))
1526 (defgroup org-refile nil
1527 "Options concerning refiling entries in Org-mode."
1528 :tag "Org Refile"
1529 :group 'org)
1531 (defcustom org-directory "~/org"
1532 "Directory with org files.
1533 This is just a default location to look for Org files. There is no need
1534 at all to put your files into this directory. It is only used in the
1535 following situations:
1537 1. When a remember template specifies a target file that is not an
1538 absolute path. The path will then be interpreted relative to
1539 `org-directory'
1540 2. When a remember note is filed away in an interactive way (when exiting the
1541 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1542 with `org-directory' as the default path."
1543 :group 'org-refile
1544 :group 'org-remember
1545 :type 'directory)
1547 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1548 "Default target for storing notes.
1549 Used by the hooks for remember.el. This can be a string, or nil to mean
1550 the value of `remember-data-file'.
1551 You can set this on a per-template basis with the variable
1552 `org-remember-templates'."
1553 :group 'org-refile
1554 :group 'org-remember
1555 :type '(choice
1556 (const :tag "Default from remember-data-file" nil)
1557 file))
1559 (defcustom org-goto-interface 'outline
1560 "The default interface to be used for `org-goto'.
1561 Allowed values are:
1562 outline The interface shows an outline of the relevant file
1563 and the correct heading is found by moving through
1564 the outline or by searching with incremental search.
1565 outline-path-completion Headlines in the current buffer are offered via
1566 completion. This is the interface also used by
1567 the refile command."
1568 :group 'org-refile
1569 :type '(choice
1570 (const :tag "Outline" outline)
1571 (const :tag "Outline-path-completion" outline-path-completion)))
1573 (defcustom org-goto-max-level 5
1574 "Maximum level to be considered when running org-goto with refile interface."
1575 :group 'org-refile
1576 :type 'integer)
1578 (defcustom org-reverse-note-order nil
1579 "Non-nil means store new notes at the beginning of a file or entry.
1580 When nil, new notes will be filed to the end of a file or entry.
1581 This can also be a list with cons cells of regular expressions that
1582 are matched against file names, and values."
1583 :group 'org-remember
1584 :group 'org-refile
1585 :type '(choice
1586 (const :tag "Reverse always" t)
1587 (const :tag "Reverse never" nil)
1588 (repeat :tag "By file name regexp"
1589 (cons regexp boolean))))
1591 (defcustom org-log-refile nil
1592 "Information to record when a task is refiled.
1594 Possible values are:
1596 nil Don't add anything
1597 time Add a time stamp to the task
1598 note Prompt for a note and add it with template `org-log-note-headings'
1600 This option can also be set with on a per-file-basis with
1602 #+STARTUP: nologrefile
1603 #+STARTUP: logrefile
1604 #+STARTUP: lognoterefile
1606 You can have local logging settings for a subtree by setting the LOGGING
1607 property to one or more of these keywords.
1609 When bulk-refiling from the agenda, the value `note' is forbidden and
1610 will temporarily be changed to `time'."
1611 :group 'org-refile
1612 :group 'org-progress
1613 :type '(choice
1614 (const :tag "No logging" nil)
1615 (const :tag "Record timestamp" time)
1616 (const :tag "Record timestamp with note." note)))
1618 (defcustom org-refile-targets nil
1619 "Targets for refiling entries with \\[org-refile].
1620 This is list of cons cells. Each cell contains:
1621 - a specification of the files to be considered, either a list of files,
1622 or a symbol whose function or variable value will be used to retrieve
1623 a file name or a list of file names. If you use `org-agenda-files' for
1624 that, all agenda files will be scanned for targets. Nil means consider
1625 headings in the current buffer.
1626 - A specification of how to find candidate refile targets. This may be
1627 any of:
1628 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1629 This tag has to be present in all target headlines, inheritance will
1630 not be considered.
1631 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1632 todo keyword.
1633 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1634 headlines that are refiling targets.
1635 - a cons cell (:level . N). Any headline of level N is considered a target.
1636 Note that, when `org-odd-levels-only' is set, level corresponds to
1637 order in hierarchy, not to the number of stars.
1638 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1639 Note that, when `org-odd-levels-only' is set, level corresponds to
1640 order in hierarchy, not to the number of stars.
1642 You can set the variable `org-refile-target-verify-function' to a function
1643 to verify each headline found by the simple critery above.
1645 When this variable is nil, all top-level headlines in the current buffer
1646 are used, equivalent to the value `((nil . (:level . 1))'."
1647 :group 'org-refile
1648 :type '(repeat
1649 (cons
1650 (choice :value org-agenda-files
1651 (const :tag "All agenda files" org-agenda-files)
1652 (const :tag "Current buffer" nil)
1653 (function) (variable) (file))
1654 (choice :tag "Identify target headline by"
1655 (cons :tag "Specific tag" (const :value :tag) (string))
1656 (cons :tag "TODO keyword" (const :value :todo) (string))
1657 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1658 (cons :tag "Level number" (const :value :level) (integer))
1659 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1661 (defcustom org-refile-target-verify-function nil
1662 "Function to verify if the headline at point should be a refile target.
1663 The function will be called without arguments, with point at the
1664 beginning of the headline. It should return t and leave point
1665 where it is if the headline is a valid target for refiling.
1667 If the target should not be selected, the function must return nil.
1668 In addition to this, it may move point to a place from where the search
1669 should be continued. For example, the function may decide that the entire
1670 subtree of the current entry should be excluded and move point to the end
1671 of the subtree."
1672 :group 'org-refile
1673 :type 'function)
1675 (defcustom org-refile-use-outline-path nil
1676 "Non-nil means provide refile targets as paths.
1677 So a level 3 headline will be available as level1/level2/level3.
1679 When the value is `file', also include the file name (without directory)
1680 into the path. In this case, you can also stop the completion after
1681 the file name, to get entries inserted as top level in the file.
1683 When `full-file-path', include the full file path."
1684 :group 'org-refile
1685 :type '(choice
1686 (const :tag "Not" nil)
1687 (const :tag "Yes" t)
1688 (const :tag "Start with file name" file)
1689 (const :tag "Start with full file path" full-file-path)))
1691 (defcustom org-outline-path-complete-in-steps t
1692 "Non-nil means complete the outline path in hierarchical steps.
1693 When Org-mode uses the refile interface to select an outline path
1694 \(see variable `org-refile-use-outline-path'), the completion of
1695 the path can be done is a single go, or if can be done in steps down
1696 the headline hierarchy. Going in steps is probably the best if you
1697 do not use a special completion package like `ido' or `icicles'.
1698 However, when using these packages, going in one step can be very
1699 fast, while still showing the whole path to the entry."
1700 :group 'org-refile
1701 :type 'boolean)
1703 (defcustom org-refile-allow-creating-parent-nodes nil
1704 "Non-nil means allow to create new nodes as refile targets.
1705 New nodes are then created by adding \"/new node name\" to the completion
1706 of an existing node. When the value of this variable is `confirm',
1707 new node creation must be confirmed by the user (recommended)
1708 When nil, the completion must match an existing entry.
1710 Note that, if the new heading is not seen by the criteria
1711 listed in `org-refile-targets', multiple instances of the same
1712 heading would be created by trying again to file under the new
1713 heading."
1714 :group 'org-refile
1715 :type '(choice
1716 (const :tag "Never" nil)
1717 (const :tag "Always" t)
1718 (const :tag "Prompt for confirmation" confirm)))
1720 (defgroup org-todo nil
1721 "Options concerning TODO items in Org-mode."
1722 :tag "Org TODO"
1723 :group 'org)
1725 (defgroup org-progress nil
1726 "Options concerning Progress logging in Org-mode."
1727 :tag "Org Progress"
1728 :group 'org-time)
1730 (defvar org-todo-interpretation-widgets
1732 (:tag "Sequence (cycling hits every state)" sequence)
1733 (:tag "Type (cycling directly to DONE)" type))
1734 "The available interpretation symbols for customizing
1735 `org-todo-keywords'.
1736 Interested libraries should add to this list.")
1738 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1739 "List of TODO entry keyword sequences and their interpretation.
1740 \\<org-mode-map>This is a list of sequences.
1742 Each sequence starts with a symbol, either `sequence' or `type',
1743 indicating if the keywords should be interpreted as a sequence of
1744 action steps, or as different types of TODO items. The first
1745 keywords are states requiring action - these states will select a headline
1746 for inclusion into the global TODO list Org-mode produces. If one of
1747 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1748 signify that no further action is necessary. If \"|\" is not found,
1749 the last keyword is treated as the only DONE state of the sequence.
1751 The command \\[org-todo] cycles an entry through these states, and one
1752 additional state where no keyword is present. For details about this
1753 cycling, see the manual.
1755 TODO keywords and interpretation can also be set on a per-file basis with
1756 the special #+SEQ_TODO and #+TYP_TODO lines.
1758 Each keyword can optionally specify a character for fast state selection
1759 \(in combination with the variable `org-use-fast-todo-selection')
1760 and specifiers for state change logging, using the same syntax
1761 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1762 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1763 indicates to record a time stamp each time this state is selected.
1765 Each keyword may also specify if a timestamp or a note should be
1766 recorded when entering or leaving the state, by adding additional
1767 characters in the parenthesis after the keyword. This looks like this:
1768 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1769 record only the time of the state change. With X and Y being either
1770 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1771 Y when leaving the state if and only if the *target* state does not
1772 define X. You may omit any of the fast-selection key or X or /Y,
1773 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1775 For backward compatibility, this variable may also be just a list
1776 of keywords - in this case the interpretation (sequence or type) will be
1777 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1778 :group 'org-todo
1779 :group 'org-keywords
1780 :type '(choice
1781 (repeat :tag "Old syntax, just keywords"
1782 (string :tag "Keyword"))
1783 (repeat :tag "New syntax"
1784 (cons
1785 (choice
1786 :tag "Interpretation"
1787 ;;Quick and dirty way to see
1788 ;;`org-todo-interpretations'. This takes the
1789 ;;place of item arguments
1790 :convert-widget
1791 (lambda (widget)
1792 (widget-put widget
1793 :args (mapcar
1794 #'(lambda (x)
1795 (widget-convert
1796 (cons 'const x)))
1797 org-todo-interpretation-widgets))
1798 widget))
1799 (repeat
1800 (string :tag "Keyword"))))))
1802 (defvar org-todo-keywords-1 nil
1803 "All TODO and DONE keywords active in a buffer.")
1804 (make-variable-buffer-local 'org-todo-keywords-1)
1805 (defvar org-todo-keywords-for-agenda nil)
1806 (defvar org-done-keywords-for-agenda nil)
1807 (defvar org-drawers-for-agenda nil)
1808 (defvar org-todo-keyword-alist-for-agenda nil)
1809 (defvar org-tag-alist-for-agenda nil)
1810 (defvar org-agenda-contributing-files nil)
1811 (defvar org-not-done-keywords nil)
1812 (make-variable-buffer-local 'org-not-done-keywords)
1813 (defvar org-done-keywords nil)
1814 (make-variable-buffer-local 'org-done-keywords)
1815 (defvar org-todo-heads nil)
1816 (make-variable-buffer-local 'org-todo-heads)
1817 (defvar org-todo-sets nil)
1818 (make-variable-buffer-local 'org-todo-sets)
1819 (defvar org-todo-log-states nil)
1820 (make-variable-buffer-local 'org-todo-log-states)
1821 (defvar org-todo-kwd-alist nil)
1822 (make-variable-buffer-local 'org-todo-kwd-alist)
1823 (defvar org-todo-key-alist nil)
1824 (make-variable-buffer-local 'org-todo-key-alist)
1825 (defvar org-todo-key-trigger nil)
1826 (make-variable-buffer-local 'org-todo-key-trigger)
1828 (defcustom org-todo-interpretation 'sequence
1829 "Controls how TODO keywords are interpreted.
1830 This variable is in principle obsolete and is only used for
1831 backward compatibility, if the interpretation of todo keywords is
1832 not given already in `org-todo-keywords'. See that variable for
1833 more information."
1834 :group 'org-todo
1835 :group 'org-keywords
1836 :type '(choice (const sequence)
1837 (const type)))
1839 (defcustom org-use-fast-todo-selection t
1840 "Non-nil means use the fast todo selection scheme with C-c C-t.
1841 This variable describes if and under what circumstances the cycling
1842 mechanism for TODO keywords will be replaced by a single-key, direct
1843 selection scheme.
1845 When nil, fast selection is never used.
1847 When the symbol `prefix', it will be used when `org-todo' is called with
1848 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1849 in an agenda buffer.
1851 When t, fast selection is used by default. In this case, the prefix
1852 argument forces cycling instead.
1854 In all cases, the special interface is only used if access keys have actually
1855 been assigned by the user, i.e. if keywords in the configuration are followed
1856 by a letter in parenthesis, like TODO(t)."
1857 :group 'org-todo
1858 :type '(choice
1859 (const :tag "Never" nil)
1860 (const :tag "By default" t)
1861 (const :tag "Only with C-u C-c C-t" prefix)))
1863 (defcustom org-provide-todo-statistics t
1864 "Non-nil means update todo statistics after insert and toggle.
1865 ALL-HEADLINES means update todo statistics by including headlines
1866 with no TODO keyword as well, counting them as not done.
1867 A list of TODO keywords means the same, but skip keywords that are
1868 not in this list.
1870 When this is set, todo statistics is updated in the parent of the
1871 current entry each time a todo state is changed."
1872 :group 'org-todo
1873 :type '(choice
1874 (const :tag "Yes, only for TODO entries" t)
1875 (const :tag "Yes, including all entries" 'all-headlines)
1876 (repeat :tag "Yes, for TODOs in this list"
1877 (string :tag "TODO keyword"))
1878 (other :tag "No TODO statistics" nil)))
1880 (defcustom org-hierarchical-todo-statistics t
1881 "Non-nil means TODO statistics covers just direct children.
1882 When nil, all entries in the subtree are considered.
1883 This has only an effect if `org-provide-todo-statistics' is set.
1884 To set this to nil for only a single subtree, use a COOKIE_DATA
1885 property and include the word \"recursive\" into the value."
1886 :group 'org-todo
1887 :type 'boolean)
1889 (defcustom org-after-todo-state-change-hook nil
1890 "Hook which is run after the state of a TODO item was changed.
1891 The new state (a string with a TODO keyword, or nil) is available in the
1892 Lisp variable `state'."
1893 :group 'org-todo
1894 :type 'hook)
1896 (defvar org-blocker-hook nil
1897 "Hook for functions that are allowed to block a state change.
1899 Each function gets as its single argument a property list, see
1900 `org-trigger-hook' for more information about this list.
1902 If any of the functions in this hook returns nil, the state change
1903 is blocked.")
1905 (defvar org-trigger-hook nil
1906 "Hook for functions that are triggered by a state change.
1908 Each function gets as its single argument a property list with at least
1909 the following elements:
1911 (:type type-of-change :position pos-at-entry-start
1912 :from old-state :to new-state)
1914 Depending on the type, more properties may be present.
1916 This mechanism is currently implemented for:
1918 TODO state changes
1919 ------------------
1920 :type todo-state-change
1921 :from previous state (keyword as a string), or nil, or a symbol
1922 'todo' or 'done', to indicate the general type of state.
1923 :to new state, like in :from")
1925 (defcustom org-enforce-todo-dependencies nil
1926 "Non-nil means undone TODO entries will block switching the parent to DONE.
1927 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1928 be blocked if any prior sibling is not yet done.
1929 Finally, if the parent is blocked because of ordered siblings of its own,
1930 the child will also be blocked.
1931 This variable needs to be set before org.el is loaded, and you need to
1932 restart Emacs after a change to make the change effective. The only way
1933 to change is while Emacs is running is through the customize interface."
1934 :set (lambda (var val)
1935 (set var val)
1936 (if val
1937 (add-hook 'org-blocker-hook
1938 'org-block-todo-from-children-or-siblings-or-parent)
1939 (remove-hook 'org-blocker-hook
1940 'org-block-todo-from-children-or-siblings-or-parent)))
1941 :group 'org-todo
1942 :type 'boolean)
1944 (defcustom org-enforce-todo-checkbox-dependencies nil
1945 "Non-nil means unchecked boxes will block switching the parent to DONE.
1946 When this is nil, checkboxes have no influence on switching TODO states.
1947 When non-nil, you first need to check off all check boxes before the TODO
1948 entry can be switched to DONE.
1949 This variable needs to be set before org.el is loaded, and you need to
1950 restart Emacs after a change to make the change effective. The only way
1951 to change is while Emacs is running is through the customize interface."
1952 :set (lambda (var val)
1953 (set var val)
1954 (if val
1955 (add-hook 'org-blocker-hook
1956 'org-block-todo-from-checkboxes)
1957 (remove-hook 'org-blocker-hook
1958 'org-block-todo-from-checkboxes)))
1959 :group 'org-todo
1960 :type 'boolean)
1962 (defcustom org-treat-insert-todo-heading-as-state-change nil
1963 "Non-nil means inserting a TODO heading is treated as state change.
1964 So when the command \\[org-insert-todo-heading] is used, state change
1965 logging will apply if appropriate. When nil, the new TODO item will
1966 be inserted directly, and no logging will take place."
1967 :group 'org-todo
1968 :type 'boolean)
1970 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1971 "Non-nil means switching TODO states with S-cursor counts as state change.
1972 This is the default behavior. However, setting this to nil allows a
1973 convenient way to select a TODO state and bypass any logging associated
1974 with that."
1975 :group 'org-todo
1976 :type 'boolean)
1978 (defcustom org-todo-state-tags-triggers nil
1979 "Tag changes that should be triggered by TODO state changes.
1980 This is a list. Each entry is
1982 (state-change (tag . flag) .......)
1984 State-change can be a string with a state, and empty string to indicate the
1985 state that has no TODO keyword, or it can be one of the symbols `todo'
1986 or `done', meaning any not-done or done state, respectively."
1987 :group 'org-todo
1988 :group 'org-tags
1989 :type '(repeat
1990 (cons (choice :tag "When changing to"
1991 (const :tag "Not-done state" todo)
1992 (const :tag "Done state" done)
1993 (string :tag "State"))
1994 (repeat
1995 (cons :tag "Tag action"
1996 (string :tag "Tag")
1997 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1999 (defcustom org-log-done nil
2000 "Information to record when a task moves to the DONE state.
2002 Possible values are:
2004 nil Don't add anything, just change the keyword
2005 time Add a time stamp to the task
2006 note Prompt for a note and add it with template `org-log-note-headings'
2008 This option can also be set with on a per-file-basis with
2010 #+STARTUP: nologdone
2011 #+STARTUP: logdone
2012 #+STARTUP: lognotedone
2014 You can have local logging settings for a subtree by setting the LOGGING
2015 property to one or more of these keywords."
2016 :group 'org-todo
2017 :group 'org-progress
2018 :type '(choice
2019 (const :tag "No logging" nil)
2020 (const :tag "Record CLOSED timestamp" time)
2021 (const :tag "Record CLOSED timestamp with note." note)))
2023 ;; Normalize old uses of org-log-done.
2024 (cond
2025 ((eq org-log-done t) (setq org-log-done 'time))
2026 ((and (listp org-log-done) (memq 'done org-log-done))
2027 (setq org-log-done 'note)))
2029 (defcustom org-log-reschedule nil
2030 "Information to record when the scheduling date of a tasks is modified.
2032 Possible values are:
2034 nil Don't add anything, just change the date
2035 time Add a time stamp to the task
2036 note Prompt for a note and add it with template `org-log-note-headings'
2038 This option can also be set with on a per-file-basis with
2040 #+STARTUP: nologreschedule
2041 #+STARTUP: logreschedule
2042 #+STARTUP: lognotereschedule"
2043 :group 'org-todo
2044 :group 'org-progress
2045 :type '(choice
2046 (const :tag "No logging" nil)
2047 (const :tag "Record timestamp" time)
2048 (const :tag "Record timestamp with note." note)))
2050 (defcustom org-log-redeadline nil
2051 "Information to record when the deadline date of a tasks is modified.
2053 Possible values are:
2055 nil Don't add anything, just change the date
2056 time Add a time stamp to the task
2057 note Prompt for a note and add it with template `org-log-note-headings'
2059 This option can also be set with on a per-file-basis with
2061 #+STARTUP: nologredeadline
2062 #+STARTUP: logredeadline
2063 #+STARTUP: lognoteredeadline
2065 You can have local logging settings for a subtree by setting the LOGGING
2066 property to one or more of these keywords."
2067 :group 'org-todo
2068 :group 'org-progress
2069 :type '(choice
2070 (const :tag "No logging" nil)
2071 (const :tag "Record timestamp" time)
2072 (const :tag "Record timestamp with note." note)))
2074 (defcustom org-log-note-clock-out nil
2075 "Non-nil means record a note when clocking out of an item.
2076 This can also be configured on a per-file basis by adding one of
2077 the following lines anywhere in the buffer:
2079 #+STARTUP: lognoteclock-out
2080 #+STARTUP: nolognoteclock-out"
2081 :group 'org-todo
2082 :group 'org-progress
2083 :type 'boolean)
2085 (defcustom org-log-done-with-time t
2086 "Non-nil means the CLOSED time stamp will contain date and time.
2087 When nil, only the date will be recorded."
2088 :group 'org-progress
2089 :type 'boolean)
2091 (defcustom org-log-note-headings
2092 '((done . "CLOSING NOTE %t")
2093 (state . "State %-12s from %-12S %t")
2094 (note . "Note taken on %t")
2095 (reschedule . "Rescheduled from %S on %t")
2096 (delschedule . "Not scheduled, was %S on %t")
2097 (redeadline . "New deadline from %S on %t")
2098 (deldeadline . "Removed deadline, was %S on %t")
2099 (refile . "Refiled on %t")
2100 (clock-out . ""))
2101 "Headings for notes added to entries.
2102 The value is an alist, with the car being a symbol indicating the note
2103 context, and the cdr is the heading to be used. The heading may also be the
2104 empty string.
2105 %t in the heading will be replaced by a time stamp.
2106 %s will be replaced by the new TODO state, in double quotes.
2107 %S will be replaced by the old TODO state, in double quotes.
2108 %u will be replaced by the user name.
2109 %U will be replaced by the full user name.
2111 In fact, it is not a good idea to change the `state' entry, because
2112 agenda log mode depends on the format of these entries."
2113 :group 'org-todo
2114 :group 'org-progress
2115 :type '(list :greedy t
2116 (cons (const :tag "Heading when closing an item" done) string)
2117 (cons (const :tag
2118 "Heading when changing todo state (todo sequence only)"
2119 state) string)
2120 (cons (const :tag "Heading when just taking a note" note) string)
2121 (cons (const :tag "Heading when clocking out" clock-out) string)
2122 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2123 (cons (const :tag "Heading when rescheduling" reschedule) string)
2124 (cons (const :tag "Heading when changing deadline" redeadline) string)
2125 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2126 (cons (const :tag "Heading when refiling" refile) string)))
2128 (unless (assq 'note org-log-note-headings)
2129 (push '(note . "%t") org-log-note-headings))
2131 (defcustom org-log-into-drawer nil
2132 "Non-nil means insert state change notes and time stamps into a drawer.
2133 When nil, state changes notes will be inserted after the headline and
2134 any scheduling and clock lines, but not inside a drawer.
2136 The value of this variable should be the name of the drawer to use.
2137 LOGBOOK is proposed at the default drawer for this purpose, you can
2138 also set this to a string to define the drawer of your choice.
2140 A value of t is also allowed, representing \"LOGBOOK\".
2142 If this variable is set, `org-log-state-notes-insert-after-drawers'
2143 will be ignored.
2145 You can set the property LOG_INTO_DRAWER to overrule this setting for
2146 a subtree."
2147 :group 'org-todo
2148 :group 'org-progress
2149 :type '(choice
2150 (const :tag "Not into a drawer" nil)
2151 (const :tag "LOGBOOK" t)
2152 (string :tag "Other")))
2154 (if (fboundp 'defvaralias)
2155 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2157 (defun org-log-into-drawer ()
2158 "Return the value of `org-log-into-drawer', but let properties overrule.
2159 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2160 used instead of the default value."
2161 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2162 (cond
2163 ((or (not p) (equal p "nil")) org-log-into-drawer)
2164 ((equal p "t") "LOGBOOK")
2165 (t p))))
2167 (defcustom org-log-state-notes-insert-after-drawers nil
2168 "Non-nil means insert state change notes after any drawers in entry.
2169 Only the drawers that *immediately* follow the headline and the
2170 deadline/scheduled line are skipped.
2171 When nil, insert notes right after the heading and perhaps the line
2172 with deadline/scheduling if present.
2174 This variable will have no effect if `org-log-into-drawer' is
2175 set."
2176 :group 'org-todo
2177 :group 'org-progress
2178 :type 'boolean)
2180 (defcustom org-log-states-order-reversed t
2181 "Non-nil means the latest state note will be directly after heading.
2182 When nil, the state change notes will be ordered according to time."
2183 :group 'org-todo
2184 :group 'org-progress
2185 :type 'boolean)
2187 (defcustom org-log-repeat 'time
2188 "Non-nil means record moving through the DONE state when triggering repeat.
2189 An auto-repeating task is immediately switched back to TODO when
2190 marked DONE. If you are not logging state changes (by adding \"@\"
2191 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2192 record a closing note, there will be no record of the task moving
2193 through DONE. This variable forces taking a note anyway.
2195 nil Don't force a record
2196 time Record a time stamp
2197 note Record a note
2199 This option can also be set with on a per-file-basis with
2201 #+STARTUP: logrepeat
2202 #+STARTUP: lognoterepeat
2203 #+STARTUP: nologrepeat
2205 You can have local logging settings for a subtree by setting the LOGGING
2206 property to one or more of these keywords."
2207 :group 'org-todo
2208 :group 'org-progress
2209 :type '(choice
2210 (const :tag "Don't force a record" nil)
2211 (const :tag "Force recording the DONE state" time)
2212 (const :tag "Force recording a note with the DONE state" note)))
2215 (defgroup org-priorities nil
2216 "Priorities in Org-mode."
2217 :tag "Org Priorities"
2218 :group 'org-todo)
2220 (defcustom org-enable-priority-commands t
2221 "Non-nil means priority commands are active.
2222 When nil, these commands will be disabled, so that you never accidentally
2223 set a priority."
2224 :group 'org-priorities
2225 :type 'boolean)
2227 (defcustom org-highest-priority ?A
2228 "The highest priority of TODO items. A character like ?A, ?B etc.
2229 Must have a smaller ASCII number than `org-lowest-priority'."
2230 :group 'org-priorities
2231 :type 'character)
2233 (defcustom org-lowest-priority ?C
2234 "The lowest priority of TODO items. A character like ?A, ?B etc.
2235 Must have a larger ASCII number than `org-highest-priority'."
2236 :group 'org-priorities
2237 :type 'character)
2239 (defcustom org-default-priority ?B
2240 "The default priority of TODO items.
2241 This is the priority an item get if no explicit priority is given."
2242 :group 'org-priorities
2243 :type 'character)
2245 (defcustom org-priority-start-cycle-with-default t
2246 "Non-nil means start with default priority when starting to cycle.
2247 When this is nil, the first step in the cycle will be (depending on the
2248 command used) one higher or lower that the default priority."
2249 :group 'org-priorities
2250 :type 'boolean)
2252 (defgroup org-time nil
2253 "Options concerning time stamps and deadlines in Org-mode."
2254 :tag "Org Time"
2255 :group 'org)
2257 (defcustom org-insert-labeled-timestamps-at-point nil
2258 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2259 When nil, these labeled time stamps are forces into the second line of an
2260 entry, just after the headline. When scheduling from the global TODO list,
2261 the time stamp will always be forced into the second line."
2262 :group 'org-time
2263 :type 'boolean)
2265 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2266 "Formats for `format-time-string' which are used for time stamps.
2267 It is not recommended to change this constant.")
2269 (defcustom org-time-stamp-rounding-minutes '(0 5)
2270 "Number of minutes to round time stamps to.
2271 These are two values, the first applies when first creating a time stamp.
2272 The second applies when changing it with the commands `S-up' and `S-down'.
2273 When changing the time stamp, this means that it will change in steps
2274 of N minutes, as given by the second value.
2276 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2277 numbers should be factors of 60, so for example 5, 10, 15.
2279 When this is larger than 1, you can still force an exact time-stamp by using
2280 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2281 and by using a prefix arg to `S-up/down' to specify the exact number
2282 of minutes to shift."
2283 :group 'org-time
2284 :get '(lambda (var) ; Make sure all entries have 5 elements
2285 (if (integerp (default-value var))
2286 (list (default-value var) 5)
2287 (default-value var)))
2288 :type '(list
2289 (integer :tag "when inserting times")
2290 (integer :tag "when modifying times")))
2292 ;; Normalize old customizations of this variable.
2293 (when (integerp org-time-stamp-rounding-minutes)
2294 (setq org-time-stamp-rounding-minutes
2295 (list org-time-stamp-rounding-minutes
2296 org-time-stamp-rounding-minutes)))
2298 (defcustom org-display-custom-times nil
2299 "Non-nil means overlay custom formats over all time stamps.
2300 The formats are defined through the variable `org-time-stamp-custom-formats'.
2301 To turn this on on a per-file basis, insert anywhere in the file:
2302 #+STARTUP: customtime"
2303 :group 'org-time
2304 :set 'set-default
2305 :type 'sexp)
2306 (make-variable-buffer-local 'org-display-custom-times)
2308 (defcustom org-time-stamp-custom-formats
2309 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2310 "Custom formats for time stamps. See `format-time-string' for the syntax.
2311 These are overlayed over the default ISO format if the variable
2312 `org-display-custom-times' is set. Time like %H:%M should be at the
2313 end of the second format. The custom formats are also honored by export
2314 commands, if custom time display is turned on at the time of export."
2315 :group 'org-time
2316 :type 'sexp)
2318 (defun org-time-stamp-format (&optional long inactive)
2319 "Get the right format for a time string."
2320 (let ((f (if long (cdr org-time-stamp-formats)
2321 (car org-time-stamp-formats))))
2322 (if inactive
2323 (concat "[" (substring f 1 -1) "]")
2324 f)))
2326 (defcustom org-time-clocksum-format "%d:%02d"
2327 "The format string used when creating CLOCKSUM lines, or when
2328 org-mode generates a time duration."
2329 :group 'org-time
2330 :type 'string)
2332 (defcustom org-time-clocksum-use-fractional nil
2333 "If non-nil, \\[org-clock-display] uses fractional times.
2334 org-mode generates a time duration."
2335 :group 'org-time
2336 :type 'boolean)
2338 (defcustom org-time-clocksum-fractional-format "%.2f"
2339 "The format string used when creating CLOCKSUM lines, or when
2340 org-mode generates a time duration."
2341 :group 'org-time
2342 :type 'string)
2344 (defcustom org-deadline-warning-days 14
2345 "No. of days before expiration during which a deadline becomes active.
2346 This variable governs the display in sparse trees and in the agenda.
2347 When 0 or negative, it means use this number (the absolute value of it)
2348 even if a deadline has a different individual lead time specified.
2350 Custom commands can set this variable in the options section."
2351 :group 'org-time
2352 :group 'org-agenda-daily/weekly
2353 :type 'integer)
2355 (defcustom org-read-date-prefer-future t
2356 "Non-nil means assume future for incomplete date input from user.
2357 This affects the following situations:
2358 1. The user gives a month but not a year.
2359 For example, if it is april and you enter \"feb 2\", this will be read
2360 as feb 2, *next* year. \"May 5\", however, will be this year.
2361 2. The user gives a day, but no month.
2362 For example, if today is the 15th, and you enter \"3\", Org-mode will
2363 read this as the third of *next* month. However, if you enter \"17\",
2364 it will be considered as *this* month.
2366 If you set this variable to the symbol `time', then also the following
2367 will work:
2369 3. If the user gives a time, but no day. If the time is before now,
2370 to will be interpreted as tomorrow.
2372 Currently none of this works for ISO week specifications.
2374 When this option is nil, the current day, month and year will always be
2375 used as defaults."
2376 :group 'org-time
2377 :type '(choice
2378 (const :tag "Never" nil)
2379 (const :tag "Check month and day" t)
2380 (const :tag "Check month, day, and time" time)))
2382 (defcustom org-read-date-display-live t
2383 "Non-nil means display current interpretation of date prompt live.
2384 This display will be in an overlay, in the minibuffer."
2385 :group 'org-time
2386 :type 'boolean)
2388 (defcustom org-read-date-popup-calendar t
2389 "Non-nil means pop up a calendar when prompting for a date.
2390 In the calendar, the date can be selected with mouse-1. However, the
2391 minibuffer will also be active, and you can simply enter the date as well.
2392 When nil, only the minibuffer will be available."
2393 :group 'org-time
2394 :type 'boolean)
2395 (if (fboundp 'defvaralias)
2396 (defvaralias 'org-popup-calendar-for-date-prompt
2397 'org-read-date-popup-calendar))
2399 (defcustom org-read-date-minibuffer-setup-hook nil
2400 "Hook to be used to set up keys for the date/time interface.
2401 Add key definitions to `minibuffer-local-map', which will be a temporary
2402 copy."
2403 :group 'org-time
2404 :type 'hook)
2406 (defcustom org-extend-today-until 0
2407 "The hour when your day really ends. Must be an integer.
2408 This has influence for the following applications:
2409 - When switching the agenda to \"today\". It it is still earlier than
2410 the time given here, the day recognized as TODAY is actually yesterday.
2411 - When a date is read from the user and it is still before the time given
2412 here, the current date and time will be assumed to be yesterday, 23:59.
2413 Also, timestamps inserted in remember templates follow this rule.
2415 IMPORTANT: This is a feature whose implementation is and likely will
2416 remain incomplete. Really, it is only here because past midnight seems to
2417 be the favorite working time of John Wiegley :-)"
2418 :group 'org-time
2419 :type 'integer)
2421 (defcustom org-edit-timestamp-down-means-later nil
2422 "Non-nil means S-down will increase the time in a time stamp.
2423 When nil, S-up will increase."
2424 :group 'org-time
2425 :type 'boolean)
2427 (defcustom org-calendar-follow-timestamp-change t
2428 "Non-nil means make the calendar window follow timestamp changes.
2429 When a timestamp is modified and the calendar window is visible, it will be
2430 moved to the new date."
2431 :group 'org-time
2432 :type 'boolean)
2434 (defgroup org-tags nil
2435 "Options concerning tags in Org-mode."
2436 :tag "Org Tags"
2437 :group 'org)
2439 (defcustom org-tag-alist nil
2440 "List of tags allowed in Org-mode files.
2441 When this list is nil, Org-mode will base TAG input on what is already in the
2442 buffer.
2443 The value of this variable is an alist, the car of each entry must be a
2444 keyword as a string, the cdr may be a character that is used to select
2445 that tag through the fast-tag-selection interface.
2446 See the manual for details."
2447 :group 'org-tags
2448 :type '(repeat
2449 (choice
2450 (cons (string :tag "Tag name")
2451 (character :tag "Access char"))
2452 (list :tag "Start radio group"
2453 (const :startgroup)
2454 (option (string :tag "Group description")))
2455 (list :tag "End radio group"
2456 (const :endgroup)
2457 (option (string :tag "Group description")))
2458 (const :tag "New line" (:newline)))))
2460 (defcustom org-tag-persistent-alist nil
2461 "List of tags that will always appear in all Org-mode files.
2462 This is in addition to any in buffer settings or customizations
2463 of `org-tag-alist'.
2464 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2465 The value of this variable is an alist, the car of each entry must be a
2466 keyword as a string, the cdr may be a character that is used to select
2467 that tag through the fast-tag-selection interface.
2468 See the manual for details.
2469 To disable these tags on a per-file basis, insert anywhere in the file:
2470 #+STARTUP: noptag"
2471 :group 'org-tags
2472 :type '(repeat
2473 (choice
2474 (cons (string :tag "Tag name")
2475 (character :tag "Access char"))
2476 (const :tag "Start radio group" (:startgroup))
2477 (const :tag "End radio group" (:endgroup))
2478 (const :tag "New line" (:newline)))))
2480 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2481 "If non-nil, always offer completion for all tags of all agenda files.
2482 Instead of customizing this variable directly, you might want to
2483 set it locally for remember buffers, because there no list of
2484 tags in that file can be created dynamically (there are none).
2486 (add-hook 'org-remember-mode-hook
2487 (lambda ()
2488 (set (make-local-variable
2489 'org-complete-tags-always-offer-all-agenda-tags)
2490 t)))"
2491 :group 'org-tags
2492 :type 'boolean)
2494 (defvar org-file-tags nil
2495 "List of tags that can be inherited by all entries in the file.
2496 The tags will be inherited if the variable `org-use-tag-inheritance'
2497 says they should be.
2498 This variable is populated from #+FILETAGS lines.")
2500 (defcustom org-use-fast-tag-selection 'auto
2501 "Non-nil means use fast tag selection scheme.
2502 This is a special interface to select and deselect tags with single keys.
2503 When nil, fast selection is never used.
2504 When the symbol `auto', fast selection is used if and only if selection
2505 characters for tags have been configured, either through the variable
2506 `org-tag-alist' or through a #+TAGS line in the buffer.
2507 When t, fast selection is always used and selection keys are assigned
2508 automatically if necessary."
2509 :group 'org-tags
2510 :type '(choice
2511 (const :tag "Always" t)
2512 (const :tag "Never" nil)
2513 (const :tag "When selection characters are configured" 'auto)))
2515 (defcustom org-fast-tag-selection-single-key nil
2516 "Non-nil means fast tag selection exits after first change.
2517 When nil, you have to press RET to exit it.
2518 During fast tag selection, you can toggle this flag with `C-c'.
2519 This variable can also have the value `expert'. In this case, the window
2520 displaying the tags menu is not even shown, until you press C-c again."
2521 :group 'org-tags
2522 :type '(choice
2523 (const :tag "No" nil)
2524 (const :tag "Yes" t)
2525 (const :tag "Expert" expert)))
2527 (defvar org-fast-tag-selection-include-todo nil
2528 "Non-nil means fast tags selection interface will also offer TODO states.
2529 This is an undocumented feature, you should not rely on it.")
2531 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2532 "The column to which tags should be indented in a headline.
2533 If this number is positive, it specifies the column. If it is negative,
2534 it means that the tags should be flushright to that column. For example,
2535 -80 works well for a normal 80 character screen."
2536 :group 'org-tags
2537 :type 'integer)
2539 (defcustom org-auto-align-tags t
2540 "Non-nil means realign tags after pro/demotion of TODO state change.
2541 These operations change the length of a headline and therefore shift
2542 the tags around. With this options turned on, after each such operation
2543 the tags are again aligned to `org-tags-column'."
2544 :group 'org-tags
2545 :type 'boolean)
2547 (defcustom org-use-tag-inheritance t
2548 "Non-nil means tags in levels apply also for sublevels.
2549 When nil, only the tags directly given in a specific line apply there.
2550 This may also be a list of tags that should be inherited, or a regexp that
2551 matches tags that should be inherited. Additional control is possible
2552 with the variable `org-tags-exclude-from-inheritance' which gives an
2553 explicit list of tags to be excluded from inheritance., even if the value of
2554 `org-use-tag-inheritance' would select it for inheritance.
2556 If this option is t, a match early-on in a tree can lead to a large
2557 number of matches in the subtree when constructing the agenda or creating
2558 a sparse tree. If you only want to see the first match in a tree during
2559 a search, check out the variable `org-tags-match-list-sublevels'."
2560 :group 'org-tags
2561 :type '(choice
2562 (const :tag "Not" nil)
2563 (const :tag "Always" t)
2564 (repeat :tag "Specific tags" (string :tag "Tag"))
2565 (regexp :tag "Tags matched by regexp")))
2567 (defcustom org-tags-exclude-from-inheritance nil
2568 "List of tags that should never be inherited.
2569 This is a way to exclude a few tags from inheritance. For way to do
2570 the opposite, to actively allow inheritance for selected tags,
2571 see the variable `org-use-tag-inheritance'."
2572 :group 'org-tags
2573 :type '(repeat (string :tag "Tag")))
2575 (defun org-tag-inherit-p (tag)
2576 "Check if TAG is one that should be inherited."
2577 (cond
2578 ((member tag org-tags-exclude-from-inheritance) nil)
2579 ((eq org-use-tag-inheritance t) t)
2580 ((not org-use-tag-inheritance) nil)
2581 ((stringp org-use-tag-inheritance)
2582 (string-match org-use-tag-inheritance tag))
2583 ((listp org-use-tag-inheritance)
2584 (member tag org-use-tag-inheritance))
2585 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2587 (defcustom org-tags-match-list-sublevels t
2588 "Non-nil means list also sublevels of headlines matching a search.
2589 This variable applies to tags/property searches, and also to stuck
2590 projects because this search is based on a tags match as well.
2592 When set to the symbol `indented', sublevels are indented with
2593 leading dots.
2595 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2596 the sublevels of a headline matching a tag search often also match
2597 the same search. Listing all of them can create very long lists.
2598 Setting this variable to nil causes subtrees of a match to be skipped.
2600 This variable is semi-obsolete and probably should always be true. It
2601 is better to limit inheritance to certain tags using the variables
2602 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2603 :group 'org-tags
2604 :type '(choice
2605 (const :tag "No, don't list them" nil)
2606 (const :tag "Yes, do list them" t)
2607 (const :tag "List them, indented with leading dots" indented)))
2609 (defcustom org-tags-sort-function nil
2610 "When set, tags are sorted using this function as a comparator"
2611 :group 'org-tags
2612 :type '(choice
2613 (const :tag "No sorting" nil)
2614 (const :tag "Alphabetical" string<)
2615 (const :tag "Reverse alphabetical" string>)
2616 (function :tag "Custom function" nil)))
2618 (defvar org-tags-history nil
2619 "History of minibuffer reads for tags.")
2620 (defvar org-last-tags-completion-table nil
2621 "The last used completion table for tags.")
2622 (defvar org-after-tags-change-hook nil
2623 "Hook that is run after the tags in a line have changed.")
2625 (defgroup org-properties nil
2626 "Options concerning properties in Org-mode."
2627 :tag "Org Properties"
2628 :group 'org)
2630 (defcustom org-property-format "%-10s %s"
2631 "How property key/value pairs should be formatted by `indent-line'.
2632 When `indent-line' hits a property definition, it will format the line
2633 according to this format, mainly to make sure that the values are
2634 lined-up with respect to each other."
2635 :group 'org-properties
2636 :type 'string)
2638 (defcustom org-use-property-inheritance nil
2639 "Non-nil means properties apply also for sublevels.
2641 This setting is chiefly used during property searches. Turning it on can
2642 cause significant overhead when doing a search, which is why it is not
2643 on by default.
2645 When nil, only the properties directly given in the current entry count.
2646 When t, every property is inherited. The value may also be a list of
2647 properties that should have inheritance, or a regular expression matching
2648 properties that should be inherited.
2650 However, note that some special properties use inheritance under special
2651 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2652 and the properties ending in \"_ALL\" when they are used as descriptor
2653 for valid values of a property.
2655 Note for programmers:
2656 When querying an entry with `org-entry-get', you can control if inheritance
2657 should be used. By default, `org-entry-get' looks only at the local
2658 properties. You can request inheritance by setting the inherit argument
2659 to t (to force inheritance) or to `selective' (to respect the setting
2660 in this variable)."
2661 :group 'org-properties
2662 :type '(choice
2663 (const :tag "Not" nil)
2664 (const :tag "Always" t)
2665 (repeat :tag "Specific properties" (string :tag "Property"))
2666 (regexp :tag "Properties matched by regexp")))
2668 (defun org-property-inherit-p (property)
2669 "Check if PROPERTY is one that should be inherited."
2670 (cond
2671 ((eq org-use-property-inheritance t) t)
2672 ((not org-use-property-inheritance) nil)
2673 ((stringp org-use-property-inheritance)
2674 (string-match org-use-property-inheritance property))
2675 ((listp org-use-property-inheritance)
2676 (member property org-use-property-inheritance))
2677 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2679 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2680 "The default column format, if no other format has been defined.
2681 This variable can be set on the per-file basis by inserting a line
2683 #+COLUMNS: %25ITEM ....."
2684 :group 'org-properties
2685 :type 'string)
2687 (defcustom org-columns-ellipses ".."
2688 "The ellipses to be used when a field in column view is truncated.
2689 When this is the empty string, as many characters as possible are shown,
2690 but then there will be no visual indication that the field has been truncated.
2691 When this is a string of length N, the last N characters of a truncated
2692 field are replaced by this string. If the column is narrower than the
2693 ellipses string, only part of the ellipses string will be shown."
2694 :group 'org-properties
2695 :type 'string)
2697 (defcustom org-columns-modify-value-for-display-function nil
2698 "Function that modifies values for display in column view.
2699 For example, it can be used to cut out a certain part from a time stamp.
2700 The function must take 2 arguments:
2702 column-title The title of the column (*not* the property name)
2703 value The value that should be modified.
2705 The function should return the value that should be displayed,
2706 or nil if the normal value should be used."
2707 :group 'org-properties
2708 :type 'function)
2710 (defcustom org-effort-property "Effort"
2711 "The property that is being used to keep track of effort estimates.
2712 Effort estimates given in this property need to have the format H:MM."
2713 :group 'org-properties
2714 :group 'org-progress
2715 :type '(string :tag "Property"))
2717 (defconst org-global-properties-fixed
2718 '(("VISIBILITY_ALL" . "folded children content all")
2719 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2720 "List of property/value pairs that can be inherited by any entry.
2722 These are fixed values, for the preset properties. The user variable
2723 that can be used to add to this list is `org-global-properties'.
2725 The entries in this list are cons cells where the car is a property
2726 name and cdr is a string with the value. If the value represents
2727 multiple items like an \"_ALL\" property, separate the items by
2728 spaces.")
2730 (defcustom org-global-properties nil
2731 "List of property/value pairs that can be inherited by any entry.
2733 This list will be combined with the constant `org-global-properties-fixed'.
2735 The entries in this list are cons cells where the car is a property
2736 name and cdr is a string with the value.
2738 You can set buffer-local values for the same purpose in the variable
2739 `org-file-properties' this by adding lines like
2741 #+PROPERTY: NAME VALUE"
2742 :group 'org-properties
2743 :type '(repeat
2744 (cons (string :tag "Property")
2745 (string :tag "Value"))))
2747 (defvar org-file-properties nil
2748 "List of property/value pairs that can be inherited by any entry.
2749 Valid for the current buffer.
2750 This variable is populated from #+PROPERTY lines.")
2751 (make-variable-buffer-local 'org-file-properties)
2753 (defgroup org-agenda nil
2754 "Options concerning agenda views in Org-mode."
2755 :tag "Org Agenda"
2756 :group 'org)
2758 (defvar org-category nil
2759 "Variable used by org files to set a category for agenda display.
2760 Such files should use a file variable to set it, for example
2762 # -*- mode: org; org-category: \"ELisp\"
2764 or contain a special line
2766 #+CATEGORY: ELisp
2768 If the file does not specify a category, then file's base name
2769 is used instead.")
2770 (make-variable-buffer-local 'org-category)
2771 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2773 (defcustom org-agenda-files nil
2774 "The files to be used for agenda display.
2775 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2776 \\[org-remove-file]. You can also use customize to edit the list.
2778 If an entry is a directory, all files in that directory that are matched by
2779 `org-agenda-file-regexp' will be part of the file list.
2781 If the value of the variable is not a list but a single file name, then
2782 the list of agenda files is actually stored and maintained in that file, one
2783 agenda file per line. In this file paths can be given relative to
2784 `org-directory'. Tilde expansion and environment variable substitution
2785 are also made."
2786 :group 'org-agenda
2787 :type '(choice
2788 (repeat :tag "List of files and directories" file)
2789 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2791 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2792 "Regular expression to match files for `org-agenda-files'.
2793 If any element in the list in that variable contains a directory instead
2794 of a normal file, all files in that directory that are matched by this
2795 regular expression will be included."
2796 :group 'org-agenda
2797 :type 'regexp)
2799 (defcustom org-agenda-text-search-extra-files nil
2800 "List of extra files to be searched by text search commands.
2801 These files will be search in addition to the agenda files by the
2802 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2803 Note that these files will only be searched for text search commands,
2804 not for the other agenda views like todo lists, tag searches or the weekly
2805 agenda. This variable is intended to list notes and possibly archive files
2806 that should also be searched by these two commands.
2807 In fact, if the first element in the list is the symbol `agenda-archives',
2808 than all archive files of all agenda files will be added to the search
2809 scope."
2810 :group 'org-agenda
2811 :type '(set :greedy t
2812 (const :tag "Agenda Archives" agenda-archives)
2813 (repeat :inline t (file))))
2815 (if (fboundp 'defvaralias)
2816 (defvaralias 'org-agenda-multi-occur-extra-files
2817 'org-agenda-text-search-extra-files))
2819 (defcustom org-agenda-skip-unavailable-files nil
2820 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2821 A nil value means to remove them, after a query, from the list."
2822 :group 'org-agenda
2823 :type 'boolean)
2825 (defcustom org-calendar-to-agenda-key [?c]
2826 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2827 The command `org-calendar-goto-agenda' will be bound to this key. The
2828 default is the character `c' because then `c' can be used to switch back and
2829 forth between agenda and calendar."
2830 :group 'org-agenda
2831 :type 'sexp)
2833 (defcustom org-calendar-agenda-action-key [?k]
2834 "The key to be installed in `calendar-mode-map' for agenda-action.
2835 The command `org-agenda-action' will be bound to this key. The
2836 default is the character `k' because we use the same key in the agenda."
2837 :group 'org-agenda
2838 :type 'sexp)
2840 (defcustom org-calendar-insert-diary-entry-key [?i]
2841 "The key to be installed in `calendar-mode-map' for adding diary entries.
2842 This option is irrelevant until `org-agenda-diary-file' has been configured
2843 to point to an Org-mode file. When that is the case, the command
2844 `org-agenda-diary-entry' will be bound to the key given here, by default
2845 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2846 if you want to continue doing this, you need to change this to a different
2847 key."
2848 :group 'org-agenda
2849 :type 'sexp)
2851 (defcustom org-agenda-diary-file 'diary-file
2852 "File to which to add new entries with the `i' key in agenda and calendar.
2853 When this is the symbol `diary-file', the functionality in the Emacs
2854 calendar will be used to add entries to the `diary-file'. But when this
2855 points to a file, `org-agenda-diary-entry' will be used instead."
2856 :group 'org-agenda
2857 :type '(choice
2858 (const :tag "The standard Emacs diary file" diary-file)
2859 (file :tag "Special Org file diary entries")))
2861 (eval-after-load "calendar"
2862 '(progn
2863 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2864 'org-calendar-goto-agenda)
2865 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2866 'org-agenda-action)
2867 (add-hook 'calendar-mode-hook
2868 (lambda ()
2869 (unless (eq org-agenda-diary-file 'diary-file)
2870 (define-key calendar-mode-map
2871 org-calendar-insert-diary-entry-key
2872 'org-agenda-diary-entry))))))
2874 (defgroup org-latex nil
2875 "Options for embedding LaTeX code into Org-mode."
2876 :tag "Org LaTeX"
2877 :group 'org)
2879 (defcustom org-format-latex-options
2880 '(:foreground default :background default :scale 1.0
2881 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2882 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2883 "Options for creating images from LaTeX fragments.
2884 This is a property list with the following properties:
2885 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2886 `default' means use the foreground of the default face.
2887 :background the background color, or \"Transparent\".
2888 `default' means use the background of the default face.
2889 :scale a scaling factor for the size of the images.
2890 :html-foreground, :html-background, :html-scale
2891 the same numbers for HTML export.
2892 :matchers a list indicating which matchers should be used to
2893 find LaTeX fragments. Valid members of this list are:
2894 \"begin\" find environments
2895 \"$1\" find single characters surrounded by $.$
2896 \"$\" find math expressions surrounded by $...$
2897 \"$$\" find math expressions surrounded by $$....$$
2898 \"\\(\" find math expressions surrounded by \\(...\\)
2899 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2900 :group 'org-latex
2901 :type 'plist)
2903 (defcustom org-format-latex-signal-error t
2904 "Non-nil means signal an error when image creation of LaTeX snippets fails.
2905 When nil, just push out a message."
2906 :group 'org-latex
2907 :type 'boolean)
2909 (defcustom org-format-latex-header "\\documentclass{article}
2910 \\usepackage[usenames]{color}
2911 \\usepackage{amsmath}
2912 \\usepackage[mathscr]{eucal}
2913 \\pagestyle{empty} % do not remove
2914 % The settings below are copied from fullpage.sty
2915 \\setlength{\\textwidth}{\\paperwidth}
2916 \\addtolength{\\textwidth}{-3cm}
2917 \\setlength{\\oddsidemargin}{1.5cm}
2918 \\addtolength{\\oddsidemargin}{-2.54cm}
2919 \\setlength{\\evensidemargin}{\\oddsidemargin}
2920 \\setlength{\\textheight}{\\paperheight}
2921 \\addtolength{\\textheight}{-\\headheight}
2922 \\addtolength{\\textheight}{-\\headsep}
2923 \\addtolength{\\textheight}{-\\footskip}
2924 \\addtolength{\\textheight}{-3cm}
2925 \\setlength{\\topmargin}{1.5cm}
2926 \\addtolength{\\topmargin}{-2.54cm}"
2927 "The document header used for processing LaTeX fragments.
2928 It is imperative that this header make sure that no page number
2929 appears on the page."
2930 :group 'org-latex
2931 :type 'string)
2933 (defvar org-format-latex-header-extra nil)
2935 ;; The following variables are defined here because is it also used
2936 ;; when formatting latex fragments. Originally it was part of the
2937 ;; LaTeX exporter, which is why the name includes "export".
2938 (defcustom org-export-latex-default-packages-alist
2939 '(("AUTO" . "inputenc")
2940 ("T1" . "fontenc")
2941 ("" . "graphicx")
2942 ("" . "longtable")
2943 ("" . "float")
2944 ("" . "wrapfig")
2945 ("" . "soul")
2946 ("" . "t1enc")
2947 ("" . "textcomp")
2948 ("" . "marvosym")
2949 ("" . "wasysym")
2950 ("" . "latexsym")
2951 ("" . "amssymb")
2952 ("" . "hyperref"))
2953 "Alist of default packages to be inserted in the header. DON'T CHANGE THIS.
2954 Unless abslutely necessary that is.
2955 All the packages in this list are needed by one part or another of Org-mode
2956 to function properly. Therefore you should, not modify this variable unless
2957 you know what you are doing. The one reason to change it anyway is that
2958 you might be loading some other package that conflicts with one of the default
2959 packages.
2960 Each cell is of the format \( \"options\" . \"package\" \)."
2961 :group 'org-export-latex
2962 :type '(repeat
2963 (list
2964 (string :tag "options")
2965 (string :tag "package"))))
2967 (defcustom org-export-latex-packages-alist nil
2968 "Alist of packages to be inserted in the header.
2969 These will be inserted after `org-export-latex-default-packages-alist'.
2970 Each cell is of the format \( \"options\" . \"package\" \)."
2971 :group 'org-export-latex
2972 :type '(repeat
2973 (list
2974 (string :tag "options")
2975 (string :tag "package"))))
2977 (defgroup org-appearance nil
2978 "Settings for Org-mode appearance."
2979 :tag "Org Appearance"
2980 :group 'org)
2982 (defcustom org-level-color-stars-only nil
2983 "Non-nil means fontify only the stars in each headline.
2984 When nil, the entire headline is fontified.
2985 Changing it requires restart of `font-lock-mode' to become effective
2986 also in regions already fontified."
2987 :group 'org-appearance
2988 :type 'boolean)
2990 (defcustom org-hide-leading-stars nil
2991 "Non-nil means hide the first N-1 stars in a headline.
2992 This works by using the face `org-hide' for these stars. This
2993 face is white for a light background, and black for a dark
2994 background. You may have to customize the face `org-hide' to
2995 make this work.
2996 Changing it requires restart of `font-lock-mode' to become effective
2997 also in regions already fontified.
2998 You may also set this on a per-file basis by adding one of the following
2999 lines to the buffer:
3001 #+STARTUP: hidestars
3002 #+STARTUP: showstars"
3003 :group 'org-appearance
3004 :type 'boolean)
3006 (defcustom org-hidden-keywords nil
3007 "List of keywords that should be hidden when typed in the org buffer.
3008 For example, add #+TITLE to this list in order to make the
3009 document title appear in the buffer without the initial #+TITLE:
3010 keyword."
3011 :group 'org-appearance
3012 :type '(set (const :tag "#+AUTHOR" author)
3013 (const :tag "#+DATE" date)
3014 (const :tag "#+EMAIL" email)
3015 (const :tag "#+TITLE" title)))
3017 (defcustom org-fontify-done-headline nil
3018 "Non-nil means change the face of a headline if it is marked DONE.
3019 Normally, only the TODO/DONE keyword indicates the state of a headline.
3020 When this is non-nil, the headline after the keyword is set to the
3021 `org-headline-done' as an additional indication."
3022 :group 'org-appearance
3023 :type 'boolean)
3025 (defcustom org-fontify-emphasized-text t
3026 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3027 Changing this variable requires a restart of Emacs to take effect."
3028 :group 'org-appearance
3029 :type 'boolean)
3031 (defcustom org-fontify-whole-heading-line nil
3032 "Non-nil means fontify the whole line for headings.
3033 This is useful when setting a background color for the
3034 org-level-* faces."
3035 :group 'org-appearance
3036 :type 'boolean)
3038 (defcustom org-highlight-latex-fragments-and-specials nil
3039 "Non-nil means fontify what is treated specially by the exporters."
3040 :group 'org-appearance
3041 :type 'boolean)
3043 (defcustom org-hide-emphasis-markers nil
3044 "Non-nil mean font-lock should hide the emphasis marker characters."
3045 :group 'org-appearance
3046 :type 'boolean)
3048 (defvar org-emph-re nil
3049 "Regular expression for matching emphasis.")
3050 (defvar org-verbatim-re nil
3051 "Regular expression for matching verbatim text.")
3052 (defvar org-emphasis-regexp-components) ; defined just below
3053 (defvar org-emphasis-alist) ; defined just below
3054 (defun org-set-emph-re (var val)
3055 "Set variable and compute the emphasis regular expression."
3056 (set var val)
3057 (when (and (boundp 'org-emphasis-alist)
3058 (boundp 'org-emphasis-regexp-components)
3059 org-emphasis-alist org-emphasis-regexp-components)
3060 (let* ((e org-emphasis-regexp-components)
3061 (pre (car e))
3062 (post (nth 1 e))
3063 (border (nth 2 e))
3064 (body (nth 3 e))
3065 (nl (nth 4 e))
3066 (body1 (concat body "*?"))
3067 (markers (mapconcat 'car org-emphasis-alist ""))
3068 (vmarkers (mapconcat
3069 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3070 org-emphasis-alist "")))
3071 ;; make sure special characters appear at the right position in the class
3072 (if (string-match "\\^" markers)
3073 (setq markers (concat (replace-match "" t t markers) "^")))
3074 (if (string-match "-" markers)
3075 (setq markers (concat (replace-match "" t t markers) "-")))
3076 (if (string-match "\\^" vmarkers)
3077 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3078 (if (string-match "-" vmarkers)
3079 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3080 (if (> nl 0)
3081 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3082 (int-to-string nl) "\\}")))
3083 ;; Make the regexp
3084 (setq org-emph-re
3085 (concat "\\([" pre "]\\|^\\)"
3086 "\\("
3087 "\\([" markers "]\\)"
3088 "\\("
3089 "[^" border "]\\|"
3090 "[^" border "]"
3091 body1
3092 "[^" border "]"
3093 "\\)"
3094 "\\3\\)"
3095 "\\([" post "]\\|$\\)"))
3096 (setq org-verbatim-re
3097 (concat "\\([" pre "]\\|^\\)"
3098 "\\("
3099 "\\([" vmarkers "]\\)"
3100 "\\("
3101 "[^" border "]\\|"
3102 "[^" border "]"
3103 body1
3104 "[^" border "]"
3105 "\\)"
3106 "\\3\\)"
3107 "\\([" post "]\\|$\\)")))))
3109 (defcustom org-emphasis-regexp-components
3110 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3111 "Components used to build the regular expression for emphasis.
3112 This is a list with 6 entries. Terminology: In an emphasis string
3113 like \" *strong word* \", we call the initial space PREMATCH, the final
3114 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3115 and \"trong wor\" is the body. The different components in this variable
3116 specify what is allowed/forbidden in each part:
3118 pre Chars allowed as prematch. Beginning of line will be allowed too.
3119 post Chars allowed as postmatch. End of line will be allowed too.
3120 border The chars *forbidden* as border characters.
3121 body-regexp A regexp like \".\" to match a body character. Don't use
3122 non-shy groups here, and don't allow newline here.
3123 newline The maximum number of newlines allowed in an emphasis exp.
3125 Use customize to modify this, or restart Emacs after changing it."
3126 :group 'org-appearance
3127 :set 'org-set-emph-re
3128 :type '(list
3129 (sexp :tag "Allowed chars in pre ")
3130 (sexp :tag "Allowed chars in post ")
3131 (sexp :tag "Forbidden chars in border ")
3132 (sexp :tag "Regexp for body ")
3133 (integer :tag "number of newlines allowed")
3134 (option (boolean :tag "Please ignore this button"))))
3136 (defcustom org-emphasis-alist
3137 `(("*" bold "<b>" "</b>")
3138 ("/" italic "<i>" "</i>")
3139 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3140 ("=" org-code "<code>" "</code>" verbatim)
3141 ("~" org-verbatim "<code>" "</code>" verbatim)
3142 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3143 "<del>" "</del>")
3145 "Special syntax for emphasized text.
3146 Text starting and ending with a special character will be emphasized, for
3147 example *bold*, _underlined_ and /italic/. This variable sets the marker
3148 characters, the face to be used by font-lock for highlighting in Org-mode
3149 Emacs buffers, and the HTML tags to be used for this.
3150 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3151 Use customize to modify this, or restart Emacs after changing it."
3152 :group 'org-appearance
3153 :set 'org-set-emph-re
3154 :type '(repeat
3155 (list
3156 (string :tag "Marker character")
3157 (choice
3158 (face :tag "Font-lock-face")
3159 (plist :tag "Face property list"))
3160 (string :tag "HTML start tag")
3161 (string :tag "HTML end tag")
3162 (option (const verbatim)))))
3164 (defvar org-protecting-blocks
3165 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3166 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3167 This is needed for font-lock setup.")
3169 ;;; Miscellaneous options
3171 (defgroup org-completion nil
3172 "Completion in Org-mode."
3173 :tag "Org Completion"
3174 :group 'org)
3176 (defcustom org-completion-use-ido nil
3177 "Non-nil means use ido completion wherever possible.
3178 Note that `ido-mode' must be active for this variable to be relevant.
3179 If you decide to turn this variable on, you might well want to turn off
3180 `org-outline-path-complete-in-steps'.
3181 See also `org-completion-use-iswitchb'."
3182 :group 'org-completion
3183 :type 'boolean)
3185 (defcustom org-completion-use-iswitchb nil
3186 "Non-nil means use iswitchb completion wherever possible.
3187 Note that `iswitchb-mode' must be active for this variable to be relevant.
3188 If you decide to turn this variable on, you might well want to turn off
3189 `org-outline-path-complete-in-steps'.
3190 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3191 :group 'org-completion
3192 :type 'boolean)
3194 (defcustom org-completion-fallback-command 'hippie-expand
3195 "The expansion command called by \\[org-complete] in normal context.
3196 Normal means no org-mode-specific context."
3197 :group 'org-completion
3198 :type 'function)
3200 ;;; Functions and variables from their packages
3201 ;; Declared here to avoid compiler warnings
3203 ;; XEmacs only
3204 (defvar outline-mode-menu-heading)
3205 (defvar outline-mode-menu-show)
3206 (defvar outline-mode-menu-hide)
3207 (defvar zmacs-regions) ; XEmacs regions
3209 ;; Emacs only
3210 (defvar mark-active)
3212 ;; Various packages
3213 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3214 (declare-function calendar-forward-day "cal-move" (arg))
3215 (declare-function calendar-goto-date "cal-move" (date))
3216 (declare-function calendar-goto-today "cal-move" ())
3217 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3218 (defvar calc-embedded-close-formula)
3219 (defvar calc-embedded-open-formula)
3220 (declare-function cdlatex-tab "ext:cdlatex" ())
3221 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3222 (defvar font-lock-unfontify-region-function)
3223 (declare-function iswitchb-read-buffer "iswitchb"
3224 (prompt &optional default require-match start matches-set))
3225 (defvar iswitchb-temp-buflist)
3226 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3227 (defvar org-agenda-tags-todo-honor-ignore-options)
3228 (declare-function org-agenda-skip "org-agenda" ())
3229 (declare-function
3230 org-format-agenda-item "org-agenda"
3231 (extra txt &optional category tags dotime noprefix remove-re habitp))
3232 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3233 (declare-function org-agenda-change-all-lines "org-agenda"
3234 (newhead hdmarker &optional fixface just-this))
3235 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3236 (declare-function org-agenda-maybe-redo "org-agenda" ())
3237 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3238 (beg end))
3239 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3240 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3241 "org-agenda" (&optional end))
3242 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3243 (declare-function org-indent-mode "org-indent" (&optional arg))
3244 (declare-function parse-time-string "parse-time" (string))
3245 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3246 (defvar remember-data-file)
3247 (defvar texmathp-why)
3248 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3249 (declare-function table--at-cell-p "table" (position &optional object at-column))
3251 (defvar w3m-current-url)
3252 (defvar w3m-current-title)
3254 (defvar org-latex-regexps)
3256 ;;; Autoload and prepare some org modules
3258 ;; Some table stuff that needs to be defined here, because it is used
3259 ;; by the functions setting up org-mode or checking for table context.
3261 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3262 "Detects an org-type or table-type table.")
3263 (defconst org-table-line-regexp "^[ \t]*|"
3264 "Detects an org-type table line.")
3265 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3266 "Detects an org-type table line.")
3267 (defconst org-table-hline-regexp "^[ \t]*|-"
3268 "Detects an org-type table hline.")
3269 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3270 "Detects a table-type table hline.")
3271 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3272 "Searching from within a table (any type) this finds the first line
3273 outside the table.")
3275 ;; Autoload the functions in org-table.el that are needed by functions here.
3277 (eval-and-compile
3278 (org-autoload "org-table"
3279 '(org-table-align org-table-begin org-table-blank-field
3280 org-table-convert org-table-convert-region org-table-copy-down
3281 org-table-copy-region org-table-create
3282 org-table-create-or-convert-from-region
3283 org-table-create-with-table.el org-table-current-dline
3284 org-table-cut-region org-table-delete-column org-table-edit-field
3285 org-table-edit-formulas org-table-end org-table-eval-formula
3286 org-table-export org-table-field-info
3287 org-table-get-stored-formulas org-table-goto-column
3288 org-table-hline-and-move org-table-import org-table-insert-column
3289 org-table-insert-hline org-table-insert-row org-table-iterate
3290 org-table-justify-field-maybe org-table-kill-row
3291 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3292 org-table-move-column org-table-move-column-left
3293 org-table-move-column-right org-table-move-row
3294 org-table-move-row-down org-table-move-row-up
3295 org-table-next-field org-table-next-row org-table-paste-rectangle
3296 org-table-previous-field org-table-recalculate
3297 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3298 org-table-toggle-coordinate-overlays
3299 org-table-toggle-formula-debugger org-table-wrap-region
3300 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3302 (defun org-at-table-p (&optional table-type)
3303 "Return t if the cursor is inside an org-type table.
3304 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3305 (if org-enable-table-editor
3306 (save-excursion
3307 (beginning-of-line 1)
3308 (looking-at (if table-type org-table-any-line-regexp
3309 org-table-line-regexp)))
3310 nil))
3311 (defsubst org-table-p () (org-at-table-p))
3313 (defun org-at-table.el-p ()
3314 "Return t if and only if we are at a table.el table."
3315 (and (org-at-table-p 'any)
3316 (save-excursion
3317 (goto-char (org-table-begin 'any))
3318 (looking-at org-table1-hline-regexp))))
3319 (defun org-table-recognize-table.el ()
3320 "If there is a table.el table nearby, recognize it and move into it."
3321 (if org-table-tab-recognizes-table.el
3322 (if (org-at-table.el-p)
3323 (progn
3324 (beginning-of-line 1)
3325 (if (looking-at org-table-dataline-regexp)
3327 (if (looking-at org-table1-hline-regexp)
3328 (progn
3329 (beginning-of-line 2)
3330 (if (looking-at org-table-any-border-regexp)
3331 (beginning-of-line -1)))))
3332 (if (re-search-forward "|" (org-table-end t) t)
3333 (progn
3334 (require 'table)
3335 (if (table--at-cell-p (point))
3337 (message "recognizing table.el table...")
3338 (table-recognize-table)
3339 (message "recognizing table.el table...done")))
3340 (error "This should not happen..."))
3342 nil)
3343 nil))
3345 (defun org-at-table-hline-p ()
3346 "Return t if the cursor is inside a hline in a table."
3347 (if org-enable-table-editor
3348 (save-excursion
3349 (beginning-of-line 1)
3350 (looking-at org-table-hline-regexp))
3351 nil))
3353 (defvar org-table-clean-did-remove-column nil)
3355 (defun org-table-map-tables (function)
3356 "Apply FUNCTION to the start of all tables in the buffer."
3357 (save-excursion
3358 (save-restriction
3359 (widen)
3360 (goto-char (point-min))
3361 (while (re-search-forward org-table-any-line-regexp nil t)
3362 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3363 (beginning-of-line 1)
3364 (when (looking-at org-table-line-regexp)
3365 (save-excursion (funcall function))
3366 (or (looking-at org-table-line-regexp)
3367 (forward-char 1)))
3368 (re-search-forward org-table-any-border-regexp nil 1))))
3369 (message "Mapping tables: done"))
3371 ;; Declare and autoload functions from org-exp.el & Co
3373 (declare-function org-default-export-plist "org-exp")
3374 (declare-function org-infile-export-plist "org-exp")
3375 (declare-function org-get-current-options "org-exp")
3376 (eval-and-compile
3377 (org-autoload "org-exp"
3378 '(org-export org-export-visible
3379 org-insert-export-options-template
3380 org-table-clean-before-export))
3381 (org-autoload "org-ascii"
3382 '(org-export-as-ascii org-export-ascii-preprocess
3383 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3384 org-export-region-as-ascii))
3385 (org-autoload "org-latex"
3386 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3387 org-replace-region-by-latex org-export-region-as-latex
3388 org-export-as-latex org-export-as-pdf
3389 org-export-as-pdf-and-open))
3390 (org-autoload "org-html"
3391 '(org-export-as-html-and-open
3392 org-export-as-html-batch org-export-as-html-to-buffer
3393 org-replace-region-by-html org-export-region-as-html
3394 org-export-as-html))
3395 (org-autoload "org-docbook"
3396 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3397 org-replace-region-by-docbook org-export-region-as-docbook
3398 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3399 org-export-as-docbook))
3400 (org-autoload "org-icalendar"
3401 '(org-export-icalendar-this-file
3402 org-export-icalendar-all-agenda-files
3403 org-export-icalendar-combine-agenda-files))
3404 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3405 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3407 ;; Declare and autoload functions from org-agenda.el
3409 (eval-and-compile
3410 (org-autoload "org-agenda"
3411 '(org-agenda org-agenda-list org-search-view
3412 org-todo-list org-tags-view org-agenda-list-stuck-projects
3413 org-diary org-agenda-to-appt
3414 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3416 ;; Autoload org-remember
3418 (eval-and-compile
3419 (org-autoload "org-remember"
3420 '(org-remember-insinuate org-remember-annotation
3421 org-remember-apply-template org-remember org-remember-handler)))
3423 ;; Autoload org-clock.el
3426 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3427 (beg end))
3428 (declare-function org-clock-update-mode-line "org-clock" ())
3429 (declare-function org-resolve-clocks "org-clock"
3430 (&optional also-non-dangling-p prompt last-valid))
3431 (defvar org-clock-start-time)
3432 (defvar org-clock-marker (make-marker)
3433 "Marker recording the last clock-in.")
3434 (defvar org-clock-hd-marker (make-marker)
3435 "Marker recording the last clock-in, but the headline position.")
3436 (defvar org-clock-heading ""
3437 "The heading of the current clock entry.")
3438 (defun org-clock-is-active ()
3439 "Return non-nil if clock is currently running.
3440 The return value is actually the clock marker."
3441 (marker-buffer org-clock-marker))
3443 (eval-and-compile
3444 (org-autoload
3445 "org-clock"
3446 '(org-clock-in org-clock-out org-clock-cancel
3447 org-clock-goto org-clock-sum org-clock-display
3448 org-clock-remove-overlays org-clock-report
3449 org-clocktable-shift org-dblock-write:clocktable
3450 org-get-clocktable org-resolve-clocks)))
3452 (defun org-clock-update-time-maybe ()
3453 "If this is a CLOCK line, update it and return t.
3454 Otherwise, return nil."
3455 (interactive)
3456 (save-excursion
3457 (beginning-of-line 1)
3458 (skip-chars-forward " \t")
3459 (when (looking-at org-clock-string)
3460 (let ((re (concat "[ \t]*" org-clock-string
3461 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3462 "\\([ \t]*=>.*\\)?\\)?"))
3463 ts te h m s neg)
3464 (cond
3465 ((not (looking-at re))
3466 nil)
3467 ((not (match-end 2))
3468 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3469 (> org-clock-marker (point))
3470 (<= org-clock-marker (point-at-eol)))
3471 ;; The clock is running here
3472 (setq org-clock-start-time
3473 (apply 'encode-time
3474 (org-parse-time-string (match-string 1))))
3475 (org-clock-update-mode-line)))
3477 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3478 (end-of-line 1)
3479 (setq ts (match-string 1)
3480 te (match-string 3))
3481 (setq s (- (org-float-time
3482 (apply 'encode-time (org-parse-time-string te)))
3483 (org-float-time
3484 (apply 'encode-time (org-parse-time-string ts))))
3485 neg (< s 0)
3486 s (abs s)
3487 h (floor (/ s 3600))
3488 s (- s (* 3600 h))
3489 m (floor (/ s 60))
3490 s (- s (* 60 s)))
3491 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3492 t))))))
3494 (defun org-check-running-clock ()
3495 "Check if the current buffer contains the running clock.
3496 If yes, offer to stop it and to save the buffer with the changes."
3497 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3498 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3499 (buffer-name))))
3500 (org-clock-out)
3501 (when (y-or-n-p "Save changed buffer?")
3502 (save-buffer))))
3504 (defun org-clocktable-try-shift (dir n)
3505 "Check if this line starts a clock table, if yes, shift the time block."
3506 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3507 (org-clocktable-shift dir n)))
3509 ;; Autoload org-timer.el
3511 (eval-and-compile
3512 (org-autoload
3513 "org-timer"
3514 '(org-timer-start org-timer org-timer-item
3515 org-timer-change-times-in-region
3516 org-timer-set-timer
3517 org-timer-reset-timers
3518 org-timer-show-remaining-time)))
3520 ;; Autoload org-feed.el
3522 (eval-and-compile
3523 (org-autoload
3524 "org-feed"
3525 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3528 ;; Autoload org-indent.el
3530 ;; Define the variable already here, to make sure we have it.
3531 (defvar org-indent-mode nil
3532 "Non-nil if Org-Indent mode is enabled.
3533 Use the command `org-indent-mode' to change this variable.")
3535 (eval-and-compile
3536 (org-autoload
3537 "org-indent"
3538 '(org-indent-mode)))
3540 ;; Autoload org-mobile.el
3542 (eval-and-compile
3543 (org-autoload
3544 "org-mobile"
3545 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3547 ;; Autoload archiving code
3548 ;; The stuff that is needed for cycling and tags has to be defined here.
3550 (defgroup org-archive nil
3551 "Options concerning archiving in Org-mode."
3552 :tag "Org Archive"
3553 :group 'org-structure)
3555 (defcustom org-archive-location "%s_archive::"
3556 "The location where subtrees should be archived.
3558 The value of this variable is a string, consisting of two parts,
3559 separated by a double-colon. The first part is a filename and
3560 the second part is a headline.
3562 When the filename is omitted, archiving happens in the same file.
3563 %s in the filename will be replaced by the current file
3564 name (without the directory part). Archiving to a different file
3565 is useful to keep archived entries from contributing to the
3566 Org-mode Agenda.
3568 The archived entries will be filed as subtrees of the specified
3569 headline. When the headline is omitted, the subtrees are simply
3570 filed away at the end of the file, as top-level entries. Also in
3571 the heading you can use %s to represent the file name, this can be
3572 useful when using the same archive for a number of different files.
3574 Here are a few examples:
3575 \"%s_archive::\"
3576 If the current file is Projects.org, archive in file
3577 Projects.org_archive, as top-level trees. This is the default.
3579 \"::* Archived Tasks\"
3580 Archive in the current file, under the top-level headline
3581 \"* Archived Tasks\".
3583 \"~/org/archive.org::\"
3584 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3586 \"~/org/archive.org::From %s\"
3587 Archive in file ~/org/archive.org (absolute path), under headlines
3588 \"From FILENAME\" where file name is the current file name.
3590 \"basement::** Finished Tasks\"
3591 Archive in file ./basement (relative path), as level 3 trees
3592 below the level 2 heading \"** Finished Tasks\".
3594 You may set this option on a per-file basis by adding to the buffer a
3595 line like
3597 #+ARCHIVE: basement::** Finished Tasks
3599 You may also define it locally for a subtree by setting an ARCHIVE property
3600 in the entry. If such a property is found in an entry, or anywhere up
3601 the hierarchy, it will be used."
3602 :group 'org-archive
3603 :type 'string)
3605 (defcustom org-archive-tag "ARCHIVE"
3606 "The tag that marks a subtree as archived.
3607 An archived subtree does not open during visibility cycling, and does
3608 not contribute to the agenda listings.
3609 After changing this, font-lock must be restarted in the relevant buffers to
3610 get the proper fontification."
3611 :group 'org-archive
3612 :group 'org-keywords
3613 :type 'string)
3615 (defcustom org-agenda-skip-archived-trees t
3616 "Non-nil means the agenda will skip any items located in archived trees.
3617 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3618 variable is no longer recommended, you should leave it at the value t.
3619 Instead, use the key `v' to cycle the archives-mode in the agenda."
3620 :group 'org-archive
3621 :group 'org-agenda-skip
3622 :type 'boolean)
3624 (defcustom org-columns-skip-archived-trees t
3625 "Non-nil means ignore archived trees when creating column view."
3626 :group 'org-archive
3627 :group 'org-properties
3628 :type 'boolean)
3630 (defcustom org-cycle-open-archived-trees nil
3631 "Non-nil means `org-cycle' will open archived trees.
3632 An archived tree is a tree marked with the tag ARCHIVE.
3633 When nil, archived trees will stay folded. You can still open them with
3634 normal outline commands like `show-all', but not with the cycling commands."
3635 :group 'org-archive
3636 :group 'org-cycle
3637 :type 'boolean)
3639 (defcustom org-sparse-tree-open-archived-trees nil
3640 "Non-nil means sparse tree construction shows matches in archived trees.
3641 When nil, matches in these trees are highlighted, but the trees are kept in
3642 collapsed state."
3643 :group 'org-archive
3644 :group 'org-sparse-trees
3645 :type 'boolean)
3647 (defun org-cycle-hide-archived-subtrees (state)
3648 "Re-hide all archived subtrees after a visibility state change."
3649 (when (and (not org-cycle-open-archived-trees)
3650 (not (memq state '(overview folded))))
3651 (save-excursion
3652 (let* ((globalp (memq state '(contents all)))
3653 (beg (if globalp (point-min) (point)))
3654 (end (if globalp (point-max) (org-end-of-subtree t))))
3655 (org-hide-archived-subtrees beg end)
3656 (goto-char beg)
3657 (if (looking-at (concat ".*:" org-archive-tag ":"))
3658 (message "%s" (substitute-command-keys
3659 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3661 (defun org-force-cycle-archived ()
3662 "Cycle subtree even if it is archived."
3663 (interactive)
3664 (setq this-command 'org-cycle)
3665 (let ((org-cycle-open-archived-trees t))
3666 (call-interactively 'org-cycle)))
3668 (defun org-hide-archived-subtrees (beg end)
3669 "Re-hide all archived subtrees after a visibility state change."
3670 (save-excursion
3671 (let* ((re (concat ":" org-archive-tag ":")))
3672 (goto-char beg)
3673 (while (re-search-forward re end t)
3674 (when (org-on-heading-p)
3675 (org-flag-subtree t)
3676 (org-end-of-subtree t))))))
3678 (defun org-flag-subtree (flag)
3679 (save-excursion
3680 (org-back-to-heading t)
3681 (outline-end-of-heading)
3682 (outline-flag-region (point)
3683 (progn (org-end-of-subtree t) (point))
3684 flag)))
3686 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3688 (eval-and-compile
3689 (org-autoload "org-archive"
3690 '(org-add-archive-files org-archive-subtree
3691 org-archive-to-archive-sibling org-toggle-archive-tag
3692 org-archive-subtree-default
3693 org-archive-subtree-default-with-confirmation)))
3695 ;; Autoload Column View Code
3697 (declare-function org-columns-number-to-string "org-colview")
3698 (declare-function org-columns-get-format-and-top-level "org-colview")
3699 (declare-function org-columns-compute "org-colview")
3701 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3702 '(org-columns-number-to-string org-columns-get-format-and-top-level
3703 org-columns-compute org-agenda-columns org-columns-remove-overlays
3704 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3706 ;; Autoload ID code
3708 (declare-function org-id-store-link "org-id")
3709 (declare-function org-id-locations-load "org-id")
3710 (declare-function org-id-locations-save "org-id")
3711 (defvar org-id-track-globally)
3712 (org-autoload "org-id"
3713 '(org-id-get-create org-id-new org-id-copy org-id-get
3714 org-id-get-with-outline-path-completion
3715 org-id-get-with-outline-drilling
3716 org-id-goto org-id-find org-id-store-link))
3718 ;; Autoload Plotting Code
3720 (org-autoload "org-plot"
3721 '(org-plot/gnuplot))
3723 ;;; Variables for pre-computed regular expressions, all buffer local
3725 (defvar org-drawer-regexp nil
3726 "Matches first line of a hidden block.")
3727 (make-variable-buffer-local 'org-drawer-regexp)
3728 (defvar org-todo-regexp nil
3729 "Matches any of the TODO state keywords.")
3730 (make-variable-buffer-local 'org-todo-regexp)
3731 (defvar org-not-done-regexp nil
3732 "Matches any of the TODO state keywords except the last one.")
3733 (make-variable-buffer-local 'org-not-done-regexp)
3734 (defvar org-not-done-heading-regexp nil
3735 "Matches a TODO headline that is not done.")
3736 (make-variable-buffer-local 'org-not-done-regexp)
3737 (defvar org-todo-line-regexp nil
3738 "Matches a headline and puts TODO state into group 2 if present.")
3739 (make-variable-buffer-local 'org-todo-line-regexp)
3740 (defvar org-complex-heading-regexp nil
3741 "Matches a headline and puts everything into groups:
3742 group 1: the stars
3743 group 2: The todo keyword, maybe
3744 group 3: Priority cookie
3745 group 4: True headline
3746 group 5: Tags")
3747 (make-variable-buffer-local 'org-complex-heading-regexp)
3748 (defvar org-complex-heading-regexp-format nil)
3749 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3750 (defvar org-todo-line-tags-regexp nil
3751 "Matches a headline and puts TODO state into group 2 if present.
3752 Also put tags into group 4 if tags are present.")
3753 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3754 (defvar org-nl-done-regexp nil
3755 "Matches newline followed by a headline with the DONE keyword.")
3756 (make-variable-buffer-local 'org-nl-done-regexp)
3757 (defvar org-looking-at-done-regexp nil
3758 "Matches the DONE keyword a point.")
3759 (make-variable-buffer-local 'org-looking-at-done-regexp)
3760 (defvar org-ds-keyword-length 12
3761 "Maximum length of the Deadline and SCHEDULED keywords.")
3762 (make-variable-buffer-local 'org-ds-keyword-length)
3763 (defvar org-deadline-regexp nil
3764 "Matches the DEADLINE keyword.")
3765 (make-variable-buffer-local 'org-deadline-regexp)
3766 (defvar org-deadline-time-regexp nil
3767 "Matches the DEADLINE keyword together with a time stamp.")
3768 (make-variable-buffer-local 'org-deadline-time-regexp)
3769 (defvar org-deadline-line-regexp nil
3770 "Matches the DEADLINE keyword and the rest of the line.")
3771 (make-variable-buffer-local 'org-deadline-line-regexp)
3772 (defvar org-scheduled-regexp nil
3773 "Matches the SCHEDULED keyword.")
3774 (make-variable-buffer-local 'org-scheduled-regexp)
3775 (defvar org-scheduled-time-regexp nil
3776 "Matches the SCHEDULED keyword together with a time stamp.")
3777 (make-variable-buffer-local 'org-scheduled-time-regexp)
3778 (defvar org-closed-time-regexp nil
3779 "Matches the CLOSED keyword together with a time stamp.")
3780 (make-variable-buffer-local 'org-closed-time-regexp)
3782 (defvar org-keyword-time-regexp nil
3783 "Matches any of the 4 keywords, together with the time stamp.")
3784 (make-variable-buffer-local 'org-keyword-time-regexp)
3785 (defvar org-keyword-time-not-clock-regexp nil
3786 "Matches any of the 3 keywords, together with the time stamp.")
3787 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3788 (defvar org-maybe-keyword-time-regexp nil
3789 "Matches a timestamp, possibly preceeded by a keyword.")
3790 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3791 (defvar org-planning-or-clock-line-re nil
3792 "Matches a line with planning or clock info.")
3793 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3794 (defvar org-all-time-keywords nil
3795 "List of time keywords.")
3796 (make-variable-buffer-local 'org-all-time-keywords)
3798 (defconst org-plain-time-of-day-regexp
3799 (concat
3800 "\\(\\<[012]?[0-9]"
3801 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3802 "\\(--?"
3803 "\\(\\<[012]?[0-9]"
3804 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3805 "\\)?")
3806 "Regular expression to match a plain time or time range.
3807 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3808 groups carry important information:
3809 0 the full match
3810 1 the first time, range or not
3811 8 the second time, if it is a range.")
3813 (defconst org-plain-time-extension-regexp
3814 (concat
3815 "\\(\\<[012]?[0-9]"
3816 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3817 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3818 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3819 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3820 groups carry important information:
3821 0 the full match
3822 7 hours of duration
3823 9 minutes of duration")
3825 (defconst org-stamp-time-of-day-regexp
3826 (concat
3827 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3828 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3829 "\\(--?"
3830 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3831 "Regular expression to match a timestamp time or time range.
3832 After a match, the following groups carry important information:
3833 0 the full match
3834 1 date plus weekday, for back referencing to make sure both times are on the same day
3835 2 the first time, range or not
3836 4 the second time, if it is a range.")
3838 (defconst org-startup-options
3839 '(("fold" org-startup-folded t)
3840 ("overview" org-startup-folded t)
3841 ("nofold" org-startup-folded nil)
3842 ("showall" org-startup-folded nil)
3843 ("showeverything" org-startup-folded showeverything)
3844 ("content" org-startup-folded content)
3845 ("indent" org-startup-indented t)
3846 ("noindent" org-startup-indented nil)
3847 ("hidestars" org-hide-leading-stars t)
3848 ("showstars" org-hide-leading-stars nil)
3849 ("odd" org-odd-levels-only t)
3850 ("oddeven" org-odd-levels-only nil)
3851 ("align" org-startup-align-all-tables t)
3852 ("noalign" org-startup-align-all-tables nil)
3853 ("customtime" org-display-custom-times t)
3854 ("logdone" org-log-done time)
3855 ("lognotedone" org-log-done note)
3856 ("nologdone" org-log-done nil)
3857 ("lognoteclock-out" org-log-note-clock-out t)
3858 ("nolognoteclock-out" org-log-note-clock-out nil)
3859 ("logrepeat" org-log-repeat state)
3860 ("lognoterepeat" org-log-repeat note)
3861 ("nologrepeat" org-log-repeat nil)
3862 ("logreschedule" org-log-reschedule time)
3863 ("lognotereschedule" org-log-reschedule note)
3864 ("nologreschedule" org-log-reschedule nil)
3865 ("logredeadline" org-log-redeadline time)
3866 ("lognoteredeadline" org-log-redeadline note)
3867 ("nologredeadline" org-log-redeadline nil)
3868 ("logrefile" org-log-refile time)
3869 ("lognoterefile" org-log-refile note)
3870 ("nologrefile" org-log-refile nil)
3871 ("fninline" org-footnote-define-inline t)
3872 ("nofninline" org-footnote-define-inline nil)
3873 ("fnlocal" org-footnote-section nil)
3874 ("fnauto" org-footnote-auto-label t)
3875 ("fnprompt" org-footnote-auto-label nil)
3876 ("fnconfirm" org-footnote-auto-label confirm)
3877 ("fnplain" org-footnote-auto-label plain)
3878 ("fnadjust" org-footnote-auto-adjust t)
3879 ("nofnadjust" org-footnote-auto-adjust nil)
3880 ("constcgs" constants-unit-system cgs)
3881 ("constSI" constants-unit-system SI)
3882 ("noptag" org-tag-persistent-alist nil)
3883 ("hideblocks" org-hide-block-startup t)
3884 ("nohideblocks" org-hide-block-startup nil)
3885 ("beamer" org-startup-with-beamer-mode t))
3886 "Variable associated with STARTUP options for org-mode.
3887 Each element is a list of three items: The startup options as written
3888 in the #+STARTUP line, the corresponding variable, and the value to
3889 set this variable to if the option is found. An optional forth element PUSH
3890 means to push this value onto the list in the variable.")
3892 (defun org-set-regexps-and-options ()
3893 "Precompute regular expressions for current buffer."
3894 (when (org-mode-p)
3895 (org-set-local 'org-todo-kwd-alist nil)
3896 (org-set-local 'org-todo-key-alist nil)
3897 (org-set-local 'org-todo-key-trigger nil)
3898 (org-set-local 'org-todo-keywords-1 nil)
3899 (org-set-local 'org-done-keywords nil)
3900 (org-set-local 'org-todo-heads nil)
3901 (org-set-local 'org-todo-sets nil)
3902 (org-set-local 'org-todo-log-states nil)
3903 (org-set-local 'org-file-properties nil)
3904 (org-set-local 'org-file-tags nil)
3905 (let ((re (org-make-options-regexp
3906 '("CATEGORY" "TODO" "COLUMNS"
3907 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3908 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS")
3909 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3910 (splitre "[ \t]+")
3911 kwds kws0 kwsa key log value cat arch tags const links hw dws
3912 tail sep kws1 prio props ftags drawers beamer-p
3913 ext-setup-or-nil setup-contents (start 0))
3914 (save-excursion
3915 (save-restriction
3916 (widen)
3917 (goto-char (point-min))
3918 (while (or (and ext-setup-or-nil
3919 (string-match re ext-setup-or-nil start)
3920 (setq start (match-end 0)))
3921 (and (setq ext-setup-or-nil nil start 0)
3922 (re-search-forward re nil t)))
3923 (setq key (upcase (match-string 1 ext-setup-or-nil))
3924 value (org-match-string-no-properties 2 ext-setup-or-nil))
3925 (cond
3926 ((equal key "CATEGORY")
3927 (if (string-match "[ \t]+$" value)
3928 (setq value (replace-match "" t t value)))
3929 (setq cat value))
3930 ((member key '("SEQ_TODO" "TODO"))
3931 (push (cons 'sequence (org-split-string value splitre)) kwds))
3932 ((equal key "TYP_TODO")
3933 (push (cons 'type (org-split-string value splitre)) kwds))
3934 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3935 ;; general TODO-like setup
3936 (push (cons (intern (downcase (match-string 1 key)))
3937 (org-split-string value splitre)) kwds))
3938 ((equal key "TAGS")
3939 (setq tags (append tags (if tags '("\\n") nil)
3940 (org-split-string value splitre))))
3941 ((equal key "COLUMNS")
3942 (org-set-local 'org-columns-default-format value))
3943 ((equal key "LINK")
3944 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3945 (push (cons (match-string 1 value)
3946 (org-trim (match-string 2 value)))
3947 links)))
3948 ((equal key "PRIORITIES")
3949 (setq prio (org-split-string value " +")))
3950 ((equal key "PROPERTY")
3951 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3952 (push (cons (match-string 1 value) (match-string 2 value))
3953 props)))
3954 ((equal key "FILETAGS")
3955 (when (string-match "\\S-" value)
3956 (setq ftags
3957 (append
3958 ftags
3959 (apply 'append
3960 (mapcar (lambda (x) (org-split-string x ":"))
3961 (org-split-string value)))))))
3962 ((equal key "DRAWERS")
3963 (setq drawers (org-split-string value splitre)))
3964 ((equal key "CONSTANTS")
3965 (setq const (append const (org-split-string value splitre))))
3966 ((equal key "STARTUP")
3967 (let ((opts (org-split-string value splitre))
3968 l var val)
3969 (while (setq l (pop opts))
3970 (when (setq l (assoc l org-startup-options))
3971 (setq var (nth 1 l) val (nth 2 l))
3972 (if (not (nth 3 l))
3973 (set (make-local-variable var) val)
3974 (if (not (listp (symbol-value var)))
3975 (set (make-local-variable var) nil))
3976 (set (make-local-variable var) (symbol-value var))
3977 (add-to-list var val))))))
3978 ((equal key "ARCHIVE")
3979 (string-match " *$" value)
3980 (setq arch (replace-match "" t t value))
3981 (remove-text-properties 0 (length arch)
3982 '(face t fontified t) arch))
3983 ((equal key "LATEX_CLASS")
3984 (setq beamer-p (equal value "beamer")))
3985 ((equal key "SETUPFILE")
3986 (setq setup-contents (org-file-contents
3987 (expand-file-name
3988 (org-remove-double-quotes value))
3989 'noerror))
3990 (if (not ext-setup-or-nil)
3991 (setq ext-setup-or-nil setup-contents start 0)
3992 (setq ext-setup-or-nil
3993 (concat (substring ext-setup-or-nil 0 start)
3994 "\n" setup-contents "\n"
3995 (substring ext-setup-or-nil start)))))
3996 ))))
3997 (when cat
3998 (org-set-local 'org-category (intern cat))
3999 (push (cons "CATEGORY" cat) props))
4000 (when prio
4001 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4002 (setq prio (mapcar 'string-to-char prio))
4003 (org-set-local 'org-highest-priority (nth 0 prio))
4004 (org-set-local 'org-lowest-priority (nth 1 prio))
4005 (org-set-local 'org-default-priority (nth 2 prio)))
4006 (and props (org-set-local 'org-file-properties (nreverse props)))
4007 (and ftags (org-set-local 'org-file-tags
4008 (mapcar 'org-add-prop-inherited ftags)))
4009 (and drawers (org-set-local 'org-drawers drawers))
4010 (and arch (org-set-local 'org-archive-location arch))
4011 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4012 ;; Process the TODO keywords
4013 (unless kwds
4014 ;; Use the global values as if they had been given locally.
4015 (setq kwds (default-value 'org-todo-keywords))
4016 (if (stringp (car kwds))
4017 (setq kwds (list (cons org-todo-interpretation
4018 (default-value 'org-todo-keywords)))))
4019 (setq kwds (reverse kwds)))
4020 (setq kwds (nreverse kwds))
4021 (let (inter kws kw)
4022 (while (setq kws (pop kwds))
4023 (let ((kws (or
4024 (run-hook-with-args-until-success
4025 'org-todo-setup-filter-hook kws)
4026 kws)))
4027 (setq inter (pop kws) sep (member "|" kws)
4028 kws0 (delete "|" (copy-sequence kws))
4029 kwsa nil
4030 kws1 (mapcar
4031 (lambda (x)
4032 ;; 1 2
4033 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4034 (progn
4035 (setq kw (match-string 1 x)
4036 key (and (match-end 2) (match-string 2 x))
4037 log (org-extract-log-state-settings x))
4038 (push (cons kw (and key (string-to-char key))) kwsa)
4039 (and log (push log org-todo-log-states))
4041 (error "Invalid TODO keyword %s" x)))
4042 kws0)
4043 kwsa (if kwsa (append '((:startgroup))
4044 (nreverse kwsa)
4045 '((:endgroup))))
4046 hw (car kws1)
4047 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4048 tail (list inter hw (car dws) (org-last dws))))
4049 (add-to-list 'org-todo-heads hw 'append)
4050 (push kws1 org-todo-sets)
4051 (setq org-done-keywords (append org-done-keywords dws nil))
4052 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4053 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4054 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4055 (setq org-todo-sets (nreverse org-todo-sets)
4056 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4057 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4058 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4059 ;; Process the constants
4060 (when const
4061 (let (e cst)
4062 (while (setq e (pop const))
4063 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4064 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4065 (setq org-table-formula-constants-local cst)))
4067 ;; Process the tags.
4068 (when tags
4069 (let (e tgs)
4070 (while (setq e (pop tags))
4071 (cond
4072 ((equal e "{") (push '(:startgroup) tgs))
4073 ((equal e "}") (push '(:endgroup) tgs))
4074 ((equal e "\\n") (push '(:newline) tgs))
4075 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4076 (push (cons (match-string 1 e)
4077 (string-to-char (match-string 2 e)))
4078 tgs))
4079 (t (push (list e) tgs))))
4080 (org-set-local 'org-tag-alist nil)
4081 (while (setq e (pop tgs))
4082 (or (and (stringp (car e))
4083 (assoc (car e) org-tag-alist))
4084 (push e org-tag-alist)))))
4086 ;; Compute the regular expressions and other local variables
4087 (if (not org-done-keywords)
4088 (setq org-done-keywords (and org-todo-keywords-1
4089 (list (org-last org-todo-keywords-1)))))
4090 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4091 (length org-scheduled-string)
4092 (length org-clock-string)
4093 (length org-closed-string)))
4094 org-drawer-regexp
4095 (concat "^[ \t]*:\\("
4096 (mapconcat 'regexp-quote org-drawers "\\|")
4097 "\\):[ \t]*$")
4098 org-not-done-keywords
4099 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4100 org-todo-regexp
4101 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4102 "\\|") "\\)\\>")
4103 org-not-done-regexp
4104 (concat "\\<\\("
4105 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4106 "\\)\\>")
4107 org-not-done-heading-regexp
4108 (concat "^\\(\\*+\\)[ \t]+\\("
4109 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4110 "\\)\\>")
4111 org-todo-line-regexp
4112 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4113 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4114 "\\)\\>\\)?[ \t]*\\(.*\\)")
4115 org-complex-heading-regexp
4116 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4117 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4118 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4119 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4120 org-complex-heading-regexp-format
4121 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4122 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4123 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
4124 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4125 org-nl-done-regexp
4126 (concat "\n\\*+[ \t]+"
4127 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4128 "\\)" "\\>")
4129 org-todo-line-tags-regexp
4130 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4131 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4132 (org-re
4133 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4134 org-looking-at-done-regexp
4135 (concat "^" "\\(?:"
4136 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4137 "\\>")
4138 org-deadline-regexp (concat "\\<" org-deadline-string)
4139 org-deadline-time-regexp
4140 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4141 org-deadline-line-regexp
4142 (concat "\\<\\(" org-deadline-string "\\).*")
4143 org-scheduled-regexp
4144 (concat "\\<" org-scheduled-string)
4145 org-scheduled-time-regexp
4146 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4147 org-closed-time-regexp
4148 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4149 org-keyword-time-regexp
4150 (concat "\\<\\(" org-scheduled-string
4151 "\\|" org-deadline-string
4152 "\\|" org-closed-string
4153 "\\|" org-clock-string "\\)"
4154 " *[[<]\\([^]>]+\\)[]>]")
4155 org-keyword-time-not-clock-regexp
4156 (concat "\\<\\(" org-scheduled-string
4157 "\\|" org-deadline-string
4158 "\\|" org-closed-string
4159 "\\)"
4160 " *[[<]\\([^]>]+\\)[]>]")
4161 org-maybe-keyword-time-regexp
4162 (concat "\\(\\<\\(" org-scheduled-string
4163 "\\|" org-deadline-string
4164 "\\|" org-closed-string
4165 "\\|" org-clock-string "\\)\\)?"
4166 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4167 org-planning-or-clock-line-re
4168 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4169 "\\|" org-deadline-string
4170 "\\|" org-closed-string "\\|" org-clock-string
4171 "\\)\\>\\)")
4172 org-all-time-keywords
4173 (mapcar (lambda (w) (substring w 0 -1))
4174 (list org-scheduled-string org-deadline-string
4175 org-clock-string org-closed-string))
4177 (org-compute-latex-and-specials-regexp)
4178 (org-set-font-lock-defaults))))
4180 (defun org-file-contents (file &optional noerror)
4181 "Return the contents of FILE, as a string."
4182 (if (or (not file)
4183 (not (file-readable-p file)))
4184 (if noerror
4185 (progn
4186 (message "Cannot read file %s" file)
4187 (ding) (sit-for 2)
4189 (error "Cannot read file %s" file))
4190 (with-temp-buffer
4191 (insert-file-contents file)
4192 (buffer-string))))
4194 (defun org-extract-log-state-settings (x)
4195 "Extract the log state setting from a TODO keyword string.
4196 This will extract info from a string like \"WAIT(w@/!)\"."
4197 (let (kw key log1 log2)
4198 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4199 (setq kw (match-string 1 x)
4200 key (and (match-end 2) (match-string 2 x))
4201 log1 (and (match-end 3) (match-string 3 x))
4202 log2 (and (match-end 4) (match-string 4 x)))
4203 (and (or log1 log2)
4204 (list kw
4205 (and log1 (if (equal log1 "!") 'time 'note))
4206 (and log2 (if (equal log2 "!") 'time 'note)))))))
4208 (defun org-remove-keyword-keys (list)
4209 "Remove a pair of parenthesis at the end of each string in LIST."
4210 (mapcar (lambda (x)
4211 (if (string-match "(.*)$" x)
4212 (substring x 0 (match-beginning 0))
4214 list))
4216 (defun org-assign-fast-keys (alist)
4217 "Assign fast keys to a keyword-key alist.
4218 Respect keys that are already there."
4219 (let (new e (alt ?0))
4220 (while (setq e (pop alist))
4221 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4222 (cdr e)) ;; Key already assigned.
4223 (push e new)
4224 (let ((clist (string-to-list (downcase (car e))))
4225 (used (append new alist)))
4226 (when (= (car clist) ?@)
4227 (pop clist))
4228 (while (and clist (rassoc (car clist) used))
4229 (pop clist))
4230 (unless clist
4231 (while (rassoc alt used)
4232 (incf alt)))
4233 (push (cons (car e) (or (car clist) alt)) new))))
4234 (nreverse new)))
4236 ;;; Some variables used in various places
4238 (defvar org-window-configuration nil
4239 "Used in various places to store a window configuration.")
4240 (defvar org-selected-window nil
4241 "Used in various places to store a window configuration.")
4242 (defvar org-finish-function nil
4243 "Function to be called when `C-c C-c' is used.
4244 This is for getting out of special buffers like remember.")
4247 ;; FIXME: Occasionally check by commenting these, to make sure
4248 ;; no other functions uses these, forgetting to let-bind them.
4249 (defvar entry)
4250 (defvar last-state)
4251 (defvar date)
4253 ;; Defined somewhere in this file, but used before definition.
4254 (defvar org-entities) ;; defined in org-entities.el
4255 (defvar org-struct-menu)
4256 (defvar org-org-menu)
4257 (defvar org-tbl-menu)
4259 ;;;; Define the Org-mode
4261 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4262 (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."))
4265 ;; We use a before-change function to check if a table might need
4266 ;; an update.
4267 (defvar org-table-may-need-update t
4268 "Indicates that a table might need an update.
4269 This variable is set by `org-before-change-function'.
4270 `org-table-align' sets it back to nil.")
4271 (defun org-before-change-function (beg end)
4272 "Every change indicates that a table might need an update."
4273 (setq org-table-may-need-update t))
4274 (defvar org-mode-map)
4275 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4276 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4277 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4278 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4279 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4280 (defvar org-table-buffer-is-an nil)
4281 (defconst org-outline-regexp "\\*+ ")
4283 ;;;###autoload
4284 (define-derived-mode org-mode outline-mode "Org"
4285 "Outline-based notes management and organizer, alias
4286 \"Carsten's outline-mode for keeping track of everything.\"
4288 Org-mode develops organizational tasks around a NOTES file which
4289 contains information about projects as plain text. Org-mode is
4290 implemented on top of outline-mode, which is ideal to keep the content
4291 of large files well structured. It supports ToDo items, deadlines and
4292 time stamps, which magically appear in the diary listing of the Emacs
4293 calendar. Tables are easily created with a built-in table editor.
4294 Plain text URL-like links connect to websites, emails (VM), Usenet
4295 messages (Gnus), BBDB entries, and any files related to the project.
4296 For printing and sharing of notes, an Org-mode file (or a part of it)
4297 can be exported as a structured ASCII or HTML file.
4299 The following commands are available:
4301 \\{org-mode-map}"
4303 ;; Get rid of Outline menus, they are not needed
4304 ;; Need to do this here because define-derived-mode sets up
4305 ;; the keymap so late. Still, it is a waste to call this each time
4306 ;; we switch another buffer into org-mode.
4307 (if (featurep 'xemacs)
4308 (when (boundp 'outline-mode-menu-heading)
4309 ;; Assume this is Greg's port, it used easymenu
4310 (easy-menu-remove outline-mode-menu-heading)
4311 (easy-menu-remove outline-mode-menu-show)
4312 (easy-menu-remove outline-mode-menu-hide))
4313 (define-key org-mode-map [menu-bar headings] 'undefined)
4314 (define-key org-mode-map [menu-bar hide] 'undefined)
4315 (define-key org-mode-map [menu-bar show] 'undefined))
4317 (org-load-modules-maybe)
4318 (easy-menu-add org-org-menu)
4319 (easy-menu-add org-tbl-menu)
4320 (org-install-agenda-files-menu)
4321 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4322 (org-add-to-invisibility-spec '(org-cwidth))
4323 (org-add-to-invisibility-spec '(org-hide-block . t))
4324 (when (featurep 'xemacs)
4325 (org-set-local 'line-move-ignore-invisible t))
4326 (org-set-local 'outline-regexp org-outline-regexp)
4327 (org-set-local 'outline-level 'org-outline-level)
4328 (when (and org-ellipsis
4329 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4330 (fboundp 'make-glyph-code))
4331 (unless org-display-table
4332 (setq org-display-table (make-display-table)))
4333 (set-display-table-slot
4334 org-display-table 4
4335 (vconcat (mapcar
4336 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4337 org-ellipsis)))
4338 (if (stringp org-ellipsis) org-ellipsis "..."))))
4339 (setq buffer-display-table org-display-table))
4340 (org-set-regexps-and-options)
4341 (when (and org-tag-faces (not org-tags-special-faces-re))
4342 ;; tag faces set outside customize.... force initialization.
4343 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4344 ;; Calc embedded
4345 (org-set-local 'calc-embedded-open-mode "# ")
4346 (modify-syntax-entry ?# "<")
4347 (modify-syntax-entry ?@ "w")
4348 (if org-startup-truncated (setq truncate-lines t))
4349 (org-set-local 'font-lock-unfontify-region-function
4350 'org-unfontify-region)
4351 ;; Activate before-change-function
4352 (org-set-local 'org-table-may-need-update t)
4353 (org-add-hook 'before-change-functions 'org-before-change-function nil
4354 'local)
4355 ;; Check for running clock before killing a buffer
4356 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4357 ;; Paragraphs and auto-filling
4358 (org-set-autofill-regexps)
4359 (setq indent-line-function 'org-indent-line-function)
4360 (org-update-radio-target-regexp)
4361 ;; Make sure dependence stuff works reliably, even for users who set it
4362 ;; too late :-(
4363 (if org-enforce-todo-dependencies
4364 (add-hook 'org-blocker-hook
4365 'org-block-todo-from-children-or-siblings-or-parent)
4366 (remove-hook 'org-blocker-hook
4367 'org-block-todo-from-children-or-siblings-or-parent))
4368 (if org-enforce-todo-checkbox-dependencies
4369 (add-hook 'org-blocker-hook
4370 'org-block-todo-from-checkboxes)
4371 (remove-hook 'org-blocker-hook
4372 'org-block-todo-from-checkboxes))
4374 ;; Comment characters
4375 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4376 (org-set-local 'comment-padding " ")
4378 ;; Align options lines
4379 (org-set-local
4380 'align-mode-rules-list
4381 '((org-in-buffer-settings
4382 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4383 (modes . '(org-mode)))))
4385 ;; Imenu
4386 (org-set-local 'imenu-create-index-function
4387 'org-imenu-get-tree)
4389 ;; Make isearch reveal context
4390 (if (or (featurep 'xemacs)
4391 (not (boundp 'outline-isearch-open-invisible-function)))
4392 ;; Emacs 21 and XEmacs make use of the hook
4393 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4394 ;; Emacs 22 deals with this through a special variable
4395 (org-set-local 'outline-isearch-open-invisible-function
4396 (lambda (&rest ignore) (org-show-context 'isearch))))
4398 ;; Turn on org-beamer-mode?
4399 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4401 ;; If empty file that did not turn on org-mode automatically, make it to.
4402 (if (and org-insert-mode-line-in-empty-file
4403 (interactive-p)
4404 (= (point-min) (point-max)))
4405 (insert "# -*- mode: org -*-\n\n"))
4406 (unless org-inhibit-startup
4407 (when org-startup-align-all-tables
4408 (let ((bmp (buffer-modified-p)))
4409 (org-table-map-tables 'org-table-align)
4410 (set-buffer-modified-p bmp)))
4411 (when org-startup-indented
4412 (require 'org-indent)
4413 (org-indent-mode 1))
4414 (unless org-inhibit-startup-visibility-stuff
4415 (org-set-startup-visibility))))
4417 (when (fboundp 'abbrev-table-put)
4418 (abbrev-table-put org-mode-abbrev-table
4419 :parents (list text-mode-abbrev-table)))
4421 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4423 (defun org-current-time ()
4424 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4425 (if (> (car org-time-stamp-rounding-minutes) 1)
4426 (let ((r (car org-time-stamp-rounding-minutes))
4427 (time (decode-time)))
4428 (apply 'encode-time
4429 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4430 (nthcdr 2 time))))
4431 (current-time)))
4433 ;;;; Font-Lock stuff, including the activators
4435 (defvar org-mouse-map (make-sparse-keymap))
4436 (org-defkey org-mouse-map
4437 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4438 (org-defkey org-mouse-map
4439 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4440 (when org-mouse-1-follows-link
4441 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4442 (when org-tab-follows-link
4443 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4444 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4446 (require 'font-lock)
4448 (defconst org-non-link-chars "]\t\n\r<>")
4449 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4450 "shell" "elisp"))
4451 (defvar org-link-types-re nil
4452 "Matches a link that has a url-like prefix like \"http:\"")
4453 (defvar org-link-re-with-space nil
4454 "Matches a link with spaces, optional angular brackets around it.")
4455 (defvar org-link-re-with-space2 nil
4456 "Matches a link with spaces, optional angular brackets around it.")
4457 (defvar org-link-re-with-space3 nil
4458 "Matches a link with spaces, only for internal part in bracket links.")
4459 (defvar org-angle-link-re nil
4460 "Matches link with angular brackets, spaces are allowed.")
4461 (defvar org-plain-link-re nil
4462 "Matches plain link, without spaces.")
4463 (defvar org-bracket-link-regexp nil
4464 "Matches a link in double brackets.")
4465 (defvar org-bracket-link-analytic-regexp nil
4466 "Regular expression used to analyze links.
4467 Here is what the match groups contain after a match:
4468 1: http:
4469 2: http
4470 3: path
4471 4: [desc]
4472 5: desc")
4473 (defvar org-bracket-link-analytic-regexp++ nil
4474 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4475 (defvar org-any-link-re nil
4476 "Regular expression matching any link.")
4478 (defun org-make-link-regexps ()
4479 "Update the link regular expressions.
4480 This should be called after the variable `org-link-types' has changed."
4481 (setq org-link-types-re
4482 (concat
4483 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4484 org-link-re-with-space
4485 (concat
4486 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4487 "\\([^" org-non-link-chars " ]"
4488 "[^" org-non-link-chars "]*"
4489 "[^" org-non-link-chars " ]\\)>?")
4490 org-link-re-with-space2
4491 (concat
4492 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4493 "\\([^" org-non-link-chars " ]"
4494 "[^\t\n\r]*"
4495 "[^" org-non-link-chars " ]\\)>?")
4496 org-link-re-with-space3
4497 (concat
4498 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4499 "\\([^" org-non-link-chars " ]"
4500 "[^\t\n\r]*\\)")
4501 org-angle-link-re
4502 (concat
4503 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4504 "\\([^" org-non-link-chars " ]"
4505 "[^" org-non-link-chars "]*"
4506 "\\)>")
4507 org-plain-link-re
4508 (concat
4509 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4510 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4511 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4512 org-bracket-link-regexp
4513 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4514 org-bracket-link-analytic-regexp
4515 (concat
4516 "\\[\\["
4517 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4518 "\\([^]]+\\)"
4519 "\\]"
4520 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4521 "\\]")
4522 org-bracket-link-analytic-regexp++
4523 (concat
4524 "\\[\\["
4525 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4526 "\\([^]]+\\)"
4527 "\\]"
4528 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4529 "\\]")
4530 org-any-link-re
4531 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4532 org-angle-link-re "\\)\\|\\("
4533 org-plain-link-re "\\)")))
4535 (org-make-link-regexps)
4537 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4538 "Regular expression for fast time stamp matching.")
4539 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4540 "Regular expression for fast time stamp matching.")
4541 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4542 "Regular expression matching time strings for analysis.
4543 This one does not require the space after the date, so it can be used
4544 on a string that terminates immediately after the date.")
4545 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4546 "Regular expression matching time strings for analysis.")
4547 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4548 "Regular expression matching time stamps, with groups.")
4549 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4550 "Regular expression matching time stamps (also [..]), with groups.")
4551 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4552 "Regular expression matching a time stamp range.")
4553 (defconst org-tr-regexp-both
4554 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4555 "Regular expression matching a time stamp range.")
4556 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4557 org-ts-regexp "\\)?")
4558 "Regular expression matching a time stamp or time stamp range.")
4559 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4560 org-ts-regexp-both "\\)?")
4561 "Regular expression matching a time stamp or time stamp range.
4562 The time stamps may be either active or inactive.")
4564 (defvar org-emph-face nil)
4566 (defun org-do-emphasis-faces (limit)
4567 "Run through the buffer and add overlays to links."
4568 (let (rtn a)
4569 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4570 (if (not (= (char-after (match-beginning 3))
4571 (char-after (match-beginning 4))))
4572 (progn
4573 (setq rtn t)
4574 (setq a (assoc (match-string 3) org-emphasis-alist))
4575 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4576 'face
4577 (nth 1 a))
4578 (and (nth 4 a)
4579 (org-remove-flyspell-overlays-in
4580 (match-beginning 0) (match-end 0)))
4581 (add-text-properties (match-beginning 2) (match-end 2)
4582 '(font-lock-multiline t))
4583 (when org-hide-emphasis-markers
4584 (add-text-properties (match-end 4) (match-beginning 5)
4585 '(invisible org-link))
4586 (add-text-properties (match-beginning 3) (match-end 3)
4587 '(invisible org-link)))))
4588 (backward-char 1))
4589 rtn))
4591 (defun org-emphasize (&optional char)
4592 "Insert or change an emphasis, i.e. a font like bold or italic.
4593 If there is an active region, change that region to a new emphasis.
4594 If there is no region, just insert the marker characters and position
4595 the cursor between them.
4596 CHAR should be either the marker character, or the first character of the
4597 HTML tag associated with that emphasis. If CHAR is a space, the means
4598 to remove the emphasis of the selected region.
4599 If char is not given (for example in an interactive call) it
4600 will be prompted for."
4601 (interactive)
4602 (let ((eal org-emphasis-alist) e det
4603 (erc org-emphasis-regexp-components)
4604 (prompt "")
4605 (string "") beg end move tag c s)
4606 (if (org-region-active-p)
4607 (setq beg (region-beginning) end (region-end)
4608 string (buffer-substring beg end))
4609 (setq move t))
4611 (while (setq e (pop eal))
4612 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4613 c (aref tag 0))
4614 (push (cons c (string-to-char (car e))) det)
4615 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4616 (substring tag 1)))))
4617 (setq det (nreverse det))
4618 (unless char
4619 (message "%s" (concat "Emphasis marker or tag:" prompt))
4620 (setq char (read-char-exclusive)))
4621 (setq char (or (cdr (assoc char det)) char))
4622 (if (equal char ?\ )
4623 (setq s "" move nil)
4624 (unless (assoc (char-to-string char) org-emphasis-alist)
4625 (error "No such emphasis marker: \"%c\"" char))
4626 (setq s (char-to-string char)))
4627 (while (and (> (length string) 1)
4628 (equal (substring string 0 1) (substring string -1))
4629 (assoc (substring string 0 1) org-emphasis-alist))
4630 (setq string (substring string 1 -1)))
4631 (setq string (concat s string s))
4632 (if beg (delete-region beg end))
4633 (unless (or (bolp)
4634 (string-match (concat "[" (nth 0 erc) "\n]")
4635 (char-to-string (char-before (point)))))
4636 (insert " "))
4637 (unless (or (eobp)
4638 (string-match (concat "[" (nth 1 erc) "\n]")
4639 (char-to-string (char-after (point)))))
4640 (insert " ") (backward-char 1))
4641 (insert string)
4642 (and move (backward-char 1))))
4644 (defconst org-nonsticky-props
4645 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4647 (defsubst org-rear-nonsticky-at (pos)
4648 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4650 (defun org-activate-plain-links (limit)
4651 "Run through the buffer and add overlays to links."
4652 (catch 'exit
4653 (let (f)
4654 (if (re-search-forward org-plain-link-re limit t)
4655 (progn
4656 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4657 (setq f (get-text-property (match-beginning 0) 'face))
4658 (if (or (eq f 'org-tag)
4659 (and (listp f) (memq 'org-tag f)))
4661 (add-text-properties (match-beginning 0) (match-end 0)
4662 (list 'mouse-face 'highlight
4663 'face 'org-link
4664 'keymap org-mouse-map))
4665 (org-rear-nonsticky-at (match-end 0)))
4666 t)))))
4668 (defun org-activate-code (limit)
4669 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4670 (progn
4671 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4672 (remove-text-properties (match-beginning 0) (match-end 0)
4673 '(display t invisible t intangible t))
4674 t)))
4676 (defun org-fontify-meta-lines-and-blocks (limit)
4677 "Fontify #+ lines and blocks, in the correct ways."
4678 (let ((case-fold-search t))
4679 (if (re-search-forward
4680 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4681 limit t)
4682 (let ((beg (match-beginning 0))
4683 (beg1 (line-beginning-position 2))
4684 (dc1 (downcase (match-string 2)))
4685 (dc3 (downcase (match-string 3)))
4686 end end1 quoting block-type)
4687 (cond
4688 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4689 ;; a single line of backend-specific content
4690 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4691 (remove-text-properties (match-beginning 0) (match-end 0)
4692 '(display t invisible t intangible t))
4693 (add-text-properties (match-beginning 1) (match-end 3)
4694 '(font-lock-fontified t face org-meta-line))
4695 (add-text-properties (match-beginning 6) (match-end 6)
4696 '(font-lock-fontified t face org-block))
4698 ((and (match-end 4) (equal dc3 "begin"))
4699 ;; Truely a block
4700 (setq block-type (downcase (match-string 5))
4701 quoting (member block-type org-protecting-blocks))
4702 (when (re-search-forward
4703 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4704 nil t) ;; on purpose, we look further than LIMIT
4705 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4706 (when quoting
4707 (remove-text-properties beg end
4708 '(display t invisible t intangible t)))
4709 (add-text-properties
4710 beg end
4711 '(font-lock-fontified t font-lock-multiline t))
4712 (add-text-properties beg beg1 '(face org-meta-line))
4713 (add-text-properties end1 end '(face org-meta-line))
4714 (cond
4715 (quoting
4716 (add-text-properties beg1 end1 '(face org-block)))
4717 ((not org-fontify-quote-and-verse-blocks))
4718 ((string= block-type "quote")
4719 (add-text-properties beg1 end1 '(face org-quote)))
4720 ((string= block-type "verse")
4721 (add-text-properties beg1 end1 '(face org-verse))))
4723 ((member dc1 '("title:" "author:" "email:" "date:"))
4724 (add-text-properties
4725 beg (match-end 3)
4726 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
4727 '(font-lock-fontified t invisible t)
4728 '(font-lock-fontified t face org-document-info-keyword)))
4729 (add-text-properties
4730 (match-beginning 6) (match-end 6)
4731 (if (string-equal dc1 "title:")
4732 '(font-lock-fontified t face org-document-title)
4733 '(font-lock-fontified t face org-document-info))))
4734 ((not (member (char-after beg) '(?\ ?\t)))
4735 ;; just any other in-buffer setting, but not indented
4736 (add-text-properties
4737 beg (match-end 0)
4738 '(font-lock-fontified t face org-meta-line))
4740 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4741 "orgtbl:" "tblfm:" "tblname:"))
4742 (and (match-end 4) (equal dc3 "attr")))
4743 (add-text-properties
4744 beg (match-end 0)
4745 '(font-lock-fontified t face org-meta-line))
4747 ((member dc3 '(" " ""))
4748 (add-text-properties
4749 beg (match-end 0)
4750 '(font-lock-fontified t face font-lock-comment-face)))
4751 (t nil))))))
4753 (defun org-activate-angle-links (limit)
4754 "Run through the buffer and add overlays to links."
4755 (if (re-search-forward org-angle-link-re limit t)
4756 (progn
4757 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4758 (add-text-properties (match-beginning 0) (match-end 0)
4759 (list 'mouse-face 'highlight
4760 'keymap org-mouse-map))
4761 (org-rear-nonsticky-at (match-end 0))
4762 t)))
4764 (defun org-activate-footnote-links (limit)
4765 "Run through the buffer and add overlays to links."
4766 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4767 limit t)
4768 (progn
4769 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4770 (add-text-properties (match-beginning 2) (match-end 2)
4771 (list 'mouse-face 'highlight
4772 'keymap org-mouse-map
4773 'help-echo
4774 (if (= (point-at-bol) (match-beginning 2))
4775 "Footnote definition"
4776 "Footnote reference")
4778 (org-rear-nonsticky-at (match-end 2))
4779 t)))
4781 (defun org-activate-bracket-links (limit)
4782 "Run through the buffer and add overlays to bracketed links."
4783 (if (re-search-forward org-bracket-link-regexp limit t)
4784 (let* ((help (concat "LINK: "
4785 (org-match-string-no-properties 1)))
4786 ;; FIXME: above we should remove the escapes.
4787 ;; but that requires another match, protecting match data,
4788 ;; a lot of overhead for font-lock.
4789 (ip (org-maybe-intangible
4790 (list 'invisible 'org-link
4791 'keymap org-mouse-map 'mouse-face 'highlight
4792 'font-lock-multiline t 'help-echo help)))
4793 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4794 'font-lock-multiline t 'help-echo help)))
4795 ;; We need to remove the invisible property here. Table narrowing
4796 ;; may have made some of this invisible.
4797 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4798 (remove-text-properties (match-beginning 0) (match-end 0)
4799 '(invisible nil))
4800 (if (match-end 3)
4801 (progn
4802 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4803 (org-rear-nonsticky-at (match-beginning 3))
4804 (add-text-properties (match-beginning 3) (match-end 3) vp)
4805 (org-rear-nonsticky-at (match-end 3))
4806 (add-text-properties (match-end 3) (match-end 0) ip)
4807 (org-rear-nonsticky-at (match-end 0)))
4808 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4809 (org-rear-nonsticky-at (match-beginning 1))
4810 (add-text-properties (match-beginning 1) (match-end 1) vp)
4811 (org-rear-nonsticky-at (match-end 1))
4812 (add-text-properties (match-end 1) (match-end 0) ip)
4813 (org-rear-nonsticky-at (match-end 0)))
4814 t)))
4816 (defun org-activate-dates (limit)
4817 "Run through the buffer and add overlays to dates."
4818 (if (re-search-forward org-tsr-regexp-both limit t)
4819 (progn
4820 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4821 (add-text-properties (match-beginning 0) (match-end 0)
4822 (list 'mouse-face 'highlight
4823 'keymap org-mouse-map))
4824 (org-rear-nonsticky-at (match-end 0))
4825 (when org-display-custom-times
4826 (if (match-end 3)
4827 (org-display-custom-time (match-beginning 3) (match-end 3)))
4828 (org-display-custom-time (match-beginning 1) (match-end 1)))
4829 t)))
4831 (defvar org-target-link-regexp nil
4832 "Regular expression matching radio targets in plain text.")
4833 (make-variable-buffer-local 'org-target-link-regexp)
4834 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4835 "Regular expression matching a link target.")
4836 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4837 "Regular expression matching a radio target.")
4838 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4839 "Regular expression matching any target.")
4841 (defun org-activate-target-links (limit)
4842 "Run through the buffer and add overlays to target matches."
4843 (when org-target-link-regexp
4844 (let ((case-fold-search t))
4845 (if (re-search-forward org-target-link-regexp limit t)
4846 (progn
4847 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4848 (add-text-properties (match-beginning 0) (match-end 0)
4849 (list 'mouse-face 'highlight
4850 'keymap org-mouse-map
4851 'help-echo "Radio target link"
4852 'org-linked-text t))
4853 (org-rear-nonsticky-at (match-end 0))
4854 t)))))
4856 (defun org-update-radio-target-regexp ()
4857 "Find all radio targets in this file and update the regular expression."
4858 (interactive)
4859 (when (memq 'radio org-activate-links)
4860 (setq org-target-link-regexp
4861 (org-make-target-link-regexp (org-all-targets 'radio)))
4862 (org-restart-font-lock)))
4864 (defun org-hide-wide-columns (limit)
4865 (let (s e)
4866 (setq s (text-property-any (point) (or limit (point-max))
4867 'org-cwidth t))
4868 (when s
4869 (setq e (next-single-property-change s 'org-cwidth))
4870 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4871 (goto-char e)
4872 t)))
4874 (defvar org-latex-and-specials-regexp nil
4875 "Regular expression for highlighting export special stuff.")
4876 (defvar org-match-substring-regexp)
4877 (defvar org-match-substring-with-braces-regexp)
4879 ;; This should be with the exporter code, but we also use if for font-locking
4880 (defconst org-export-html-special-string-regexps
4881 '(("\\\\-" . "&shy;")
4882 ("---\\([^-]\\)" . "&mdash;\\1")
4883 ("--\\([^-]\\)" . "&ndash;\\1")
4884 ("\\.\\.\\." . "&hellip;"))
4885 "Regular expressions for special string conversion.")
4888 (defun org-compute-latex-and-specials-regexp ()
4889 "Compute regular expression for stuff treated specially by exporters."
4890 (if (not org-highlight-latex-fragments-and-specials)
4891 (org-set-local 'org-latex-and-specials-regexp nil)
4892 (require 'org-exp)
4893 (let*
4894 ((matchers (plist-get org-format-latex-options :matchers))
4895 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4896 org-latex-regexps)))
4897 (org-export-allow-BIND nil)
4898 (options (org-combine-plists (org-default-export-plist)
4899 (org-infile-export-plist)))
4900 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4901 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4902 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4903 (org-export-html-expand (plist-get options :expand-quoted-html))
4904 (org-export-with-special-strings (plist-get options :special-strings))
4905 (re-sub
4906 (cond
4907 ((equal org-export-with-sub-superscripts '{})
4908 (list org-match-substring-with-braces-regexp))
4909 (org-export-with-sub-superscripts
4910 (list org-match-substring-regexp))
4911 (t nil)))
4912 (re-latex
4913 (if org-export-with-LaTeX-fragments
4914 (mapcar (lambda (x) (nth 1 x)) latexs)))
4915 (re-macros
4916 (if org-export-with-TeX-macros
4917 (list (concat "\\\\"
4918 (regexp-opt
4919 (append (mapcar 'car (append org-entities-user
4920 org-entities))
4921 (if (boundp 'org-latex-entities)
4922 (mapcar (lambda (x)
4923 (or (car-safe x) x))
4924 org-latex-entities)
4925 nil))
4926 'words))) ; FIXME
4928 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4929 (re-special (if org-export-with-special-strings
4930 (mapcar (lambda (x) (car x))
4931 org-export-html-special-string-regexps)))
4932 (re-rest
4933 (delq nil
4934 (list
4935 (if org-export-html-expand "@<[^>\n]+>")
4936 ))))
4937 (org-set-local
4938 'org-latex-and-specials-regexp
4939 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4940 re-rest) "\\|")))))
4942 (defun org-do-latex-and-special-faces (limit)
4943 "Run through the buffer and add overlays to links."
4944 (when org-latex-and-specials-regexp
4945 (let (rtn d)
4946 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4947 limit t))
4948 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4949 'face))
4950 '(org-code org-verbatim underline)))
4951 (progn
4952 (setq rtn t
4953 d (cond ((member (char-after (1+ (match-beginning 0)))
4954 '(?_ ?^)) 1)
4955 (t 0)))
4956 (font-lock-prepend-text-property
4957 (+ d (match-beginning 0)) (match-end 0)
4958 'face 'org-latex-and-export-specials)
4959 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4960 '(font-lock-multiline t)))))
4961 rtn)))
4963 (defun org-restart-font-lock ()
4964 "Restart font-lock-mode, to force refontification."
4965 (when (and (boundp 'font-lock-mode) font-lock-mode)
4966 (font-lock-mode -1)
4967 (font-lock-mode 1)))
4969 (defun org-all-targets (&optional radio)
4970 "Return a list of all targets in this file.
4971 With optional argument RADIO, only find radio targets."
4972 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4973 rtn)
4974 (save-excursion
4975 (goto-char (point-min))
4976 (while (re-search-forward re nil t)
4977 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4978 rtn)))
4980 (defun org-make-target-link-regexp (targets)
4981 "Make regular expression matching all strings in TARGETS.
4982 The regular expression finds the targets also if there is a line break
4983 between words."
4984 (and targets
4985 (concat
4986 "\\<\\("
4987 (mapconcat
4988 (lambda (x)
4989 (while (string-match " +" x)
4990 (setq x (replace-match "\\s-+" t t x)))
4992 targets
4993 "\\|")
4994 "\\)\\>")))
4996 (defun org-activate-tags (limit)
4997 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4998 (progn
4999 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5000 (add-text-properties (match-beginning 1) (match-end 1)
5001 (list 'mouse-face 'highlight
5002 'keymap org-mouse-map))
5003 (org-rear-nonsticky-at (match-end 1))
5004 t)))
5006 (defun org-outline-level ()
5007 "Compute the outline level of the heading at point.
5008 This function assumes that the cursor is at the beginning of a line matched
5009 by outline-regexp. Otherwise it returns garbage.
5010 If this is called at a normal headline, the level is the number of stars.
5011 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
5012 For plain list items, if they are matched by `outline-regexp', this returns
5013 1000 plus the line indentation."
5014 (save-excursion
5015 (looking-at outline-regexp)
5016 (if (match-beginning 1)
5017 (+ (org-get-string-indentation (match-string 1)) 1000)
5018 (1- (- (match-end 0) (match-beginning 0))))))
5020 (defvar org-font-lock-keywords nil)
5022 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5023 "Regular expression matching a property line.")
5025 (defvar org-font-lock-hook nil
5026 "Functions to be called for special font lock stuff.")
5028 (defun org-font-lock-hook (limit)
5029 (run-hook-with-args 'org-font-lock-hook limit))
5031 (defun org-set-font-lock-defaults ()
5032 (let* ((em org-fontify-emphasized-text)
5033 (lk org-activate-links)
5034 (org-font-lock-extra-keywords
5035 (list
5036 ;; Call the hook
5037 '(org-font-lock-hook)
5038 ;; Headlines
5039 `(,(if org-fontify-whole-heading-line
5040 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5041 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5042 (1 (org-get-level-face 1))
5043 (2 (org-get-level-face 2))
5044 (3 (org-get-level-face 3)))
5045 ;; Table lines
5046 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5047 (1 'org-table t))
5048 ;; Table internals
5049 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5050 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5051 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5052 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
5053 ;; Drawers
5054 (list org-drawer-regexp '(0 'org-special-keyword t))
5055 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5056 ;; Properties
5057 (list org-property-re
5058 '(1 'org-special-keyword t)
5059 '(3 'org-property-value t))
5060 ;; Links
5061 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5062 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5063 (if (memq 'plain lk) '(org-activate-plain-links))
5064 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5065 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5066 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5067 (if (memq 'footnote lk) '(org-activate-footnote-links
5068 (2 'org-footnote t)))
5069 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5070 '(org-hide-wide-columns (0 nil append))
5071 ;; TODO lines
5072 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5073 '(1 (org-get-todo-face 1) t))
5074 ;; DONE
5075 (if org-fontify-done-headline
5076 (list (concat "^[*]+ +\\<\\("
5077 (mapconcat 'regexp-quote org-done-keywords "\\|")
5078 "\\)\\(.*\\)")
5079 '(2 'org-headline-done t))
5080 nil)
5081 ;; Priorities
5082 '(org-font-lock-add-priority-faces)
5083 ;; Tags
5084 '(org-font-lock-add-tag-faces)
5085 ;; Special keywords
5086 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5087 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5088 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5089 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5090 ;; Emphasis
5091 (if em
5092 (if (featurep 'xemacs)
5093 '(org-do-emphasis-faces (0 nil append))
5094 '(org-do-emphasis-faces)))
5095 ;; Checkboxes
5096 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5097 2 'org-checkbox prepend)
5098 (if org-provide-checkbox-statistics
5099 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5100 (0 (org-get-checkbox-statistics-face) t)))
5101 ;; Description list items
5102 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5103 2 'bold prepend)
5104 ;; ARCHIVEd headings
5105 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5106 '(1 'org-archived prepend))
5107 ;; Specials
5108 '(org-do-latex-and-special-faces)
5109 ;; Code
5110 '(org-activate-code (1 'org-code t))
5111 ;; COMMENT
5112 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5113 "\\|" org-quote-string "\\)\\>")
5114 '(1 'org-special-keyword t))
5115 '("^#.*" (0 'font-lock-comment-face t))
5116 ;; Blocks and meta lines
5117 '(org-fontify-meta-lines-and-blocks)
5119 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5120 ;; Now set the full font-lock-keywords
5121 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5122 (org-set-local 'font-lock-defaults
5123 '(org-font-lock-keywords t nil nil backward-paragraph))
5124 (kill-local-variable 'font-lock-keywords) nil))
5126 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5127 "Fontify string S like in Org-mode"
5128 (with-temp-buffer
5129 (insert s)
5130 (let ((org-odd-levels-only odd-levels))
5131 (org-mode)
5132 (font-lock-fontify-buffer)
5133 (buffer-string))))
5135 (defvar org-m nil)
5136 (defvar org-l nil)
5137 (defvar org-f nil)
5138 (defun org-get-level-face (n)
5139 "Get the right face for match N in font-lock matching of headlines."
5140 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5141 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5142 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5143 (cond
5144 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5145 ((eq n 2) org-f)
5146 (t (if org-level-color-stars-only nil org-f))))
5148 (defun org-get-todo-face (kwd)
5149 "Get the right face for a TODO keyword KWD.
5150 If KWD is a number, get the corresponding match group."
5151 (if (numberp kwd) (setq kwd (match-string kwd)))
5152 (or (org-face-from-face-or-color
5153 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5154 (and (member kwd org-done-keywords) 'org-done)
5155 'org-todo))
5157 (defun org-face-from-face-or-color (context inherit face-or-color)
5158 "Create a face list that inherits INHERIT, but sets the foreground color.
5159 When FACE-OR-COLOR is not a string, just return it."
5160 (if (stringp face-or-color)
5161 (list :inherit inherit
5162 (cdr (assoc context org-faces-easy-properties))
5163 face-or-color)
5164 face-or-color))
5166 (defun org-font-lock-add-tag-faces (limit)
5167 "Add the special tag faces."
5168 (when (and org-tag-faces org-tags-special-faces-re)
5169 (while (re-search-forward org-tags-special-faces-re limit t)
5170 (add-text-properties (match-beginning 1) (match-end 1)
5171 (list 'face (org-get-tag-face 1)
5172 'font-lock-fontified t))
5173 (backward-char 1))))
5175 (defun org-font-lock-add-priority-faces (limit)
5176 "Add the special priority faces."
5177 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5178 (add-text-properties
5179 (match-beginning 0) (match-end 0)
5180 (list 'face (or (org-face-from-face-or-color
5181 'priority 'org-special-keyword
5182 (cdr (assoc (char-after (match-beginning 1))
5183 org-priority-faces)))
5184 'org-special-keyword)
5185 'font-lock-fontified t))))
5187 (defun org-get-tag-face (kwd)
5188 "Get the right face for a TODO keyword KWD.
5189 If KWD is a number, get the corresponding match group."
5190 (if (numberp kwd) (setq kwd (match-string kwd)))
5191 (or (org-face-from-face-or-color
5192 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5193 'org-tag))
5195 (defun org-unfontify-region (beg end &optional maybe_loudly)
5196 "Remove fontification and activation overlays from links."
5197 (font-lock-default-unfontify-region beg end)
5198 (let* ((buffer-undo-list t)
5199 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5200 (inhibit-modification-hooks t)
5201 deactivate-mark buffer-file-name buffer-file-truename)
5202 (remove-text-properties
5203 beg end
5204 (if org-indent-mode
5205 ;; also remove line-prefix and wrap-prefix properties
5206 '(mouse-face t keymap t org-linked-text t
5207 invisible t intangible t
5208 line-prefix t wrap-prefix t
5209 org-no-flyspell t)
5210 '(mouse-face t keymap t org-linked-text t
5211 invisible t intangible t
5212 org-no-flyspell t)))))
5214 ;;;; Visibility cycling, including org-goto and indirect buffer
5216 ;;; Cycling
5218 (defvar org-cycle-global-status nil)
5219 (make-variable-buffer-local 'org-cycle-global-status)
5220 (defvar org-cycle-subtree-status nil)
5221 (make-variable-buffer-local 'org-cycle-subtree-status)
5223 ;;;###autoload
5225 (defvar org-inlinetask-min-level)
5227 (defun org-cycle (&optional arg)
5228 "TAB-action and visibility cycling for Org-mode.
5230 This is the command invoked in Org-mode by the TAB key. Its main purpose
5231 is outline visibility cycling, but it also invokes other actions
5232 in special contexts.
5234 - When this function is called with a prefix argument, rotate the entire
5235 buffer through 3 states (global cycling)
5236 1. OVERVIEW: Show only top-level headlines.
5237 2. CONTENTS: Show all headlines of all levels, but no body text.
5238 3. SHOW ALL: Show everything.
5239 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5240 determined by the variable `org-startup-folded', and by any VISIBILITY
5241 properties in the buffer.
5242 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5243 including any drawers.
5245 - When inside a table, re-align the table and move to the next field.
5247 - When point is at the beginning of a headline, rotate the subtree started
5248 by this line through 3 different states (local cycling)
5249 1. FOLDED: Only the main headline is shown.
5250 2. CHILDREN: The main headline and the direct children are shown.
5251 From this state, you can move to one of the children
5252 and zoom in further.
5253 3. SUBTREE: Show the entire subtree, including body text.
5254 If there is no subtree, switch directly from CHILDREN to FOLDED.
5256 - When point is at the beginning of an empty headline and the variable
5257 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5258 of the headline by demoting and promoting it to likely levels. This
5259 speeds up creation document structure by presing TAB once or several
5260 times right after creating a new headline.
5262 - When there is a numeric prefix, go up to a heading with level ARG, do
5263 a `show-subtree' and return to the previous cursor position. If ARG
5264 is negative, go up that many levels.
5266 - When point is not at the beginning of a headline, execute the global
5267 binding for TAB, which is re-indenting the line. See the option
5268 `org-cycle-emulate-tab' for details.
5270 - Special case: if point is at the beginning of the buffer and there is
5271 no headline in line 1, this function will act as if called with prefix arg.
5272 But only if also the variable `org-cycle-global-at-bob' is t."
5273 (interactive "P")
5274 (org-load-modules-maybe)
5275 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5276 (and org-cycle-level-after-item/entry-creation
5277 (or (org-cycle-level)
5278 (org-cycle-item-indentation))))
5279 (let* ((limit-level
5280 (or org-cycle-max-level
5281 (and (boundp 'org-inlinetask-min-level)
5282 org-inlinetask-min-level
5283 (1- org-inlinetask-min-level))))
5284 (nstars (and limit-level
5285 (if org-odd-levels-only
5286 (and limit-level (1- (* limit-level 2)))
5287 limit-level)))
5288 (outline-regexp
5289 (cond
5290 ((not (org-mode-p)) outline-regexp)
5291 ((or (eq org-cycle-include-plain-lists 'integrate)
5292 (and org-cycle-include-plain-lists (org-at-item-p)))
5293 (concat "\\(?:\\*"
5294 (if nstars (format "\\{1,%d\\}" nstars) "+")
5295 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5296 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5297 (bob-special (and org-cycle-global-at-bob (bobp)
5298 (not (looking-at outline-regexp))))
5299 (org-cycle-hook
5300 (if bob-special
5301 (delq 'org-optimize-window-after-visibility-change
5302 (copy-sequence org-cycle-hook))
5303 org-cycle-hook))
5304 (pos (point)))
5306 (if (or bob-special (equal arg '(4)))
5307 ;; special case: use global cycling
5308 (setq arg t))
5310 (cond
5312 ((equal arg '(16))
5313 (org-set-startup-visibility)
5314 (message "Startup visibility, plus VISIBILITY properties"))
5316 ((equal arg '(64))
5317 (show-all)
5318 (message "Entire buffer visible, including drawers"))
5320 ((org-at-table-p 'any)
5321 ;; Enter the table or move to the next field in the table
5322 (if (org-at-table.el-p)
5323 (message "Use C-c ' to edit table.el tables")
5324 (if arg (org-table-edit-field t)
5325 (org-table-justify-field-maybe)
5326 (call-interactively 'org-table-next-field))))
5328 ((run-hook-with-args-until-success
5329 'org-tab-after-check-for-table-hook))
5331 ((eq arg t) ;; Global cycling
5332 (org-cycle-internal-global))
5334 ((and org-drawers org-drawer-regexp
5335 (save-excursion
5336 (beginning-of-line 1)
5337 (looking-at org-drawer-regexp)))
5338 ;; Toggle block visibility
5339 (org-flag-drawer
5340 (not (get-char-property (match-end 0) 'invisible))))
5342 ((integerp arg)
5343 ;; Show-subtree, ARG levels up from here.
5344 (save-excursion
5345 (org-back-to-heading)
5346 (outline-up-heading (if (< arg 0) (- arg)
5347 (- (funcall outline-level) arg)))
5348 (org-show-subtree)))
5350 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5351 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5353 (org-cycle-internal-local))
5355 ;; TAB emulation and template completion
5356 (buffer-read-only (org-back-to-heading))
5358 ((run-hook-with-args-until-success
5359 'org-tab-after-check-for-cycling-hook))
5361 ((org-try-structure-completion))
5363 ((org-try-cdlatex-tab))
5365 ((run-hook-with-args-until-success
5366 'org-tab-before-tab-emulation-hook))
5368 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5369 (or (not (bolp))
5370 (not (looking-at outline-regexp))))
5371 (call-interactively (global-key-binding "\t")))
5373 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5374 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5375 (or (and (eq org-cycle-emulate-tab 'white)
5376 (= (match-end 0) (point-at-eol)))
5377 (and (eq org-cycle-emulate-tab 'whitestart)
5378 (>= (match-end 0) pos))))
5380 (eq org-cycle-emulate-tab t))
5381 (call-interactively (global-key-binding "\t")))
5383 (t (save-excursion
5384 (org-back-to-heading)
5385 (org-cycle)))))))
5387 (defun org-cycle-internal-global ()
5388 "Do the global cycling action."
5389 (cond
5390 ((and (eq last-command this-command)
5391 (eq org-cycle-global-status 'overview))
5392 ;; We just created the overview - now do table of contents
5393 ;; This can be slow in very large buffers, so indicate action
5394 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5395 (message "CONTENTS...")
5396 (org-content)
5397 (message "CONTENTS...done")
5398 (setq org-cycle-global-status 'contents)
5399 (run-hook-with-args 'org-cycle-hook 'contents))
5401 ((and (eq last-command this-command)
5402 (eq org-cycle-global-status 'contents))
5403 ;; We just showed the table of contents - now show everything
5404 (run-hook-with-args 'org-pre-cycle-hook 'all)
5405 (show-all)
5406 (message "SHOW ALL")
5407 (setq org-cycle-global-status 'all)
5408 (run-hook-with-args 'org-cycle-hook 'all))
5411 ;; Default action: go to overview
5412 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5413 (org-overview)
5414 (message "OVERVIEW")
5415 (setq org-cycle-global-status 'overview)
5416 (run-hook-with-args 'org-cycle-hook 'overview))))
5418 (defun org-cycle-internal-local ()
5419 "Do the local cycling action."
5420 (org-back-to-heading)
5421 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5422 ;; First, some boundaries
5423 (save-excursion
5424 (org-back-to-heading)
5425 (setq level (funcall outline-level))
5426 (save-excursion
5427 (beginning-of-line 2)
5428 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5429 ; XEmacs does not have `next-single-char-property-change'
5430 ; I'm not sure about Emacs 21.
5431 (while (and (not (eobp)) ;; this is like `next-line'
5432 (get-char-property (1- (point)) 'invisible))
5433 (beginning-of-line 2))
5434 (while (and (not (eobp)) ;; this is like `next-line'
5435 (get-char-property (1- (point)) 'invisible))
5436 (goto-char (next-single-char-property-change (point) 'invisible))
5437 ;;;??? (or (bolp) (beginning-of-line 2))))
5438 (and (eolp) (beginning-of-line 2))))
5439 (setq eol (point)))
5440 (outline-end-of-heading) (setq eoh (point))
5441 (save-excursion
5442 (outline-next-heading)
5443 (setq has-children (and (org-at-heading-p t)
5444 (> (funcall outline-level) level))))
5445 (org-end-of-subtree t)
5446 (unless (eobp)
5447 (skip-chars-forward " \t\n")
5448 (beginning-of-line 1) ; in case this is an item
5450 (setq eos (if (eobp) (point) (1- (point)))))
5451 ;; Find out what to do next and set `this-command'
5452 (cond
5453 ((= eos eoh)
5454 ;; Nothing is hidden behind this heading
5455 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5456 (message "EMPTY ENTRY")
5457 (setq org-cycle-subtree-status nil)
5458 (save-excursion
5459 (goto-char eos)
5460 (outline-next-heading)
5461 (if (org-invisible-p) (org-flag-heading nil))))
5462 ((and (or (>= eol eos)
5463 (not (string-match "\\S-" (buffer-substring eol eos))))
5464 (or has-children
5465 (not (setq children-skipped
5466 org-cycle-skip-children-state-if-no-children))))
5467 ;; Entire subtree is hidden in one line: children view
5468 (run-hook-with-args 'org-pre-cycle-hook 'children)
5469 (org-show-entry)
5470 (show-children)
5471 (message "CHILDREN")
5472 (save-excursion
5473 (goto-char eos)
5474 (outline-next-heading)
5475 (if (org-invisible-p) (org-flag-heading nil)))
5476 (setq org-cycle-subtree-status 'children)
5477 (run-hook-with-args 'org-cycle-hook 'children))
5478 ((or children-skipped
5479 (and (eq last-command this-command)
5480 (eq org-cycle-subtree-status 'children)))
5481 ;; We just showed the children, or no children are there,
5482 ;; now show everything.
5483 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5484 (org-show-subtree)
5485 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5486 (setq org-cycle-subtree-status 'subtree)
5487 (run-hook-with-args 'org-cycle-hook 'subtree))
5489 ;; Default action: hide the subtree.
5490 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5491 (hide-subtree)
5492 (message "FOLDED")
5493 (setq org-cycle-subtree-status 'folded)
5494 (run-hook-with-args 'org-cycle-hook 'folded)))))
5496 ;;;###autoload
5497 (defun org-global-cycle (&optional arg)
5498 "Cycle the global visibility. For details see `org-cycle'.
5499 With C-u prefix arg, switch to startup visibility.
5500 With a numeric prefix, show all headlines up to that level."
5501 (interactive "P")
5502 (let ((org-cycle-include-plain-lists
5503 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5504 (cond
5505 ((integerp arg)
5506 (show-all)
5507 (hide-sublevels arg)
5508 (setq org-cycle-global-status 'contents))
5509 ((equal arg '(4))
5510 (org-set-startup-visibility)
5511 (message "Startup visibility, plus VISIBILITY properties."))
5513 (org-cycle '(4))))))
5515 (defun org-set-startup-visibility ()
5516 "Set the visibility required by startup options and properties."
5517 (cond
5518 ((eq org-startup-folded t)
5519 (org-cycle '(4)))
5520 ((eq org-startup-folded 'content)
5521 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5522 (org-cycle '(4)) (org-cycle '(4)))))
5523 (unless (eq org-startup-folded 'showeverything)
5524 (if org-hide-block-startup (org-hide-block-all))
5525 (org-set-visibility-according-to-property 'no-cleanup)
5526 (org-cycle-hide-archived-subtrees 'all)
5527 (org-cycle-hide-drawers 'all)
5528 (org-cycle-show-empty-lines 'all)))
5530 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5531 "Switch subtree visibilities according to :VISIBILITY: property."
5532 (interactive)
5533 (let (org-show-entry-below state)
5534 (save-excursion
5535 (goto-char (point-min))
5536 (while (re-search-forward
5537 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5538 nil t)
5539 (setq state (match-string 1))
5540 (save-excursion
5541 (org-back-to-heading t)
5542 (hide-subtree)
5543 (org-reveal)
5544 (cond
5545 ((equal state '("fold" "folded"))
5546 (hide-subtree))
5547 ((equal state "children")
5548 (org-show-hidden-entry)
5549 (show-children))
5550 ((equal state "content")
5551 (save-excursion
5552 (save-restriction
5553 (org-narrow-to-subtree)
5554 (org-content))))
5555 ((member state '("all" "showall"))
5556 (show-subtree)))))
5557 (unless no-cleanup
5558 (org-cycle-hide-archived-subtrees 'all)
5559 (org-cycle-hide-drawers 'all)
5560 (org-cycle-show-empty-lines 'all)))))
5562 (defun org-overview ()
5563 "Switch to overview mode, showing only top-level headlines.
5564 Really, this shows all headlines with level equal or greater than the level
5565 of the first headline in the buffer. This is important, because if the
5566 first headline is not level one, then (hide-sublevels 1) gives confusing
5567 results."
5568 (interactive)
5569 (let ((level (save-excursion
5570 (goto-char (point-min))
5571 (if (re-search-forward (concat "^" outline-regexp) nil t)
5572 (progn
5573 (goto-char (match-beginning 0))
5574 (funcall outline-level))))))
5575 (and level (hide-sublevels level))))
5577 (defun org-content (&optional arg)
5578 "Show all headlines in the buffer, like a table of contents.
5579 With numerical argument N, show content up to level N."
5580 (interactive "P")
5581 (save-excursion
5582 ;; Visit all headings and show their offspring
5583 (and (integerp arg) (org-overview))
5584 (goto-char (point-max))
5585 (catch 'exit
5586 (while (and (progn (condition-case nil
5587 (outline-previous-visible-heading 1)
5588 (error (goto-char (point-min))))
5590 (looking-at outline-regexp))
5591 (if (integerp arg)
5592 (show-children (1- arg))
5593 (show-branches))
5594 (if (bobp) (throw 'exit nil))))))
5597 (defun org-optimize-window-after-visibility-change (state)
5598 "Adjust the window after a change in outline visibility.
5599 This function is the default value of the hook `org-cycle-hook'."
5600 (when (get-buffer-window (current-buffer))
5601 (cond
5602 ((eq state 'content) nil)
5603 ((eq state 'all) nil)
5604 ((eq state 'folded) nil)
5605 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5606 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5608 (defun org-remove-empty-overlays-at (pos)
5609 "Remove outline overlays that do not contain non-white stuff."
5610 (mapc
5611 (lambda (o)
5612 (and (eq 'outline (org-overlay-get o 'invisible))
5613 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5614 (org-overlay-end o))))
5615 (org-delete-overlay o)))
5616 (org-overlays-at pos)))
5618 (defun org-clean-visibility-after-subtree-move ()
5619 "Fix visibility issues after moving a subtree."
5620 ;; First, find a reasonable region to look at:
5621 ;; Start two siblings above, end three below
5622 (let* ((beg (save-excursion
5623 (and (org-get-last-sibling)
5624 (org-get-last-sibling))
5625 (point)))
5626 (end (save-excursion
5627 (and (org-get-next-sibling)
5628 (org-get-next-sibling)
5629 (org-get-next-sibling))
5630 (if (org-at-heading-p)
5631 (point-at-eol)
5632 (point))))
5633 (level (looking-at "\\*+"))
5634 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5635 (save-excursion
5636 (save-restriction
5637 (narrow-to-region beg end)
5638 (when re
5639 ;; Properly fold already folded siblings
5640 (goto-char (point-min))
5641 (while (re-search-forward re nil t)
5642 (if (and (not (org-invisible-p))
5643 (save-excursion
5644 (goto-char (point-at-eol)) (org-invisible-p)))
5645 (hide-entry))))
5646 (org-cycle-show-empty-lines 'overview)
5647 (org-cycle-hide-drawers 'overview)))))
5649 (defun org-cycle-show-empty-lines (state)
5650 "Show empty lines above all visible headlines.
5651 The region to be covered depends on STATE when called through
5652 `org-cycle-hook'. Lisp program can use t for STATE to get the
5653 entire buffer covered. Note that an empty line is only shown if there
5654 are at least `org-cycle-separator-lines' empty lines before the headline."
5655 (when (not (= org-cycle-separator-lines 0))
5656 (save-excursion
5657 (let* ((n (abs org-cycle-separator-lines))
5658 (re (cond
5659 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5660 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5661 (t (let ((ns (number-to-string (- n 2))))
5662 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5663 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5664 beg end b e)
5665 (cond
5666 ((memq state '(overview contents t))
5667 (setq beg (point-min) end (point-max)))
5668 ((memq state '(children folded))
5669 (setq beg (point) end (progn (org-end-of-subtree t t)
5670 (beginning-of-line 2)
5671 (point)))))
5672 (when beg
5673 (goto-char beg)
5674 (while (re-search-forward re end t)
5675 (unless (get-char-property (match-end 1) 'invisible)
5676 (setq e (match-end 1))
5677 (if (< org-cycle-separator-lines 0)
5678 (setq b (save-excursion
5679 (goto-char (match-beginning 0))
5680 (org-back-over-empty-lines)
5681 (if (save-excursion
5682 (goto-char (max (point-min) (1- (point))))
5683 (org-on-heading-p))
5684 (1- (point))
5685 (point))))
5686 (setq b (match-beginning 1)))
5687 (outline-flag-region b e nil)))))))
5688 ;; Never hide empty lines at the end of the file.
5689 (save-excursion
5690 (goto-char (point-max))
5691 (outline-previous-heading)
5692 (outline-end-of-heading)
5693 (if (and (looking-at "[ \t\n]+")
5694 (= (match-end 0) (point-max)))
5695 (outline-flag-region (point) (match-end 0) nil))))
5697 (defun org-show-empty-lines-in-parent ()
5698 "Move to the parent and re-show empty lines before visible headlines."
5699 (save-excursion
5700 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5701 (org-cycle-show-empty-lines context))))
5703 (defun org-files-list ()
5704 "Return `org-agenda-files' list, plus all open org-mode files.
5705 This is useful for operations that need to scan all of a user's
5706 open and agenda-wise Org files."
5707 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5708 (dolist (buf (buffer-list))
5709 (with-current-buffer buf
5710 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5711 (let ((file (expand-file-name (buffer-file-name))))
5712 (unless (member file files)
5713 (push file files))))))
5714 files))
5716 (defsubst org-entry-beginning-position ()
5717 "Return the beginning position of the current entry."
5718 (save-excursion (outline-back-to-heading t) (point)))
5720 (defsubst org-entry-end-position ()
5721 "Return the end position of the current entry."
5722 (save-excursion (outline-next-heading) (point)))
5724 (defun org-cycle-hide-drawers (state)
5725 "Re-hide all drawers after a visibility state change."
5726 (when (and (org-mode-p)
5727 (not (memq state '(overview folded contents))))
5728 (save-excursion
5729 (let* ((globalp (memq state '(contents all)))
5730 (beg (if globalp (point-min) (point)))
5731 (end (if globalp (point-max)
5732 (if (eq state 'children)
5733 (save-excursion (outline-next-heading) (point))
5734 (org-end-of-subtree t)))))
5735 (goto-char beg)
5736 (while (re-search-forward org-drawer-regexp end t)
5737 (org-flag-drawer t))))))
5739 (defun org-flag-drawer (flag)
5740 (save-excursion
5741 (beginning-of-line 1)
5742 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5743 (let ((b (match-end 0))
5744 (outline-regexp org-outline-regexp))
5745 (if (re-search-forward
5746 "^[ \t]*:END:"
5747 (save-excursion (outline-next-heading) (point)) t)
5748 (outline-flag-region b (point-at-eol) flag)
5749 (error ":END: line missing at position %s" b))))))
5751 (defun org-subtree-end-visible-p ()
5752 "Is the end of the current subtree visible?"
5753 (pos-visible-in-window-p
5754 (save-excursion (org-end-of-subtree t) (point))))
5756 (defun org-first-headline-recenter (&optional N)
5757 "Move cursor to the first headline and recenter the headline.
5758 Optional argument N means put the headline into the Nth line of the window."
5759 (goto-char (point-min))
5760 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5761 (beginning-of-line)
5762 (recenter (prefix-numeric-value N))))
5764 ;;; Saving and restoring visibility
5766 (defun org-outline-overlay-data (&optional use-markers)
5767 "Return a list of the locations of all outline overlays.
5768 The are overlays with the `invisible' property value `outline'.
5769 The return valus is a list of cons cells, with start and stop
5770 positions for each overlay.
5771 If USE-MARKERS is set, return the positions as markers."
5772 (let (beg end)
5773 (save-excursion
5774 (save-restriction
5775 (widen)
5776 (delq nil
5777 (mapcar (lambda (o)
5778 (when (eq (org-overlay-get o 'invisible) 'outline)
5779 (setq beg (org-overlay-start o)
5780 end (org-overlay-end o))
5781 (and beg end (> end beg)
5782 (if use-markers
5783 (cons (move-marker (make-marker) beg)
5784 (move-marker (make-marker) end))
5785 (cons beg end)))))
5786 (org-overlays-in (point-min) (point-max))))))))
5788 (defun org-set-outline-overlay-data (data)
5789 "Create visibility overlays for all positions in DATA.
5790 DATA should have been made by `org-outline-overlay-data'."
5791 (let (o)
5792 (save-excursion
5793 (save-restriction
5794 (widen)
5795 (show-all)
5796 (mapc (lambda (c)
5797 (setq o (org-make-overlay (car c) (cdr c)))
5798 (org-overlay-put o 'invisible 'outline))
5799 data)))))
5801 (defmacro org-save-outline-visibility (use-markers &rest body)
5802 "Save and restore outline visibility around BODY.
5803 If USE-MARKERS is non-nil, use markers for the positions.
5804 This means that the buffer may change while running BODY,
5805 but it also means that the buffer should stay alive
5806 during the operation, because otherwise all these markers will
5807 point nowhere."
5808 `(let ((data (org-outline-overlay-data ,use-markers)))
5809 (unwind-protect
5810 (progn
5811 ,@body
5812 (org-set-outline-overlay-data data))
5813 (when ,use-markers
5814 (mapc (lambda (c)
5815 (and (markerp (car c)) (move-marker (car c) nil))
5816 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
5817 data)))))
5820 ;;; Folding of blocks
5822 (defconst org-block-regexp
5824 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5825 "Regular expression for hiding blocks.")
5827 (defvar org-hide-block-overlays nil
5828 "Overlays hiding blocks.")
5829 (make-variable-buffer-local 'org-hide-block-overlays)
5831 (defun org-block-map (function &optional start end)
5832 "Call func at the head of all source blocks in the current
5833 buffer. Optional arguments START and END can be used to limit
5834 the range."
5835 (let ((start (or start (point-min)))
5836 (end (or end (point-max))))
5837 (save-excursion
5838 (goto-char start)
5839 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5840 (save-excursion
5841 (save-match-data
5842 (goto-char (match-beginning 0))
5843 (funcall function)))))))
5845 (defun org-hide-block-toggle-all ()
5846 "Toggle the visibility of all blocks in the current buffer."
5847 (org-block-map #'org-hide-block-toggle))
5849 (defun org-hide-block-all ()
5850 "Fold all blocks in the current buffer."
5851 (interactive)
5852 (org-show-block-all)
5853 (org-block-map #'org-hide-block-toggle-maybe))
5855 (defun org-show-block-all ()
5856 "Unfold all blocks in the current buffer."
5857 (mapc 'org-delete-overlay org-hide-block-overlays)
5858 (setq org-hide-block-overlays nil))
5860 (defun org-hide-block-toggle-maybe ()
5861 "Toggle visibility of block at point."
5862 (interactive)
5863 (let ((case-fold-search t))
5864 (if (save-excursion
5865 (beginning-of-line 1)
5866 (looking-at org-block-regexp))
5867 (progn (org-hide-block-toggle)
5868 t) ;; to signal that we took action
5869 nil))) ;; to signal that we did not
5871 (defun org-hide-block-toggle (&optional force)
5872 "Toggle the visibility of the current block."
5873 (interactive)
5874 (save-excursion
5875 (beginning-of-line)
5876 (if (re-search-forward org-block-regexp nil t)
5877 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5878 (end (match-end 0)) ;; end of entire body
5880 (if (memq t (mapcar (lambda (overlay)
5881 (eq (org-overlay-get overlay 'invisible)
5882 'org-hide-block))
5883 (org-overlays-at start)))
5884 (if (or (not force) (eq force 'off))
5885 (mapc (lambda (ov)
5886 (when (member ov org-hide-block-overlays)
5887 (setq org-hide-block-overlays
5888 (delq ov org-hide-block-overlays)))
5889 (when (eq (org-overlay-get ov 'invisible)
5890 'org-hide-block)
5891 (org-delete-overlay ov)))
5892 (org-overlays-at start)))
5893 (setq ov (org-make-overlay start end))
5894 (org-overlay-put ov 'invisible 'org-hide-block)
5895 ;; make the block accessible to isearch
5896 (org-overlay-put
5897 ov 'isearch-open-invisible
5898 (lambda (ov)
5899 (when (member ov org-hide-block-overlays)
5900 (setq org-hide-block-overlays
5901 (delq ov org-hide-block-overlays)))
5902 (when (eq (org-overlay-get ov 'invisible)
5903 'org-hide-block)
5904 (org-delete-overlay ov))))
5905 (push ov org-hide-block-overlays)))
5906 (error "Not looking at a source block"))))
5908 ;; org-tab-after-check-for-cycling-hook
5909 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5910 ;; Remove overlays when changing major mode
5911 (add-hook 'org-mode-hook
5912 (lambda () (org-add-hook 'change-major-mode-hook
5913 'org-show-block-all 'append 'local)))
5915 ;;; Org-goto
5917 (defvar org-goto-window-configuration nil)
5918 (defvar org-goto-marker nil)
5919 (defvar org-goto-map
5920 (let ((map (make-sparse-keymap)))
5921 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5922 (while (setq cmd (pop cmds))
5923 (substitute-key-definition cmd cmd map global-map)))
5924 (suppress-keymap map)
5925 (org-defkey map "\C-m" 'org-goto-ret)
5926 (org-defkey map [(return)] 'org-goto-ret)
5927 (org-defkey map [(left)] 'org-goto-left)
5928 (org-defkey map [(right)] 'org-goto-right)
5929 (org-defkey map [(control ?g)] 'org-goto-quit)
5930 (org-defkey map "\C-i" 'org-cycle)
5931 (org-defkey map [(tab)] 'org-cycle)
5932 (org-defkey map [(down)] 'outline-next-visible-heading)
5933 (org-defkey map [(up)] 'outline-previous-visible-heading)
5934 (if org-goto-auto-isearch
5935 (if (fboundp 'define-key-after)
5936 (define-key-after map [t] 'org-goto-local-auto-isearch)
5937 nil)
5938 (org-defkey map "q" 'org-goto-quit)
5939 (org-defkey map "n" 'outline-next-visible-heading)
5940 (org-defkey map "p" 'outline-previous-visible-heading)
5941 (org-defkey map "f" 'outline-forward-same-level)
5942 (org-defkey map "b" 'outline-backward-same-level)
5943 (org-defkey map "u" 'outline-up-heading))
5944 (org-defkey map "/" 'org-occur)
5945 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5946 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5947 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5948 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5949 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5950 map))
5952 (defconst org-goto-help
5953 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5954 RET=jump to location [Q]uit and return to previous location
5955 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5957 (defvar org-goto-start-pos) ; dynamically scoped parameter
5959 ;; FIXME: Docstring does not mention both interfaces
5960 (defun org-goto (&optional alternative-interface)
5961 "Look up a different location in the current file, keeping current visibility.
5963 When you want look-up or go to a different location in a document, the
5964 fastest way is often to fold the entire buffer and then dive into the tree.
5965 This method has the disadvantage, that the previous location will be folded,
5966 which may not be what you want.
5968 This command works around this by showing a copy of the current buffer
5969 in an indirect buffer, in overview mode. You can dive into the tree in
5970 that copy, use org-occur and incremental search to find a location.
5971 When pressing RET or `Q', the command returns to the original buffer in
5972 which the visibility is still unchanged. After RET is will also jump to
5973 the location selected in the indirect buffer and expose the
5974 the headline hierarchy above."
5975 (interactive "P")
5976 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5977 (org-refile-use-outline-path t)
5978 (org-refile-target-verify-function nil)
5979 (interface
5980 (if (not alternative-interface)
5981 org-goto-interface
5982 (if (eq org-goto-interface 'outline)
5983 'outline-path-completion
5984 'outline)))
5985 (org-goto-start-pos (point))
5986 (selected-point
5987 (if (eq interface 'outline)
5988 (car (org-get-location (current-buffer) org-goto-help))
5989 (nth 3 (org-refile-get-location "Goto: ")))))
5990 (if selected-point
5991 (progn
5992 (org-mark-ring-push org-goto-start-pos)
5993 (goto-char selected-point)
5994 (if (or (org-invisible-p) (org-invisible-p2))
5995 (org-show-context 'org-goto)))
5996 (message "Quit"))))
5998 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5999 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6000 (defvar org-goto-local-auto-isearch-map) ; defined below
6002 (defun org-get-location (buf help)
6003 "Let the user select a location in the Org-mode buffer BUF.
6004 This function uses a recursive edit. It returns the selected position
6005 or nil."
6006 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6007 (isearch-hide-immediately nil)
6008 (isearch-search-fun-function
6009 (lambda () 'org-goto-local-search-headings))
6010 (org-goto-selected-point org-goto-exit-command)
6011 (pop-up-frames nil)
6012 (special-display-buffer-names nil)
6013 (special-display-regexps nil)
6014 (special-display-function nil))
6015 (save-excursion
6016 (save-window-excursion
6017 (delete-other-windows)
6018 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6019 (switch-to-buffer
6020 (condition-case nil
6021 (make-indirect-buffer (current-buffer) "*org-goto*")
6022 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6023 (with-output-to-temp-buffer "*Help*"
6024 (princ help))
6025 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6026 (setq buffer-read-only nil)
6027 (let ((org-startup-truncated t)
6028 (org-startup-folded nil)
6029 (org-startup-align-all-tables nil))
6030 (org-mode)
6031 (org-overview))
6032 (setq buffer-read-only t)
6033 (if (and (boundp 'org-goto-start-pos)
6034 (integer-or-marker-p org-goto-start-pos))
6035 (let ((org-show-hierarchy-above t)
6036 (org-show-siblings t)
6037 (org-show-following-heading t))
6038 (goto-char org-goto-start-pos)
6039 (and (org-invisible-p) (org-show-context)))
6040 (goto-char (point-min)))
6041 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6042 (message "Select location and press RET")
6043 (use-local-map org-goto-map)
6044 (recursive-edit)
6046 (kill-buffer "*org-goto*")
6047 (cons org-goto-selected-point org-goto-exit-command)))
6049 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6050 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6051 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6052 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6054 (defun org-goto-local-search-headings (string bound noerror)
6055 "Search and make sure that any matches are in headlines."
6056 (catch 'return
6057 (while (if isearch-forward
6058 (search-forward string bound noerror)
6059 (search-backward string bound noerror))
6060 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6061 (and (member :headline context)
6062 (not (member :tags context))))
6063 (throw 'return (point))))))
6065 (defun org-goto-local-auto-isearch ()
6066 "Start isearch."
6067 (interactive)
6068 (goto-char (point-min))
6069 (let ((keys (this-command-keys)))
6070 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6071 (isearch-mode t)
6072 (isearch-process-search-char (string-to-char keys)))))
6074 (defun org-goto-ret (&optional arg)
6075 "Finish `org-goto' by going to the new location."
6076 (interactive "P")
6077 (setq org-goto-selected-point (point)
6078 org-goto-exit-command 'return)
6079 (throw 'exit nil))
6081 (defun org-goto-left ()
6082 "Finish `org-goto' by going to the new location."
6083 (interactive)
6084 (if (org-on-heading-p)
6085 (progn
6086 (beginning-of-line 1)
6087 (setq org-goto-selected-point (point)
6088 org-goto-exit-command 'left)
6089 (throw 'exit nil))
6090 (error "Not on a heading")))
6092 (defun org-goto-right ()
6093 "Finish `org-goto' by going to the new location."
6094 (interactive)
6095 (if (org-on-heading-p)
6096 (progn
6097 (setq org-goto-selected-point (point)
6098 org-goto-exit-command 'right)
6099 (throw 'exit nil))
6100 (error "Not on a heading")))
6102 (defun org-goto-quit ()
6103 "Finish `org-goto' without cursor motion."
6104 (interactive)
6105 (setq org-goto-selected-point nil)
6106 (setq org-goto-exit-command 'quit)
6107 (throw 'exit nil))
6109 ;;; Indirect buffer display of subtrees
6111 (defvar org-indirect-dedicated-frame nil
6112 "This is the frame being used for indirect tree display.")
6113 (defvar org-last-indirect-buffer nil)
6115 (defun org-tree-to-indirect-buffer (&optional arg)
6116 "Create indirect buffer and narrow it to current subtree.
6117 With numerical prefix ARG, go up to this level and then take that tree.
6118 If ARG is negative, go up that many levels.
6119 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6120 indirect buffer previously made with this command, to avoid proliferation of
6121 indirect buffers. However, when you call the command with a `C-u' prefix, or
6122 when `org-indirect-buffer-display' is `new-frame', the last buffer
6123 is kept so that you can work with several indirect buffers at the same time.
6124 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6125 requests that a new frame be made for the new buffer, so that the dedicated
6126 frame is not changed."
6127 (interactive "P")
6128 (let ((cbuf (current-buffer))
6129 (cwin (selected-window))
6130 (pos (point))
6131 beg end level heading ibuf)
6132 (save-excursion
6133 (org-back-to-heading t)
6134 (when (numberp arg)
6135 (setq level (org-outline-level))
6136 (if (< arg 0) (setq arg (+ level arg)))
6137 (while (> (setq level (org-outline-level)) arg)
6138 (outline-up-heading 1 t)))
6139 (setq beg (point)
6140 heading (org-get-heading))
6141 (org-end-of-subtree t t)
6142 (if (org-on-heading-p) (backward-char 1))
6143 (setq end (point)))
6144 (if (and (buffer-live-p org-last-indirect-buffer)
6145 (not (eq org-indirect-buffer-display 'new-frame))
6146 (not arg))
6147 (kill-buffer org-last-indirect-buffer))
6148 (setq ibuf (org-get-indirect-buffer cbuf)
6149 org-last-indirect-buffer ibuf)
6150 (cond
6151 ((or (eq org-indirect-buffer-display 'new-frame)
6152 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6153 (select-frame (make-frame))
6154 (delete-other-windows)
6155 (switch-to-buffer ibuf)
6156 (org-set-frame-title heading))
6157 ((eq org-indirect-buffer-display 'dedicated-frame)
6158 (raise-frame
6159 (select-frame (or (and org-indirect-dedicated-frame
6160 (frame-live-p org-indirect-dedicated-frame)
6161 org-indirect-dedicated-frame)
6162 (setq org-indirect-dedicated-frame (make-frame)))))
6163 (delete-other-windows)
6164 (switch-to-buffer ibuf)
6165 (org-set-frame-title (concat "Indirect: " heading)))
6166 ((eq org-indirect-buffer-display 'current-window)
6167 (switch-to-buffer ibuf))
6168 ((eq org-indirect-buffer-display 'other-window)
6169 (pop-to-buffer ibuf))
6170 (t (error "Invalid value")))
6171 (if (featurep 'xemacs)
6172 (save-excursion (org-mode) (turn-on-font-lock)))
6173 (narrow-to-region beg end)
6174 (show-all)
6175 (goto-char pos)
6176 (and (window-live-p cwin) (select-window cwin))))
6178 (defun org-get-indirect-buffer (&optional buffer)
6179 (setq buffer (or buffer (current-buffer)))
6180 (let ((n 1) (base (buffer-name buffer)) bname)
6181 (while (buffer-live-p
6182 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6183 (setq n (1+ n)))
6184 (condition-case nil
6185 (make-indirect-buffer buffer bname 'clone)
6186 (error (make-indirect-buffer buffer bname)))))
6188 (defun org-set-frame-title (title)
6189 "Set the title of the current frame to the string TITLE."
6190 ;; FIXME: how to name a single frame in XEmacs???
6191 (unless (featurep 'xemacs)
6192 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6194 ;;;; Structure editing
6196 ;;; Inserting headlines
6198 (defun org-previous-line-empty-p ()
6199 (save-excursion
6200 (and (not (bobp))
6201 (or (beginning-of-line 0) t)
6202 (save-match-data
6203 (looking-at "[ \t]*$")))))
6205 (defun org-insert-heading (&optional force-heading invisible-ok)
6206 "Insert a new heading or item with same depth at point.
6207 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6208 If point is at the beginning of a headline, insert a sibling before the
6209 current headline. If point is not at the beginning, do not split the line,
6210 but create the new headline after the current line.
6211 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6212 This is important for non-interactive uses of the command."
6213 (interactive "P")
6214 (if (or (= (buffer-size) 0)
6215 (and (not (save-excursion (and (ignore-errors (org-back-to-heading invisible-ok))
6216 (org-on-heading-p))))
6217 (not (org-in-item-p))))
6218 (insert "\n* ")
6219 (when (or force-heading (not (org-insert-item)))
6220 (let* ((empty-line-p nil)
6221 (head (save-excursion
6222 (condition-case nil
6223 (progn
6224 (org-back-to-heading invisible-ok)
6225 (setq empty-line-p (org-previous-line-empty-p))
6226 (match-string 0))
6227 (error "*"))))
6228 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6229 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6230 pos hide-previous previous-pos)
6231 (cond
6232 ((and (org-on-heading-p) (bolp)
6233 (or (bobp)
6234 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6235 ;; insert before the current line
6236 (open-line (if blank 2 1)))
6237 ((and (bolp)
6238 (not org-insert-heading-respect-content)
6239 (or (bobp)
6240 (save-excursion
6241 (backward-char 1) (not (org-invisible-p)))))
6242 ;; insert right here
6243 nil)
6245 ;; somewhere in the line
6246 (save-excursion
6247 (setq previous-pos (point-at-bol))
6248 (end-of-line)
6249 (setq hide-previous (org-invisible-p)))
6250 (and org-insert-heading-respect-content (org-show-subtree))
6251 (let ((split
6252 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6253 (save-excursion
6254 (let ((p (point)))
6255 (goto-char (point-at-bol))
6256 (and (looking-at org-complex-heading-regexp)
6257 (> p (match-beginning 4)))))))
6258 tags pos)
6259 (cond
6260 (org-insert-heading-respect-content
6261 (org-end-of-subtree nil t)
6262 (or (bolp) (newline))
6263 (or (org-previous-line-empty-p)
6264 (and blank (newline)))
6265 (open-line 1))
6266 ((org-on-heading-p)
6267 (when hide-previous
6268 (show-children)
6269 (org-show-entry))
6270 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6271 (setq tags (and (match-end 2) (match-string 2)))
6272 (and (match-end 1)
6273 (delete-region (match-beginning 1) (match-end 1)))
6274 (setq pos (point-at-bol))
6275 (or split (end-of-line 1))
6276 (delete-horizontal-space)
6277 (if (string-match "\\`\\*+\\'"
6278 (buffer-substring (point-at-bol) (point)))
6279 (insert " "))
6280 (newline (if blank 2 1))
6281 (when tags
6282 (save-excursion
6283 (goto-char pos)
6284 (end-of-line 1)
6285 (insert " " tags)
6286 (org-set-tags nil 'align))))
6288 (or split (end-of-line 1))
6289 (newline (if blank 2 1)))))))
6290 (insert head) (just-one-space)
6291 (setq pos (point))
6292 (end-of-line 1)
6293 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6294 (when (and org-insert-heading-respect-content hide-previous)
6295 (save-excursion
6296 (goto-char previous-pos)
6297 (hide-subtree)))
6298 (run-hooks 'org-insert-heading-hook)))))
6300 (defun org-get-heading (&optional no-tags)
6301 "Return the heading of the current entry, without the stars."
6302 (save-excursion
6303 (org-back-to-heading t)
6304 (if (looking-at
6305 (if no-tags
6306 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6307 "\\*+[ \t]+\\([^\r\n]*\\)"))
6308 (match-string 1) "")))
6310 (defun org-heading-components ()
6311 "Return the components of the current heading.
6312 This is a list with the following elements:
6313 - the level as an integer
6314 - the reduced level, different if `org-odd-levels-only' is set.
6315 - the TODO keyword, or nil
6316 - the priority character, like ?A, or nil if no priority is given
6317 - the headline text itself, or the tags string if no headline text
6318 - the tags string, or nil."
6319 (save-excursion
6320 (org-back-to-heading t)
6321 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6322 (list (length (match-string 1))
6323 (org-reduced-level (length (match-string 1)))
6324 (org-match-string-no-properties 2)
6325 (and (match-end 3) (aref (match-string 3) 2))
6326 (org-match-string-no-properties 4)
6327 (org-match-string-no-properties 5)))))
6329 (defun org-get-entry ()
6330 "Get the entry text, after heading, entire subtree."
6331 (save-excursion
6332 (org-back-to-heading t)
6333 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6335 (defun org-insert-heading-after-current ()
6336 "Insert a new heading with same level as current, after current subtree."
6337 (interactive)
6338 (org-back-to-heading)
6339 (org-insert-heading)
6340 (org-move-subtree-down)
6341 (end-of-line 1))
6343 (defun org-insert-heading-respect-content ()
6344 (interactive)
6345 (let ((org-insert-heading-respect-content t))
6346 (org-insert-heading t)))
6348 (defun org-insert-todo-heading-respect-content (&optional force-state)
6349 (interactive "P")
6350 (let ((org-insert-heading-respect-content t))
6351 (org-insert-todo-heading force-state t)))
6353 (defun org-insert-todo-heading (arg &optional force-heading)
6354 "Insert a new heading with the same level and TODO state as current heading.
6355 If the heading has no TODO state, or if the state is DONE, use the first
6356 state (TODO by default). Also with prefix arg, force first state."
6357 (interactive "P")
6358 (when (or force-heading (not (org-insert-item 'checkbox)))
6359 (org-insert-heading force-heading)
6360 (save-excursion
6361 (org-back-to-heading)
6362 (outline-previous-heading)
6363 (looking-at org-todo-line-regexp))
6364 (let*
6365 ((new-mark-x
6366 (if (or arg
6367 (not (match-beginning 2))
6368 (member (match-string 2) org-done-keywords))
6369 (car org-todo-keywords-1)
6370 (match-string 2)))
6371 (new-mark
6373 (run-hook-with-args-until-success
6374 'org-todo-get-default-hook new-mark-x nil)
6375 new-mark-x)))
6376 (beginning-of-line 1)
6377 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6378 (if org-treat-insert-todo-heading-as-state-change
6379 (org-todo new-mark)
6380 (insert new-mark " "))))
6381 (when org-provide-todo-statistics
6382 (org-update-parent-todo-statistics))))
6384 (defun org-insert-subheading (arg)
6385 "Insert a new subheading and demote it.
6386 Works for outline headings and for plain lists alike."
6387 (interactive "P")
6388 (org-insert-heading arg)
6389 (cond
6390 ((org-on-heading-p) (org-do-demote))
6391 ((org-at-item-p) (org-indent-item 1))))
6393 (defun org-insert-todo-subheading (arg)
6394 "Insert a new subheading with TODO keyword or checkbox and demote it.
6395 Works for outline headings and for plain lists alike."
6396 (interactive "P")
6397 (org-insert-todo-heading arg)
6398 (cond
6399 ((org-on-heading-p) (org-do-demote))
6400 ((org-at-item-p) (org-indent-item 1))))
6402 ;;; Promotion and Demotion
6404 (defvar org-after-demote-entry-hook nil
6405 "Hook run after an entry has been demoted.
6406 The cursor will be at the beginning of the entry.
6407 When a subtree is being demoted, the hook will be called for each node.")
6409 (defvar org-after-promote-entry-hook nil
6410 "Hook run after an entry has been promoted.
6411 The cursor will be at the beginning of the entry.
6412 When a subtree is being promoted, the hook will be called for each node.")
6414 (defun org-promote-subtree ()
6415 "Promote the entire subtree.
6416 See also `org-promote'."
6417 (interactive)
6418 (save-excursion
6419 (org-map-tree 'org-promote))
6420 (org-fix-position-after-promote))
6422 (defun org-demote-subtree ()
6423 "Demote the entire subtree. See `org-demote'.
6424 See also `org-promote'."
6425 (interactive)
6426 (save-excursion
6427 (org-map-tree 'org-demote))
6428 (org-fix-position-after-promote))
6431 (defun org-do-promote ()
6432 "Promote the current heading higher up the tree.
6433 If the region is active in `transient-mark-mode', promote all headings
6434 in the region."
6435 (interactive)
6436 (save-excursion
6437 (if (org-region-active-p)
6438 (org-map-region 'org-promote (region-beginning) (region-end))
6439 (org-promote)))
6440 (org-fix-position-after-promote))
6442 (defun org-do-demote ()
6443 "Demote the current heading lower down the tree.
6444 If the region is active in `transient-mark-mode', demote all headings
6445 in the region."
6446 (interactive)
6447 (save-excursion
6448 (if (org-region-active-p)
6449 (org-map-region 'org-demote (region-beginning) (region-end))
6450 (org-demote)))
6451 (org-fix-position-after-promote))
6453 (defun org-fix-position-after-promote ()
6454 "Make sure that after pro/demotion cursor position is right."
6455 (let ((pos (point)))
6456 (when (save-excursion
6457 (beginning-of-line 1)
6458 (looking-at org-todo-line-regexp)
6459 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6460 (cond ((eobp) (insert " "))
6461 ((eolp) (insert " "))
6462 ((equal (char-after) ?\ ) (forward-char 1))))))
6464 (defun org-current-level ()
6465 "Return the level of the current entry, or nil if before the first headline.
6466 The level is the number of stars at the beginning of the headline."
6467 (save-excursion
6468 (condition-case nil
6469 (progn
6470 (org-back-to-heading t)
6471 (funcall outline-level))
6472 (error nil))))
6474 (defun org-get-previous-line-level ()
6475 "Return the outline depth of the last headline before the current line.
6476 Returns 0 for the first headline in the buffer, and nil if before the
6477 first headline."
6478 (let ((current-level (org-current-level))
6479 (prev-level (when (> (line-number-at-pos) 1)
6480 (save-excursion
6481 (beginning-of-line 0)
6482 (org-current-level)))))
6483 (cond ((null current-level) nil) ; Before first headline
6484 ((null prev-level) 0) ; At first headline
6485 (prev-level))))
6487 (defun org-reduced-level (l)
6488 "Compute the effective level of a heading.
6489 This takes into account the setting of `org-odd-levels-only'."
6490 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6492 (defun org-level-increment ()
6493 "Return the number of stars that will be added or removed at a
6494 time to headlines when structure editing, based on the value of
6495 `org-odd-levels-only'."
6496 (if org-odd-levels-only 2 1))
6498 (defun org-get-valid-level (level &optional change)
6499 "Rectify a level change under the influence of `org-odd-levels-only'
6500 LEVEL is a current level, CHANGE is by how much the level should be
6501 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6502 even level numbers will become the next higher odd number."
6503 (if org-odd-levels-only
6504 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6505 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6506 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6507 (max 1 (+ level (or change 0)))))
6509 (if (boundp 'define-obsolete-function-alias)
6510 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6511 (define-obsolete-function-alias 'org-get-legal-level
6512 'org-get-valid-level)
6513 (define-obsolete-function-alias 'org-get-legal-level
6514 'org-get-valid-level "23.1")))
6516 (defun org-promote ()
6517 "Promote the current heading higher up the tree.
6518 If the region is active in `transient-mark-mode', promote all headings
6519 in the region."
6520 (org-back-to-heading t)
6521 (let* ((level (save-match-data (funcall outline-level)))
6522 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6523 (diff (abs (- level (length up-head) -1))))
6524 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6525 (replace-match up-head nil t)
6526 ;; Fixup tag positioning
6527 (and org-auto-align-tags (org-set-tags nil t))
6528 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6529 (run-hooks 'org-after-promote-entry-hook)))
6531 (defun org-demote ()
6532 "Demote the current heading lower down the tree.
6533 If the region is active in `transient-mark-mode', demote all headings
6534 in the region."
6535 (org-back-to-heading t)
6536 (let* ((level (save-match-data (funcall outline-level)))
6537 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6538 (diff (abs (- level (length down-head) -1))))
6539 (replace-match down-head nil t)
6540 ;; Fixup tag positioning
6541 (and org-auto-align-tags (org-set-tags nil t))
6542 (if org-adapt-indentation (org-fixup-indentation diff))
6543 (run-hooks 'org-after-demote-entry-hook)))
6545 (defun org-cycle-level ()
6546 "Cycle the level of an empty headline through possible states.
6547 This goes first to child, then to parent, level, then up the hierarchy.
6548 After top level, it switches back to sibling level."
6549 (interactive)
6550 (let ((org-adapt-indentation nil))
6551 (when (org-point-at-end-of-empty-headline)
6552 (setq this-command 'org-cycle-level) ; Only needed for caching
6553 (let ((cur-level (org-current-level))
6554 (prev-level (org-get-previous-line-level)))
6555 (cond
6556 ;; If first headline in file, promote to top-level.
6557 ((= prev-level 0)
6558 (loop repeat (/ (- cur-level 1) (org-level-increment))
6559 do (org-do-promote)))
6560 ;; If same level as prev, demote one.
6561 ((= prev-level cur-level)
6562 (org-do-demote))
6563 ;; If parent is top-level, promote to top level if not already.
6564 ((= prev-level 1)
6565 (loop repeat (/ (- cur-level 1) (org-level-increment))
6566 do (org-do-promote)))
6567 ;; If top-level, return to prev-level.
6568 ((= cur-level 1)
6569 (loop repeat (/ (- prev-level 1) (org-level-increment))
6570 do (org-do-demote)))
6571 ;; If less than prev-level, promote one.
6572 ((< cur-level prev-level)
6573 (org-do-promote))
6574 ;; If deeper than prev-level, promote until higher than
6575 ;; prev-level.
6576 ((> cur-level prev-level)
6577 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
6578 do (org-do-promote))))
6579 t))))
6581 (defun org-map-tree (fun)
6582 "Call FUN for every heading underneath the current one."
6583 (org-back-to-heading)
6584 (let ((level (funcall outline-level)))
6585 (save-excursion
6586 (funcall fun)
6587 (while (and (progn
6588 (outline-next-heading)
6589 (> (funcall outline-level) level))
6590 (not (eobp)))
6591 (funcall fun)))))
6593 (defun org-map-region (fun beg end)
6594 "Call FUN for every heading between BEG and END."
6595 (let ((org-ignore-region t))
6596 (save-excursion
6597 (setq end (copy-marker end))
6598 (goto-char beg)
6599 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6600 (< (point) end))
6601 (funcall fun))
6602 (while (and (progn
6603 (outline-next-heading)
6604 (< (point) end))
6605 (not (eobp)))
6606 (funcall fun)))))
6608 (defun org-fixup-indentation (diff)
6609 "Change the indentation in the current entry by DIFF
6610 However, if any line in the current entry has no indentation, or if it
6611 would end up with no indentation after the change, nothing at all is done."
6612 (save-excursion
6613 (let ((end (save-excursion (outline-next-heading)
6614 (point-marker)))
6615 (prohibit (if (> diff 0)
6616 "^\\S-"
6617 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6618 col)
6619 (unless (save-excursion (end-of-line 1)
6620 (re-search-forward prohibit end t))
6621 (while (and (< (point) end)
6622 (re-search-forward "^[ \t]+" end t))
6623 (goto-char (match-end 0))
6624 (setq col (current-column))
6625 (if (< diff 0) (replace-match ""))
6626 (org-indent-to-column (+ diff col))))
6627 (move-marker end nil))))
6629 (defun org-convert-to-odd-levels ()
6630 "Convert an org-mode file with all levels allowed to one with odd levels.
6631 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6632 level 5 etc."
6633 (interactive)
6634 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6635 (let ((outline-regexp org-outline-regexp)
6636 (outline-level 'org-outline-level)
6637 (org-odd-levels-only nil) n)
6638 (save-excursion
6639 (goto-char (point-min))
6640 (while (re-search-forward "^\\*\\*+ " nil t)
6641 (setq n (- (length (match-string 0)) 2))
6642 (while (>= (setq n (1- n)) 0)
6643 (org-demote))
6644 (end-of-line 1))))))
6646 (defun org-convert-to-oddeven-levels ()
6647 "Convert an org-mode file with only odd levels to one with odd and even levels.
6648 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6649 section with an even level, conversion would destroy the structure of the file. An error
6650 is signaled in this case."
6651 (interactive)
6652 (goto-char (point-min))
6653 ;; First check if there are no even levels
6654 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6655 (org-show-context t)
6656 (error "Not all levels are odd in this file. Conversion not possible"))
6657 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6658 (let ((outline-regexp org-outline-regexp)
6659 (outline-level 'org-outline-level)
6660 (org-odd-levels-only nil) n)
6661 (save-excursion
6662 (goto-char (point-min))
6663 (while (re-search-forward "^\\*\\*+ " nil t)
6664 (setq n (/ (1- (length (match-string 0))) 2))
6665 (while (>= (setq n (1- n)) 0)
6666 (org-promote))
6667 (end-of-line 1))))))
6669 (defun org-tr-level (n)
6670 "Make N odd if required."
6671 (if org-odd-levels-only (1+ (/ n 2)) n))
6673 ;;; Vertical tree motion, cutting and pasting of subtrees
6675 (defun org-move-subtree-up (&optional arg)
6676 "Move the current subtree up past ARG headlines of the same level."
6677 (interactive "p")
6678 (org-move-subtree-down (- (prefix-numeric-value arg))))
6680 (defun org-move-subtree-down (&optional arg)
6681 "Move the current subtree down past ARG headlines of the same level."
6682 (interactive "p")
6683 (setq arg (prefix-numeric-value arg))
6684 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6685 'org-get-last-sibling))
6686 (ins-point (make-marker))
6687 (cnt (abs arg))
6688 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6689 ;; Select the tree
6690 (org-back-to-heading)
6691 (setq beg0 (point))
6692 (save-excursion
6693 (setq ne-beg (org-back-over-empty-lines))
6694 (setq beg (point)))
6695 (save-match-data
6696 (save-excursion (outline-end-of-heading)
6697 (setq folded (org-invisible-p)))
6698 (outline-end-of-subtree))
6699 (outline-next-heading)
6700 (setq ne-end (org-back-over-empty-lines))
6701 (setq end (point))
6702 (goto-char beg0)
6703 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6704 ;; include less whitespace
6705 (save-excursion
6706 (goto-char beg)
6707 (forward-line (- ne-beg ne-end))
6708 (setq beg (point))))
6709 ;; Find insertion point, with error handling
6710 (while (> cnt 0)
6711 (or (and (funcall movfunc) (looking-at outline-regexp))
6712 (progn (goto-char beg0)
6713 (error "Cannot move past superior level or buffer limit")))
6714 (setq cnt (1- cnt)))
6715 (if (> arg 0)
6716 ;; Moving forward - still need to move over subtree
6717 (progn (org-end-of-subtree t t)
6718 (save-excursion
6719 (org-back-over-empty-lines)
6720 (or (bolp) (newline)))))
6721 (setq ne-ins (org-back-over-empty-lines))
6722 (move-marker ins-point (point))
6723 (setq txt (buffer-substring beg end))
6724 (org-save-markers-in-region beg end)
6725 (delete-region beg end)
6726 (org-remove-empty-overlays-at beg)
6727 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6728 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6729 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6730 (let ((bbb (point)))
6731 (insert-before-markers txt)
6732 (org-reinstall-markers-in-region bbb)
6733 (move-marker ins-point bbb))
6734 (or (bolp) (insert "\n"))
6735 (setq ins-end (point))
6736 (goto-char ins-point)
6737 (org-skip-whitespace)
6738 (when (and (< arg 0)
6739 (org-first-sibling-p)
6740 (> ne-ins ne-beg))
6741 ;; Move whitespace back to beginning
6742 (save-excursion
6743 (goto-char ins-end)
6744 (let ((kill-whole-line t))
6745 (kill-line (- ne-ins ne-beg)) (point)))
6746 (insert (make-string (- ne-ins ne-beg) ?\n)))
6747 (move-marker ins-point nil)
6748 (if folded
6749 (hide-subtree)
6750 (org-show-entry)
6751 (show-children)
6752 (org-cycle-hide-drawers 'children))
6753 (org-clean-visibility-after-subtree-move)))
6755 (defvar org-subtree-clip ""
6756 "Clipboard for cut and paste of subtrees.
6757 This is actually only a copy of the kill, because we use the normal kill
6758 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6760 (defvar org-subtree-clip-folded nil
6761 "Was the last copied subtree folded?
6762 This is used to fold the tree back after pasting.")
6764 (defun org-cut-subtree (&optional n)
6765 "Cut the current subtree into the clipboard.
6766 With prefix arg N, cut this many sequential subtrees.
6767 This is a short-hand for marking the subtree and then cutting it."
6768 (interactive "p")
6769 (org-copy-subtree n 'cut))
6771 (defun org-copy-subtree (&optional n cut force-store-markers)
6772 "Cut the current subtree into the clipboard.
6773 With prefix arg N, cut this many sequential subtrees.
6774 This is a short-hand for marking the subtree and then copying it.
6775 If CUT is non-nil, actually cut the subtree.
6776 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6777 of some markers in the region, even if CUT is non-nil. This is
6778 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6779 (interactive "p")
6780 (let (beg end folded (beg0 (point)))
6781 (if (interactive-p)
6782 (org-back-to-heading nil) ; take what looks like a subtree
6783 (org-back-to-heading t)) ; take what is really there
6784 (org-back-over-empty-lines)
6785 (setq beg (point))
6786 (skip-chars-forward " \t\r\n")
6787 (save-match-data
6788 (save-excursion (outline-end-of-heading)
6789 (setq folded (org-invisible-p)))
6790 (condition-case nil
6791 (org-forward-same-level (1- n) t)
6792 (error nil))
6793 (org-end-of-subtree t t))
6794 (org-back-over-empty-lines)
6795 (setq end (point))
6796 (goto-char beg0)
6797 (when (> end beg)
6798 (setq org-subtree-clip-folded folded)
6799 (when (or cut force-store-markers)
6800 (org-save-markers-in-region beg end))
6801 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6802 (setq org-subtree-clip (current-kill 0))
6803 (message "%s: Subtree(s) with %d characters"
6804 (if cut "Cut" "Copied")
6805 (length org-subtree-clip)))))
6807 (defun org-paste-subtree (&optional level tree for-yank)
6808 "Paste the clipboard as a subtree, with modification of headline level.
6809 The entire subtree is promoted or demoted in order to match a new headline
6810 level.
6812 If the cursor is at the beginning of a headline, the same level as
6813 that headline is used to paste the tree
6815 If not, the new level is derived from the *visible* headings
6816 before and after the insertion point, and taken to be the inferior headline
6817 level of the two. So if the previous visible heading is level 3 and the
6818 next is level 4 (or vice versa), level 4 will be used for insertion.
6819 This makes sure that the subtree remains an independent subtree and does
6820 not swallow low level entries.
6822 You can also force a different level, either by using a numeric prefix
6823 argument, or by inserting the heading marker by hand. For example, if the
6824 cursor is after \"*****\", then the tree will be shifted to level 5.
6826 If optional TREE is given, use this text instead of the kill ring.
6828 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6829 move back over whitespace before inserting, and move point to the end of
6830 the inserted text when done."
6831 (interactive "P")
6832 (setq tree (or tree (and kill-ring (current-kill 0))))
6833 (unless (org-kill-is-subtree-p tree)
6834 (error "%s"
6835 (substitute-command-keys
6836 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6837 (let* ((visp (not (org-invisible-p)))
6838 (txt tree)
6839 (^re (concat "^\\(" outline-regexp "\\)"))
6840 (re (concat "\\(" outline-regexp "\\)"))
6841 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6843 (old-level (if (string-match ^re txt)
6844 (- (match-end 0) (match-beginning 0) 1)
6845 -1))
6846 (force-level (cond (level (prefix-numeric-value level))
6847 ((and (looking-at "[ \t]*$")
6848 (string-match
6849 ^re_ (buffer-substring
6850 (point-at-bol) (point))))
6851 (- (match-end 1) (match-beginning 1)))
6852 ((and (bolp)
6853 (looking-at org-outline-regexp))
6854 (- (match-end 0) (point) 1))
6855 (t nil)))
6856 (previous-level (save-excursion
6857 (condition-case nil
6858 (progn
6859 (outline-previous-visible-heading 1)
6860 (if (looking-at re)
6861 (- (match-end 0) (match-beginning 0) 1)
6863 (error 1))))
6864 (next-level (save-excursion
6865 (condition-case nil
6866 (progn
6867 (or (looking-at outline-regexp)
6868 (outline-next-visible-heading 1))
6869 (if (looking-at re)
6870 (- (match-end 0) (match-beginning 0) 1)
6872 (error 1))))
6873 (new-level (or force-level (max previous-level next-level)))
6874 (shift (if (or (= old-level -1)
6875 (= new-level -1)
6876 (= old-level new-level))
6878 (- new-level old-level)))
6879 (delta (if (> shift 0) -1 1))
6880 (func (if (> shift 0) 'org-demote 'org-promote))
6881 (org-odd-levels-only nil)
6882 beg end newend)
6883 ;; Remove the forced level indicator
6884 (if force-level
6885 (delete-region (point-at-bol) (point)))
6886 ;; Paste
6887 (beginning-of-line 1)
6888 (unless for-yank (org-back-over-empty-lines))
6889 (setq beg (point))
6890 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6891 (insert-before-markers txt)
6892 (unless (string-match "\n\\'" txt) (insert "\n"))
6893 (setq newend (point))
6894 (org-reinstall-markers-in-region beg)
6895 (setq end (point))
6896 (goto-char beg)
6897 (skip-chars-forward " \t\n\r")
6898 (setq beg (point))
6899 (if (and (org-invisible-p) visp)
6900 (save-excursion (outline-show-heading)))
6901 ;; Shift if necessary
6902 (unless (= shift 0)
6903 (save-restriction
6904 (narrow-to-region beg end)
6905 (while (not (= shift 0))
6906 (org-map-region func (point-min) (point-max))
6907 (setq shift (+ delta shift)))
6908 (goto-char (point-min))
6909 (setq newend (point-max))))
6910 (when (or (interactive-p) for-yank)
6911 (message "Clipboard pasted as level %d subtree" new-level))
6912 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6913 kill-ring
6914 (eq org-subtree-clip (current-kill 0))
6915 org-subtree-clip-folded)
6916 ;; The tree was folded before it was killed/copied
6917 (hide-subtree))
6918 (and for-yank (goto-char newend))))
6920 (defun org-kill-is-subtree-p (&optional txt)
6921 "Check if the current kill is an outline subtree, or a set of trees.
6922 Returns nil if kill does not start with a headline, or if the first
6923 headline level is not the largest headline level in the tree.
6924 So this will actually accept several entries of equal levels as well,
6925 which is OK for `org-paste-subtree'.
6926 If optional TXT is given, check this string instead of the current kill."
6927 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6928 (start-level (and kill
6929 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6930 org-outline-regexp "\\)")
6931 kill)
6932 (- (match-end 2) (match-beginning 2) 1)))
6933 (re (concat "^" org-outline-regexp))
6934 (start (1+ (or (match-beginning 2) -1))))
6935 (if (not start-level)
6936 (progn
6937 nil) ;; does not even start with a heading
6938 (catch 'exit
6939 (while (setq start (string-match re kill (1+ start)))
6940 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6941 (throw 'exit nil)))
6942 t))))
6944 (defvar org-markers-to-move nil
6945 "Markers that should be moved with a cut-and-paste operation.
6946 Those markers are stored together with their positions relative to
6947 the start of the region.")
6949 (defun org-save-markers-in-region (beg end)
6950 "Check markers in region.
6951 If these markers are between BEG and END, record their position relative
6952 to BEG, so that after moving the block of text, we can put the markers back
6953 into place.
6954 This function gets called just before an entry or tree gets cut from the
6955 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6956 called immediately, to move the markers with the entries."
6957 (setq org-markers-to-move nil)
6958 (when (featurep 'org-clock)
6959 (org-clock-save-markers-for-cut-and-paste beg end))
6960 (when (featurep 'org-agenda)
6961 (org-agenda-save-markers-for-cut-and-paste beg end)))
6963 (defun org-check-and-save-marker (marker beg end)
6964 "Check if MARKER is between BEG and END.
6965 If yes, remember the marker and the distance to BEG."
6966 (when (and (marker-buffer marker)
6967 (equal (marker-buffer marker) (current-buffer)))
6968 (if (and (>= marker beg) (< marker end))
6969 (push (cons marker (- marker beg)) org-markers-to-move))))
6971 (defun org-reinstall-markers-in-region (beg)
6972 "Move all remembered markers to their position relative to BEG."
6973 (mapc (lambda (x)
6974 (move-marker (car x) (+ beg (cdr x))))
6975 org-markers-to-move)
6976 (setq org-markers-to-move nil))
6978 (defun org-narrow-to-subtree ()
6979 "Narrow buffer to the current subtree."
6980 (interactive)
6981 (save-excursion
6982 (save-match-data
6983 (narrow-to-region
6984 (progn (org-back-to-heading t) (point))
6985 (progn (org-end-of-subtree t t)
6986 (if (org-on-heading-p) (backward-char 1))
6987 (point))))))
6989 (defun org-clone-subtree-with-time-shift (n &optional shift)
6990 "Clone the task (subtree) at point N times.
6991 The clones will be inserted as siblings.
6993 In interactive use, the user will be prompted for the number of clones
6994 to be produced, and for a time SHIFT, which may be a repeater as used
6995 in time stamps, for example `+3d'.
6997 When a valid repeater is given and the entry contains any time stamps,
6998 the clones will become a sequence in time, with time stamps in the
6999 subtree shifted for each clone produced. If SHIFT is nil or the
7000 empty string, time stamps will be left alone.
7002 If the original subtree did contain time stamps with a repeater,
7003 the following will happen:
7004 - the repeater will be removed in each clone
7005 - an additional clone will be produced, with the current, unshifted
7006 date(s) in the entry.
7007 - the original entry will be placed *after* all the clones, with
7008 repeater intact.
7009 - the start days in the repeater in the original entry will be shifted
7010 to past the last clone.
7011 I this way you can spell out a number of instances of a repeating task,
7012 and still retain the repeater to cover future instances of the task."
7013 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7014 (let (beg end template task
7015 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7016 (if (not (and (integerp n) (> n 0)))
7017 (error "Invalid number of replications %s" n))
7018 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7019 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7020 shift)))
7021 (error "Invalid shift specification %s" shift))
7022 (when doshift
7023 (setq shift-n (string-to-number (match-string 1 shift))
7024 shift-what (cdr (assoc (match-string 2 shift)
7025 '(("d" . day) ("w" . week)
7026 ("m" . month) ("y" . year))))))
7027 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7028 (setq nmin 1 nmax n)
7029 (org-back-to-heading t)
7030 (setq beg (point))
7031 (org-end-of-subtree t t)
7032 (or (bolp) (insert "\n"))
7033 (setq end (point))
7034 (setq template (buffer-substring beg end))
7035 (when (and doshift
7036 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7037 (delete-region beg end)
7038 (setq end beg)
7039 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7040 (goto-char end)
7041 (loop for n from nmin to nmax do
7042 (if (not doshift)
7043 (setq task template)
7044 (with-temp-buffer
7045 (insert template)
7046 (org-mode)
7047 (goto-char (point-min))
7048 (while (re-search-forward org-ts-regexp-both nil t)
7049 (org-timestamp-change (* n shift-n) shift-what))
7050 (unless (= n n-no-remove)
7051 (goto-char (point-min))
7052 (while (re-search-forward org-ts-regexp nil t)
7053 (save-excursion
7054 (goto-char (match-beginning 0))
7055 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7056 (delete-region (match-beginning 1) (match-end 1))))))
7057 (setq task (buffer-string))))
7058 (insert task))
7059 (goto-char beg)))
7061 ;;; Outline Sorting
7063 (defun org-sort (with-case)
7064 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
7065 Optional argument WITH-CASE means sort case-sensitively.
7066 With a double prefix argument, also remove duplicate entries."
7067 (interactive "P")
7068 (if (org-at-table-p)
7069 (org-call-with-arg 'org-table-sort-lines with-case)
7070 (org-call-with-arg 'org-sort-entries-or-items with-case)))
7072 (defun org-sort-remove-invisible (s)
7073 (remove-text-properties 0 (length s) org-rm-props s)
7074 (while (string-match org-bracket-link-regexp s)
7075 (setq s (replace-match (if (match-end 2)
7076 (match-string 3 s)
7077 (match-string 1 s)) t t s)))
7080 (defvar org-priority-regexp) ; defined later in the file
7082 (defvar org-after-sorting-entries-or-items-hook nil
7083 "Hook that is run after a bunch of entries or items have been sorted.
7084 When children are sorted, the cursor is in the parent line when this
7085 hook gets called. When a region or a plain list is sorted, the cursor
7086 will be in the first entry of the sorted region/list.")
7088 (defun org-sort-entries-or-items
7089 (&optional with-case sorting-type getkey-func compare-func property)
7090 "Sort entries on a certain level of an outline tree, or plain list items.
7091 If there is an active region, the entries in the region are sorted.
7092 Else, if the cursor is before the first entry, sort the top-level items.
7093 Else, the children of the entry at point are sorted.
7094 If the cursor is at the first item in a plain list, the list items will be
7095 sorted.
7097 Sorting can be alphabetically, numerically, by date/time as given by
7098 a time stamp, by a property or by priority.
7100 The command prompts for the sorting type unless it has been given to the
7101 function through the SORTING-TYPE argument, which needs to a character,
7102 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7103 precise meaning of each character:
7105 n Numerically, by converting the beginning of the entry/item to a number.
7106 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7107 t By date/time, either the first active time stamp in the entry, or, if
7108 none exist, by the first inactive one.
7109 In items, only the first line will be checked.
7110 s By the scheduled date/time.
7111 d By deadline date/time.
7112 c By creation time, which is assumed to be the first inactive time stamp
7113 at the beginning of a line.
7114 p By priority according to the cookie.
7115 r By the value of a property.
7117 Capital letters will reverse the sort order.
7119 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7120 called with point at the beginning of the record. It must return either
7121 a string or a number that should serve as the sorting key for that record.
7123 Comparing entries ignores case by default. However, with an optional argument
7124 WITH-CASE, the sorting considers case as well."
7125 (interactive "P")
7126 (let ((case-func (if with-case 'identity 'downcase))
7127 start beg end stars re re2
7128 txt what tmp plain-list-p)
7129 ;; Find beginning and end of region to sort
7130 (cond
7131 ((org-region-active-p)
7132 ;; we will sort the region
7133 (setq end (region-end)
7134 what "region")
7135 (goto-char (region-beginning))
7136 (if (not (org-on-heading-p)) (outline-next-heading))
7137 (setq start (point)))
7138 ((org-at-item-p)
7139 ;; we will sort this plain list
7140 (org-beginning-of-item-list) (setq start (point))
7141 (org-end-of-item-list)
7142 (or (bolp) (insert "\n"))
7143 (setq end (point))
7144 (goto-char start)
7145 (setq plain-list-p t
7146 what "plain list"))
7147 ((or (org-on-heading-p)
7148 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7149 ;; we will sort the children of the current headline
7150 (org-back-to-heading)
7151 (setq start (point)
7152 end (progn (org-end-of-subtree t t)
7153 (or (bolp) (insert "\n"))
7154 (org-back-over-empty-lines)
7155 (point))
7156 what "children")
7157 (goto-char start)
7158 (show-subtree)
7159 (outline-next-heading))
7161 ;; we will sort the top-level entries in this file
7162 (goto-char (point-min))
7163 (or (org-on-heading-p) (outline-next-heading))
7164 (setq start (point))
7165 (goto-char (point-max))
7166 (beginning-of-line 1)
7167 (when (looking-at ".*?\\S-")
7168 ;; File ends in a non-white line
7169 (end-of-line 1)
7170 (insert "\n"))
7171 (setq end (point-max))
7172 (setq what "top-level")
7173 (goto-char start)
7174 (show-all)))
7176 (setq beg (point))
7177 (if (>= beg end) (error "Nothing to sort"))
7179 (unless plain-list-p
7180 (looking-at "\\(\\*+\\)")
7181 (setq stars (match-string 1)
7182 re (concat "^" (regexp-quote stars) " +")
7183 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7184 txt (buffer-substring beg end))
7185 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7186 (if (and (not (equal stars "*")) (string-match re2 txt))
7187 (error "Region to sort contains a level above the first entry")))
7189 (unless sorting-type
7190 (message
7191 (if plain-list-p
7192 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7193 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7194 [t]ime [s]cheduled [d]eadline [c]reated
7195 A/N/T/S/D/C/P/O/F means reversed:")
7196 what)
7197 (setq sorting-type (read-char-exclusive))
7199 (and (= (downcase sorting-type) ?f)
7200 (setq getkey-func
7201 (org-icompleting-read "Sort using function: "
7202 obarray 'fboundp t nil nil))
7203 (setq getkey-func (intern getkey-func)))
7205 (and (= (downcase sorting-type) ?r)
7206 (setq property
7207 (org-icompleting-read "Property: "
7208 (mapcar 'list (org-buffer-property-keys t))
7209 nil t))))
7211 (message "Sorting entries...")
7213 (save-restriction
7214 (narrow-to-region start end)
7216 (let ((dcst (downcase sorting-type))
7217 (case-fold-search nil)
7218 (now (current-time)))
7219 (sort-subr
7220 (/= dcst sorting-type)
7221 ;; This function moves to the beginning character of the "record" to
7222 ;; be sorted.
7223 (if plain-list-p
7224 (lambda nil
7225 (if (org-at-item-p) t (goto-char (point-max))))
7226 (lambda nil
7227 (if (re-search-forward re nil t)
7228 (goto-char (match-beginning 0))
7229 (goto-char (point-max)))))
7230 ;; This function moves to the last character of the "record" being
7231 ;; sorted.
7232 (if plain-list-p
7233 'org-end-of-item
7234 (lambda nil
7235 (save-match-data
7236 (condition-case nil
7237 (outline-forward-same-level 1)
7238 (error
7239 (goto-char (point-max)))))))
7241 ;; This function returns the value that gets sorted against.
7242 (if plain-list-p
7243 (lambda nil
7244 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7245 (cond
7246 ((= dcst ?n)
7247 (string-to-number (buffer-substring (match-end 0)
7248 (point-at-eol))))
7249 ((= dcst ?a)
7250 (buffer-substring (match-end 0) (point-at-eol)))
7251 ((= dcst ?t)
7252 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7253 (re-search-forward org-ts-regexp-both
7254 (point-at-eol) t))
7255 (org-time-string-to-seconds (match-string 0))
7256 (org-float-time now)))
7257 ((= dcst ?f)
7258 (if getkey-func
7259 (progn
7260 (setq tmp (funcall getkey-func))
7261 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7262 tmp)
7263 (error "Invalid key function `%s'" getkey-func)))
7264 (t (error "Invalid sorting type `%c'" sorting-type)))))
7265 (lambda nil
7266 (cond
7267 ((= dcst ?n)
7268 (if (looking-at org-complex-heading-regexp)
7269 (string-to-number (match-string 4))
7270 nil))
7271 ((= dcst ?a)
7272 (if (looking-at org-complex-heading-regexp)
7273 (funcall case-func (match-string 4))
7274 nil))
7275 ((= dcst ?t)
7276 (let ((end (save-excursion (outline-next-heading) (point))))
7277 (if (or (re-search-forward org-ts-regexp end t)
7278 (re-search-forward org-ts-regexp-both end t))
7279 (org-time-string-to-seconds (match-string 0))
7280 (org-float-time now))))
7281 ((= dcst ?c)
7282 (let ((end (save-excursion (outline-next-heading) (point))))
7283 (if (re-search-forward
7284 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7285 end t)
7286 (org-time-string-to-seconds (match-string 0))
7287 (org-float-time now))))
7288 ((= dcst ?s)
7289 (let ((end (save-excursion (outline-next-heading) (point))))
7290 (if (re-search-forward org-scheduled-time-regexp end t)
7291 (org-time-string-to-seconds (match-string 1))
7292 (org-float-time now))))
7293 ((= dcst ?d)
7294 (let ((end (save-excursion (outline-next-heading) (point))))
7295 (if (re-search-forward org-deadline-time-regexp end t)
7296 (org-time-string-to-seconds (match-string 1))
7297 (org-float-time now))))
7298 ((= dcst ?p)
7299 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7300 (string-to-char (match-string 2))
7301 org-default-priority))
7302 ((= dcst ?r)
7303 (or (org-entry-get nil property) ""))
7304 ((= dcst ?o)
7305 (if (looking-at org-complex-heading-regexp)
7306 (- 9999 (length (member (match-string 2)
7307 org-todo-keywords-1)))))
7308 ((= dcst ?f)
7309 (if getkey-func
7310 (progn
7311 (setq tmp (funcall getkey-func))
7312 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7313 tmp)
7314 (error "Invalid key function `%s'" getkey-func)))
7315 (t (error "Invalid sorting type `%c'" sorting-type)))))
7317 (cond
7318 ((= dcst ?a) 'string<)
7319 ((= dcst ?f) compare-func)
7320 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7321 (t nil)))))
7322 (run-hooks 'org-after-sorting-entries-or-items-hook)
7323 (message "Sorting entries...done")))
7325 (defun org-do-sort (table what &optional with-case sorting-type)
7326 "Sort TABLE of WHAT according to SORTING-TYPE.
7327 The user will be prompted for the SORTING-TYPE if the call to this
7328 function does not specify it. WHAT is only for the prompt, to indicate
7329 what is being sorted. The sorting key will be extracted from
7330 the car of the elements of the table.
7331 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7332 (unless sorting-type
7333 (message
7334 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7335 what)
7336 (setq sorting-type (read-char-exclusive)))
7337 (let ((dcst (downcase sorting-type))
7338 extractfun comparefun)
7339 ;; Define the appropriate functions
7340 (cond
7341 ((= dcst ?n)
7342 (setq extractfun 'string-to-number
7343 comparefun (if (= dcst sorting-type) '< '>)))
7344 ((= dcst ?a)
7345 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7346 (lambda(x) (downcase (org-sort-remove-invisible x))))
7347 comparefun (if (= dcst sorting-type)
7348 'string<
7349 (lambda (a b) (and (not (string< a b))
7350 (not (string= a b)))))))
7351 ((= dcst ?t)
7352 (setq extractfun
7353 (lambda (x)
7354 (if (or (string-match org-ts-regexp x)
7355 (string-match org-ts-regexp-both x))
7356 (org-float-time
7357 (org-time-string-to-time (match-string 0 x)))
7359 comparefun (if (= dcst sorting-type) '< '>)))
7360 (t (error "Invalid sorting type `%c'" sorting-type)))
7362 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7363 table)
7364 (lambda (a b) (funcall comparefun (car a) (car b))))))
7367 ;;; The orgstruct minor mode
7369 ;; Define a minor mode which can be used in other modes in order to
7370 ;; integrate the org-mode structure editing commands.
7372 ;; This is really a hack, because the org-mode structure commands use
7373 ;; keys which normally belong to the major mode. Here is how it
7374 ;; works: The minor mode defines all the keys necessary to operate the
7375 ;; structure commands, but wraps the commands into a function which
7376 ;; tests if the cursor is currently at a headline or a plain list
7377 ;; item. If that is the case, the structure command is used,
7378 ;; temporarily setting many Org-mode variables like regular
7379 ;; expressions for filling etc. However, when any of those keys is
7380 ;; used at a different location, function uses `key-binding' to look
7381 ;; up if the key has an associated command in another currently active
7382 ;; keymap (minor modes, major mode, global), and executes that
7383 ;; command. There might be problems if any of the keys is otherwise
7384 ;; used as a prefix key.
7386 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7387 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7388 ;; addresses this by checking explicitly for both bindings.
7390 (defvar orgstruct-mode-map (make-sparse-keymap)
7391 "Keymap for the minor `orgstruct-mode'.")
7393 (defvar org-local-vars nil
7394 "List of local variables, for use by `orgstruct-mode'")
7396 ;;;###autoload
7397 (define-minor-mode orgstruct-mode
7398 "Toggle the minor more `orgstruct-mode'.
7399 This mode is for using Org-mode structure commands in other modes.
7400 The following key behave as if Org-mode was active, if the cursor
7401 is on a headline, or on a plain list item (both in the definition
7402 of Org-mode).
7404 M-up Move entry/item up
7405 M-down Move entry/item down
7406 M-left Promote
7407 M-right Demote
7408 M-S-up Move entry/item up
7409 M-S-down Move entry/item down
7410 M-S-left Promote subtree
7411 M-S-right Demote subtree
7412 M-q Fill paragraph and items like in Org-mode
7413 C-c ^ Sort entries
7414 C-c - Cycle list bullet
7415 TAB Cycle item visibility
7416 M-RET Insert new heading/item
7417 S-M-RET Insert new TODO heading / Checkbox item
7418 C-c C-c Set tags / toggle checkbox"
7419 nil " OrgStruct" nil
7420 (org-load-modules-maybe)
7421 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7423 ;;;###autoload
7424 (defun turn-on-orgstruct ()
7425 "Unconditionally turn on `orgstruct-mode'."
7426 (orgstruct-mode 1))
7428 (defun orgstruct++-mode (&optional arg)
7429 "Toggle `orgstruct-mode', the enhanced version of it.
7430 In addition to setting orgstruct-mode, this also exports all indentation
7431 and autofilling variables from org-mode into the buffer. It will also
7432 recognize item context in multiline items.
7433 Note that turning off orgstruct-mode will *not* remove the
7434 indentation/paragraph settings. This can only be done by refreshing the
7435 major mode, for example with \\[normal-mode]."
7436 (interactive "P")
7437 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7438 (if (< arg 1)
7439 (orgstruct-mode -1)
7440 (orgstruct-mode 1)
7441 (let (var val)
7442 (mapc
7443 (lambda (x)
7444 (when (string-match
7445 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7446 (symbol-name (car x)))
7447 (setq var (car x) val (nth 1 x))
7448 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7449 org-local-vars)
7450 (org-set-local 'orgstruct-is-++ t))))
7452 (defvar orgstruct-is-++ nil
7453 "Is orgstruct-mode in ++ version in the current-buffer?")
7454 (make-variable-buffer-local 'orgstruct-is-++)
7456 ;;;###autoload
7457 (defun turn-on-orgstruct++ ()
7458 "Unconditionally turn on `orgstruct++-mode'."
7459 (orgstruct++-mode 1))
7461 (defun orgstruct-error ()
7462 "Error when there is no default binding for a structure key."
7463 (interactive)
7464 (error "This key has no function outside structure elements"))
7466 (defun orgstruct-setup ()
7467 "Setup orgstruct keymaps."
7468 (let ((nfunc 0)
7469 (bindings
7470 (list
7471 '([(meta up)] org-metaup)
7472 '([(meta down)] org-metadown)
7473 '([(meta left)] org-metaleft)
7474 '([(meta right)] org-metaright)
7475 '([(meta shift up)] org-shiftmetaup)
7476 '([(meta shift down)] org-shiftmetadown)
7477 '([(meta shift left)] org-shiftmetaleft)
7478 '([(meta shift right)] org-shiftmetaright)
7479 '([?\e (up)] org-metaup)
7480 '([?\e (down)] org-metadown)
7481 '([?\e (left)] org-metaleft)
7482 '([?\e (right)] org-metaright)
7483 '([?\e (shift up)] org-shiftmetaup)
7484 '([?\e (shift down)] org-shiftmetadown)
7485 '([?\e (shift left)] org-shiftmetaleft)
7486 '([?\e (shift right)] org-shiftmetaright)
7487 '([(shift up)] org-shiftup)
7488 '([(shift down)] org-shiftdown)
7489 '([(shift left)] org-shiftleft)
7490 '([(shift right)] org-shiftright)
7491 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7492 '("\M-q" fill-paragraph)
7493 '("\C-c^" org-sort)
7494 '("\C-c-" org-cycle-list-bullet)))
7495 elt key fun cmd)
7496 (while (setq elt (pop bindings))
7497 (setq nfunc (1+ nfunc))
7498 (setq key (org-key (car elt))
7499 fun (nth 1 elt)
7500 cmd (orgstruct-make-binding fun nfunc key))
7501 (org-defkey orgstruct-mode-map key cmd))
7503 ;; Special treatment needed for TAB and RET
7504 (org-defkey orgstruct-mode-map [(tab)]
7505 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7506 (org-defkey orgstruct-mode-map "\C-i"
7507 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7509 (org-defkey orgstruct-mode-map "\M-\C-m"
7510 (orgstruct-make-binding 'org-insert-heading 105
7511 "\M-\C-m" [(meta return)]))
7512 (org-defkey orgstruct-mode-map [(meta return)]
7513 (orgstruct-make-binding 'org-insert-heading 106
7514 [(meta return)] "\M-\C-m"))
7516 (org-defkey orgstruct-mode-map [(shift meta return)]
7517 (orgstruct-make-binding 'org-insert-todo-heading 107
7518 [(meta return)] "\M-\C-m"))
7520 (org-defkey orgstruct-mode-map "\e\C-m"
7521 (orgstruct-make-binding 'org-insert-heading 108
7522 "\e\C-m" [?\e (return)]))
7523 (org-defkey orgstruct-mode-map [?\e (return)]
7524 (orgstruct-make-binding 'org-insert-heading 109
7525 [?\e (return)] "\e\C-m"))
7526 (org-defkey orgstruct-mode-map [?\e (shift return)]
7527 (orgstruct-make-binding 'org-insert-todo-heading 110
7528 [?\e (return)] "\e\C-m"))
7530 (unless org-local-vars
7531 (setq org-local-vars (org-get-local-variables)))
7535 (defun orgstruct-make-binding (fun n &rest keys)
7536 "Create a function for binding in the structure minor mode.
7537 FUN is the command to call inside a table. N is used to create a unique
7538 command name. KEYS are keys that should be checked in for a command
7539 to execute outside of tables."
7540 (eval
7541 (list 'defun
7542 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7543 '(arg)
7544 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7545 "Outside of structure, run the binding of `"
7546 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7547 "'.")
7548 '(interactive "p")
7549 (list 'if
7550 `(org-context-p 'headline 'item
7551 (and orgstruct-is-++
7552 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7553 'item-body))
7554 (list 'org-run-like-in-org-mode (list 'quote fun))
7555 (list 'let '(orgstruct-mode)
7556 (list 'call-interactively
7557 (append '(or)
7558 (mapcar (lambda (k)
7559 (list 'key-binding k))
7560 keys)
7561 '('orgstruct-error))))))))
7563 (defun org-context-p (&rest contexts)
7564 "Check if local context is any of CONTEXTS.
7565 Possible values in the list of contexts are `table', `headline', and `item'."
7566 (let ((pos (point)))
7567 (goto-char (point-at-bol))
7568 (prog1 (or (and (memq 'table contexts)
7569 (looking-at "[ \t]*|"))
7570 (and (memq 'headline contexts)
7571 ;;????????? (looking-at "\\*+"))
7572 (looking-at outline-regexp))
7573 (and (memq 'item contexts)
7574 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7575 (and (memq 'item-body contexts)
7576 (org-in-item-p)))
7577 (goto-char pos))))
7579 (defun org-get-local-variables ()
7580 "Return a list of all local variables in an org-mode buffer."
7581 (let (varlist)
7582 (with-current-buffer (get-buffer-create "*Org tmp*")
7583 (erase-buffer)
7584 (org-mode)
7585 (setq varlist (buffer-local-variables)))
7586 (kill-buffer "*Org tmp*")
7587 (delq nil
7588 (mapcar
7589 (lambda (x)
7590 (setq x
7591 (if (symbolp x)
7592 (list x)
7593 (list (car x) (list 'quote (cdr x)))))
7594 (if (string-match
7595 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7596 (symbol-name (car x)))
7597 x nil))
7598 varlist))))
7600 ;;;###autoload
7601 (defun org-run-like-in-org-mode (cmd)
7602 "Run a command, pretending that the current buffer is in Org-mode.
7603 This will temporarily bind local variables that are typically bound in
7604 Org-mode to the values they have in Org-mode, and then interactively
7605 call CMD."
7606 (org-load-modules-maybe)
7607 (unless org-local-vars
7608 (setq org-local-vars (org-get-local-variables)))
7609 (eval (list 'let org-local-vars
7610 (list 'call-interactively (list 'quote cmd)))))
7612 ;;;; Archiving
7614 (defun org-get-category (&optional pos)
7615 "Get the category applying to position POS."
7616 (get-text-property (or pos (point)) 'org-category))
7618 (defun org-refresh-category-properties ()
7619 "Refresh category text properties in the buffer."
7620 (let ((def-cat (cond
7621 ((null org-category)
7622 (if buffer-file-name
7623 (file-name-sans-extension
7624 (file-name-nondirectory buffer-file-name))
7625 "???"))
7626 ((symbolp org-category) (symbol-name org-category))
7627 (t org-category)))
7628 beg end cat pos optionp)
7629 (org-unmodified
7630 (save-excursion
7631 (save-restriction
7632 (widen)
7633 (goto-char (point-min))
7634 (put-text-property (point) (point-max) 'org-category def-cat)
7635 (while (re-search-forward
7636 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7637 (setq pos (match-end 0)
7638 optionp (equal (char-after (match-beginning 0)) ?#)
7639 cat (org-trim (match-string 2)))
7640 (if optionp
7641 (setq beg (point-at-bol) end (point-max))
7642 (org-back-to-heading t)
7643 (setq beg (point) end (org-end-of-subtree t t)))
7644 (put-text-property beg end 'org-category cat)
7645 (goto-char pos)))))))
7648 ;;;; Link Stuff
7650 ;;; Link abbreviations
7652 (defun org-link-expand-abbrev (link)
7653 "Apply replacements as defined in `org-link-abbrev-alist."
7654 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7655 (let* ((key (match-string 1 link))
7656 (as (or (assoc key org-link-abbrev-alist-local)
7657 (assoc key org-link-abbrev-alist)))
7658 (tag (and (match-end 2) (match-string 3 link)))
7659 rpl)
7660 (if (not as)
7661 link
7662 (setq rpl (cdr as))
7663 (cond
7664 ((symbolp rpl) (funcall rpl tag))
7665 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7666 ((string-match "%h" rpl)
7667 (replace-match (url-hexify-string (or tag "")) t t rpl))
7668 (t (concat rpl tag)))))
7669 link))
7671 ;;; Storing and inserting links
7673 (defvar org-insert-link-history nil
7674 "Minibuffer history for links inserted with `org-insert-link'.")
7676 (defvar org-stored-links nil
7677 "Contains the links stored with `org-store-link'.")
7679 (defvar org-store-link-plist nil
7680 "Plist with info about the most recently link created with `org-store-link'.")
7682 (defvar org-link-protocols nil
7683 "Link protocols added to Org-mode using `org-add-link-type'.")
7685 (defvar org-store-link-functions nil
7686 "List of functions that are called to create and store a link.
7687 Each function will be called in turn until one returns a non-nil
7688 value. Each function should check if it is responsible for creating
7689 this link (for example by looking at the major mode).
7690 If not, it must exit and return nil.
7691 If yes, it should return a non-nil value after a calling
7692 `org-store-link-props' with a list of properties and values.
7693 Special properties are:
7695 :type The link prefix. like \"http\". This must be given.
7696 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7697 This is obligatory as well.
7698 :description Optional default description for the second pair
7699 of brackets in an Org-mode link. The user can still change
7700 this when inserting this link into an Org-mode buffer.
7702 In addition to these, any additional properties can be specified
7703 and then used in remember templates.")
7705 (defun org-add-link-type (type &optional follow export)
7706 "Add TYPE to the list of `org-link-types'.
7707 Re-compute all regular expressions depending on `org-link-types'
7709 FOLLOW and EXPORT are two functions.
7711 FOLLOW should take the link path as the single argument and do whatever
7712 is necessary to follow the link, for example find a file or display
7713 a mail message.
7715 EXPORT should format the link path for export to one of the export formats.
7716 It should be a function accepting three arguments:
7718 path the path of the link, the text after the prefix (like \"http:\")
7719 desc the description of the link, if any, nil if there was no description
7720 format the export format, a symbol like `html' or `latex'.
7722 The function may use the FORMAT information to return different values
7723 depending on the format. The return value will be put literally into
7724 the exported file.
7725 Org-mode has a built-in default for exporting links. If you are happy with
7726 this default, there is no need to define an export function for the link
7727 type. For a simple example of an export function, see `org-bbdb.el'."
7728 (add-to-list 'org-link-types type t)
7729 (org-make-link-regexps)
7730 (if (assoc type org-link-protocols)
7731 (setcdr (assoc type org-link-protocols) (list follow export))
7732 (push (list type follow export) org-link-protocols)))
7734 (defvar org-agenda-buffer-name)
7736 ;;;###autoload
7737 (defun org-store-link (arg)
7738 "\\<org-mode-map>Store an org-link to the current location.
7739 This link is added to `org-stored-links' and can later be inserted
7740 into an org-buffer with \\[org-insert-link].
7742 For some link types, a prefix arg is interpreted:
7743 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7744 For file links, arg negates `org-context-in-file-links'."
7745 (interactive "P")
7746 (org-load-modules-maybe)
7747 (setq org-store-link-plist nil) ; reset
7748 (let ((outline-regexp (org-get-limited-outline-regexp))
7749 link cpltxt desc description search txt custom-id)
7750 (cond
7752 ((run-hook-with-args-until-success 'org-store-link-functions)
7753 (setq link (plist-get org-store-link-plist :link)
7754 desc (or (plist-get org-store-link-plist :description) link)))
7756 ((equal (buffer-name) "*Org Edit Src Example*")
7757 (let (label gc)
7758 (while (or (not label)
7759 (save-excursion
7760 (save-restriction
7761 (widen)
7762 (goto-char (point-min))
7763 (re-search-forward
7764 (regexp-quote (format org-coderef-label-format label))
7765 nil t))))
7766 (when label (message "Label exists already") (sit-for 2))
7767 (setq label (read-string "Code line label: " label)))
7768 (end-of-line 1)
7769 (setq link (format org-coderef-label-format label))
7770 (setq gc (- 79 (length link)))
7771 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7772 (insert link)
7773 (setq link (concat "(" label ")") desc nil)))
7775 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7776 ;; We are in the agenda, link to referenced location
7777 (let ((m (or (get-text-property (point) 'org-hd-marker)
7778 (get-text-property (point) 'org-marker))))
7779 (when m
7780 (org-with-point-at m
7781 (call-interactively 'org-store-link)))))
7783 ((eq major-mode 'calendar-mode)
7784 (let ((cd (calendar-cursor-to-date)))
7785 (setq link
7786 (format-time-string
7787 (car org-time-stamp-formats)
7788 (apply 'encode-time
7789 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7790 nil nil nil))))
7791 (org-store-link-props :type "calendar" :date cd)))
7793 ((eq major-mode 'w3-mode)
7794 (setq cpltxt (if (and (buffer-name)
7795 (not (string-match "Untitled" (buffer-name))))
7796 (buffer-name)
7797 (url-view-url t))
7798 link (org-make-link (url-view-url t)))
7799 (org-store-link-props :type "w3" :url (url-view-url t)))
7801 ((eq major-mode 'w3m-mode)
7802 (setq cpltxt (or w3m-current-title w3m-current-url)
7803 link (org-make-link w3m-current-url))
7804 (org-store-link-props :type "w3m" :url (url-view-url t)))
7806 ((setq search (run-hook-with-args-until-success
7807 'org-create-file-search-functions))
7808 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7809 "::" search))
7810 (setq cpltxt (or description link)))
7812 ((eq major-mode 'image-mode)
7813 (setq cpltxt (concat "file:"
7814 (abbreviate-file-name buffer-file-name))
7815 link (org-make-link cpltxt))
7816 (org-store-link-props :type "image" :file buffer-file-name))
7818 ((eq major-mode 'dired-mode)
7819 ;; link to the file in the current line
7820 (let ((file (dired-get-filename nil t)))
7821 (setq file (if file
7822 (abbreviate-file-name
7823 (expand-file-name (dired-get-filename nil t)))
7824 ;; otherwise, no file so use current directory.
7825 default-directory))
7826 (setq cpltxt (concat "file:" file)
7827 link (org-make-link cpltxt))))
7829 ((and buffer-file-name (org-mode-p))
7830 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7831 (cond
7832 ((org-in-regexp "<<\\(.*?\\)>>")
7833 (setq cpltxt
7834 (concat "file:"
7835 (abbreviate-file-name buffer-file-name)
7836 "::" (match-string 1))
7837 link (org-make-link cpltxt)))
7838 ((and (featurep 'org-id)
7839 (or (eq org-link-to-org-use-id t)
7840 (and (eq org-link-to-org-use-id 'create-if-interactive)
7841 (interactive-p))
7842 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7843 (interactive-p)
7844 (not custom-id))
7845 (and org-link-to-org-use-id
7846 (condition-case nil
7847 (org-entry-get nil "ID")
7848 (error nil)))))
7849 ;; We can make a link using the ID.
7850 (setq link (condition-case nil
7851 (prog1 (org-id-store-link)
7852 (setq desc (plist-get org-store-link-plist
7853 :description)))
7854 (error
7855 ;; probably before first headline, link to file only
7856 (concat "file:"
7857 (abbreviate-file-name buffer-file-name))))))
7859 ;; Just link to current headline
7860 (setq cpltxt (concat "file:"
7861 (abbreviate-file-name buffer-file-name)))
7862 ;; Add a context search string
7863 (when (org-xor org-context-in-file-links arg)
7864 (setq txt (cond
7865 ((org-on-heading-p) nil)
7866 ((org-region-active-p)
7867 (buffer-substring (region-beginning) (region-end)))
7868 (t nil)))
7869 (when (or (null txt) (string-match "\\S-" txt))
7870 (setq cpltxt
7871 (concat cpltxt "::"
7872 (condition-case nil
7873 (org-make-org-heading-search-string txt)
7874 (error "")))
7875 desc (or (nth 4 (ignore-errors
7876 (org-heading-components))) "NONE"))))
7877 (if (string-match "::\\'" cpltxt)
7878 (setq cpltxt (substring cpltxt 0 -2)))
7879 (setq link (org-make-link cpltxt)))))
7881 ((buffer-file-name (buffer-base-buffer))
7882 ;; Just link to this file here.
7883 (setq cpltxt (concat "file:"
7884 (abbreviate-file-name
7885 (buffer-file-name (buffer-base-buffer)))))
7886 ;; Add a context string
7887 (when (org-xor org-context-in-file-links arg)
7888 (setq txt (if (org-region-active-p)
7889 (buffer-substring (region-beginning) (region-end))
7890 (buffer-substring (point-at-bol) (point-at-eol))))
7891 ;; Only use search option if there is some text.
7892 (when (string-match "\\S-" txt)
7893 (setq cpltxt
7894 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7895 desc "NONE")))
7896 (setq link (org-make-link cpltxt)))
7898 ((interactive-p)
7899 (error "Cannot link to a buffer which is not visiting a file"))
7901 (t (setq link nil)))
7903 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7904 (setq link (or link cpltxt)
7905 desc (or desc cpltxt))
7906 (if (equal desc "NONE") (setq desc nil))
7908 (if (and (or (interactive-p) executing-kbd-macro) link)
7909 (progn
7910 (setq org-stored-links
7911 (cons (list link desc) org-stored-links))
7912 (message "Stored: %s" (or desc link))
7913 (when custom-id
7914 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7915 "::#" custom-id))
7916 (setq org-stored-links
7917 (cons (list link desc) org-stored-links))))
7918 (and link (org-make-link-string link desc)))))
7920 (defun org-store-link-props (&rest plist)
7921 "Store link properties, extract names and addresses."
7922 (let (x adr)
7923 (when (setq x (plist-get plist :from))
7924 (setq adr (mail-extract-address-components x))
7925 (setq plist (plist-put plist :fromname (car adr)))
7926 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7927 (when (setq x (plist-get plist :to))
7928 (setq adr (mail-extract-address-components x))
7929 (setq plist (plist-put plist :toname (car adr)))
7930 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7931 (let ((from (plist-get plist :from))
7932 (to (plist-get plist :to)))
7933 (when (and from to org-from-is-user-regexp)
7934 (setq plist
7935 (plist-put plist :fromto
7936 (if (string-match org-from-is-user-regexp from)
7937 (concat "to %t")
7938 (concat "from %f"))))))
7939 (setq org-store-link-plist plist))
7941 (defun org-add-link-props (&rest plist)
7942 "Add these properties to the link property list."
7943 (let (key value)
7944 (while plist
7945 (setq key (pop plist) value (pop plist))
7946 (setq org-store-link-plist
7947 (plist-put org-store-link-plist key value)))))
7949 (defun org-email-link-description (&optional fmt)
7950 "Return the description part of an email link.
7951 This takes information from `org-store-link-plist' and formats it
7952 according to FMT (default from `org-email-link-description-format')."
7953 (setq fmt (or fmt org-email-link-description-format))
7954 (let* ((p org-store-link-plist)
7955 (to (plist-get p :toaddress))
7956 (from (plist-get p :fromaddress))
7957 (table
7958 (list
7959 (cons "%c" (plist-get p :fromto))
7960 (cons "%F" (plist-get p :from))
7961 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7962 (cons "%T" (plist-get p :to))
7963 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7964 (cons "%s" (plist-get p :subject))
7965 (cons "%m" (plist-get p :message-id)))))
7966 (when (string-match "%c" fmt)
7967 ;; Check if the user wrote this message
7968 (if (and org-from-is-user-regexp from to
7969 (save-match-data (string-match org-from-is-user-regexp from)))
7970 (setq fmt (replace-match "to %t" t t fmt))
7971 (setq fmt (replace-match "from %f" t t fmt))))
7972 (org-replace-escapes fmt table)))
7974 (defun org-make-org-heading-search-string (&optional string heading)
7975 "Make search string for STRING or current headline."
7976 (interactive)
7977 (let ((s (or string (org-get-heading))))
7978 (unless (and string (not heading))
7979 ;; We are using a headline, clean up garbage in there.
7980 (if (string-match org-todo-regexp s)
7981 (setq s (replace-match "" t t s)))
7982 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7983 (setq s (replace-match "" t t s)))
7984 (setq s (org-trim s))
7985 (if (string-match (concat "^\\(" org-quote-string "\\|"
7986 org-comment-string "\\)") s)
7987 (setq s (replace-match "" t t s)))
7988 (while (string-match org-ts-regexp s)
7989 (setq s (replace-match "" t t s))))
7990 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7991 (setq s (replace-match " " t t s)))
7992 (or string (setq s (concat "*" s))) ; Add * for headlines
7993 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7995 (defun org-make-link (&rest strings)
7996 "Concatenate STRINGS."
7997 (apply 'concat strings))
7999 (defun org-make-link-string (link &optional description)
8000 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8001 (unless (string-match "\\S-" link)
8002 (error "Empty link"))
8003 (when (and description
8004 (stringp description)
8005 (not (string-match "\\S-" description)))
8006 (setq description nil))
8007 (when (stringp description)
8008 ;; Remove brackets from the description, they are fatal.
8009 (while (string-match "\\[" description)
8010 (setq description (replace-match "{" t t description)))
8011 (while (string-match "\\]" description)
8012 (setq description (replace-match "}" t t description))))
8013 (when (equal (org-link-escape link) description)
8014 ;; No description needed, it is identical
8015 (setq description nil))
8016 (when (and (not description)
8017 (not (equal link (org-link-escape link))))
8018 (setq description (org-extract-attributes link)))
8019 (concat "[[" (org-link-escape link) "]"
8020 (if description (concat "[" description "]") "")
8021 "]"))
8023 (defconst org-link-escape-chars
8024 '((?\ . "%20")
8025 (?\[ . "%5B")
8026 (?\] . "%5D")
8027 (?\340 . "%E0") ; `a
8028 (?\342 . "%E2") ; ^a
8029 (?\347 . "%E7") ; ,c
8030 (?\350 . "%E8") ; `e
8031 (?\351 . "%E9") ; 'e
8032 (?\352 . "%EA") ; ^e
8033 (?\356 . "%EE") ; ^i
8034 (?\364 . "%F4") ; ^o
8035 (?\371 . "%F9") ; `u
8036 (?\373 . "%FB") ; ^u
8037 (?\; . "%3B")
8038 ;; (?? . "%3F")
8039 (?= . "%3D")
8040 (?+ . "%2B")
8042 "Association list of escapes for some characters problematic in links.
8043 This is the list that is used for internal purposes.")
8045 (defvar org-url-encoding-use-url-hexify nil)
8047 (defconst org-link-escape-chars-browser
8048 '((?\ . "%20")) ; 32 for the SPC char
8049 "Association list of escapes for some characters problematic in links.
8050 This is the list that is used before handing over to the browser.")
8052 (defun org-link-escape (text &optional table)
8053 "Escape characters in TEXT that are problematic for links."
8054 (if (and org-url-encoding-use-url-hexify (not table))
8055 (url-hexify-string text)
8056 (setq table (or table org-link-escape-chars))
8057 (when text
8058 (let ((re (mapconcat (lambda (x) (regexp-quote
8059 (char-to-string (car x))))
8060 table "\\|")))
8061 (while (string-match re text)
8062 (setq text
8063 (replace-match
8064 (cdr (assoc (string-to-char (match-string 0 text))
8065 table))
8066 t t text)))
8067 text))))
8069 (defun org-link-unescape (text &optional table)
8070 "Reverse the action of `org-link-escape'."
8071 (if (and org-url-encoding-use-url-hexify (not table))
8072 (url-unhex-string text)
8073 (setq table (or table org-link-escape-chars))
8074 (when text
8075 (let ((case-fold-search t)
8076 (re (mapconcat (lambda (x) (regexp-quote (downcase (cdr x))))
8077 table "\\|")))
8078 (while (string-match re text)
8079 (setq text
8080 (replace-match
8081 (char-to-string (car (rassoc (upcase (match-string 0 text))
8082 table)))
8083 t t text)))
8084 text))))
8086 (defun org-xor (a b)
8087 "Exclusive or."
8088 (if a (not b) b))
8090 (defun org-fixup-message-id-for-http (s)
8091 "Replace special characters in a message id, so it can be used in an http query."
8092 (while (string-match "<" s)
8093 (setq s (replace-match "%3C" t t s)))
8094 (while (string-match ">" s)
8095 (setq s (replace-match "%3E" t t s)))
8096 (while (string-match "@" s)
8097 (setq s (replace-match "%40" t t s)))
8100 ;;;###autoload
8101 (defun org-insert-link-global ()
8102 "Insert a link like Org-mode does.
8103 This command can be called in any mode to insert a link in Org-mode syntax."
8104 (interactive)
8105 (org-load-modules-maybe)
8106 (org-run-like-in-org-mode 'org-insert-link))
8108 (defun org-insert-link (&optional complete-file link-location)
8109 "Insert a link. At the prompt, enter the link.
8111 Completion can be used to insert any of the link protocol prefixes like
8112 http or ftp in use.
8114 The history can be used to select a link previously stored with
8115 `org-store-link'. When the empty string is entered (i.e. if you just
8116 press RET at the prompt), the link defaults to the most recently
8117 stored link. As SPC triggers completion in the minibuffer, you need to
8118 use M-SPC or C-q SPC to force the insertion of a space character.
8120 You will also be prompted for a description, and if one is given, it will
8121 be displayed in the buffer instead of the link.
8123 If there is already a link at point, this command will allow you to edit link
8124 and description parts.
8126 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8127 be selected using completion. The path to the file will be relative to the
8128 current directory if the file is in the current directory or a subdirectory.
8129 Otherwise, the link will be the absolute path as completed in the minibuffer
8130 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8131 option `org-link-file-path-type'.
8133 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8134 the current directory or below.
8136 With three \\[universal-argument] prefixes, negate the meaning of
8137 `org-keep-stored-link-after-insertion'.
8139 If `org-make-link-description-function' is non-nil, this function will be
8140 called with the link target, and the result will be the default
8141 link description.
8143 If the LINK-LOCATION parameter is non-nil, this value will be
8144 used as the link location instead of reading one interactively."
8145 (interactive "P")
8146 (let* ((wcf (current-window-configuration))
8147 (region (if (org-region-active-p)
8148 (buffer-substring (region-beginning) (region-end))))
8149 (remove (and region (list (region-beginning) (region-end))))
8150 (desc region)
8151 tmphist ; byte-compile incorrectly complains about this
8152 (link link-location)
8153 entry file all-prefixes)
8154 (cond
8155 (link-location) ; specified by arg, just use it.
8156 ((org-in-regexp org-bracket-link-regexp 1)
8157 ;; We do have a link at point, and we are going to edit it.
8158 (setq remove (list (match-beginning 0) (match-end 0)))
8159 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8160 (setq link (read-string "Link: "
8161 (org-link-unescape
8162 (org-match-string-no-properties 1)))))
8163 ((or (org-in-regexp org-angle-link-re)
8164 (org-in-regexp org-plain-link-re))
8165 ;; Convert to bracket link
8166 (setq remove (list (match-beginning 0) (match-end 0))
8167 link (read-string "Link: "
8168 (org-remove-angle-brackets (match-string 0)))))
8169 ((member complete-file '((4) (16)))
8170 ;; Completing read for file names.
8171 (setq link (org-file-complete-link complete-file)))
8173 ;; Read link, with completion for stored links.
8174 (with-output-to-temp-buffer "*Org Links*"
8175 (princ "Insert a link.
8176 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8177 (when org-stored-links
8178 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8179 (princ (mapconcat
8180 (lambda (x)
8181 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8182 (reverse org-stored-links) "\n"))))
8183 (let ((cw (selected-window)))
8184 (select-window (get-buffer-window "*Org Links*"))
8185 (setq truncate-lines t)
8186 (unless (pos-visible-in-window-p (point-max))
8187 (org-fit-window-to-buffer))
8188 (and (window-live-p cw) (select-window cw)))
8189 ;; Fake a link history, containing the stored links.
8190 (setq tmphist (append (mapcar 'car org-stored-links)
8191 org-insert-link-history))
8192 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8193 (mapcar 'car org-link-abbrev-alist)
8194 org-link-types))
8195 (unwind-protect
8196 (progn
8197 (setq link
8198 (let ((org-completion-use-ido nil)
8199 (org-completion-use-iswitchb nil))
8200 (org-completing-read
8201 "Link: "
8202 (append
8203 (mapcar (lambda (x) (list (concat x ":")))
8204 all-prefixes)
8205 (mapcar 'car org-stored-links))
8206 nil nil nil
8207 'tmphist
8208 (car (car org-stored-links)))))
8209 (if (not (string-match "\\S-" link))
8210 (error "No link selected"))
8211 (if (or (member link all-prefixes)
8212 (and (equal ":" (substring link -1))
8213 (member (substring link 0 -1) all-prefixes)
8214 (setq link (substring link 0 -1))))
8215 (setq link (org-link-try-special-completion link))))
8216 (set-window-configuration wcf)
8217 (kill-buffer "*Org Links*"))
8218 (setq entry (assoc link org-stored-links))
8219 (or entry (push link org-insert-link-history))
8220 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8221 (not org-keep-stored-link-after-insertion))
8222 (setq org-stored-links (delq (assoc link org-stored-links)
8223 org-stored-links)))
8224 (setq desc (or desc (nth 1 entry)))))
8226 (if (string-match org-plain-link-re link)
8227 ;; URL-like link, normalize the use of angular brackets.
8228 (setq link (org-make-link (org-remove-angle-brackets link))))
8230 ;; Check if we are linking to the current file with a search option
8231 ;; If yes, simplify the link by using only the search option.
8232 (when (and buffer-file-name
8233 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8234 (let* ((path (match-string 1 link))
8235 (case-fold-search nil)
8236 (search (match-string 2 link)))
8237 (save-match-data
8238 (if (equal (file-truename buffer-file-name) (file-truename path))
8239 ;; We are linking to this same file, with a search option
8240 (setq link search)))))
8242 ;; Check if we can/should use a relative path. If yes, simplify the link
8243 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8244 (let* ((type (match-string 1 link))
8245 (path (match-string 2 link))
8246 (origpath path)
8247 (case-fold-search nil))
8248 (cond
8249 ((or (eq org-link-file-path-type 'absolute)
8250 (equal complete-file '(16)))
8251 (setq path (abbreviate-file-name (expand-file-name path))))
8252 ((eq org-link-file-path-type 'noabbrev)
8253 (setq path (expand-file-name path)))
8254 ((eq org-link-file-path-type 'relative)
8255 (setq path (file-relative-name path)))
8257 (save-match-data
8258 (if (string-match (concat "^" (regexp-quote
8259 (file-name-as-directory
8260 (expand-file-name "."))))
8261 (expand-file-name path))
8262 ;; We are linking a file with relative path name.
8263 (setq path (substring (expand-file-name path)
8264 (match-end 0)))
8265 (setq path (abbreviate-file-name (expand-file-name path)))))))
8266 (setq link (concat type path))
8267 (if (equal desc origpath)
8268 (setq desc path))))
8270 (if org-make-link-description-function
8271 (setq desc (funcall org-make-link-description-function link desc)))
8273 (setq desc (read-string "Description: " desc))
8274 (unless (string-match "\\S-" desc) (setq desc nil))
8275 (if remove (apply 'delete-region remove))
8276 (insert (org-make-link-string link desc))))
8278 (defun org-link-try-special-completion (type)
8279 "If there is completion support for link type TYPE, offer it."
8280 (let ((fun (intern (concat "org-" type "-complete-link"))))
8281 (if (functionp fun)
8282 (funcall fun)
8283 (read-string "Link (no completion support): " (concat type ":")))))
8285 (defun org-file-complete-link (&optional arg)
8286 "Create a file link using completion."
8287 (let (file link)
8288 (setq file (read-file-name "File: "))
8289 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8290 (pwd1 (file-name-as-directory (abbreviate-file-name
8291 (expand-file-name ".")))))
8292 (cond
8293 ((equal arg '(16))
8294 (setq link (org-make-link
8295 "file:"
8296 (abbreviate-file-name (expand-file-name file)))))
8297 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8298 (setq link (org-make-link "file:" (match-string 1 file))))
8299 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8300 (expand-file-name file))
8301 (setq link (org-make-link
8302 "file:" (match-string 1 (expand-file-name file)))))
8303 (t (setq link (org-make-link "file:" file)))))
8304 link))
8306 (defun org-completing-read (&rest args)
8307 "Completing-read with SPACE being a normal character."
8308 (let ((minibuffer-local-completion-map
8309 (copy-keymap minibuffer-local-completion-map)))
8310 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8311 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8312 (apply 'org-icompleting-read args)))
8314 (defun org-completing-read-no-i (&rest args)
8315 (let (org-completion-use-ido org-completion-use-iswitchb)
8316 (apply 'org-completing-read args)))
8318 (defun org-iswitchb-completing-read (prompt choices &rest args)
8319 "Use iswitch as a completing-read replacement to choose from choices.
8320 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8321 from."
8322 (let* ((iswitchb-use-virtual-buffers nil)
8323 (iswitchb-make-buflist-hook
8324 (lambda ()
8325 (setq iswitchb-temp-buflist choices))))
8326 (iswitchb-read-buffer prompt)))
8328 (defun org-icompleting-read (&rest args)
8329 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8330 (org-without-partial-completion
8331 (if (and org-completion-use-ido
8332 (fboundp 'ido-completing-read)
8333 (boundp 'ido-mode) ido-mode
8334 (listp (second args)))
8335 (let ((ido-enter-matching-directory nil))
8336 (apply 'ido-completing-read (concat (car args))
8337 (if (consp (car (nth 1 args)))
8338 (mapcar (lambda (x) (car x)) (nth 1 args))
8339 (nth 1 args))
8340 (cddr args)))
8341 (if (and org-completion-use-iswitchb
8342 (boundp 'iswitchb-mode) iswitchb-mode
8343 (listp (second args)))
8344 (apply 'org-iswitchb-completing-read (concat (car args))
8345 (if (consp (car (nth 1 args)))
8346 (mapcar (lambda (x) (car x)) (nth 1 args))
8347 (nth 1 args))
8348 (cddr args))
8349 (apply 'completing-read args)))))
8351 (defun org-extract-attributes (s)
8352 "Extract the attributes cookie from a string and set as text property."
8353 (let (a attr (start 0) key value)
8354 (save-match-data
8355 (when (string-match "{{\\([^}]+\\)}}$" s)
8356 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8357 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8358 (setq key (match-string 1 a) value (match-string 2 a)
8359 start (match-end 0)
8360 attr (plist-put attr (intern key) value))))
8361 (org-add-props s nil 'org-attr attr))
8364 (defun org-extract-attributes-from-string (tag)
8365 (let (key value attr)
8366 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8367 (setq key (match-string 1 tag) value (match-string 2 tag)
8368 tag (replace-match "" t t tag)
8369 attr (plist-put attr (intern key) value)))
8370 (cons tag attr)))
8372 (defun org-attributes-to-string (plist)
8373 "Format a property list into an HTML attribute list."
8374 (let ((s "") key value)
8375 (while plist
8376 (setq key (pop plist) value (pop plist))
8377 (and value
8378 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8381 ;;; Opening/following a link
8383 (defvar org-link-search-failed nil)
8385 (defvar org-open-link-functions nil
8386 "Hook for functions finding a plain text link.
8387 These functions must take a single argument, the link content.
8388 They will be called for links that look like [[link text][description]]
8389 when LINK TEXT does not have a protocol like \"http:\" and does not look
8390 like a filename (e.g. \"./blue.png\").
8392 These functions will be called *before* Org attempts to resolve the
8393 link by doing text searches in the current buffer - so if you want a
8394 link \"[[target]]\" to still find \"<<target>>\", your function should
8395 handle this as a special case.
8397 When the function does handle the link, it must return a non-nil value.
8398 If it decides that it is not responsible for this link, it must return
8399 nil to indicate that that Org-mode can continue with other options
8400 like exact and fuzzy text search.")
8402 (defun org-next-link ()
8403 "Move forward to the next link.
8404 If the link is in hidden text, expose it."
8405 (interactive)
8406 (when (and org-link-search-failed (eq this-command last-command))
8407 (goto-char (point-min))
8408 (message "Link search wrapped back to beginning of buffer"))
8409 (setq org-link-search-failed nil)
8410 (let* ((pos (point))
8411 (ct (org-context))
8412 (a (assoc :link ct)))
8413 (if a (goto-char (nth 2 a)))
8414 (if (re-search-forward org-any-link-re nil t)
8415 (progn
8416 (goto-char (match-beginning 0))
8417 (if (org-invisible-p) (org-show-context)))
8418 (goto-char pos)
8419 (setq org-link-search-failed t)
8420 (error "No further link found"))))
8422 (defun org-previous-link ()
8423 "Move backward to the previous link.
8424 If the link is in hidden text, expose it."
8425 (interactive)
8426 (when (and org-link-search-failed (eq this-command last-command))
8427 (goto-char (point-max))
8428 (message "Link search wrapped back to end of buffer"))
8429 (setq org-link-search-failed nil)
8430 (let* ((pos (point))
8431 (ct (org-context))
8432 (a (assoc :link ct)))
8433 (if a (goto-char (nth 1 a)))
8434 (if (re-search-backward org-any-link-re nil t)
8435 (progn
8436 (goto-char (match-beginning 0))
8437 (if (org-invisible-p) (org-show-context)))
8438 (goto-char pos)
8439 (setq org-link-search-failed t)
8440 (error "No further link found"))))
8442 (defun org-translate-link (s)
8443 "Translate a link string if a translation function has been defined."
8444 (if (and org-link-translation-function
8445 (fboundp org-link-translation-function)
8446 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8447 (progn
8448 (setq s (funcall org-link-translation-function
8449 (match-string 1) (match-string 2)))
8450 (concat (car s) ":" (cdr s)))
8453 (defun org-translate-link-from-planner (type path)
8454 "Translate a link from Emacs Planner syntax so that Org can follow it.
8455 This is still an experimental function, your mileage may vary."
8456 (cond
8457 ((member type '("http" "https" "news" "ftp"))
8458 ;; standard Internet links are the same.
8459 nil)
8460 ((and (equal type "irc") (string-match "^//" path))
8461 ;; Planner has two / at the beginning of an irc link, we have 1.
8462 ;; We should have zero, actually....
8463 (setq path (substring path 1)))
8464 ((and (equal type "lisp") (string-match "^/" path))
8465 ;; Planner has a slash, we do not.
8466 (setq type "elisp" path (substring path 1)))
8467 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8468 ;; A typical message link. Planner has the id after the final slash,
8469 ;; we separate it with a hash mark
8470 (setq path (concat (match-string 1 path) "#"
8471 (org-remove-angle-brackets (match-string 2 path)))))
8473 (cons type path))
8475 (defun org-find-file-at-mouse (ev)
8476 "Open file link or URL at mouse."
8477 (interactive "e")
8478 (mouse-set-point ev)
8479 (org-open-at-point 'in-emacs))
8481 (defun org-open-at-mouse (ev)
8482 "Open file link or URL at mouse."
8483 (interactive "e")
8484 (mouse-set-point ev)
8485 (if (eq major-mode 'org-agenda-mode)
8486 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8487 (org-open-at-point))
8489 (defvar org-window-config-before-follow-link nil
8490 "The window configuration before following a link.
8491 This is saved in case the need arises to restore it.")
8493 (defvar org-open-link-marker (make-marker)
8494 "Marker pointing to the location where `org-open-at-point; was called.")
8496 ;;;###autoload
8497 (defun org-open-at-point-global ()
8498 "Follow a link like Org-mode does.
8499 This command can be called in any mode to follow a link that has
8500 Org-mode syntax."
8501 (interactive)
8502 (org-run-like-in-org-mode 'org-open-at-point))
8504 ;;;###autoload
8505 (defun org-open-link-from-string (s &optional arg reference-buffer)
8506 "Open a link in the string S, as if it was in Org-mode."
8507 (interactive "sLink: \nP")
8508 (let ((reference-buffer (or reference-buffer (current-buffer))))
8509 (with-temp-buffer
8510 (let ((org-inhibit-startup t))
8511 (org-mode)
8512 (insert s)
8513 (goto-char (point-min))
8514 (when reference-buffer
8515 (setq org-link-abbrev-alist-local
8516 (with-current-buffer reference-buffer
8517 org-link-abbrev-alist-local)))
8518 (org-open-at-point arg reference-buffer)))))
8520 (defun org-open-at-point (&optional in-emacs reference-buffer)
8521 "Open link at or after point.
8522 If there is no link at point, this function will search forward up to
8523 the end of the current line.
8524 Normally, files will be opened by an appropriate application. If the
8525 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8526 With a double prefix argument, try to open outside of Emacs, in the
8527 application the system uses for this file type."
8528 (interactive "P")
8529 (org-load-modules-maybe)
8530 (move-marker org-open-link-marker (point))
8531 (setq org-window-config-before-follow-link (current-window-configuration))
8532 (org-remove-occur-highlights nil nil t)
8533 (cond
8534 ((and (org-on-heading-p)
8535 (not (org-in-regexp
8536 (concat org-plain-link-re "\\|"
8537 org-bracket-link-regexp "\\|"
8538 org-angle-link-re "\\|"
8539 "[ \t]:[^ \t\n]+:[ \t]*$")))
8540 (not (get-text-property (point) 'org-linked-text)))
8541 (or (org-offer-links-in-entry in-emacs)
8542 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8543 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8544 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8545 (org-footnote-action))
8547 (let (type path link line search (pos (point)))
8548 (catch 'match
8549 (save-excursion
8550 (skip-chars-forward "^]\n\r")
8551 (when (org-in-regexp org-bracket-link-regexp 1)
8552 (setq link (org-extract-attributes
8553 (org-link-unescape (org-match-string-no-properties 1))))
8554 (while (string-match " *\n *" link)
8555 (setq link (replace-match " " t t link)))
8556 (setq link (org-link-expand-abbrev link))
8557 (cond
8558 ((or (file-name-absolute-p link)
8559 (string-match "^\\.\\.?/" link))
8560 (setq type "file" path link))
8561 ((string-match org-link-re-with-space3 link)
8562 (setq type (match-string 1 link) path (match-string 2 link)))
8563 (t (setq type "thisfile" path link)))
8564 (throw 'match t)))
8566 (when (get-text-property (point) 'org-linked-text)
8567 (setq type "thisfile"
8568 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8569 (1+ (point)) (point))
8570 path (buffer-substring
8571 (previous-single-property-change pos 'org-linked-text)
8572 (next-single-property-change pos 'org-linked-text)))
8573 (throw 'match t))
8575 (save-excursion
8576 (when (or (org-in-regexp org-angle-link-re)
8577 (org-in-regexp org-plain-link-re))
8578 (setq type (match-string 1) path (match-string 2))
8579 (throw 'match t)))
8580 (save-excursion
8581 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8582 (setq type "tags"
8583 path (match-string 1))
8584 (while (string-match ":" path)
8585 (setq path (replace-match "+" t t path)))
8586 (throw 'match t)))
8587 (when (org-in-regexp "<\\([^><\n]+\\)>")
8588 (setq type "tree-match"
8589 path (match-string 1))
8590 (throw 'match t)))
8591 (unless path
8592 (error "No link found"))
8594 ;; switch back to reference buffer
8595 ;; needed when if called in a temporary buffer through
8596 ;; org-open-link-from-string
8597 (with-current-buffer (or reference-buffer (current-buffer))
8599 ;; Remove any trailing spaces in path
8600 (if (string-match " +\\'" path)
8601 (setq path (replace-match "" t t path)))
8602 (if (and org-link-translation-function
8603 (fboundp org-link-translation-function))
8604 ;; Check if we need to translate the link
8605 (let ((tmp (funcall org-link-translation-function type path)))
8606 (setq type (car tmp) path (cdr tmp))))
8608 (cond
8610 ((assoc type org-link-protocols)
8611 (funcall (nth 1 (assoc type org-link-protocols)) path))
8613 ((equal type "mailto")
8614 (let ((cmd (car org-link-mailto-program))
8615 (args (cdr org-link-mailto-program)) args1
8616 (address path) (subject "") a)
8617 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8618 (setq address (match-string 1 path)
8619 subject (org-link-escape (match-string 2 path))))
8620 (while args
8621 (cond
8622 ((not (stringp (car args))) (push (pop args) args1))
8623 (t (setq a (pop args))
8624 (if (string-match "%a" a)
8625 (setq a (replace-match address t t a)))
8626 (if (string-match "%s" a)
8627 (setq a (replace-match subject t t a)))
8628 (push a args1))))
8629 (apply cmd (nreverse args1))))
8631 ((member type '("http" "https" "ftp" "news"))
8632 (browse-url (concat type ":" (org-link-escape
8633 path org-link-escape-chars-browser))))
8635 ((member type '("message"))
8636 (browse-url (concat type ":" path)))
8638 ((string= type "tags")
8639 (org-tags-view in-emacs path))
8641 ((string= type "tree-match")
8642 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8644 ((string= type "file")
8645 (if (string-match "::\\([0-9]+\\)\\'" path)
8646 (setq line (string-to-number (match-string 1 path))
8647 path (substring path 0 (match-beginning 0)))
8648 (if (string-match "::\\(.+\\)\\'" path)
8649 (setq search (match-string 1 path)
8650 path (substring path 0 (match-beginning 0)))))
8651 (if (string-match "[*?{]" (file-name-nondirectory path))
8652 (dired path)
8653 (org-open-file path in-emacs line search)))
8655 ((string= type "news")
8656 (require 'org-gnus)
8657 (org-gnus-follow-link path))
8659 ((string= type "shell")
8660 (let ((cmd path))
8661 (if (or (not org-confirm-shell-link-function)
8662 (funcall org-confirm-shell-link-function
8663 (format "Execute \"%s\" in shell? "
8664 (org-add-props cmd nil
8665 'face 'org-warning))))
8666 (progn
8667 (message "Executing %s" cmd)
8668 (shell-command cmd))
8669 (error "Abort"))))
8671 ((string= type "elisp")
8672 (let ((cmd path))
8673 (if (or (not org-confirm-elisp-link-function)
8674 (funcall org-confirm-elisp-link-function
8675 (format "Execute \"%s\" as elisp? "
8676 (org-add-props cmd nil
8677 'face 'org-warning))))
8678 (message "%s => %s" cmd
8679 (if (equal (string-to-char cmd) ?\()
8680 (eval (read cmd))
8681 (call-interactively (read cmd))))
8682 (error "Abort"))))
8684 ((and (string= type "thisfile")
8685 (run-hook-with-args-until-success
8686 'org-open-link-functions path)))
8688 ((string= type "thisfile")
8689 (if in-emacs
8690 (switch-to-buffer-other-window
8691 (org-get-buffer-for-internal-link (current-buffer)))
8692 (org-mark-ring-push))
8693 (let ((cmd `(org-link-search
8694 ,path
8695 ,(cond ((equal in-emacs '(4)) 'occur)
8696 ((equal in-emacs '(16)) 'org-occur)
8697 (t nil))
8698 ,pos)))
8699 (condition-case nil (eval cmd)
8700 (error (progn (widen) (eval cmd))))))
8703 (browse-url-at-point)))))))
8704 (move-marker org-open-link-marker nil)
8705 (run-hook-with-args 'org-follow-link-hook))
8707 (defun org-offer-links-in-entry (&optional nth zero)
8708 "Offer links in the current entry and follow the selected link.
8709 If there is only one link, follow it immediately as well.
8710 If NTH is an integer, immediately pick the NTH link found.
8711 If ZERO is a string, check also this string for a link, and if
8712 there is one, offer it as link number zero."
8713 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8714 "\\(" org-angle-link-re "\\)\\|"
8715 "\\(" org-plain-link-re "\\)"))
8716 (cnt ?0)
8717 (in-emacs (if (integerp nth) nil nth))
8718 have-zero end links link c)
8719 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8720 (push (match-string 0 zero) links)
8721 (setq cnt (1- cnt) have-zero t))
8722 (save-excursion
8723 (org-back-to-heading t)
8724 (setq end (save-excursion (outline-next-heading) (point)))
8725 (while (re-search-forward re end t)
8726 (push (match-string 0) links))
8727 (setq links (org-uniquify (reverse links))))
8729 (cond
8730 ((null links)
8731 (message "No links"))
8732 ((equal (length links) 1)
8733 (setq link (list (car links))))
8734 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8735 (setq link (nth (if have-zero nth (1- nth)) links)))
8736 (t ; we have to select a link
8737 (save-excursion
8738 (save-window-excursion
8739 (delete-other-windows)
8740 (with-output-to-temp-buffer "*Select Link*"
8741 (mapc (lambda (l)
8742 (if (not (string-match org-bracket-link-regexp l))
8743 (princ (format "[%c] %s\n" (incf cnt)
8744 (org-remove-angle-brackets l)))
8745 (if (match-end 3)
8746 (princ (format "[%c] %s (%s)\n" (incf cnt)
8747 (match-string 3 l) (match-string 1 l)))
8748 (princ (format "[%c] %s\n" (incf cnt)
8749 (match-string 1 l))))))
8750 links))
8751 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8752 (message "Select link to open, RET to open all:")
8753 (setq c (read-char-exclusive))
8754 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8755 (when (equal c ?q) (error "Abort"))
8756 (if (equal c ?\C-m)
8757 (setq link links)
8758 (setq nth (- c ?0))
8759 (if have-zero (setq nth (1+ nth)))
8760 (unless (and (integerp nth) (>= (length links) nth))
8761 (error "Invalid link selection"))
8762 (setq link (list (nth (1- nth) links))))))
8763 (if link
8764 (let ((buf (current-buffer)))
8765 (dolist (l link)
8766 (org-open-link-from-string l in-emacs buf))
8768 nil)))
8770 ;; Add special file links that specify the way of opening
8772 (org-add-link-type "file+sys" 'org-open-file-with-system)
8773 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
8774 (defun org-open-file-with-system (path)
8775 "Open file at PATH using the system way of opeing it."
8776 (org-open-file path 'system))
8777 (defun org-open-file-with-emacs (path)
8778 "Open file at PATH in emacs."
8779 (org-open-file path 'emacs))
8780 (defun org-remove-file-link-modifiers ()
8781 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
8782 (goto-char (point-min))
8783 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
8784 (org-if-unprotected
8785 (replace-match "file:" t t))))
8786 (eval-after-load "org-exp"
8787 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
8788 'org-remove-file-link-modifiers))
8790 ;;;; Time estimates
8792 (defun org-get-effort (&optional pom)
8793 "Get the effort estimate for the current entry."
8794 (org-entry-get pom org-effort-property))
8796 ;;; File search
8798 (defvar org-create-file-search-functions nil
8799 "List of functions to construct the right search string for a file link.
8800 These functions are called in turn with point at the location to
8801 which the link should point.
8803 A function in the hook should first test if it would like to
8804 handle this file type, for example by checking the major-mode or
8805 the file extension. If it decides not to handle this file, it
8806 should just return nil to give other functions a chance. If it
8807 does handle the file, it must return the search string to be used
8808 when following the link. The search string will be part of the
8809 file link, given after a double colon, and `org-open-at-point'
8810 will automatically search for it. If special measures must be
8811 taken to make the search successful, another function should be
8812 added to the companion hook `org-execute-file-search-functions',
8813 which see.
8815 A function in this hook may also use `setq' to set the variable
8816 `description' to provide a suggestion for the descriptive text to
8817 be used for this link when it gets inserted into an Org-mode
8818 buffer with \\[org-insert-link].")
8820 (defvar org-execute-file-search-functions nil
8821 "List of functions to execute a file search triggered by a link.
8823 Functions added to this hook must accept a single argument, the
8824 search string that was part of the file link, the part after the
8825 double colon. The function must first check if it would like to
8826 handle this search, for example by checking the major-mode or the
8827 file extension. If it decides not to handle this search, it
8828 should just return nil to give other functions a chance. If it
8829 does handle the search, it must return a non-nil value to keep
8830 other functions from trying.
8832 Each function can access the current prefix argument through the
8833 variable `current-prefix-argument'. Note that a single prefix is
8834 used to force opening a link in Emacs, so it may be good to only
8835 use a numeric or double prefix to guide the search function.
8837 In case this is needed, a function in this hook can also restore
8838 the window configuration before `org-open-at-point' was called using:
8840 (set-window-configuration org-window-config-before-follow-link)")
8842 (defun org-link-search (s &optional type avoid-pos)
8843 "Search for a link search option.
8844 If S is surrounded by forward slashes, it is interpreted as a
8845 regular expression. In org-mode files, this will create an `org-occur'
8846 sparse tree. In ordinary files, `occur' will be used to list matches.
8847 If the current buffer is in `dired-mode', grep will be used to search
8848 in all files. If AVOID-POS is given, ignore matches near that position."
8849 (let ((case-fold-search t)
8850 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8851 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8852 (append '(("") (" ") ("\t") ("\n"))
8853 org-emphasis-alist)
8854 "\\|") "\\)"))
8855 (pos (point))
8856 (pre nil) (post nil)
8857 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8858 (cond
8859 ;; First check if there are any special
8860 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8861 ;; Now try the builtin stuff
8862 ((and (equal (string-to-char s0) ?#)
8863 (> (length s0) 1)
8864 (save-excursion
8865 (goto-char (point-min))
8866 (and
8867 (re-search-forward
8868 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8869 (setq type 'dedicated
8870 pos (match-beginning 0))))
8871 ;; There is an exact target for this
8872 (goto-char pos)
8873 (org-back-to-heading t)))
8874 ((save-excursion
8875 (goto-char (point-min))
8876 (and
8877 (re-search-forward
8878 (concat "<<" (regexp-quote s0) ">>") nil t)
8879 (setq type 'dedicated
8880 pos (match-beginning 0))))
8881 ;; There is an exact target for this
8882 (goto-char pos))
8883 ((and (string-match "^(\\(.*\\))$" s0)
8884 (save-excursion
8885 (goto-char (point-min))
8886 (and
8887 (re-search-forward
8888 (concat "[^[]" (regexp-quote
8889 (format org-coderef-label-format
8890 (match-string 1 s0))))
8891 nil t)
8892 (setq type 'dedicated
8893 pos (1+ (match-beginning 0))))))
8894 ;; There is a coderef target for this
8895 (goto-char pos))
8896 ((string-match "^/\\(.*\\)/$" s)
8897 ;; A regular expression
8898 (cond
8899 ((org-mode-p)
8900 (org-occur (match-string 1 s)))
8901 ;;((eq major-mode 'dired-mode)
8902 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8903 (t (org-do-occur (match-string 1 s)))))
8905 ;; A normal search strings
8906 (when (equal (string-to-char s) ?*)
8907 ;; Anchor on headlines, post may include tags.
8908 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8909 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8910 s (substring s 1)))
8911 (remove-text-properties
8912 0 (length s)
8913 '(face nil mouse-face nil keymap nil fontified nil) s)
8914 ;; Make a series of regular expressions to find a match
8915 (setq words (org-split-string s "[ \n\r\t]+")
8917 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8918 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8919 "\\)" markers)
8920 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8921 re2a (concat "[ \t\r\n]" re2a_)
8922 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8923 re4 (concat "[^a-zA-Z_]" re4_)
8925 re1 (concat pre re2 post)
8926 re3 (concat pre (if pre re4_ re4) post)
8927 re5 (concat pre ".*" re4)
8928 re2 (concat pre re2)
8929 re2a (concat pre (if pre re2a_ re2a))
8930 re4 (concat pre (if pre re4_ re4))
8931 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8932 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8933 re5 "\\)"
8935 (cond
8936 ((eq type 'org-occur) (org-occur reall))
8937 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8938 (t (goto-char (point-min))
8939 (setq type 'fuzzy)
8940 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8941 (org-search-not-self 1 re1 nil t)
8942 (org-search-not-self 1 re2 nil t)
8943 (org-search-not-self 1 re2a nil t)
8944 (org-search-not-self 1 re3 nil t)
8945 (org-search-not-self 1 re4 nil t)
8946 (org-search-not-self 1 re5 nil t)
8948 (goto-char (match-beginning 1))
8949 (goto-char pos)
8950 (error "No match")))))
8952 ;; Normal string-search
8953 (goto-char (point-min))
8954 (if (search-forward s nil t)
8955 (goto-char (match-beginning 0))
8956 (error "No match"))))
8957 (and (org-mode-p) (org-show-context 'link-search))
8958 type))
8960 (defun org-search-not-self (group &rest args)
8961 "Execute `re-search-forward', but only accept matches that do not
8962 enclose the position of `org-open-link-marker'."
8963 (let ((m org-open-link-marker))
8964 (catch 'exit
8965 (while (apply 're-search-forward args)
8966 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8967 (goto-char (match-end group))
8968 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8969 (> (match-beginning 0) (marker-position m))
8970 (< (match-end 0) (marker-position m)))
8971 (save-match-data
8972 (or (not (org-in-regexp
8973 org-bracket-link-analytic-regexp 1))
8974 (not (match-end 4)) ; no description
8975 (and (<= (match-beginning 4) (point))
8976 (>= (match-end 4) (point))))))
8977 (throw 'exit (point))))))))
8979 (defun org-get-buffer-for-internal-link (buffer)
8980 "Return a buffer to be used for displaying the link target of internal links."
8981 (cond
8982 ((not org-display-internal-link-with-indirect-buffer)
8983 buffer)
8984 ((string-match "(Clone)$" (buffer-name buffer))
8985 (message "Buffer is already a clone, not making another one")
8986 ;; we also do not modify visibility in this case
8987 buffer)
8988 (t ; make a new indirect buffer for displaying the link
8989 (let* ((bn (buffer-name buffer))
8990 (ibn (concat bn "(Clone)"))
8991 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8992 (with-current-buffer ib (org-overview))
8993 ib))))
8995 (defun org-do-occur (regexp &optional cleanup)
8996 "Call the Emacs command `occur'.
8997 If CLEANUP is non-nil, remove the printout of the regular expression
8998 in the *Occur* buffer. This is useful if the regex is long and not useful
8999 to read."
9000 (occur regexp)
9001 (when cleanup
9002 (let ((cwin (selected-window)) win beg end)
9003 (when (setq win (get-buffer-window "*Occur*"))
9004 (select-window win))
9005 (goto-char (point-min))
9006 (when (re-search-forward "match[a-z]+" nil t)
9007 (setq beg (match-end 0))
9008 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9009 (setq end (1- (match-beginning 0)))))
9010 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9011 (goto-char (point-min))
9012 (select-window cwin))))
9014 ;;; The mark ring for links jumps
9016 (defvar org-mark-ring nil
9017 "Mark ring for positions before jumps in Org-mode.")
9018 (defvar org-mark-ring-last-goto nil
9019 "Last position in the mark ring used to go back.")
9020 ;; Fill and close the ring
9021 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9022 (loop for i from 1 to org-mark-ring-length do
9023 (push (make-marker) org-mark-ring))
9024 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9025 org-mark-ring)
9027 (defun org-mark-ring-push (&optional pos buffer)
9028 "Put the current position or POS into the mark ring and rotate it."
9029 (interactive)
9030 (setq pos (or pos (point)))
9031 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9032 (move-marker (car org-mark-ring)
9033 (or pos (point))
9034 (or buffer (current-buffer)))
9035 (message "%s"
9036 (substitute-command-keys
9037 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9039 (defun org-mark-ring-goto (&optional n)
9040 "Jump to the previous position in the mark ring.
9041 With prefix arg N, jump back that many stored positions. When
9042 called several times in succession, walk through the entire ring.
9043 Org-mode commands jumping to a different position in the current file,
9044 or to another Org-mode file, automatically push the old position
9045 onto the ring."
9046 (interactive "p")
9047 (let (p m)
9048 (if (eq last-command this-command)
9049 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9050 (setq p org-mark-ring))
9051 (setq org-mark-ring-last-goto p)
9052 (setq m (car p))
9053 (switch-to-buffer (marker-buffer m))
9054 (goto-char m)
9055 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9057 (defun org-remove-angle-brackets (s)
9058 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9059 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9061 (defun org-add-angle-brackets (s)
9062 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9063 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9065 (defun org-remove-double-quotes (s)
9066 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9067 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9070 ;;; Following specific links
9072 (defun org-follow-timestamp-link ()
9073 (cond
9074 ((org-at-date-range-p t)
9075 (let ((org-agenda-start-on-weekday)
9076 (t1 (match-string 1))
9077 (t2 (match-string 2)))
9078 (setq t1 (time-to-days (org-time-string-to-time t1))
9079 t2 (time-to-days (org-time-string-to-time t2)))
9080 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9081 ((org-at-timestamp-p t)
9082 (org-agenda-list nil (time-to-days (org-time-string-to-time
9083 (substring (match-string 1) 0 10)))
9085 (t (error "This should not happen"))))
9088 ;;; Following file links
9089 (defvar org-wait nil)
9090 (defun org-open-file (path &optional in-emacs line search)
9091 "Open the file at PATH.
9092 First, this expands any special file name abbreviations. Then the
9093 configuration variable `org-file-apps' is checked if it contains an
9094 entry for this file type, and if yes, the corresponding command is launched.
9096 If no application is found, Emacs simply visits the file.
9098 With optional prefix argument IN-EMACS, Emacs will visit the file.
9099 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
9100 and to use an external application to visit the file.
9102 Optional LINE specifies a line to go to, optional SEARCH a string to
9103 search for. If LINE or SEARCH is given, but IN-EMACS is nil, it will
9104 be assumed that org-open-file was called to open a file: link, and the
9105 original link to match against org-file-apps will be reconstructed
9106 from PATH and whichever of LINE or SEARCH is given.
9108 If the file does not exist, an error is thrown."
9109 (let* ((file (if (equal path "")
9110 buffer-file-name
9111 (substitute-in-file-name (expand-file-name path))))
9112 (apps (append org-file-apps (org-default-apps)))
9113 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9114 (dirp (if remp nil (file-directory-p file)))
9115 (file (if (and dirp org-open-directory-means-index-dot-org)
9116 (concat (file-name-as-directory file) "index.org")
9117 file))
9118 (a-m-a-p (assq 'auto-mode apps))
9119 (dfile (downcase file))
9120 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9121 (link (cond ((and (eq line nil)
9122 (eq search nil))
9123 file)
9124 (line
9125 (concat file "::" (number-to-string line)))
9126 (search
9127 (concat file "::" search))))
9128 (dlink (downcase link))
9129 (old-buffer (current-buffer))
9130 (old-pos (point))
9131 (old-mode major-mode)
9132 ext cmd link-match-data)
9133 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9134 (setq ext (match-string 1 dfile))
9135 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9136 (setq ext (match-string 1 dfile))))
9137 (cond
9138 ((member in-emacs '((16) system))
9139 (setq cmd (cdr (assoc 'system apps))))
9140 (in-emacs (setq cmd 'emacs))
9142 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9143 (and dirp (cdr (assoc 'directory apps)))
9144 ;; if we find a match in org-file-apps, store the match
9145 ;; data for later
9146 (let ((match (assoc-default dlink (org-apps-regexp-alist
9147 apps a-m-a-p)
9148 'string-match)))
9149 (if match
9150 (progn (setq link-match-data (match-data))
9151 match)
9152 nil))
9153 (cdr (assoc ext apps))
9154 (cdr (assoc t apps))))))
9155 (when (eq cmd 'system)
9156 (setq cmd (cdr (assoc 'system apps))))
9157 (when (eq cmd 'default)
9158 (setq cmd (cdr (assoc t apps))))
9159 (when (eq cmd 'mailcap)
9160 (require 'mailcap)
9161 (mailcap-parse-mailcaps)
9162 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9163 (command (mailcap-mime-info mime-type)))
9164 (if (stringp command)
9165 (setq cmd command)
9166 (setq cmd 'emacs))))
9167 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9168 (not (file-exists-p file))
9169 (not org-open-non-existing-files))
9170 (error "No such file: %s" file))
9171 (cond
9172 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9173 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9174 (while (string-match "['\"]%s['\"]" cmd)
9175 (setq cmd (replace-match "%s" t t cmd)))
9176 (while (string-match "%s" cmd)
9177 (setq cmd (replace-match
9178 (save-match-data
9179 (shell-quote-argument
9180 (convert-standard-filename file)))
9181 t t cmd)))
9182 ;; Replace "%1", "%2" etc. in command with group matches from regex
9183 (save-match-data
9184 (let ((match-index 1)
9185 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9186 (set-match-data link-match-data)
9187 (while (<= match-index number-of-groups)
9188 (let ((regex (concat "%" (number-to-string match-index)))
9189 (replace-with (match-string match-index dlink)))
9190 (while (string-match regex cmd)
9191 (setq cmd (replace-match replace-with t t cmd))))
9192 (setq match-index (+ match-index 1)))))
9194 (save-window-excursion
9195 (start-process-shell-command cmd nil cmd)
9196 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9198 ((or (stringp cmd)
9199 (eq cmd 'emacs))
9200 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9201 (widen)
9202 (if line (org-goto-line line)
9203 (if search (org-link-search search))))
9204 ((consp cmd)
9205 (let ((file (convert-standard-filename file)))
9206 (save-match-data
9207 (set-match-data link-match-data)
9208 (eval cmd))))
9209 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9210 (and (org-mode-p) (eq old-mode 'org-mode)
9211 (or (not (equal old-buffer (current-buffer)))
9212 (not (equal old-pos (point))))
9213 (org-mark-ring-push old-pos old-buffer))))
9215 (defun org-default-apps ()
9216 "Return the default applications for this operating system."
9217 (cond
9218 ((eq system-type 'darwin)
9219 org-file-apps-defaults-macosx)
9220 ((eq system-type 'windows-nt)
9221 org-file-apps-defaults-windowsnt)
9222 (t org-file-apps-defaults-gnu)))
9224 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9225 "Convert extensions to regular expressions in the cars of LIST.
9226 Also, weed out any non-string entries, because the return value is used
9227 only for regexp matching.
9228 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9229 point to the symbol `emacs', indicating that the file should
9230 be opened in Emacs."
9231 (append
9232 (delq nil
9233 (mapcar (lambda (x)
9234 (if (not (stringp (car x)))
9236 (if (string-match "\\W" (car x))
9238 (cons (concat "\\." (car x) "\\(::.*\\)?\\'")
9239 (cdr x)))))
9240 list))
9241 (if add-auto-mode
9242 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9244 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9245 (defun org-file-remote-p (file)
9246 "Test whether FILE specifies a location on a remote system.
9247 Return non-nil if the location is indeed remote.
9249 For example, the filename \"/user@host:/foo\" specifies a location
9250 on the system \"/user@host:\"."
9251 (cond ((fboundp 'file-remote-p)
9252 (file-remote-p file))
9253 ((fboundp 'tramp-handle-file-remote-p)
9254 (tramp-handle-file-remote-p file))
9255 ((and (boundp 'ange-ftp-name-format)
9256 (string-match (car ange-ftp-name-format) file))
9258 (t nil)))
9261 ;;;; Refiling
9263 (defun org-get-org-file ()
9264 "Read a filename, with default directory `org-directory'."
9265 (let ((default (or org-default-notes-file remember-data-file)))
9266 (read-file-name (format "File name [%s]: " default)
9267 (file-name-as-directory org-directory)
9268 default)))
9270 (defun org-notes-order-reversed-p ()
9271 "Check if the current file should receive notes in reversed order."
9272 (cond
9273 ((not org-reverse-note-order) nil)
9274 ((eq t org-reverse-note-order) t)
9275 ((not (listp org-reverse-note-order)) nil)
9276 (t (catch 'exit
9277 (let ((all org-reverse-note-order)
9278 entry)
9279 (while (setq entry (pop all))
9280 (if (string-match (car entry) buffer-file-name)
9281 (throw 'exit (cdr entry))))
9282 nil)))))
9284 (defvar org-refile-target-table nil
9285 "The list of refile targets, created by `org-refile'.")
9287 (defvar org-agenda-new-buffers nil
9288 "Buffers created to visit agenda files.")
9290 (defun org-get-refile-targets (&optional default-buffer)
9291 "Produce a table with refile targets."
9292 (let ((case-fold-search nil)
9293 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9294 (entries (or org-refile-targets '((nil . (:level . 1)))))
9295 targets txt re files f desc descre fast-path-p level pos0)
9296 (message "Getting targets...")
9297 (with-current-buffer (or default-buffer (current-buffer))
9298 (while (setq entry (pop entries))
9299 (setq files (car entry) desc (cdr entry))
9300 (setq fast-path-p nil)
9301 (cond
9302 ((null files) (setq files (list (current-buffer))))
9303 ((eq files 'org-agenda-files)
9304 (setq files (org-agenda-files 'unrestricted)))
9305 ((and (symbolp files) (fboundp files))
9306 (setq files (funcall files)))
9307 ((and (symbolp files) (boundp files))
9308 (setq files (symbol-value files))))
9309 (if (stringp files) (setq files (list files)))
9310 (cond
9311 ((eq (car desc) :tag)
9312 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9313 ((eq (car desc) :todo)
9314 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9315 ((eq (car desc) :regexp)
9316 (setq descre (cdr desc)))
9317 ((eq (car desc) :level)
9318 (setq descre (concat "^\\*\\{" (number-to-string
9319 (if org-odd-levels-only
9320 (1- (* 2 (cdr desc)))
9321 (cdr desc)))
9322 "\\}[ \t]")))
9323 ((eq (car desc) :maxlevel)
9324 (setq fast-path-p t)
9325 (setq descre (concat "^\\*\\{1," (number-to-string
9326 (if org-odd-levels-only
9327 (1- (* 2 (cdr desc)))
9328 (cdr desc)))
9329 "\\}[ \t]")))
9330 (t (error "Bad refiling target description %s" desc)))
9331 (while (setq f (pop files))
9332 (with-current-buffer
9333 (if (bufferp f) f (org-get-agenda-file-buffer f))
9334 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
9335 (setq f (and f (expand-file-name f)))
9336 (if (eq org-refile-use-outline-path 'file)
9337 (push (list (file-name-nondirectory f) f nil nil) targets))
9338 (save-excursion
9339 (save-restriction
9340 (widen)
9341 (goto-char (point-min))
9342 (while (re-search-forward descre nil t)
9343 (goto-char (setq pos0 (point-at-bol)))
9344 (catch 'next
9345 (when org-refile-target-verify-function
9346 (save-match-data
9347 (or (funcall org-refile-target-verify-function)
9348 (throw 'next t))))
9349 (when (looking-at org-complex-heading-regexp)
9350 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
9351 txt (org-link-display-format (match-string 4))
9352 re (concat "^" (regexp-quote
9353 (buffer-substring (match-beginning 1)
9354 (match-end 4)))))
9355 (if (match-end 5) (setq re (concat re "[ \t]+"
9356 (regexp-quote
9357 (match-string 5)))))
9358 (setq re (concat re "[ \t]*$"))
9359 (when org-refile-use-outline-path
9360 (setq txt (mapconcat 'org-protect-slash
9361 (append
9362 (if (eq org-refile-use-outline-path 'file)
9363 (list (file-name-nondirectory
9364 (buffer-file-name (buffer-base-buffer))))
9365 (if (eq org-refile-use-outline-path 'full-file-path)
9366 (list (buffer-file-name (buffer-base-buffer)))))
9367 (org-get-outline-path fast-path-p level txt)
9368 (list txt))
9369 "/")))
9370 (push (list txt f re (point)) targets)))
9371 (when (= (point) pos0)
9372 ;; verification function has not moved point
9373 (goto-char (point-at-eol))))))))))
9374 (message "Getting targets...done")
9375 (nreverse targets)))
9377 (defun org-protect-slash (s)
9378 (while (string-match "/" s)
9379 (setq s (replace-match "\\" t t s)))
9382 (defvar org-olpa (make-vector 20 nil))
9384 (defun org-get-outline-path (&optional fastp level heading)
9385 "Return the outline path to the current entry, as a list.
9386 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9387 routine which makes outline path derivations for an entire file,
9388 avoiding backtracing."
9389 (if fastp
9390 (progn
9391 (if (> level 19)
9392 (error "Outline path failure, more than 19 levels."))
9393 (loop for i from level upto 19 do
9394 (aset org-olpa i nil))
9395 (prog1
9396 (delq nil (append org-olpa nil))
9397 (aset org-olpa level heading)))
9398 (let (rtn case-fold-search)
9399 (save-excursion
9400 (save-restriction
9401 (widen)
9402 (while (org-up-heading-safe)
9403 (when (looking-at org-complex-heading-regexp)
9404 (push (org-match-string-no-properties 4) rtn)))
9405 rtn)))))
9407 (defun org-format-outline-path (path &optional width prefix)
9408 "Format the outlie path PATH for display.
9409 Width is the maximum number of characters that is available.
9410 Prefix is a prefix to be included in the returned string,
9411 such as the file name."
9412 (setq width (or width 79))
9413 (if prefix (setq width (- width (length prefix))))
9414 (if (not path)
9415 (or prefix "")
9416 (let* ((nsteps (length path))
9417 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9418 (maxwidth (if (<= total-width width)
9419 10000 ;; everything fits
9420 ;; we need to shorten the level headings
9421 (/ (- width nsteps) nsteps)))
9422 (org-odd-levels-only nil)
9423 (n 0)
9424 (total (1+ (length prefix))))
9425 (setq maxwidth (max maxwidth 10))
9426 (concat prefix
9427 (mapconcat
9428 (lambda (h)
9429 (setq n (1+ n))
9430 (if (and (= n nsteps) (< maxwidth 10000))
9431 (setq maxwidth (- total-width total)))
9432 (if (< (length h) maxwidth)
9433 (progn (setq total (+ total (length h) 1)) h)
9434 (setq h (substring h 0 (- maxwidth 2))
9435 total (+ total maxwidth 1))
9436 (if (string-match "[ \t]+\\'" h)
9437 (setq h (substring h 0 (match-beginning 0))))
9438 (setq h (concat h "..")))
9439 (org-add-props h nil 'face
9440 (nth (% (1- n) org-n-level-faces)
9441 org-level-faces))
9443 path "/")))))
9445 (defun org-display-outline-path (&optional file current)
9446 "Display the current outline path in the echo area."
9447 (interactive "P")
9448 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
9449 (case-fold-search nil)
9450 (path (and (org-mode-p) (org-get-outline-path))))
9451 (if current (setq path (append path
9452 (save-excursion
9453 (org-back-to-heading t)
9454 (if (looking-at org-complex-heading-regexp)
9455 (list (match-string 4)))))))
9456 (message "%s"
9457 (org-format-outline-path
9458 path
9459 (1- (frame-width))
9460 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9462 (defvar org-refile-history nil
9463 "History for refiling operations.")
9465 (defvar org-after-refile-insert-hook nil
9466 "Hook run after `org-refile' has inserted its stuff at the new location.
9467 Note that this is still *before* the stuff will be removed from
9468 the *old* location.")
9470 (defun org-refile (&optional goto default-buffer rfloc)
9471 "Move the entry at point to another heading.
9472 The list of target headings is compiled using the information in
9473 `org-refile-targets', which see. This list is created before each use
9474 and will therefore always be up-to-date.
9476 At the target location, the entry is filed as a subitem of the target heading.
9477 Depending on `org-reverse-note-order', the new subitem will either be the
9478 first or the last subitem.
9480 If there is an active region, all entries in that region will be moved.
9481 However, the region must fulfil the requirement that the first heading
9482 is the first one sets the top-level of the moved text - at most siblings
9483 below it are allowed.
9485 With prefix arg GOTO, the command will only visit the target location,
9486 not actually move anything.
9487 With a double prefix `C-u C-u', go to the location where the last refiling
9488 operation has put the subtree.
9489 With a prefix argument of `2', refile to the running clock.
9491 RFLOC can be a refile location obtained in a different way.
9493 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9494 (interactive "P")
9495 (let* ((cbuf (current-buffer))
9496 (regionp (org-region-active-p))
9497 (region-start (and regionp (region-beginning)))
9498 (region-end (and regionp (region-end)))
9499 (region-length (and regionp (- region-end region-start)))
9500 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9501 pos it nbuf file re level reversed)
9502 (setq last-command nil)
9503 (when regionp
9504 (goto-char region-start)
9505 (or (bolp) (goto-char (point-at-bol)))
9506 (setq region-start (point))
9507 (unless (org-kill-is-subtree-p
9508 (buffer-substring region-start region-end))
9509 (error "The region is not a (sequence of) subtree(s)")))
9510 (if (equal goto '(16))
9511 (org-refile-goto-last-stored)
9512 (when (or
9513 (and (equal goto 2)
9514 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9515 (prog1
9516 (setq it (list (or org-clock-heading "running clock")
9517 (buffer-file-name
9518 (marker-buffer org-clock-hd-marker))
9520 (marker-position org-clock-hd-marker)))
9521 (setq goto nil)))
9522 (setq it (or rfloc
9523 (save-excursion
9524 (org-refile-get-location
9525 (if goto "Goto: " "Refile to: ") default-buffer
9526 org-refile-allow-creating-parent-nodes)))))
9527 (setq file (nth 1 it)
9528 re (nth 2 it)
9529 pos (nth 3 it))
9530 (if (and (not goto)
9532 (equal (buffer-file-name) file)
9533 (if regionp
9534 (and (>= pos region-start)
9535 (<= pos region-end))
9536 (and (>= pos (point))
9537 (< pos (save-excursion
9538 (org-end-of-subtree t t))))))
9539 (error "Cannot refile to position inside the tree or region"))
9541 (setq nbuf (or (find-buffer-visiting file)
9542 (find-file-noselect file)))
9543 (if goto
9544 (progn
9545 (switch-to-buffer nbuf)
9546 (goto-char pos)
9547 (org-show-context 'org-goto))
9548 (if regionp
9549 (progn
9550 (org-kill-new (buffer-substring region-start region-end))
9551 (org-save-markers-in-region region-start region-end))
9552 (org-copy-subtree 1 nil t))
9553 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9554 (find-file-noselect file)))
9555 (setq reversed (org-notes-order-reversed-p))
9556 (save-excursion
9557 (save-restriction
9558 (widen)
9559 (if pos
9560 (progn
9561 (goto-char pos)
9562 (looking-at outline-regexp)
9563 (setq level (org-get-valid-level (funcall outline-level) 1))
9564 (goto-char
9565 (if reversed
9566 (or (outline-next-heading) (point-max))
9567 (or (save-excursion (org-get-next-sibling))
9568 (org-end-of-subtree t t)
9569 (point-max)))))
9570 (setq level 1)
9571 (if (not reversed)
9572 (goto-char (point-max))
9573 (goto-char (point-min))
9574 (or (outline-next-heading) (goto-char (point-max)))))
9575 (if (not (bolp)) (newline))
9576 (org-paste-subtree level)
9577 (when org-log-refile
9578 (org-add-log-setup 'refile nil nil 'findpos
9579 org-log-refile)
9580 (unless (eq org-log-refile 'note)
9581 (save-excursion (org-add-log-note))))
9582 (and org-auto-align-tags (org-set-tags nil t))
9583 (bookmark-set "org-refile-last-stored")
9584 (if (fboundp 'deactivate-mark) (deactivate-mark))
9585 (run-hooks 'org-after-refile-insert-hook))))
9586 (if regionp
9587 (delete-region (point) (+ (point) region-length))
9588 (org-cut-subtree))
9589 (when (featurep 'org-inlinetask)
9590 (org-inlinetask-remove-END-maybe))
9591 (setq org-markers-to-move nil)
9592 (message "Refiled to \"%s\"" (car it))))))
9593 (org-reveal))
9595 (defun org-refile-goto-last-stored ()
9596 "Go to the location where the last refile was stored."
9597 (interactive)
9598 (bookmark-jump "org-refile-last-stored")
9599 (message "This is the location of the last refile"))
9601 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9602 "Prompt the user for a refile location, using PROMPT."
9603 (let ((org-refile-targets org-refile-targets)
9604 (org-refile-use-outline-path org-refile-use-outline-path))
9605 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9606 (unless org-refile-target-table
9607 (error "No refile targets"))
9608 (let* ((cbuf (current-buffer))
9609 (partial-completion-mode nil)
9610 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9611 (cfunc (if (and org-refile-use-outline-path
9612 org-outline-path-complete-in-steps)
9613 'org-olpath-completing-read
9614 'org-icompleting-read))
9615 (extra (if org-refile-use-outline-path "/" ""))
9616 (filename (and cfn (expand-file-name cfn)))
9617 (tbl (mapcar
9618 (lambda (x)
9619 (if (and (not (member org-refile-use-outline-path
9620 '(file full-file-path)))
9621 (not (equal filename (nth 1 x))))
9622 (cons (concat (car x) extra " ("
9623 (file-name-nondirectory (nth 1 x)) ")")
9624 (cdr x))
9625 (cons (concat (car x) extra) (cdr x))))
9626 org-refile-target-table))
9627 (completion-ignore-case t)
9628 pa answ parent-target child parent old-hist)
9629 (setq old-hist org-refile-history)
9630 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9631 nil 'org-refile-history))
9632 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9633 (if pa
9634 (progn
9635 (when (or (not org-refile-history)
9636 (not (eq old-hist org-refile-history))
9637 (not (equal (car pa) (car org-refile-history))))
9638 (setq org-refile-history
9639 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9640 org-refile-history
9641 (cdr org-refile-history))))
9642 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9643 (pop org-refile-history)))
9645 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9646 (progn
9647 (setq parent (match-string 1 answ)
9648 child (match-string 2 answ))
9649 (setq parent-target (or (assoc parent tbl)
9650 (assoc (concat parent "/") tbl)))
9651 (when (and parent-target
9652 (or (eq new-nodes t)
9653 (and (eq new-nodes 'confirm)
9654 (y-or-n-p (format "Create new node \"%s\"? "
9655 child)))))
9656 (org-refile-new-child parent-target child)))
9657 (error "Invalid target location")))))
9659 (defun org-refile-new-child (parent-target child)
9660 "Use refile target PARENT-TARGET to add new CHILD below it."
9661 (unless parent-target
9662 (error "Cannot find parent for new node"))
9663 (let ((file (nth 1 parent-target))
9664 (pos (nth 3 parent-target))
9665 level)
9666 (with-current-buffer (or (find-buffer-visiting file)
9667 (find-file-noselect file))
9668 (save-excursion
9669 (save-restriction
9670 (widen)
9671 (if pos
9672 (goto-char pos)
9673 (goto-char (point-max))
9674 (if (not (bolp)) (newline)))
9675 (when (looking-at outline-regexp)
9676 (setq level (funcall outline-level))
9677 (org-end-of-subtree t t))
9678 (org-back-over-empty-lines)
9679 (insert "\n" (make-string
9680 (if pos (org-get-valid-level level 1) 1) ?*)
9681 " " child "\n")
9682 (beginning-of-line 0)
9683 (list (concat (car parent-target) "/" child) file "" (point)))))))
9685 (defun org-olpath-completing-read (prompt collection &rest args)
9686 "Read an outline path like a file name."
9687 (let ((thetable collection)
9688 (org-completion-use-ido nil) ; does not work with ido.
9689 (org-completion-use-iswitchb nil)) ; or iswitchb
9690 (apply
9691 'org-icompleting-read prompt
9692 (lambda (string predicate &optional flag)
9693 (let (rtn r f (l (length string)))
9694 (cond
9695 ((eq flag nil)
9696 ;; try completion
9697 (try-completion string thetable))
9698 ((eq flag t)
9699 ;; all-completions
9700 (setq rtn (all-completions string thetable predicate))
9701 (mapcar
9702 (lambda (x)
9703 (setq r (substring x l))
9704 (if (string-match " ([^)]*)$" x)
9705 (setq f (match-string 0 x))
9706 (setq f ""))
9707 (if (string-match "/" r)
9708 (concat string (substring r 0 (match-end 0)) f)
9710 rtn))
9711 ((eq flag 'lambda)
9712 ;; exact match?
9713 (assoc string thetable)))
9715 args)))
9717 ;;;; Dynamic blocks
9719 (defun org-find-dblock (name)
9720 "Find the first dynamic block with name NAME in the buffer.
9721 If not found, stay at current position and return nil."
9722 (let (pos)
9723 (save-excursion
9724 (goto-char (point-min))
9725 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9726 nil t)
9727 (match-beginning 0))))
9728 (if pos (goto-char pos))
9729 pos))
9731 (defconst org-dblock-start-re
9732 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9733 "Matches the start line of a dynamic block, with parameters.")
9735 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9736 "Matches the end of a dynamic block.")
9738 (defun org-create-dblock (plist)
9739 "Create a dynamic block section, with parameters taken from PLIST.
9740 PLIST must contain a :name entry which is used as name of the block."
9741 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9742 (end-of-line 1)
9743 (newline))
9744 (let ((col (current-column))
9745 (name (plist-get plist :name)))
9746 (insert "#+BEGIN: " name)
9747 (while plist
9748 (if (eq (car plist) :name)
9749 (setq plist (cddr plist))
9750 (insert " " (prin1-to-string (pop plist)))))
9751 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9752 (beginning-of-line -2)))
9754 (defun org-prepare-dblock ()
9755 "Prepare dynamic block for refresh.
9756 This empties the block, puts the cursor at the insert position and returns
9757 the property list including an extra property :name with the block name."
9758 (unless (looking-at org-dblock-start-re)
9759 (error "Not at a dynamic block"))
9760 (let* ((begdel (1+ (match-end 0)))
9761 (name (org-no-properties (match-string 1)))
9762 (params (append (list :name name)
9763 (read (concat "(" (match-string 3) ")")))))
9764 (save-excursion
9765 (beginning-of-line 1)
9766 (skip-chars-forward " \t")
9767 (setq params (plist-put params :indentation-column (current-column))))
9768 (unless (re-search-forward org-dblock-end-re nil t)
9769 (error "Dynamic block not terminated"))
9770 (setq params
9771 (append params
9772 (list :content (buffer-substring
9773 begdel (match-beginning 0)))))
9774 (delete-region begdel (match-beginning 0))
9775 (goto-char begdel)
9776 (open-line 1)
9777 params))
9779 (defun org-map-dblocks (&optional command)
9780 "Apply COMMAND to all dynamic blocks in the current buffer.
9781 If COMMAND is not given, use `org-update-dblock'."
9782 (let ((cmd (or command 'org-update-dblock)))
9783 (save-excursion
9784 (goto-char (point-min))
9785 (while (re-search-forward org-dblock-start-re nil t)
9786 (goto-char (match-beginning 0))
9787 (save-excursion
9788 (condition-case nil
9789 (funcall cmd)
9790 (error (message "Error during update of dynamic block"))))
9791 (unless (re-search-forward org-dblock-end-re nil t)
9792 (error "Dynamic block not terminated"))))))
9794 (defun org-dblock-update (&optional arg)
9795 "User command for updating dynamic blocks.
9796 Update the dynamic block at point. With prefix ARG, update all dynamic
9797 blocks in the buffer."
9798 (interactive "P")
9799 (if arg
9800 (org-update-all-dblocks)
9801 (or (looking-at org-dblock-start-re)
9802 (org-beginning-of-dblock))
9803 (org-update-dblock)))
9805 (defun org-update-dblock ()
9806 "Update the dynamic block at point
9807 This means to empty the block, parse for parameters and then call
9808 the correct writing function."
9809 (save-window-excursion
9810 (let* ((pos (point))
9811 (line (org-current-line))
9812 (params (org-prepare-dblock))
9813 (name (plist-get params :name))
9814 (indent (plist-get params :indentation-column))
9815 (cmd (intern (concat "org-dblock-write:" name))))
9816 (message "Updating dynamic block `%s' at line %d..." name line)
9817 (funcall cmd params)
9818 (message "Updating dynamic block `%s' at line %d...done" name line)
9819 (goto-char pos)
9820 (when (and indent (> indent 0))
9821 (setq indent (make-string indent ?\ ))
9822 (save-excursion
9823 (org-beginning-of-dblock)
9824 (forward-line 1)
9825 (while (not (looking-at org-dblock-end-re))
9826 (insert indent)
9827 (beginning-of-line 2))
9828 (when (looking-at org-dblock-end-re)
9829 (and (looking-at "[ \t]+")
9830 (replace-match ""))
9831 (insert indent)))))))
9833 (defun org-beginning-of-dblock ()
9834 "Find the beginning of the dynamic block at point.
9835 Error if there is no such block at point."
9836 (let ((pos (point))
9837 beg)
9838 (end-of-line 1)
9839 (if (and (re-search-backward org-dblock-start-re nil t)
9840 (setq beg (match-beginning 0))
9841 (re-search-forward org-dblock-end-re nil t)
9842 (> (match-end 0) pos))
9843 (goto-char beg)
9844 (goto-char pos)
9845 (error "Not in a dynamic block"))))
9847 (defun org-update-all-dblocks ()
9848 "Update all dynamic blocks in the buffer.
9849 This function can be used in a hook."
9850 (when (org-mode-p)
9851 (org-map-dblocks 'org-update-dblock)))
9854 ;;;; Completion
9856 (defconst org-additional-option-like-keywords
9857 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9858 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9859 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
9860 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
9861 "BEGIN:" "END:"
9862 "ORGTBL" "TBLFM:" "TBLNAME:"
9863 "BEGIN_EXAMPLE" "END_EXAMPLE"
9864 "BEGIN_QUOTE" "END_QUOTE"
9865 "BEGIN_VERSE" "END_VERSE"
9866 "BEGIN_CENTER" "END_CENTER"
9867 "BEGIN_SRC" "END_SRC"
9868 "CATEGORY" "COLUMNS"
9869 "CAPTION" "LABEL"
9870 "SETUPFILE"
9871 "BIND"
9872 "MACRO"))
9874 (defcustom org-structure-template-alist
9876 ("s" "#+begin_src ?\n\n#+end_src"
9877 "<src lang=\"?\">\n\n</src>")
9878 ("e" "#+begin_example\n?\n#+end_example"
9879 "<example>\n?\n</example>")
9880 ("q" "#+begin_quote\n?\n#+end_quote"
9881 "<quote>\n?\n</quote>")
9882 ("v" "#+begin_verse\n?\n#+end_verse"
9883 "<verse>\n?\n/verse>")
9884 ("c" "#+begin_center\n?\n#+end_center"
9885 "<center>\n?\n/center>")
9886 ("l" "#+begin_latex\n?\n#+end_latex"
9887 "<literal style=\"latex\">\n?\n</literal>")
9888 ("L" "#+latex: "
9889 "<literal style=\"latex\">?</literal>")
9890 ("h" "#+begin_html\n?\n#+end_html"
9891 "<literal style=\"html\">\n?\n</literal>")
9892 ("H" "#+html: "
9893 "<literal style=\"html\">?</literal>")
9894 ("a" "#+begin_ascii\n?\n#+end_ascii")
9895 ("A" "#+ascii: ")
9896 ("i" "#+include %file ?"
9897 "<include file=%file markup=\"?\">")
9899 "Structure completion elements.
9900 This is a list of abbreviation keys and values. The value gets inserted
9901 it you type @samp{.} followed by the key and then the completion key,
9902 usually `M-TAB'. %file will be replaced by a file name after prompting
9903 for the file using completion.
9904 There are two templates for each key, the first uses the original Org syntax,
9905 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9906 the default when the /org-mtags.el/ module has been loaded. See also the
9907 variable `org-mtags-prefer-muse-templates'.
9908 This is an experimental feature, it is undecided if it is going to stay in."
9909 :group 'org-completion
9910 :type '(repeat
9911 (string :tag "Key")
9912 (string :tag "Template")
9913 (string :tag "Muse Template")))
9915 (defun org-try-structure-completion ()
9916 "Try to complete a structure template before point.
9917 This looks for strings like \"<e\" on an otherwise empty line and
9918 expands them."
9919 (let ((l (buffer-substring (point-at-bol) (point)))
9921 (when (and (looking-at "[ \t]*$")
9922 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9923 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9924 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9925 (match-beginning 1)) a)
9926 t)))
9928 (defun org-complete-expand-structure-template (start cell)
9929 "Expand a structure template."
9930 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9931 (rpl (nth (if musep 2 1) cell))
9932 (ind ""))
9933 (delete-region start (point))
9934 (when (string-match "\\`#\\+" rpl)
9935 (cond
9936 ((bolp))
9937 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9938 (setq ind (buffer-substring (point-at-bol) (point))))
9939 (t (newline))))
9940 (setq start (point))
9941 (if (string-match "%file" rpl)
9942 (setq rpl (replace-match
9943 (concat
9944 "\""
9945 (save-match-data
9946 (abbreviate-file-name (read-file-name "Include file: ")))
9947 "\"")
9948 t t rpl)))
9949 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9950 (concat "\n" ind)))
9951 (insert rpl)
9952 (if (re-search-backward "\\?" start t) (delete-char 1))))
9955 (defun org-complete (&optional arg)
9956 "Perform completion on word at point.
9957 At the beginning of a headline, this completes TODO keywords as given in
9958 `org-todo-keywords'.
9959 If the current word is preceded by a backslash, completes the TeX symbols
9960 that are supported for HTML support.
9961 If the current word is preceded by \"#+\", completes special words for
9962 setting file options.
9963 In the line after \"#+STARTUP:, complete valid keywords.\"
9964 At all other locations, this simply calls the value of
9965 `org-completion-fallback-command'."
9966 (interactive "P")
9967 (org-without-partial-completion
9968 (catch 'exit
9969 (let* ((a nil)
9970 (end (point))
9971 (beg1 (save-excursion
9972 (skip-chars-backward (org-re "[:alnum:]_@"))
9973 (point)))
9974 (beg (save-excursion
9975 (skip-chars-backward "a-zA-Z0-9_:$")
9976 (point)))
9977 (confirm (lambda (x) (stringp (car x))))
9978 (searchhead (equal (char-before beg) ?*))
9979 (struct
9980 (when (and (member (char-before beg1) '(?. ?<))
9981 (setq a (assoc (buffer-substring beg1 (point))
9982 org-structure-template-alist)))
9983 (org-complete-expand-structure-template (1- beg1) a)
9984 (throw 'exit t)))
9985 (tag (and (equal (char-before beg1) ?:)
9986 (equal (char-after (point-at-bol)) ?*)))
9987 (prop (and (equal (char-before beg1) ?:)
9988 (not (equal (char-after (point-at-bol)) ?*))))
9989 (texp (equal (char-before beg) ?\\))
9990 (link (equal (char-before beg) ?\[))
9991 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9992 beg)
9993 "#+"))
9994 (startup (string-match "^#\\+STARTUP:.*"
9995 (buffer-substring (point-at-bol) (point))))
9996 (completion-ignore-case opt)
9997 (type nil)
9998 (tbl nil)
9999 (table (cond
10000 (opt
10001 (setq type :opt)
10002 (require 'org-exp)
10003 (append
10004 (delq nil
10005 (mapcar
10006 (lambda (x)
10007 (if (string-match
10008 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
10009 (cons (match-string 2 x)
10010 (match-string 1 x))))
10011 (org-split-string (org-get-current-options) "\n")))
10012 (mapcar 'list org-additional-option-like-keywords)))
10013 (startup
10014 (setq type :startup)
10015 org-startup-options)
10016 (link (append org-link-abbrev-alist-local
10017 org-link-abbrev-alist))
10018 (texp
10019 (setq type :tex)
10020 (append org-entities-user org-entities))
10021 ((string-match "\\`\\*+[ \t]+\\'"
10022 (buffer-substring (point-at-bol) beg))
10023 (setq type :todo)
10024 (mapcar 'list org-todo-keywords-1))
10025 (searchhead
10026 (setq type :searchhead)
10027 (save-excursion
10028 (goto-char (point-min))
10029 (while (re-search-forward org-todo-line-regexp nil t)
10030 (push (list
10031 (org-make-org-heading-search-string
10032 (match-string 3) t))
10033 tbl)))
10034 tbl)
10035 (tag (setq type :tag beg beg1)
10036 (or org-tag-alist (org-get-buffer-tags)))
10037 (prop (setq type :prop beg beg1)
10038 (mapcar 'list (org-buffer-property-keys nil t t)))
10039 (t (progn
10040 (call-interactively org-completion-fallback-command)
10041 (throw 'exit nil)))))
10042 (pattern (buffer-substring-no-properties beg end))
10043 (completion (try-completion pattern table confirm)))
10044 (cond ((eq completion t)
10045 (if (not (assoc (upcase pattern) table))
10046 (message "Already complete")
10047 (if (and (equal type :opt)
10048 (not (member (car (assoc (upcase pattern) table))
10049 org-additional-option-like-keywords)))
10050 (insert (substring (cdr (assoc (upcase pattern) table))
10051 (length pattern)))
10052 (if (memq type '(:tag :prop)) (insert ":")))))
10053 ((null completion)
10054 (message "Can't find completion for \"%s\"" pattern)
10055 (ding))
10056 ((not (string= pattern completion))
10057 (delete-region beg end)
10058 (if (string-match " +$" completion)
10059 (setq completion (replace-match "" t t completion)))
10060 (insert completion)
10061 (if (get-buffer-window "*Completions*")
10062 (delete-window (get-buffer-window "*Completions*")))
10063 (if (assoc completion table)
10064 (if (eq type :todo) (insert " ")
10065 (if (memq type '(:tag :prop)) (insert ":"))))
10066 (if (and (equal type :opt) (assoc completion table))
10067 (message "%s" (substitute-command-keys
10068 "Press \\[org-complete] again to insert example settings"))))
10070 (message "Making completion list...")
10071 (let ((list (sort (all-completions pattern table confirm)
10072 'string<)))
10073 (with-output-to-temp-buffer "*Completions*"
10074 (condition-case nil
10075 ;; Protection needed for XEmacs and emacs 21
10076 (display-completion-list list pattern)
10077 (error (display-completion-list list)))))
10078 (message "Making completion list...%s" "done")))))))
10080 ;;;; TODO, DEADLINE, Comments
10082 (defun org-toggle-comment ()
10083 "Change the COMMENT state of an entry."
10084 (interactive)
10085 (save-excursion
10086 (org-back-to-heading)
10087 (let (case-fold-search)
10088 (if (looking-at (concat outline-regexp
10089 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10090 (replace-match "" t t nil 1)
10091 (if (looking-at outline-regexp)
10092 (progn
10093 (goto-char (match-end 0))
10094 (insert org-comment-string " ")))))))
10096 (defvar org-last-todo-state-is-todo nil
10097 "This is non-nil when the last TODO state change led to a TODO state.
10098 If the last change removed the TODO tag or switched to DONE, then
10099 this is nil.")
10101 (defvar org-setting-tags nil) ; dynamically skipped
10103 (defun org-parse-local-options (string var)
10104 "Parse STRING for startup setting relevant for variable VAR."
10105 (let ((rtn (symbol-value var))
10106 e opts)
10107 (save-match-data
10108 (if (or (not string) (not (string-match "\\S-" string)))
10110 (setq opts (delq nil (mapcar (lambda (x)
10111 (setq e (assoc x org-startup-options))
10112 (if (eq (nth 1 e) var) e nil))
10113 (org-split-string string "[ \t]+"))))
10114 (if (not opts)
10116 (setq rtn nil)
10117 (while (setq e (pop opts))
10118 (if (not (nth 3 e))
10119 (setq rtn (nth 2 e))
10120 (if (not (listp rtn)) (setq rtn nil))
10121 (push (nth 2 e) rtn)))
10122 rtn)))))
10124 (defvar org-todo-setup-filter-hook nil
10125 "Hook for functions that pre-filter todo specs.
10127 Each function takes a todo spec and returns either `nil' or the spec
10128 transformed into canonical form." )
10130 (defvar org-todo-get-default-hook nil
10131 "Hook for functions that get a default item for todo.
10133 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10134 `nil' or a string to be used for the todo mark." )
10136 (defvar org-agenda-headline-snapshot-before-repeat)
10138 (defun org-todo (&optional arg)
10139 "Change the TODO state of an item.
10140 The state of an item is given by a keyword at the start of the heading,
10141 like
10142 *** TODO Write paper
10143 *** DONE Call mom
10145 The different keywords are specified in the variable `org-todo-keywords'.
10146 By default the available states are \"TODO\" and \"DONE\".
10147 So for this example: when the item starts with TODO, it is changed to DONE.
10148 When it starts with DONE, the DONE is removed. And when neither TODO nor
10149 DONE are present, add TODO at the beginning of the heading.
10151 With C-u prefix arg, use completion to determine the new state.
10152 With numeric prefix arg, switch to that state.
10153 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
10154 With a triple C-u prefix, circumvent any state blocking.
10156 For calling through lisp, arg is also interpreted in the following way:
10157 'none -> empty state
10158 \"\"(empty string) -> switch to empty state
10159 'done -> switch to DONE
10160 'nextset -> switch to the next set of keywords
10161 'previousset -> switch to the previous set of keywords
10162 \"WAITING\" -> switch to the specified keyword, but only if it
10163 really is a member of `org-todo-keywords'."
10164 (interactive "P")
10165 (if (equal arg '(16)) (setq arg 'nextset))
10166 (let ((org-blocker-hook org-blocker-hook)
10167 (case-fold-search nil))
10168 (when (equal arg '(64))
10169 (setq arg nil org-blocker-hook nil))
10170 (when (and org-blocker-hook
10171 (or org-inhibit-blocking
10172 (org-entry-get nil "NOBLOCKING")))
10173 (setq org-blocker-hook nil))
10174 (save-excursion
10175 (catch 'exit
10176 (org-back-to-heading t)
10177 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10178 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10179 (looking-at " *"))
10180 (let* ((match-data (match-data))
10181 (startpos (point-at-bol))
10182 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
10183 (org-log-done org-log-done)
10184 (org-log-repeat org-log-repeat)
10185 (org-todo-log-states org-todo-log-states)
10186 (this (match-string 1))
10187 (hl-pos (match-beginning 0))
10188 (head (org-get-todo-sequence-head this))
10189 (ass (assoc head org-todo-kwd-alist))
10190 (interpret (nth 1 ass))
10191 (done-word (nth 3 ass))
10192 (final-done-word (nth 4 ass))
10193 (last-state (or this ""))
10194 (completion-ignore-case t)
10195 (member (member this org-todo-keywords-1))
10196 (tail (cdr member))
10197 (state (cond
10198 ((and org-todo-key-trigger
10199 (or (and (equal arg '(4))
10200 (eq org-use-fast-todo-selection 'prefix))
10201 (and (not arg) org-use-fast-todo-selection
10202 (not (eq org-use-fast-todo-selection
10203 'prefix)))))
10204 ;; Use fast selection
10205 (org-fast-todo-selection))
10206 ((and (equal arg '(4))
10207 (or (not org-use-fast-todo-selection)
10208 (not org-todo-key-trigger)))
10209 ;; Read a state with completion
10210 (org-icompleting-read
10211 "State: " (mapcar (lambda(x) (list x))
10212 org-todo-keywords-1)
10213 nil t))
10214 ((eq arg 'right)
10215 (if this
10216 (if tail (car tail) nil)
10217 (car org-todo-keywords-1)))
10218 ((eq arg 'left)
10219 (if (equal member org-todo-keywords-1)
10221 (if this
10222 (nth (- (length org-todo-keywords-1)
10223 (length tail) 2)
10224 org-todo-keywords-1)
10225 (org-last org-todo-keywords-1))))
10226 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10227 (setq arg nil))) ; hack to fall back to cycling
10228 (arg
10229 ;; user or caller requests a specific state
10230 (cond
10231 ((equal arg "") nil)
10232 ((eq arg 'none) nil)
10233 ((eq arg 'done) (or done-word (car org-done-keywords)))
10234 ((eq arg 'nextset)
10235 (or (car (cdr (member head org-todo-heads)))
10236 (car org-todo-heads)))
10237 ((eq arg 'previousset)
10238 (let ((org-todo-heads (reverse org-todo-heads)))
10239 (or (car (cdr (member head org-todo-heads)))
10240 (car org-todo-heads))))
10241 ((car (member arg org-todo-keywords-1)))
10242 ((stringp arg)
10243 (error "State `%s' not valid in this file" arg))
10244 ((nth (1- (prefix-numeric-value arg))
10245 org-todo-keywords-1))))
10246 ((null member) (or head (car org-todo-keywords-1)))
10247 ((equal this final-done-word) nil) ;; -> make empty
10248 ((null tail) nil) ;; -> first entry
10249 ((memq interpret '(type priority))
10250 (if (eq this-command last-command)
10251 (car tail)
10252 (if (> (length tail) 0)
10253 (or done-word (car org-done-keywords))
10254 nil)))
10256 (car tail))))
10257 (state (or
10258 (run-hook-with-args-until-success
10259 'org-todo-get-default-hook state last-state)
10260 state))
10261 (next (if state (concat " " state " ") " "))
10262 (change-plist (list :type 'todo-state-change :from this :to state
10263 :position startpos))
10264 dolog now-done-p)
10265 (when org-blocker-hook
10266 (setq org-last-todo-state-is-todo
10267 (not (member this org-done-keywords)))
10268 (unless (save-excursion
10269 (save-match-data
10270 (run-hook-with-args-until-failure
10271 'org-blocker-hook change-plist)))
10272 (if (interactive-p)
10273 (error "TODO state change from %s to %s blocked" this state)
10274 ;; fail silently
10275 (message "TODO state change from %s to %s blocked" this state)
10276 (throw 'exit nil))))
10277 (store-match-data match-data)
10278 (replace-match next t t)
10279 (unless (pos-visible-in-window-p hl-pos)
10280 (message "TODO state changed to %s" (org-trim next)))
10281 (unless head
10282 (setq head (org-get-todo-sequence-head state)
10283 ass (assoc head org-todo-kwd-alist)
10284 interpret (nth 1 ass)
10285 done-word (nth 3 ass)
10286 final-done-word (nth 4 ass)))
10287 (when (memq arg '(nextset previousset))
10288 (message "Keyword-Set %d/%d: %s"
10289 (- (length org-todo-sets) -1
10290 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10291 (length org-todo-sets)
10292 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10293 (setq org-last-todo-state-is-todo
10294 (not (member state org-done-keywords)))
10295 (setq now-done-p (and (member state org-done-keywords)
10296 (not (member this org-done-keywords))))
10297 (and logging (org-local-logging logging))
10298 (when (and (or org-todo-log-states org-log-done)
10299 (not (eq org-inhibit-logging t))
10300 (not (memq arg '(nextset previousset))))
10301 ;; we need to look at recording a time and note
10302 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10303 (nth 2 (assoc this org-todo-log-states))))
10304 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10305 (setq dolog 'time))
10306 (when (and state
10307 (member state org-not-done-keywords)
10308 (not (member this org-not-done-keywords)))
10309 ;; This is now a todo state and was not one before
10310 ;; If there was a CLOSED time stamp, get rid of it.
10311 (org-add-planning-info nil nil 'closed))
10312 (when (and now-done-p org-log-done)
10313 ;; It is now done, and it was not done before
10314 (org-add-planning-info 'closed (org-current-time))
10315 (if (and (not dolog) (eq 'note org-log-done))
10316 (org-add-log-setup 'done state this 'findpos 'note)))
10317 (when (and state dolog)
10318 ;; This is a non-nil state, and we need to log it
10319 (org-add-log-setup 'state state this 'findpos dolog)))
10320 ;; Fixup tag positioning
10321 (org-todo-trigger-tag-changes state)
10322 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10323 (when org-provide-todo-statistics
10324 (org-update-parent-todo-statistics))
10325 (run-hooks 'org-after-todo-state-change-hook)
10326 (if (and arg (not (member state org-done-keywords)))
10327 (setq head (org-get-todo-sequence-head state)))
10328 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10329 ;; Do we need to trigger a repeat?
10330 (when now-done-p
10331 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10332 ;; This is for the agenda, take a snapshot of the headline.
10333 (save-match-data
10334 (setq org-agenda-headline-snapshot-before-repeat
10335 (org-get-heading))))
10336 (org-auto-repeat-maybe state))
10337 ;; Fixup cursor location if close to the keyword
10338 (if (and (outline-on-heading-p)
10339 (not (bolp))
10340 (save-excursion (beginning-of-line 1)
10341 (looking-at org-todo-line-regexp))
10342 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10343 (progn
10344 (goto-char (or (match-end 2) (match-end 1)))
10345 (and (looking-at " ") (just-one-space))))
10346 (when org-trigger-hook
10347 (save-excursion
10348 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10350 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10351 "Block turning an entry into a TODO, using the hierarchy.
10352 This checks whether the current task should be blocked from state
10353 changes. Such blocking occurs when:
10355 1. The task has children which are not all in a completed state.
10357 2. A task has a parent with the property :ORDERED:, and there
10358 are siblings prior to the current task with incomplete
10359 status.
10361 3. The parent of the task is blocked because it has siblings that should
10362 be done first, or is child of a block grandparent TODO entry."
10364 (if (not org-enforce-todo-dependencies)
10365 t ; if locally turned off don't block
10366 (catch 'dont-block
10367 ;; If this is not a todo state change, or if this entry is already DONE,
10368 ;; do not block
10369 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10370 (member (plist-get change-plist :from)
10371 (cons 'done org-done-keywords))
10372 (member (plist-get change-plist :to)
10373 (cons 'todo org-not-done-keywords))
10374 (not (plist-get change-plist :to)))
10375 (throw 'dont-block t))
10376 ;; If this task has children, and any are undone, it's blocked
10377 (save-excursion
10378 (org-back-to-heading t)
10379 (let ((this-level (funcall outline-level)))
10380 (outline-next-heading)
10381 (let ((child-level (funcall outline-level)))
10382 (while (and (not (eobp))
10383 (> child-level this-level))
10384 ;; this todo has children, check whether they are all
10385 ;; completed
10386 (if (and (not (org-entry-is-done-p))
10387 (org-entry-is-todo-p))
10388 (throw 'dont-block nil))
10389 (outline-next-heading)
10390 (setq child-level (funcall outline-level))))))
10391 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10392 ;; any previous siblings are undone, it's blocked
10393 (save-excursion
10394 (org-back-to-heading t)
10395 (let* ((pos (point))
10396 (parent-pos (and (org-up-heading-safe) (point))))
10397 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10398 (when (and (org-entry-get (point) "ORDERED")
10399 (forward-line 1)
10400 (re-search-forward org-not-done-heading-regexp pos t))
10401 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10402 ;; Search further up the hierarchy, to see if an anchestor is blocked
10403 (while t
10404 (goto-char parent-pos)
10405 (if (not (looking-at org-not-done-heading-regexp))
10406 (throw 'dont-block t)) ; do not block, parent is not a TODO
10407 (setq pos (point))
10408 (setq parent-pos (and (org-up-heading-safe) (point)))
10409 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10410 (when (and (org-entry-get (point) "ORDERED")
10411 (forward-line 1)
10412 (re-search-forward org-not-done-heading-regexp pos t))
10413 (throw 'dont-block nil)))))))) ; block, older sibling not done.
10415 (defcustom org-track-ordered-property-with-tag nil
10416 "Should the ORDERED property also be shown as a tag?
10417 The ORDERED property decides if an entry should require subtasks to be
10418 completed in sequence. Since a property is not very visible, setting
10419 this option means that toggling the ORDERED property with the command
10420 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10421 not relevant for the behavior, but it makes things more visible.
10423 Note that toggling the tag with tags commands will not change the property
10424 and therefore not influence behavior!
10426 This can be t, meaning the tag ORDERED should be used, It can also be a
10427 string to select a different tag for this task."
10428 :group 'org-todo
10429 :type '(choice
10430 (const :tag "No tracking" nil)
10431 (const :tag "Track with ORDERED tag" t)
10432 (string :tag "Use other tag")))
10434 (defun org-toggle-ordered-property ()
10435 "Toggle the ORDERED property of the current entry.
10436 For better visibility, you can track the value of this property with a tag.
10437 See variable `org-track-ordered-property-with-tag'."
10438 (interactive)
10439 (let* ((t1 org-track-ordered-property-with-tag)
10440 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10441 (save-excursion
10442 (org-back-to-heading)
10443 (if (org-entry-get nil "ORDERED")
10444 (progn
10445 (org-delete-property "ORDERED")
10446 (and tag (org-toggle-tag tag 'off))
10447 (message "Subtasks can be completed in arbitrary order"))
10448 (org-entry-put nil "ORDERED" "t")
10449 (and tag (org-toggle-tag tag 'on))
10450 (message "Subtasks must be completed in sequence")))))
10452 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10453 (defun org-block-todo-from-checkboxes (change-plist)
10454 "Block turning an entry into a TODO, using checkboxes.
10455 This checks whether the current task should be blocked from state
10456 changes because there are unchecked boxes in this entry."
10457 (if (not org-enforce-todo-checkbox-dependencies)
10458 t ; if locally turned off don't block
10459 (catch 'dont-block
10460 ;; If this is not a todo state change, or if this entry is already DONE,
10461 ;; do not block
10462 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10463 (member (plist-get change-plist :from)
10464 (cons 'done org-done-keywords))
10465 (member (plist-get change-plist :to)
10466 (cons 'todo org-not-done-keywords))
10467 (not (plist-get change-plist :to)))
10468 (throw 'dont-block t))
10469 ;; If this task has checkboxes that are not checked, it's blocked
10470 (save-excursion
10471 (org-back-to-heading t)
10472 (let ((beg (point)) end)
10473 (outline-next-heading)
10474 (setq end (point))
10475 (goto-char beg)
10476 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10477 end t)
10478 (progn
10479 (if (boundp 'org-blocked-by-checkboxes)
10480 (setq org-blocked-by-checkboxes t))
10481 (throw 'dont-block nil)))))
10482 t))) ; do not block
10484 (defun org-entry-blocked-p ()
10485 "Is the current entry blocked?"
10486 (if (org-entry-get nil "NOBLOCKING")
10487 nil ;; Never block this entry
10488 (not
10489 (run-hook-with-args-until-failure
10490 'org-blocker-hook
10491 (list :type 'todo-state-change
10492 :position (point)
10493 :from 'todo
10494 :to 'done)))))
10496 (defun org-update-statistics-cookies (all)
10497 "Update the statistics cookie, either from TODO or from checkboxes.
10498 This should be called with the cursor in a line with a statistics cookie."
10499 (interactive "P")
10500 (if all
10501 (progn
10502 (org-update-checkbox-count 'all)
10503 (org-map-entries 'org-update-parent-todo-statistics))
10504 (if (not (org-on-heading-p))
10505 (org-update-checkbox-count)
10506 (let ((pos (move-marker (make-marker) (point)))
10507 end l1 l2)
10508 (ignore-errors (org-back-to-heading t))
10509 (if (not (org-on-heading-p))
10510 (org-update-checkbox-count)
10511 (setq l1 (org-outline-level))
10512 (setq end (save-excursion
10513 (outline-next-heading)
10514 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10515 (point)))
10516 (if (and (save-excursion
10517 (re-search-forward
10518 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
10519 (not (save-excursion (re-search-forward
10520 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10521 (org-update-checkbox-count)
10522 (if (and l2 (> l2 l1))
10523 (progn
10524 (goto-char end)
10525 (org-update-parent-todo-statistics))
10526 (goto-char pos)
10527 (beginning-of-line 1)
10528 (while (re-search-forward
10529 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
10530 (point-at-eol) t)
10531 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
10532 (goto-char pos)
10533 (move-marker pos nil)))))
10535 (defvar org-entry-property-inherited-from) ;; defined below
10536 (defun org-update-parent-todo-statistics ()
10537 "Update any statistics cookie in the parent of the current headline.
10538 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10539 the entire subtree and this will travel up the hierarchy and update
10540 statistics everywhere."
10541 (interactive)
10542 (let* ((lim 0) prop
10543 (recursive (or (not org-hierarchical-todo-statistics)
10544 (string-match
10545 "\\<recursive\\>"
10546 (or (setq prop (org-entry-get
10547 nil "COOKIE_DATA" 'inherit)) ""))))
10548 (lim (or (and prop (marker-position
10549 org-entry-property-inherited-from))
10550 lim))
10551 (first t)
10552 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10553 level ltoggle l1 new ndel
10554 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10555 (catch 'exit
10556 (save-excursion
10557 (beginning-of-line 1)
10558 (if (org-at-heading-p)
10559 (setq ltoggle (funcall outline-level))
10560 (error "This should not happen"))
10561 (while (and (setq level (org-up-heading-safe))
10562 (or recursive first)
10563 (>= (point) lim))
10564 (setq first nil cookie-present nil)
10565 (unless (and level
10566 (not (string-match
10567 "\\<checkbox\\>"
10568 (downcase
10569 (or (org-entry-get
10570 nil "COOKIE_DATA")
10571 "")))))
10572 (throw 'exit nil))
10573 (while (re-search-forward box-re (point-at-eol) t)
10574 (setq cnt-all 0 cnt-done 0 cookie-present t)
10575 (setq is-percent (match-end 2))
10576 (save-match-data
10577 (unless (outline-next-heading) (throw 'exit nil))
10578 (while (and (looking-at org-complex-heading-regexp)
10579 (> (setq l1 (length (match-string 1))) level))
10580 (setq kwd (and (or recursive (= l1 ltoggle))
10581 (match-string 2)))
10582 (if (or (eq org-provide-todo-statistics 'all-headlines)
10583 (and (listp org-provide-todo-statistics)
10584 (or (member kwd org-provide-todo-statistics)
10585 (member kwd org-done-keywords))))
10586 (setq cnt-all (1+ cnt-all))
10587 (if (eq org-provide-todo-statistics t)
10588 (and kwd (setq cnt-all (1+ cnt-all)))))
10589 (and (member kwd org-done-keywords)
10590 (setq cnt-done (1+ cnt-done)))
10591 (outline-next-heading)))
10592 (setq new
10593 (if is-percent
10594 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10595 (format "[%d/%d]" cnt-done cnt-all))
10596 ndel (- (match-end 0) (match-beginning 0)))
10597 (goto-char (match-beginning 0))
10598 (insert new)
10599 (delete-region (point) (+ (point) ndel)))
10600 (when cookie-present
10601 (run-hook-with-args 'org-after-todo-statistics-hook
10602 cnt-done (- cnt-all cnt-done))))))
10603 (run-hooks 'org-todo-statistics-hook)))
10605 (defvar org-after-todo-statistics-hook nil
10606 "Hook that is called after a TODO statistics cookie has been updated.
10607 Each function is called with two arguments: the number of not-done entries
10608 and the number of done entries.
10610 For example, the following function, when added to this hook, will switch
10611 an entry to DONE when all children are done, and back to TODO when new
10612 entries are set to a TODO status. Note that this hook is only called
10613 when there is a statistics cookie in the headline!
10615 (defun org-summary-todo (n-done n-not-done)
10616 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10617 (let (org-log-done org-log-states) ; turn off logging
10618 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10621 (defvar org-todo-statistics-hook nil
10622 "Hook that is run whenever Org thinks TODO statistics should be updated.
10623 This hook runs even if there is no statistics cookie present, in which case
10624 `org-after-todo-statistics-hook' would not run.")
10626 (defun org-todo-trigger-tag-changes (state)
10627 "Apply the changes defined in `org-todo-state-tags-triggers'."
10628 (let ((l org-todo-state-tags-triggers)
10629 changes)
10630 (when (or (not state) (equal state ""))
10631 (setq changes (append changes (cdr (assoc "" l)))))
10632 (when (and (stringp state) (> (length state) 0))
10633 (setq changes (append changes (cdr (assoc state l)))))
10634 (when (member state org-not-done-keywords)
10635 (setq changes (append changes (cdr (assoc 'todo l)))))
10636 (when (member state org-done-keywords)
10637 (setq changes (append changes (cdr (assoc 'done l)))))
10638 (dolist (c changes)
10639 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10641 (defun org-local-logging (value)
10642 "Get logging settings from a property VALUE."
10643 (let* (words w a)
10644 ;; directly set the variables, they are already local.
10645 (setq org-log-done nil
10646 org-log-repeat nil
10647 org-todo-log-states nil)
10648 (setq words (org-split-string value))
10649 (while (setq w (pop words))
10650 (cond
10651 ((setq a (assoc w org-startup-options))
10652 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10653 (set (nth 1 a) (nth 2 a))))
10654 ((setq a (org-extract-log-state-settings w))
10655 (and (member (car a) org-todo-keywords-1)
10656 (push a org-todo-log-states)))))))
10658 (defun org-get-todo-sequence-head (kwd)
10659 "Return the head of the TODO sequence to which KWD belongs.
10660 If KWD is not set, check if there is a text property remembering the
10661 right sequence."
10662 (let (p)
10663 (cond
10664 ((not kwd)
10665 (or (get-text-property (point-at-bol) 'org-todo-head)
10666 (progn
10667 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10668 nil (point-at-eol)))
10669 (get-text-property p 'org-todo-head))))
10670 ((not (member kwd org-todo-keywords-1))
10671 (car org-todo-keywords-1))
10672 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10674 (defun org-fast-todo-selection ()
10675 "Fast TODO keyword selection with single keys.
10676 Returns the new TODO keyword, or nil if no state change should occur."
10677 (let* ((fulltable org-todo-key-alist)
10678 (done-keywords org-done-keywords) ;; needed for the faces.
10679 (maxlen (apply 'max (mapcar
10680 (lambda (x)
10681 (if (stringp (car x)) (string-width (car x)) 0))
10682 fulltable)))
10683 (expert nil)
10684 (fwidth (+ maxlen 3 1 3))
10685 (ncol (/ (- (window-width) 4) fwidth))
10686 tg cnt e c tbl
10687 groups ingroup)
10688 (save-excursion
10689 (save-window-excursion
10690 (if expert
10691 (set-buffer (get-buffer-create " *Org todo*"))
10692 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10693 (erase-buffer)
10694 (org-set-local 'org-done-keywords done-keywords)
10695 (setq tbl fulltable cnt 0)
10696 (while (setq e (pop tbl))
10697 (cond
10698 ((equal e '(:startgroup))
10699 (push '() groups) (setq ingroup t)
10700 (when (not (= cnt 0))
10701 (setq cnt 0)
10702 (insert "\n"))
10703 (insert "{ "))
10704 ((equal e '(:endgroup))
10705 (setq ingroup nil cnt 0)
10706 (insert "}\n"))
10707 ((equal e '(:newline))
10708 (when (not (= cnt 0))
10709 (setq cnt 0)
10710 (insert "\n")
10711 (setq e (car tbl))
10712 (while (equal (car tbl) '(:newline))
10713 (insert "\n")
10714 (setq tbl (cdr tbl)))))
10716 (setq tg (car e) c (cdr e))
10717 (if ingroup (push tg (car groups)))
10718 (setq tg (org-add-props tg nil 'face
10719 (org-get-todo-face tg)))
10720 (if (and (= cnt 0) (not ingroup)) (insert " "))
10721 (insert "[" c "] " tg (make-string
10722 (- fwidth 4 (length tg)) ?\ ))
10723 (when (= (setq cnt (1+ cnt)) ncol)
10724 (insert "\n")
10725 (if ingroup (insert " "))
10726 (setq cnt 0)))))
10727 (insert "\n")
10728 (goto-char (point-min))
10729 (if (not expert) (org-fit-window-to-buffer))
10730 (message "[a-z..]:Set [SPC]:clear")
10731 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10732 (cond
10733 ((or (= c ?\C-g)
10734 (and (= c ?q) (not (rassoc c fulltable))))
10735 (setq quit-flag t))
10736 ((= c ?\ ) nil)
10737 ((setq e (rassoc c fulltable) tg (car e))
10739 (t (setq quit-flag t)))))))
10741 (defun org-entry-is-todo-p ()
10742 (member (org-get-todo-state) org-not-done-keywords))
10744 (defun org-entry-is-done-p ()
10745 (member (org-get-todo-state) org-done-keywords))
10747 (defun org-get-todo-state ()
10748 (save-excursion
10749 (org-back-to-heading t)
10750 (and (looking-at org-todo-line-regexp)
10751 (match-end 2)
10752 (match-string 2))))
10754 (defun org-at-date-range-p (&optional inactive-ok)
10755 "Is the cursor inside a date range?"
10756 (interactive)
10757 (save-excursion
10758 (catch 'exit
10759 (let ((pos (point)))
10760 (skip-chars-backward "^[<\r\n")
10761 (skip-chars-backward "<[")
10762 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10763 (>= (match-end 0) pos)
10764 (throw 'exit t))
10765 (skip-chars-backward "^<[\r\n")
10766 (skip-chars-backward "<[")
10767 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10768 (>= (match-end 0) pos)
10769 (throw 'exit t)))
10770 nil)))
10772 (defun org-get-repeat (&optional tagline)
10773 "Check if there is a deadline/schedule with repeater in this entry."
10774 (save-match-data
10775 (save-excursion
10776 (org-back-to-heading t)
10777 (and (re-search-forward (if tagline
10778 (concat tagline "\\s-*" org-repeat-re)
10779 org-repeat-re)
10780 (org-entry-end-position) t)
10781 (match-string-no-properties 1)))))
10783 (defvar org-last-changed-timestamp)
10784 (defvar org-last-inserted-timestamp)
10785 (defvar org-log-post-message)
10786 (defvar org-log-note-purpose)
10787 (defvar org-log-note-how)
10788 (defvar org-log-note-extra)
10789 (defun org-auto-repeat-maybe (done-word)
10790 "Check if the current headline contains a repeated deadline/schedule.
10791 If yes, set TODO state back to what it was and change the base date
10792 of repeating deadline/scheduled time stamps to new date.
10793 This function is run automatically after each state change to a DONE state."
10794 ;; last-state is dynamically scoped into this function
10795 (let* ((repeat (org-get-repeat))
10796 (aa (assoc last-state org-todo-kwd-alist))
10797 (interpret (nth 1 aa))
10798 (head (nth 2 aa))
10799 (whata '(("d" . day) ("m" . month) ("y" . year)))
10800 (msg "Entry repeats: ")
10801 (org-log-done nil)
10802 (org-todo-log-states nil)
10803 (nshiftmax 10) (nshift 0)
10804 re type n what ts time)
10805 (when repeat
10806 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10807 (org-todo (if (eq interpret 'type) last-state head))
10808 (org-entry-put nil "LAST_REPEAT" (format-time-string
10809 (org-time-stamp-format t t)))
10810 (when org-log-repeat
10811 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10812 (memq 'org-add-log-note post-command-hook))
10813 ;; OK, we are already setup for some record
10814 (if (eq org-log-repeat 'note)
10815 ;; make sure we take a note, not only a time stamp
10816 (setq org-log-note-how 'note))
10817 ;; Set up for taking a record
10818 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10819 last-state
10820 'findpos org-log-repeat)))
10821 (org-back-to-heading t)
10822 (org-add-planning-info nil nil 'closed)
10823 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10824 org-deadline-time-regexp "\\)\\|\\("
10825 org-ts-regexp "\\)"))
10826 (while (re-search-forward
10827 re (save-excursion (outline-next-heading) (point)) t)
10828 (setq type (if (match-end 1) org-scheduled-string
10829 (if (match-end 3) org-deadline-string "Plain:"))
10830 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10831 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10832 (setq n (string-to-number (match-string 2 ts))
10833 what (match-string 3 ts))
10834 (if (equal what "w") (setq n (* n 7) what "d"))
10835 ;; Preparation, see if we need to modify the start date for the change
10836 (when (match-end 1)
10837 (setq time (save-match-data (org-time-string-to-time ts)))
10838 (cond
10839 ((equal (match-string 1 ts) ".")
10840 ;; Shift starting date to today
10841 (org-timestamp-change
10842 (- (time-to-days (current-time)) (time-to-days time))
10843 'day))
10844 ((equal (match-string 1 ts) "+")
10845 (while (or (= nshift 0)
10846 (<= (time-to-days time) (time-to-days (current-time))))
10847 (when (= (incf nshift) nshiftmax)
10848 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10849 (error "Abort")))
10850 (org-timestamp-change n (cdr (assoc what whata)))
10851 (org-at-timestamp-p t)
10852 (setq ts (match-string 1))
10853 (setq time (save-match-data (org-time-string-to-time ts))))
10854 (org-timestamp-change (- n) (cdr (assoc what whata)))
10855 ;; rematch, so that we have everything in place for the real shift
10856 (org-at-timestamp-p t)
10857 (setq ts (match-string 1))
10858 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10859 (org-timestamp-change n (cdr (assoc what whata)))
10860 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10861 (setq org-log-post-message msg)
10862 (message "%s" msg))))
10864 (defun org-show-todo-tree (arg)
10865 "Make a compact tree which shows all headlines marked with TODO.
10866 The tree will show the lines where the regexp matches, and all higher
10867 headlines above the match.
10868 With a \\[universal-argument] prefix, prompt for a regexp to match.
10869 With a numeric prefix N, construct a sparse tree for the Nth element
10870 of `org-todo-keywords-1'."
10871 (interactive "P")
10872 (let ((case-fold-search nil)
10873 (kwd-re
10874 (cond ((null arg) org-not-done-regexp)
10875 ((equal arg '(4))
10876 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10877 (mapcar 'list org-todo-keywords-1))))
10878 (concat "\\("
10879 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10880 "\\)\\>")))
10881 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10882 (regexp-quote (nth (1- (prefix-numeric-value arg))
10883 org-todo-keywords-1)))
10884 (t (error "Invalid prefix argument: %s" arg)))))
10885 (message "%d TODO entries found"
10886 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10888 (defun org-deadline (&optional remove time)
10889 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10890 With argument REMOVE, remove any deadline from the item.
10891 When TIME is set, it should be an internal time specification, and the
10892 scheduling will use the corresponding date."
10893 (interactive "P")
10894 (let* ((old-date (org-entry-get nil "DEADLINE"))
10895 (repeater (and old-date
10896 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
10897 (match-string 1 old-date))))
10898 (if remove
10899 (progn
10900 (when (and old-date org-log-redeadline)
10901 (org-add-log-setup 'deldeadline nil old-date 'findpos
10902 org-log-redeadline))
10903 (org-remove-timestamp-with-keyword org-deadline-string)
10904 (message "Item no longer has a deadline."))
10905 (org-add-planning-info 'deadline time 'closed)
10906 (when (and old-date org-log-redeadline
10907 (not (equal old-date
10908 (substring org-last-inserted-timestamp 1 -1))))
10909 (org-add-log-setup 'redeadline nil old-date 'findpos
10910 org-log-redeadline))
10911 (when repeater
10912 (save-excursion
10913 (org-back-to-heading t)
10914 (when (re-search-forward (concat org-deadline-string " "
10915 org-last-inserted-timestamp)
10916 (save-excursion
10917 (outline-next-heading) (point)) t)
10918 (goto-char (1- (match-end 0)))
10919 (insert " " repeater)
10920 (setq org-last-inserted-timestamp
10921 (concat (substring org-last-inserted-timestamp 0 -1)
10922 " " repeater
10923 (substring org-last-inserted-timestamp -1))))))
10924 (message "Deadline on %s" org-last-inserted-timestamp))))
10926 (defun org-schedule (&optional remove time)
10927 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10928 With argument REMOVE, remove any scheduling date from the item.
10929 When TIME is set, it should be an internal time specification, and the
10930 scheduling will use the corresponding date."
10931 (interactive "P")
10932 (let* ((old-date (org-entry-get nil "SCHEDULED"))
10933 (repeater (and old-date
10934 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
10935 (match-string 1 old-date))))
10936 (if remove
10937 (progn
10938 (when (and old-date org-log-reschedule)
10939 (org-add-log-setup 'delschedule nil old-date 'findpos
10940 org-log-reschedule))
10941 (org-remove-timestamp-with-keyword org-scheduled-string)
10942 (message "Item is no longer scheduled."))
10943 (org-add-planning-info 'scheduled time 'closed)
10944 (when (and old-date org-log-reschedule
10945 (not (equal old-date
10946 (substring org-last-inserted-timestamp 1 -1))))
10947 (org-add-log-setup 'reschedule nil old-date 'findpos
10948 org-log-reschedule))
10949 (when repeater
10950 (save-excursion
10951 (org-back-to-heading t)
10952 (when (re-search-forward (concat org-scheduled-string " "
10953 org-last-inserted-timestamp)
10954 (save-excursion
10955 (outline-next-heading) (point)) t)
10956 (goto-char (1- (match-end 0)))
10957 (insert " " repeater)
10958 (setq org-last-inserted-timestamp
10959 (concat (substring org-last-inserted-timestamp 0 -1)
10960 " " repeater
10961 (substring org-last-inserted-timestamp -1))))))
10962 (message "Scheduled to %s" org-last-inserted-timestamp))))
10964 (defun org-get-scheduled-time (pom &optional inherit)
10965 "Get the scheduled time as a time tuple, of a format suitable
10966 for calling org-schedule with, or if there is no scheduling,
10967 returns nil."
10968 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10969 (when time
10970 (apply 'encode-time (org-parse-time-string time)))))
10972 (defun org-get-deadline-time (pom &optional inherit)
10973 "Get the deadine as a time tuple, of a format suitable for
10974 calling org-deadline with, or if there is no scheduling, returns
10975 nil."
10976 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10977 (when time
10978 (apply 'encode-time (org-parse-time-string time)))))
10980 (defun org-remove-timestamp-with-keyword (keyword)
10981 "Remove all time stamps with KEYWORD in the current entry."
10982 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10983 beg)
10984 (save-excursion
10985 (org-back-to-heading t)
10986 (setq beg (point))
10987 (outline-next-heading)
10988 (while (re-search-backward re beg t)
10989 (replace-match "")
10990 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10991 (equal (char-before) ?\ ))
10992 (backward-delete-char 1)
10993 (if (string-match "^[ \t]*$" (buffer-substring
10994 (point-at-bol) (point-at-eol)))
10995 (delete-region (point-at-bol)
10996 (min (point-max) (1+ (point-at-eol))))))))))
10998 (defun org-add-planning-info (what &optional time &rest remove)
10999 "Insert new timestamp with keyword in the line directly after the headline.
11000 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11001 If non is given, the user is prompted for a date.
11002 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11003 be removed."
11004 (interactive)
11005 (let (org-time-was-given org-end-time-was-given ts
11006 end default-time default-input)
11008 (catch 'exit
11009 (when (and (not time) (memq what '(scheduled deadline)))
11010 ;; Try to get a default date/time from existing timestamp
11011 (save-excursion
11012 (org-back-to-heading t)
11013 (setq end (save-excursion (outline-next-heading) (point)))
11014 (when (re-search-forward (if (eq what 'scheduled)
11015 org-scheduled-time-regexp
11016 org-deadline-time-regexp)
11017 end t)
11018 (setq ts (match-string 1)
11019 default-time
11020 (apply 'encode-time (org-parse-time-string ts))
11021 default-input (and ts (org-get-compact-tod ts))))))
11022 (when what
11023 ;; If necessary, get the time from the user
11024 (setq time (or time (org-read-date nil 'to-time nil nil
11025 default-time default-input))))
11027 (when (and org-insert-labeled-timestamps-at-point
11028 (member what '(scheduled deadline)))
11029 (insert
11030 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11031 (org-insert-time-stamp time org-time-was-given
11032 nil nil nil (list org-end-time-was-given))
11033 (setq what nil))
11034 (save-excursion
11035 (save-restriction
11036 (let (col list elt ts buffer-invisibility-spec)
11037 (org-back-to-heading t)
11038 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11039 (goto-char (match-end 1))
11040 (setq col (current-column))
11041 (goto-char (match-end 0))
11042 (if (eobp) (insert "\n") (forward-char 1))
11043 (when (and (not what)
11044 (not (looking-at
11045 (concat "[ \t]*"
11046 org-keyword-time-not-clock-regexp))))
11047 ;; Nothing to add, nothing to remove...... :-)
11048 (throw 'exit nil))
11049 (if (and (not (looking-at outline-regexp))
11050 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11051 "[^\r\n]*"))
11052 (not (equal (match-string 1) org-clock-string)))
11053 (narrow-to-region (match-beginning 0) (match-end 0))
11054 (insert-before-markers "\n")
11055 (backward-char 1)
11056 (narrow-to-region (point) (point))
11057 (and org-adapt-indentation (org-indent-to-column col)))
11058 ;; Check if we have to remove something.
11059 (setq list (cons what remove))
11060 (while list
11061 (setq elt (pop list))
11062 (goto-char (point-min))
11063 (when (or (and (eq elt 'scheduled)
11064 (re-search-forward org-scheduled-time-regexp nil t))
11065 (and (eq elt 'deadline)
11066 (re-search-forward org-deadline-time-regexp nil t))
11067 (and (eq elt 'closed)
11068 (re-search-forward org-closed-time-regexp nil t)))
11069 (replace-match "")
11070 (if (looking-at "--+<[^>]+>") (replace-match ""))
11071 (skip-chars-backward " ")
11072 (if (looking-at " +") (replace-match ""))))
11073 (goto-char (point-max))
11074 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11075 (when what
11076 (insert
11077 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11078 (cond ((eq what 'scheduled) org-scheduled-string)
11079 ((eq what 'deadline) org-deadline-string)
11080 ((eq what 'closed) org-closed-string))
11081 " ")
11082 (setq ts (org-insert-time-stamp
11083 time
11084 (or org-time-was-given
11085 (and (eq what 'closed) org-log-done-with-time))
11086 (eq what 'closed)
11087 nil nil (list org-end-time-was-given)))
11088 (end-of-line 1))
11089 (goto-char (point-min))
11090 (widen)
11091 (if (and (looking-at "[ \t]+\n")
11092 (equal (char-before) ?\n))
11093 (delete-region (1- (point)) (point-at-eol)))
11094 ts))))))
11096 (defvar org-log-note-marker (make-marker))
11097 (defvar org-log-note-purpose nil)
11098 (defvar org-log-note-state nil)
11099 (defvar org-log-note-previous-state nil)
11100 (defvar org-log-note-how nil)
11101 (defvar org-log-note-extra nil)
11102 (defvar org-log-note-window-configuration nil)
11103 (defvar org-log-note-return-to (make-marker))
11104 (defvar org-log-post-message nil
11105 "Message to be displayed after a log note has been stored.
11106 The auto-repeater uses this.")
11108 (defun org-add-note ()
11109 "Add a note to the current entry.
11110 This is done in the same way as adding a state change note."
11111 (interactive)
11112 (org-add-log-setup 'note nil nil 'findpos nil))
11114 (defvar org-property-end-re)
11115 (defun org-add-log-setup (&optional purpose state prev-state
11116 findpos how &optional extra)
11117 "Set up the post command hook to take a note.
11118 If this is about to TODO state change, the new state is expected in STATE.
11119 When FINDPOS is non-nil, find the correct position for the note in
11120 the current entry. If not, assume that it can be inserted at point.
11121 HOW is an indicator what kind of note should be created.
11122 EXTRA is additional text that will be inserted into the notes buffer."
11123 (let* ((org-log-into-drawer (org-log-into-drawer))
11124 (drawer (cond ((stringp org-log-into-drawer)
11125 org-log-into-drawer)
11126 (org-log-into-drawer "LOGBOOK")
11127 (t nil))))
11128 (save-restriction
11129 (save-excursion
11130 (when findpos
11131 (org-back-to-heading t)
11132 (narrow-to-region (point) (save-excursion
11133 (outline-next-heading) (point)))
11134 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11135 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11136 "[^\r\n]*\\)?"))
11137 (goto-char (match-end 0))
11138 (cond
11139 (drawer
11140 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11141 nil t)
11142 (progn
11143 (goto-char (match-end 0))
11144 (or org-log-states-order-reversed
11145 (and (re-search-forward org-property-end-re nil t)
11146 (goto-char (1- (match-beginning 0))))))
11147 (insert "\n:" drawer ":\n:END:")
11148 (beginning-of-line 0)
11149 (org-indent-line-function)
11150 (beginning-of-line 2)
11151 (org-indent-line-function)
11152 (end-of-line 0)))
11153 ((and org-log-state-notes-insert-after-drawers
11154 (save-excursion
11155 (forward-line) (looking-at org-drawer-regexp)))
11156 (forward-line)
11157 (while (looking-at org-drawer-regexp)
11158 (goto-char (match-end 0))
11159 (re-search-forward org-property-end-re (point-max) t)
11160 (forward-line))
11161 (forward-line -1)))
11162 (unless org-log-states-order-reversed
11163 (and (= (char-after) ?\n) (forward-char 1))
11164 (org-skip-over-state-notes)
11165 (skip-chars-backward " \t\n\r")))
11166 (move-marker org-log-note-marker (point))
11167 (setq org-log-note-purpose purpose
11168 org-log-note-state state
11169 org-log-note-previous-state prev-state
11170 org-log-note-how how
11171 org-log-note-extra extra)
11172 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11174 (defun org-skip-over-state-notes ()
11175 "Skip past the list of State notes in an entry."
11176 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11177 (while (looking-at "[ \t]*- State")
11178 (condition-case nil
11179 (org-next-item)
11180 (error (org-end-of-item)))))
11182 (defun org-add-log-note (&optional purpose)
11183 "Pop up a window for taking a note, and add this note later at point."
11184 (remove-hook 'post-command-hook 'org-add-log-note)
11185 (setq org-log-note-window-configuration (current-window-configuration))
11186 (delete-other-windows)
11187 (move-marker org-log-note-return-to (point))
11188 (switch-to-buffer (marker-buffer org-log-note-marker))
11189 (goto-char org-log-note-marker)
11190 (org-switch-to-buffer-other-window "*Org Note*")
11191 (erase-buffer)
11192 (if (memq org-log-note-how '(time state))
11193 (let (current-prefix-arg) (org-store-log-note))
11194 (let ((org-inhibit-startup t)) (org-mode))
11195 (insert (format "# Insert note for %s.
11196 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11197 (cond
11198 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11199 ((eq org-log-note-purpose 'done) "closed todo item")
11200 ((eq org-log-note-purpose 'state)
11201 (format "state change from \"%s\" to \"%s\""
11202 (or org-log-note-previous-state "")
11203 (or org-log-note-state "")))
11204 ((eq org-log-note-purpose 'reschedule)
11205 "rescheduling")
11206 ((eq org-log-note-purpose 'delschedule)
11207 "no longer scheduled")
11208 ((eq org-log-note-purpose 'redeadline)
11209 "changing deadline")
11210 ((eq org-log-note-purpose 'deldeadline)
11211 "removing deadline")
11212 ((eq org-log-note-purpose 'refile)
11213 "refiling")
11214 ((eq org-log-note-purpose 'note)
11215 "this entry")
11216 (t (error "This should not happen")))))
11217 (if org-log-note-extra (insert org-log-note-extra))
11218 (org-set-local 'org-finish-function 'org-store-log-note)))
11220 (defvar org-note-abort nil) ; dynamically scoped
11221 (defun org-store-log-note ()
11222 "Finish taking a log note, and insert it to where it belongs."
11223 (let ((txt (buffer-string))
11224 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11225 lines ind)
11226 (kill-buffer (current-buffer))
11227 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11228 (setq txt (replace-match "" t t txt)))
11229 (if (string-match "\\s-+\\'" txt)
11230 (setq txt (replace-match "" t t txt)))
11231 (setq lines (org-split-string txt "\n"))
11232 (when (and note (string-match "\\S-" note))
11233 (setq note
11234 (org-replace-escapes
11235 note
11236 (list (cons "%u" (user-login-name))
11237 (cons "%U" user-full-name)
11238 (cons "%t" (format-time-string
11239 (org-time-stamp-format 'long 'inactive)
11240 (current-time)))
11241 (cons "%s" (if org-log-note-state
11242 (concat "\"" org-log-note-state "\"")
11243 ""))
11244 (cons "%S" (if org-log-note-previous-state
11245 (concat "\"" org-log-note-previous-state "\"")
11246 "\"\"")))))
11247 (if lines (setq note (concat note " \\\\")))
11248 (push note lines))
11249 (when (or current-prefix-arg org-note-abort)
11250 (when org-log-into-drawer
11251 (org-remove-empty-drawer-at
11252 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11253 org-log-note-marker))
11254 (setq lines nil))
11255 (when lines
11256 (with-current-buffer (marker-buffer org-log-note-marker)
11257 (save-excursion
11258 (goto-char org-log-note-marker)
11259 (move-marker org-log-note-marker nil)
11260 (end-of-line 1)
11261 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11262 (insert "- " (pop lines))
11263 (org-indent-line-function)
11264 (beginning-of-line 1)
11265 (looking-at "[ \t]*")
11266 (setq ind (concat (match-string 0) " "))
11267 (end-of-line 1)
11268 (while lines (insert "\n" ind (pop lines)))
11269 (message "Note stored")
11270 (org-back-to-heading t)
11271 (org-cycle-hide-drawers 'children)))))
11272 (set-window-configuration org-log-note-window-configuration)
11273 (with-current-buffer (marker-buffer org-log-note-return-to)
11274 (goto-char org-log-note-return-to))
11275 (move-marker org-log-note-return-to nil)
11276 (and org-log-post-message (message "%s" org-log-post-message)))
11278 (defun org-remove-empty-drawer-at (drawer pos)
11279 "Remove an empty drawer DRAWER at position POS.
11280 POS may also be a marker."
11281 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11282 (save-excursion
11283 (save-restriction
11284 (widen)
11285 (goto-char pos)
11286 (if (org-in-regexp
11287 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11288 (replace-match ""))))))
11290 (defun org-sparse-tree (&optional arg)
11291 "Create a sparse tree, prompt for the details.
11292 This command can create sparse trees. You first need to select the type
11293 of match used to create the tree:
11295 t Show entries with a specific TODO keyword.
11296 m Show entries selected by a tags/property match.
11297 p Enter a property name and its value (both with completion on existing
11298 names/values) and show entries with that property.
11299 / Show entries matching a regular expression (`r' can be used as well)
11300 d Show deadlines due within `org-deadline-warning-days'.
11301 b Show deadlines and scheduled items before a date.
11302 a Show deadlines and scheduled items after a date."
11303 (interactive "P")
11304 (let (ans kwd value)
11305 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
11306 (setq ans (read-char-exclusive))
11307 (cond
11308 ((equal ans ?d)
11309 (call-interactively 'org-check-deadlines))
11310 ((equal ans ?b)
11311 (call-interactively 'org-check-before-date))
11312 ((equal ans ?a)
11313 (call-interactively 'org-check-after-date))
11314 ((equal ans ?t)
11315 (org-show-todo-tree '(4)))
11316 ((member ans '(?T ?m))
11317 (call-interactively 'org-match-sparse-tree))
11318 ((member ans '(?p ?P))
11319 (setq kwd (org-icompleting-read "Property: "
11320 (mapcar 'list (org-buffer-property-keys))))
11321 (setq value (org-icompleting-read "Value: "
11322 (mapcar 'list (org-property-values kwd))))
11323 (unless (string-match "\\`{.*}\\'" value)
11324 (setq value (concat "\"" value "\"")))
11325 (org-match-sparse-tree arg (concat kwd "=" value)))
11326 ((member ans '(?r ?R ?/))
11327 (call-interactively 'org-occur))
11328 (t (error "No such sparse tree command \"%c\"" ans)))))
11330 (defvar org-occur-highlights nil
11331 "List of overlays used for occur matches.")
11332 (make-variable-buffer-local 'org-occur-highlights)
11333 (defvar org-occur-parameters nil
11334 "Parameters of the active org-occur calls.
11335 This is a list, each call to org-occur pushes as cons cell,
11336 containing the regular expression and the callback, onto the list.
11337 The list can contain several entries if `org-occur' has been called
11338 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11339 will only contain one set of parameters. When the highlights are
11340 removed (for example with `C-c C-c', or with the next edit (depending
11341 on `org-remove-highlights-with-change'), this variable is emptied
11342 as well.")
11343 (make-variable-buffer-local 'org-occur-parameters)
11345 (defun org-occur (regexp &optional keep-previous callback)
11346 "Make a compact tree which shows all matches of REGEXP.
11347 The tree will show the lines where the regexp matches, and all higher
11348 headlines above the match. It will also show the heading after the match,
11349 to make sure editing the matching entry is easy.
11350 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11351 call to `org-occur' will be kept, to allow stacking of calls to this
11352 command.
11353 If CALLBACK is non-nil, it is a function which is called to confirm
11354 that the match should indeed be shown."
11355 (interactive "sRegexp: \nP")
11356 (when (equal regexp "")
11357 (error "Regexp cannot be empty"))
11358 (unless keep-previous
11359 (org-remove-occur-highlights nil nil t))
11360 (push (cons regexp callback) org-occur-parameters)
11361 (let ((cnt 0))
11362 (save-excursion
11363 (goto-char (point-min))
11364 (if (or (not keep-previous) ; do not want to keep
11365 (not org-occur-highlights)) ; no previous matches
11366 ;; hide everything
11367 (org-overview))
11368 (while (re-search-forward regexp nil t)
11369 (when (or (not callback)
11370 (save-match-data (funcall callback)))
11371 (setq cnt (1+ cnt))
11372 (when org-highlight-sparse-tree-matches
11373 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11374 (org-show-context 'occur-tree))))
11375 (when org-remove-highlights-with-change
11376 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11377 nil 'local))
11378 (unless org-sparse-tree-open-archived-trees
11379 (org-hide-archived-subtrees (point-min) (point-max)))
11380 (run-hooks 'org-occur-hook)
11381 (if (interactive-p)
11382 (message "%d match(es) for regexp %s" cnt regexp))
11383 cnt))
11385 (defun org-show-context (&optional key)
11386 "Make sure point and context and visible.
11387 How much context is shown depends upon the variables
11388 `org-show-hierarchy-above', `org-show-following-heading'. and
11389 `org-show-siblings'."
11390 (let ((heading-p (org-on-heading-p t))
11391 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11392 (following-p (org-get-alist-option org-show-following-heading key))
11393 (entry-p (org-get-alist-option org-show-entry-below key))
11394 (siblings-p (org-get-alist-option org-show-siblings key)))
11395 (catch 'exit
11396 ;; Show heading or entry text
11397 (if (and heading-p (not entry-p))
11398 (org-flag-heading nil) ; only show the heading
11399 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11400 (org-show-hidden-entry))) ; show entire entry
11401 (when following-p
11402 ;; Show next sibling, or heading below text
11403 (save-excursion
11404 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11405 (org-flag-heading nil))))
11406 (when siblings-p (org-show-siblings))
11407 (when hierarchy-p
11408 ;; show all higher headings, possibly with siblings
11409 (save-excursion
11410 (while (and (condition-case nil
11411 (progn (org-up-heading-all 1) t)
11412 (error nil))
11413 (not (bobp)))
11414 (org-flag-heading nil)
11415 (when siblings-p (org-show-siblings))))))))
11417 (defvar org-reveal-start-hook nil
11418 "Hook run before revealing a location.")
11420 (defun org-reveal (&optional siblings)
11421 "Show current entry, hierarchy above it, and the following headline.
11422 This can be used to show a consistent set of context around locations
11423 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11424 not t for the search context.
11426 With optional argument SIBLINGS, on each level of the hierarchy all
11427 siblings are shown. This repairs the tree structure to what it would
11428 look like when opened with hierarchical calls to `org-cycle'.
11429 With double optional argument `C-u C-u', go to the parent and show the
11430 entire tree."
11431 (interactive "P")
11432 (run-hooks 'org-reveal-start-hook)
11433 (let ((org-show-hierarchy-above t)
11434 (org-show-following-heading t)
11435 (org-show-siblings (if siblings t org-show-siblings)))
11436 (org-show-context nil))
11437 (when (equal siblings '(16))
11438 (save-excursion
11439 (when (org-up-heading-safe)
11440 (org-show-subtree)
11441 (run-hook-with-args 'org-cycle-hook 'subtree)))))
11443 (defun org-highlight-new-match (beg end)
11444 "Highlight from BEG to END and mark the highlight is an occur headline."
11445 (let ((ov (org-make-overlay beg end)))
11446 (org-overlay-put ov 'face 'secondary-selection)
11447 (push ov org-occur-highlights)))
11449 (defun org-remove-occur-highlights (&optional beg end noremove)
11450 "Remove the occur highlights from the buffer.
11451 BEG and END are ignored. If NOREMOVE is nil, remove this function
11452 from the `before-change-functions' in the current buffer."
11453 (interactive)
11454 (unless org-inhibit-highlight-removal
11455 (mapc 'org-delete-overlay org-occur-highlights)
11456 (setq org-occur-highlights nil)
11457 (setq org-occur-parameters nil)
11458 (unless noremove
11459 (remove-hook 'before-change-functions
11460 'org-remove-occur-highlights 'local))))
11462 ;;;; Priorities
11464 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11465 "Regular expression matching the priority indicator.")
11467 (defvar org-remove-priority-next-time nil)
11469 (defun org-priority-up ()
11470 "Increase the priority of the current item."
11471 (interactive)
11472 (org-priority 'up))
11474 (defun org-priority-down ()
11475 "Decrease the priority of the current item."
11476 (interactive)
11477 (org-priority 'down))
11479 (defun org-priority (&optional action)
11480 "Change the priority of an item by ARG.
11481 ACTION can be `set', `up', `down', or a character."
11482 (interactive)
11483 (unless org-enable-priority-commands
11484 (error "Priority commands are disabled"))
11485 (setq action (or action 'set))
11486 (let (current new news have remove)
11487 (save-excursion
11488 (org-back-to-heading t)
11489 (if (looking-at org-priority-regexp)
11490 (setq current (string-to-char (match-string 2))
11491 have t)
11492 (setq current org-default-priority))
11493 (cond
11494 ((eq action 'remove)
11495 (setq remove t new ?\ ))
11496 ((or (eq action 'set)
11497 (if (featurep 'xemacs) (characterp action) (integerp action)))
11498 (if (not (eq action 'set))
11499 (setq new action)
11500 (message "Priority %c-%c, SPC to remove: "
11501 org-highest-priority org-lowest-priority)
11502 (setq new (read-char-exclusive)))
11503 (if (and (= (upcase org-highest-priority) org-highest-priority)
11504 (= (upcase org-lowest-priority) org-lowest-priority))
11505 (setq new (upcase new)))
11506 (cond ((equal new ?\ ) (setq remove t))
11507 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11508 (error "Priority must be between `%c' and `%c'"
11509 org-highest-priority org-lowest-priority))))
11510 ((eq action 'up)
11511 (if (and (not have) (eq last-command this-command))
11512 (setq new org-lowest-priority)
11513 (setq new (if (and org-priority-start-cycle-with-default (not have))
11514 org-default-priority (1- current)))))
11515 ((eq action 'down)
11516 (if (and (not have) (eq last-command this-command))
11517 (setq new org-highest-priority)
11518 (setq new (if (and org-priority-start-cycle-with-default (not have))
11519 org-default-priority (1+ current)))))
11520 (t (error "Invalid action")))
11521 (if (or (< (upcase new) org-highest-priority)
11522 (> (upcase new) org-lowest-priority))
11523 (setq remove t))
11524 (setq news (format "%c" new))
11525 (if have
11526 (if remove
11527 (replace-match "" t t nil 1)
11528 (replace-match news t t nil 2))
11529 (if remove
11530 (error "No priority cookie found in line")
11531 (let ((case-fold-search nil))
11532 (looking-at org-todo-line-regexp))
11533 (if (match-end 2)
11534 (progn
11535 (goto-char (match-end 2))
11536 (insert " [#" news "]"))
11537 (goto-char (match-beginning 3))
11538 (insert "[#" news "] "))))
11539 (org-preserve-lc (org-set-tags nil 'align)))
11540 (if remove
11541 (message "Priority removed")
11542 (message "Priority of current item set to %s" news))))
11544 (defun org-get-priority (s)
11545 "Find priority cookie and return priority."
11546 (save-match-data
11547 (if (not (string-match org-priority-regexp s))
11548 (* 1000 (- org-lowest-priority org-default-priority))
11549 (* 1000 (- org-lowest-priority
11550 (string-to-char (match-string 2 s)))))))
11552 ;;;; Tags
11554 (defvar org-agenda-archives-mode)
11555 (defvar org-map-continue-from nil
11556 "Position from where mapping should continue.
11557 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11559 (defvar org-scanner-tags nil
11560 "The current tag list while the tags scanner is running.")
11561 (defvar org-trust-scanner-tags nil
11562 "Should `org-get-tags-at' use the tags fro the scanner.
11563 This is for internal dynamical scoping only.
11564 When this is non-nil, the function `org-get-tags-at' will return the value
11565 of `org-scanner-tags' instead of building the list by itself. This
11566 can lead to large speed-ups when the tags scanner is used in a file with
11567 many entries, and when the list of tags is retrieved, for example to
11568 obtain a list of properties. Building the tags list for each entry in such
11569 a file becomes an N^2 operation - but with this variable set, it scales
11570 as N.")
11572 (defun org-scan-tags (action matcher &optional todo-only)
11573 "Scan headline tags with inheritance and produce output ACTION.
11575 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11576 or `agenda' to produce an entry list for an agenda view. It can also be
11577 a Lisp form or a function that should be called at each matched headline, in
11578 this case the return value is a list of all return values from these calls.
11580 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11581 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11582 only lines with a TODO keyword are included in the output."
11583 (require 'org-agenda)
11584 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11585 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11586 (org-re
11587 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11588 (props (list 'face 'default
11589 'done-face 'org-agenda-done
11590 'undone-face 'default
11591 'mouse-face 'highlight
11592 'org-not-done-regexp org-not-done-regexp
11593 'org-todo-regexp org-todo-regexp
11594 'help-echo
11595 (format "mouse-2 or RET jump to org file %s"
11596 (abbreviate-file-name
11597 (or (buffer-file-name (buffer-base-buffer))
11598 (buffer-name (buffer-base-buffer)))))))
11599 (case-fold-search nil)
11600 (org-map-continue-from nil)
11601 lspos tags tags-list
11602 (tags-alist (list (cons 0 org-file-tags)))
11603 (llast 0) rtn rtn1 level category i txt
11604 todo marker entry priority)
11605 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11606 (setq action (list 'lambda nil action)))
11607 (save-excursion
11608 (goto-char (point-min))
11609 (when (eq action 'sparse-tree)
11610 (org-overview)
11611 (org-remove-occur-highlights))
11612 (while (re-search-forward re nil t)
11613 (catch :skip
11614 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11615 tags (if (match-end 4) (org-match-string-no-properties 4)))
11616 (goto-char (setq lspos (match-beginning 0)))
11617 (setq level (org-reduced-level (funcall outline-level))
11618 category (org-get-category))
11619 (setq i llast llast level)
11620 ;; remove tag lists from same and sublevels
11621 (while (>= i level)
11622 (when (setq entry (assoc i tags-alist))
11623 (setq tags-alist (delete entry tags-alist)))
11624 (setq i (1- i)))
11625 ;; add the next tags
11626 (when tags
11627 (setq tags (org-split-string tags ":")
11628 tags-alist
11629 (cons (cons level tags) tags-alist)))
11630 ;; compile tags for current headline
11631 (setq tags-list
11632 (if org-use-tag-inheritance
11633 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11634 tags)
11635 org-scanner-tags tags-list)
11636 (when org-use-tag-inheritance
11637 (setcdr (car tags-alist)
11638 (mapcar (lambda (x)
11639 (setq x (copy-sequence x))
11640 (org-add-prop-inherited x))
11641 (cdar tags-alist))))
11642 (when (and tags org-use-tag-inheritance
11643 (or (not (eq t org-use-tag-inheritance))
11644 org-tags-exclude-from-inheritance))
11645 ;; selective inheritance, remove uninherited ones
11646 (setcdr (car tags-alist)
11647 (org-remove-uniherited-tags (cdar tags-alist))))
11648 (when (and (or (not todo-only)
11649 (and (member todo org-not-done-keywords)
11650 (or (not org-agenda-tags-todo-honor-ignore-options)
11651 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11652 (let ((case-fold-search t)) (eval matcher))
11654 (not (member org-archive-tag tags-list))
11655 ;; we have an archive tag, should we use this anyway?
11656 (or (not org-agenda-skip-archived-trees)
11657 (and (eq action 'agenda) org-agenda-archives-mode))))
11658 (unless (eq action 'sparse-tree) (org-agenda-skip))
11660 ;; select this headline
11662 (cond
11663 ((eq action 'sparse-tree)
11664 (and org-highlight-sparse-tree-matches
11665 (org-get-heading) (match-end 0)
11666 (org-highlight-new-match
11667 (match-beginning 0) (match-beginning 1)))
11668 (org-show-context 'tags-tree))
11669 ((eq action 'agenda)
11670 (setq txt (org-format-agenda-item
11672 (concat
11673 (if (eq org-tags-match-list-sublevels 'indented)
11674 (make-string (1- level) ?.) "")
11675 (org-get-heading))
11676 category
11677 tags-list
11679 priority (org-get-priority txt))
11680 (goto-char lspos)
11681 (setq marker (org-agenda-new-marker))
11682 (org-add-props txt props
11683 'org-marker marker 'org-hd-marker marker 'org-category category
11684 'todo-state todo
11685 'priority priority 'type "tagsmatch")
11686 (push txt rtn))
11687 ((functionp action)
11688 (setq org-map-continue-from nil)
11689 (save-excursion
11690 (setq rtn1 (funcall action))
11691 (push rtn1 rtn)))
11692 (t (error "Invalid action")))
11694 ;; if we are to skip sublevels, jump to end of subtree
11695 (unless org-tags-match-list-sublevels
11696 (org-end-of-subtree t)
11697 (backward-char 1))))
11698 ;; Get the correct position from where to continue
11699 (if org-map-continue-from
11700 (goto-char org-map-continue-from)
11701 (and (= (point) lspos) (end-of-line 1)))))
11702 (when (and (eq action 'sparse-tree)
11703 (not org-sparse-tree-open-archived-trees))
11704 (org-hide-archived-subtrees (point-min) (point-max)))
11705 (nreverse rtn)))
11707 (defun org-remove-uniherited-tags (tags)
11708 "Remove all tags that are not inherited from the list TAGS."
11709 (cond
11710 ((eq org-use-tag-inheritance t)
11711 (if org-tags-exclude-from-inheritance
11712 (org-delete-all org-tags-exclude-from-inheritance tags)
11713 tags))
11714 ((not org-use-tag-inheritance) nil)
11715 ((stringp org-use-tag-inheritance)
11716 (delq nil (mapcar
11717 (lambda (x)
11718 (if (and (string-match org-use-tag-inheritance x)
11719 (not (member x org-tags-exclude-from-inheritance)))
11720 x nil))
11721 tags)))
11722 ((listp org-use-tag-inheritance)
11723 (delq nil (mapcar
11724 (lambda (x)
11725 (if (member x org-use-tag-inheritance) x nil))
11726 tags)))))
11728 (defvar todo-only) ;; dynamically scoped
11730 (defun org-match-sparse-tree (&optional todo-only match)
11731 "Create a sparse tree according to tags string MATCH.
11732 MATCH can contain positive and negative selection of tags, like
11733 \"+WORK+URGENT-WITHBOSS\".
11734 If optional argument TODO-ONLY is non-nil, only select lines that are
11735 also TODO lines."
11736 (interactive "P")
11737 (org-prepare-agenda-buffers (list (current-buffer)))
11738 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11740 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11742 (defvar org-cached-props nil)
11743 (defun org-cached-entry-get (pom property)
11744 (if (or (eq t org-use-property-inheritance)
11745 (and (stringp org-use-property-inheritance)
11746 (string-match org-use-property-inheritance property))
11747 (and (listp org-use-property-inheritance)
11748 (member property org-use-property-inheritance)))
11749 ;; Caching is not possible, check it directly
11750 (org-entry-get pom property 'inherit)
11751 ;; Get all properties, so that we can do complicated checks easily
11752 (cdr (assoc property (or org-cached-props
11753 (setq org-cached-props
11754 (org-entry-properties pom)))))))
11756 (defun org-global-tags-completion-table (&optional files)
11757 "Return the list of all tags in all agenda buffer/files."
11758 (save-excursion
11759 (org-uniquify
11760 (delq nil
11761 (apply 'append
11762 (mapcar
11763 (lambda (file)
11764 (set-buffer (find-file-noselect file))
11765 (append (org-get-buffer-tags)
11766 (mapcar (lambda (x) (if (stringp (car-safe x))
11767 (list (car-safe x)) nil))
11768 org-tag-alist)))
11769 (if (and files (car files))
11770 files
11771 (org-agenda-files))))))))
11773 (defun org-make-tags-matcher (match)
11774 "Create the TAGS//TODO matcher form for the selection string MATCH."
11775 ;; todo-only is scoped dynamically into this function, and the function
11776 ;; may change it if the matcher asks for it.
11777 (unless match
11778 ;; Get a new match request, with completion
11779 (let ((org-last-tags-completion-table
11780 (org-global-tags-completion-table)))
11781 (setq match (org-completing-read-no-i
11782 "Match: " 'org-tags-completion-function nil nil nil
11783 'org-tags-history))))
11785 ;; Parse the string and create a lisp form
11786 (let ((match0 match)
11787 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11788 minus tag mm
11789 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11790 orterms term orlist re-p str-p level-p level-op time-p
11791 prop-p pn pv po cat-p gv rest)
11792 (if (string-match "/+" match)
11793 ;; match contains also a todo-matching request
11794 (progn
11795 (setq tagsmatch (substring match 0 (match-beginning 0))
11796 todomatch (substring match (match-end 0)))
11797 (if (string-match "^!" todomatch)
11798 (setq todo-only t todomatch (substring todomatch 1)))
11799 (if (string-match "^\\s-*$" todomatch)
11800 (setq todomatch nil)))
11801 ;; only matching tags
11802 (setq tagsmatch match todomatch nil))
11804 ;; Make the tags matcher
11805 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11806 (setq tagsmatcher t)
11807 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11808 (while (setq term (pop orterms))
11809 (while (and (equal (substring term -1) "\\") orterms)
11810 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11811 (while (string-match re term)
11812 (setq rest (substring term (match-end 0))
11813 minus (and (match-end 1)
11814 (equal (match-string 1 term) "-"))
11815 tag (match-string 2 term)
11816 re-p (equal (string-to-char tag) ?{)
11817 level-p (match-end 4)
11818 prop-p (match-end 5)
11819 mm (cond
11820 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11821 (level-p
11822 (setq level-op (org-op-to-function (match-string 3 term)))
11823 `(,level-op level ,(string-to-number
11824 (match-string 4 term))))
11825 (prop-p
11826 (setq pn (match-string 5 term)
11827 po (match-string 6 term)
11828 pv (match-string 7 term)
11829 cat-p (equal pn "CATEGORY")
11830 re-p (equal (string-to-char pv) ?{)
11831 str-p (equal (string-to-char pv) ?\")
11832 time-p (save-match-data
11833 (string-match "^\"[[<].*[]>]\"$" pv))
11834 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11835 (if time-p (setq pv (org-matcher-time pv)))
11836 (setq po (org-op-to-function po (if time-p 'time str-p)))
11837 (cond
11838 ((equal pn "CATEGORY")
11839 (setq gv '(get-text-property (point) 'org-category)))
11840 ((equal pn "TODO")
11841 (setq gv 'todo))
11843 (setq gv `(org-cached-entry-get nil ,pn))))
11844 (if re-p
11845 (if (eq po 'org<>)
11846 `(not (string-match ,pv (or ,gv "")))
11847 `(string-match ,pv (or ,gv "")))
11848 (if str-p
11849 `(,po (or ,gv "") ,pv)
11850 `(,po (string-to-number (or ,gv ""))
11851 ,(string-to-number pv) ))))
11852 (t `(member ,tag tags-list)))
11853 mm (if minus (list 'not mm) mm)
11854 term rest)
11855 (push mm tagsmatcher))
11856 (push (if (> (length tagsmatcher) 1)
11857 (cons 'and tagsmatcher)
11858 (car tagsmatcher))
11859 orlist)
11860 (setq tagsmatcher nil))
11861 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11862 (setq tagsmatcher
11863 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11864 ;; Make the todo matcher
11865 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11866 (setq todomatcher t)
11867 (setq orterms (org-split-string todomatch "|") orlist nil)
11868 (while (setq term (pop orterms))
11869 (while (string-match re term)
11870 (setq minus (and (match-end 1)
11871 (equal (match-string 1 term) "-"))
11872 kwd (match-string 2 term)
11873 re-p (equal (string-to-char kwd) ?{)
11874 term (substring term (match-end 0))
11875 mm (if re-p
11876 `(string-match ,(substring kwd 1 -1) todo)
11877 (list 'equal 'todo kwd))
11878 mm (if minus (list 'not mm) mm))
11879 (push mm todomatcher))
11880 (push (if (> (length todomatcher) 1)
11881 (cons 'and todomatcher)
11882 (car todomatcher))
11883 orlist)
11884 (setq todomatcher nil))
11885 (setq todomatcher (if (> (length orlist) 1)
11886 (cons 'or orlist) (car orlist))))
11888 ;; Return the string and lisp forms of the matcher
11889 (setq matcher (if todomatcher
11890 (list 'and tagsmatcher todomatcher)
11891 tagsmatcher))
11892 (cons match0 matcher)))
11894 (defun org-op-to-function (op &optional stringp)
11895 "Turn an operator into the appropriate function."
11896 (setq op
11897 (cond
11898 ((equal op "<" ) '(< string< org-time<))
11899 ((equal op ">" ) '(> org-string> org-time>))
11900 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11901 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11902 ((member op '("=" "==")) '(= string= org-time=))
11903 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11904 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11906 (defun org<> (a b) (not (= a b)))
11907 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11908 (defun org-string>= (a b) (not (string< a b)))
11909 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11910 (defun org-string<> (a b) (not (string= a b)))
11911 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11912 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11913 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11914 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11915 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11916 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11917 (defun org-2ft (s)
11918 "Convert S to a floating point time.
11919 If S is already a number, just return it. If it is a string, parse
11920 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11921 (cond
11922 ((numberp s) s)
11923 ((stringp s)
11924 (condition-case nil
11925 (float-time (apply 'encode-time (org-parse-time-string s)))
11926 (error 0.)))
11927 (t 0.)))
11929 (defun org-time-today ()
11930 "Time in seconds today at 0:00.
11931 Returns the float number of seconds since the beginning of the
11932 epoch to the beginning of today (00:00)."
11933 (float-time (apply 'encode-time
11934 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11936 (defun org-matcher-time (s)
11937 "Interpret a time comparison value."
11938 (save-match-data
11939 (cond
11940 ((string= s "<now>") (float-time))
11941 ((string= s "<today>") (org-time-today))
11942 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11943 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11944 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11945 (+ (org-time-today)
11946 (* (string-to-number (match-string 1 s))
11947 (cdr (assoc (match-string 2 s)
11948 '(("d" . 86400.0) ("w" . 604800.0)
11949 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11950 (t (org-2ft s)))))
11952 (defun org-match-any-p (re list)
11953 "Does re match any element of list?"
11954 (setq list (mapcar (lambda (x) (string-match re x)) list))
11955 (delq nil list))
11957 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11958 (defvar org-tags-overlay (org-make-overlay 1 1))
11959 (org-detach-overlay org-tags-overlay)
11961 (defun org-get-local-tags-at (&optional pos)
11962 "Get a list of tags defined in the current headline."
11963 (org-get-tags-at pos 'local))
11965 (defun org-get-local-tags ()
11966 "Get a list of tags defined in the current headline."
11967 (org-get-tags-at nil 'local))
11969 (defun org-get-tags-at (&optional pos local)
11970 "Get a list of all headline tags applicable at POS.
11971 POS defaults to point. If tags are inherited, the list contains
11972 the targets in the same sequence as the headlines appear, i.e.
11973 the tags of the current headline come last.
11974 When LOCAL is non-nil, only return tags from the current headline,
11975 ignore inherited ones."
11976 (interactive)
11977 (if (and org-trust-scanner-tags
11978 (or (not pos) (equal pos (point)))
11979 (not local))
11980 org-scanner-tags
11981 (let (tags ltags lastpos parent)
11982 (save-excursion
11983 (save-restriction
11984 (widen)
11985 (goto-char (or pos (point)))
11986 (save-match-data
11987 (catch 'done
11988 (condition-case nil
11989 (progn
11990 (org-back-to-heading t)
11991 (while (not (equal lastpos (point)))
11992 (setq lastpos (point))
11993 (when (looking-at
11994 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11995 (setq ltags (org-split-string
11996 (org-match-string-no-properties 1) ":"))
11997 (when parent
11998 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11999 (setq tags (append
12000 (if parent
12001 (org-remove-uniherited-tags ltags)
12002 ltags)
12003 tags)))
12004 (or org-use-tag-inheritance (throw 'done t))
12005 (if local (throw 'done t))
12006 (or (org-up-heading-safe) (error nil))
12007 (setq parent t)))
12008 (error nil)))))
12009 (append (org-remove-uniherited-tags org-file-tags) tags)))))
12011 (defun org-add-prop-inherited (s)
12012 (add-text-properties 0 (length s) '(inherited t) s)
12015 (defun org-toggle-tag (tag &optional onoff)
12016 "Toggle the tag TAG for the current line.
12017 If ONOFF is `on' or `off', don't toggle but set to this state."
12018 (let (res current)
12019 (save-excursion
12020 (org-back-to-heading t)
12021 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
12022 (point-at-eol) t)
12023 (progn
12024 (setq current (match-string 1))
12025 (replace-match ""))
12026 (setq current ""))
12027 (setq current (nreverse (org-split-string current ":")))
12028 (cond
12029 ((eq onoff 'on)
12030 (setq res t)
12031 (or (member tag current) (push tag current)))
12032 ((eq onoff 'off)
12033 (or (not (member tag current)) (setq current (delete tag current))))
12034 (t (if (member tag current)
12035 (setq current (delete tag current))
12036 (setq res t)
12037 (push tag current))))
12038 (end-of-line 1)
12039 (if current
12040 (progn
12041 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12042 (org-set-tags nil t))
12043 (delete-horizontal-space))
12044 (run-hooks 'org-after-tags-change-hook))
12045 res))
12047 (defun org-align-tags-here (to-col)
12048 ;; Assumes that this is a headline
12049 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12050 (beginning-of-line 1)
12051 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12052 (< pos (match-beginning 2)))
12053 (progn
12054 (setq tags-l (- (match-end 2) (match-beginning 2)))
12055 (goto-char (match-beginning 1))
12056 (insert " ")
12057 (delete-region (point) (1+ (match-beginning 2)))
12058 (setq ncol (max (1+ (current-column))
12059 (1+ col)
12060 (if (> to-col 0)
12061 to-col
12062 (- (abs to-col) tags-l))))
12063 (setq p (point))
12064 (insert (make-string (- ncol (current-column)) ?\ ))
12065 (setq ncol (current-column))
12066 (when indent-tabs-mode (tabify p (point-at-eol)))
12067 (org-move-to-column (min ncol col) t))
12068 (goto-char pos))))
12070 (defun org-set-tags-command (&optional arg just-align)
12071 "Call the set-tags command for the current entry."
12072 (interactive "P")
12073 (if (org-on-heading-p)
12074 (org-set-tags arg just-align)
12075 (save-excursion
12076 (org-back-to-heading t)
12077 (org-set-tags arg just-align))))
12079 (defun org-set-tags-to (data)
12080 "Set the tags of the current entry to DATA, replacing the current tags.
12081 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12082 If DATA is nil or the empty string, any tags will be removed."
12083 (interactive "sTags: ")
12084 (setq data
12085 (cond
12086 ((eq data nil) "")
12087 ((equal data "") "")
12088 ((stringp data)
12089 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12090 ":"))
12091 ((listp data)
12092 (concat ":" (mapconcat 'identity data ":") ":"))
12093 (t nil)))
12094 (when data
12095 (save-excursion
12096 (org-back-to-heading t)
12097 (when (looking-at org-complex-heading-regexp)
12098 (if (match-end 5)
12099 (progn
12100 (goto-char (match-beginning 5))
12101 (insert data)
12102 (delete-region (point) (point-at-eol))
12103 (org-set-tags nil 'align))
12104 (goto-char (point-at-eol))
12105 (insert " " data)
12106 (org-set-tags nil 'align)))
12107 (beginning-of-line 1)
12108 (if (looking-at ".*?\\([ \t]+\\)$")
12109 (delete-region (match-beginning 1) (match-end 1))))))
12111 (defun org-set-tags (&optional arg just-align)
12112 "Set the tags for the current headline.
12113 With prefix ARG, realign all tags in headings in the current buffer."
12114 (interactive "P")
12115 (let* ((re (concat "^" outline-regexp))
12116 (current (org-get-tags-string))
12117 (col (current-column))
12118 (org-setting-tags t)
12119 table current-tags inherited-tags ; computed below when needed
12120 tags p0 c0 c1 rpl)
12121 (if arg
12122 (save-excursion
12123 (goto-char (point-min))
12124 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12125 (while (re-search-forward re nil t)
12126 (org-set-tags nil t)
12127 (end-of-line 1)))
12128 (message "All tags realigned to column %d" org-tags-column))
12129 (if just-align
12130 (setq tags current)
12131 ;; Get a new set of tags from the user
12132 (save-excursion
12133 (setq table (append org-tag-persistent-alist
12134 (or org-tag-alist (org-get-buffer-tags))
12135 (and org-complete-tags-always-offer-all-agenda-tags
12136 (org-global-tags-completion-table (org-agenda-files))))
12137 org-last-tags-completion-table table
12138 current-tags (org-split-string current ":")
12139 inherited-tags (nreverse
12140 (nthcdr (length current-tags)
12141 (nreverse (org-get-tags-at))))
12142 tags
12143 (if (or (eq t org-use-fast-tag-selection)
12144 (and org-use-fast-tag-selection
12145 (delq nil (mapcar 'cdr table))))
12146 (org-fast-tag-selection
12147 current-tags inherited-tags table
12148 (if org-fast-tag-selection-include-todo org-todo-key-alist))
12149 (let ((org-add-colon-after-tag-completion t))
12150 (org-trim
12151 (org-without-partial-completion
12152 (org-icompleting-read "Tags: " 'org-tags-completion-function
12153 nil nil current 'org-tags-history)))))))
12154 (while (string-match "[-+&]+" tags)
12155 ;; No boolean logic, just a list
12156 (setq tags (replace-match ":" t t tags))))
12158 (if org-tags-sort-function
12159 (setq tags (mapconcat 'identity
12160 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
12161 org-tags-sort-function) ":")))
12163 (if (string-match "\\`[\t ]*\\'" tags)
12164 (setq tags "")
12165 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12166 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12168 ;; Insert new tags at the correct column
12169 (beginning-of-line 1)
12170 (cond
12171 ((and (equal current "") (equal tags "")))
12172 ((re-search-forward
12173 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12174 (point-at-eol) t)
12175 (if (equal tags "")
12176 (setq rpl "")
12177 (goto-char (match-beginning 0))
12178 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
12179 (1+ (point)) (point))
12180 c1 (max (1+ c0) (if (> org-tags-column 0)
12181 org-tags-column
12182 (- (- org-tags-column) (length tags))))
12183 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12184 (replace-match rpl t t)
12185 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
12186 tags)
12187 (t (error "Tags alignment failed")))
12188 (org-move-to-column col)
12189 (unless just-align
12190 (run-hooks 'org-after-tags-change-hook)))))
12192 (defun org-change-tag-in-region (beg end tag off)
12193 "Add or remove TAG for each entry in the region.
12194 This works in the agenda, and also in an org-mode buffer."
12195 (interactive
12196 (list (region-beginning) (region-end)
12197 (let ((org-last-tags-completion-table
12198 (if (org-mode-p)
12199 (org-get-buffer-tags)
12200 (org-global-tags-completion-table))))
12201 (org-icompleting-read
12202 "Tag: " 'org-tags-completion-function nil nil nil
12203 'org-tags-history))
12204 (progn
12205 (message "[s]et or [r]emove? ")
12206 (equal (read-char-exclusive) ?r))))
12207 (if (fboundp 'deactivate-mark) (deactivate-mark))
12208 (let ((agendap (equal major-mode 'org-agenda-mode))
12209 l1 l2 m buf pos newhead (cnt 0))
12210 (goto-char end)
12211 (setq l2 (1- (org-current-line)))
12212 (goto-char beg)
12213 (setq l1 (org-current-line))
12214 (loop for l from l1 to l2 do
12215 (org-goto-line l)
12216 (setq m (get-text-property (point) 'org-hd-marker))
12217 (when (or (and (org-mode-p) (org-on-heading-p))
12218 (and agendap m))
12219 (setq buf (if agendap (marker-buffer m) (current-buffer))
12220 pos (if agendap m (point)))
12221 (with-current-buffer buf
12222 (save-excursion
12223 (save-restriction
12224 (goto-char pos)
12225 (setq cnt (1+ cnt))
12226 (org-toggle-tag tag (if off 'off 'on))
12227 (setq newhead (org-get-heading)))))
12228 (and agendap (org-agenda-change-all-lines newhead m))))
12229 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12231 (defun org-tags-completion-function (string predicate &optional flag)
12232 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12233 (confirm (lambda (x) (stringp (car x)))))
12234 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12235 (setq s1 (match-string 1 string)
12236 s2 (match-string 2 string))
12237 (setq s1 "" s2 string))
12238 (cond
12239 ((eq flag nil)
12240 ;; try completion
12241 (setq rtn (try-completion s2 ctable confirm))
12242 (if (stringp rtn)
12243 (setq rtn
12244 (concat s1 s2 (substring rtn (length s2))
12245 (if (and org-add-colon-after-tag-completion
12246 (assoc rtn ctable))
12247 ":" ""))))
12248 rtn)
12249 ((eq flag t)
12250 ;; all-completions
12251 (all-completions s2 ctable confirm)
12253 ((eq flag 'lambda)
12254 ;; exact match?
12255 (assoc s2 ctable)))
12258 (defun org-fast-tag-insert (kwd tags face &optional end)
12259 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12260 (insert (format "%-12s" (concat kwd ":"))
12261 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12262 (or end "")))
12264 (defun org-fast-tag-show-exit (flag)
12265 (save-excursion
12266 (org-goto-line 3)
12267 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12268 (replace-match ""))
12269 (when flag
12270 (end-of-line 1)
12271 (org-move-to-column (- (window-width) 19) t)
12272 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12274 (defun org-set-current-tags-overlay (current prefix)
12275 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12276 (if (featurep 'xemacs)
12277 (org-overlay-display org-tags-overlay (concat prefix s)
12278 'secondary-selection)
12279 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12280 (org-overlay-display org-tags-overlay (concat prefix s)))))
12282 (defvar org-last-tag-selection-key nil)
12283 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12284 "Fast tag selection with single keys.
12285 CURRENT is the current list of tags in the headline, INHERITED is the
12286 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12287 possibly with grouping information. TODO-TABLE is a similar table with
12288 TODO keywords, should these have keys assigned to them.
12289 If the keys are nil, a-z are automatically assigned.
12290 Returns the new tags string, or nil to not change the current settings."
12291 (let* ((fulltable (append table todo-table))
12292 (maxlen (apply 'max (mapcar
12293 (lambda (x)
12294 (if (stringp (car x)) (string-width (car x)) 0))
12295 fulltable)))
12296 (buf (current-buffer))
12297 (expert (eq org-fast-tag-selection-single-key 'expert))
12298 (buffer-tags nil)
12299 (fwidth (+ maxlen 3 1 3))
12300 (ncol (/ (- (window-width) 4) fwidth))
12301 (i-face 'org-done)
12302 (c-face 'org-todo)
12303 tg cnt e c char c1 c2 ntable tbl rtn
12304 ov-start ov-end ov-prefix
12305 (exit-after-next org-fast-tag-selection-single-key)
12306 (done-keywords org-done-keywords)
12307 groups ingroup)
12308 (save-excursion
12309 (beginning-of-line 1)
12310 (if (looking-at
12311 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12312 (setq ov-start (match-beginning 1)
12313 ov-end (match-end 1)
12314 ov-prefix "")
12315 (setq ov-start (1- (point-at-eol))
12316 ov-end (1+ ov-start))
12317 (skip-chars-forward "^\n\r")
12318 (setq ov-prefix
12319 (concat
12320 (buffer-substring (1- (point)) (point))
12321 (if (> (current-column) org-tags-column)
12323 (make-string (- org-tags-column (current-column)) ?\ ))))))
12324 (org-move-overlay org-tags-overlay ov-start ov-end)
12325 (save-window-excursion
12326 (if expert
12327 (set-buffer (get-buffer-create " *Org tags*"))
12328 (delete-other-windows)
12329 (split-window-vertically)
12330 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12331 (erase-buffer)
12332 (org-set-local 'org-done-keywords done-keywords)
12333 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12334 (org-fast-tag-insert "Current" current c-face "\n\n")
12335 (org-fast-tag-show-exit exit-after-next)
12336 (org-set-current-tags-overlay current ov-prefix)
12337 (setq tbl fulltable char ?a cnt 0)
12338 (while (setq e (pop tbl))
12339 (cond
12340 ((equal (car e) :startgroup)
12341 (push '() groups) (setq ingroup t)
12342 (when (not (= cnt 0))
12343 (setq cnt 0)
12344 (insert "\n"))
12345 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12346 ((equal (car e) :endgroup)
12347 (setq ingroup nil cnt 0)
12348 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12349 ((equal e '(:newline))
12350 (when (not (= cnt 0))
12351 (setq cnt 0)
12352 (insert "\n")
12353 (setq e (car tbl))
12354 (while (equal (car tbl) '(:newline))
12355 (insert "\n")
12356 (setq tbl (cdr tbl)))))
12358 (setq tg (copy-sequence (car e)) c2 nil)
12359 (if (cdr e)
12360 (setq c (cdr e))
12361 ;; automatically assign a character.
12362 (setq c1 (string-to-char
12363 (downcase (substring
12364 tg (if (= (string-to-char tg) ?@) 1 0)))))
12365 (if (or (rassoc c1 ntable) (rassoc c1 table))
12366 (while (or (rassoc char ntable) (rassoc char table))
12367 (setq char (1+ char)))
12368 (setq c2 c1))
12369 (setq c (or c2 char)))
12370 (if ingroup (push tg (car groups)))
12371 (setq tg (org-add-props tg nil 'face
12372 (cond
12373 ((not (assoc tg table))
12374 (org-get-todo-face tg))
12375 ((member tg current) c-face)
12376 ((member tg inherited) i-face)
12377 (t nil))))
12378 (if (and (= cnt 0) (not ingroup)) (insert " "))
12379 (insert "[" c "] " tg (make-string
12380 (- fwidth 4 (length tg)) ?\ ))
12381 (push (cons tg c) ntable)
12382 (when (= (setq cnt (1+ cnt)) ncol)
12383 (insert "\n")
12384 (if ingroup (insert " "))
12385 (setq cnt 0)))))
12386 (setq ntable (nreverse ntable))
12387 (insert "\n")
12388 (goto-char (point-min))
12389 (if (not expert) (org-fit-window-to-buffer))
12390 (setq rtn
12391 (catch 'exit
12392 (while t
12393 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12394 (if (not groups) "no " "")
12395 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12396 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12397 (setq org-last-tag-selection-key c)
12398 (cond
12399 ((= c ?\r) (throw 'exit t))
12400 ((= c ?!)
12401 (setq groups (not groups))
12402 (goto-char (point-min))
12403 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12404 ((= c ?\C-c)
12405 (if (not expert)
12406 (org-fast-tag-show-exit
12407 (setq exit-after-next (not exit-after-next)))
12408 (setq expert nil)
12409 (delete-other-windows)
12410 (split-window-vertically)
12411 (org-switch-to-buffer-other-window " *Org tags*")
12412 (org-fit-window-to-buffer)))
12413 ((or (= c ?\C-g)
12414 (and (= c ?q) (not (rassoc c ntable))))
12415 (org-detach-overlay org-tags-overlay)
12416 (setq quit-flag t))
12417 ((= c ?\ )
12418 (setq current nil)
12419 (if exit-after-next (setq exit-after-next 'now)))
12420 ((= c ?\t)
12421 (condition-case nil
12422 (setq tg (org-icompleting-read
12423 "Tag: "
12424 (or buffer-tags
12425 (with-current-buffer buf
12426 (org-get-buffer-tags)))))
12427 (quit (setq tg "")))
12428 (when (string-match "\\S-" tg)
12429 (add-to-list 'buffer-tags (list tg))
12430 (if (member tg current)
12431 (setq current (delete tg current))
12432 (push tg current)))
12433 (if exit-after-next (setq exit-after-next 'now)))
12434 ((setq e (rassoc c todo-table) tg (car e))
12435 (with-current-buffer buf
12436 (save-excursion (org-todo tg)))
12437 (if exit-after-next (setq exit-after-next 'now)))
12438 ((setq e (rassoc c ntable) tg (car e))
12439 (if (member tg current)
12440 (setq current (delete tg current))
12441 (loop for g in groups do
12442 (if (member tg g)
12443 (mapc (lambda (x)
12444 (setq current (delete x current)))
12445 g)))
12446 (push tg current))
12447 (if exit-after-next (setq exit-after-next 'now))))
12449 ;; Create a sorted list
12450 (setq current
12451 (sort current
12452 (lambda (a b)
12453 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12454 (if (eq exit-after-next 'now) (throw 'exit t))
12455 (goto-char (point-min))
12456 (beginning-of-line 2)
12457 (delete-region (point) (point-at-eol))
12458 (org-fast-tag-insert "Current" current c-face)
12459 (org-set-current-tags-overlay current ov-prefix)
12460 (while (re-search-forward
12461 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12462 (setq tg (match-string 1))
12463 (add-text-properties
12464 (match-beginning 1) (match-end 1)
12465 (list 'face
12466 (cond
12467 ((member tg current) c-face)
12468 ((member tg inherited) i-face)
12469 (t (get-text-property (match-beginning 1) 'face))))))
12470 (goto-char (point-min)))))
12471 (org-detach-overlay org-tags-overlay)
12472 (if rtn
12473 (mapconcat 'identity current ":")
12474 nil))))
12476 (defun org-get-tags-string ()
12477 "Get the TAGS string in the current headline."
12478 (unless (org-on-heading-p t)
12479 (error "Not on a heading"))
12480 (save-excursion
12481 (beginning-of-line 1)
12482 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12483 (org-match-string-no-properties 1)
12484 "")))
12486 (defun org-get-tags ()
12487 "Get the list of tags specified in the current headline."
12488 (org-split-string (org-get-tags-string) ":"))
12490 (defun org-get-buffer-tags ()
12491 "Get a table of all tags used in the buffer, for completion."
12492 (let (tags)
12493 (save-excursion
12494 (goto-char (point-min))
12495 (while (re-search-forward
12496 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12497 (when (equal (char-after (point-at-bol 0)) ?*)
12498 (mapc (lambda (x) (add-to-list 'tags x))
12499 (org-split-string (org-match-string-no-properties 1) ":")))))
12500 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12501 (mapcar 'list tags)))
12503 ;;;; The mapping API
12505 ;;;###autoload
12506 (defun org-map-entries (func &optional match scope &rest skip)
12507 "Call FUNC at each headline selected by MATCH in SCOPE.
12509 FUNC is a function or a lisp form. The function will be called without
12510 arguments, with the cursor positioned at the beginning of the headline.
12511 The return values of all calls to the function will be collected and
12512 returned as a list.
12514 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12515 does not need to preserve point. After evaluation, the cursor will be
12516 moved to the end of the line (presumably of the headline of the
12517 processed entry) and search continues from there. Under some
12518 circumstances, this may not produce the wanted results. For example,
12519 if you have removed (e.g. archived) the current (sub)tree it could
12520 mean that the next entry will be skipped entirely. In such cases, you
12521 can specify the position from where search should continue by making
12522 FUNC set the variable `org-map-continue-from' to the desired buffer
12523 position.
12525 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12526 Only headlines that are matched by this query will be considered during
12527 the iteration. When MATCH is nil or t, all headlines will be
12528 visited by the iteration.
12530 SCOPE determines the scope of this command. It can be any of:
12532 nil The current buffer, respecting the restriction if any
12533 tree The subtree started with the entry at point
12534 file The current buffer, without restriction
12535 file-with-archives
12536 The current buffer, and any archives associated with it
12537 agenda All agenda files
12538 agenda-with-archives
12539 All agenda files with any archive files associated with them
12540 \(file1 file2 ...)
12541 If this is a list, all files in the list will be scanned
12543 The remaining args are treated as settings for the skipping facilities of
12544 the scanner. The following items can be given here:
12546 archive skip trees with the archive tag.
12547 comment skip trees with the COMMENT keyword
12548 function or Emacs Lisp form:
12549 will be used as value for `org-agenda-skip-function', so whenever
12550 the function returns t, FUNC will not be called for that
12551 entry and search will continue from the point where the
12552 function leaves it.
12554 If your function needs to retrieve the tags including inherited tags
12555 at the *current* entry, you can use the value of the variable
12556 `org-scanner-tags' which will be much faster than getting the value
12557 with `org-get-tags-at'. If your function gets properties with
12558 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12559 to t around the call to `org-entry-properties' to get the same speedup.
12560 Note that if your function moves around to retrieve tags and properties at
12561 a *different* entry, you cannot use these techniques."
12562 (let* ((org-agenda-archives-mode nil) ; just to make sure
12563 (org-agenda-skip-archived-trees (memq 'archive skip))
12564 (org-agenda-skip-comment-trees (memq 'comment skip))
12565 (org-agenda-skip-function
12566 (car (org-delete-all '(comment archive) skip)))
12567 (org-tags-match-list-sublevels t)
12568 matcher file res
12569 org-todo-keywords-for-agenda
12570 org-done-keywords-for-agenda
12571 org-todo-keyword-alist-for-agenda
12572 org-drawers-for-agenda
12573 org-tag-alist-for-agenda)
12575 (cond
12576 ((eq match t) (setq matcher t))
12577 ((eq match nil) (setq matcher t))
12578 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12580 (save-excursion
12581 (save-restriction
12582 (when (eq scope 'tree)
12583 (org-back-to-heading t)
12584 (org-narrow-to-subtree)
12585 (setq scope nil))
12587 (if (not scope)
12588 (progn
12589 (org-prepare-agenda-buffers
12590 (list (buffer-file-name (current-buffer))))
12591 (setq res (org-scan-tags func matcher)))
12592 ;; Get the right scope
12593 (cond
12594 ((and scope (listp scope) (symbolp (car scope)))
12595 (setq scope (eval scope)))
12596 ((eq scope 'agenda)
12597 (setq scope (org-agenda-files t)))
12598 ((eq scope 'agenda-with-archives)
12599 (setq scope (org-agenda-files t))
12600 (setq scope (org-add-archive-files scope)))
12601 ((eq scope 'file)
12602 (setq scope (list (buffer-file-name))))
12603 ((eq scope 'file-with-archives)
12604 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12605 (org-prepare-agenda-buffers scope)
12606 (while (setq file (pop scope))
12607 (with-current-buffer (org-find-base-buffer-visiting file)
12608 (save-excursion
12609 (save-restriction
12610 (widen)
12611 (goto-char (point-min))
12612 (setq res (append res (org-scan-tags func matcher))))))))))
12613 res))
12615 ;;;; Properties
12617 ;;; Setting and retrieving properties
12619 (defconst org-special-properties
12620 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12621 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
12622 "The special properties valid in Org-mode.
12624 These are properties that are not defined in the property drawer,
12625 but in some other way.")
12627 (defconst org-default-properties
12628 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12629 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12630 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12631 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12632 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12633 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
12634 "Some properties that are used by Org-mode for various purposes.
12635 Being in this list makes sure that they are offered for completion.")
12637 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12638 "Regular expression matching the first line of a property drawer.")
12640 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12641 "Regular expression matching the last line of a property drawer.")
12643 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12644 "Regular expression matching the first line of a property drawer.")
12646 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12647 "Regular expression matching the first line of a property drawer.")
12649 (defconst org-property-drawer-re
12650 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12651 org-property-end-re "\\)\n?")
12652 "Matches an entire property drawer.")
12654 (defconst org-clock-drawer-re
12655 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12656 org-property-end-re "\\)\n?")
12657 "Matches an entire clock drawer.")
12659 (defun org-property-action ()
12660 "Do an action on properties."
12661 (interactive)
12662 (let (c)
12663 (org-at-property-p)
12664 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12665 (setq c (read-char-exclusive))
12666 (cond
12667 ((equal c ?s)
12668 (call-interactively 'org-set-property))
12669 ((equal c ?d)
12670 (call-interactively 'org-delete-property))
12671 ((equal c ?D)
12672 (call-interactively 'org-delete-property-globally))
12673 ((equal c ?c)
12674 (call-interactively 'org-compute-property-at-point))
12675 (t (error "No such property action %c" c)))))
12677 (defun org-set-effort (&optional value)
12678 "Set the effort property of the current entry.
12679 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12680 allowed value."
12681 (interactive "P")
12682 (if (equal value 0) (setq value 10))
12683 (let* ((completion-ignore-case t)
12684 (prop org-effort-property)
12685 (cur (org-entry-get nil prop))
12686 (allowed (org-property-get-allowed-values nil prop 'table))
12687 (existing (mapcar 'list (org-property-values prop)))
12689 (val (cond
12690 ((stringp value) value)
12691 ((and allowed (integerp value))
12692 (or (car (nth (1- value) allowed))
12693 (car (org-last allowed))))
12694 (allowed
12695 (message "Select 1-9,0, [RET%s]: %s"
12696 (if cur (concat "=" cur) "")
12697 (mapconcat 'car allowed " "))
12698 (setq rpl (read-char-exclusive))
12699 (if (equal rpl ?\r)
12701 (setq rpl (- rpl ?0))
12702 (if (equal rpl 0) (setq rpl 10))
12703 (if (and (> rpl 0) (<= rpl (length allowed)))
12704 (car (nth (1- rpl) allowed))
12705 (org-completing-read "Effort: " allowed nil))))
12707 (let (org-completion-use-ido org-completion-use-iswitchb)
12708 (org-completing-read
12709 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12710 (concat "[" cur "]") "")
12711 ": ")
12712 existing nil nil "" nil cur))))))
12713 (unless (equal (org-entry-get nil prop) val)
12714 (org-entry-put nil prop val))
12715 (message "%s is now %s" prop val)))
12717 (defun org-at-property-p ()
12718 "Is cursor inside a property drawer?"
12719 (save-excursion
12720 (beginning-of-line 1)
12721 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
12722 (let ((match (match-data)) ;; Keep match-data for use by calling
12723 (p (point)) ;; procedures.
12724 (range (unless (org-before-first-heading-p)
12725 (org-get-property-block))))
12726 (prog1 (and range (<= (car range) p) (< p (cdr range)))
12727 (set-match-data match))))))
12729 (defun org-get-property-block (&optional beg end force)
12730 "Return the (beg . end) range of the body of the property drawer.
12731 BEG and END can be beginning and end of subtree, if not given
12732 they will be found.
12733 If the drawer does not exist and FORCE is non-nil, create the drawer."
12734 (catch 'exit
12735 (save-excursion
12736 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12737 (end (or end (progn (outline-next-heading) (point)))))
12738 (goto-char beg)
12739 (if (re-search-forward org-property-start-re end t)
12740 (setq beg (1+ (match-end 0)))
12741 (if force
12742 (save-excursion
12743 (org-insert-property-drawer)
12744 (setq end (progn (outline-next-heading) (point))))
12745 (throw 'exit nil))
12746 (goto-char beg)
12747 (if (re-search-forward org-property-start-re end t)
12748 (setq beg (1+ (match-end 0)))))
12749 (if (re-search-forward org-property-end-re end t)
12750 (setq end (match-beginning 0))
12751 (or force (throw 'exit nil))
12752 (goto-char beg)
12753 (setq end beg)
12754 (org-indent-line-function)
12755 (insert ":END:\n"))
12756 (cons beg end)))))
12758 (defun org-entry-properties (&optional pom which specific)
12759 "Get all properties of the entry at point-or-marker POM.
12760 This includes the TODO keyword, the tags, time strings for deadline,
12761 scheduled, and clocking, and any additional properties defined in the
12762 entry. The return value is an alist, keys may occur multiple times
12763 if the property key was used several times.
12764 POM may also be nil, in which case the current entry is used.
12765 If WHICH is nil or `all', get all properties. If WHICH is
12766 `special' or `standard', only get that subclass. If WHICH
12767 is a string only get exactly this property. Specific can be a string, the
12768 specific property we are interested in. Specifying it can speed
12769 things up because then unnecessary parsing is avoided."
12770 (setq which (or which 'all))
12771 (org-with-point-at pom
12772 (let ((clockstr (substring org-clock-string 0 -1))
12773 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
12774 (case-fold-search nil)
12775 beg end range props sum-props key value string clocksum)
12776 (save-excursion
12777 (when (condition-case nil
12778 (and (org-mode-p) (org-back-to-heading t))
12779 (error nil))
12780 (setq beg (point))
12781 (setq sum-props (get-text-property (point) 'org-summaries))
12782 (setq clocksum (get-text-property (point) :org-clock-minutes))
12783 (outline-next-heading)
12784 (setq end (point))
12785 (when (memq which '(all special))
12786 ;; Get the special properties, like TODO and tags
12787 (goto-char beg)
12788 (when (and (or (not specific) (string= specific "TODO"))
12789 (looking-at org-todo-line-regexp) (match-end 2))
12790 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12791 (when (and (or (not specific) (string= specific "PRIORITY"))
12792 (looking-at org-priority-regexp))
12793 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12794 (when (and (or (not specific) (string= specific "TAGS"))
12795 (setq value (org-get-tags-string))
12796 (string-match "\\S-" value))
12797 (push (cons "TAGS" value) props))
12798 (when (and (or (not specific) (string= specific "ALLTAGS"))
12799 (setq value (org-get-tags-at)))
12800 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
12801 ":"))
12802 props))
12803 (when (or (not specific) (string= specific "BLOCKED"))
12804 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
12805 (when (or (not specific)
12806 (member specific org-all-time-keywords)
12807 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
12808 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12809 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12810 string (if (equal key clockstr)
12811 (org-no-properties
12812 (org-trim
12813 (buffer-substring
12814 (match-beginning 3) (goto-char (point-at-eol)))))
12815 (substring (org-match-string-no-properties 3) 1 -1)))
12816 (unless key
12817 (if (= (char-after (match-beginning 3)) ?\[)
12818 (setq key "TIMESTAMP_IA")
12819 (setq key "TIMESTAMP")))
12820 (when (or (equal key clockstr) (not (assoc key props)))
12821 (push (cons key string) props))))
12825 (when (memq which '(all standard))
12826 ;; Get the standard properties, like :PROP: ...
12827 (setq range (org-get-property-block beg end))
12828 (when range
12829 (goto-char (car range))
12830 (while (re-search-forward
12831 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12832 (cdr range) t)
12833 (setq key (org-match-string-no-properties 1)
12834 value (org-trim (or (org-match-string-no-properties 2) "")))
12835 (unless (member key excluded)
12836 (push (cons key (or value "")) props)))))
12837 (if clocksum
12838 (push (cons "CLOCKSUM"
12839 (org-columns-number-to-string (/ (float clocksum) 60.)
12840 'add_times))
12841 props))
12842 (unless (assoc "CATEGORY" props)
12843 (setq value (or (org-get-category)
12844 (progn (org-refresh-category-properties)
12845 (org-get-category))))
12846 (push (cons "CATEGORY" value) props))
12847 (append sum-props (nreverse props)))))))
12849 (defun org-entry-get (pom property &optional inherit)
12850 "Get value of PROPERTY for entry at point-or-marker POM.
12851 If INHERIT is non-nil and the entry does not have the property,
12852 then also check higher levels of the hierarchy.
12853 If INHERIT is the symbol `selective', use inheritance only if the setting
12854 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12855 If the property is present but empty, the return value is the empty string.
12856 If the property is not present at all, nil is returned."
12857 (org-with-point-at pom
12858 (if (and inherit (if (eq inherit 'selective)
12859 (org-property-inherit-p property)
12861 (org-entry-get-with-inheritance property)
12862 (if (member property org-special-properties)
12863 ;; We need a special property. Use `org-entry-properties' to
12864 ;; retrieve it, but specify the wanted property
12865 (cdr (assoc property (org-entry-properties nil 'special property)))
12866 (let ((range (org-get-property-block)))
12867 (if (and range
12868 (goto-char (car range))
12869 (re-search-forward
12870 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12871 (cdr range) t))
12872 ;; Found the property, return it.
12873 (if (match-end 1)
12874 (org-match-string-no-properties 1)
12875 "")))))))
12877 (defun org-property-or-variable-value (var &optional inherit)
12878 "Check if there is a property fixing the value of VAR.
12879 If yes, return this value. If not, return the current value of the variable."
12880 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12881 (if (and prop (stringp prop) (string-match "\\S-" prop))
12882 (read prop)
12883 (symbol-value var))))
12885 (defun org-entry-delete (pom property)
12886 "Delete the property PROPERTY from entry at point-or-marker POM."
12887 (org-with-point-at pom
12888 (if (member property org-special-properties)
12889 nil ; cannot delete these properties.
12890 (let ((range (org-get-property-block)))
12891 (if (and range
12892 (goto-char (car range))
12893 (re-search-forward
12894 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12895 (cdr range) t))
12896 (progn
12897 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12899 nil)))))
12901 ;; Multi-values properties are properties that contain multiple values
12902 ;; These values are assumed to be single words, separated by whitespace.
12903 (defun org-entry-add-to-multivalued-property (pom property value)
12904 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12905 (let* ((old (org-entry-get pom property))
12906 (values (and old (org-split-string old "[ \t]"))))
12907 (setq value (org-entry-protect-space value))
12908 (unless (member value values)
12909 (setq values (cons value values))
12910 (org-entry-put pom property
12911 (mapconcat 'identity values " ")))))
12913 (defun org-entry-remove-from-multivalued-property (pom property value)
12914 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12915 (let* ((old (org-entry-get pom property))
12916 (values (and old (org-split-string old "[ \t]"))))
12917 (setq value (org-entry-protect-space value))
12918 (when (member value values)
12919 (setq values (delete value values))
12920 (org-entry-put pom property
12921 (mapconcat 'identity values " ")))))
12923 (defun org-entry-member-in-multivalued-property (pom property value)
12924 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12925 (let* ((old (org-entry-get pom property))
12926 (values (and old (org-split-string old "[ \t]"))))
12927 (setq value (org-entry-protect-space value))
12928 (member value values)))
12930 (defun org-entry-get-multivalued-property (pom property)
12931 "Return a list of values in a multivalued property."
12932 (let* ((value (org-entry-get pom property))
12933 (values (and value (org-split-string value "[ \t]"))))
12934 (mapcar 'org-entry-restore-space values)))
12936 (defun org-entry-put-multivalued-property (pom property &rest values)
12937 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12938 VALUES should be a list of strings. Spaces will be protected."
12939 (org-entry-put pom property
12940 (mapconcat 'org-entry-protect-space values " "))
12941 (let* ((value (org-entry-get pom property))
12942 (values (and value (org-split-string value "[ \t]"))))
12943 (mapcar 'org-entry-restore-space values)))
12945 (defun org-entry-protect-space (s)
12946 "Protect spaces and newline in string S."
12947 (while (string-match " " s)
12948 (setq s (replace-match "%20" t t s)))
12949 (while (string-match "\n" s)
12950 (setq s (replace-match "%0A" t t s)))
12953 (defun org-entry-restore-space (s)
12954 "Restore spaces and newline in string S."
12955 (while (string-match "%20" s)
12956 (setq s (replace-match " " t t s)))
12957 (while (string-match "%0A" s)
12958 (setq s (replace-match "\n" t t s)))
12961 (defvar org-entry-property-inherited-from (make-marker)
12962 "Marker pointing to the entry from where a property was inherited.
12963 Each call to `org-entry-get-with-inheritance' will set this marker to the
12964 location of the entry where the inheritance search matched. If there was
12965 no match, the marker will point nowhere.
12966 Note that also `org-entry-get' calls this function, if the INHERIT flag
12967 is set.")
12969 (defun org-entry-get-with-inheritance (property)
12970 "Get entry property, and search higher levels if not present."
12971 (move-marker org-entry-property-inherited-from nil)
12972 (let (tmp)
12973 (save-excursion
12974 (save-restriction
12975 (widen)
12976 (catch 'ex
12977 (while t
12978 (when (setq tmp (org-entry-get nil property))
12979 (org-back-to-heading t)
12980 (move-marker org-entry-property-inherited-from (point))
12981 (throw 'ex tmp))
12982 (or (org-up-heading-safe) (throw 'ex nil)))))
12983 (or tmp
12984 (cdr (assoc property org-file-properties))
12985 (cdr (assoc property org-global-properties))
12986 (cdr (assoc property org-global-properties-fixed))))))
12988 (defvar org-property-changed-functions nil
12989 "Hook called when the value of a property has changed.
12990 Each hook function should accept two arguments, the name of the property
12991 and the new value.")
12993 (defun org-entry-put (pom property value)
12994 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12995 (org-with-point-at pom
12996 (org-back-to-heading t)
12997 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12998 range)
12999 (cond
13000 ((equal property "TODO")
13001 (when (and (stringp value) (string-match "\\S-" value)
13002 (not (member value org-todo-keywords-1)))
13003 (error "\"%s\" is not a valid TODO state" value))
13004 (if (or (not value)
13005 (not (string-match "\\S-" value)))
13006 (setq value 'none))
13007 (org-todo value)
13008 (org-set-tags nil 'align))
13009 ((equal property "PRIORITY")
13010 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13011 (string-to-char value) ?\ ))
13012 (org-set-tags nil 'align))
13013 ((equal property "SCHEDULED")
13014 (if (re-search-forward org-scheduled-time-regexp end t)
13015 (cond
13016 ((eq value 'earlier) (org-timestamp-change -1 'day))
13017 ((eq value 'later) (org-timestamp-change 1 'day))
13018 (t (call-interactively 'org-schedule)))
13019 (call-interactively 'org-schedule)))
13020 ((equal property "DEADLINE")
13021 (if (re-search-forward org-deadline-time-regexp end t)
13022 (cond
13023 ((eq value 'earlier) (org-timestamp-change -1 'day))
13024 ((eq value 'later) (org-timestamp-change 1 'day))
13025 (t (call-interactively 'org-deadline)))
13026 (call-interactively 'org-deadline)))
13027 ((member property org-special-properties)
13028 (error "The %s property can not yet be set with `org-entry-put'"
13029 property))
13030 (t ; a non-special property
13031 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13032 (setq range (org-get-property-block beg end 'force))
13033 (goto-char (car range))
13034 (if (re-search-forward
13035 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13036 (progn
13037 (delete-region (match-beginning 1) (match-end 1))
13038 (goto-char (match-beginning 1)))
13039 (goto-char (cdr range))
13040 (insert "\n")
13041 (backward-char 1)
13042 (org-indent-line-function)
13043 (insert ":" property ":"))
13044 (and value (insert " " value))
13045 (org-indent-line-function)))))
13046 (run-hook-with-args 'org-property-changed-functions property value)))
13048 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13049 "Get all property keys in the current buffer.
13050 With INCLUDE-SPECIALS, also list the special properties that reflect things
13051 like tags and TODO state.
13052 With INCLUDE-DEFAULTS, also include properties that has special meaning
13053 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
13054 With INCLUDE-COLUMNS, also include property names given in COLUMN
13055 formats in the current buffer."
13056 (let (rtn range cfmt s p)
13057 (save-excursion
13058 (save-restriction
13059 (widen)
13060 (goto-char (point-min))
13061 (while (re-search-forward org-property-start-re nil t)
13062 (setq range (org-get-property-block))
13063 (goto-char (car range))
13064 (while (re-search-forward
13065 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13066 (cdr range) t)
13067 (add-to-list 'rtn (org-match-string-no-properties 1)))
13068 (outline-next-heading))))
13070 (when include-specials
13071 (setq rtn (append org-special-properties rtn)))
13073 (when include-defaults
13074 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13075 (add-to-list 'rtn org-effort-property))
13077 (when include-columns
13078 (save-excursion
13079 (save-restriction
13080 (widen)
13081 (goto-char (point-min))
13082 (while (re-search-forward
13083 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13084 nil t)
13085 (setq cfmt (match-string 2) s 0)
13086 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13087 cfmt s)
13088 (setq s (match-end 0)
13089 p (match-string 1 cfmt))
13090 (unless (or (equal p "ITEM")
13091 (member p org-special-properties))
13092 (add-to-list 'rtn (match-string 1 cfmt))))))))
13094 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13096 (defun org-property-values (key)
13097 "Return a list of all values of property KEY."
13098 (save-excursion
13099 (save-restriction
13100 (widen)
13101 (goto-char (point-min))
13102 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
13103 values)
13104 (while (re-search-forward re nil t)
13105 (add-to-list 'values (org-trim (match-string 1))))
13106 (delete "" values)))))
13108 (defun org-insert-property-drawer ()
13109 "Insert a property drawer into the current entry."
13110 (interactive)
13111 (org-back-to-heading t)
13112 (looking-at outline-regexp)
13113 (let ((indent (if org-adapt-indentation
13114 (- (match-end 0)(match-beginning 0))
13116 (beg (point))
13117 (re (concat "^[ \t]*" org-keyword-time-regexp))
13118 end hiddenp)
13119 (outline-next-heading)
13120 (setq end (point))
13121 (goto-char beg)
13122 (while (re-search-forward re end t))
13123 (setq hiddenp (org-invisible-p))
13124 (end-of-line 1)
13125 (and (equal (char-after) ?\n) (forward-char 1))
13126 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
13127 (if (member (match-string 1) '("CLOCK:" ":END:"))
13128 ;; just skip this line
13129 (beginning-of-line 2)
13130 ;; Drawer start, find the end
13131 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
13132 (beginning-of-line 1)))
13133 (org-skip-over-state-notes)
13134 (skip-chars-backward " \t\n\r")
13135 (if (eq (char-before) ?*) (forward-char 1))
13136 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
13137 (beginning-of-line 0)
13138 (org-indent-to-column indent)
13139 (beginning-of-line 2)
13140 (org-indent-to-column indent)
13141 (beginning-of-line 0)
13142 (if hiddenp
13143 (save-excursion
13144 (org-back-to-heading t)
13145 (hide-entry))
13146 (org-flag-drawer t))))
13148 (defun org-set-property (property value)
13149 "In the current entry, set PROPERTY to VALUE.
13150 When called interactively, this will prompt for a property name, offering
13151 completion on existing and default properties. And then it will prompt
13152 for a value, offering completion either on allowed values (via an inherited
13153 xxx_ALL property) or on existing values in other instances of this property
13154 in the current file."
13155 (interactive
13156 (let* ((completion-ignore-case t)
13157 (keys (org-buffer-property-keys nil t t))
13158 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
13159 (prop (if (member prop0 keys)
13160 prop0
13161 (or (cdr (assoc (downcase prop0)
13162 (mapcar (lambda (x) (cons (downcase x) x))
13163 keys)))
13164 prop0)))
13165 (cur (org-entry-get nil prop))
13166 (prompt (concat prop " value"
13167 (if (and cur (string-match "\\S-" cur))
13168 (concat " [" cur "]") "") ": "))
13169 (allowed (org-property-get-allowed-values nil prop 'table))
13170 (existing (mapcar 'list (org-property-values prop)))
13171 (val (if allowed
13172 (org-completing-read prompt allowed nil
13173 (not (get-text-property 0 'org-unrestricted
13174 (caar allowed))))
13175 (let (org-completion-use-ido org-completion-use-iswitchb)
13176 (org-completing-read prompt existing nil nil "" nil cur)))))
13177 (list prop (if (equal val "") cur val))))
13178 (unless (equal (org-entry-get nil property) value)
13179 (org-entry-put nil property value)))
13181 (defun org-delete-property (property)
13182 "In the current entry, delete PROPERTY."
13183 (interactive
13184 (let* ((completion-ignore-case t)
13185 (prop (org-icompleting-read "Property: " (org-entry-properties nil 'standard))))
13186 (list prop)))
13187 (message "Property %s %s" property
13188 (if (org-entry-delete nil property)
13189 "deleted"
13190 "was not present in the entry")))
13192 (defun org-delete-property-globally (property)
13193 "Remove PROPERTY globally, from all entries."
13194 (interactive
13195 (let* ((completion-ignore-case t)
13196 (prop (org-icompleting-read
13197 "Globally remove property: "
13198 (mapcar 'list (org-buffer-property-keys)))))
13199 (list prop)))
13200 (save-excursion
13201 (save-restriction
13202 (widen)
13203 (goto-char (point-min))
13204 (let ((cnt 0))
13205 (while (re-search-forward
13206 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
13207 nil t)
13208 (setq cnt (1+ cnt))
13209 (replace-match ""))
13210 (message "Property \"%s\" removed from %d entries" property cnt)))))
13212 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
13214 (defun org-compute-property-at-point ()
13215 "Compute the property at point.
13216 This looks for an enclosing column format, extracts the operator and
13217 then applies it to the property in the column format's scope."
13218 (interactive)
13219 (unless (org-at-property-p)
13220 (error "Not at a property"))
13221 (let ((prop (org-match-string-no-properties 2)))
13222 (org-columns-get-format-and-top-level)
13223 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
13224 (error "No operator defined for property %s" prop))
13225 (org-columns-compute prop)))
13227 (defvar org-property-allowed-value-functions nil
13228 "Hook for functions supplying allowed values for a specific property.
13229 The functions must take a single argument, the name of the property, and
13230 return a flat list of allowed values. If \":ETC\" is one of
13231 the values, this means that these values are intended as defaults for
13232 completion, but that other values should be allowed too.
13233 The functions must return nil if they are not responsible for this
13234 property.")
13236 (defun org-property-get-allowed-values (pom property &optional table)
13237 "Get allowed values for the property PROPERTY.
13238 When TABLE is non-nil, return an alist that can directly be used for
13239 completion."
13240 (let (vals)
13241 (cond
13242 ((equal property "TODO")
13243 (setq vals (org-with-point-at pom
13244 (append org-todo-keywords-1 '("")))))
13245 ((equal property "PRIORITY")
13246 (let ((n org-lowest-priority))
13247 (while (>= n org-highest-priority)
13248 (push (char-to-string n) vals)
13249 (setq n (1- n)))))
13250 ((member property org-special-properties))
13251 ((setq vals (run-hook-with-args-until-success
13252 'org-property-allowed-value-functions property)))
13254 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13255 (when (and vals (string-match "\\S-" vals))
13256 (setq vals (car (read-from-string (concat "(" vals ")"))))
13257 (setq vals (mapcar (lambda (x)
13258 (cond ((stringp x) x)
13259 ((numberp x) (number-to-string x))
13260 ((symbolp x) (symbol-name x))
13261 (t "???")))
13262 vals)))))
13263 (when (member ":ETC" vals)
13264 (setq vals (remove ":ETC" vals))
13265 (org-add-props (car vals) '(org-unrestricted t)))
13266 (if table (mapcar 'list vals) vals)))
13268 (defun org-property-previous-allowed-value (&optional previous)
13269 "Switch to the next allowed value for this property."
13270 (interactive)
13271 (org-property-next-allowed-value t))
13273 (defun org-property-next-allowed-value (&optional previous)
13274 "Switch to the next allowed value for this property."
13275 (interactive)
13276 (unless (org-at-property-p)
13277 (error "Not at a property"))
13278 (let* ((key (match-string 2))
13279 (value (match-string 3))
13280 (allowed (or (org-property-get-allowed-values (point) key)
13281 (and (member value '("[ ]" "[-]" "[X]"))
13282 '("[ ]" "[X]"))))
13283 nval)
13284 (unless allowed
13285 (error "Allowed values for this property have not been defined"))
13286 (if previous (setq allowed (reverse allowed)))
13287 (if (member value allowed)
13288 (setq nval (car (cdr (member value allowed)))))
13289 (setq nval (or nval (car allowed)))
13290 (if (equal nval value)
13291 (error "Only one allowed value for this property"))
13292 (org-at-property-p)
13293 (replace-match (concat " :" key ": " nval) t t)
13294 (org-indent-line-function)
13295 (beginning-of-line 1)
13296 (skip-chars-forward " \t")
13297 (run-hook-with-args 'org-property-changed-functions key nval)))
13299 (defun org-find-entry-with-id (ident)
13300 "Locate the entry that contains the ID property with exact value IDENT.
13301 IDENT can be a string, a symbol or a number, this function will search for
13302 the string representation of it.
13303 Return the position where this entry starts, or nil if there is no such entry."
13304 (interactive "sID: ")
13305 (let ((id (cond
13306 ((stringp ident) ident)
13307 ((symbol-name ident) (symbol-name ident))
13308 ((numberp ident) (number-to-string ident))
13309 (t (error "IDENT %s must be a string, symbol or number" ident))))
13310 (case-fold-search nil))
13311 (save-excursion
13312 (save-restriction
13313 (widen)
13314 (goto-char (point-min))
13315 (when (re-search-forward
13316 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13317 nil t)
13318 (org-back-to-heading t)
13319 (point))))))
13321 ;;;; Timestamps
13323 (defvar org-last-changed-timestamp nil)
13324 (defvar org-last-inserted-timestamp nil
13325 "The last time stamp inserted with `org-insert-time-stamp'.")
13326 (defvar org-time-was-given) ; dynamically scoped parameter
13327 (defvar org-end-time-was-given) ; dynamically scoped parameter
13328 (defvar org-ts-what) ; dynamically scoped parameter
13330 (defun org-time-stamp (arg &optional inactive)
13331 "Prompt for a date/time and insert a time stamp.
13332 If the user specifies a time like HH:MM, or if this command is called
13333 with a prefix argument, the time stamp will contain date and time.
13334 Otherwise, only the date will be included. All parts of a date not
13335 specified by the user will be filled in from the current date/time.
13336 So if you press just return without typing anything, the time stamp
13337 will represent the current date/time. If there is already a timestamp
13338 at the cursor, it will be modified."
13339 (interactive "P")
13340 (let* ((ts nil)
13341 (default-time
13342 ;; Default time is either today, or, when entering a range,
13343 ;; the range start.
13344 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13345 (save-excursion
13346 (re-search-backward
13347 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13348 (- (point) 20) t)))
13349 (apply 'encode-time (org-parse-time-string (match-string 1)))
13350 (current-time)))
13351 (default-input (and ts (org-get-compact-tod ts)))
13352 org-time-was-given org-end-time-was-given time)
13353 (cond
13354 ((and (org-at-timestamp-p t)
13355 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13356 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13357 (insert "--")
13358 (setq time (let ((this-command this-command))
13359 (org-read-date arg 'totime nil nil
13360 default-time default-input)))
13361 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13362 ((org-at-timestamp-p t)
13363 (setq time (let ((this-command this-command))
13364 (org-read-date arg 'totime nil nil default-time default-input)))
13365 (when (org-at-timestamp-p t) ; just to get the match data
13366 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13367 (replace-match "")
13368 (setq org-last-changed-timestamp
13369 (org-insert-time-stamp
13370 time (or org-time-was-given arg)
13371 inactive nil nil (list org-end-time-was-given))))
13372 (message "Timestamp updated"))
13374 (setq time (let ((this-command this-command))
13375 (org-read-date arg 'totime nil nil default-time default-input)))
13376 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13377 nil nil (list org-end-time-was-given))))))
13379 ;; FIXME: can we use this for something else, like computing time differences?
13380 (defun org-get-compact-tod (s)
13381 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13382 (let* ((t1 (match-string 1 s))
13383 (h1 (string-to-number (match-string 2 s)))
13384 (m1 (string-to-number (match-string 3 s)))
13385 (t2 (and (match-end 4) (match-string 5 s)))
13386 (h2 (and t2 (string-to-number (match-string 6 s))))
13387 (m2 (and t2 (string-to-number (match-string 7 s))))
13388 dh dm)
13389 (if (not t2)
13391 (setq dh (- h2 h1) dm (- m2 m1))
13392 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13393 (concat t1 "+" (number-to-string dh)
13394 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13396 (defun org-time-stamp-inactive (&optional arg)
13397 "Insert an inactive time stamp.
13398 An inactive time stamp is enclosed in square brackets instead of angle
13399 brackets. It is inactive in the sense that it does not trigger agenda entries,
13400 does not link to the calendar and cannot be changed with the S-cursor keys.
13401 So these are more for recording a certain time/date."
13402 (interactive "P")
13403 (org-time-stamp arg 'inactive))
13405 (defvar org-date-ovl (org-make-overlay 1 1))
13406 (org-overlay-put org-date-ovl 'face 'org-warning)
13407 (org-detach-overlay org-date-ovl)
13409 (defvar org-ans1) ; dynamically scoped parameter
13410 (defvar org-ans2) ; dynamically scoped parameter
13412 (defvar org-plain-time-of-day-regexp) ; defined below
13414 (defvar org-overriding-default-time nil) ; dynamically scoped
13415 (defvar org-read-date-overlay nil)
13416 (defvar org-dcst nil) ; dynamically scoped
13417 (defvar org-read-date-history nil)
13418 (defvar org-read-date-final-answer nil)
13420 (defun org-read-date (&optional with-time to-time from-string prompt
13421 default-time default-input)
13422 "Read a date, possibly a time, and make things smooth for the user.
13423 The prompt will suggest to enter an ISO date, but you can also enter anything
13424 which will at least partially be understood by `parse-time-string'.
13425 Unrecognized parts of the date will default to the current day, month, year,
13426 hour and minute. If this command is called to replace a timestamp at point,
13427 of to enter the second timestamp of a range, the default time is taken from the
13428 existing stamp. For example,
13429 3-2-5 --> 2003-02-05
13430 feb 15 --> currentyear-02-15
13431 sep 12 9 --> 2009-09-12
13432 12:45 --> today 12:45
13433 22 sept 0:34 --> currentyear-09-22 0:34
13434 12 --> currentyear-currentmonth-12
13435 Fri --> nearest Friday (today or later)
13436 etc.
13438 Furthermore you can specify a relative date by giving, as the *first* thing
13439 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13440 change in days weeks, months, years.
13441 With a single plus or minus, the date is relative to today. With a double
13442 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13443 +4d --> four days from today
13444 +4 --> same as above
13445 +2w --> two weeks from today
13446 ++5 --> five days from default date
13448 The function understands only English month and weekday abbreviations,
13449 but this can be configured with the variables `parse-time-months' and
13450 `parse-time-weekdays'.
13452 While prompting, a calendar is popped up - you can also select the
13453 date with the mouse (button 1). The calendar shows a period of three
13454 months. To scroll it to other months, use the keys `>' and `<'.
13455 If you don't like the calendar, turn it off with
13456 \(setq org-read-date-popup-calendar nil)
13458 With optional argument TO-TIME, the date will immediately be converted
13459 to an internal time.
13460 With an optional argument WITH-TIME, the prompt will suggest to also
13461 insert a time. Note that when WITH-TIME is not set, you can still
13462 enter a time, and this function will inform the calling routine about
13463 this change. The calling routine may then choose to change the format
13464 used to insert the time stamp into the buffer to include the time.
13465 With optional argument FROM-STRING, read from this string instead from
13466 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13467 the time/date that is used for everything that is not specified by the
13468 user."
13469 (require 'parse-time)
13470 (let* ((org-time-stamp-rounding-minutes
13471 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13472 (org-dcst org-display-custom-times)
13473 (ct (org-current-time))
13474 (def (or org-overriding-default-time default-time ct))
13475 (defdecode (decode-time def))
13476 (dummy (progn
13477 (when (< (nth 2 defdecode) org-extend-today-until)
13478 (setcar (nthcdr 2 defdecode) -1)
13479 (setcar (nthcdr 1 defdecode) 59)
13480 (setq def (apply 'encode-time defdecode)
13481 defdecode (decode-time def)))))
13482 (calendar-frame-setup nil)
13483 (calendar-move-hook nil)
13484 (calendar-view-diary-initially-flag nil)
13485 (view-diary-entries-initially nil)
13486 (calendar-view-holidays-initially-flag nil)
13487 (view-calendar-holidays-initially nil)
13488 (timestr (format-time-string
13489 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
13490 (prompt (concat (if prompt (concat prompt " ") "")
13491 (format "Date+time [%s]: " timestr)))
13492 ans (org-ans0 "") org-ans1 org-ans2 final)
13494 (cond
13495 (from-string (setq ans from-string))
13496 (org-read-date-popup-calendar
13497 (save-excursion
13498 (save-window-excursion
13499 (calendar)
13500 (calendar-forward-day (- (time-to-days def)
13501 (calendar-absolute-from-gregorian
13502 (calendar-current-date))))
13503 (org-eval-in-calendar nil t)
13504 (let* ((old-map (current-local-map))
13505 (map (copy-keymap calendar-mode-map))
13506 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13507 (org-defkey map (kbd "RET") 'org-calendar-select)
13508 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
13509 'org-calendar-select-mouse)
13510 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
13511 'org-calendar-select-mouse)
13512 (org-defkey minibuffer-local-map [(meta shift left)]
13513 (lambda () (interactive)
13514 (org-eval-in-calendar '(calendar-backward-month 1))))
13515 (org-defkey minibuffer-local-map [(meta shift right)]
13516 (lambda () (interactive)
13517 (org-eval-in-calendar '(calendar-forward-month 1))))
13518 (org-defkey minibuffer-local-map [(meta shift up)]
13519 (lambda () (interactive)
13520 (org-eval-in-calendar '(calendar-backward-year 1))))
13521 (org-defkey minibuffer-local-map [(meta shift down)]
13522 (lambda () (interactive)
13523 (org-eval-in-calendar '(calendar-forward-year 1))))
13524 (org-defkey minibuffer-local-map [?\e (shift left)]
13525 (lambda () (interactive)
13526 (org-eval-in-calendar '(calendar-backward-month 1))))
13527 (org-defkey minibuffer-local-map [?\e (shift right)]
13528 (lambda () (interactive)
13529 (org-eval-in-calendar '(calendar-forward-month 1))))
13530 (org-defkey minibuffer-local-map [?\e (shift up)]
13531 (lambda () (interactive)
13532 (org-eval-in-calendar '(calendar-backward-year 1))))
13533 (org-defkey minibuffer-local-map [?\e (shift down)]
13534 (lambda () (interactive)
13535 (org-eval-in-calendar '(calendar-forward-year 1))))
13536 (org-defkey minibuffer-local-map [(shift up)]
13537 (lambda () (interactive)
13538 (org-eval-in-calendar '(calendar-backward-week 1))))
13539 (org-defkey minibuffer-local-map [(shift down)]
13540 (lambda () (interactive)
13541 (org-eval-in-calendar '(calendar-forward-week 1))))
13542 (org-defkey minibuffer-local-map [(shift left)]
13543 (lambda () (interactive)
13544 (org-eval-in-calendar '(calendar-backward-day 1))))
13545 (org-defkey minibuffer-local-map [(shift right)]
13546 (lambda () (interactive)
13547 (org-eval-in-calendar '(calendar-forward-day 1))))
13548 (org-defkey minibuffer-local-map ">"
13549 (lambda () (interactive)
13550 (org-eval-in-calendar '(scroll-calendar-left 1))))
13551 (org-defkey minibuffer-local-map "<"
13552 (lambda () (interactive)
13553 (org-eval-in-calendar '(scroll-calendar-right 1))))
13554 (run-hooks 'org-read-date-minibuffer-setup-hook)
13555 (unwind-protect
13556 (progn
13557 (use-local-map map)
13558 (add-hook 'post-command-hook 'org-read-date-display)
13559 (setq org-ans0 (read-string prompt default-input
13560 'org-read-date-history nil))
13561 ;; org-ans0: from prompt
13562 ;; org-ans1: from mouse click
13563 ;; org-ans2: from calendar motion
13564 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13565 (remove-hook 'post-command-hook 'org-read-date-display)
13566 (use-local-map old-map)
13567 (when org-read-date-overlay
13568 (org-delete-overlay org-read-date-overlay)
13569 (setq org-read-date-overlay nil)))))))
13571 (t ; Naked prompt only
13572 (unwind-protect
13573 (setq ans (read-string prompt default-input
13574 'org-read-date-history timestr))
13575 (when org-read-date-overlay
13576 (org-delete-overlay org-read-date-overlay)
13577 (setq org-read-date-overlay nil)))))
13579 (setq final (org-read-date-analyze ans def defdecode))
13580 (setq org-read-date-final-answer ans)
13582 (if to-time
13583 (apply 'encode-time final)
13584 (if (and (boundp 'org-time-was-given) org-time-was-given)
13585 (format "%04d-%02d-%02d %02d:%02d"
13586 (nth 5 final) (nth 4 final) (nth 3 final)
13587 (nth 2 final) (nth 1 final))
13588 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13590 (defvar def)
13591 (defvar defdecode)
13592 (defvar with-time)
13593 (defvar org-read-date-analyze-futurep nil)
13594 (defun org-read-date-display ()
13595 "Display the current date prompt interpretation in the minibuffer."
13596 (when org-read-date-display-live
13597 (when org-read-date-overlay
13598 (org-delete-overlay org-read-date-overlay))
13599 (let ((p (point)))
13600 (end-of-line 1)
13601 (while (not (equal (buffer-substring
13602 (max (point-min) (- (point) 4)) (point))
13603 " "))
13604 (insert " "))
13605 (goto-char p))
13606 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13607 " " (or org-ans1 org-ans2)))
13608 (org-end-time-was-given nil)
13609 (f (org-read-date-analyze ans def defdecode))
13610 (fmts (if org-dcst
13611 org-time-stamp-custom-formats
13612 org-time-stamp-formats))
13613 (fmt (if (or with-time
13614 (and (boundp 'org-time-was-given) org-time-was-given))
13615 (cdr fmts)
13616 (car fmts)))
13617 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13618 (when (and org-end-time-was-given
13619 (string-match org-plain-time-of-day-regexp txt))
13620 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13621 org-end-time-was-given
13622 (substring txt (match-end 0)))))
13623 (when org-read-date-analyze-futurep
13624 (setq txt (concat txt " (=>F)")))
13625 (setq org-read-date-overlay
13626 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13627 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13629 (defun org-read-date-analyze (ans def defdecode)
13630 "Analyse the combined answer of the date prompt."
13631 ;; FIXME: cleanup and comment
13632 (let ((nowdecode (decode-time (current-time)))
13633 delta deltan deltaw deltadef year month day
13634 hour minute second wday pm h2 m2 tl wday1
13635 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
13636 (setq org-read-date-analyze-futurep nil)
13637 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13638 (setq ans "+0"))
13640 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13641 (setq ans (replace-match "" t t ans)
13642 deltan (car delta)
13643 deltaw (nth 1 delta)
13644 deltadef (nth 2 delta)))
13646 ;; Check if there is an iso week date in there
13647 ;; If yes, store the info and postpone interpreting it until the rest
13648 ;; of the parsing is done
13649 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13650 (setq iso-year (if (match-end 1)
13651 (org-small-year-to-year
13652 (string-to-number (match-string 1 ans))))
13653 iso-weekday (if (match-end 3)
13654 (string-to-number (match-string 3 ans)))
13655 iso-week (string-to-number (match-string 2 ans)))
13656 (setq ans (replace-match "" t t ans)))
13658 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
13659 (when (string-match
13660 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13661 (setq year (if (match-end 2)
13662 (string-to-number (match-string 2 ans))
13663 (progn (setq kill-year t)
13664 (string-to-number (format-time-string "%Y"))))
13665 month (string-to-number (match-string 3 ans))
13666 day (string-to-number (match-string 4 ans)))
13667 (if (< year 100) (setq year (+ 2000 year)))
13668 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13669 t nil ans)))
13670 ;; Help matching american dates, like 5/30 or 5/30/7
13671 (when (string-match
13672 "^ *\\([0-3]?[0-9]\\)/\\([0-1]?[0-9]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
13673 (setq year (if (match-end 4)
13674 (string-to-number (match-string 4 ans))
13675 (progn (setq kill-year t)
13676 (string-to-number (format-time-string "%Y"))))
13677 month (string-to-number (match-string 1 ans))
13678 day (string-to-number (match-string 2 ans)))
13679 (if (< year 100) (setq year (+ 2000 year)))
13680 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13681 t nil ans)))
13682 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13683 ;; If there is a time with am/pm, and *no* time without it, we convert
13684 ;; so that matching will be successful.
13685 (loop for i from 1 to 2 do ; twice, for end time as well
13686 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13687 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13688 (setq hour (string-to-number (match-string 1 ans))
13689 minute (if (match-end 3)
13690 (string-to-number (match-string 3 ans))
13692 pm (equal ?p
13693 (string-to-char (downcase (match-string 4 ans)))))
13694 (if (and (= hour 12) (not pm))
13695 (setq hour 0)
13696 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13697 (setq ans (replace-match (format "%02d:%02d" hour minute)
13698 t t ans))))
13700 ;; Check if a time range is given as a duration
13701 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13702 (setq hour (string-to-number (match-string 1 ans))
13703 h2 (+ hour (string-to-number (match-string 3 ans)))
13704 minute (string-to-number (match-string 2 ans))
13705 m2 (+ minute (if (match-end 5) (string-to-number
13706 (match-string 5 ans))0)))
13707 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13708 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13709 t t ans)))
13711 ;; Check if there is a time range
13712 (when (boundp 'org-end-time-was-given)
13713 (setq org-time-was-given nil)
13714 (when (and (string-match org-plain-time-of-day-regexp ans)
13715 (match-end 8))
13716 (setq org-end-time-was-given (match-string 8 ans))
13717 (setq ans (concat (substring ans 0 (match-beginning 7))
13718 (substring ans (match-end 7))))))
13720 (setq tl (parse-time-string ans)
13721 day (or (nth 3 tl) (nth 3 defdecode))
13722 month (or (nth 4 tl)
13723 (if (and org-read-date-prefer-future
13724 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
13725 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
13726 (nth 4 defdecode)))
13727 year (or (and (not kill-year) (nth 5 tl))
13728 (if (and org-read-date-prefer-future
13729 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
13730 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
13731 (nth 5 defdecode)))
13732 hour (or (nth 2 tl) (nth 2 defdecode))
13733 minute (or (nth 1 tl) (nth 1 defdecode))
13734 second (or (nth 0 tl) 0)
13735 wday (nth 6 tl))
13737 (when (and (eq org-read-date-prefer-future 'time)
13738 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13739 (equal day (nth 3 nowdecode))
13740 (equal month (nth 4 nowdecode))
13741 (equal year (nth 5 nowdecode))
13742 (nth 2 tl)
13743 (or (< (nth 2 tl) (nth 2 nowdecode))
13744 (and (= (nth 2 tl) (nth 2 nowdecode))
13745 (nth 1 tl)
13746 (< (nth 1 tl) (nth 1 nowdecode)))))
13747 (setq day (1+ day)
13748 futurep t))
13750 ;; Special date definitions below
13751 (cond
13752 (iso-week
13753 ;; There was an iso week
13754 (require 'cal-iso)
13755 (setq futurep nil)
13756 (setq year (or iso-year year)
13757 day (or iso-weekday wday 1)
13758 wday nil ; to make sure that the trigger below does not match
13759 iso-date (calendar-gregorian-from-absolute
13760 (calendar-absolute-from-iso
13761 (list iso-week day year))))
13762 ; FIXME: Should we also push ISO weeks into the future?
13763 ; (when (and org-read-date-prefer-future
13764 ; (not iso-year)
13765 ; (< (calendar-absolute-from-gregorian iso-date)
13766 ; (time-to-days (current-time))))
13767 ; (setq year (1+ year)
13768 ; iso-date (calendar-gregorian-from-absolute
13769 ; (calendar-absolute-from-iso
13770 ; (list iso-week day year)))))
13771 (setq month (car iso-date)
13772 year (nth 2 iso-date)
13773 day (nth 1 iso-date)))
13774 (deltan
13775 (setq futurep nil)
13776 (unless deltadef
13777 (let ((now (decode-time (current-time))))
13778 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13779 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13780 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13781 ((equal deltaw "m") (setq month (+ month deltan)))
13782 ((equal deltaw "y") (setq year (+ year deltan)))))
13783 ((and wday (not (nth 3 tl)))
13784 (setq futurep nil)
13785 ;; Weekday was given, but no day, so pick that day in the week
13786 ;; on or after the derived date.
13787 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13788 (unless (equal wday wday1)
13789 (setq day (+ day (% (- wday wday1 -7) 7))))))
13790 (if (and (boundp 'org-time-was-given)
13791 (nth 2 tl))
13792 (setq org-time-was-given t))
13793 (if (< year 100) (setq year (+ 2000 year)))
13794 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13795 (setq org-read-date-analyze-futurep futurep)
13796 (list second minute hour day month year)))
13798 (defvar parse-time-weekdays)
13800 (defun org-read-date-get-relative (s today default)
13801 "Check string S for special relative date string.
13802 TODAY and DEFAULT are internal times, for today and for a default.
13803 Return shift list (N what def-flag)
13804 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13805 N is the number of WHATs to shift.
13806 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13807 the DEFAULT date rather than TODAY."
13808 (when (and
13809 (string-match
13810 (concat
13811 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13812 "\\([0-9]+\\)?"
13813 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13814 "\\([ \t]\\|$\\)") s)
13815 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13816 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13817 (string-to-char (substring (match-string 1 s) -1))
13818 ?+))
13819 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13820 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13821 (what (if (match-end 3) (match-string 3 s) "d"))
13822 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13823 (date (if rel default today))
13824 (wday (nth 6 (decode-time date)))
13825 delta)
13826 (if wday1
13827 (progn
13828 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13829 (if (= dir ?-) (setq delta (- delta 7)))
13830 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13831 (list delta "d" rel))
13832 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13834 (defun org-order-calendar-date-args (arg1 arg2 arg3)
13835 "Turn a user-specified date into the internal representation.
13836 The internal representation needed by the calendar is (month day year).
13837 This is a wrapper to handle the brain-dead convention in calendar that
13838 user function argument order change dependent on argument order."
13839 (if (boundp 'calendar-date-style)
13840 (cond
13841 ((eq calendar-date-style 'american)
13842 (list arg1 arg2 arg3))
13843 ((eq calendar-date-style 'european)
13844 (list arg2 arg1 arg3))
13845 ((eq calendar-date-style 'iso)
13846 (list arg2 arg3 arg1)))
13847 (if (org-bound-and-true-p european-calendar-style)
13848 (list arg2 arg1 arg3)
13849 (list arg1 arg2 arg3))))
13851 (defun org-eval-in-calendar (form &optional keepdate)
13852 "Eval FORM in the calendar window and return to current window.
13853 Also, store the cursor date in variable org-ans2."
13854 (let ((sf (selected-frame))
13855 (sw (selected-window)))
13856 (select-window (get-buffer-window "*Calendar*" t))
13857 (eval form)
13858 (when (and (not keepdate) (calendar-cursor-to-date))
13859 (let* ((date (calendar-cursor-to-date))
13860 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13861 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13862 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13863 (select-window sw)
13864 (org-select-frame-set-input-focus sf)))
13866 (defun org-calendar-select ()
13867 "Return to `org-read-date' with the date currently selected.
13868 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13869 (interactive)
13870 (when (calendar-cursor-to-date)
13871 (let* ((date (calendar-cursor-to-date))
13872 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13873 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13874 (if (active-minibuffer-window) (exit-minibuffer))))
13876 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13877 "Insert a date stamp for the date given by the internal TIME.
13878 WITH-HM means use the stamp format that includes the time of the day.
13879 INACTIVE means use square brackets instead of angular ones, so that the
13880 stamp will not contribute to the agenda.
13881 PRE and POST are optional strings to be inserted before and after the
13882 stamp.
13883 The command returns the inserted time stamp."
13884 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13885 stamp)
13886 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13887 (insert-before-markers (or pre ""))
13888 (insert-before-markers (setq stamp (format-time-string fmt time)))
13889 (when (listp extra)
13890 (setq extra (car extra))
13891 (if (and (stringp extra)
13892 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13893 (setq extra (format "-%02d:%02d"
13894 (string-to-number (match-string 1 extra))
13895 (string-to-number (match-string 2 extra))))
13896 (setq extra nil)))
13897 (when extra
13898 (backward-char 1)
13899 (insert-before-markers extra)
13900 (forward-char 1))
13901 (insert-before-markers (or post ""))
13902 (setq org-last-inserted-timestamp stamp)))
13904 (defun org-toggle-time-stamp-overlays ()
13905 "Toggle the use of custom time stamp formats."
13906 (interactive)
13907 (setq org-display-custom-times (not org-display-custom-times))
13908 (unless org-display-custom-times
13909 (let ((p (point-min)) (bmp (buffer-modified-p)))
13910 (while (setq p (next-single-property-change p 'display))
13911 (if (and (get-text-property p 'display)
13912 (eq (get-text-property p 'face) 'org-date))
13913 (remove-text-properties
13914 p (setq p (next-single-property-change p 'display))
13915 '(display t))))
13916 (set-buffer-modified-p bmp)))
13917 (if (featurep 'xemacs)
13918 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13919 (org-restart-font-lock)
13920 (setq org-table-may-need-update t)
13921 (if org-display-custom-times
13922 (message "Time stamps are overlayed with custom format")
13923 (message "Time stamp overlays removed")))
13925 (defun org-display-custom-time (beg end)
13926 "Overlay modified time stamp format over timestamp between BEG and END."
13927 (let* ((ts (buffer-substring beg end))
13928 t1 w1 with-hm tf time str w2 (off 0))
13929 (save-match-data
13930 (setq t1 (org-parse-time-string ts t))
13931 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13932 (setq off (- (match-end 0) (match-beginning 0)))))
13933 (setq end (- end off))
13934 (setq w1 (- end beg)
13935 with-hm (and (nth 1 t1) (nth 2 t1))
13936 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13937 time (org-fix-decoded-time t1)
13938 str (org-add-props
13939 (format-time-string
13940 (substring tf 1 -1) (apply 'encode-time time))
13941 nil 'mouse-face 'highlight)
13942 w2 (length str))
13943 (if (not (= w2 w1))
13944 (add-text-properties (1+ beg) (+ 2 beg)
13945 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13946 (if (featurep 'xemacs)
13947 (progn
13948 (put-text-property beg end 'invisible t)
13949 (put-text-property beg end 'end-glyph (make-glyph str)))
13950 (put-text-property beg end 'display str))))
13952 (defun org-translate-time (string)
13953 "Translate all timestamps in STRING to custom format.
13954 But do this only if the variable `org-display-custom-times' is set."
13955 (when org-display-custom-times
13956 (save-match-data
13957 (let* ((start 0)
13958 (re org-ts-regexp-both)
13959 t1 with-hm inactive tf time str beg end)
13960 (while (setq start (string-match re string start))
13961 (setq beg (match-beginning 0)
13962 end (match-end 0)
13963 t1 (save-match-data
13964 (org-parse-time-string (substring string beg end) t))
13965 with-hm (and (nth 1 t1) (nth 2 t1))
13966 inactive (equal (substring string beg (1+ beg)) "[")
13967 tf (funcall (if with-hm 'cdr 'car)
13968 org-time-stamp-custom-formats)
13969 time (org-fix-decoded-time t1)
13970 str (format-time-string
13971 (concat
13972 (if inactive "[" "<") (substring tf 1 -1)
13973 (if inactive "]" ">"))
13974 (apply 'encode-time time))
13975 string (replace-match str t t string)
13976 start (+ start (length str)))))))
13977 string)
13979 (defun org-fix-decoded-time (time)
13980 "Set 0 instead of nil for the first 6 elements of time.
13981 Don't touch the rest."
13982 (let ((n 0))
13983 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13985 (defun org-days-to-time (timestamp-string)
13986 "Difference between TIMESTAMP-STRING and now in days."
13987 (- (time-to-days (org-time-string-to-time timestamp-string))
13988 (time-to-days (current-time))))
13990 (defun org-deadline-close (timestamp-string &optional ndays)
13991 "Is the time in TIMESTAMP-STRING close to the current date?"
13992 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13993 (and (< (org-days-to-time timestamp-string) ndays)
13994 (not (org-entry-is-done-p))))
13996 (defun org-get-wdays (ts)
13997 "Get the deadline lead time appropriate for timestring TS."
13998 (cond
13999 ((<= org-deadline-warning-days 0)
14000 ;; 0 or negative, enforce this value no matter what
14001 (- org-deadline-warning-days))
14002 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
14003 ;; lead time is specified.
14004 (floor (* (string-to-number (match-string 1 ts))
14005 (cdr (assoc (match-string 2 ts)
14006 '(("d" . 1) ("w" . 7)
14007 ("m" . 30.4) ("y" . 365.25)))))))
14008 ;; go for the default.
14009 (t org-deadline-warning-days)))
14011 (defun org-calendar-select-mouse (ev)
14012 "Return to `org-read-date' with the date currently selected.
14013 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14014 (interactive "e")
14015 (mouse-set-point ev)
14016 (when (calendar-cursor-to-date)
14017 (let* ((date (calendar-cursor-to-date))
14018 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14019 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14020 (if (active-minibuffer-window) (exit-minibuffer))))
14022 (defun org-check-deadlines (ndays)
14023 "Check if there are any deadlines due or past due.
14024 A deadline is considered due if it happens within `org-deadline-warning-days'
14025 days from today's date. If the deadline appears in an entry marked DONE,
14026 it is not shown. The prefix arg NDAYS can be used to test that many
14027 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
14028 (interactive "P")
14029 (let* ((org-warn-days
14030 (cond
14031 ((equal ndays '(4)) 100000)
14032 (ndays (prefix-numeric-value ndays))
14033 (t (abs org-deadline-warning-days))))
14034 (case-fold-search nil)
14035 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
14036 (callback
14037 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
14039 (message "%d deadlines past-due or due within %d days"
14040 (org-occur regexp nil callback)
14041 org-warn-days)))
14043 (defun org-check-before-date (date)
14044 "Check if there are deadlines or scheduled entries before DATE."
14045 (interactive (list (org-read-date)))
14046 (let ((case-fold-search nil)
14047 (regexp (concat "\\<\\(" org-deadline-string
14048 "\\|" org-scheduled-string
14049 "\\) *<\\([^>]+\\)>"))
14050 (callback
14051 (lambda () (time-less-p
14052 (org-time-string-to-time (match-string 2))
14053 (org-time-string-to-time date)))))
14054 (message "%d entries before %s"
14055 (org-occur regexp nil callback) date)))
14057 (defun org-check-after-date (date)
14058 "Check if there are deadlines or scheduled entries after DATE."
14059 (interactive (list (org-read-date)))
14060 (let ((case-fold-search nil)
14061 (regexp (concat "\\<\\(" org-deadline-string
14062 "\\|" org-scheduled-string
14063 "\\) *<\\([^>]+\\)>"))
14064 (callback
14065 (lambda () (not
14066 (time-less-p
14067 (org-time-string-to-time (match-string 2))
14068 (org-time-string-to-time date))))))
14069 (message "%d entries after %s"
14070 (org-occur regexp nil callback) date)))
14072 (defun org-evaluate-time-range (&optional to-buffer)
14073 "Evaluate a time range by computing the difference between start and end.
14074 Normally the result is just printed in the echo area, but with prefix arg
14075 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
14076 If the time range is actually in a table, the result is inserted into the
14077 next column.
14078 For time difference computation, a year is assumed to be exactly 365
14079 days in order to avoid rounding problems."
14080 (interactive "P")
14082 (org-clock-update-time-maybe)
14083 (save-excursion
14084 (unless (org-at-date-range-p t)
14085 (goto-char (point-at-bol))
14086 (re-search-forward org-tr-regexp-both (point-at-eol) t))
14087 (if (not (org-at-date-range-p t))
14088 (error "Not at a time-stamp range, and none found in current line")))
14089 (let* ((ts1 (match-string 1))
14090 (ts2 (match-string 2))
14091 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
14092 (match-end (match-end 0))
14093 (time1 (org-time-string-to-time ts1))
14094 (time2 (org-time-string-to-time ts2))
14095 (t1 (org-float-time time1))
14096 (t2 (org-float-time time2))
14097 (diff (abs (- t2 t1)))
14098 (negative (< (- t2 t1) 0))
14099 ;; (ys (floor (* 365 24 60 60)))
14100 (ds (* 24 60 60))
14101 (hs (* 60 60))
14102 (fy "%dy %dd %02d:%02d")
14103 (fy1 "%dy %dd")
14104 (fd "%dd %02d:%02d")
14105 (fd1 "%dd")
14106 (fh "%02d:%02d")
14107 y d h m align)
14108 (if havetime
14109 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14111 d (floor (/ diff ds)) diff (mod diff ds)
14112 h (floor (/ diff hs)) diff (mod diff hs)
14113 m (floor (/ diff 60)))
14114 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14116 d (floor (+ (/ diff ds) 0.5))
14117 h 0 m 0))
14118 (if (not to-buffer)
14119 (message "%s" (org-make-tdiff-string y d h m))
14120 (if (org-at-table-p)
14121 (progn
14122 (goto-char match-end)
14123 (setq align t)
14124 (and (looking-at " *|") (goto-char (match-end 0))))
14125 (goto-char match-end))
14126 (if (looking-at
14127 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
14128 (replace-match ""))
14129 (if negative (insert " -"))
14130 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
14131 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
14132 (insert " " (format fh h m))))
14133 (if align (org-table-align))
14134 (message "Time difference inserted")))))
14136 (defun org-make-tdiff-string (y d h m)
14137 (let ((fmt "")
14138 (l nil))
14139 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
14140 l (push y l)))
14141 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
14142 l (push d l)))
14143 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
14144 l (push h l)))
14145 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
14146 l (push m l)))
14147 (apply 'format fmt (nreverse l))))
14149 (defun org-time-string-to-time (s)
14150 (apply 'encode-time (org-parse-time-string s)))
14151 (defun org-time-string-to-seconds (s)
14152 (org-float-time (org-time-string-to-time s)))
14154 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
14155 "Convert a time stamp to an absolute day number.
14156 If there is a specifyer for a cyclic time stamp, get the closest date to
14157 DAYNR.
14158 PREFER and SHOW-ALL are passed through to `org-closest-date'.
14159 the variable date is bound by the calendar when this is called."
14160 (cond
14161 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
14162 (if (org-diary-sexp-entry (match-string 1 s) "" date)
14163 daynr
14164 (+ daynr 1000)))
14165 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
14166 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
14167 (time-to-days (current-time))) (match-string 0 s)
14168 prefer show-all))
14169 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
14171 (defun org-days-to-iso-week (days)
14172 "Return the iso week number."
14173 (require 'cal-iso)
14174 (car (calendar-iso-from-absolute days)))
14176 (defun org-small-year-to-year (year)
14177 "Convert 2-digit years into 4-digit years.
14178 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
14179 The year 2000 cannot be abbreviated. Any year larger than 99
14180 is returned unchanged."
14181 (if (< year 38)
14182 (setq year (+ 2000 year))
14183 (if (< year 100)
14184 (setq year (+ 1900 year))))
14185 year)
14187 (defun org-time-from-absolute (d)
14188 "Return the time corresponding to date D.
14189 D may be an absolute day number, or a calendar-type list (month day year)."
14190 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
14191 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
14193 (defun org-calendar-holiday ()
14194 "List of holidays, for Diary display in Org-mode."
14195 (require 'holidays)
14196 (let ((hl (funcall
14197 (if (fboundp 'calendar-check-holidays)
14198 'calendar-check-holidays 'check-calendar-holidays) date)))
14199 (if hl (mapconcat 'identity hl "; "))))
14201 (defun org-diary-sexp-entry (sexp entry date)
14202 "Process a SEXP diary ENTRY for DATE."
14203 (require 'diary-lib)
14204 (let ((result (if calendar-debug-sexp
14205 (let ((stack-trace-on-error t))
14206 (eval (car (read-from-string sexp))))
14207 (condition-case nil
14208 (eval (car (read-from-string sexp)))
14209 (error
14210 (beep)
14211 (message "Bad sexp at line %d in %s: %s"
14212 (org-current-line)
14213 (buffer-file-name) sexp)
14214 (sleep-for 2))))))
14215 (cond ((stringp result) result)
14216 ((and (consp result)
14217 (stringp (cdr result))) (cdr result))
14218 (result entry)
14219 (t nil))))
14221 (defun org-diary-to-ical-string (frombuf)
14222 "Get iCalendar entries from diary entries in buffer FROMBUF.
14223 This uses the icalendar.el library."
14224 (let* ((tmpdir (if (featurep 'xemacs)
14225 (temp-directory)
14226 temporary-file-directory))
14227 (tmpfile (make-temp-name
14228 (expand-file-name "orgics" tmpdir)))
14229 buf rtn b e)
14230 (with-current-buffer frombuf
14231 (icalendar-export-region (point-min) (point-max) tmpfile)
14232 (setq buf (find-buffer-visiting tmpfile))
14233 (set-buffer buf)
14234 (goto-char (point-min))
14235 (if (re-search-forward "^BEGIN:VEVENT" nil t)
14236 (setq b (match-beginning 0)))
14237 (goto-char (point-max))
14238 (if (re-search-backward "^END:VEVENT" nil t)
14239 (setq e (match-end 0)))
14240 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
14241 (kill-buffer buf)
14242 (delete-file tmpfile)
14243 rtn))
14245 (defun org-closest-date (start current change prefer show-all)
14246 "Find the date closest to CURRENT that is consistent with START and CHANGE.
14247 When PREFER is `past' return a date that is either CURRENT or past.
14248 When PREFER is `future', return a date that is either CURRENT or future.
14249 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
14250 ;; Make the proper lists from the dates
14251 (catch 'exit
14252 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
14253 dn dw sday cday n1 n2 n0
14254 d m y y1 y2 date1 date2 nmonths nm ny m2)
14256 (setq start (org-date-to-gregorian start)
14257 current (org-date-to-gregorian
14258 (if show-all
14259 current
14260 (time-to-days (current-time))))
14261 sday (calendar-absolute-from-gregorian start)
14262 cday (calendar-absolute-from-gregorian current))
14264 (if (<= cday sday) (throw 'exit sday))
14266 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
14267 (setq dn (string-to-number (match-string 1 change))
14268 dw (cdr (assoc (match-string 2 change) a1)))
14269 (error "Invalid change specifyer: %s" change))
14270 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
14271 (cond
14272 ((eq dw 'day)
14273 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
14274 n2 (+ n1 dn)))
14275 ((eq dw 'year)
14276 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
14277 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
14278 (setq date1 (list m d y1)
14279 n1 (calendar-absolute-from-gregorian date1)
14280 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
14281 n2 (calendar-absolute-from-gregorian date2)))
14282 ((eq dw 'month)
14283 ;; approx number of month between the two dates
14284 (setq nmonths (floor (/ (- cday sday) 30.436875)))
14285 ;; How often does dn fit in there?
14286 (setq d (nth 1 start) m (car start) y (nth 2 start)
14287 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
14288 m (+ m nm)
14289 ny (floor (/ m 12))
14290 y (+ y ny)
14291 m (- m (* ny 12)))
14292 (while (> m 12) (setq m (- m 12) y (1+ y)))
14293 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14294 (setq m2 (+ m dn) y2 y)
14295 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14296 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14297 (while (<= n2 cday)
14298 (setq n1 n2 m m2 y y2)
14299 (setq m2 (+ m dn) y2 y)
14300 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14301 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14302 ;; Make sure n1 is the earlier date
14303 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14304 (if show-all
14305 (cond
14306 ((eq prefer 'past) (if (= cday n2) n2 n1))
14307 ((eq prefer 'future) (if (= cday n1) n1 n2))
14308 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14309 (cond
14310 ((eq prefer 'past) (if (= cday n2) n2 n1))
14311 ((eq prefer 'future) (if (= cday n1) n1 n2))
14312 (t (if (= cday n1) n1 n2)))))))
14314 (defun org-date-to-gregorian (date)
14315 "Turn any specification of DATE into a gregorian date for the calendar."
14316 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14317 ((and (listp date) (= (length date) 3)) date)
14318 ((stringp date)
14319 (setq date (org-parse-time-string date))
14320 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14321 ((listp date)
14322 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14324 (defun org-parse-time-string (s &optional nodefault)
14325 "Parse the standard Org-mode time string.
14326 This should be a lot faster than the normal `parse-time-string'.
14327 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14328 hour and minute fields will be nil if not given."
14329 (if (string-match org-ts-regexp0 s)
14330 (list 0
14331 (if (or (match-beginning 8) (not nodefault))
14332 (string-to-number (or (match-string 8 s) "0")))
14333 (if (or (match-beginning 7) (not nodefault))
14334 (string-to-number (or (match-string 7 s) "0")))
14335 (string-to-number (match-string 4 s))
14336 (string-to-number (match-string 3 s))
14337 (string-to-number (match-string 2 s))
14338 nil nil nil)
14339 (error "Not a standard Org-mode time string: %s" s)))
14341 (defun org-timestamp-up (&optional arg)
14342 "Increase the date item at the cursor by one.
14343 If the cursor is on the year, change the year. If it is on the month or
14344 the day, change that.
14345 With prefix ARG, change by that many units."
14346 (interactive "p")
14347 (org-timestamp-change (prefix-numeric-value arg)))
14349 (defun org-timestamp-down (&optional arg)
14350 "Decrease the date item at the cursor by one.
14351 If the cursor is on the year, change the year. If it is on the month or
14352 the day, change that.
14353 With prefix ARG, change by that many units."
14354 (interactive "p")
14355 (org-timestamp-change (- (prefix-numeric-value arg))))
14357 (defun org-timestamp-up-day (&optional arg)
14358 "Increase the date in the time stamp by one day.
14359 With prefix ARG, change that many days."
14360 (interactive "p")
14361 (if (and (not (org-at-timestamp-p t))
14362 (org-on-heading-p))
14363 (org-todo 'up)
14364 (org-timestamp-change (prefix-numeric-value arg) 'day)))
14366 (defun org-timestamp-down-day (&optional arg)
14367 "Decrease the date in the time stamp by one day.
14368 With prefix ARG, change that many days."
14369 (interactive "p")
14370 (if (and (not (org-at-timestamp-p t))
14371 (org-on-heading-p))
14372 (org-todo 'down)
14373 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
14375 (defun org-at-timestamp-p (&optional inactive-ok)
14376 "Determine if the cursor is in or at a timestamp."
14377 (interactive)
14378 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
14379 (pos (point))
14380 (ans (or (looking-at tsr)
14381 (save-excursion
14382 (skip-chars-backward "^[<\n\r\t")
14383 (if (> (point) (point-min)) (backward-char 1))
14384 (and (looking-at tsr)
14385 (> (- (match-end 0) pos) -1))))))
14386 (and ans
14387 (boundp 'org-ts-what)
14388 (setq org-ts-what
14389 (cond
14390 ((= pos (match-beginning 0)) 'bracket)
14391 ((= pos (1- (match-end 0))) 'bracket)
14392 ((org-pos-in-match-range pos 2) 'year)
14393 ((org-pos-in-match-range pos 3) 'month)
14394 ((org-pos-in-match-range pos 7) 'hour)
14395 ((org-pos-in-match-range pos 8) 'minute)
14396 ((or (org-pos-in-match-range pos 4)
14397 (org-pos-in-match-range pos 5)) 'day)
14398 ((and (> pos (or (match-end 8) (match-end 5)))
14399 (< pos (match-end 0)))
14400 (- pos (or (match-end 8) (match-end 5))))
14401 (t 'day))))
14402 ans))
14404 (defun org-toggle-timestamp-type ()
14405 "Toggle the type (<active> or [inactive]) of a time stamp."
14406 (interactive)
14407 (when (org-at-timestamp-p t)
14408 (let ((beg (match-beginning 0)) (end (match-end 0))
14409 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14410 (save-excursion
14411 (goto-char beg)
14412 (while (re-search-forward "[][<>]" end t)
14413 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14414 t t)))
14415 (message "Timestamp is now %sactive"
14416 (if (equal (char-after beg) ?<) "" "in")))))
14418 (defun org-timestamp-change (n &optional what)
14419 "Change the date in the time stamp at point.
14420 The date will be changed by N times WHAT. WHAT can be `day', `month',
14421 `year', `minute', `second'. If WHAT is not given, the cursor position
14422 in the timestamp determines what will be changed."
14423 (let ((pos (point))
14424 with-hm inactive
14425 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14426 org-ts-what
14427 extra rem
14428 ts time time0)
14429 (if (not (org-at-timestamp-p t))
14430 (error "Not at a timestamp"))
14431 (if (and (not what) (eq org-ts-what 'bracket))
14432 (org-toggle-timestamp-type)
14433 (if (and (not what) (not (eq org-ts-what 'day))
14434 org-display-custom-times
14435 (get-text-property (point) 'display)
14436 (not (get-text-property (1- (point)) 'display)))
14437 (setq org-ts-what 'day))
14438 (setq org-ts-what (or what org-ts-what)
14439 inactive (= (char-after (match-beginning 0)) ?\[)
14440 ts (match-string 0))
14441 (replace-match "")
14442 (if (string-match
14443 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14445 (setq extra (match-string 1 ts)))
14446 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14447 (setq with-hm t))
14448 (setq time0 (org-parse-time-string ts))
14449 (when (and (eq org-ts-what 'minute)
14450 (eq current-prefix-arg nil))
14451 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14452 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14453 (setcar (cdr time0) (+ (nth 1 time0)
14454 (if (> n 0) (- rem) (- dm rem))))))
14455 (setq time
14456 (encode-time (or (car time0) 0)
14457 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14458 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14459 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14460 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14461 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14462 (nthcdr 6 time0)))
14463 (when (and (member org-ts-what '(hour minute))
14464 extra
14465 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14466 (setq extra (org-modify-ts-extra
14467 extra
14468 (if (eq org-ts-what 'hour) 2 5)
14469 n dm)))
14470 (when (integerp org-ts-what)
14471 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14472 (if (eq what 'calendar)
14473 (let ((cal-date (org-get-date-from-calendar)))
14474 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14475 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14476 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14477 (setcar time0 (or (car time0) 0))
14478 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
14479 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
14480 (setq time (apply 'encode-time time0))))
14481 (setq org-last-changed-timestamp
14482 (org-insert-time-stamp time with-hm inactive nil nil extra))
14483 (org-clock-update-time-maybe)
14484 (goto-char pos)
14485 ;; Try to recenter the calendar window, if any
14486 (if (and org-calendar-follow-timestamp-change
14487 (get-buffer-window "*Calendar*" t)
14488 (memq org-ts-what '(day month year)))
14489 (org-recenter-calendar (time-to-days time))))))
14491 (defun org-modify-ts-extra (s pos n dm)
14492 "Change the different parts of the lead-time and repeat fields in timestamp."
14493 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
14494 ng h m new rem)
14495 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
14496 (cond
14497 ((or (org-pos-in-match-range pos 2)
14498 (org-pos-in-match-range pos 3))
14499 (setq m (string-to-number (match-string 3 s))
14500 h (string-to-number (match-string 2 s)))
14501 (if (org-pos-in-match-range pos 2)
14502 (setq h (+ h n))
14503 (setq n (* dm (org-no-warnings (signum n))))
14504 (when (not (= 0 (setq rem (% m dm))))
14505 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
14506 (setq m (+ m n)))
14507 (if (< m 0) (setq m (+ m 60) h (1- h)))
14508 (if (> m 59) (setq m (- m 60) h (1+ h)))
14509 (setq h (min 24 (max 0 h)))
14510 (setq ng 1 new (format "-%02d:%02d" h m)))
14511 ((org-pos-in-match-range pos 6)
14512 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
14513 ((org-pos-in-match-range pos 5)
14514 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
14516 ((org-pos-in-match-range pos 9)
14517 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
14518 ((org-pos-in-match-range pos 8)
14519 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
14521 (when ng
14522 (setq s (concat
14523 (substring s 0 (match-beginning ng))
14525 (substring s (match-end ng))))))
14528 (defun org-recenter-calendar (date)
14529 "If the calendar is visible, recenter it to DATE."
14530 (let* ((win (selected-window))
14531 (cwin (get-buffer-window "*Calendar*" t))
14532 (calendar-move-hook nil))
14533 (when cwin
14534 (select-window cwin)
14535 (calendar-goto-date (if (listp date) date
14536 (calendar-gregorian-from-absolute date)))
14537 (select-window win))))
14539 (defun org-goto-calendar (&optional arg)
14540 "Go to the Emacs calendar at the current date.
14541 If there is a time stamp in the current line, go to that date.
14542 A prefix ARG can be used to force the current date."
14543 (interactive "P")
14544 (let ((tsr org-ts-regexp) diff
14545 (calendar-move-hook nil)
14546 (calendar-view-holidays-initially-flag nil)
14547 (view-calendar-holidays-initially nil)
14548 (calendar-view-diary-initially-flag nil)
14549 (view-diary-entries-initially nil))
14550 (if (or (org-at-timestamp-p)
14551 (save-excursion
14552 (beginning-of-line 1)
14553 (looking-at (concat ".*" tsr))))
14554 (let ((d1 (time-to-days (current-time)))
14555 (d2 (time-to-days
14556 (org-time-string-to-time (match-string 1)))))
14557 (setq diff (- d2 d1))))
14558 (calendar)
14559 (calendar-goto-today)
14560 (if (and diff (not arg)) (calendar-forward-day diff))))
14562 (defun org-get-date-from-calendar ()
14563 "Return a list (month day year) of date at point in calendar."
14564 (with-current-buffer "*Calendar*"
14565 (save-match-data
14566 (calendar-cursor-to-date))))
14568 (defun org-date-from-calendar ()
14569 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14570 If there is already a time stamp at the cursor position, update it."
14571 (interactive)
14572 (if (org-at-timestamp-p t)
14573 (org-timestamp-change 0 'calendar)
14574 (let ((cal-date (org-get-date-from-calendar)))
14575 (org-insert-time-stamp
14576 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14578 (defun org-minutes-to-hh:mm-string (m)
14579 "Compute H:MM from a number of minutes."
14580 (let ((h (/ m 60)))
14581 (setq m (- m (* 60 h)))
14582 (format org-time-clocksum-format h m)))
14584 (defun org-hh:mm-string-to-minutes (s)
14585 "Convert a string H:MM to a number of minutes.
14586 If the string is just a number, interpret it as minutes.
14587 In fact, the first hh:mm or number in the string will be taken,
14588 there can be extra stuff in the string.
14589 If no number is found, the return value is 0."
14590 (cond
14591 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14592 (+ (* (string-to-number (match-string 1 s)) 60)
14593 (string-to-number (match-string 2 s))))
14594 ((string-match "\\([0-9]+\\)" s)
14595 (string-to-number (match-string 1 s)))
14596 (t 0)))
14598 ;;;; Files
14600 (defun org-save-all-org-buffers ()
14601 "Save all Org-mode buffers without user confirmation."
14602 (interactive)
14603 (message "Saving all Org-mode buffers...")
14604 (save-some-buffers t 'org-mode-p)
14605 (when (featurep 'org-id) (org-id-locations-save))
14606 (message "Saving all Org-mode buffers... done"))
14608 (defun org-revert-all-org-buffers ()
14609 "Revert all Org-mode buffers.
14610 Prompt for confirmation when there are unsaved changes.
14611 Be sure you know what you are doing before letting this function
14612 overwrite your changes.
14614 This function is useful in a setup where one tracks org files
14615 with a version control system, to revert on one machine after pulling
14616 changes from another. I believe the procedure must be like this:
14618 1. M-x org-save-all-org-buffers
14619 2. Pull changes from the other machine, resolve conflicts
14620 3. M-x org-revert-all-org-buffers"
14621 (interactive)
14622 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14623 (error "Abort"))
14624 (save-excursion
14625 (save-window-excursion
14626 (mapc
14627 (lambda (b)
14628 (when (and (with-current-buffer b (org-mode-p))
14629 (with-current-buffer b buffer-file-name))
14630 (switch-to-buffer b)
14631 (revert-buffer t 'no-confirm)))
14632 (buffer-list))
14633 (when (and (featurep 'org-id) org-id-track-globally)
14634 (org-id-locations-load)))))
14636 ;;;; Agenda files
14638 ;;;###autoload
14639 (defun org-iswitchb (&optional arg)
14640 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14641 With a prefix argument, restrict available to files.
14642 With two prefix arguments, restrict available buffers to agenda files."
14643 (interactive "P")
14644 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14645 ((equal arg '(16)) (org-buffer-list 'agenda))
14646 (t (org-buffer-list)))))
14647 (switch-to-buffer
14648 (org-icompleting-read "Org buffer: "
14649 (mapcar 'list (mapcar 'buffer-name blist))
14650 nil t))))
14652 ;;;###autoload
14653 (defalias 'org-ido-switchb 'org-iswitchb)
14655 (defun org-buffer-list (&optional predicate exclude-tmp)
14656 "Return a list of Org buffers.
14657 PREDICATE can be `export', `files' or `agenda'.
14659 export restrict the list to Export buffers.
14660 files restrict the list to buffers visiting Org files.
14661 agenda restrict the list to buffers visiting agenda files.
14663 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14664 (let* ((bfn nil)
14665 (agenda-files (and (eq predicate 'agenda)
14666 (mapcar 'file-truename (org-agenda-files t))))
14667 (filter
14668 (cond
14669 ((eq predicate 'files)
14670 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14671 ((eq predicate 'export)
14672 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14673 ((eq predicate 'agenda)
14674 (lambda (b)
14675 (with-current-buffer b
14676 (and (eq major-mode 'org-mode)
14677 (setq bfn (buffer-file-name b))
14678 (member (file-truename bfn) agenda-files)))))
14679 (t (lambda (b) (with-current-buffer b
14680 (or (eq major-mode 'org-mode)
14681 (string-match "\*Org .*Export"
14682 (buffer-name b)))))))))
14683 (delq nil
14684 (mapcar
14685 (lambda(b)
14686 (if (and (funcall filter b)
14687 (or (not exclude-tmp)
14688 (not (string-match "tmp" (buffer-name b)))))
14690 nil))
14691 (buffer-list)))))
14693 (defun org-agenda-files (&optional unrestricted archives)
14694 "Get the list of agenda files.
14695 Optional UNRESTRICTED means return the full list even if a restriction
14696 is currently in place.
14697 When ARCHIVES is t, include all archive files that are really being
14698 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14699 `org-agenda-archives-mode' is t."
14700 (let ((files
14701 (cond
14702 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14703 ((stringp org-agenda-files) (org-read-agenda-file-list))
14704 ((listp org-agenda-files) org-agenda-files)
14705 (t (error "Invalid value of `org-agenda-files'")))))
14706 (setq files (apply 'append
14707 (mapcar (lambda (f)
14708 (if (file-directory-p f)
14709 (directory-files
14710 f t org-agenda-file-regexp)
14711 (list f)))
14712 files)))
14713 (when org-agenda-skip-unavailable-files
14714 (setq files (delq nil
14715 (mapcar (function
14716 (lambda (file)
14717 (and (file-readable-p file) file)))
14718 files))))
14719 (when (or (eq archives t)
14720 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14721 (setq files (org-add-archive-files files)))
14722 files))
14724 (defun org-edit-agenda-file-list ()
14725 "Edit the list of agenda files.
14726 Depending on setup, this either uses customize to edit the variable
14727 `org-agenda-files', or it visits the file that is holding the list. In the
14728 latter case, the buffer is set up in a way that saving it automatically kills
14729 the buffer and restores the previous window configuration."
14730 (interactive)
14731 (if (stringp org-agenda-files)
14732 (let ((cw (current-window-configuration)))
14733 (find-file org-agenda-files)
14734 (org-set-local 'org-window-configuration cw)
14735 (org-add-hook 'after-save-hook
14736 (lambda ()
14737 (set-window-configuration
14738 (prog1 org-window-configuration
14739 (kill-buffer (current-buffer))))
14740 (org-install-agenda-files-menu)
14741 (message "New agenda file list installed"))
14742 nil 'local)
14743 (message "%s" (substitute-command-keys
14744 "Edit list and finish with \\[save-buffer]")))
14745 (customize-variable 'org-agenda-files)))
14747 (defun org-store-new-agenda-file-list (list)
14748 "Set new value for the agenda file list and save it correctly."
14749 (if (stringp org-agenda-files)
14750 (let ((fe (org-read-agenda-file-list t)) b u)
14751 (while (setq b (find-buffer-visiting org-agenda-files))
14752 (kill-buffer b))
14753 (with-temp-file org-agenda-files
14754 (insert
14755 (mapconcat
14756 (lambda (f) ;; Keep un-expanded entries.
14757 (if (setq u (assoc f fe))
14758 (cdr u)
14760 list "\n")
14761 "\n")))
14762 (let ((org-mode-hook nil) (org-inhibit-startup t)
14763 (org-insert-mode-line-in-empty-file nil))
14764 (setq org-agenda-files list)
14765 (customize-save-variable 'org-agenda-files org-agenda-files))))
14767 (defun org-read-agenda-file-list (&optional pair-with-expansion)
14768 "Read the list of agenda files from a file.
14769 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
14770 filenames, used by `org-store-new-agenda-file-list' to write back
14771 un-expanded file names."
14772 (when (file-directory-p org-agenda-files)
14773 (error "`org-agenda-files' cannot be a single directory"))
14774 (when (stringp org-agenda-files)
14775 (with-temp-buffer
14776 (insert-file-contents org-agenda-files)
14777 (mapcar
14778 (lambda (f)
14779 (let ((e (expand-file-name (substitute-in-file-name f)
14780 org-directory)))
14781 (if pair-with-expansion
14782 (cons e f)
14783 e)))
14784 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
14786 ;;;###autoload
14787 (defun org-cycle-agenda-files ()
14788 "Cycle through the files in `org-agenda-files'.
14789 If the current buffer visits an agenda file, find the next one in the list.
14790 If the current buffer does not, find the first agenda file."
14791 (interactive)
14792 (let* ((fs (org-agenda-files t))
14793 (files (append fs (list (car fs))))
14794 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14795 file)
14796 (unless files (error "No agenda files"))
14797 (catch 'exit
14798 (while (setq file (pop files))
14799 (if (equal (file-truename file) tcf)
14800 (when (car files)
14801 (find-file (car files))
14802 (throw 'exit t))))
14803 (find-file (car fs)))
14804 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14806 (defun org-agenda-file-to-front (&optional to-end)
14807 "Move/add the current file to the top of the agenda file list.
14808 If the file is not present in the list, it is added to the front. If it is
14809 present, it is moved there. With optional argument TO-END, add/move to the
14810 end of the list."
14811 (interactive "P")
14812 (let ((org-agenda-skip-unavailable-files nil)
14813 (file-alist (mapcar (lambda (x)
14814 (cons (file-truename x) x))
14815 (org-agenda-files t)))
14816 (ctf (file-truename buffer-file-name))
14817 x had)
14818 (setq x (assoc ctf file-alist) had x)
14820 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14821 (if to-end
14822 (setq file-alist (append (delq x file-alist) (list x)))
14823 (setq file-alist (cons x (delq x file-alist))))
14824 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14825 (org-install-agenda-files-menu)
14826 (message "File %s to %s of agenda file list"
14827 (if had "moved" "added") (if to-end "end" "front"))))
14829 (defun org-remove-file (&optional file)
14830 "Remove current file from the list of files in variable `org-agenda-files'.
14831 These are the files which are being checked for agenda entries.
14832 Optional argument FILE means use this file instead of the current."
14833 (interactive)
14834 (let* ((org-agenda-skip-unavailable-files nil)
14835 (file (or file buffer-file-name))
14836 (true-file (file-truename file))
14837 (afile (abbreviate-file-name file))
14838 (files (delq nil (mapcar
14839 (lambda (x)
14840 (if (equal true-file
14841 (file-truename x))
14842 nil x))
14843 (org-agenda-files t)))))
14844 (if (not (= (length files) (length (org-agenda-files t))))
14845 (progn
14846 (org-store-new-agenda-file-list files)
14847 (org-install-agenda-files-menu)
14848 (message "Removed file: %s" afile))
14849 (message "File was not in list: %s (not removed)" afile))))
14851 (defun org-file-menu-entry (file)
14852 (vector file (list 'find-file file) t))
14854 (defun org-check-agenda-file (file)
14855 "Make sure FILE exists. If not, ask user what to do."
14856 (when (not (file-exists-p file))
14857 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14858 (abbreviate-file-name file))
14859 (let ((r (downcase (read-char-exclusive))))
14860 (cond
14861 ((equal r ?r)
14862 (org-remove-file file)
14863 (throw 'nextfile t))
14864 (t (error "Abort"))))))
14866 (defun org-get-agenda-file-buffer (file)
14867 "Get a buffer visiting FILE. If the buffer needs to be created, add
14868 it to the list of buffers which might be released later."
14869 (let ((buf (org-find-base-buffer-visiting file)))
14870 (if buf
14871 buf ; just return it
14872 ;; Make a new buffer and remember it
14873 (setq buf (find-file-noselect file))
14874 (if buf (push buf org-agenda-new-buffers))
14875 buf)))
14877 (defun org-release-buffers (blist)
14878 "Release all buffers in list, asking the user for confirmation when needed.
14879 When a buffer is unmodified, it is just killed. When modified, it is saved
14880 \(if the user agrees) and then killed."
14881 (let (buf file)
14882 (while (setq buf (pop blist))
14883 (setq file (buffer-file-name buf))
14884 (when (and (buffer-modified-p buf)
14885 file
14886 (y-or-n-p (format "Save file %s? " file)))
14887 (with-current-buffer buf (save-buffer)))
14888 (kill-buffer buf))))
14890 (defun org-prepare-agenda-buffers (files)
14891 "Create buffers for all agenda files, protect archived trees and comments."
14892 (interactive)
14893 (let ((pa '(:org-archived t))
14894 (pc '(:org-comment t))
14895 (pall '(:org-archived t :org-comment t))
14896 (inhibit-read-only t)
14897 (rea (concat ":" org-archive-tag ":"))
14898 bmp file re)
14899 (save-excursion
14900 (save-restriction
14901 (while (setq file (pop files))
14902 (catch 'nextfile
14903 (if (bufferp file)
14904 (set-buffer file)
14905 (org-check-agenda-file file)
14906 (set-buffer (org-get-agenda-file-buffer file)))
14907 (widen)
14908 (setq bmp (buffer-modified-p))
14909 (org-refresh-category-properties)
14910 (setq org-todo-keywords-for-agenda
14911 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14912 (setq org-done-keywords-for-agenda
14913 (append org-done-keywords-for-agenda org-done-keywords))
14914 (setq org-todo-keyword-alist-for-agenda
14915 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14916 (setq org-drawers-for-agenda
14917 (append org-drawers-for-agenda org-drawers))
14918 (setq org-tag-alist-for-agenda
14919 (append org-tag-alist-for-agenda org-tag-alist))
14921 (save-excursion
14922 (remove-text-properties (point-min) (point-max) pall)
14923 (when org-agenda-skip-archived-trees
14924 (goto-char (point-min))
14925 (while (re-search-forward rea nil t)
14926 (if (org-on-heading-p t)
14927 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14928 (goto-char (point-min))
14929 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14930 (while (re-search-forward re nil t)
14931 (add-text-properties
14932 (match-beginning 0) (org-end-of-subtree t) pc)))
14933 (set-buffer-modified-p bmp)))))
14934 (setq org-todo-keyword-alist-for-agenda
14935 (org-uniquify org-todo-keyword-alist-for-agenda)
14936 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14938 ;;;; Embedded LaTeX
14940 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14941 "Keymap for the minor `org-cdlatex-mode'.")
14943 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14944 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14945 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14946 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14947 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14949 (defvar org-cdlatex-texmathp-advice-is-done nil
14950 "Flag remembering if we have applied the advice to texmathp already.")
14952 (define-minor-mode org-cdlatex-mode
14953 "Toggle the minor `org-cdlatex-mode'.
14954 This mode supports entering LaTeX environment and math in LaTeX fragments
14955 in Org-mode.
14956 \\{org-cdlatex-mode-map}"
14957 nil " OCDL" nil
14958 (when org-cdlatex-mode (require 'cdlatex))
14959 (unless org-cdlatex-texmathp-advice-is-done
14960 (setq org-cdlatex-texmathp-advice-is-done t)
14961 (defadvice texmathp (around org-math-always-on activate)
14962 "Always return t in org-mode buffers.
14963 This is because we want to insert math symbols without dollars even outside
14964 the LaTeX math segments. If Orgmode thinks that point is actually inside
14965 an embedded LaTeX fragment, let texmathp do its job.
14966 \\[org-cdlatex-mode-map]"
14967 (interactive)
14968 (let (p)
14969 (cond
14970 ((not (org-mode-p)) ad-do-it)
14971 ((eq this-command 'cdlatex-math-symbol)
14972 (setq ad-return-value t
14973 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14975 (let ((p (org-inside-LaTeX-fragment-p)))
14976 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14977 (setq ad-return-value t
14978 texmathp-why '("Org-mode embedded math" . 0))
14979 (if p ad-do-it)))))))))
14981 (defun turn-on-org-cdlatex ()
14982 "Unconditionally turn on `org-cdlatex-mode'."
14983 (org-cdlatex-mode 1))
14985 (defun org-inside-LaTeX-fragment-p ()
14986 "Test if point is inside a LaTeX fragment.
14987 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14988 sequence appearing also before point.
14989 Even though the matchers for math are configurable, this function assumes
14990 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14991 delimiters are skipped when they have been removed by customization.
14992 The return value is nil, or a cons cell with the delimiter and
14993 and the position of this delimiter.
14995 This function does a reasonably good job, but can locally be fooled by
14996 for example currency specifications. For example it will assume being in
14997 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14998 fragments that are properly closed, but during editing, we have to live
14999 with the uncertainty caused by missing closing delimiters. This function
15000 looks only before point, not after."
15001 (catch 'exit
15002 (let ((pos (point))
15003 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15004 (lim (progn
15005 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15006 (point)))
15007 dd-on str (start 0) m re)
15008 (goto-char pos)
15009 (when dodollar
15010 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15011 re (nth 1 (assoc "$" org-latex-regexps)))
15012 (while (string-match re str start)
15013 (cond
15014 ((= (match-end 0) (length str))
15015 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
15016 ((= (match-end 0) (- (length str) 5))
15017 (throw 'exit nil))
15018 (t (setq start (match-end 0))))))
15019 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15020 (goto-char pos)
15021 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15022 (and (match-beginning 2) (throw 'exit nil))
15023 ;; count $$
15024 (while (re-search-backward "\\$\\$" lim t)
15025 (setq dd-on (not dd-on)))
15026 (goto-char pos)
15027 (if dd-on (cons "$$" m))))))
15029 (defun org-inside-latex-macro-p ()
15030 "Is point inside a LaTeX macro or its arguments?"
15031 (save-match-data
15032 (org-in-regexp
15033 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
15035 (defun test ()
15036 (interactive)
15037 (message "%s" (org-inside-latex-macro-p)))
15039 (defun org-try-cdlatex-tab ()
15040 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15041 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15042 - inside a LaTeX fragment, or
15043 - after the first word in a line, where an abbreviation expansion could
15044 insert a LaTeX environment."
15045 (when org-cdlatex-mode
15046 (cond
15047 ((save-excursion
15048 (skip-chars-backward "a-zA-Z0-9*")
15049 (skip-chars-backward " \t")
15050 (bolp))
15051 (cdlatex-tab) t)
15052 ((org-inside-LaTeX-fragment-p)
15053 (cdlatex-tab) t)
15054 (t nil))))
15056 (defun org-cdlatex-underscore-caret (&optional arg)
15057 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15058 Revert to the normal definition outside of these fragments."
15059 (interactive "P")
15060 (if (org-inside-LaTeX-fragment-p)
15061 (call-interactively 'cdlatex-sub-superscript)
15062 (let (org-cdlatex-mode)
15063 (call-interactively (key-binding (vector last-input-event))))))
15065 (defun org-cdlatex-math-modify (&optional arg)
15066 "Execute `cdlatex-math-modify' in LaTeX fragments.
15067 Revert to the normal definition outside of these fragments."
15068 (interactive "P")
15069 (if (org-inside-LaTeX-fragment-p)
15070 (call-interactively 'cdlatex-math-modify)
15071 (let (org-cdlatex-mode)
15072 (call-interactively (key-binding (vector last-input-event))))))
15074 (defvar org-latex-fragment-image-overlays nil
15075 "List of overlays carrying the images of latex fragments.")
15076 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15078 (defun org-remove-latex-fragment-image-overlays ()
15079 "Remove all overlays with LaTeX fragment images in current buffer."
15080 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
15081 (setq org-latex-fragment-image-overlays nil))
15083 (defun org-preview-latex-fragment (&optional subtree)
15084 "Preview the LaTeX fragment at point, or all locally or globally.
15085 If the cursor is in a LaTeX fragment, create the image and overlay
15086 it over the source code. If there is no fragment at point, display
15087 all fragments in the current text, from one headline to the next. With
15088 prefix SUBTREE, display all fragments in the current subtree. With a
15089 double prefix `C-u C-u', or when the cursor is before the first headline,
15090 display all fragments in the buffer.
15091 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15092 (interactive "P")
15093 (org-remove-latex-fragment-image-overlays)
15094 (save-excursion
15095 (save-restriction
15096 (let (beg end at msg)
15097 (cond
15098 ((or (equal subtree '(16))
15099 (not (save-excursion
15100 (re-search-backward (concat "^" outline-regexp) nil t))))
15101 (setq beg (point-min) end (point-max)
15102 msg "Creating images for buffer...%s"))
15103 ((equal subtree '(4))
15104 (org-back-to-heading)
15105 (setq beg (point) end (org-end-of-subtree t)
15106 msg "Creating images for subtree...%s"))
15108 (if (setq at (org-inside-LaTeX-fragment-p))
15109 (goto-char (max (point-min) (- (cdr at) 2)))
15110 (org-back-to-heading))
15111 (setq beg (point) end (progn (outline-next-heading) (point))
15112 msg (if at "Creating image...%s"
15113 "Creating images for entry...%s"))))
15114 (message msg "")
15115 (narrow-to-region beg end)
15116 (goto-char beg)
15117 (org-format-latex
15118 (concat "ltxpng/" (file-name-sans-extension
15119 (file-name-nondirectory
15120 buffer-file-name)))
15121 default-directory 'overlays msg at 'forbuffer)
15122 (message msg "done. Use `C-c C-c' to remove images.")))))
15124 (defvar org-latex-regexps
15125 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15126 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15127 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15128 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15129 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15130 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15131 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
15132 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
15133 "Regular expressions for matching embedded LaTeX.")
15135 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
15136 "Replace LaTeX fragments with links to an image, and produce images.
15137 Some of the options can be changed using the variable
15138 `org-format-latex-options'."
15139 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15140 (let* ((prefixnodir (file-name-nondirectory prefix))
15141 (absprefix (expand-file-name prefix dir))
15142 (todir (file-name-directory absprefix))
15143 (opt org-format-latex-options)
15144 (matchers (plist-get opt :matchers))
15145 (re-list org-latex-regexps)
15146 (org-format-latex-header-extra
15147 (plist-get (org-infile-export-plist) :latex-header-extra))
15148 (cnt 0) txt hash link beg end re e checkdir
15149 executables-checked
15150 m n block linkfile movefile ov)
15151 ;; Check the different regular expressions
15152 (while (setq e (pop re-list))
15153 (setq m (car e) re (nth 1 e) n (nth 2 e)
15154 block (if (nth 3 e) "\n\n" ""))
15155 (when (member m matchers)
15156 (goto-char (point-min))
15157 (while (re-search-forward re nil t)
15158 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
15159 (not (get-text-property (match-beginning n)
15160 'org-protected))
15161 (or (not overlays)
15162 (not (eq (get-char-property (match-beginning n)
15163 'org-overlay-type)
15164 'org-latex-overlay))))
15165 (setq txt (match-string n)
15166 beg (match-beginning n) end (match-end n)
15167 cnt (1+ cnt))
15168 (let (print-length print-level) ; make sure full list is printed
15169 (setq hash (sha1 (prin1-to-string
15170 (list org-format-latex-header
15171 org-format-latex-header-extra
15172 org-export-latex-default-packages-alist
15173 org-export-latex-packages-alist
15174 org-format-latex-options
15175 forbuffer txt)))
15176 linkfile (format "%s_%s.png" prefix hash)
15177 movefile (format "%s_%s.png" absprefix hash)))
15178 (setq link (concat block "[[file:" linkfile "]]" block))
15179 (if msg (message msg cnt))
15180 (goto-char beg)
15181 (unless checkdir ; make sure the directory exists
15182 (setq checkdir t)
15183 (or (file-directory-p todir) (make-directory todir)))
15185 (unless executables-checked
15186 (org-check-external-command
15187 "latex" "needed to convert LaTeX fragments to images")
15188 (org-check-external-command
15189 "dvipng" "needed to convert LaTeX fragments to images")
15190 (setq executables-checked t))
15192 (unless (file-exists-p movefile)
15193 (org-create-formula-image
15194 txt movefile opt forbuffer))
15195 (if overlays
15196 (progn
15197 (mapc (lambda (o)
15198 (if (eq (org-overlay-get o 'org-overlay-type)
15199 'org-latex-overlay)
15200 (org-delete-overlay o)))
15201 (org-overlays-in beg end))
15202 (setq ov (org-make-overlay beg end))
15203 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
15204 (if (featurep 'xemacs)
15205 (progn
15206 (org-overlay-put ov 'invisible t)
15207 (org-overlay-put
15208 ov 'end-glyph
15209 (make-glyph (vector 'png :file movefile))))
15210 (org-overlay-put
15211 ov 'display
15212 (list 'image :type 'png :file movefile :ascent 'center)))
15213 (push ov org-latex-fragment-image-overlays)
15214 (goto-char end))
15215 (delete-region beg end)
15216 (insert (org-add-props link
15217 (list 'org-latex-src
15218 (replace-regexp-in-string "\"" "" txt)))))))))))
15220 ;; This function borrows from Ganesh Swami's latex2png.el
15221 (defun org-create-formula-image (string tofile options buffer)
15222 "This calls dvipng."
15223 (require 'org-latex)
15224 (let* ((tmpdir (if (featurep 'xemacs)
15225 (temp-directory)
15226 temporary-file-directory))
15227 (texfilebase (make-temp-name
15228 (expand-file-name "orgtex" tmpdir)))
15229 (texfile (concat texfilebase ".tex"))
15230 (dvifile (concat texfilebase ".dvi"))
15231 (pngfile (concat texfilebase ".png"))
15232 (fnh (if (featurep 'xemacs)
15233 (font-height (get-face-font 'default))
15234 (face-attribute 'default :height nil)))
15235 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
15236 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
15237 (fg (or (plist-get options (if buffer :foreground :html-foreground))
15238 "Black"))
15239 (bg (or (plist-get options (if buffer :background :html-background))
15240 "Transparent")))
15241 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
15242 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
15243 (with-temp-file texfile
15244 (insert org-format-latex-header
15245 (if (or org-export-latex-default-packages-alist
15246 org-export-latex-packages-alist)
15247 (concat "\n"
15248 (mapconcat (lambda(p)
15249 (if (equal "" (car p))
15250 (format "\\usepackage{%s}" (cadr p))
15251 (format "\\usepackage[%s]{%s}"
15252 (car p) (cadr p))))
15253 (append
15254 org-export-latex-default-packages-alist
15255 org-export-latex-packages-alist)
15256 "\n"))
15258 (if org-format-latex-header-extra
15259 (concat "\n" org-format-latex-header-extra)
15261 "\n\\begin{document}\n" string "\n\\end{document}\n"))
15262 (let ((dir default-directory))
15263 (condition-case nil
15264 (progn
15265 (cd tmpdir)
15266 (call-process "latex" nil nil nil texfile))
15267 (error nil))
15268 (cd dir))
15269 (if (not (file-exists-p dvifile))
15270 (progn (message "Failed to create dvi file from %s" texfile) nil)
15271 (condition-case nil
15272 (call-process "dvipng" nil nil nil
15273 "-fg" fg "-bg" bg
15274 "-D" dpi
15275 ;;"-x" scale "-y" scale
15276 "-T" "tight"
15277 "-o" pngfile
15278 dvifile)
15279 (error nil))
15280 (if (not (file-exists-p pngfile))
15281 (if org-format-latex-signal-error
15282 (error "Failed to create png file from %s" texfile)
15283 (message "Failed to create png file from %s" texfile)
15284 nil)
15285 ;; Use the requested file name and clean up
15286 (copy-file pngfile tofile 'replace)
15287 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15288 (delete-file (concat texfilebase e)))
15289 pngfile))))
15291 (defun org-dvipng-color (attr)
15292 "Return an rgb color specification for dvipng."
15293 (apply 'format "rgb %s %s %s"
15294 (mapcar 'org-normalize-color
15295 (color-values (face-attribute 'default attr nil)))))
15297 (defun org-normalize-color (value)
15298 "Return string to be used as color value for an RGB component."
15299 (format "%g" (/ value 65535.0)))
15301 ;;;; Key bindings
15303 ;; Make `C-c C-x' a prefix key
15304 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
15306 ;; TAB key with modifiers
15307 (org-defkey org-mode-map "\C-i" 'org-cycle)
15308 (org-defkey org-mode-map [(tab)] 'org-cycle)
15309 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
15310 (org-defkey org-mode-map [(meta tab)] 'org-complete)
15311 (org-defkey org-mode-map "\M-\t" 'org-complete)
15312 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
15313 ;; The following line is necessary under Suse GNU/Linux
15314 (unless (featurep 'xemacs)
15315 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
15316 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
15317 (define-key org-mode-map [backtab] 'org-shifttab)
15319 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
15320 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15321 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
15323 ;; Cursor keys with modifiers
15324 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
15325 (org-defkey org-mode-map [(meta right)] 'org-metaright)
15326 (org-defkey org-mode-map [(meta up)] 'org-metaup)
15327 (org-defkey org-mode-map [(meta down)] 'org-metadown)
15329 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15330 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
15331 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
15332 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
15334 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
15335 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
15336 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
15337 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
15339 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
15340 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
15342 ;;; Extra keys for tty access.
15343 ;; We only set them when really needed because otherwise the
15344 ;; menus don't show the simple keys
15346 (when (or org-use-extra-keys
15347 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
15348 (not window-system))
15349 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
15350 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
15351 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
15352 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
15353 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
15354 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
15355 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
15356 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
15357 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
15358 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
15359 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
15360 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
15361 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
15362 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
15363 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
15364 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
15365 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
15366 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
15367 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
15368 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
15369 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
15370 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
15371 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
15372 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
15373 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
15374 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
15375 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
15376 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
15378 ;; All the other keys
15380 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15381 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
15382 (if (boundp 'narrow-map)
15383 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
15384 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
15385 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
15386 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
15387 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
15388 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
15389 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
15390 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
15391 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
15392 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
15393 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
15394 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
15395 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
15396 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
15397 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
15398 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
15399 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15400 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
15401 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
15402 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
15403 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
15404 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
15405 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
15406 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
15407 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
15408 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
15409 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
15410 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
15411 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
15412 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
15413 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
15414 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
15415 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15416 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15417 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15418 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15419 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
15420 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
15421 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15422 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
15423 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
15424 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
15425 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
15426 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15427 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
15428 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
15429 (org-defkey org-mode-map "\C-c^" 'org-sort)
15430 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15431 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
15432 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
15433 (org-defkey org-mode-map "\C-m" 'org-return)
15434 (org-defkey org-mode-map "\C-j" 'org-return-indent)
15435 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
15436 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
15437 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
15438 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
15439 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
15440 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
15441 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15442 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15443 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
15444 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
15445 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
15446 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
15447 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
15448 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15449 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
15450 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
15451 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
15452 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
15453 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
15454 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
15456 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
15457 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15458 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15459 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15461 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
15462 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15463 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15464 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
15465 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15466 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15467 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15468 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15469 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15470 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15471 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
15472 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
15473 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
15474 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
15475 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
15477 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
15478 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
15479 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
15480 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
15482 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
15484 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
15486 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
15487 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
15489 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
15492 (when (featurep 'xemacs)
15493 (org-defkey org-mode-map 'button3 'popup-mode-menu))
15496 (defconst org-speed-commands-default
15498 ("Outline Navigation")
15499 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
15500 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
15501 ("f" . (org-speed-move-safe 'org-forward-same-level))
15502 ("b" . (org-speed-move-safe 'org-backward-same-level))
15503 ("u" . (org-speed-move-safe 'outline-up-heading))
15504 ("j" . org-goto)
15505 ("g" . (org-refile t))
15506 ("Outline Visibility")
15507 ("c" . org-cycle)
15508 ("C" . org-shifttab)
15509 (" " . org-display-outline-path)
15510 ("Outline Structure Editing")
15511 ("U" . org-shiftmetaup)
15512 ("D" . org-shiftmetadown)
15513 ("r" . org-metaright)
15514 ("l" . org-metaleft)
15515 ("R" . org-shiftmetaright)
15516 ("L" . org-shiftmetaleft)
15517 ("i" . (progn (forward-char 1) (call-interactively
15518 'org-insert-heading-respect-content)))
15519 ("^" . org-sort)
15520 ("w" . org-refile)
15521 ("a" . org-archive-subtree-default-with-confirmation)
15522 ("." . outline-mark-subtree)
15523 ("Clock Commands")
15524 ("I" . org-clock-in)
15525 ("O" . org-clock-out)
15526 ("Meta Data Editing")
15527 ("t" . org-todo)
15528 ("0" . (org-priority ?\ ))
15529 ("1" . (org-priority ?A))
15530 ("2" . (org-priority ?B))
15531 ("3" . (org-priority ?C))
15532 (";" . org-set-tags-command)
15533 ("e" . org-set-effort)
15534 ("Agenda Views etc")
15535 ("v" . org-agenda)
15536 ("/" . org-sparse-tree)
15537 ("Misc")
15538 ("o" . org-open-at-point)
15539 ("?" . org-speed-command-help)
15541 "The default speed commands.")
15543 (defun org-print-speed-command (e)
15544 (if (> (length (car e)) 1)
15545 (progn
15546 (princ "\n")
15547 (princ (car e))
15548 (princ "\n")
15549 (princ (make-string (length (car e)) ?-))
15550 (princ "\n"))
15551 (princ (car e))
15552 (princ " ")
15553 (if (symbolp (cdr e))
15554 (princ (symbol-name (cdr e)))
15555 (prin1 (cdr e)))
15556 (princ "\n")))
15558 (defun org-speed-command-help ()
15559 "Show the available speed commands."
15560 (interactive)
15561 (if (not org-use-speed-commands)
15562 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
15563 (with-output-to-temp-buffer "*Help*"
15564 (princ "User-defined Speed commands\n===========================\n")
15565 (mapc 'org-print-speed-command org-speed-commands-user)
15566 (princ "\n")
15567 (princ "Built-in Speed commands\n=======================\n")
15568 (mapc 'org-print-speed-command org-speed-commands-default))
15569 (with-current-buffer "*Help*"
15570 (setq truncate-lines t))))
15572 (defun org-speed-move-safe (cmd)
15573 "Execute CMD, but make sure that the cursor always ends up in a headline.
15574 If not, return to the original position and throw an error."
15575 (interactive)
15576 (let ((pos (point)))
15577 (call-interactively cmd)
15578 (unless (and (bolp) (org-on-heading-p))
15579 (goto-char pos)
15580 (error "Boundary reached while executing %s" cmd))))
15582 (defvar org-self-insert-command-undo-counter 0)
15584 (defvar org-table-auto-blank-field) ; defined in org-table.el
15585 (defvar org-speed-command nil)
15586 (defun org-self-insert-command (N)
15587 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15588 If the cursor is in a table looking at whitespace, the whitespace is
15589 overwritten, and the table is not marked as requiring realignment."
15590 (interactive "p")
15591 (cond
15592 ((and org-use-speed-commands
15593 (or (and (bolp) (looking-at outline-regexp))
15594 (and (functionp org-use-speed-commands)
15595 (funcall org-use-speed-commands)))
15596 (setq
15597 org-speed-command
15598 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15599 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15600 (cond
15601 ((commandp org-speed-command)
15602 (setq this-command org-speed-command)
15603 (call-interactively org-speed-command))
15604 ((functionp org-speed-command)
15605 (funcall org-speed-command))
15606 ((and org-speed-command (listp org-speed-command))
15607 (eval org-speed-command))
15608 (t (let (org-use-speed-commands)
15609 (call-interactively 'org-self-insert-command)))))
15610 ((and
15611 (org-table-p)
15612 (progn
15613 ;; check if we blank the field, and if that triggers align
15614 (and (featurep 'org-table) org-table-auto-blank-field
15615 (member last-command
15616 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15617 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15618 ;; got extra space, this field does not determine column width
15619 (let (org-table-may-need-update) (org-table-blank-field))
15620 ;; no extra space, this field may determine column width
15621 (org-table-blank-field)))
15623 (eq N 1)
15624 (looking-at "[^|\n]* |"))
15625 (let (org-table-may-need-update)
15626 (goto-char (1- (match-end 0)))
15627 (delete-backward-char 1)
15628 (goto-char (match-beginning 0))
15629 (self-insert-command N)))
15631 (setq org-table-may-need-update t)
15632 (self-insert-command N)
15633 (org-fix-tags-on-the-fly)
15634 (if org-self-insert-cluster-for-undo
15635 (if (not (eq last-command 'org-self-insert-command))
15636 (setq org-self-insert-command-undo-counter 1)
15637 (if (>= org-self-insert-command-undo-counter 20)
15638 (setq org-self-insert-command-undo-counter 1)
15639 (and (> org-self-insert-command-undo-counter 0)
15640 buffer-undo-list
15641 (not (cadr buffer-undo-list)) ; remove nil entry
15642 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15643 (setq org-self-insert-command-undo-counter
15644 (1+ org-self-insert-command-undo-counter))))))))
15646 (defun org-fix-tags-on-the-fly ()
15647 (when (and (equal (char-after (point-at-bol)) ?*)
15648 (org-on-heading-p))
15649 (org-align-tags-here org-tags-column)))
15651 (defun org-delete-backward-char (N)
15652 "Like `delete-backward-char', insert whitespace at field end in tables.
15653 When deleting backwards, in tables this function will insert whitespace in
15654 front of the next \"|\" separator, to keep the table aligned. The table will
15655 still be marked for re-alignment if the field did fill the entire column,
15656 because, in this case the deletion might narrow the column."
15657 (interactive "p")
15658 (if (and (org-table-p)
15659 (eq N 1)
15660 (string-match "|" (buffer-substring (point-at-bol) (point)))
15661 (looking-at ".*?|"))
15662 (let ((pos (point))
15663 (noalign (looking-at "[^|\n\r]* |"))
15664 (c org-table-may-need-update))
15665 (backward-delete-char N)
15666 (skip-chars-forward "^|")
15667 (insert " ")
15668 (goto-char (1- pos))
15669 ;; noalign: if there were two spaces at the end, this field
15670 ;; does not determine the width of the column.
15671 (if noalign (setq org-table-may-need-update c)))
15672 (backward-delete-char N)
15673 (org-fix-tags-on-the-fly)))
15675 (defun org-delete-char (N)
15676 "Like `delete-char', but insert whitespace at field end in tables.
15677 When deleting characters, in tables this function will insert whitespace in
15678 front of the next \"|\" separator, to keep the table aligned. The table will
15679 still be marked for re-alignment if the field did fill the entire column,
15680 because, in this case the deletion might narrow the column."
15681 (interactive "p")
15682 (if (and (org-table-p)
15683 (not (bolp))
15684 (not (= (char-after) ?|))
15685 (eq N 1))
15686 (if (looking-at ".*?|")
15687 (let ((pos (point))
15688 (noalign (looking-at "[^|\n\r]* |"))
15689 (c org-table-may-need-update))
15690 (replace-match (concat
15691 (substring (match-string 0) 1 -1)
15692 " |"))
15693 (goto-char pos)
15694 ;; noalign: if there were two spaces at the end, this field
15695 ;; does not determine the width of the column.
15696 (if noalign (setq org-table-may-need-update c)))
15697 (delete-char N))
15698 (delete-char N)
15699 (org-fix-tags-on-the-fly)))
15701 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15702 (put 'org-self-insert-command 'delete-selection t)
15703 (put 'orgtbl-self-insert-command 'delete-selection t)
15704 (put 'org-delete-char 'delete-selection 'supersede)
15705 (put 'org-delete-backward-char 'delete-selection 'supersede)
15706 (put 'org-yank 'delete-selection 'yank)
15708 ;; Make `flyspell-mode' delay after some commands
15709 (put 'org-self-insert-command 'flyspell-delayed t)
15710 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15711 (put 'org-delete-char 'flyspell-delayed t)
15712 (put 'org-delete-backward-char 'flyspell-delayed t)
15714 ;; Make pabbrev-mode expand after org-mode commands
15715 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15716 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15718 ;; How to do this: Measure non-white length of current string
15719 ;; If equal to column width, we should realign.
15721 (defun org-remap (map &rest commands)
15722 "In MAP, remap the functions given in COMMANDS.
15723 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15724 (let (new old)
15725 (while commands
15726 (setq old (pop commands) new (pop commands))
15727 (if (fboundp 'command-remapping)
15728 (org-defkey map (vector 'remap old) new)
15729 (substitute-key-definition old new map global-map)))))
15731 (when (eq org-enable-table-editor 'optimized)
15732 ;; If the user wants maximum table support, we need to hijack
15733 ;; some standard editing functions
15734 (org-remap org-mode-map
15735 'self-insert-command 'org-self-insert-command
15736 'delete-char 'org-delete-char
15737 'delete-backward-char 'org-delete-backward-char)
15738 (org-defkey org-mode-map "|" 'org-force-self-insert))
15740 (defvar org-ctrl-c-ctrl-c-hook nil
15741 "Hook for functions attaching themselves to `C-c C-c'.
15742 This can be used to add additional functionality to the C-c C-c key which
15743 executes context-dependent commands.
15744 Each function will be called with no arguments. The function must check
15745 if the context is appropriate for it to act. If yes, it should do its
15746 thing and then return a non-nil value. If the context is wrong,
15747 just do nothing and return nil.")
15749 (defvar org-tab-first-hook nil
15750 "Hook for functions to attach themselves to TAB.
15751 See `org-ctrl-c-ctrl-c-hook' for more information.
15752 This hook runs as the first action when TAB is pressed, even before
15753 `org-cycle' messes around with the `outline-regexp' to cater for
15754 inline tasks and plain list item folding.
15755 If any function in this hook returns t, not other actions like table
15756 field motion visibility cycling will be done.")
15758 (defvar org-tab-after-check-for-table-hook nil
15759 "Hook for functions to attach themselves to TAB.
15760 See `org-ctrl-c-ctrl-c-hook' for more information.
15761 This hook runs after it has been established that the cursor is not in a
15762 table, but before checking if the cursor is in a headline or if global cycling
15763 should be done.
15764 If any function in this hook returns t, not other actions like visibility
15765 cycling will be done.")
15767 (defvar org-tab-after-check-for-cycling-hook nil
15768 "Hook for functions to attach themselves to TAB.
15769 See `org-ctrl-c-ctrl-c-hook' for more information.
15770 This hook runs after it has been established that not table field motion and
15771 not visibility should be done because of current context. This is probably
15772 the place where a package like yasnippets can hook in.")
15774 (defvar org-tab-before-tab-emulation-hook nil
15775 "Hook for functions to attach themselves to TAB.
15776 See `org-ctrl-c-ctrl-c-hook' for more information.
15777 This hook runs after every other options for TAB have been exhausted, but
15778 before indentation and \t insertion takes place.")
15780 (defvar org-metaleft-hook nil
15781 "Hook for functions attaching themselves to `M-left'.
15782 See `org-ctrl-c-ctrl-c-hook' for more information.")
15783 (defvar org-metaright-hook nil
15784 "Hook for functions attaching themselves to `M-right'.
15785 See `org-ctrl-c-ctrl-c-hook' for more information.")
15786 (defvar org-metaup-hook nil
15787 "Hook for functions attaching themselves to `M-up'.
15788 See `org-ctrl-c-ctrl-c-hook' for more information.")
15789 (defvar org-metadown-hook nil
15790 "Hook for functions attaching themselves to `M-down'.
15791 See `org-ctrl-c-ctrl-c-hook' for more information.")
15792 (defvar org-shiftmetaleft-hook nil
15793 "Hook for functions attaching themselves to `M-S-left'.
15794 See `org-ctrl-c-ctrl-c-hook' for more information.")
15795 (defvar org-shiftmetaright-hook nil
15796 "Hook for functions attaching themselves to `M-S-right'.
15797 See `org-ctrl-c-ctrl-c-hook' for more information.")
15798 (defvar org-shiftmetaup-hook nil
15799 "Hook for functions attaching themselves to `M-S-up'.
15800 See `org-ctrl-c-ctrl-c-hook' for more information.")
15801 (defvar org-shiftmetadown-hook nil
15802 "Hook for functions attaching themselves to `M-S-down'.
15803 See `org-ctrl-c-ctrl-c-hook' for more information.")
15804 (defvar org-metareturn-hook nil
15805 "Hook for functions attaching themselves to `M-RET'.
15806 See `org-ctrl-c-ctrl-c-hook' for more information.")
15808 (defun org-modifier-cursor-error ()
15809 "Throw an error, a modified cursor command was applied in wrong context."
15810 (error "This command is active in special context like tables, headlines or items"))
15812 (defun org-shiftselect-error ()
15813 "Throw an error because Shift-Cursor command was applied in wrong context."
15814 (if (and (boundp 'shift-select-mode) shift-select-mode)
15815 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15816 (error "This command works only in special context like headlines or timestamps")))
15818 (defun org-call-for-shift-select (cmd)
15819 (let ((this-command-keys-shift-translated t))
15820 (call-interactively cmd)))
15822 (defun org-shifttab (&optional arg)
15823 "Global visibility cycling or move to previous table field.
15824 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15825 on context.
15826 See the individual commands for more information."
15827 (interactive "P")
15828 (cond
15829 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15830 ((integerp arg)
15831 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15832 (message "Content view to level: %d" arg)
15833 (org-content (prefix-numeric-value arg2))
15834 (setq org-cycle-global-status 'overview)))
15835 (t (call-interactively 'org-global-cycle))))
15837 (defun org-shiftmetaleft ()
15838 "Promote subtree or delete table column.
15839 Calls `org-promote-subtree', `org-outdent-item',
15840 or `org-table-delete-column', depending on context.
15841 See the individual commands for more information."
15842 (interactive)
15843 (cond
15844 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15845 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15846 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15847 ((org-at-item-p) (call-interactively 'org-outdent-item))
15848 (t (org-modifier-cursor-error))))
15850 (defun org-shiftmetaright ()
15851 "Demote subtree or insert table column.
15852 Calls `org-demote-subtree', `org-indent-item',
15853 or `org-table-insert-column', depending on context.
15854 See the individual commands for more information."
15855 (interactive)
15856 (cond
15857 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15858 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15859 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15860 ((org-at-item-p) (call-interactively 'org-indent-item))
15861 (t (org-modifier-cursor-error))))
15863 (defun org-shiftmetaup (&optional arg)
15864 "Move subtree up or kill table row.
15865 Calls `org-move-subtree-up' or `org-table-kill-row' or
15866 `org-move-item-up' depending on context. See the individual commands
15867 for more information."
15868 (interactive "P")
15869 (cond
15870 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15871 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15872 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15873 ((org-at-item-p) (call-interactively 'org-move-item-up))
15874 (t (org-modifier-cursor-error))))
15876 (defun org-shiftmetadown (&optional arg)
15877 "Move subtree down or insert table row.
15878 Calls `org-move-subtree-down' or `org-table-insert-row' or
15879 `org-move-item-down', depending on context. See the individual
15880 commands for more information."
15881 (interactive "P")
15882 (cond
15883 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15884 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15885 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15886 ((org-at-item-p) (call-interactively 'org-move-item-down))
15887 (t (org-modifier-cursor-error))))
15889 (defun org-metaleft (&optional arg)
15890 "Promote heading or move table column to left.
15891 Calls `org-do-promote' or `org-table-move-column', depending on context.
15892 With no specific context, calls the Emacs default `backward-word'.
15893 See the individual commands for more information."
15894 (interactive "P")
15895 (cond
15896 ((run-hook-with-args-until-success 'org-metaleft-hook))
15897 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15898 ((or (org-on-heading-p)
15899 (and (org-region-active-p)
15900 (save-excursion
15901 (goto-char (region-beginning))
15902 (org-on-heading-p))))
15903 (call-interactively 'org-do-promote))
15904 ((or (org-at-item-p)
15905 (and (org-region-active-p)
15906 (save-excursion
15907 (goto-char (region-beginning))
15908 (org-at-item-p))))
15909 (call-interactively 'org-outdent-item))
15910 (t (call-interactively 'backward-word))))
15912 (defun org-metaright (&optional arg)
15913 "Demote subtree or move table column to right.
15914 Calls `org-do-demote' or `org-table-move-column', depending on context.
15915 With no specific context, calls the Emacs default `forward-word'.
15916 See the individual commands for more information."
15917 (interactive "P")
15918 (cond
15919 ((run-hook-with-args-until-success 'org-metaright-hook))
15920 ((org-at-table-p) (call-interactively 'org-table-move-column))
15921 ((or (org-on-heading-p)
15922 (and (org-region-active-p)
15923 (save-excursion
15924 (goto-char (region-beginning))
15925 (org-on-heading-p))))
15926 (call-interactively 'org-do-demote))
15927 ((or (org-at-item-p)
15928 (and (org-region-active-p)
15929 (save-excursion
15930 (goto-char (region-beginning))
15931 (org-at-item-p))))
15932 (call-interactively 'org-indent-item))
15933 (t (call-interactively 'forward-word))))
15935 (defun org-metaup (&optional arg)
15936 "Move subtree up or move table row up.
15937 Calls `org-move-subtree-up' or `org-table-move-row' or
15938 `org-move-item-up', depending on context. See the individual commands
15939 for more information."
15940 (interactive "P")
15941 (cond
15942 ((run-hook-with-args-until-success 'org-metaup-hook))
15943 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15944 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15945 ((org-at-item-p) (call-interactively 'org-move-item-up))
15946 (t (transpose-lines 1) (beginning-of-line -1))))
15948 (defun org-metadown (&optional arg)
15949 "Move subtree down or move table row down.
15950 Calls `org-move-subtree-down' or `org-table-move-row' or
15951 `org-move-item-down', depending on context. See the individual
15952 commands for more information."
15953 (interactive "P")
15954 (cond
15955 ((run-hook-with-args-until-success 'org-metadown-hook))
15956 ((org-at-table-p) (call-interactively 'org-table-move-row))
15957 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15958 ((org-at-item-p) (call-interactively 'org-move-item-down))
15959 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15961 (defun org-shiftup (&optional arg)
15962 "Increase item in timestamp or increase priority of current headline.
15963 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15964 depending on context. See the individual commands for more information."
15965 (interactive "P")
15966 (cond
15967 ((and org-support-shift-select (org-region-active-p))
15968 (org-call-for-shift-select 'previous-line))
15969 ((org-at-timestamp-p t)
15970 (call-interactively (if org-edit-timestamp-down-means-later
15971 'org-timestamp-down 'org-timestamp-up)))
15972 ((and (not (eq org-support-shift-select 'always))
15973 org-enable-priority-commands
15974 (org-on-heading-p))
15975 (call-interactively 'org-priority-up))
15976 ((and (not org-support-shift-select) (org-at-item-p))
15977 (call-interactively 'org-previous-item))
15978 ((org-clocktable-try-shift 'up arg))
15979 (org-support-shift-select
15980 (org-call-for-shift-select 'previous-line))
15981 (t (org-shiftselect-error))))
15983 (defun org-shiftdown (&optional arg)
15984 "Decrease item in timestamp or decrease priority of current headline.
15985 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15986 depending on context. See the individual commands for more information."
15987 (interactive "P")
15988 (cond
15989 ((and org-support-shift-select (org-region-active-p))
15990 (org-call-for-shift-select 'next-line))
15991 ((org-at-timestamp-p t)
15992 (call-interactively (if org-edit-timestamp-down-means-later
15993 'org-timestamp-up 'org-timestamp-down)))
15994 ((and (not (eq org-support-shift-select 'always))
15995 org-enable-priority-commands
15996 (org-on-heading-p))
15997 (call-interactively 'org-priority-down))
15998 ((and (not org-support-shift-select) (org-at-item-p))
15999 (call-interactively 'org-next-item))
16000 ((org-clocktable-try-shift 'down arg))
16001 (org-support-shift-select
16002 (org-call-for-shift-select 'next-line))
16003 (t (org-shiftselect-error))))
16005 (defun org-shiftright (&optional arg)
16006 "Cycle the thing at point or in the current line, depending on context.
16007 Depending on context, this does one of the following:
16009 - switch a timestamp at point one day into the future
16010 - on a headline, switch to the next TODO keyword.
16011 - on an item, switch entire list to the next bullet type
16012 - on a property line, switch to the next allowed value
16013 - on a clocktable definition line, move time block into the future"
16014 (interactive "P")
16015 (cond
16016 ((and org-support-shift-select (org-region-active-p))
16017 (org-call-for-shift-select 'forward-char))
16018 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
16019 ((and (not (eq org-support-shift-select 'always))
16020 (org-on-heading-p))
16021 (let ((org-inhibit-logging
16022 (not org-treat-S-cursor-todo-selection-as-state-change))
16023 (org-inhibit-blocking
16024 (not org-treat-S-cursor-todo-selection-as-state-change)))
16025 (org-call-with-arg 'org-todo 'right)))
16026 ((or (and org-support-shift-select
16027 (not (eq org-support-shift-select 'always))
16028 (org-at-item-bullet-p))
16029 (and (not org-support-shift-select) (org-at-item-p)))
16030 (org-call-with-arg 'org-cycle-list-bullet nil))
16031 ((and (not (eq org-support-shift-select 'always))
16032 (org-at-property-p))
16033 (call-interactively 'org-property-next-allowed-value))
16034 ((org-clocktable-try-shift 'right arg))
16035 (org-support-shift-select
16036 (org-call-for-shift-select 'forward-char))
16037 (t (org-shiftselect-error))))
16039 (defun org-shiftleft (&optional arg)
16040 "Cycle the thing at point or in the current line, depending on context.
16041 Depending on context, this does one of the following:
16043 - switch a timestamp at point one day into the past
16044 - on a headline, switch to the previous TODO keyword.
16045 - on an item, switch entire list to the previous bullet type
16046 - on a property line, switch to the previous allowed value
16047 - on a clocktable definition line, move time block into the past"
16048 (interactive "P")
16049 (cond
16050 ((and org-support-shift-select (org-region-active-p))
16051 (org-call-for-shift-select 'backward-char))
16052 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
16053 ((and (not (eq org-support-shift-select 'always))
16054 (org-on-heading-p))
16055 (let ((org-inhibit-logging
16056 (not org-treat-S-cursor-todo-selection-as-state-change))
16057 (org-inhibit-blocking
16058 (not org-treat-S-cursor-todo-selection-as-state-change)))
16059 (org-call-with-arg 'org-todo 'left)))
16060 ((or (and org-support-shift-select
16061 (not (eq org-support-shift-select 'always))
16062 (org-at-item-bullet-p))
16063 (and (not org-support-shift-select) (org-at-item-p)))
16064 (org-call-with-arg 'org-cycle-list-bullet 'previous))
16065 ((and (not (eq org-support-shift-select 'always))
16066 (org-at-property-p))
16067 (call-interactively 'org-property-previous-allowed-value))
16068 ((org-clocktable-try-shift 'left arg))
16069 (org-support-shift-select
16070 (org-call-for-shift-select 'backward-char))
16071 (t (org-shiftselect-error))))
16073 (defun org-shiftcontrolright ()
16074 "Switch to next TODO set."
16075 (interactive)
16076 (cond
16077 ((and org-support-shift-select (org-region-active-p))
16078 (org-call-for-shift-select 'forward-word))
16079 ((and (not (eq org-support-shift-select 'always))
16080 (org-on-heading-p))
16081 (org-call-with-arg 'org-todo 'nextset))
16082 (org-support-shift-select
16083 (org-call-for-shift-select 'forward-word))
16084 (t (org-shiftselect-error))))
16086 (defun org-shiftcontrolleft ()
16087 "Switch to previous TODO set."
16088 (interactive)
16089 (cond
16090 ((and org-support-shift-select (org-region-active-p))
16091 (org-call-for-shift-select 'backward-word))
16092 ((and (not (eq org-support-shift-select 'always))
16093 (org-on-heading-p))
16094 (org-call-with-arg 'org-todo 'previousset))
16095 (org-support-shift-select
16096 (org-call-for-shift-select 'backward-word))
16097 (t (org-shiftselect-error))))
16099 (defun org-ctrl-c-ret ()
16100 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
16101 (interactive)
16102 (cond
16103 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
16104 (t (call-interactively 'org-insert-heading))))
16106 (defun org-copy-special ()
16107 "Copy region in table or copy current subtree.
16108 Calls `org-table-copy' or `org-copy-subtree', depending on context.
16109 See the individual commands for more information."
16110 (interactive)
16111 (call-interactively
16112 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
16114 (defun org-cut-special ()
16115 "Cut region in table or cut current subtree.
16116 Calls `org-table-copy' or `org-cut-subtree', depending on context.
16117 See the individual commands for more information."
16118 (interactive)
16119 (call-interactively
16120 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
16122 (defun org-paste-special (arg)
16123 "Paste rectangular region into table, or past subtree relative to level.
16124 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
16125 See the individual commands for more information."
16126 (interactive "P")
16127 (if (org-at-table-p)
16128 (org-table-paste-rectangle)
16129 (org-paste-subtree arg)))
16131 (defun org-edit-special ()
16132 "Call a special editor for the stuff at point.
16133 When at a table, call the formula editor with `org-table-edit-formulas'.
16134 When at the first line of an src example, call `org-edit-src-code'.
16135 When in an #+include line, visit the include file. Otherwise call
16136 `ffap' to visit the file at point."
16137 (interactive)
16138 (cond
16139 ((org-at-table.el-p)
16140 (org-edit-src-code))
16141 ((org-at-table-p)
16142 (call-interactively 'org-table-edit-formulas))
16143 ((save-excursion
16144 (beginning-of-line 1)
16145 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
16146 (find-file (org-trim (match-string 1))))
16147 ((org-edit-src-code))
16148 ((org-edit-fixed-width-region))
16149 (t (call-interactively 'ffap))))
16152 (defun org-ctrl-c-ctrl-c (&optional arg)
16153 "Set tags in headline, or update according to changed information at point.
16155 This command does many different things, depending on context:
16157 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
16158 this is what we do.
16160 - If the cursor is on a statistics cookie, update it.
16162 - If the cursor is in a headline, prompt for tags and insert them
16163 into the current line, aligned to `org-tags-column'. When called
16164 with prefix arg, realign all tags in the current buffer.
16166 - If the cursor is in one of the special #+KEYWORD lines, this
16167 triggers scanning the buffer for these lines and updating the
16168 information.
16170 - If the cursor is inside a table, realign the table. This command
16171 works even if the automatic table editor has been turned off.
16173 - If the cursor is on a #+TBLFM line, re-apply the formulas to
16174 the entire table.
16176 - If the cursor is at a footnote reference or definition, jump to
16177 the corresponding definition or references, respectively.
16179 - If the cursor is a the beginning of a dynamic block, update it.
16181 - If the current buffer is a remember buffer, close note and file
16182 it. A prefix argument of 1 files to the default location
16183 without further interaction. A prefix argument of 2 files to
16184 the currently clocking task.
16186 - If the cursor is on a <<<target>>>, update radio targets and corresponding
16187 links in this buffer.
16189 - If the cursor is on a numbered item in a plain list, renumber the
16190 ordered list.
16192 - If the cursor is on a checkbox, toggle it."
16193 (interactive "P")
16194 (let ((org-enable-table-editor t))
16195 (cond
16196 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
16197 org-occur-highlights
16198 org-latex-fragment-image-overlays)
16199 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
16200 (org-remove-occur-highlights)
16201 (org-remove-latex-fragment-image-overlays)
16202 (message "Temporary highlights/overlays removed from current buffer"))
16203 ((and (local-variable-p 'org-finish-function (current-buffer))
16204 (fboundp org-finish-function))
16205 (funcall org-finish-function))
16206 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
16207 ((or (looking-at (org-re org-property-start-re))
16208 (org-at-property-p))
16209 (call-interactively 'org-property-action))
16210 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
16211 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
16212 (or (org-on-heading-p) (org-at-item-p)))
16213 (call-interactively 'org-update-statistics-cookies))
16214 ((org-on-heading-p) (call-interactively 'org-set-tags))
16215 ((org-at-table.el-p)
16216 (message "Use C-c ' to edit table.el tables"))
16217 ((org-at-table-p)
16218 (org-table-maybe-eval-formula)
16219 (if arg
16220 (call-interactively 'org-table-recalculate)
16221 (org-table-maybe-recalculate-line))
16222 (call-interactively 'org-table-align))
16223 ((or (org-footnote-at-reference-p)
16224 (org-footnote-at-definition-p))
16225 (call-interactively 'org-footnote-action))
16226 ((org-at-item-checkbox-p)
16227 (call-interactively 'org-toggle-checkbox))
16228 ((org-at-item-p)
16229 (if arg
16230 (call-interactively 'org-toggle-checkbox)
16231 (call-interactively 'org-maybe-renumber-ordered-list)))
16232 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
16233 ;; Dynamic block
16234 (beginning-of-line 1)
16235 (save-excursion (org-update-dblock)))
16236 ((save-excursion
16237 (beginning-of-line 1)
16238 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
16239 (cond
16240 ((equal (match-string 1) "TBLFM")
16241 ;; Recalculate the table before this line
16242 (save-excursion
16243 (beginning-of-line 1)
16244 (skip-chars-backward " \r\n\t")
16245 (if (org-at-table-p)
16246 (org-call-with-arg 'org-table-recalculate (or arg t)))))
16248 (let ((org-inhibit-startup-visibility-stuff t)
16249 (org-startup-align-all-tables nil))
16250 (org-save-outline-visibility 'use-markers (org-mode-restart)))
16251 (message "Local setup has been refreshed"))))
16252 ((org-clock-update-time-maybe))
16253 (t (error "C-c C-c can do nothing useful at this location")))))
16255 (defun org-mode-restart ()
16256 "Restart Org-mode, to scan again for special lines.
16257 Also updates the keyword regular expressions."
16258 (interactive)
16259 (org-mode)
16260 (message "Org-mode restarted"))
16262 (defun org-kill-note-or-show-branches ()
16263 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
16264 (interactive)
16265 (if (not org-finish-function)
16266 (call-interactively 'show-branches)
16267 (let ((org-note-abort t))
16268 (funcall org-finish-function))))
16270 (defun org-return (&optional indent)
16271 "Goto next table row or insert a newline.
16272 Calls `org-table-next-row' or `newline', depending on context.
16273 See the individual commands for more information."
16274 (interactive)
16275 (cond
16276 ((bobp) (if indent (newline-and-indent) (newline)))
16277 ((org-at-table-p)
16278 (org-table-justify-field-maybe)
16279 (call-interactively 'org-table-next-row))
16280 ((and org-return-follows-link
16281 (eq (get-text-property (point) 'face) 'org-link))
16282 (call-interactively 'org-open-at-point))
16283 ((and (org-at-heading-p)
16284 (looking-at
16285 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
16286 (org-show-entry)
16287 (end-of-line 1)
16288 (newline))
16289 (t (if indent (newline-and-indent) (newline)))))
16291 (defun org-return-indent ()
16292 "Goto next table row or insert a newline and indent.
16293 Calls `org-table-next-row' or `newline-and-indent', depending on
16294 context. See the individual commands for more information."
16295 (interactive)
16296 (org-return t))
16298 (defun org-ctrl-c-star ()
16299 "Compute table, or change heading status of lines.
16300 Calls `org-table-recalculate' or `org-toggle-heading',
16301 depending on context."
16302 (interactive)
16303 (cond
16304 ((org-at-table-p)
16305 (call-interactively 'org-table-recalculate))
16307 ;; Convert all lines in region to list items
16308 (call-interactively 'org-toggle-heading))))
16310 (defun org-ctrl-c-minus ()
16311 "Insert separator line in table or modify bullet status of line.
16312 Also turns a plain line or a region of lines into list items.
16313 Calls `org-table-insert-hline', `org-toggle-item', or
16314 `org-cycle-list-bullet', depending on context."
16315 (interactive)
16316 (cond
16317 ((org-at-table-p)
16318 (call-interactively 'org-table-insert-hline))
16319 ((org-region-active-p)
16320 (call-interactively 'org-toggle-item))
16321 ((org-in-item-p)
16322 (call-interactively 'org-cycle-list-bullet))
16324 (call-interactively 'org-toggle-item))))
16326 (defun org-toggle-item ()
16327 "Convert headings or normal lines to items, items to normal lines.
16328 If there is no active region, only the current line is considered.
16330 If the first line in the region is a headline, convert all headlines to items.
16332 If the first line in the region is an item, convert all items to normal lines.
16334 If the first line is normal text, add an item bullet to each line."
16335 (interactive)
16336 (let (l2 l beg end)
16337 (if (org-region-active-p)
16338 (setq beg (region-beginning) end (region-end))
16339 (setq beg (point-at-bol)
16340 end (min (1+ (point-at-eol)) (point-max))))
16341 (save-excursion
16342 (goto-char end)
16343 (setq l2 (org-current-line))
16344 (goto-char beg)
16345 (beginning-of-line 1)
16346 (setq l (1- (org-current-line)))
16347 (if (org-at-item-p)
16348 ;; We already have items, de-itemize
16349 (while (< (setq l (1+ l)) l2)
16350 (when (org-at-item-p)
16351 (goto-char (match-beginning 2))
16352 (delete-region (match-beginning 2) (match-end 2))
16353 (and (looking-at "[ \t]+") (replace-match "")))
16354 (beginning-of-line 2))
16355 (if (org-on-heading-p)
16356 ;; Headings, convert to items
16357 (while (< (setq l (1+ l)) l2)
16358 (if (looking-at org-outline-regexp)
16359 (replace-match "- " t t))
16360 (beginning-of-line 2))
16361 ;; normal lines, turn them into items
16362 (while (< (setq l (1+ l)) l2)
16363 (unless (org-at-item-p)
16364 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16365 (replace-match "\\1- \\2")))
16366 (beginning-of-line 2)))))))
16368 (defun org-toggle-heading (&optional nstars)
16369 "Convert headings to normal text, or items or text to headings.
16370 If there is no active region, only the current line is considered.
16372 If the first line is a heading, remove the stars from all headlines
16373 in the region.
16375 If the first line is a plain list item, turn all plain list items
16376 into headings.
16378 If the first line is a normal line, turn each and every line in the
16379 region into a heading.
16381 When converting a line into a heading, the number of stars is chosen
16382 such that the lines become children of the current entry. However,
16383 when a prefix argument is given, its value determines the number of
16384 stars to add."
16385 (interactive "P")
16386 (let (l2 l itemp beg end)
16387 (if (org-region-active-p)
16388 (setq beg (region-beginning) end (region-end))
16389 (setq beg (point-at-bol)
16390 end (min (1+ (point-at-eol)) (point-max))))
16391 (save-excursion
16392 (goto-char end)
16393 (setq l2 (org-current-line))
16394 (goto-char beg)
16395 (beginning-of-line 1)
16396 (setq l (1- (org-current-line)))
16397 (if (org-on-heading-p)
16398 ;; We already have headlines, de-star them
16399 (while (< (setq l (1+ l)) l2)
16400 (when (org-on-heading-p t)
16401 (and (looking-at outline-regexp) (replace-match "")))
16402 (beginning-of-line 2))
16403 (setq itemp (org-at-item-p))
16404 (let* ((stars
16405 (if nstars
16406 (make-string (prefix-numeric-value current-prefix-arg)
16408 (save-excursion
16409 (if (re-search-backward org-complex-heading-regexp nil t)
16410 (match-string 1) ""))))
16411 (add-stars (cond (nstars "")
16412 ((equal stars "") "*")
16413 (org-odd-levels-only "**")
16414 (t "*")))
16415 (rpl (concat stars add-stars " ")))
16416 (while (< (setq l (1+ l)) l2)
16417 (if itemp
16418 (and (org-at-item-p) (replace-match rpl t t))
16419 (unless (org-on-heading-p)
16420 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16421 (replace-match (concat rpl (match-string 2))))))
16422 (beginning-of-line 2)))))))
16424 (defun org-meta-return (&optional arg)
16425 "Insert a new heading or wrap a region in a table.
16426 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16427 See the individual commands for more information."
16428 (interactive "P")
16429 (cond
16430 ((run-hook-with-args-until-success 'org-metareturn-hook))
16431 ((org-at-table-p)
16432 (call-interactively 'org-table-wrap-region))
16433 (t (call-interactively 'org-insert-heading))))
16435 ;;; Menu entries
16437 ;; Define the Org-mode menus
16438 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16439 '("Tbl"
16440 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
16441 ["Next Field" org-cycle (org-at-table-p)]
16442 ["Previous Field" org-shifttab (org-at-table-p)]
16443 ["Next Row" org-return (org-at-table-p)]
16444 "--"
16445 ["Blank Field" org-table-blank-field (org-at-table-p)]
16446 ["Edit Field" org-table-edit-field (org-at-table-p)]
16447 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16448 "--"
16449 ("Column"
16450 ["Move Column Left" org-metaleft (org-at-table-p)]
16451 ["Move Column Right" org-metaright (org-at-table-p)]
16452 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16453 ["Insert Column" org-shiftmetaright (org-at-table-p)])
16454 ("Row"
16455 ["Move Row Up" org-metaup (org-at-table-p)]
16456 ["Move Row Down" org-metadown (org-at-table-p)]
16457 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16458 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16459 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16460 "--"
16461 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
16462 ("Rectangle"
16463 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16464 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16465 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16466 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16467 "--"
16468 ("Calculate"
16469 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16470 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16471 ["Edit Formulas" org-edit-special (org-at-table-p)]
16472 "--"
16473 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16474 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16475 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
16476 "--"
16477 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16478 "--"
16479 ["Sum Column/Rectangle" org-table-sum
16480 (or (org-at-table-p) (org-region-active-p))]
16481 ["Which Column?" org-table-current-column (org-at-table-p)])
16482 ["Debug Formulas"
16483 org-table-toggle-formula-debugger
16484 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
16485 ["Show Col/Row Numbers"
16486 org-table-toggle-coordinate-overlays
16487 :style toggle
16488 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
16489 "--"
16490 ["Create" org-table-create (and (not (org-at-table-p))
16491 org-enable-table-editor)]
16492 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16493 ["Import from File" org-table-import (not (org-at-table-p))]
16494 ["Export to File" org-table-export (org-at-table-p)]
16495 "--"
16496 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16498 (easy-menu-define org-org-menu org-mode-map "Org menu"
16499 '("Org"
16500 ("Show/Hide"
16501 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
16502 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
16503 ["Sparse Tree..." org-sparse-tree t]
16504 ["Reveal Context" org-reveal t]
16505 ["Show All" show-all t]
16506 "--"
16507 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
16508 "--"
16509 ["New Heading" org-insert-heading t]
16510 ("Navigate Headings"
16511 ["Up" outline-up-heading t]
16512 ["Next" outline-next-visible-heading t]
16513 ["Previous" outline-previous-visible-heading t]
16514 ["Next Same Level" outline-forward-same-level t]
16515 ["Previous Same Level" outline-backward-same-level t]
16516 "--"
16517 ["Jump" org-goto t])
16518 ("Edit Structure"
16519 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16520 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16521 "--"
16522 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16523 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16524 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16525 "--"
16526 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
16527 "--"
16528 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16529 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16530 ["Demote Heading" org-metaright (not (org-at-table-p))]
16531 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16532 "--"
16533 ["Sort Region/Children" org-sort (not (org-at-table-p))]
16534 "--"
16535 ["Convert to odd levels" org-convert-to-odd-levels t]
16536 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16537 ("Editing"
16538 ["Emphasis..." org-emphasize t]
16539 ["Edit Source Example" org-edit-special t]
16540 "--"
16541 ["Footnote new/jump" org-footnote-action t]
16542 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
16543 ("Archive"
16544 ["Archive (default method)" org-archive-subtree-default t]
16545 "--"
16546 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
16547 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16548 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
16550 "--"
16551 ("Hyperlinks"
16552 ["Store Link (Global)" org-store-link t]
16553 ["Find existing link to here" org-occur-link-in-agenda-files t]
16554 ["Insert Link" org-insert-link t]
16555 ["Follow Link" org-open-at-point t]
16556 "--"
16557 ["Next link" org-next-link t]
16558 ["Previous link" org-previous-link t]
16559 "--"
16560 ["Descriptive Links"
16561 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16562 :style radio
16563 :selected (member '(org-link) buffer-invisibility-spec)]
16564 ["Literal Links"
16565 (progn
16566 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16567 :style radio
16568 :selected (not (member '(org-link) buffer-invisibility-spec))])
16569 "--"
16570 ("TODO Lists"
16571 ["TODO/DONE/-" org-todo t]
16572 ("Select keyword"
16573 ["Next keyword" org-shiftright (org-on-heading-p)]
16574 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16575 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
16576 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
16577 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
16578 ["Show TODO Tree" org-show-todo-tree t]
16579 ["Global TODO list" org-todo-list t]
16580 "--"
16581 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
16582 :selected org-enforce-todo-dependencies :style toggle :active t]
16583 "Settings for tree at point"
16584 ["Do Children sequentially" org-toggle-ordered-property :style radio
16585 :selected (ignore-errors (org-entry-get nil "ORDERED"))
16586 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16587 ["Do Children parallel" org-toggle-ordered-property :style radio
16588 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
16589 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16590 "--"
16591 ["Set Priority" org-priority t]
16592 ["Priority Up" org-shiftup t]
16593 ["Priority Down" org-shiftdown t]
16594 "--"
16595 ["Get news from all feeds" org-feed-update-all t]
16596 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16597 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16598 ("TAGS and Properties"
16599 ["Set Tags" org-set-tags-command t]
16600 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16601 "--"
16602 ["Set property" org-set-property t]
16603 ["Column view of properties" org-columns t]
16604 ["Insert Column View DBlock" org-insert-columns-dblock t])
16605 ("Dates and Scheduling"
16606 ["Timestamp" org-time-stamp t]
16607 ["Timestamp (inactive)" org-time-stamp-inactive t]
16608 ("Change Date"
16609 ["1 Day Later" org-shiftright t]
16610 ["1 Day Earlier" org-shiftleft t]
16611 ["1 ... Later" org-shiftup t]
16612 ["1 ... Earlier" org-shiftdown t])
16613 ["Compute Time Range" org-evaluate-time-range t]
16614 ["Schedule Item" org-schedule t]
16615 ["Deadline" org-deadline t]
16616 "--"
16617 ["Custom time format" org-toggle-time-stamp-overlays
16618 :style radio :selected org-display-custom-times]
16619 "--"
16620 ["Goto Calendar" org-goto-calendar t]
16621 ["Date from Calendar" org-date-from-calendar t]
16622 "--"
16623 ["Start/Restart Timer" org-timer-start t]
16624 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16625 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16626 ["Insert Timer String" org-timer t]
16627 ["Insert Timer Item" org-timer-item t])
16628 ("Logging work"
16629 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16630 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16631 ["Clock out" org-clock-out t]
16632 ["Clock cancel" org-clock-cancel t]
16633 "--"
16634 ["Mark as default task" org-clock-mark-default-task t]
16635 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16636 ["Goto running clock" org-clock-goto t]
16637 "--"
16638 ["Display times" org-clock-display t]
16639 ["Create clock table" org-clock-report t]
16640 "--"
16641 ["Record DONE time"
16642 (progn (setq org-log-done (not org-log-done))
16643 (message "Switching to %s will %s record a timestamp"
16644 (car org-done-keywords)
16645 (if org-log-done "automatically" "not")))
16646 :style toggle :selected org-log-done])
16647 "--"
16648 ["Agenda Command..." org-agenda t]
16649 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16650 ("File List for Agenda")
16651 ("Special views current file"
16652 ["TODO Tree" org-show-todo-tree t]
16653 ["Check Deadlines" org-check-deadlines t]
16654 ["Timeline" org-timeline t]
16655 ["Tags/Property tree" org-match-sparse-tree t])
16656 "--"
16657 ["Export/Publish..." org-export t]
16658 ("LaTeX"
16659 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16660 :selected org-cdlatex-mode]
16661 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16662 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16663 ["Modify math symbol" org-cdlatex-math-modify
16664 (org-inside-LaTeX-fragment-p)]
16665 ["Insert citation" org-reftex-citation t]
16666 "--"
16667 ["Export LaTeX fragments as images"
16668 (if (featurep 'org-exp)
16669 (setq org-export-with-LaTeX-fragments
16670 (not org-export-with-LaTeX-fragments))
16671 (require 'org-exp))
16672 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16673 org-export-with-LaTeX-fragments)]
16674 "--"
16675 ["Template for BEAMER" org-beamer-settings-template t])
16676 "--"
16677 ("MobileOrg"
16678 ["Push Files and Views" org-mobile-push t]
16679 ["Get Captured and Flagged" org-mobile-pull t]
16680 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16681 "--"
16682 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16683 "--"
16684 ("Documentation"
16685 ["Show Version" org-version t]
16686 ["Info Documentation" org-info t])
16687 ("Customize"
16688 ["Browse Org Group" org-customize t]
16689 "--"
16690 ["Expand This Menu" org-create-customize-menu
16691 (fboundp 'customize-menu-create)])
16692 ["Send bug report" org-submit-bug-report t]
16693 "--"
16694 ("Refresh/Reload"
16695 ["Refresh setup current buffer" org-mode-restart t]
16696 ["Reload Org (after update)" org-reload t]
16697 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16700 (defun org-info (&optional node)
16701 "Read documentation for Org-mode in the info system.
16702 With optional NODE, go directly to that node."
16703 (interactive)
16704 (info (format "(org)%s" (or node ""))))
16706 ;;;###autoload
16707 (defun org-submit-bug-report ()
16708 "Submit a bug report on Org-mode via mail.
16710 Don't hesitate to report any problems or inaccurate documentation.
16712 If you don't have setup sending mail from (X)Emacs, please copy the
16713 output buffer into your mail program, as it gives us important
16714 information about your Org-mode version and configuration."
16715 (interactive)
16716 (require 'reporter)
16717 (org-load-modules-maybe)
16718 (org-require-autoloaded-modules)
16719 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16720 (reporter-submit-bug-report
16721 "emacs-orgmode@gnu.org"
16722 (org-version)
16723 (let (list)
16724 (save-window-excursion
16725 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16726 (delete-other-windows)
16727 (erase-buffer)
16728 (insert "You are about to submit a bug report to the Org-mode mailing list.
16730 We would like to add your full Org-mode and Outline configuration to the
16731 bug report. This greatly simplifies the work of the maintainer and
16732 other experts on the mailing list.
16734 HOWEVER, some variables you have customized may contain private
16735 information. The names of customers, colleagues, or friends, might
16736 appear in the form of file names, tags, todo states, or search strings.
16737 If you answer yes to the prompt, you might want to check and remove
16738 such private information before sending the email.")
16739 (add-text-properties (point-min) (point-max) '(face org-warning))
16740 (when (yes-or-no-p "Include your Org-mode configuration ")
16741 (mapatoms
16742 (lambda (v)
16743 (and (boundp v)
16744 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16745 (or (and (symbol-value v)
16746 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16747 (and
16748 (get v 'custom-type) (get v 'standard-value)
16749 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16750 (push v list)))))
16751 (kill-buffer (get-buffer "*Warn about privacy*"))
16752 list))
16753 nil nil
16754 "Remember to cover the basics, that is, what you expected to happen and
16755 what in fact did happen. You don't know how to make a good report? See
16757 http://orgmode.org/manual/Feedback.html#Feedback
16759 Your bug report will be posted to the Org-mode mailing list.
16760 ------------------------------------------------------------------------")
16761 (save-excursion
16762 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16763 (replace-match "\\1Bug: \\3 [\\2]")))))
16766 (defun org-install-agenda-files-menu ()
16767 (let ((bl (buffer-list)))
16768 (save-excursion
16769 (while bl
16770 (set-buffer (pop bl))
16771 (if (org-mode-p) (setq bl nil)))
16772 (when (org-mode-p)
16773 (easy-menu-change
16774 '("Org") "File List for Agenda"
16775 (append
16776 (list
16777 ["Edit File List" (org-edit-agenda-file-list) t]
16778 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16779 ["Remove Current File from List" org-remove-file t]
16780 ["Cycle through agenda files" org-cycle-agenda-files t]
16781 ["Occur in all agenda files" org-occur-in-agenda-files t]
16782 "--")
16783 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16785 ;;;; Documentation
16787 ;;;###autoload
16788 (defun org-require-autoloaded-modules ()
16789 (interactive)
16790 (mapc 'require
16791 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16792 org-docbook org-exp org-html org-icalendar
16793 org-id org-latex
16794 org-publish org-remember org-table
16795 org-timer org-xoxo)))
16797 ;;;###autoload
16798 (defun org-reload (&optional uncompiled)
16799 "Reload all org lisp files.
16800 With prefix arg UNCOMPILED, load the uncompiled versions."
16801 (interactive "P")
16802 (require 'find-func)
16803 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16804 (dir-org (file-name-directory (org-find-library-name "org")))
16805 (dir-org-contrib (ignore-errors
16806 (file-name-directory
16807 (org-find-library-name "org-contribdir"))))
16808 (files
16809 (append (directory-files dir-org t file-re)
16810 (and dir-org-contrib
16811 (directory-files dir-org-contrib t file-re))))
16812 (remove-re (concat (if (featurep 'xemacs)
16813 "org-colview" "org-colview-xemacs")
16814 "\\'")))
16815 (setq files (mapcar 'file-name-sans-extension files))
16816 (setq files (mapcar
16817 (lambda (x) (if (string-match remove-re x) nil x))
16818 files))
16819 (setq files (delq nil files))
16820 (mapc
16821 (lambda (f)
16822 (when (featurep (intern (file-name-nondirectory f)))
16823 (if (and (not uncompiled)
16824 (file-exists-p (concat f ".elc")))
16825 (load (concat f ".elc") nil nil t)
16826 (load (concat f ".el") nil nil t))))
16827 files))
16828 (org-version))
16830 ;;;###autoload
16831 (defun org-customize ()
16832 "Call the customize function with org as argument."
16833 (interactive)
16834 (org-load-modules-maybe)
16835 (org-require-autoloaded-modules)
16836 (customize-browse 'org))
16838 (defun org-create-customize-menu ()
16839 "Create a full customization menu for Org-mode, insert it into the menu."
16840 (interactive)
16841 (org-load-modules-maybe)
16842 (org-require-autoloaded-modules)
16843 (if (fboundp 'customize-menu-create)
16844 (progn
16845 (easy-menu-change
16846 '("Org") "Customize"
16847 `(["Browse Org group" org-customize t]
16848 "--"
16849 ,(customize-menu-create 'org)
16850 ["Set" Custom-set t]
16851 ["Save" Custom-save t]
16852 ["Reset to Current" Custom-reset-current t]
16853 ["Reset to Saved" Custom-reset-saved t]
16854 ["Reset to Standard Settings" Custom-reset-standard t]))
16855 (message "\"Org\"-menu now contains full customization menu"))
16856 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16858 ;;;; Miscellaneous stuff
16860 ;;; Generally useful functions
16862 (defun org-get-at-bol (property)
16863 "Get text property PROPERTY at beginning of line."
16864 (get-text-property (point-at-bol) property))
16866 (defun org-find-text-property-in-string (prop s)
16867 "Return the first non-nil value of property PROP in string S."
16868 (or (get-text-property 0 prop s)
16869 (get-text-property (or (next-single-property-change 0 prop s) 0)
16870 prop s)))
16872 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16873 "Display the given MESSAGE as a warning."
16874 (if (fboundp 'display-warning)
16875 (display-warning 'org message
16876 (if (featurep 'xemacs)
16877 'warning
16878 :warning))
16879 (let ((buf (get-buffer-create "*Org warnings*")))
16880 (with-current-buffer buf
16881 (goto-char (point-max))
16882 (insert "Warning (Org): " message)
16883 (unless (bolp)
16884 (newline)))
16885 (display-buffer buf)
16886 (sit-for 0))))
16888 (defun org-in-commented-line ()
16889 "Is point in a line starting with `#'?"
16890 (equal (char-after (point-at-bol)) ?#))
16892 (defun org-in-verbatim-emphasis ()
16893 (save-match-data
16894 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16896 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16897 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16898 (if (and marker (marker-buffer marker)
16899 (buffer-live-p (marker-buffer marker)))
16900 (progn
16901 (switch-to-buffer (marker-buffer marker))
16902 (if (or (> marker (point-max)) (< marker (point-min)))
16903 (widen))
16904 (goto-char marker)
16905 (org-show-context 'org-goto))
16906 (if bookmark
16907 (bookmark-jump bookmark)
16908 (error "Cannot find location"))))
16910 (defun org-quote-csv-field (s)
16911 "Quote field for inclusion in CSV material."
16912 (if (string-match "[\",]" s)
16913 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16916 (defun org-plist-delete (plist property)
16917 "Delete PROPERTY from PLIST.
16918 This is in contrast to merely setting it to 0."
16919 (let (p)
16920 (while plist
16921 (if (not (eq property (car plist)))
16922 (setq p (plist-put p (car plist) (nth 1 plist))))
16923 (setq plist (cddr plist)))
16926 (defun org-force-self-insert (N)
16927 "Needed to enforce self-insert under remapping."
16928 (interactive "p")
16929 (self-insert-command N))
16931 (defun org-string-width (s)
16932 "Compute width of string, ignoring invisible characters.
16933 This ignores character with invisibility property `org-link', and also
16934 characters with property `org-cwidth', because these will become invisible
16935 upon the next fontification round."
16936 (let (b l)
16937 (when (or (eq t buffer-invisibility-spec)
16938 (assq 'org-link buffer-invisibility-spec))
16939 (while (setq b (text-property-any 0 (length s)
16940 'invisible 'org-link s))
16941 (setq s (concat (substring s 0 b)
16942 (substring s (or (next-single-property-change
16943 b 'invisible s) (length s)))))))
16944 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16945 (setq s (concat (substring s 0 b)
16946 (substring s (or (next-single-property-change
16947 b 'org-cwidth s) (length s))))))
16948 (setq l (string-width s) b -1)
16949 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16950 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16953 (defun org-get-indentation (&optional line)
16954 "Get the indentation of the current line, interpreting tabs.
16955 When LINE is given, assume it represents a line and compute its indentation."
16956 (if line
16957 (if (string-match "^ *" (org-remove-tabs line))
16958 (match-end 0))
16959 (save-excursion
16960 (beginning-of-line 1)
16961 (skip-chars-forward " \t")
16962 (current-column))))
16964 (defun org-remove-tabs (s &optional width)
16965 "Replace tabulators in S with spaces.
16966 Assumes that s is a single line, starting in column 0."
16967 (setq width (or width tab-width))
16968 (while (string-match "\t" s)
16969 (setq s (replace-match
16970 (make-string
16971 (- (* width (/ (+ (match-beginning 0) width) width))
16972 (match-beginning 0)) ?\ )
16973 t t s)))
16976 (defun org-fix-indentation (line ind)
16977 "Fix indentation in LINE.
16978 IND is a cons cell with target and minimum indentation.
16979 If the current indentation in LINE is smaller than the minimum,
16980 leave it alone. If it is larger than ind, set it to the target."
16981 (let* ((l (org-remove-tabs line))
16982 (i (org-get-indentation l))
16983 (i1 (car ind)) (i2 (cdr ind)))
16984 (if (>= i i2) (setq l (substring line i2)))
16985 (if (> i1 0)
16986 (concat (make-string i1 ?\ ) l)
16987 l)))
16989 (defun org-remove-indentation (code &optional n)
16990 "Remove the maximum common indentation from the lines in CODE.
16991 N may optionally be the number of spaces to remove."
16992 (with-temp-buffer
16993 (insert code)
16994 (org-do-remove-indentation n)
16995 (buffer-string)))
16997 (defun org-do-remove-indentation (&optional n)
16998 "Remove the maximum common indentation from the buffer."
16999 (untabify (point-min) (point-max))
17000 (let ((min 10000) re)
17001 (if n
17002 (setq min n)
17003 (goto-char (point-min))
17004 (while (re-search-forward "^ *[^ \n]" nil t)
17005 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
17006 (unless (or (= min 0) (= min 10000))
17007 (setq re (format "^ \\{%d\\}" min))
17008 (goto-char (point-min))
17009 (while (re-search-forward re nil t)
17010 (replace-match "")
17011 (end-of-line 1))
17012 min)))
17014 (defun org-fill-template (template alist)
17015 "Find each %key of ALIST in TEMPLATE and replace it."
17016 (let ((case-fold-search nil)
17017 entry key value)
17018 (setq alist (sort (copy-sequence alist)
17019 (lambda (a b) (< (length (car a)) (length (car b))))))
17020 (while (setq entry (pop alist))
17021 (setq template
17022 (replace-regexp-in-string
17023 (concat "%" (regexp-quote (car entry)))
17024 (cdr entry) template t t)))
17025 template))
17027 (defun org-base-buffer (buffer)
17028 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
17029 (if (not buffer)
17030 buffer
17031 (or (buffer-base-buffer buffer)
17032 buffer)))
17034 (defun org-trim (s)
17035 "Remove whitespace at beginning and end of string."
17036 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
17037 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
17040 (defun org-wrap (string &optional width lines)
17041 "Wrap string to either a number of lines, or a width in characters.
17042 If WIDTH is non-nil, the string is wrapped to that width, however many lines
17043 that costs. If there is a word longer than WIDTH, the text is actually
17044 wrapped to the length of that word.
17045 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
17046 many lines, whatever width that takes.
17047 The return value is a list of lines, without newlines at the end."
17048 (let* ((words (org-split-string string "[ \t\n]+"))
17049 (maxword (apply 'max (mapcar 'org-string-width words)))
17050 w ll)
17051 (cond (width
17052 (org-do-wrap words (max maxword width)))
17053 (lines
17054 (setq w maxword)
17055 (setq ll (org-do-wrap words maxword))
17056 (if (<= (length ll) lines)
17058 (setq ll words)
17059 (while (> (length ll) lines)
17060 (setq w (1+ w))
17061 (setq ll (org-do-wrap words w)))
17062 ll))
17063 (t (error "Cannot wrap this")))))
17065 (defun org-do-wrap (words width)
17066 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
17067 (let (lines line)
17068 (while words
17069 (setq line (pop words))
17070 (while (and words (< (+ (length line) (length (car words))) width))
17071 (setq line (concat line " " (pop words))))
17072 (setq lines (push line lines)))
17073 (nreverse lines)))
17075 (defun org-split-string (string &optional separators)
17076 "Splits STRING into substrings at SEPARATORS.
17077 No empty strings are returned if there are matches at the beginning
17078 and end of string."
17079 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
17080 (start 0)
17081 notfirst
17082 (list nil))
17083 (while (and (string-match rexp string
17084 (if (and notfirst
17085 (= start (match-beginning 0))
17086 (< start (length string)))
17087 (1+ start) start))
17088 (< (match-beginning 0) (length string)))
17089 (setq notfirst t)
17090 (or (eq (match-beginning 0) 0)
17091 (and (eq (match-beginning 0) (match-end 0))
17092 (eq (match-beginning 0) start))
17093 (setq list
17094 (cons (substring string start (match-beginning 0))
17095 list)))
17096 (setq start (match-end 0)))
17097 (or (eq start (length string))
17098 (setq list
17099 (cons (substring string start)
17100 list)))
17101 (nreverse list)))
17103 (defun org-quote-vert (s)
17104 "Replace \"|\" with \"\\vert\"."
17105 (while (string-match "|" s)
17106 (setq s (replace-match "\\vert" t t s)))
17109 (defun org-uuidgen-p (s)
17110 "Is S an ID created by UUIDGEN?"
17111 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
17113 (defun org-context ()
17114 "Return a list of contexts of the current cursor position.
17115 If several contexts apply, all are returned.
17116 Each context entry is a list with a symbol naming the context, and
17117 two positions indicating start and end of the context. Possible
17118 contexts are:
17120 :headline anywhere in a headline
17121 :headline-stars on the leading stars in a headline
17122 :todo-keyword on a TODO keyword (including DONE) in a headline
17123 :tags on the TAGS in a headline
17124 :priority on the priority cookie in a headline
17125 :item on the first line of a plain list item
17126 :item-bullet on the bullet/number of a plain list item
17127 :checkbox on the checkbox in a plain list item
17128 :table in an org-mode table
17129 :table-special on a special filed in a table
17130 :table-table in a table.el table
17131 :link on a hyperlink
17132 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
17133 :target on a <<target>>
17134 :radio-target on a <<<radio-target>>>
17135 :latex-fragment on a LaTeX fragment
17136 :latex-preview on a LaTeX fragment with overlayed preview image
17138 This function expects the position to be visible because it uses font-lock
17139 faces as a help to recognize the following contexts: :table-special, :link,
17140 and :keyword."
17141 (let* ((f (get-text-property (point) 'face))
17142 (faces (if (listp f) f (list f)))
17143 (p (point)) clist o)
17144 ;; First the large context
17145 (cond
17146 ((org-on-heading-p t)
17147 (push (list :headline (point-at-bol) (point-at-eol)) clist)
17148 (when (progn
17149 (beginning-of-line 1)
17150 (looking-at org-todo-line-tags-regexp))
17151 (push (org-point-in-group p 1 :headline-stars) clist)
17152 (push (org-point-in-group p 2 :todo-keyword) clist)
17153 (push (org-point-in-group p 4 :tags) clist))
17154 (goto-char p)
17155 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
17156 (if (looking-at "\\[#[A-Z0-9]\\]")
17157 (push (org-point-in-group p 0 :priority) clist)))
17159 ((org-at-item-p)
17160 (push (org-point-in-group p 2 :item-bullet) clist)
17161 (push (list :item (point-at-bol)
17162 (save-excursion (org-end-of-item) (point)))
17163 clist)
17164 (and (org-at-item-checkbox-p)
17165 (push (org-point-in-group p 0 :checkbox) clist)))
17167 ((org-at-table-p)
17168 (push (list :table (org-table-begin) (org-table-end)) clist)
17169 (if (memq 'org-formula faces)
17170 (push (list :table-special
17171 (previous-single-property-change p 'face)
17172 (next-single-property-change p 'face)) clist)))
17173 ((org-at-table-p 'any)
17174 (push (list :table-table) clist)))
17175 (goto-char p)
17177 ;; Now the small context
17178 (cond
17179 ((org-at-timestamp-p)
17180 (push (org-point-in-group p 0 :timestamp) clist))
17181 ((memq 'org-link faces)
17182 (push (list :link
17183 (previous-single-property-change p 'face)
17184 (next-single-property-change p 'face)) clist))
17185 ((memq 'org-special-keyword faces)
17186 (push (list :keyword
17187 (previous-single-property-change p 'face)
17188 (next-single-property-change p 'face)) clist))
17189 ((org-on-target-p)
17190 (push (org-point-in-group p 0 :target) clist)
17191 (goto-char (1- (match-beginning 0)))
17192 (if (looking-at org-radio-target-regexp)
17193 (push (org-point-in-group p 0 :radio-target) clist))
17194 (goto-char p))
17195 ((setq o (car (delq nil
17196 (mapcar
17197 (lambda (x)
17198 (if (memq x org-latex-fragment-image-overlays) x))
17199 (org-overlays-at (point))))))
17200 (push (list :latex-fragment
17201 (org-overlay-start o) (org-overlay-end o)) clist)
17202 (push (list :latex-preview
17203 (org-overlay-start o) (org-overlay-end o)) clist))
17204 ((org-inside-LaTeX-fragment-p)
17205 ;; FIXME: positions wrong.
17206 (push (list :latex-fragment (point) (point)) clist)))
17208 (setq clist (nreverse (delq nil clist)))
17209 clist))
17211 ;; FIXME: Compare with at-regexp-p Do we need both?
17212 (defun org-in-regexp (re &optional nlines visually)
17213 "Check if point is inside a match of regexp.
17214 Normally only the current line is checked, but you can include NLINES extra
17215 lines both before and after point into the search.
17216 If VISUALLY is set, require that the cursor is not after the match but
17217 really on, so that the block visually is on the match."
17218 (catch 'exit
17219 (let ((pos (point))
17220 (eol (point-at-eol (+ 1 (or nlines 0))))
17221 (inc (if visually 1 0)))
17222 (save-excursion
17223 (beginning-of-line (- 1 (or nlines 0)))
17224 (while (re-search-forward re eol t)
17225 (if (and (<= (match-beginning 0) pos)
17226 (>= (+ inc (match-end 0)) pos))
17227 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
17229 (defun org-at-regexp-p (regexp)
17230 "Is point inside a match of REGEXP in the current line?"
17231 (catch 'exit
17232 (save-excursion
17233 (let ((pos (point)) (end (point-at-eol)))
17234 (beginning-of-line 1)
17235 (while (re-search-forward regexp end t)
17236 (if (and (<= (match-beginning 0) pos)
17237 (>= (match-end 0) pos))
17238 (throw 'exit t)))
17239 nil))))
17241 (defun org-in-regexps-block-p (start-re end-re)
17242 "Returns t if the current point is between matches of START-RE and END-RE.
17243 This will also return to if point is on one of the two matches."
17244 (interactive)
17245 (let ((p (point)))
17246 (save-excursion
17247 (and (or (org-at-regexp-p start-re)
17248 (re-search-backward start-re nil t))
17249 (re-search-forward end-re nil t)
17250 (>= (point) p)))))
17252 (defun org-occur-in-agenda-files (regexp &optional nlines)
17253 "Call `multi-occur' with buffers for all agenda files."
17254 (interactive "sOrg-files matching: \np")
17255 (let* ((files (org-agenda-files))
17256 (tnames (mapcar 'file-truename files))
17257 (extra org-agenda-text-search-extra-files)
17259 (when (eq (car extra) 'agenda-archives)
17260 (setq extra (cdr extra))
17261 (setq files (org-add-archive-files files)))
17262 (while (setq f (pop extra))
17263 (unless (member (file-truename f) tnames)
17264 (add-to-list 'files f 'append)
17265 (add-to-list 'tnames (file-truename f) 'append)))
17266 (multi-occur
17267 (mapcar (lambda (x)
17268 (with-current-buffer
17269 (or (get-file-buffer x) (find-file-noselect x))
17270 (widen)
17271 (current-buffer)))
17272 files)
17273 regexp)))
17275 (if (boundp 'occur-mode-find-occurrence-hook)
17276 ;; Emacs 23
17277 (add-hook 'occur-mode-find-occurrence-hook
17278 (lambda ()
17279 (when (org-mode-p)
17280 (org-reveal))))
17281 ;; Emacs 22
17282 (defadvice occur-mode-goto-occurrence
17283 (after org-occur-reveal activate)
17284 (and (org-mode-p) (org-reveal)))
17285 (defadvice occur-mode-goto-occurrence-other-window
17286 (after org-occur-reveal activate)
17287 (and (org-mode-p) (org-reveal)))
17288 (defadvice occur-mode-display-occurrence
17289 (after org-occur-reveal activate)
17290 (when (org-mode-p)
17291 (let ((pos (occur-mode-find-occurrence)))
17292 (with-current-buffer (marker-buffer pos)
17293 (save-excursion
17294 (goto-char pos)
17295 (org-reveal)))))))
17297 (defun org-occur-link-in-agenda-files ()
17298 "Create a link and search for it in the agendas.
17299 The link is not stored in `org-stored-links', it is just created
17300 for the search purpose."
17301 (interactive)
17302 (let ((link (condition-case nil
17303 (org-store-link nil)
17304 (error "Unable to create a link to here"))))
17305 (org-occur-in-agenda-files (regexp-quote link))))
17307 (defun org-uniquify (list)
17308 "Remove duplicate elements from LIST."
17309 (let (res)
17310 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
17311 res))
17313 (defun org-delete-all (elts list)
17314 "Remove all elements in ELTS from LIST."
17315 (while elts
17316 (setq list (delete (pop elts) list)))
17317 list)
17319 (defun org-back-over-empty-lines ()
17320 "Move backwards over whitespace, to the beginning of the first empty line.
17321 Returns the number of empty lines passed."
17322 (let ((pos (point)))
17323 (skip-chars-backward " \t\n\r")
17324 (beginning-of-line 2)
17325 (goto-char (min (point) pos))
17326 (count-lines (point) pos)))
17328 (defun org-skip-whitespace ()
17329 (skip-chars-forward " \t\n\r"))
17331 (defun org-point-in-group (point group &optional context)
17332 "Check if POINT is in match-group GROUP.
17333 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
17334 match. If the match group does ot exist or point is not inside it,
17335 return nil."
17336 (and (match-beginning group)
17337 (>= point (match-beginning group))
17338 (<= point (match-end group))
17339 (if context
17340 (list context (match-beginning group) (match-end group))
17341 t)))
17343 (defun org-switch-to-buffer-other-window (&rest args)
17344 "Switch to buffer in a second window on the current frame.
17345 In particular, do not allow pop-up frames."
17346 (let (pop-up-frames special-display-buffer-names special-display-regexps
17347 special-display-function)
17348 (apply 'switch-to-buffer-other-window args)))
17350 (defun org-combine-plists (&rest plists)
17351 "Create a single property list from all plists in PLISTS.
17352 The process starts by copying the first list, and then setting properties
17353 from the other lists. Settings in the last list are the most significant
17354 ones and overrule settings in the other lists."
17355 (let ((rtn (copy-sequence (pop plists)))
17356 p v ls)
17357 (while plists
17358 (setq ls (pop plists))
17359 (while ls
17360 (setq p (pop ls) v (pop ls))
17361 (setq rtn (plist-put rtn p v))))
17362 rtn))
17364 (defun org-move-line-down (arg)
17365 "Move the current line down. With prefix argument, move it past ARG lines."
17366 (interactive "p")
17367 (let ((col (current-column))
17368 beg end pos)
17369 (beginning-of-line 1) (setq beg (point))
17370 (beginning-of-line 2) (setq end (point))
17371 (beginning-of-line (+ 1 arg))
17372 (setq pos (move-marker (make-marker) (point)))
17373 (insert (delete-and-extract-region beg end))
17374 (goto-char pos)
17375 (org-move-to-column col)))
17377 (defun org-move-line-up (arg)
17378 "Move the current line up. With prefix argument, move it past ARG lines."
17379 (interactive "p")
17380 (let ((col (current-column))
17381 beg end pos)
17382 (beginning-of-line 1) (setq beg (point))
17383 (beginning-of-line 2) (setq end (point))
17384 (beginning-of-line (- arg))
17385 (setq pos (move-marker (make-marker) (point)))
17386 (insert (delete-and-extract-region beg end))
17387 (goto-char pos)
17388 (org-move-to-column col)))
17390 (defun org-replace-escapes (string table)
17391 "Replace %-escapes in STRING with values in TABLE.
17392 TABLE is an association list with keys like \"%a\" and string values.
17393 The sequences in STRING may contain normal field width and padding information,
17394 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
17395 so values can contain further %-escapes if they are define later in TABLE."
17396 (let ((case-fold-search nil)
17397 e re rpl)
17398 (while (setq e (pop table))
17399 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
17400 (while (string-match re string)
17401 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
17402 (cdr e)))
17403 (setq string (replace-match rpl t t string))))
17404 string))
17407 (defun org-sublist (list start end)
17408 "Return a section of LIST, from START to END.
17409 Counting starts at 1."
17410 (let (rtn (c start))
17411 (setq list (nthcdr (1- start) list))
17412 (while (and list (<= c end))
17413 (push (pop list) rtn)
17414 (setq c (1+ c)))
17415 (nreverse rtn)))
17417 (defun org-find-base-buffer-visiting (file)
17418 "Like `find-buffer-visiting' but always return the base buffer and
17419 not an indirect buffer."
17420 (let ((buf (or (get-file-buffer file)
17421 (find-buffer-visiting file))))
17422 (if buf
17423 (or (buffer-base-buffer buf) buf)
17424 nil)))
17426 (defun org-image-file-name-regexp (&optional extensions)
17427 "Return regexp matching the file names of images.
17428 If EXTENSIONS is given, only match these."
17429 (if (and (not extensions) (fboundp 'image-file-name-regexp))
17430 (image-file-name-regexp)
17431 (let ((image-file-name-extensions
17432 (or extensions
17433 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
17434 "xbm" "xpm" "pbm" "pgm" "ppm"))))
17435 (concat "\\."
17436 (regexp-opt (nconc (mapcar 'upcase
17437 image-file-name-extensions)
17438 image-file-name-extensions)
17440 "\\'"))))
17442 (defun org-file-image-p (file &optional extensions)
17443 "Return non-nil if FILE is an image."
17444 (save-match-data
17445 (string-match (org-image-file-name-regexp extensions) file)))
17447 (defun org-get-cursor-date ()
17448 "Return the date at cursor in as a time.
17449 This works in the calendar and in the agenda, anywhere else it just
17450 returns the current time."
17451 (let (date day defd)
17452 (cond
17453 ((eq major-mode 'calendar-mode)
17454 (setq date (calendar-cursor-to-date)
17455 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17456 ((eq major-mode 'org-agenda-mode)
17457 (setq day (get-text-property (point) 'day))
17458 (if day
17459 (setq date (calendar-gregorian-from-absolute day)
17460 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
17461 (nth 2 date))))))
17462 (or defd (current-time))))
17464 (defvar org-agenda-action-marker (make-marker)
17465 "Marker pointing to the entry for the next agenda action.")
17467 (defun org-mark-entry-for-agenda-action ()
17468 "Mark the current entry as target of an agenda action.
17469 Agenda actions are actions executed from the agenda with the key `k',
17470 which make use of the date at the cursor."
17471 (interactive)
17472 (move-marker org-agenda-action-marker
17473 (save-excursion (org-back-to-heading t) (point))
17474 (current-buffer))
17475 (message
17476 "Entry marked for action; press `k' at desired date in agenda or calendar"))
17478 ;;; Paragraph filling stuff.
17479 ;; We want this to be just right, so use the full arsenal.
17481 (defun org-indent-line-function ()
17482 "Indent line like previous, but further if previous was headline or item."
17483 (interactive)
17484 (let* ((pos (point))
17485 (itemp (org-at-item-p))
17486 (case-fold-search t)
17487 (org-drawer-regexp (or org-drawer-regexp "\000"))
17488 column bpos bcol tpos tcol bullet btype bullet-type)
17489 ;; Find the previous relevant line
17490 (beginning-of-line 1)
17491 (cond
17492 ((looking-at "#") (setq column 0))
17493 ((looking-at "\\*+ ") (setq column 0))
17494 ((and (looking-at "[ \t]*:END:")
17495 (save-excursion (re-search-backward org-drawer-regexp nil t)))
17496 (save-excursion
17497 (goto-char (1- (match-beginning 1)))
17498 (setq column (current-column))))
17499 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
17500 (save-excursion
17501 (re-search-backward
17502 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
17503 (setq column (org-get-indentation (match-string 0))))
17505 (beginning-of-line 0)
17506 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
17507 (not (looking-at "[ \t]*:END:"))
17508 (not (looking-at org-drawer-regexp)))
17509 (beginning-of-line 0))
17510 (cond
17511 ((looking-at "\\*+[ \t]+")
17512 (if (not org-adapt-indentation)
17513 (setq column 0)
17514 (goto-char (match-end 0))
17515 (setq column (current-column))))
17516 ((looking-at org-drawer-regexp)
17517 (goto-char (1- (match-beginning 1)))
17518 (setq column (current-column)))
17519 ((looking-at "\\([ \t]*\\):END:")
17520 (goto-char (match-end 1))
17521 (setq column (current-column)))
17522 ((org-in-item-p)
17523 (org-beginning-of-item)
17524 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
17525 (setq bpos (match-beginning 1) tpos (match-end 0)
17526 bcol (progn (goto-char bpos) (current-column))
17527 tcol (progn (goto-char tpos) (current-column))
17528 bullet (match-string 1)
17529 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
17530 (if (> tcol (+ bcol org-description-max-indent))
17531 (setq tcol (+ bcol 5)))
17532 (if (not itemp)
17533 (setq column tcol)
17534 (goto-char pos)
17535 (beginning-of-line 1)
17536 (if (looking-at "\\S-")
17537 (progn
17538 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
17539 (setq bullet (match-string 1)
17540 btype (if (string-match "[0-9]" bullet) "n" bullet))
17541 (setq column (if (equal btype bullet-type) bcol tcol)))
17542 (setq column (org-get-indentation)))))
17543 (t (setq column (org-get-indentation))))))
17544 (goto-char pos)
17545 (if (<= (current-column) (current-indentation))
17546 (org-indent-line-to column)
17547 (save-excursion (org-indent-line-to column)))
17548 (setq column (current-column))
17549 (beginning-of-line 1)
17550 (if (looking-at
17551 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
17552 (replace-match (concat (match-string 1)
17553 (format org-property-format
17554 (match-string 2) (match-string 3)))
17555 t t))
17556 (org-move-to-column column)))
17558 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
17559 "Variable to store copy of `adaptive-fill-regexp'.
17560 Since `adaptive-fill-regexp' is set to never match, we need to
17561 store a backup of its value before entering `org-mode' so that
17562 the functionality can be provided as a fall-back.")
17564 (defun org-set-autofill-regexps ()
17565 (interactive)
17566 ;; In the paragraph separator we include headlines, because filling
17567 ;; text in a line directly attached to a headline would otherwise
17568 ;; fill the headline as well.
17569 (org-set-local 'comment-start-skip "^#+[ \t]*")
17570 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
17571 ;; The paragraph starter includes hand-formatted lists.
17572 (org-set-local
17573 'paragraph-start
17574 (concat
17575 "\f" "\\|"
17576 "[ ]*$" "\\|"
17577 "\\*+ " "\\|"
17578 "[ \t]*#" "\\|"
17579 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
17580 "[ \t]*[:|]" "\\|"
17581 "\\$\\$" "\\|"
17582 "\\\\\\(begin\\|end\\|[][]\\)"))
17583 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17584 ;; But only if the user has not turned off tables or fixed-width regions
17585 (org-set-local
17586 'auto-fill-inhibit-regexp
17587 (concat "\\*+ \\|#\\+"
17588 "\\|[ \t]*" org-keyword-time-regexp
17589 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17590 (concat
17591 "\\|[ \t]*["
17592 (if org-enable-table-editor "|" "")
17593 (if org-enable-fixed-width-editor ":" "")
17594 "]"))))
17595 ;; We use our own fill-paragraph function, to make sure that tables
17596 ;; and fixed-width regions are not wrapped. That function will pass
17597 ;; through to `fill-paragraph' when appropriate.
17598 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17599 ;; Adaptive filling: To get full control, first make sure that
17600 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17601 (unless (local-variable-p 'adaptive-fill-regexp)
17602 (org-set-local 'org-adaptive-fill-regexp-backup
17603 adaptive-fill-regexp))
17604 (org-set-local 'adaptive-fill-regexp "\000")
17605 (org-set-local 'adaptive-fill-function
17606 'org-adaptive-fill-function)
17607 (org-set-local
17608 'align-mode-rules-list
17609 '((org-in-buffer-settings
17610 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
17611 (modes . '(org-mode))))))
17613 (defun org-fill-paragraph (&optional justify)
17614 "Re-align a table, pass through to fill-paragraph if no table."
17615 (let ((table-p (org-at-table-p))
17616 (table.el-p (org-at-table.el-p)))
17617 (cond ((and (equal (char-after (point-at-bol)) ?*)
17618 (save-excursion (goto-char (point-at-bol))
17619 (looking-at outline-regexp)))
17620 t) ; skip headlines
17621 (table.el-p t) ; skip table.el tables
17622 (table-p (org-table-align) t) ; align org-mode tables
17623 (t nil)))) ; call paragraph-fill
17625 ;; For reference, this is the default value of adaptive-fill-regexp
17626 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17628 (defun org-adaptive-fill-function ()
17629 "Return a fill prefix for org-mode files.
17630 In particular, this makes sure hanging paragraphs for hand-formatted lists
17631 work correctly."
17632 (cond
17633 ;; Comment line
17634 ((looking-at "#[ \t]+")
17635 (match-string-no-properties 0))
17636 ;; Description list
17637 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17638 (save-excursion
17639 (if (> (match-end 1) (+ (match-beginning 1)
17640 org-description-max-indent))
17641 (goto-char (+ (match-beginning 1) 5))
17642 (goto-char (match-end 0)))
17643 (make-string (current-column) ?\ )))
17644 ;; Ordered or unordered list
17645 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)")
17646 (save-excursion
17647 (goto-char (match-end 0))
17648 (make-string (current-column) ?\ )))
17649 ;; Other text
17650 ((looking-at org-adaptive-fill-regexp-backup)
17651 (match-string-no-properties 0))))
17653 ;;; Other stuff.
17655 (defun org-toggle-fixed-width-section (arg)
17656 "Toggle the fixed-width export.
17657 If there is no active region, the QUOTE keyword at the current headline is
17658 inserted or removed. When present, it causes the text between this headline
17659 and the next to be exported as fixed-width text, and unmodified.
17660 If there is an active region, this command adds or removes a colon as the
17661 first character of this line. If the first character of a line is a colon,
17662 this line is also exported in fixed-width font."
17663 (interactive "P")
17664 (let* ((cc 0)
17665 (regionp (org-region-active-p))
17666 (beg (if regionp (region-beginning) (point)))
17667 (end (if regionp (region-end)))
17668 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17669 (case-fold-search nil)
17670 (re "[ \t]*\\(: \\)")
17671 off)
17672 (if regionp
17673 (save-excursion
17674 (goto-char beg)
17675 (setq cc (current-column))
17676 (beginning-of-line 1)
17677 (setq off (looking-at re))
17678 (while (> nlines 0)
17679 (setq nlines (1- nlines))
17680 (beginning-of-line 1)
17681 (cond
17682 (arg
17683 (org-move-to-column cc t)
17684 (insert ": \n")
17685 (forward-line -1))
17686 ((and off (looking-at re))
17687 (replace-match "" t t nil 1))
17688 ((not off) (org-move-to-column cc t) (insert ": ")))
17689 (forward-line 1)))
17690 (save-excursion
17691 (org-back-to-heading)
17692 (if (looking-at (concat outline-regexp
17693 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17694 (replace-match "" t t nil 1)
17695 (if (looking-at outline-regexp)
17696 (progn
17697 (goto-char (match-end 0))
17698 (insert org-quote-string " "))))))))
17700 (defun org-reftex-citation ()
17701 "Use reftex-citation to insert a citation into the buffer.
17702 This looks for a line like
17704 #+BIBLIOGRAPHY: foo plain option:-d
17706 and derives from it that foo.bib is the bibliography file relevant
17707 for this document. It then installs the necessary environment for RefTeX
17708 to work in this buffer and calls `reftex-citation' to insert a citation
17709 into the buffer.
17711 Export of such citations to both LaTeX and HTML is handled by the contributed
17712 package org-exp-bibtex by Taru Karttunen."
17713 (interactive)
17714 (let ((reftex-docstruct-symbol 'rds)
17715 (reftex-cite-format "\\cite{%l}")
17716 rds bib)
17717 (save-excursion
17718 (save-restriction
17719 (widen)
17720 (let ((case-fold-search t)
17721 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17722 (if (not (save-excursion
17723 (or (re-search-forward re nil t)
17724 (re-search-backward re nil t))))
17725 (error "No bibliography defined in file")
17726 (setq bib (concat (match-string 1) ".bib")
17727 rds (list (list 'bib bib)))))))
17728 (call-interactively 'reftex-citation)))
17730 ;;;; Functions extending outline functionality
17732 (defun org-beginning-of-line (&optional arg)
17733 "Go to the beginning of the current line. If that is invisible, continue
17734 to a visible line beginning. This makes the function of C-a more intuitive.
17735 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17736 first attempt, and only move to after the tags when the cursor is already
17737 beyond the end of the headline."
17738 (interactive "P")
17739 (let ((pos (point))
17740 (special (if (consp org-special-ctrl-a/e)
17741 (car org-special-ctrl-a/e)
17742 org-special-ctrl-a/e))
17743 refpos)
17744 (if (org-bound-and-true-p line-move-visual)
17745 (beginning-of-visual-line 1)
17746 (beginning-of-line 1))
17747 (if (and arg (fboundp 'move-beginning-of-line))
17748 (call-interactively 'move-beginning-of-line)
17749 (if (bobp)
17751 (backward-char 1)
17752 (if (org-invisible-p)
17753 (while (and (not (bobp)) (org-invisible-p))
17754 (backward-char 1)
17755 (beginning-of-line 1))
17756 (forward-char 1))))
17757 (when special
17758 (cond
17759 ((and (looking-at org-complex-heading-regexp)
17760 (= (char-after (match-end 1)) ?\ ))
17761 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17762 (point-at-eol)))
17763 (goto-char
17764 (if (eq special t)
17765 (cond ((> pos refpos) refpos)
17766 ((= pos (point)) refpos)
17767 (t (point)))
17768 (cond ((> pos (point)) (point))
17769 ((not (eq last-command this-command)) (point))
17770 (t refpos)))))
17771 ((org-at-item-p)
17772 (goto-char
17773 (if (eq special t)
17774 (cond ((> pos (match-end 4)) (match-end 4))
17775 ((= pos (point)) (match-end 4))
17776 (t (point)))
17777 (cond ((> pos (point)) (point))
17778 ((not (eq last-command this-command)) (point))
17779 (t (match-end 4))))))))
17780 (org-no-warnings
17781 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17783 (defun org-end-of-line (&optional arg)
17784 "Go to the end of the line.
17785 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17786 first attempt, and only move to after the tags when the cursor is already
17787 beyond the end of the headline."
17788 (interactive "P")
17789 (let ((special (if (consp org-special-ctrl-a/e)
17790 (cdr org-special-ctrl-a/e)
17791 org-special-ctrl-a/e)))
17792 (if (or (not special)
17793 (not (org-on-heading-p))
17794 arg)
17795 (call-interactively
17796 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17797 ((fboundp 'move-end-of-line) 'move-end-of-line)
17798 (t 'end-of-line)))
17799 (let ((pos (point)))
17800 (beginning-of-line 1)
17801 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17802 (if (eq special t)
17803 (if (or (< pos (match-beginning 1))
17804 (= pos (match-end 0)))
17805 (goto-char (match-beginning 1))
17806 (goto-char (match-end 0)))
17807 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17808 (goto-char (match-end 0))
17809 (goto-char (match-beginning 1))))
17810 (call-interactively (if (fboundp 'move-end-of-line)
17811 'move-end-of-line
17812 'end-of-line)))))
17813 (org-no-warnings
17814 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17816 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17817 (define-key org-mode-map "\C-e" 'org-end-of-line)
17818 (define-key org-mode-map [home] 'org-beginning-of-line)
17819 (define-key org-mode-map [end] 'org-end-of-line)
17821 (defun org-backward-sentence (&optional arg)
17822 "Go to beginning of sentence, or beginning of table field.
17823 This will call `backward-sentence' or `org-table-beginning-of-field',
17824 depending on context."
17825 (interactive "P")
17826 (cond
17827 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17828 (t (call-interactively 'backward-sentence))))
17830 (defun org-forward-sentence (&optional arg)
17831 "Go to end of sentence, or end of table field.
17832 This will call `forward-sentence' or `org-table-end-of-field',
17833 depending on context."
17834 (interactive "P")
17835 (cond
17836 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17837 (t (call-interactively 'forward-sentence))))
17839 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17840 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17842 (defun org-kill-line (&optional arg)
17843 "Kill line, to tags or end of line."
17844 (interactive "P")
17845 (cond
17846 ((or (not org-special-ctrl-k)
17847 (bolp)
17848 (not (org-on-heading-p)))
17849 (call-interactively 'kill-line))
17850 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17851 (kill-region (point) (match-beginning 1))
17852 (org-set-tags nil t))
17853 (t (kill-region (point) (point-at-eol)))))
17855 (define-key org-mode-map "\C-k" 'org-kill-line)
17857 (defun org-yank (&optional arg)
17858 "Yank. If the kill is a subtree, treat it specially.
17859 This command will look at the current kill and check if is a single
17860 subtree, or a series of subtrees[1]. If it passes the test, and if the
17861 cursor is at the beginning of a line or after the stars of a currently
17862 empty headline, then the yank is handled specially. How exactly depends
17863 on the value of the following variables, both set by default.
17865 org-yank-folded-subtrees
17866 When set, the subtree(s) will be folded after insertion, but only
17867 if doing so would now swallow text after the yanked text.
17869 org-yank-adjusted-subtrees
17870 When set, the subtree will be promoted or demoted in order to
17871 fit into the local outline tree structure, which means that the level
17872 will be adjusted so that it becomes the smaller one of the two
17873 *visible* surrounding headings.
17875 Any prefix to this command will cause `yank' to be called directly with
17876 no special treatment. In particular, a simple `C-u' prefix will just
17877 plainly yank the text as it is.
17879 \[1] The test checks if the first non-white line is a heading
17880 and if there are no other headings with fewer stars."
17881 (interactive "P")
17882 (org-yank-generic 'yank arg))
17884 (defun org-yank-generic (command arg)
17885 "Perform some yank-like command.
17887 This function implements the behavior described in the `org-yank'
17888 documentation. However, it has been generalized to work for any
17889 interactive command with similar behavior."
17891 ;; pretend to be command COMMAND
17892 (setq this-command command)
17894 (if arg
17895 (call-interactively command)
17897 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17898 (and (org-kill-is-subtree-p)
17899 (or (bolp)
17900 (and (looking-at "[ \t]*$")
17901 (string-match
17902 "\\`\\*+\\'"
17903 (buffer-substring (point-at-bol) (point)))))))
17904 swallowp)
17905 (cond
17906 ((and subtreep org-yank-folded-subtrees)
17907 (let ((beg (point))
17908 end)
17909 (if (and subtreep org-yank-adjusted-subtrees)
17910 (org-paste-subtree nil nil 'for-yank)
17911 (call-interactively command))
17913 (setq end (point))
17914 (goto-char beg)
17915 (when (and (bolp) subtreep
17916 (not (setq swallowp
17917 (org-yank-folding-would-swallow-text beg end))))
17918 (or (looking-at outline-regexp)
17919 (re-search-forward (concat "^" outline-regexp) end t))
17920 (while (and (< (point) end) (looking-at outline-regexp))
17921 (hide-subtree)
17922 (org-cycle-show-empty-lines 'folded)
17923 (condition-case nil
17924 (outline-forward-same-level 1)
17925 (error (goto-char end)))))
17926 (when swallowp
17927 (message
17928 "Inserted text not folded because that would swallow text"))
17930 (goto-char end)
17931 (skip-chars-forward " \t\n\r")
17932 (beginning-of-line 1)
17933 (push-mark beg 'nomsg)))
17934 ((and subtreep org-yank-adjusted-subtrees)
17935 (let ((beg (point-at-bol)))
17936 (org-paste-subtree nil nil 'for-yank)
17937 (push-mark beg 'nomsg)))
17939 (call-interactively command))))))
17941 (defun org-yank-folding-would-swallow-text (beg end)
17942 "Would hide-subtree at BEG swallow any text after END?"
17943 (let (level)
17944 (save-excursion
17945 (goto-char beg)
17946 (when (or (looking-at outline-regexp)
17947 (re-search-forward (concat "^" outline-regexp) end t))
17948 (setq level (org-outline-level)))
17949 (goto-char end)
17950 (skip-chars-forward " \t\r\n\v\f")
17951 (if (or (eobp)
17952 (and (bolp) (looking-at org-outline-regexp)
17953 (<= (org-outline-level) level)))
17954 nil ; Nothing would be swallowed
17955 t)))) ; something would swallow
17957 (define-key org-mode-map "\C-y" 'org-yank)
17959 (defun org-invisible-p ()
17960 "Check if point is at a character currently not visible."
17961 ;; Early versions of noutline don't have `outline-invisible-p'.
17962 (if (fboundp 'outline-invisible-p)
17963 (outline-invisible-p)
17964 (get-char-property (point) 'invisible)))
17966 (defun org-invisible-p2 ()
17967 "Check if point is at a character currently not visible."
17968 (save-excursion
17969 (if (and (eolp) (not (bobp))) (backward-char 1))
17970 ;; Early versions of noutline don't have `outline-invisible-p'.
17971 (if (fboundp 'outline-invisible-p)
17972 (outline-invisible-p)
17973 (get-char-property (point) 'invisible))))
17975 (defun org-back-to-heading (&optional invisible-ok)
17976 "Call `outline-back-to-heading', but provide a better error message."
17977 (condition-case nil
17978 (outline-back-to-heading invisible-ok)
17979 (error (error "Before first headline at position %d in buffer %s"
17980 (point) (current-buffer)))))
17982 (defun org-before-first-heading-p ()
17983 "Before first heading?"
17984 (save-excursion
17985 (null (re-search-backward "^\\*+ " nil t))))
17987 (defun org-on-heading-p (&optional ignored)
17988 (outline-on-heading-p t))
17989 (defun org-at-heading-p (&optional ignored)
17990 (outline-on-heading-p t))
17992 (defun org-point-at-end-of-empty-headline ()
17993 "If point is at the end of an empty headline, return t, else nil.
17994 If the heading only contains a TODO keyword, it is still still considered
17995 empty."
17996 (and (looking-at "[ \t]*$")
17997 (save-excursion
17998 (beginning-of-line 1)
17999 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
18000 "\\)?[ \t]*$")))))
18001 (defun org-at-heading-or-item-p ()
18002 (or (org-on-heading-p) (org-at-item-p)))
18004 (defun org-on-target-p ()
18005 (or (org-in-regexp org-radio-target-regexp)
18006 (org-in-regexp org-target-regexp)))
18008 (defun org-up-heading-all (arg)
18009 "Move to the heading line of which the present line is a subheading.
18010 This function considers both visible and invisible heading lines.
18011 With argument, move up ARG levels."
18012 (if (fboundp 'outline-up-heading-all)
18013 (outline-up-heading-all arg) ; emacs 21 version of outline.el
18014 (outline-up-heading arg t))) ; emacs 22 version of outline.el
18016 (defun org-up-heading-safe ()
18017 "Move to the heading line of which the present line is a subheading.
18018 This version will not throw an error. It will return the level of the
18019 headline found, or nil if no higher level is found.
18021 Also, this function will be a lot faster than `outline-up-heading',
18022 because it relies on stars being the outline starters. This can really
18023 make a significant difference in outlines with very many siblings."
18024 (let (start-level re)
18025 (org-back-to-heading t)
18026 (setq start-level (funcall outline-level))
18027 (if (equal start-level 1)
18029 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
18030 (if (re-search-backward re nil t)
18031 (funcall outline-level)))))
18033 (defun org-first-sibling-p ()
18034 "Is this heading the first child of its parents?"
18035 (interactive)
18036 (let ((re (concat "^" outline-regexp))
18037 level l)
18038 (unless (org-at-heading-p t)
18039 (error "Not at a heading"))
18040 (setq level (funcall outline-level))
18041 (save-excursion
18042 (if (not (re-search-backward re nil t))
18044 (setq l (funcall outline-level))
18045 (< l level)))))
18047 (defun org-goto-sibling (&optional previous)
18048 "Goto the next sibling, even if it is invisible.
18049 When PREVIOUS is set, go to the previous sibling instead. Returns t
18050 when a sibling was found. When none is found, return nil and don't
18051 move point."
18052 (let ((fun (if previous 're-search-backward 're-search-forward))
18053 (pos (point))
18054 (re (concat "^" outline-regexp))
18055 level l)
18056 (when (condition-case nil (org-back-to-heading t) (error nil))
18057 (setq level (funcall outline-level))
18058 (catch 'exit
18059 (or previous (forward-char 1))
18060 (while (funcall fun re nil t)
18061 (setq l (funcall outline-level))
18062 (when (< l level) (goto-char pos) (throw 'exit nil))
18063 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
18064 (goto-char pos)
18065 nil))))
18067 (defun org-show-siblings ()
18068 "Show all siblings of the current headline."
18069 (save-excursion
18070 (while (org-goto-sibling) (org-flag-heading nil)))
18071 (save-excursion
18072 (while (org-goto-sibling 'previous)
18073 (org-flag-heading nil))))
18075 (defun org-show-hidden-entry ()
18076 "Show an entry where even the heading is hidden."
18077 (save-excursion
18078 (org-show-entry)))
18080 (defun org-flag-heading (flag &optional entry)
18081 "Flag the current heading. FLAG non-nil means make invisible.
18082 When ENTRY is non-nil, show the entire entry."
18083 (save-excursion
18084 (org-back-to-heading t)
18085 ;; Check if we should show the entire entry
18086 (if entry
18087 (progn
18088 (org-show-entry)
18089 (save-excursion
18090 (and (outline-next-heading)
18091 (org-flag-heading nil))))
18092 (outline-flag-region (max (point-min) (1- (point)))
18093 (save-excursion (outline-end-of-heading) (point))
18094 flag))))
18096 (defun org-get-next-sibling ()
18097 "Move to next heading of the same level, and return point.
18098 If there is no such heading, return nil.
18099 This is like outline-next-sibling, but invisible headings are ok."
18100 (let ((level (funcall outline-level)))
18101 (outline-next-heading)
18102 (while (and (not (eobp)) (> (funcall outline-level) level))
18103 (outline-next-heading))
18104 (if (or (eobp) (< (funcall outline-level) level))
18106 (point))))
18108 (defun org-get-last-sibling ()
18109 "Move to previous heading of the same level, and return point.
18110 If there is no such heading, return nil."
18111 (let ((opoint (point))
18112 (level (funcall outline-level)))
18113 (outline-previous-heading)
18114 (when (and (/= (point) opoint) (outline-on-heading-p t))
18115 (while (and (> (funcall outline-level) level)
18116 (not (bobp)))
18117 (outline-previous-heading))
18118 (if (< (funcall outline-level) level)
18120 (point)))))
18122 (defun org-end-of-subtree (&optional invisible-OK to-heading)
18123 ;; This contains an exact copy of the original function, but it uses
18124 ;; `org-back-to-heading', to make it work also in invisible
18125 ;; trees. And is uses an invisible-OK argument.
18126 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
18127 ;; Furthermore, when used inside Org, finding the end of a large subtree
18128 ;; with many children and grandchildren etc, this can be much faster
18129 ;; than the outline version.
18130 (org-back-to-heading invisible-OK)
18131 (let ((first t)
18132 (level (funcall outline-level)))
18133 (if (and (org-mode-p) (< level 1000))
18134 ;; A true heading (not a plain list item), in Org-mode
18135 ;; This means we can easily find the end by looking
18136 ;; only for the right number of stars. Using a regexp to do
18137 ;; this is so much faster than using a Lisp loop.
18138 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
18139 (forward-char 1)
18140 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
18141 ;; something else, do it the slow way
18142 (while (and (not (eobp))
18143 (or first (> (funcall outline-level) level)))
18144 (setq first nil)
18145 (outline-next-heading)))
18146 (unless to-heading
18147 (if (memq (preceding-char) '(?\n ?\^M))
18148 (progn
18149 ;; Go to end of line before heading
18150 (forward-char -1)
18151 (if (memq (preceding-char) '(?\n ?\^M))
18152 ;; leave blank line before heading
18153 (forward-char -1))))))
18154 (point))
18156 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
18157 "Use Org version in org-mode, for dramatic speed-up."
18158 (if (eq major-mode 'org-mode)
18159 (progn
18160 (org-end-of-subtree nil t)
18161 (unless (eobp) (backward-char 1)))
18162 ad-do-it))
18164 (defun org-forward-same-level (arg &optional invisible-ok)
18165 "Move forward to the arg'th subheading at same level as this one.
18166 Stop at the first and last subheadings of a superior heading."
18167 (interactive "p")
18168 (org-back-to-heading invisible-ok)
18169 (org-on-heading-p)
18170 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18171 (re (format "^\\*\\{1,%d\\} " level))
18173 (forward-char 1)
18174 (while (> arg 0)
18175 (while (and (re-search-forward re nil 'move)
18176 (setq l (- (match-end 0) (match-beginning 0) 1))
18177 (= l level)
18178 (not invisible-ok)
18179 (progn (backward-char 1) (org-invisible-p)))
18180 (if (< l level) (setq arg 1)))
18181 (setq arg (1- arg)))
18182 (beginning-of-line 1)))
18184 (defun org-backward-same-level (arg &optional invisible-ok)
18185 "Move backward to the arg'th subheading at same level as this one.
18186 Stop at the first and last subheadings of a superior heading."
18187 (interactive "p")
18188 (org-back-to-heading)
18189 (org-on-heading-p)
18190 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18191 (re (format "^\\*\\{1,%d\\} " level))
18193 (while (> arg 0)
18194 (while (and (re-search-backward re nil 'move)
18195 (setq l (- (match-end 0) (match-beginning 0) 1))
18196 (= l level)
18197 (not invisible-ok)
18198 (org-invisible-p))
18199 (if (< l level) (setq arg 1)))
18200 (setq arg (1- arg)))))
18202 (defun org-show-subtree ()
18203 "Show everything after this heading at deeper levels."
18204 (outline-flag-region
18205 (point)
18206 (save-excursion
18207 (org-end-of-subtree t t))
18208 nil))
18210 (defun org-show-entry ()
18211 "Show the body directly following this heading.
18212 Show the heading too, if it is currently invisible."
18213 (interactive)
18214 (save-excursion
18215 (condition-case nil
18216 (progn
18217 (org-back-to-heading t)
18218 (outline-flag-region
18219 (max (point-min) (1- (point)))
18220 (save-excursion
18221 (if (re-search-forward
18222 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
18223 (match-beginning 1)
18224 (point-max)))
18225 nil)
18226 (org-cycle-hide-drawers 'children))
18227 (error nil))))
18229 (defun org-make-options-regexp (kwds &optional extra)
18230 "Make a regular expression for keyword lines."
18231 (concat
18233 "#?[ \t]*\\+\\("
18234 (mapconcat 'regexp-quote kwds "\\|")
18235 (if extra (concat "\\|" extra))
18236 "\\):[ \t]*"
18237 "\\(.*\\)"))
18239 ;; Make isearch reveal the necessary context
18240 (defun org-isearch-end ()
18241 "Reveal context after isearch exits."
18242 (when isearch-success ; only if search was successful
18243 (if (featurep 'xemacs)
18244 ;; Under XEmacs, the hook is run in the correct place,
18245 ;; we directly show the context.
18246 (org-show-context 'isearch)
18247 ;; In Emacs the hook runs *before* restoring the overlays.
18248 ;; So we have to use a one-time post-command-hook to do this.
18249 ;; (Emacs 22 has a special variable, see function `org-mode')
18250 (unless (and (boundp 'isearch-mode-end-hook-quit)
18251 isearch-mode-end-hook-quit)
18252 ;; Only when the isearch was not quitted.
18253 (org-add-hook 'post-command-hook 'org-isearch-post-command
18254 'append 'local)))))
18256 (defun org-isearch-post-command ()
18257 "Remove self from hook, and show context."
18258 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
18259 (org-show-context 'isearch))
18262 ;;;; Integration with and fixes for other packages
18264 ;;; Imenu support
18266 (defvar org-imenu-markers nil
18267 "All markers currently used by Imenu.")
18268 (make-variable-buffer-local 'org-imenu-markers)
18270 (defun org-imenu-new-marker (&optional pos)
18271 "Return a new marker for use by Imenu, and remember the marker."
18272 (let ((m (make-marker)))
18273 (move-marker m (or pos (point)))
18274 (push m org-imenu-markers)
18277 (defun org-imenu-get-tree ()
18278 "Produce the index for Imenu."
18279 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
18280 (setq org-imenu-markers nil)
18281 (let* ((n org-imenu-depth)
18282 (re (concat "^" outline-regexp))
18283 (subs (make-vector (1+ n) nil))
18284 (last-level 0)
18285 m level head)
18286 (save-excursion
18287 (save-restriction
18288 (widen)
18289 (goto-char (point-max))
18290 (while (re-search-backward re nil t)
18291 (setq level (org-reduced-level (funcall outline-level)))
18292 (when (<= level n)
18293 (looking-at org-complex-heading-regexp)
18294 (setq head (org-link-display-format
18295 (org-match-string-no-properties 4))
18296 m (org-imenu-new-marker))
18297 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
18298 (if (>= level last-level)
18299 (push (cons head m) (aref subs level))
18300 (push (cons head (aref subs (1+ level))) (aref subs level))
18301 (loop for i from (1+ level) to n do (aset subs i nil)))
18302 (setq last-level level)))))
18303 (aref subs 1)))
18305 (eval-after-load "imenu"
18306 '(progn
18307 (add-hook 'imenu-after-jump-hook
18308 (lambda ()
18309 (if (eq major-mode 'org-mode)
18310 (org-show-context 'org-goto))))))
18312 (defun org-link-display-format (link)
18313 "Replace a link with either the description, or the link target
18314 if no description is present"
18315 (save-match-data
18316 (if (string-match org-bracket-link-analytic-regexp link)
18317 (replace-match (if (match-end 5)
18318 (match-string 5 link)
18319 (concat (match-string 1 link)
18320 (match-string 3 link)))
18321 nil t link)
18322 link)))
18324 ;; Speedbar support
18326 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
18327 "Overlay marking the agenda restriction line in speedbar.")
18328 (org-overlay-put org-speedbar-restriction-lock-overlay
18329 'face 'org-agenda-restriction-lock)
18330 (org-overlay-put org-speedbar-restriction-lock-overlay
18331 'help-echo "Agendas are currently limited to this item.")
18332 (org-detach-overlay org-speedbar-restriction-lock-overlay)
18334 (defun org-speedbar-set-agenda-restriction ()
18335 "Restrict future agenda commands to the location at point in speedbar.
18336 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
18337 (interactive)
18338 (require 'org-agenda)
18339 (let (p m tp np dir txt)
18340 (cond
18341 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18342 'org-imenu t))
18343 (setq m (get-text-property p 'org-imenu-marker))
18344 (with-current-buffer (marker-buffer m)
18345 (goto-char m)
18346 (org-agenda-set-restriction-lock 'subtree)))
18347 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18348 'speedbar-function 'speedbar-find-file))
18349 (setq tp (previous-single-property-change
18350 (1+ p) 'speedbar-function)
18351 np (next-single-property-change
18352 tp 'speedbar-function)
18353 dir (speedbar-line-directory)
18354 txt (buffer-substring-no-properties (or tp (point-min))
18355 (or np (point-max))))
18356 (with-current-buffer (find-file-noselect
18357 (let ((default-directory dir))
18358 (expand-file-name txt)))
18359 (unless (org-mode-p)
18360 (error "Cannot restrict to non-Org-mode file"))
18361 (org-agenda-set-restriction-lock 'file)))
18362 (t (error "Don't know how to restrict Org-mode's agenda")))
18363 (org-move-overlay org-speedbar-restriction-lock-overlay
18364 (point-at-bol) (point-at-eol))
18365 (setq current-prefix-arg nil)
18366 (org-agenda-maybe-redo)))
18368 (eval-after-load "speedbar"
18369 '(progn
18370 (speedbar-add-supported-extension ".org")
18371 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
18372 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
18373 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
18374 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18375 (add-hook 'speedbar-visiting-tag-hook
18376 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
18379 ;;; Fixes and Hacks for problems with other packages
18381 ;; Make flyspell not check words in links, to not mess up our keymap
18382 (defun org-mode-flyspell-verify ()
18383 "Don't let flyspell put overlays at active buttons."
18384 (and (not (get-text-property (point) 'keymap))
18385 (not (get-text-property (point) 'org-no-flyspell))))
18387 (defun org-remove-flyspell-overlays-in (beg end)
18388 "Remove flyspell overlays in region."
18389 (and (org-bound-and-true-p flyspell-mode)
18390 (fboundp 'flyspell-delete-region-overlays)
18391 (flyspell-delete-region-overlays beg end))
18392 (add-text-properties beg end '(org-no-flyspell t)))
18394 ;; Make `bookmark-jump' shows the jump location if it was hidden.
18395 (eval-after-load "bookmark"
18396 '(if (boundp 'bookmark-after-jump-hook)
18397 ;; We can use the hook
18398 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
18399 ;; Hook not available, use advice
18400 (defadvice bookmark-jump (after org-make-visible activate)
18401 "Make the position visible."
18402 (org-bookmark-jump-unhide))))
18404 ;; Make sure saveplace shows the location if it was hidden
18405 (eval-after-load "saveplace"
18406 '(defadvice save-place-find-file-hook (after org-make-visible activate)
18407 "Make the position visible."
18408 (org-bookmark-jump-unhide)))
18410 ;; Make sure ecb shows the location if it was hidden
18411 (eval-after-load "ecb"
18412 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
18413 "Make hierarchy visible when jumping into location from ECB tree buffer."
18414 (if (eq major-mode 'org-mode)
18415 (org-show-context))))
18417 (defun org-bookmark-jump-unhide ()
18418 "Unhide the current position, to show the bookmark location."
18419 (and (org-mode-p)
18420 (or (org-invisible-p)
18421 (save-excursion (goto-char (max (point-min) (1- (point))))
18422 (org-invisible-p)))
18423 (org-show-context 'bookmark-jump)))
18425 ;; Make session.el ignore our circular variable
18426 (eval-after-load "session"
18427 '(add-to-list 'session-globals-exclude 'org-mark-ring))
18429 ;;;; Experimental code
18431 (defun org-closed-in-range ()
18432 "Sparse tree of items closed in a certain time range.
18433 Still experimental, may disappear in the future."
18434 (interactive)
18435 ;; Get the time interval from the user.
18436 (let* ((time1 (org-float-time
18437 (org-read-date nil 'to-time nil "Starting date: ")))
18438 (time2 (org-float-time
18439 (org-read-date nil 'to-time nil "End date:")))
18440 ;; callback function
18441 (callback (lambda ()
18442 (let ((time
18443 (org-float-time
18444 (apply 'encode-time
18445 (org-parse-time-string
18446 (match-string 1))))))
18447 ;; check if time in interval
18448 (and (>= time time1) (<= time time2))))))
18449 ;; make tree, check each match with the callback
18450 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
18452 ;;;; Finish up
18454 (provide 'org)
18456 (run-hooks 'org-load-hook)
18458 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
18460 ;;; org.el ends here