Use the normal overlay API, not Org's one
[org-mode.git] / lisp / org.el
blobc9fa4b5f0b56805f795a1e437e90275d848b8acb
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, 2010
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.35trans
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 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
77 ;; the file noutline.el being loaded.
78 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
79 ;; We require noutline, which might be provided in outline.el
80 (require 'outline) (require 'noutline)
81 ;; Other stuff we need.
82 (require 'time-date)
83 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
84 (require 'easymenu)
85 (require 'overlay)
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.35trans"
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 name. For backward
1467 compatibility, this can also be a string with only alphanumeric
1468 characters, which is then interpreted as an extension.
1469 `directory' Matches a directory
1470 `remote' Matches a remote file, accessible through tramp or efs.
1471 Remote files most likely should be visited through Emacs
1472 because external applications cannot handle such paths.
1473 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1474 so all files Emacs knows how to handle. Using this with
1475 command `emacs' will open most files in Emacs. Beware that this
1476 will also open html files inside Emacs, unless you add
1477 (\"html\" . default) to the list as well.
1478 t Default for files not matched by any of the other options.
1479 `system' The system command to open files, like `open' on Windows
1480 and Mac OS X, and mailcap under GNU/Linux. This is the command
1481 that will be selected if you call `C-c C-o' with a double
1482 `C-u C-u' prefix.
1484 Possible values for the command are:
1485 `emacs' The file will be visited by the current Emacs process.
1486 `default' Use the default application for this file type, which is the
1487 association for t in the list, most likely in the system-specific
1488 part.
1489 This can be used to overrule an unwanted setting in the
1490 system-specific variable.
1491 `system' Use the system command for opening files, like \"open\".
1492 This command is specified by the entry whose car is `system'.
1493 Most likely, the system-specific version of this variable
1494 does define this command, but you can overrule/replace it
1495 here.
1496 string A command to be executed by a shell; %s will be replaced
1497 by the path to the file.
1498 sexp A Lisp form which will be evaluated. The file path will
1499 be available in the Lisp variable `file'.
1500 For more examples, see the system specific constants
1501 `org-file-apps-defaults-macosx'
1502 `org-file-apps-defaults-windowsnt'
1503 `org-file-apps-defaults-gnu'."
1504 :group 'org-link-follow
1505 :type '(repeat
1506 (cons (choice :value ""
1507 (string :tag "Extension")
1508 (const :tag "System command to open files" system)
1509 (const :tag "Default for unrecognized files" t)
1510 (const :tag "Remote file" remote)
1511 (const :tag "Links to a directory" directory)
1512 (const :tag "Any files that have Emacs modes"
1513 auto-mode))
1514 (choice :value ""
1515 (const :tag "Visit with Emacs" emacs)
1516 (const :tag "Use default" default)
1517 (const :tag "Use the system command" system)
1518 (string :tag "Command")
1519 (sexp :tag "Lisp form")))))
1523 (defgroup org-refile nil
1524 "Options concerning refiling entries in Org-mode."
1525 :tag "Org Refile"
1526 :group 'org)
1528 (defcustom org-directory "~/org"
1529 "Directory with org files.
1530 This is just a default location to look for Org files. There is no need
1531 at all to put your files into this directory. It is only used in the
1532 following situations:
1534 1. When a remember template specifies a target file that is not an
1535 absolute path. The path will then be interpreted relative to
1536 `org-directory'
1537 2. When a remember note is filed away in an interactive way (when exiting the
1538 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1539 with `org-directory' as the default path."
1540 :group 'org-refile
1541 :group 'org-remember
1542 :type 'directory)
1544 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1545 "Default target for storing notes.
1546 Used by the hooks for remember.el. This can be a string, or nil to mean
1547 the value of `remember-data-file'.
1548 You can set this on a per-template basis with the variable
1549 `org-remember-templates'."
1550 :group 'org-refile
1551 :group 'org-remember
1552 :type '(choice
1553 (const :tag "Default from remember-data-file" nil)
1554 file))
1556 (defcustom org-goto-interface 'outline
1557 "The default interface to be used for `org-goto'.
1558 Allowed values are:
1559 outline The interface shows an outline of the relevant file
1560 and the correct heading is found by moving through
1561 the outline or by searching with incremental search.
1562 outline-path-completion Headlines in the current buffer are offered via
1563 completion. This is the interface also used by
1564 the refile command."
1565 :group 'org-refile
1566 :type '(choice
1567 (const :tag "Outline" outline)
1568 (const :tag "Outline-path-completion" outline-path-completion)))
1570 (defcustom org-goto-max-level 5
1571 "Maximum level to be considered when running org-goto with refile interface."
1572 :group 'org-refile
1573 :type 'integer)
1575 (defcustom org-reverse-note-order nil
1576 "Non-nil means store new notes at the beginning of a file or entry.
1577 When nil, new notes will be filed to the end of a file or entry.
1578 This can also be a list with cons cells of regular expressions that
1579 are matched against file names, and values."
1580 :group 'org-remember
1581 :group 'org-refile
1582 :type '(choice
1583 (const :tag "Reverse always" t)
1584 (const :tag "Reverse never" nil)
1585 (repeat :tag "By file name regexp"
1586 (cons regexp boolean))))
1588 (defcustom org-log-refile nil
1589 "Information to record when a task is refiled.
1591 Possible values are:
1593 nil Don't add anything
1594 time Add a time stamp to the task
1595 note Prompt for a note and add it with template `org-log-note-headings'
1597 This option can also be set with on a per-file-basis with
1599 #+STARTUP: nologrefile
1600 #+STARTUP: logrefile
1601 #+STARTUP: lognoterefile
1603 You can have local logging settings for a subtree by setting the LOGGING
1604 property to one or more of these keywords.
1606 When bulk-refiling from the agenda, the value `note' is forbidden and
1607 will temporarily be changed to `time'."
1608 :group 'org-refile
1609 :group 'org-progress
1610 :type '(choice
1611 (const :tag "No logging" nil)
1612 (const :tag "Record timestamp" time)
1613 (const :tag "Record timestamp with note." note)))
1615 (defcustom org-refile-targets nil
1616 "Targets for refiling entries with \\[org-refile].
1617 This is list of cons cells. Each cell contains:
1618 - a specification of the files to be considered, either a list of files,
1619 or a symbol whose function or variable value will be used to retrieve
1620 a file name or a list of file names. If you use `org-agenda-files' for
1621 that, all agenda files will be scanned for targets. Nil means consider
1622 headings in the current buffer.
1623 - A specification of how to find candidate refile targets. This may be
1624 any of:
1625 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1626 This tag has to be present in all target headlines, inheritance will
1627 not be considered.
1628 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1629 todo keyword.
1630 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1631 headlines that are refiling targets.
1632 - a cons cell (:level . N). Any headline of level N is considered a target.
1633 Note that, when `org-odd-levels-only' is set, level corresponds to
1634 order in hierarchy, not to the number of stars.
1635 - a cons cell (:maxlevel . N). Any headline with level <= N is 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.
1639 You can set the variable `org-refile-target-verify-function' to a function
1640 to verify each headline found by the simple critery above.
1642 When this variable is nil, all top-level headlines in the current buffer
1643 are used, equivalent to the value `((nil . (:level . 1))'."
1644 :group 'org-refile
1645 :type '(repeat
1646 (cons
1647 (choice :value org-agenda-files
1648 (const :tag "All agenda files" org-agenda-files)
1649 (const :tag "Current buffer" nil)
1650 (function) (variable) (file))
1651 (choice :tag "Identify target headline by"
1652 (cons :tag "Specific tag" (const :value :tag) (string))
1653 (cons :tag "TODO keyword" (const :value :todo) (string))
1654 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1655 (cons :tag "Level number" (const :value :level) (integer))
1656 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1658 (defcustom org-refile-target-verify-function nil
1659 "Function to verify if the headline at point should be a refile target.
1660 The function will be called without arguments, with point at the
1661 beginning of the headline. It should return t and leave point
1662 where it is if the headline is a valid target for refiling.
1664 If the target should not be selected, the function must return nil.
1665 In addition to this, it may move point to a place from where the search
1666 should be continued. For example, the function may decide that the entire
1667 subtree of the current entry should be excluded and move point to the end
1668 of the subtree."
1669 :group 'org-refile
1670 :type 'function)
1672 (defcustom org-refile-use-outline-path nil
1673 "Non-nil means provide refile targets as paths.
1674 So a level 3 headline will be available as level1/level2/level3.
1676 When the value is `file', also include the file name (without directory)
1677 into the path. In this case, you can also stop the completion after
1678 the file name, to get entries inserted as top level in the file.
1680 When `full-file-path', include the full file path."
1681 :group 'org-refile
1682 :type '(choice
1683 (const :tag "Not" nil)
1684 (const :tag "Yes" t)
1685 (const :tag "Start with file name" file)
1686 (const :tag "Start with full file path" full-file-path)))
1688 (defcustom org-outline-path-complete-in-steps t
1689 "Non-nil means complete the outline path in hierarchical steps.
1690 When Org-mode uses the refile interface to select an outline path
1691 \(see variable `org-refile-use-outline-path'), the completion of
1692 the path can be done is a single go, or if can be done in steps down
1693 the headline hierarchy. Going in steps is probably the best if you
1694 do not use a special completion package like `ido' or `icicles'.
1695 However, when using these packages, going in one step can be very
1696 fast, while still showing the whole path to the entry."
1697 :group 'org-refile
1698 :type 'boolean)
1700 (defcustom org-refile-allow-creating-parent-nodes nil
1701 "Non-nil means allow to create new nodes as refile targets.
1702 New nodes are then created by adding \"/new node name\" to the completion
1703 of an existing node. When the value of this variable is `confirm',
1704 new node creation must be confirmed by the user (recommended)
1705 When nil, the completion must match an existing entry.
1707 Note that, if the new heading is not seen by the criteria
1708 listed in `org-refile-targets', multiple instances of the same
1709 heading would be created by trying again to file under the new
1710 heading."
1711 :group 'org-refile
1712 :type '(choice
1713 (const :tag "Never" nil)
1714 (const :tag "Always" t)
1715 (const :tag "Prompt for confirmation" confirm)))
1717 (defgroup org-todo nil
1718 "Options concerning TODO items in Org-mode."
1719 :tag "Org TODO"
1720 :group 'org)
1722 (defgroup org-progress nil
1723 "Options concerning Progress logging in Org-mode."
1724 :tag "Org Progress"
1725 :group 'org-time)
1727 (defvar org-todo-interpretation-widgets
1729 (:tag "Sequence (cycling hits every state)" sequence)
1730 (:tag "Type (cycling directly to DONE)" type))
1731 "The available interpretation symbols for customizing
1732 `org-todo-keywords'.
1733 Interested libraries should add to this list.")
1735 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1736 "List of TODO entry keyword sequences and their interpretation.
1737 \\<org-mode-map>This is a list of sequences.
1739 Each sequence starts with a symbol, either `sequence' or `type',
1740 indicating if the keywords should be interpreted as a sequence of
1741 action steps, or as different types of TODO items. The first
1742 keywords are states requiring action - these states will select a headline
1743 for inclusion into the global TODO list Org-mode produces. If one of
1744 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1745 signify that no further action is necessary. If \"|\" is not found,
1746 the last keyword is treated as the only DONE state of the sequence.
1748 The command \\[org-todo] cycles an entry through these states, and one
1749 additional state where no keyword is present. For details about this
1750 cycling, see the manual.
1752 TODO keywords and interpretation can also be set on a per-file basis with
1753 the special #+SEQ_TODO and #+TYP_TODO lines.
1755 Each keyword can optionally specify a character for fast state selection
1756 \(in combination with the variable `org-use-fast-todo-selection')
1757 and specifiers for state change logging, using the same syntax
1758 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1759 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1760 indicates to record a time stamp each time this state is selected.
1762 Each keyword may also specify if a timestamp or a note should be
1763 recorded when entering or leaving the state, by adding additional
1764 characters in the parenthesis after the keyword. This looks like this:
1765 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1766 record only the time of the state change. With X and Y being either
1767 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1768 Y when leaving the state if and only if the *target* state does not
1769 define X. You may omit any of the fast-selection key or X or /Y,
1770 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1772 For backward compatibility, this variable may also be just a list
1773 of keywords - in this case the interpretation (sequence or type) will be
1774 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1775 :group 'org-todo
1776 :group 'org-keywords
1777 :type '(choice
1778 (repeat :tag "Old syntax, just keywords"
1779 (string :tag "Keyword"))
1780 (repeat :tag "New syntax"
1781 (cons
1782 (choice
1783 :tag "Interpretation"
1784 ;;Quick and dirty way to see
1785 ;;`org-todo-interpretations'. This takes the
1786 ;;place of item arguments
1787 :convert-widget
1788 (lambda (widget)
1789 (widget-put widget
1790 :args (mapcar
1791 #'(lambda (x)
1792 (widget-convert
1793 (cons 'const x)))
1794 org-todo-interpretation-widgets))
1795 widget))
1796 (repeat
1797 (string :tag "Keyword"))))))
1799 (defvar org-todo-keywords-1 nil
1800 "All TODO and DONE keywords active in a buffer.")
1801 (make-variable-buffer-local 'org-todo-keywords-1)
1802 (defvar org-todo-keywords-for-agenda nil)
1803 (defvar org-done-keywords-for-agenda nil)
1804 (defvar org-drawers-for-agenda nil)
1805 (defvar org-todo-keyword-alist-for-agenda nil)
1806 (defvar org-tag-alist-for-agenda nil)
1807 (defvar org-agenda-contributing-files nil)
1808 (defvar org-not-done-keywords nil)
1809 (make-variable-buffer-local 'org-not-done-keywords)
1810 (defvar org-done-keywords nil)
1811 (make-variable-buffer-local 'org-done-keywords)
1812 (defvar org-todo-heads nil)
1813 (make-variable-buffer-local 'org-todo-heads)
1814 (defvar org-todo-sets nil)
1815 (make-variable-buffer-local 'org-todo-sets)
1816 (defvar org-todo-log-states nil)
1817 (make-variable-buffer-local 'org-todo-log-states)
1818 (defvar org-todo-kwd-alist nil)
1819 (make-variable-buffer-local 'org-todo-kwd-alist)
1820 (defvar org-todo-key-alist nil)
1821 (make-variable-buffer-local 'org-todo-key-alist)
1822 (defvar org-todo-key-trigger nil)
1823 (make-variable-buffer-local 'org-todo-key-trigger)
1825 (defcustom org-todo-interpretation 'sequence
1826 "Controls how TODO keywords are interpreted.
1827 This variable is in principle obsolete and is only used for
1828 backward compatibility, if the interpretation of todo keywords is
1829 not given already in `org-todo-keywords'. See that variable for
1830 more information."
1831 :group 'org-todo
1832 :group 'org-keywords
1833 :type '(choice (const sequence)
1834 (const type)))
1836 (defcustom org-use-fast-todo-selection t
1837 "Non-nil means use the fast todo selection scheme with C-c C-t.
1838 This variable describes if and under what circumstances the cycling
1839 mechanism for TODO keywords will be replaced by a single-key, direct
1840 selection scheme.
1842 When nil, fast selection is never used.
1844 When the symbol `prefix', it will be used when `org-todo' is called with
1845 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1846 in an agenda buffer.
1848 When t, fast selection is used by default. In this case, the prefix
1849 argument forces cycling instead.
1851 In all cases, the special interface is only used if access keys have actually
1852 been assigned by the user, i.e. if keywords in the configuration are followed
1853 by a letter in parenthesis, like TODO(t)."
1854 :group 'org-todo
1855 :type '(choice
1856 (const :tag "Never" nil)
1857 (const :tag "By default" t)
1858 (const :tag "Only with C-u C-c C-t" prefix)))
1860 (defcustom org-provide-todo-statistics t
1861 "Non-nil means update todo statistics after insert and toggle.
1862 ALL-HEADLINES means update todo statistics by including headlines
1863 with no TODO keyword as well, counting them as not done.
1864 A list of TODO keywords means the same, but skip keywords that are
1865 not in this list.
1867 When this is set, todo statistics is updated in the parent of the
1868 current entry each time a todo state is changed."
1869 :group 'org-todo
1870 :type '(choice
1871 (const :tag "Yes, only for TODO entries" t)
1872 (const :tag "Yes, including all entries" 'all-headlines)
1873 (repeat :tag "Yes, for TODOs in this list"
1874 (string :tag "TODO keyword"))
1875 (other :tag "No TODO statistics" nil)))
1877 (defcustom org-hierarchical-todo-statistics t
1878 "Non-nil means TODO statistics covers just direct children.
1879 When nil, all entries in the subtree are considered.
1880 This has only an effect if `org-provide-todo-statistics' is set.
1881 To set this to nil for only a single subtree, use a COOKIE_DATA
1882 property and include the word \"recursive\" into the value."
1883 :group 'org-todo
1884 :type 'boolean)
1886 (defcustom org-after-todo-state-change-hook nil
1887 "Hook which is run after the state of a TODO item was changed.
1888 The new state (a string with a TODO keyword, or nil) is available in the
1889 Lisp variable `state'."
1890 :group 'org-todo
1891 :type 'hook)
1893 (defvar org-blocker-hook nil
1894 "Hook for functions that are allowed to block a state change.
1896 Each function gets as its single argument a property list, see
1897 `org-trigger-hook' for more information about this list.
1899 If any of the functions in this hook returns nil, the state change
1900 is blocked.")
1902 (defvar org-trigger-hook nil
1903 "Hook for functions that are triggered by a state change.
1905 Each function gets as its single argument a property list with at least
1906 the following elements:
1908 (:type type-of-change :position pos-at-entry-start
1909 :from old-state :to new-state)
1911 Depending on the type, more properties may be present.
1913 This mechanism is currently implemented for:
1915 TODO state changes
1916 ------------------
1917 :type todo-state-change
1918 :from previous state (keyword as a string), or nil, or a symbol
1919 'todo' or 'done', to indicate the general type of state.
1920 :to new state, like in :from")
1922 (defcustom org-enforce-todo-dependencies nil
1923 "Non-nil means undone TODO entries will block switching the parent to DONE.
1924 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1925 be blocked if any prior sibling is not yet done.
1926 Finally, if the parent is blocked because of ordered siblings of its own,
1927 the child will also be blocked.
1928 This variable needs to be set before org.el is loaded, and you need to
1929 restart Emacs after a change to make the change effective. The only way
1930 to change is while Emacs is running is through the customize interface."
1931 :set (lambda (var val)
1932 (set var val)
1933 (if val
1934 (add-hook 'org-blocker-hook
1935 'org-block-todo-from-children-or-siblings-or-parent)
1936 (remove-hook 'org-blocker-hook
1937 'org-block-todo-from-children-or-siblings-or-parent)))
1938 :group 'org-todo
1939 :type 'boolean)
1941 (defcustom org-enforce-todo-checkbox-dependencies nil
1942 "Non-nil means unchecked boxes will block switching the parent to DONE.
1943 When this is nil, checkboxes have no influence on switching TODO states.
1944 When non-nil, you first need to check off all check boxes before the TODO
1945 entry can be switched to DONE.
1946 This variable needs to be set before org.el is loaded, and you need to
1947 restart Emacs after a change to make the change effective. The only way
1948 to change is while Emacs is running is through the customize interface."
1949 :set (lambda (var val)
1950 (set var val)
1951 (if val
1952 (add-hook 'org-blocker-hook
1953 'org-block-todo-from-checkboxes)
1954 (remove-hook 'org-blocker-hook
1955 'org-block-todo-from-checkboxes)))
1956 :group 'org-todo
1957 :type 'boolean)
1959 (defcustom org-treat-insert-todo-heading-as-state-change nil
1960 "Non-nil means inserting a TODO heading is treated as state change.
1961 So when the command \\[org-insert-todo-heading] is used, state change
1962 logging will apply if appropriate. When nil, the new TODO item will
1963 be inserted directly, and no logging will take place."
1964 :group 'org-todo
1965 :type 'boolean)
1967 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1968 "Non-nil means switching TODO states with S-cursor counts as state change.
1969 This is the default behavior. However, setting this to nil allows a
1970 convenient way to select a TODO state and bypass any logging associated
1971 with that."
1972 :group 'org-todo
1973 :type 'boolean)
1975 (defcustom org-todo-state-tags-triggers nil
1976 "Tag changes that should be triggered by TODO state changes.
1977 This is a list. Each entry is
1979 (state-change (tag . flag) .......)
1981 State-change can be a string with a state, and empty string to indicate the
1982 state that has no TODO keyword, or it can be one of the symbols `todo'
1983 or `done', meaning any not-done or done state, respectively."
1984 :group 'org-todo
1985 :group 'org-tags
1986 :type '(repeat
1987 (cons (choice :tag "When changing to"
1988 (const :tag "Not-done state" todo)
1989 (const :tag "Done state" done)
1990 (string :tag "State"))
1991 (repeat
1992 (cons :tag "Tag action"
1993 (string :tag "Tag")
1994 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1996 (defcustom org-log-done nil
1997 "Information to record when a task moves to the DONE state.
1999 Possible values are:
2001 nil Don't add anything, just change the keyword
2002 time Add a time stamp to the task
2003 note Prompt for a note and add it with template `org-log-note-headings'
2005 This option can also be set with on a per-file-basis with
2007 #+STARTUP: nologdone
2008 #+STARTUP: logdone
2009 #+STARTUP: lognotedone
2011 You can have local logging settings for a subtree by setting the LOGGING
2012 property to one or more of these keywords."
2013 :group 'org-todo
2014 :group 'org-progress
2015 :type '(choice
2016 (const :tag "No logging" nil)
2017 (const :tag "Record CLOSED timestamp" time)
2018 (const :tag "Record CLOSED timestamp with note." note)))
2020 ;; Normalize old uses of org-log-done.
2021 (cond
2022 ((eq org-log-done t) (setq org-log-done 'time))
2023 ((and (listp org-log-done) (memq 'done org-log-done))
2024 (setq org-log-done 'note)))
2026 (defcustom org-log-reschedule nil
2027 "Information to record when the scheduling date of a tasks is modified.
2029 Possible values are:
2031 nil Don't add anything, just change the date
2032 time Add a time stamp to the task
2033 note Prompt for a note and add it with template `org-log-note-headings'
2035 This option can also be set with on a per-file-basis with
2037 #+STARTUP: nologreschedule
2038 #+STARTUP: logreschedule
2039 #+STARTUP: lognotereschedule"
2040 :group 'org-todo
2041 :group 'org-progress
2042 :type '(choice
2043 (const :tag "No logging" nil)
2044 (const :tag "Record timestamp" time)
2045 (const :tag "Record timestamp with note." note)))
2047 (defcustom org-log-redeadline nil
2048 "Information to record when the deadline date of a tasks is modified.
2050 Possible values are:
2052 nil Don't add anything, just change the date
2053 time Add a time stamp to the task
2054 note Prompt for a note and add it with template `org-log-note-headings'
2056 This option can also be set with on a per-file-basis with
2058 #+STARTUP: nologredeadline
2059 #+STARTUP: logredeadline
2060 #+STARTUP: lognoteredeadline
2062 You can have local logging settings for a subtree by setting the LOGGING
2063 property to one or more of these keywords."
2064 :group 'org-todo
2065 :group 'org-progress
2066 :type '(choice
2067 (const :tag "No logging" nil)
2068 (const :tag "Record timestamp" time)
2069 (const :tag "Record timestamp with note." note)))
2071 (defcustom org-log-note-clock-out nil
2072 "Non-nil means record a note when clocking out of an item.
2073 This can also be configured on a per-file basis by adding one of
2074 the following lines anywhere in the buffer:
2076 #+STARTUP: lognoteclock-out
2077 #+STARTUP: nolognoteclock-out"
2078 :group 'org-todo
2079 :group 'org-progress
2080 :type 'boolean)
2082 (defcustom org-log-done-with-time t
2083 "Non-nil means the CLOSED time stamp will contain date and time.
2084 When nil, only the date will be recorded."
2085 :group 'org-progress
2086 :type 'boolean)
2088 (defcustom org-log-note-headings
2089 '((done . "CLOSING NOTE %t")
2090 (state . "State %-12s from %-12S %t")
2091 (note . "Note taken on %t")
2092 (reschedule . "Rescheduled from %S on %t")
2093 (delschedule . "Not scheduled, was %S on %t")
2094 (redeadline . "New deadline from %S on %t")
2095 (deldeadline . "Removed deadline, was %S on %t")
2096 (refile . "Refiled on %t")
2097 (clock-out . ""))
2098 "Headings for notes added to entries.
2099 The value is an alist, with the car being a symbol indicating the note
2100 context, and the cdr is the heading to be used. The heading may also be the
2101 empty string.
2102 %t in the heading will be replaced by a time stamp.
2103 %s will be replaced by the new TODO state, in double quotes.
2104 %S will be replaced by the old TODO state, in double quotes.
2105 %u will be replaced by the user name.
2106 %U will be replaced by the full user name.
2108 In fact, it is not a good idea to change the `state' entry, because
2109 agenda log mode depends on the format of these entries."
2110 :group 'org-todo
2111 :group 'org-progress
2112 :type '(list :greedy t
2113 (cons (const :tag "Heading when closing an item" done) string)
2114 (cons (const :tag
2115 "Heading when changing todo state (todo sequence only)"
2116 state) string)
2117 (cons (const :tag "Heading when just taking a note" note) string)
2118 (cons (const :tag "Heading when clocking out" clock-out) string)
2119 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2120 (cons (const :tag "Heading when rescheduling" reschedule) string)
2121 (cons (const :tag "Heading when changing deadline" redeadline) string)
2122 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2123 (cons (const :tag "Heading when refiling" refile) string)))
2125 (unless (assq 'note org-log-note-headings)
2126 (push '(note . "%t") org-log-note-headings))
2128 (defcustom org-log-into-drawer nil
2129 "Non-nil means insert state change notes and time stamps into a drawer.
2130 When nil, state changes notes will be inserted after the headline and
2131 any scheduling and clock lines, but not inside a drawer.
2133 The value of this variable should be the name of the drawer to use.
2134 LOGBOOK is proposed at the default drawer for this purpose, you can
2135 also set this to a string to define the drawer of your choice.
2137 A value of t is also allowed, representing \"LOGBOOK\".
2139 If this variable is set, `org-log-state-notes-insert-after-drawers'
2140 will be ignored.
2142 You can set the property LOG_INTO_DRAWER to overrule this setting for
2143 a subtree."
2144 :group 'org-todo
2145 :group 'org-progress
2146 :type '(choice
2147 (const :tag "Not into a drawer" nil)
2148 (const :tag "LOGBOOK" t)
2149 (string :tag "Other")))
2151 (if (fboundp 'defvaralias)
2152 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2154 (defun org-log-into-drawer ()
2155 "Return the value of `org-log-into-drawer', but let properties overrule.
2156 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2157 used instead of the default value."
2158 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2159 (cond
2160 ((or (not p) (equal p "nil")) org-log-into-drawer)
2161 ((equal p "t") "LOGBOOK")
2162 (t p))))
2164 (defcustom org-log-state-notes-insert-after-drawers nil
2165 "Non-nil means insert state change notes after any drawers in entry.
2166 Only the drawers that *immediately* follow the headline and the
2167 deadline/scheduled line are skipped.
2168 When nil, insert notes right after the heading and perhaps the line
2169 with deadline/scheduling if present.
2171 This variable will have no effect if `org-log-into-drawer' is
2172 set."
2173 :group 'org-todo
2174 :group 'org-progress
2175 :type 'boolean)
2177 (defcustom org-log-states-order-reversed t
2178 "Non-nil means the latest state note will be directly after heading.
2179 When nil, the state change notes will be ordered according to time."
2180 :group 'org-todo
2181 :group 'org-progress
2182 :type 'boolean)
2184 (defcustom org-todo-repeat-to-state nil
2185 "The TODO state to which a repeater should return the repeating task.
2186 By default this is the first task in a TODO sequence, or the previous state
2187 in a TODO_TYP set. But you can specify another task here.
2188 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2189 :group 'org-todo
2190 :type '(choice (const :tag "Head of sequence" nil)
2191 (string :tag "Specific state")))
2193 (defcustom org-log-repeat 'time
2194 "Non-nil means record moving through the DONE state when triggering repeat.
2195 An auto-repeating task is immediately switched back to TODO when
2196 marked DONE. If you are not logging state changes (by adding \"@\"
2197 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2198 record a closing note, there will be no record of the task moving
2199 through DONE. This variable forces taking a note anyway.
2201 nil Don't force a record
2202 time Record a time stamp
2203 note Record a note
2205 This option can also be set with on a per-file-basis with
2207 #+STARTUP: logrepeat
2208 #+STARTUP: lognoterepeat
2209 #+STARTUP: nologrepeat
2211 You can have local logging settings for a subtree by setting the LOGGING
2212 property to one or more of these keywords."
2213 :group 'org-todo
2214 :group 'org-progress
2215 :type '(choice
2216 (const :tag "Don't force a record" nil)
2217 (const :tag "Force recording the DONE state" time)
2218 (const :tag "Force recording a note with the DONE state" note)))
2221 (defgroup org-priorities nil
2222 "Priorities in Org-mode."
2223 :tag "Org Priorities"
2224 :group 'org-todo)
2226 (defcustom org-enable-priority-commands t
2227 "Non-nil means priority commands are active.
2228 When nil, these commands will be disabled, so that you never accidentally
2229 set a priority."
2230 :group 'org-priorities
2231 :type 'boolean)
2233 (defcustom org-highest-priority ?A
2234 "The highest priority of TODO items. A character like ?A, ?B etc.
2235 Must have a smaller ASCII number than `org-lowest-priority'."
2236 :group 'org-priorities
2237 :type 'character)
2239 (defcustom org-lowest-priority ?C
2240 "The lowest priority of TODO items. A character like ?A, ?B etc.
2241 Must have a larger ASCII number than `org-highest-priority'."
2242 :group 'org-priorities
2243 :type 'character)
2245 (defcustom org-default-priority ?B
2246 "The default priority of TODO items.
2247 This is the priority an item get if no explicit priority is given."
2248 :group 'org-priorities
2249 :type 'character)
2251 (defcustom org-priority-start-cycle-with-default t
2252 "Non-nil means start with default priority when starting to cycle.
2253 When this is nil, the first step in the cycle will be (depending on the
2254 command used) one higher or lower that the default priority."
2255 :group 'org-priorities
2256 :type 'boolean)
2258 (defgroup org-time nil
2259 "Options concerning time stamps and deadlines in Org-mode."
2260 :tag "Org Time"
2261 :group 'org)
2263 (defcustom org-insert-labeled-timestamps-at-point nil
2264 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2265 When nil, these labeled time stamps are forces into the second line of an
2266 entry, just after the headline. When scheduling from the global TODO list,
2267 the time stamp will always be forced into the second line."
2268 :group 'org-time
2269 :type 'boolean)
2271 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2272 "Formats for `format-time-string' which are used for time stamps.
2273 It is not recommended to change this constant.")
2275 (defcustom org-time-stamp-rounding-minutes '(0 5)
2276 "Number of minutes to round time stamps to.
2277 These are two values, the first applies when first creating a time stamp.
2278 The second applies when changing it with the commands `S-up' and `S-down'.
2279 When changing the time stamp, this means that it will change in steps
2280 of N minutes, as given by the second value.
2282 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2283 numbers should be factors of 60, so for example 5, 10, 15.
2285 When this is larger than 1, you can still force an exact time-stamp by using
2286 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2287 and by using a prefix arg to `S-up/down' to specify the exact number
2288 of minutes to shift."
2289 :group 'org-time
2290 :get '(lambda (var) ; Make sure all entries have 5 elements
2291 (if (integerp (default-value var))
2292 (list (default-value var) 5)
2293 (default-value var)))
2294 :type '(list
2295 (integer :tag "when inserting times")
2296 (integer :tag "when modifying times")))
2298 ;; Normalize old customizations of this variable.
2299 (when (integerp org-time-stamp-rounding-minutes)
2300 (setq org-time-stamp-rounding-minutes
2301 (list org-time-stamp-rounding-minutes
2302 org-time-stamp-rounding-minutes)))
2304 (defcustom org-display-custom-times nil
2305 "Non-nil means overlay custom formats over all time stamps.
2306 The formats are defined through the variable `org-time-stamp-custom-formats'.
2307 To turn this on on a per-file basis, insert anywhere in the file:
2308 #+STARTUP: customtime"
2309 :group 'org-time
2310 :set 'set-default
2311 :type 'sexp)
2312 (make-variable-buffer-local 'org-display-custom-times)
2314 (defcustom org-time-stamp-custom-formats
2315 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2316 "Custom formats for time stamps. See `format-time-string' for the syntax.
2317 These are overlayed over the default ISO format if the variable
2318 `org-display-custom-times' is set. Time like %H:%M should be at the
2319 end of the second format. The custom formats are also honored by export
2320 commands, if custom time display is turned on at the time of export."
2321 :group 'org-time
2322 :type 'sexp)
2324 (defun org-time-stamp-format (&optional long inactive)
2325 "Get the right format for a time string."
2326 (let ((f (if long (cdr org-time-stamp-formats)
2327 (car org-time-stamp-formats))))
2328 (if inactive
2329 (concat "[" (substring f 1 -1) "]")
2330 f)))
2332 (defcustom org-time-clocksum-format "%d:%02d"
2333 "The format string used when creating CLOCKSUM lines, or when
2334 org-mode generates a time duration."
2335 :group 'org-time
2336 :type 'string)
2338 (defcustom org-time-clocksum-use-fractional nil
2339 "If non-nil, \\[org-clock-display] uses fractional times.
2340 org-mode generates a time duration."
2341 :group 'org-time
2342 :type 'boolean)
2344 (defcustom org-time-clocksum-fractional-format "%.2f"
2345 "The format string used when creating CLOCKSUM lines, or when
2346 org-mode generates a time duration."
2347 :group 'org-time
2348 :type 'string)
2350 (defcustom org-deadline-warning-days 14
2351 "No. of days before expiration during which a deadline becomes active.
2352 This variable governs the display in sparse trees and in the agenda.
2353 When 0 or negative, it means use this number (the absolute value of it)
2354 even if a deadline has a different individual lead time specified.
2356 Custom commands can set this variable in the options section."
2357 :group 'org-time
2358 :group 'org-agenda-daily/weekly
2359 :type 'integer)
2361 (defcustom org-read-date-prefer-future t
2362 "Non-nil means assume future for incomplete date input from user.
2363 This affects the following situations:
2364 1. The user gives a month but not a year.
2365 For example, if it is april and you enter \"feb 2\", this will be read
2366 as feb 2, *next* year. \"May 5\", however, will be this year.
2367 2. The user gives a day, but no month.
2368 For example, if today is the 15th, and you enter \"3\", Org-mode will
2369 read this as the third of *next* month. However, if you enter \"17\",
2370 it will be considered as *this* month.
2372 If you set this variable to the symbol `time', then also the following
2373 will work:
2375 3. If the user gives a time, but no day. If the time is before now,
2376 to will be interpreted as tomorrow.
2378 Currently none of this works for ISO week specifications.
2380 When this option is nil, the current day, month and year will always be
2381 used as defaults."
2382 :group 'org-time
2383 :type '(choice
2384 (const :tag "Never" nil)
2385 (const :tag "Check month and day" t)
2386 (const :tag "Check month, day, and time" time)))
2388 (defcustom org-read-date-display-live t
2389 "Non-nil means display current interpretation of date prompt live.
2390 This display will be in an overlay, in the minibuffer."
2391 :group 'org-time
2392 :type 'boolean)
2394 (defcustom org-read-date-popup-calendar t
2395 "Non-nil means pop up a calendar when prompting for a date.
2396 In the calendar, the date can be selected with mouse-1. However, the
2397 minibuffer will also be active, and you can simply enter the date as well.
2398 When nil, only the minibuffer will be available."
2399 :group 'org-time
2400 :type 'boolean)
2401 (if (fboundp 'defvaralias)
2402 (defvaralias 'org-popup-calendar-for-date-prompt
2403 'org-read-date-popup-calendar))
2405 (defcustom org-read-date-minibuffer-setup-hook nil
2406 "Hook to be used to set up keys for the date/time interface.
2407 Add key definitions to `minibuffer-local-map', which will be a temporary
2408 copy."
2409 :group 'org-time
2410 :type 'hook)
2412 (defcustom org-extend-today-until 0
2413 "The hour when your day really ends. Must be an integer.
2414 This has influence for the following applications:
2415 - When switching the agenda to \"today\". It it is still earlier than
2416 the time given here, the day recognized as TODAY is actually yesterday.
2417 - When a date is read from the user and it is still before the time given
2418 here, the current date and time will be assumed to be yesterday, 23:59.
2419 Also, timestamps inserted in remember templates follow this rule.
2421 IMPORTANT: This is a feature whose implementation is and likely will
2422 remain incomplete. Really, it is only here because past midnight seems to
2423 be the favorite working time of John Wiegley :-)"
2424 :group 'org-time
2425 :type 'integer)
2427 (defcustom org-edit-timestamp-down-means-later nil
2428 "Non-nil means S-down will increase the time in a time stamp.
2429 When nil, S-up will increase."
2430 :group 'org-time
2431 :type 'boolean)
2433 (defcustom org-calendar-follow-timestamp-change t
2434 "Non-nil means make the calendar window follow timestamp changes.
2435 When a timestamp is modified and the calendar window is visible, it will be
2436 moved to the new date."
2437 :group 'org-time
2438 :type 'boolean)
2440 (defgroup org-tags nil
2441 "Options concerning tags in Org-mode."
2442 :tag "Org Tags"
2443 :group 'org)
2445 (defcustom org-tag-alist nil
2446 "List of tags allowed in Org-mode files.
2447 When this list is nil, Org-mode will base TAG input on what is already in the
2448 buffer.
2449 The value of this variable is an alist, the car of each entry must be a
2450 keyword as a string, the cdr may be a character that is used to select
2451 that tag through the fast-tag-selection interface.
2452 See the manual for details."
2453 :group 'org-tags
2454 :type '(repeat
2455 (choice
2456 (cons (string :tag "Tag name")
2457 (character :tag "Access char"))
2458 (list :tag "Start radio group"
2459 (const :startgroup)
2460 (option (string :tag "Group description")))
2461 (list :tag "End radio group"
2462 (const :endgroup)
2463 (option (string :tag "Group description")))
2464 (const :tag "New line" (:newline)))))
2466 (defcustom org-tag-persistent-alist nil
2467 "List of tags that will always appear in all Org-mode files.
2468 This is in addition to any in buffer settings or customizations
2469 of `org-tag-alist'.
2470 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2471 The value of this variable is an alist, the car of each entry must be a
2472 keyword as a string, the cdr may be a character that is used to select
2473 that tag through the fast-tag-selection interface.
2474 See the manual for details.
2475 To disable these tags on a per-file basis, insert anywhere in the file:
2476 #+STARTUP: noptag"
2477 :group 'org-tags
2478 :type '(repeat
2479 (choice
2480 (cons (string :tag "Tag name")
2481 (character :tag "Access char"))
2482 (const :tag "Start radio group" (:startgroup))
2483 (const :tag "End radio group" (:endgroup))
2484 (const :tag "New line" (:newline)))))
2486 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2487 "If non-nil, always offer completion for all tags of all agenda files.
2488 Instead of customizing this variable directly, you might want to
2489 set it locally for remember buffers, because there no list of
2490 tags in that file can be created dynamically (there are none).
2492 (add-hook 'org-remember-mode-hook
2493 (lambda ()
2494 (set (make-local-variable
2495 'org-complete-tags-always-offer-all-agenda-tags)
2496 t)))"
2497 :group 'org-tags
2498 :type 'boolean)
2500 (defvar org-file-tags nil
2501 "List of tags that can be inherited by all entries in the file.
2502 The tags will be inherited if the variable `org-use-tag-inheritance'
2503 says they should be.
2504 This variable is populated from #+FILETAGS lines.")
2506 (defcustom org-use-fast-tag-selection 'auto
2507 "Non-nil means use fast tag selection scheme.
2508 This is a special interface to select and deselect tags with single keys.
2509 When nil, fast selection is never used.
2510 When the symbol `auto', fast selection is used if and only if selection
2511 characters for tags have been configured, either through the variable
2512 `org-tag-alist' or through a #+TAGS line in the buffer.
2513 When t, fast selection is always used and selection keys are assigned
2514 automatically if necessary."
2515 :group 'org-tags
2516 :type '(choice
2517 (const :tag "Always" t)
2518 (const :tag "Never" nil)
2519 (const :tag "When selection characters are configured" 'auto)))
2521 (defcustom org-fast-tag-selection-single-key nil
2522 "Non-nil means fast tag selection exits after first change.
2523 When nil, you have to press RET to exit it.
2524 During fast tag selection, you can toggle this flag with `C-c'.
2525 This variable can also have the value `expert'. In this case, the window
2526 displaying the tags menu is not even shown, until you press C-c again."
2527 :group 'org-tags
2528 :type '(choice
2529 (const :tag "No" nil)
2530 (const :tag "Yes" t)
2531 (const :tag "Expert" expert)))
2533 (defvar org-fast-tag-selection-include-todo nil
2534 "Non-nil means fast tags selection interface will also offer TODO states.
2535 This is an undocumented feature, you should not rely on it.")
2537 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2538 "The column to which tags should be indented in a headline.
2539 If this number is positive, it specifies the column. If it is negative,
2540 it means that the tags should be flushright to that column. For example,
2541 -80 works well for a normal 80 character screen."
2542 :group 'org-tags
2543 :type 'integer)
2545 (defcustom org-auto-align-tags t
2546 "Non-nil means realign tags after pro/demotion of TODO state change.
2547 These operations change the length of a headline and therefore shift
2548 the tags around. With this options turned on, after each such operation
2549 the tags are again aligned to `org-tags-column'."
2550 :group 'org-tags
2551 :type 'boolean)
2553 (defcustom org-use-tag-inheritance t
2554 "Non-nil means tags in levels apply also for sublevels.
2555 When nil, only the tags directly given in a specific line apply there.
2556 This may also be a list of tags that should be inherited, or a regexp that
2557 matches tags that should be inherited. Additional control is possible
2558 with the variable `org-tags-exclude-from-inheritance' which gives an
2559 explicit list of tags to be excluded from inheritance., even if the value of
2560 `org-use-tag-inheritance' would select it for inheritance.
2562 If this option is t, a match early-on in a tree can lead to a large
2563 number of matches in the subtree when constructing the agenda or creating
2564 a sparse tree. If you only want to see the first match in a tree during
2565 a search, check out the variable `org-tags-match-list-sublevels'."
2566 :group 'org-tags
2567 :type '(choice
2568 (const :tag "Not" nil)
2569 (const :tag "Always" t)
2570 (repeat :tag "Specific tags" (string :tag "Tag"))
2571 (regexp :tag "Tags matched by regexp")))
2573 (defcustom org-tags-exclude-from-inheritance nil
2574 "List of tags that should never be inherited.
2575 This is a way to exclude a few tags from inheritance. For way to do
2576 the opposite, to actively allow inheritance for selected tags,
2577 see the variable `org-use-tag-inheritance'."
2578 :group 'org-tags
2579 :type '(repeat (string :tag "Tag")))
2581 (defun org-tag-inherit-p (tag)
2582 "Check if TAG is one that should be inherited."
2583 (cond
2584 ((member tag org-tags-exclude-from-inheritance) nil)
2585 ((eq org-use-tag-inheritance t) t)
2586 ((not org-use-tag-inheritance) nil)
2587 ((stringp org-use-tag-inheritance)
2588 (string-match org-use-tag-inheritance tag))
2589 ((listp org-use-tag-inheritance)
2590 (member tag org-use-tag-inheritance))
2591 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2593 (defcustom org-tags-match-list-sublevels t
2594 "Non-nil means list also sublevels of headlines matching a search.
2595 This variable applies to tags/property searches, and also to stuck
2596 projects because this search is based on a tags match as well.
2598 When set to the symbol `indented', sublevels are indented with
2599 leading dots.
2601 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2602 the sublevels of a headline matching a tag search often also match
2603 the same search. Listing all of them can create very long lists.
2604 Setting this variable to nil causes subtrees of a match to be skipped.
2606 This variable is semi-obsolete and probably should always be true. It
2607 is better to limit inheritance to certain tags using the variables
2608 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2609 :group 'org-tags
2610 :type '(choice
2611 (const :tag "No, don't list them" nil)
2612 (const :tag "Yes, do list them" t)
2613 (const :tag "List them, indented with leading dots" indented)))
2615 (defcustom org-tags-sort-function nil
2616 "When set, tags are sorted using this function as a comparator"
2617 :group 'org-tags
2618 :type '(choice
2619 (const :tag "No sorting" nil)
2620 (const :tag "Alphabetical" string<)
2621 (const :tag "Reverse alphabetical" string>)
2622 (function :tag "Custom function" nil)))
2624 (defvar org-tags-history nil
2625 "History of minibuffer reads for tags.")
2626 (defvar org-last-tags-completion-table nil
2627 "The last used completion table for tags.")
2628 (defvar org-after-tags-change-hook nil
2629 "Hook that is run after the tags in a line have changed.")
2631 (defgroup org-properties nil
2632 "Options concerning properties in Org-mode."
2633 :tag "Org Properties"
2634 :group 'org)
2636 (defcustom org-property-format "%-10s %s"
2637 "How property key/value pairs should be formatted by `indent-line'.
2638 When `indent-line' hits a property definition, it will format the line
2639 according to this format, mainly to make sure that the values are
2640 lined-up with respect to each other."
2641 :group 'org-properties
2642 :type 'string)
2644 (defcustom org-use-property-inheritance nil
2645 "Non-nil means properties apply also for sublevels.
2647 This setting is chiefly used during property searches. Turning it on can
2648 cause significant overhead when doing a search, which is why it is not
2649 on by default.
2651 When nil, only the properties directly given in the current entry count.
2652 When t, every property is inherited. The value may also be a list of
2653 properties that should have inheritance, or a regular expression matching
2654 properties that should be inherited.
2656 However, note that some special properties use inheritance under special
2657 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2658 and the properties ending in \"_ALL\" when they are used as descriptor
2659 for valid values of a property.
2661 Note for programmers:
2662 When querying an entry with `org-entry-get', you can control if inheritance
2663 should be used. By default, `org-entry-get' looks only at the local
2664 properties. You can request inheritance by setting the inherit argument
2665 to t (to force inheritance) or to `selective' (to respect the setting
2666 in this variable)."
2667 :group 'org-properties
2668 :type '(choice
2669 (const :tag "Not" nil)
2670 (const :tag "Always" t)
2671 (repeat :tag "Specific properties" (string :tag "Property"))
2672 (regexp :tag "Properties matched by regexp")))
2674 (defun org-property-inherit-p (property)
2675 "Check if PROPERTY is one that should be inherited."
2676 (cond
2677 ((eq org-use-property-inheritance t) t)
2678 ((not org-use-property-inheritance) nil)
2679 ((stringp org-use-property-inheritance)
2680 (string-match org-use-property-inheritance property))
2681 ((listp org-use-property-inheritance)
2682 (member property org-use-property-inheritance))
2683 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2685 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2686 "The default column format, if no other format has been defined.
2687 This variable can be set on the per-file basis by inserting a line
2689 #+COLUMNS: %25ITEM ....."
2690 :group 'org-properties
2691 :type 'string)
2693 (defcustom org-columns-ellipses ".."
2694 "The ellipses to be used when a field in column view is truncated.
2695 When this is the empty string, as many characters as possible are shown,
2696 but then there will be no visual indication that the field has been truncated.
2697 When this is a string of length N, the last N characters of a truncated
2698 field are replaced by this string. If the column is narrower than the
2699 ellipses string, only part of the ellipses string will be shown."
2700 :group 'org-properties
2701 :type 'string)
2703 (defcustom org-columns-modify-value-for-display-function nil
2704 "Function that modifies values for display in column view.
2705 For example, it can be used to cut out a certain part from a time stamp.
2706 The function must take 2 arguments:
2708 column-title The title of the column (*not* the property name)
2709 value The value that should be modified.
2711 The function should return the value that should be displayed,
2712 or nil if the normal value should be used."
2713 :group 'org-properties
2714 :type 'function)
2716 (defcustom org-effort-property "Effort"
2717 "The property that is being used to keep track of effort estimates.
2718 Effort estimates given in this property need to have the format H:MM."
2719 :group 'org-properties
2720 :group 'org-progress
2721 :type '(string :tag "Property"))
2723 (defconst org-global-properties-fixed
2724 '(("VISIBILITY_ALL" . "folded children content all")
2725 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2726 "List of property/value pairs that can be inherited by any entry.
2728 These are fixed values, for the preset properties. The user variable
2729 that can be used to add to this list is `org-global-properties'.
2731 The entries in this list are cons cells where the car is a property
2732 name and cdr is a string with the value. If the value represents
2733 multiple items like an \"_ALL\" property, separate the items by
2734 spaces.")
2736 (defcustom org-global-properties nil
2737 "List of property/value pairs that can be inherited by any entry.
2739 This list will be combined with the constant `org-global-properties-fixed'.
2741 The entries in this list are cons cells where the car is a property
2742 name and cdr is a string with the value.
2744 You can set buffer-local values for the same purpose in the variable
2745 `org-file-properties' this by adding lines like
2747 #+PROPERTY: NAME VALUE"
2748 :group 'org-properties
2749 :type '(repeat
2750 (cons (string :tag "Property")
2751 (string :tag "Value"))))
2753 (defvar org-file-properties nil
2754 "List of property/value pairs that can be inherited by any entry.
2755 Valid for the current buffer.
2756 This variable is populated from #+PROPERTY lines.")
2757 (make-variable-buffer-local 'org-file-properties)
2759 (defgroup org-agenda nil
2760 "Options concerning agenda views in Org-mode."
2761 :tag "Org Agenda"
2762 :group 'org)
2764 (defvar org-category nil
2765 "Variable used by org files to set a category for agenda display.
2766 Such files should use a file variable to set it, for example
2768 # -*- mode: org; org-category: \"ELisp\"
2770 or contain a special line
2772 #+CATEGORY: ELisp
2774 If the file does not specify a category, then file's base name
2775 is used instead.")
2776 (make-variable-buffer-local 'org-category)
2777 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2779 (defcustom org-agenda-files nil
2780 "The files to be used for agenda display.
2781 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2782 \\[org-remove-file]. You can also use customize to edit the list.
2784 If an entry is a directory, all files in that directory that are matched by
2785 `org-agenda-file-regexp' will be part of the file list.
2787 If the value of the variable is not a list but a single file name, then
2788 the list of agenda files is actually stored and maintained in that file, one
2789 agenda file per line. In this file paths can be given relative to
2790 `org-directory'. Tilde expansion and environment variable substitution
2791 are also made."
2792 :group 'org-agenda
2793 :type '(choice
2794 (repeat :tag "List of files and directories" file)
2795 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2797 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2798 "Regular expression to match files for `org-agenda-files'.
2799 If any element in the list in that variable contains a directory instead
2800 of a normal file, all files in that directory that are matched by this
2801 regular expression will be included."
2802 :group 'org-agenda
2803 :type 'regexp)
2805 (defcustom org-agenda-text-search-extra-files nil
2806 "List of extra files to be searched by text search commands.
2807 These files will be search in addition to the agenda files by the
2808 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2809 Note that these files will only be searched for text search commands,
2810 not for the other agenda views like todo lists, tag searches or the weekly
2811 agenda. This variable is intended to list notes and possibly archive files
2812 that should also be searched by these two commands.
2813 In fact, if the first element in the list is the symbol `agenda-archives',
2814 than all archive files of all agenda files will be added to the search
2815 scope."
2816 :group 'org-agenda
2817 :type '(set :greedy t
2818 (const :tag "Agenda Archives" agenda-archives)
2819 (repeat :inline t (file))))
2821 (if (fboundp 'defvaralias)
2822 (defvaralias 'org-agenda-multi-occur-extra-files
2823 'org-agenda-text-search-extra-files))
2825 (defcustom org-agenda-skip-unavailable-files nil
2826 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2827 A nil value means to remove them, after a query, from the list."
2828 :group 'org-agenda
2829 :type 'boolean)
2831 (defcustom org-calendar-to-agenda-key [?c]
2832 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2833 The command `org-calendar-goto-agenda' will be bound to this key. The
2834 default is the character `c' because then `c' can be used to switch back and
2835 forth between agenda and calendar."
2836 :group 'org-agenda
2837 :type 'sexp)
2839 (defcustom org-calendar-agenda-action-key [?k]
2840 "The key to be installed in `calendar-mode-map' for agenda-action.
2841 The command `org-agenda-action' will be bound to this key. The
2842 default is the character `k' because we use the same key in the agenda."
2843 :group 'org-agenda
2844 :type 'sexp)
2846 (defcustom org-calendar-insert-diary-entry-key [?i]
2847 "The key to be installed in `calendar-mode-map' for adding diary entries.
2848 This option is irrelevant until `org-agenda-diary-file' has been configured
2849 to point to an Org-mode file. When that is the case, the command
2850 `org-agenda-diary-entry' will be bound to the key given here, by default
2851 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2852 if you want to continue doing this, you need to change this to a different
2853 key."
2854 :group 'org-agenda
2855 :type 'sexp)
2857 (defcustom org-agenda-diary-file 'diary-file
2858 "File to which to add new entries with the `i' key in agenda and calendar.
2859 When this is the symbol `diary-file', the functionality in the Emacs
2860 calendar will be used to add entries to the `diary-file'. But when this
2861 points to a file, `org-agenda-diary-entry' will be used instead."
2862 :group 'org-agenda
2863 :type '(choice
2864 (const :tag "The standard Emacs diary file" diary-file)
2865 (file :tag "Special Org file diary entries")))
2867 (eval-after-load "calendar"
2868 '(progn
2869 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2870 'org-calendar-goto-agenda)
2871 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2872 'org-agenda-action)
2873 (add-hook 'calendar-mode-hook
2874 (lambda ()
2875 (unless (eq org-agenda-diary-file 'diary-file)
2876 (define-key calendar-mode-map
2877 org-calendar-insert-diary-entry-key
2878 'org-agenda-diary-entry))))))
2880 (defgroup org-latex nil
2881 "Options for embedding LaTeX code into Org-mode."
2882 :tag "Org LaTeX"
2883 :group 'org)
2885 (defcustom org-format-latex-options
2886 '(:foreground default :background default :scale 1.0
2887 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2888 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2889 "Options for creating images from LaTeX fragments.
2890 This is a property list with the following properties:
2891 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2892 `default' means use the foreground of the default face.
2893 :background the background color, or \"Transparent\".
2894 `default' means use the background of the default face.
2895 :scale a scaling factor for the size of the images.
2896 :html-foreground, :html-background, :html-scale
2897 the same numbers for HTML export.
2898 :matchers a list indicating which matchers should be used to
2899 find LaTeX fragments. Valid members of this list are:
2900 \"begin\" find environments
2901 \"$1\" find single characters surrounded by $.$
2902 \"$\" find math expressions surrounded by $...$
2903 \"$$\" find math expressions surrounded by $$....$$
2904 \"\\(\" find math expressions surrounded by \\(...\\)
2905 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2906 :group 'org-latex
2907 :type 'plist)
2909 (defcustom org-format-latex-signal-error t
2910 "Non-nil means signal an error when image creation of LaTeX snippets fails.
2911 When nil, just push out a message."
2912 :group 'org-latex
2913 :type 'boolean)
2915 (defcustom org-format-latex-header "\\documentclass{article}
2916 \\usepackage[usenames]{color}
2917 \\usepackage{amsmath}
2918 \\usepackage[mathscr]{eucal}
2919 \\pagestyle{empty} % do not remove
2920 \[PACKAGES]
2921 \[DEFAULT-PACKAGES]
2922 % The settings below are copied from fullpage.sty
2923 \\setlength{\\textwidth}{\\paperwidth}
2924 \\addtolength{\\textwidth}{-3cm}
2925 \\setlength{\\oddsidemargin}{1.5cm}
2926 \\addtolength{\\oddsidemargin}{-2.54cm}
2927 \\setlength{\\evensidemargin}{\\oddsidemargin}
2928 \\setlength{\\textheight}{\\paperheight}
2929 \\addtolength{\\textheight}{-\\headheight}
2930 \\addtolength{\\textheight}{-\\headsep}
2931 \\addtolength{\\textheight}{-\\footskip}
2932 \\addtolength{\\textheight}{-3cm}
2933 \\setlength{\\topmargin}{1.5cm}
2934 \\addtolength{\\topmargin}{-2.54cm}"
2935 "The document header used for processing LaTeX fragments.
2936 It is imperative that this header make sure that no page number
2937 appears on the page. The package defined in the variables
2938 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
2939 will either replace the placeholder \"[PACKAGES]\" in this header, or they
2940 will be appended."
2941 :group 'org-latex
2942 :type 'string)
2944 (defvar org-format-latex-header-extra nil)
2946 ;; The following variables are defined here because is it also used
2947 ;; when formatting latex fragments. Originally it was part of the
2948 ;; LaTeX exporter, which is why the name includes "export".
2949 (defcustom org-export-latex-default-packages-alist
2950 '(("AUTO" "inputenc")
2951 ("T1" "fontenc")
2952 ("" "fixltx2e")
2953 ("" "graphicx")
2954 ("" "longtable")
2955 ("" "float")
2956 ("" "wrapfig")
2957 ("" "soul")
2958 ("" "t1enc")
2959 ("" "textcomp")
2960 ("" "marvosym")
2961 ("" "wasysym")
2962 ("" "latexsym")
2963 ("" "amssymb")
2964 ("" "hyperref")
2965 "\\tolerance=1000"
2967 "Alist of default packages to be inserted in the header.
2968 Change this only if one of the packages here causes an incompatibility
2969 with another package you are using.
2970 The packages in this list are needed by one part or another of Org-mode
2971 to function properly.
2973 - inputenc, fontenc, t1enc: for basic font and character selection
2974 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
2975 for interpreting the entities in `org-entities'. You can skip some of these
2976 packages if you don't use any of the symbols in it.
2977 - graphicx: for including images
2978 - float, wrapfig: for figure placement
2979 - longtable: for long tables
2980 - hyperref: for cross references
2982 Therefore you should not modify this variable unless you know what you
2983 are doing. The one reason to change it anyway is that you might be loading
2984 some other package that conflicts with one of the default packages.
2985 Each cell is of the format \( \"options\" \"package\" \)."
2986 :group 'org-export-latex
2987 :type '(repeat
2988 (choice
2989 (string :tag "A line of LaTeX")
2990 (list :tag "options/package pair"
2991 (string :tag "options")
2992 (string :tag "package")))))
2994 (defcustom org-export-latex-packages-alist nil
2995 "Alist of packages to be inserted in every LaTeX the header.
2996 These will be inserted after `org-export-latex-default-packages-alist'.
2997 Each cell is of the format \( \"options\" \"package\" \).
2998 Make sure that you only lis packages here which:
2999 - you want in every file
3000 - do not conflict with the default packages in
3001 `org-export-latex-default-packages-alist'
3002 - do not conflict with the setup in `org-format-latex-header'."
3003 :group 'org-export-latex
3004 :type '(repeat
3005 (choice
3006 (string :tag "A line of LaTeX")
3007 (list :tag "options/package pair"
3008 (string :tag "options")
3009 (string :tag "package")))))
3011 (defgroup org-appearance nil
3012 "Settings for Org-mode appearance."
3013 :tag "Org Appearance"
3014 :group 'org)
3016 (defcustom org-level-color-stars-only nil
3017 "Non-nil means fontify only the stars in each headline.
3018 When nil, the entire headline is fontified.
3019 Changing it requires restart of `font-lock-mode' to become effective
3020 also in regions already fontified."
3021 :group 'org-appearance
3022 :type 'boolean)
3024 (defcustom org-hide-leading-stars nil
3025 "Non-nil means hide the first N-1 stars in a headline.
3026 This works by using the face `org-hide' for these stars. This
3027 face is white for a light background, and black for a dark
3028 background. You may have to customize the face `org-hide' to
3029 make this work.
3030 Changing it requires restart of `font-lock-mode' to become effective
3031 also in regions already fontified.
3032 You may also set this on a per-file basis by adding one of the following
3033 lines to the buffer:
3035 #+STARTUP: hidestars
3036 #+STARTUP: showstars"
3037 :group 'org-appearance
3038 :type 'boolean)
3040 (defcustom org-hidden-keywords nil
3041 "List of keywords that should be hidden when typed in the org buffer.
3042 For example, add #+TITLE to this list in order to make the
3043 document title appear in the buffer without the initial #+TITLE:
3044 keyword."
3045 :group 'org-appearance
3046 :type '(set (const :tag "#+AUTHOR" author)
3047 (const :tag "#+DATE" date)
3048 (const :tag "#+EMAIL" email)
3049 (const :tag "#+TITLE" title)))
3051 (defcustom org-fontify-done-headline nil
3052 "Non-nil means change the face of a headline if it is marked DONE.
3053 Normally, only the TODO/DONE keyword indicates the state of a headline.
3054 When this is non-nil, the headline after the keyword is set to the
3055 `org-headline-done' as an additional indication."
3056 :group 'org-appearance
3057 :type 'boolean)
3059 (defcustom org-fontify-emphasized-text t
3060 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3061 Changing this variable requires a restart of Emacs to take effect."
3062 :group 'org-appearance
3063 :type 'boolean)
3065 (defcustom org-fontify-whole-heading-line nil
3066 "Non-nil means fontify the whole line for headings.
3067 This is useful when setting a background color for the
3068 org-level-* faces."
3069 :group 'org-appearance
3070 :type 'boolean)
3072 (defcustom org-highlight-latex-fragments-and-specials nil
3073 "Non-nil means fontify what is treated specially by the exporters."
3074 :group 'org-appearance
3075 :type 'boolean)
3077 (defcustom org-hide-emphasis-markers nil
3078 "Non-nil mean font-lock should hide the emphasis marker characters."
3079 :group 'org-appearance
3080 :type 'boolean)
3082 (defvar org-emph-re nil
3083 "Regular expression for matching emphasis.")
3084 (defvar org-verbatim-re nil
3085 "Regular expression for matching verbatim text.")
3086 (defvar org-emphasis-regexp-components) ; defined just below
3087 (defvar org-emphasis-alist) ; defined just below
3088 (defun org-set-emph-re (var val)
3089 "Set variable and compute the emphasis regular expression."
3090 (set var val)
3091 (when (and (boundp 'org-emphasis-alist)
3092 (boundp 'org-emphasis-regexp-components)
3093 org-emphasis-alist org-emphasis-regexp-components)
3094 (let* ((e org-emphasis-regexp-components)
3095 (pre (car e))
3096 (post (nth 1 e))
3097 (border (nth 2 e))
3098 (body (nth 3 e))
3099 (nl (nth 4 e))
3100 (body1 (concat body "*?"))
3101 (markers (mapconcat 'car org-emphasis-alist ""))
3102 (vmarkers (mapconcat
3103 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3104 org-emphasis-alist "")))
3105 ;; make sure special characters appear at the right position in the class
3106 (if (string-match "\\^" markers)
3107 (setq markers (concat (replace-match "" t t markers) "^")))
3108 (if (string-match "-" markers)
3109 (setq markers (concat (replace-match "" t t markers) "-")))
3110 (if (string-match "\\^" vmarkers)
3111 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3112 (if (string-match "-" vmarkers)
3113 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3114 (if (> nl 0)
3115 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3116 (int-to-string nl) "\\}")))
3117 ;; Make the regexp
3118 (setq org-emph-re
3119 (concat "\\([" pre "]\\|^\\)"
3120 "\\("
3121 "\\([" markers "]\\)"
3122 "\\("
3123 "[^" border "]\\|"
3124 "[^" border "]"
3125 body1
3126 "[^" border "]"
3127 "\\)"
3128 "\\3\\)"
3129 "\\([" post "]\\|$\\)"))
3130 (setq org-verbatim-re
3131 (concat "\\([" pre "]\\|^\\)"
3132 "\\("
3133 "\\([" vmarkers "]\\)"
3134 "\\("
3135 "[^" border "]\\|"
3136 "[^" border "]"
3137 body1
3138 "[^" border "]"
3139 "\\)"
3140 "\\3\\)"
3141 "\\([" post "]\\|$\\)")))))
3143 (defcustom org-emphasis-regexp-components
3144 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3145 "Components used to build the regular expression for emphasis.
3146 This is a list with 6 entries. Terminology: In an emphasis string
3147 like \" *strong word* \", we call the initial space PREMATCH, the final
3148 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3149 and \"trong wor\" is the body. The different components in this variable
3150 specify what is allowed/forbidden in each part:
3152 pre Chars allowed as prematch. Beginning of line will be allowed too.
3153 post Chars allowed as postmatch. End of line will be allowed too.
3154 border The chars *forbidden* as border characters.
3155 body-regexp A regexp like \".\" to match a body character. Don't use
3156 non-shy groups here, and don't allow newline here.
3157 newline The maximum number of newlines allowed in an emphasis exp.
3159 Use customize to modify this, or restart Emacs after changing it."
3160 :group 'org-appearance
3161 :set 'org-set-emph-re
3162 :type '(list
3163 (sexp :tag "Allowed chars in pre ")
3164 (sexp :tag "Allowed chars in post ")
3165 (sexp :tag "Forbidden chars in border ")
3166 (sexp :tag "Regexp for body ")
3167 (integer :tag "number of newlines allowed")
3168 (option (boolean :tag "Please ignore this button"))))
3170 (defcustom org-emphasis-alist
3171 `(("*" bold "<b>" "</b>")
3172 ("/" italic "<i>" "</i>")
3173 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3174 ("=" org-code "<code>" "</code>" verbatim)
3175 ("~" org-verbatim "<code>" "</code>" verbatim)
3176 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3177 "<del>" "</del>")
3179 "Special syntax for emphasized text.
3180 Text starting and ending with a special character will be emphasized, for
3181 example *bold*, _underlined_ and /italic/. This variable sets the marker
3182 characters, the face to be used by font-lock for highlighting in Org-mode
3183 Emacs buffers, and the HTML tags to be used for this.
3184 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3185 Use customize to modify this, or restart Emacs after changing it."
3186 :group 'org-appearance
3187 :set 'org-set-emph-re
3188 :type '(repeat
3189 (list
3190 (string :tag "Marker character")
3191 (choice
3192 (face :tag "Font-lock-face")
3193 (plist :tag "Face property list"))
3194 (string :tag "HTML start tag")
3195 (string :tag "HTML end tag")
3196 (option (const verbatim)))))
3198 (defvar org-protecting-blocks
3199 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3200 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3201 This is needed for font-lock setup.")
3203 ;;; Miscellaneous options
3205 (defgroup org-completion nil
3206 "Completion in Org-mode."
3207 :tag "Org Completion"
3208 :group 'org)
3210 (defcustom org-completion-use-ido nil
3211 "Non-nil means use ido completion wherever possible.
3212 Note that `ido-mode' must be active for this variable to be relevant.
3213 If you decide to turn this variable on, you might well want to turn off
3214 `org-outline-path-complete-in-steps'.
3215 See also `org-completion-use-iswitchb'."
3216 :group 'org-completion
3217 :type 'boolean)
3219 (defcustom org-completion-use-iswitchb nil
3220 "Non-nil means use iswitchb completion wherever possible.
3221 Note that `iswitchb-mode' must be active for this variable to be relevant.
3222 If you decide to turn this variable on, you might well want to turn off
3223 `org-outline-path-complete-in-steps'.
3224 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3225 :group 'org-completion
3226 :type 'boolean)
3228 (defcustom org-completion-fallback-command 'hippie-expand
3229 "The expansion command called by \\[org-complete] in normal context.
3230 Normal means no org-mode-specific context."
3231 :group 'org-completion
3232 :type 'function)
3234 ;;; Functions and variables from their packages
3235 ;; Declared here to avoid compiler warnings
3237 ;; XEmacs only
3238 (defvar outline-mode-menu-heading)
3239 (defvar outline-mode-menu-show)
3240 (defvar outline-mode-menu-hide)
3241 (defvar zmacs-regions) ; XEmacs regions
3243 ;; Emacs only
3244 (defvar mark-active)
3246 ;; Various packages
3247 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3248 (declare-function calendar-forward-day "cal-move" (arg))
3249 (declare-function calendar-goto-date "cal-move" (date))
3250 (declare-function calendar-goto-today "cal-move" ())
3251 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3252 (defvar calc-embedded-close-formula)
3253 (defvar calc-embedded-open-formula)
3254 (declare-function cdlatex-tab "ext:cdlatex" ())
3255 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3256 (defvar font-lock-unfontify-region-function)
3257 (declare-function iswitchb-read-buffer "iswitchb"
3258 (prompt &optional default require-match start matches-set))
3259 (defvar iswitchb-temp-buflist)
3260 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3261 (defvar org-agenda-tags-todo-honor-ignore-options)
3262 (declare-function org-agenda-skip "org-agenda" ())
3263 (declare-function
3264 org-format-agenda-item "org-agenda"
3265 (extra txt &optional category tags dotime noprefix remove-re habitp))
3266 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3267 (declare-function org-agenda-change-all-lines "org-agenda"
3268 (newhead hdmarker &optional fixface just-this))
3269 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3270 (declare-function org-agenda-maybe-redo "org-agenda" ())
3271 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3272 (beg end))
3273 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3274 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3275 "org-agenda" (&optional end))
3276 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3277 (declare-function org-indent-mode "org-indent" (&optional arg))
3278 (declare-function parse-time-string "parse-time" (string))
3279 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3280 (defvar remember-data-file)
3281 (defvar texmathp-why)
3282 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3283 (declare-function table--at-cell-p "table" (position &optional object at-column))
3285 (defvar w3m-current-url)
3286 (defvar w3m-current-title)
3288 (defvar org-latex-regexps)
3290 ;;; Autoload and prepare some org modules
3292 ;; Some table stuff that needs to be defined here, because it is used
3293 ;; by the functions setting up org-mode or checking for table context.
3295 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3296 "Detects an org-type or table-type table.")
3297 (defconst org-table-line-regexp "^[ \t]*|"
3298 "Detects an org-type table line.")
3299 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3300 "Detects an org-type table line.")
3301 (defconst org-table-hline-regexp "^[ \t]*|-"
3302 "Detects an org-type table hline.")
3303 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3304 "Detects a table-type table hline.")
3305 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3306 "Searching from within a table (any type) this finds the first line
3307 outside the table.")
3309 ;; Autoload the functions in org-table.el that are needed by functions here.
3311 (eval-and-compile
3312 (org-autoload "org-table"
3313 '(org-table-align org-table-begin org-table-blank-field
3314 org-table-convert org-table-convert-region org-table-copy-down
3315 org-table-copy-region org-table-create
3316 org-table-create-or-convert-from-region
3317 org-table-create-with-table.el org-table-current-dline
3318 org-table-cut-region org-table-delete-column org-table-edit-field
3319 org-table-edit-formulas org-table-end org-table-eval-formula
3320 org-table-export org-table-field-info
3321 org-table-get-stored-formulas org-table-goto-column
3322 org-table-hline-and-move org-table-import org-table-insert-column
3323 org-table-insert-hline org-table-insert-row org-table-iterate
3324 org-table-justify-field-maybe org-table-kill-row
3325 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3326 org-table-move-column org-table-move-column-left
3327 org-table-move-column-right org-table-move-row
3328 org-table-move-row-down org-table-move-row-up
3329 org-table-next-field org-table-next-row org-table-paste-rectangle
3330 org-table-previous-field org-table-recalculate
3331 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3332 org-table-toggle-coordinate-overlays
3333 org-table-toggle-formula-debugger org-table-wrap-region
3334 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3336 (defun org-at-table-p (&optional table-type)
3337 "Return t if the cursor is inside an org-type table.
3338 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3339 (if org-enable-table-editor
3340 (save-excursion
3341 (beginning-of-line 1)
3342 (looking-at (if table-type org-table-any-line-regexp
3343 org-table-line-regexp)))
3344 nil))
3345 (defsubst org-table-p () (org-at-table-p))
3347 (defun org-at-table.el-p ()
3348 "Return t if and only if we are at a table.el table."
3349 (and (org-at-table-p 'any)
3350 (save-excursion
3351 (goto-char (org-table-begin 'any))
3352 (looking-at org-table1-hline-regexp))))
3353 (defun org-table-recognize-table.el ()
3354 "If there is a table.el table nearby, recognize it and move into it."
3355 (if org-table-tab-recognizes-table.el
3356 (if (org-at-table.el-p)
3357 (progn
3358 (beginning-of-line 1)
3359 (if (looking-at org-table-dataline-regexp)
3361 (if (looking-at org-table1-hline-regexp)
3362 (progn
3363 (beginning-of-line 2)
3364 (if (looking-at org-table-any-border-regexp)
3365 (beginning-of-line -1)))))
3366 (if (re-search-forward "|" (org-table-end t) t)
3367 (progn
3368 (require 'table)
3369 (if (table--at-cell-p (point))
3371 (message "recognizing table.el table...")
3372 (table-recognize-table)
3373 (message "recognizing table.el table...done")))
3374 (error "This should not happen..."))
3376 nil)
3377 nil))
3379 (defun org-at-table-hline-p ()
3380 "Return t if the cursor is inside a hline in a table."
3381 (if org-enable-table-editor
3382 (save-excursion
3383 (beginning-of-line 1)
3384 (looking-at org-table-hline-regexp))
3385 nil))
3387 (defvar org-table-clean-did-remove-column nil)
3389 (defun org-table-map-tables (function)
3390 "Apply FUNCTION to the start of all tables in the buffer."
3391 (save-excursion
3392 (save-restriction
3393 (widen)
3394 (goto-char (point-min))
3395 (while (re-search-forward org-table-any-line-regexp nil t)
3396 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3397 (beginning-of-line 1)
3398 (when (looking-at org-table-line-regexp)
3399 (save-excursion (funcall function))
3400 (or (looking-at org-table-line-regexp)
3401 (forward-char 1)))
3402 (re-search-forward org-table-any-border-regexp nil 1))))
3403 (message "Mapping tables: done"))
3405 ;; Declare and autoload functions from org-exp.el & Co
3407 (declare-function org-default-export-plist "org-exp")
3408 (declare-function org-infile-export-plist "org-exp")
3409 (declare-function org-get-current-options "org-exp")
3410 (eval-and-compile
3411 (org-autoload "org-exp"
3412 '(org-export org-export-visible
3413 org-insert-export-options-template
3414 org-table-clean-before-export))
3415 (org-autoload "org-ascii"
3416 '(org-export-as-ascii org-export-ascii-preprocess
3417 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3418 org-export-region-as-ascii))
3419 (org-autoload "org-latex"
3420 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3421 org-replace-region-by-latex org-export-region-as-latex
3422 org-export-as-latex org-export-as-pdf
3423 org-export-as-pdf-and-open))
3424 (org-autoload "org-html"
3425 '(org-export-as-html-and-open
3426 org-export-as-html-batch org-export-as-html-to-buffer
3427 org-replace-region-by-html org-export-region-as-html
3428 org-export-as-html))
3429 (org-autoload "org-docbook"
3430 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3431 org-replace-region-by-docbook org-export-region-as-docbook
3432 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3433 org-export-as-docbook))
3434 (org-autoload "org-icalendar"
3435 '(org-export-icalendar-this-file
3436 org-export-icalendar-all-agenda-files
3437 org-export-icalendar-combine-agenda-files))
3438 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3439 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3441 ;; Declare and autoload functions from org-agenda.el
3443 (eval-and-compile
3444 (org-autoload "org-agenda"
3445 '(org-agenda org-agenda-list org-search-view
3446 org-todo-list org-tags-view org-agenda-list-stuck-projects
3447 org-diary org-agenda-to-appt
3448 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3450 ;; Autoload org-remember
3452 (eval-and-compile
3453 (org-autoload "org-remember"
3454 '(org-remember-insinuate org-remember-annotation
3455 org-remember-apply-template org-remember org-remember-handler)))
3457 ;; Autoload org-clock.el
3460 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3461 (beg end))
3462 (declare-function org-clock-update-mode-line "org-clock" ())
3463 (declare-function org-resolve-clocks "org-clock"
3464 (&optional also-non-dangling-p prompt last-valid))
3465 (defvar org-clock-start-time)
3466 (defvar org-clock-marker (make-marker)
3467 "Marker recording the last clock-in.")
3468 (defvar org-clock-hd-marker (make-marker)
3469 "Marker recording the last clock-in, but the headline position.")
3470 (defvar org-clock-heading ""
3471 "The heading of the current clock entry.")
3472 (defun org-clock-is-active ()
3473 "Return non-nil if clock is currently running.
3474 The return value is actually the clock marker."
3475 (marker-buffer org-clock-marker))
3477 (eval-and-compile
3478 (org-autoload
3479 "org-clock"
3480 '(org-clock-in org-clock-out org-clock-cancel
3481 org-clock-goto org-clock-sum org-clock-display
3482 org-clock-remove-overlays org-clock-report
3483 org-clocktable-shift org-dblock-write:clocktable
3484 org-get-clocktable org-resolve-clocks)))
3486 (defun org-clock-update-time-maybe ()
3487 "If this is a CLOCK line, update it and return t.
3488 Otherwise, return nil."
3489 (interactive)
3490 (save-excursion
3491 (beginning-of-line 1)
3492 (skip-chars-forward " \t")
3493 (when (looking-at org-clock-string)
3494 (let ((re (concat "[ \t]*" org-clock-string
3495 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3496 "\\([ \t]*=>.*\\)?\\)?"))
3497 ts te h m s neg)
3498 (cond
3499 ((not (looking-at re))
3500 nil)
3501 ((not (match-end 2))
3502 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3503 (> org-clock-marker (point))
3504 (<= org-clock-marker (point-at-eol)))
3505 ;; The clock is running here
3506 (setq org-clock-start-time
3507 (apply 'encode-time
3508 (org-parse-time-string (match-string 1))))
3509 (org-clock-update-mode-line)))
3511 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3512 (end-of-line 1)
3513 (setq ts (match-string 1)
3514 te (match-string 3))
3515 (setq s (- (org-float-time
3516 (apply 'encode-time (org-parse-time-string te)))
3517 (org-float-time
3518 (apply 'encode-time (org-parse-time-string ts))))
3519 neg (< s 0)
3520 s (abs s)
3521 h (floor (/ s 3600))
3522 s (- s (* 3600 h))
3523 m (floor (/ s 60))
3524 s (- s (* 60 s)))
3525 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3526 t))))))
3528 (defun org-check-running-clock ()
3529 "Check if the current buffer contains the running clock.
3530 If yes, offer to stop it and to save the buffer with the changes."
3531 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3532 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3533 (buffer-name))))
3534 (org-clock-out)
3535 (when (y-or-n-p "Save changed buffer?")
3536 (save-buffer))))
3538 (defun org-clocktable-try-shift (dir n)
3539 "Check if this line starts a clock table, if yes, shift the time block."
3540 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3541 (org-clocktable-shift dir n)))
3543 ;; Autoload org-timer.el
3545 (eval-and-compile
3546 (org-autoload
3547 "org-timer"
3548 '(org-timer-start org-timer org-timer-item
3549 org-timer-change-times-in-region
3550 org-timer-set-timer
3551 org-timer-reset-timers
3552 org-timer-show-remaining-time)))
3554 ;; Autoload org-feed.el
3556 (eval-and-compile
3557 (org-autoload
3558 "org-feed"
3559 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3562 ;; Autoload org-indent.el
3564 ;; Define the variable already here, to make sure we have it.
3565 (defvar org-indent-mode nil
3566 "Non-nil if Org-Indent mode is enabled.
3567 Use the command `org-indent-mode' to change this variable.")
3569 (eval-and-compile
3570 (org-autoload
3571 "org-indent"
3572 '(org-indent-mode)))
3574 ;; Autoload org-mobile.el
3576 (eval-and-compile
3577 (org-autoload
3578 "org-mobile"
3579 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3581 ;; Autoload archiving code
3582 ;; The stuff that is needed for cycling and tags has to be defined here.
3584 (defgroup org-archive nil
3585 "Options concerning archiving in Org-mode."
3586 :tag "Org Archive"
3587 :group 'org-structure)
3589 (defcustom org-archive-location "%s_archive::"
3590 "The location where subtrees should be archived.
3592 The value of this variable is a string, consisting of two parts,
3593 separated by a double-colon. The first part is a filename and
3594 the second part is a headline.
3596 When the filename is omitted, archiving happens in the same file.
3597 %s in the filename will be replaced by the current file
3598 name (without the directory part). Archiving to a different file
3599 is useful to keep archived entries from contributing to the
3600 Org-mode Agenda.
3602 The archived entries will be filed as subtrees of the specified
3603 headline. When the headline is omitted, the subtrees are simply
3604 filed away at the end of the file, as top-level entries. Also in
3605 the heading you can use %s to represent the file name, this can be
3606 useful when using the same archive for a number of different files.
3608 Here are a few examples:
3609 \"%s_archive::\"
3610 If the current file is Projects.org, archive in file
3611 Projects.org_archive, as top-level trees. This is the default.
3613 \"::* Archived Tasks\"
3614 Archive in the current file, under the top-level headline
3615 \"* Archived Tasks\".
3617 \"~/org/archive.org::\"
3618 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3620 \"~/org/archive.org::From %s\"
3621 Archive in file ~/org/archive.org (absolute path), under headlines
3622 \"From FILENAME\" where file name is the current file name.
3624 \"basement::** Finished Tasks\"
3625 Archive in file ./basement (relative path), as level 3 trees
3626 below the level 2 heading \"** Finished Tasks\".
3628 You may set this option on a per-file basis by adding to the buffer a
3629 line like
3631 #+ARCHIVE: basement::** Finished Tasks
3633 You may also define it locally for a subtree by setting an ARCHIVE property
3634 in the entry. If such a property is found in an entry, or anywhere up
3635 the hierarchy, it will be used."
3636 :group 'org-archive
3637 :type 'string)
3639 (defcustom org-archive-tag "ARCHIVE"
3640 "The tag that marks a subtree as archived.
3641 An archived subtree does not open during visibility cycling, and does
3642 not contribute to the agenda listings.
3643 After changing this, font-lock must be restarted in the relevant buffers to
3644 get the proper fontification."
3645 :group 'org-archive
3646 :group 'org-keywords
3647 :type 'string)
3649 (defcustom org-agenda-skip-archived-trees t
3650 "Non-nil means the agenda will skip any items located in archived trees.
3651 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3652 variable is no longer recommended, you should leave it at the value t.
3653 Instead, use the key `v' to cycle the archives-mode in the agenda."
3654 :group 'org-archive
3655 :group 'org-agenda-skip
3656 :type 'boolean)
3658 (defcustom org-columns-skip-archived-trees t
3659 "Non-nil means ignore archived trees when creating column view."
3660 :group 'org-archive
3661 :group 'org-properties
3662 :type 'boolean)
3664 (defcustom org-cycle-open-archived-trees nil
3665 "Non-nil means `org-cycle' will open archived trees.
3666 An archived tree is a tree marked with the tag ARCHIVE.
3667 When nil, archived trees will stay folded. You can still open them with
3668 normal outline commands like `show-all', but not with the cycling commands."
3669 :group 'org-archive
3670 :group 'org-cycle
3671 :type 'boolean)
3673 (defcustom org-sparse-tree-open-archived-trees nil
3674 "Non-nil means sparse tree construction shows matches in archived trees.
3675 When nil, matches in these trees are highlighted, but the trees are kept in
3676 collapsed state."
3677 :group 'org-archive
3678 :group 'org-sparse-trees
3679 :type 'boolean)
3681 (defun org-cycle-hide-archived-subtrees (state)
3682 "Re-hide all archived subtrees after a visibility state change."
3683 (when (and (not org-cycle-open-archived-trees)
3684 (not (memq state '(overview folded))))
3685 (save-excursion
3686 (let* ((globalp (memq state '(contents all)))
3687 (beg (if globalp (point-min) (point)))
3688 (end (if globalp (point-max) (org-end-of-subtree t))))
3689 (org-hide-archived-subtrees beg end)
3690 (goto-char beg)
3691 (if (looking-at (concat ".*:" org-archive-tag ":"))
3692 (message "%s" (substitute-command-keys
3693 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3695 (defun org-force-cycle-archived ()
3696 "Cycle subtree even if it is archived."
3697 (interactive)
3698 (setq this-command 'org-cycle)
3699 (let ((org-cycle-open-archived-trees t))
3700 (call-interactively 'org-cycle)))
3702 (defun org-hide-archived-subtrees (beg end)
3703 "Re-hide all archived subtrees after a visibility state change."
3704 (save-excursion
3705 (let* ((re (concat ":" org-archive-tag ":")))
3706 (goto-char beg)
3707 (while (re-search-forward re end t)
3708 (when (org-on-heading-p)
3709 (org-flag-subtree t)
3710 (org-end-of-subtree t))))))
3712 (defun org-flag-subtree (flag)
3713 (save-excursion
3714 (org-back-to-heading t)
3715 (outline-end-of-heading)
3716 (outline-flag-region (point)
3717 (progn (org-end-of-subtree t) (point))
3718 flag)))
3720 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3722 (eval-and-compile
3723 (org-autoload "org-archive"
3724 '(org-add-archive-files org-archive-subtree
3725 org-archive-to-archive-sibling org-toggle-archive-tag
3726 org-archive-subtree-default
3727 org-archive-subtree-default-with-confirmation)))
3729 ;; Autoload Column View Code
3731 (declare-function org-columns-number-to-string "org-colview")
3732 (declare-function org-columns-get-format-and-top-level "org-colview")
3733 (declare-function org-columns-compute "org-colview")
3735 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3736 '(org-columns-number-to-string org-columns-get-format-and-top-level
3737 org-columns-compute org-agenda-columns org-columns-remove-overlays
3738 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3740 ;; Autoload ID code
3742 (declare-function org-id-store-link "org-id")
3743 (declare-function org-id-locations-load "org-id")
3744 (declare-function org-id-locations-save "org-id")
3745 (defvar org-id-track-globally)
3746 (org-autoload "org-id"
3747 '(org-id-get-create org-id-new org-id-copy org-id-get
3748 org-id-get-with-outline-path-completion
3749 org-id-get-with-outline-drilling
3750 org-id-goto org-id-find org-id-store-link))
3752 ;; Autoload Plotting Code
3754 (org-autoload "org-plot"
3755 '(org-plot/gnuplot))
3757 ;;; Variables for pre-computed regular expressions, all buffer local
3759 (defvar org-drawer-regexp nil
3760 "Matches first line of a hidden block.")
3761 (make-variable-buffer-local 'org-drawer-regexp)
3762 (defvar org-todo-regexp nil
3763 "Matches any of the TODO state keywords.")
3764 (make-variable-buffer-local 'org-todo-regexp)
3765 (defvar org-not-done-regexp nil
3766 "Matches any of the TODO state keywords except the last one.")
3767 (make-variable-buffer-local 'org-not-done-regexp)
3768 (defvar org-not-done-heading-regexp nil
3769 "Matches a TODO headline that is not done.")
3770 (make-variable-buffer-local 'org-not-done-regexp)
3771 (defvar org-todo-line-regexp nil
3772 "Matches a headline and puts TODO state into group 2 if present.")
3773 (make-variable-buffer-local 'org-todo-line-regexp)
3774 (defvar org-complex-heading-regexp nil
3775 "Matches a headline and puts everything into groups:
3776 group 1: the stars
3777 group 2: The todo keyword, maybe
3778 group 3: Priority cookie
3779 group 4: True headline
3780 group 5: Tags")
3781 (make-variable-buffer-local 'org-complex-heading-regexp)
3782 (defvar org-complex-heading-regexp-format nil)
3783 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3784 (defvar org-todo-line-tags-regexp nil
3785 "Matches a headline and puts TODO state into group 2 if present.
3786 Also put tags into group 4 if tags are present.")
3787 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3788 (defvar org-nl-done-regexp nil
3789 "Matches newline followed by a headline with the DONE keyword.")
3790 (make-variable-buffer-local 'org-nl-done-regexp)
3791 (defvar org-looking-at-done-regexp nil
3792 "Matches the DONE keyword a point.")
3793 (make-variable-buffer-local 'org-looking-at-done-regexp)
3794 (defvar org-ds-keyword-length 12
3795 "Maximum length of the Deadline and SCHEDULED keywords.")
3796 (make-variable-buffer-local 'org-ds-keyword-length)
3797 (defvar org-deadline-regexp nil
3798 "Matches the DEADLINE keyword.")
3799 (make-variable-buffer-local 'org-deadline-regexp)
3800 (defvar org-deadline-time-regexp nil
3801 "Matches the DEADLINE keyword together with a time stamp.")
3802 (make-variable-buffer-local 'org-deadline-time-regexp)
3803 (defvar org-deadline-line-regexp nil
3804 "Matches the DEADLINE keyword and the rest of the line.")
3805 (make-variable-buffer-local 'org-deadline-line-regexp)
3806 (defvar org-scheduled-regexp nil
3807 "Matches the SCHEDULED keyword.")
3808 (make-variable-buffer-local 'org-scheduled-regexp)
3809 (defvar org-scheduled-time-regexp nil
3810 "Matches the SCHEDULED keyword together with a time stamp.")
3811 (make-variable-buffer-local 'org-scheduled-time-regexp)
3812 (defvar org-closed-time-regexp nil
3813 "Matches the CLOSED keyword together with a time stamp.")
3814 (make-variable-buffer-local 'org-closed-time-regexp)
3816 (defvar org-keyword-time-regexp nil
3817 "Matches any of the 4 keywords, together with the time stamp.")
3818 (make-variable-buffer-local 'org-keyword-time-regexp)
3819 (defvar org-keyword-time-not-clock-regexp nil
3820 "Matches any of the 3 keywords, together with the time stamp.")
3821 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3822 (defvar org-maybe-keyword-time-regexp nil
3823 "Matches a timestamp, possibly preceeded by a keyword.")
3824 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3825 (defvar org-planning-or-clock-line-re nil
3826 "Matches a line with planning or clock info.")
3827 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3828 (defvar org-all-time-keywords nil
3829 "List of time keywords.")
3830 (make-variable-buffer-local 'org-all-time-keywords)
3832 (defconst org-plain-time-of-day-regexp
3833 (concat
3834 "\\(\\<[012]?[0-9]"
3835 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3836 "\\(--?"
3837 "\\(\\<[012]?[0-9]"
3838 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3839 "\\)?")
3840 "Regular expression to match a plain time or time range.
3841 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3842 groups carry important information:
3843 0 the full match
3844 1 the first time, range or not
3845 8 the second time, if it is a range.")
3847 (defconst org-plain-time-extension-regexp
3848 (concat
3849 "\\(\\<[012]?[0-9]"
3850 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3851 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3852 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3853 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3854 groups carry important information:
3855 0 the full match
3856 7 hours of duration
3857 9 minutes of duration")
3859 (defconst org-stamp-time-of-day-regexp
3860 (concat
3861 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3862 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3863 "\\(--?"
3864 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3865 "Regular expression to match a timestamp time or time range.
3866 After a match, the following groups carry important information:
3867 0 the full match
3868 1 date plus weekday, for back referencing to make sure both times are on the same day
3869 2 the first time, range or not
3870 4 the second time, if it is a range.")
3872 (defconst org-startup-options
3873 '(("fold" org-startup-folded t)
3874 ("overview" org-startup-folded t)
3875 ("nofold" org-startup-folded nil)
3876 ("showall" org-startup-folded nil)
3877 ("showeverything" org-startup-folded showeverything)
3878 ("content" org-startup-folded content)
3879 ("indent" org-startup-indented t)
3880 ("noindent" org-startup-indented nil)
3881 ("hidestars" org-hide-leading-stars t)
3882 ("showstars" org-hide-leading-stars nil)
3883 ("odd" org-odd-levels-only t)
3884 ("oddeven" org-odd-levels-only nil)
3885 ("align" org-startup-align-all-tables t)
3886 ("noalign" org-startup-align-all-tables nil)
3887 ("customtime" org-display-custom-times t)
3888 ("logdone" org-log-done time)
3889 ("lognotedone" org-log-done note)
3890 ("nologdone" org-log-done nil)
3891 ("lognoteclock-out" org-log-note-clock-out t)
3892 ("nolognoteclock-out" org-log-note-clock-out nil)
3893 ("logrepeat" org-log-repeat state)
3894 ("lognoterepeat" org-log-repeat note)
3895 ("nologrepeat" org-log-repeat nil)
3896 ("logreschedule" org-log-reschedule time)
3897 ("lognotereschedule" org-log-reschedule note)
3898 ("nologreschedule" org-log-reschedule nil)
3899 ("logredeadline" org-log-redeadline time)
3900 ("lognoteredeadline" org-log-redeadline note)
3901 ("nologredeadline" org-log-redeadline nil)
3902 ("logrefile" org-log-refile time)
3903 ("lognoterefile" org-log-refile note)
3904 ("nologrefile" org-log-refile nil)
3905 ("fninline" org-footnote-define-inline t)
3906 ("nofninline" org-footnote-define-inline nil)
3907 ("fnlocal" org-footnote-section nil)
3908 ("fnauto" org-footnote-auto-label t)
3909 ("fnprompt" org-footnote-auto-label nil)
3910 ("fnconfirm" org-footnote-auto-label confirm)
3911 ("fnplain" org-footnote-auto-label plain)
3912 ("fnadjust" org-footnote-auto-adjust t)
3913 ("nofnadjust" org-footnote-auto-adjust nil)
3914 ("constcgs" constants-unit-system cgs)
3915 ("constSI" constants-unit-system SI)
3916 ("noptag" org-tag-persistent-alist nil)
3917 ("hideblocks" org-hide-block-startup t)
3918 ("nohideblocks" org-hide-block-startup nil)
3919 ("beamer" org-startup-with-beamer-mode t))
3920 "Variable associated with STARTUP options for org-mode.
3921 Each element is a list of three items: The startup options as written
3922 in the #+STARTUP line, the corresponding variable, and the value to
3923 set this variable to if the option is found. An optional forth element PUSH
3924 means to push this value onto the list in the variable.")
3926 (defun org-set-regexps-and-options ()
3927 "Precompute regular expressions for current buffer."
3928 (when (org-mode-p)
3929 (org-set-local 'org-todo-kwd-alist nil)
3930 (org-set-local 'org-todo-key-alist nil)
3931 (org-set-local 'org-todo-key-trigger nil)
3932 (org-set-local 'org-todo-keywords-1 nil)
3933 (org-set-local 'org-done-keywords nil)
3934 (org-set-local 'org-todo-heads nil)
3935 (org-set-local 'org-todo-sets nil)
3936 (org-set-local 'org-todo-log-states nil)
3937 (org-set-local 'org-file-properties nil)
3938 (org-set-local 'org-file-tags nil)
3939 (let ((re (org-make-options-regexp
3940 '("CATEGORY" "TODO" "COLUMNS"
3941 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3942 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS")
3943 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3944 (splitre "[ \t]+")
3945 kwds kws0 kwsa key log value cat arch tags const links hw dws
3946 tail sep kws1 prio props ftags drawers beamer-p
3947 ext-setup-or-nil setup-contents (start 0))
3948 (save-excursion
3949 (save-restriction
3950 (widen)
3951 (goto-char (point-min))
3952 (while (or (and ext-setup-or-nil
3953 (string-match re ext-setup-or-nil start)
3954 (setq start (match-end 0)))
3955 (and (setq ext-setup-or-nil nil start 0)
3956 (re-search-forward re nil t)))
3957 (setq key (upcase (match-string 1 ext-setup-or-nil))
3958 value (org-match-string-no-properties 2 ext-setup-or-nil))
3959 (cond
3960 ((equal key "CATEGORY")
3961 (if (string-match "[ \t]+$" value)
3962 (setq value (replace-match "" t t value)))
3963 (setq cat value))
3964 ((member key '("SEQ_TODO" "TODO"))
3965 (push (cons 'sequence (org-split-string value splitre)) kwds))
3966 ((equal key "TYP_TODO")
3967 (push (cons 'type (org-split-string value splitre)) kwds))
3968 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3969 ;; general TODO-like setup
3970 (push (cons (intern (downcase (match-string 1 key)))
3971 (org-split-string value splitre)) kwds))
3972 ((equal key "TAGS")
3973 (setq tags (append tags (if tags '("\\n") nil)
3974 (org-split-string value splitre))))
3975 ((equal key "COLUMNS")
3976 (org-set-local 'org-columns-default-format value))
3977 ((equal key "LINK")
3978 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3979 (push (cons (match-string 1 value)
3980 (org-trim (match-string 2 value)))
3981 links)))
3982 ((equal key "PRIORITIES")
3983 (setq prio (org-split-string value " +")))
3984 ((equal key "PROPERTY")
3985 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3986 (push (cons (match-string 1 value) (match-string 2 value))
3987 props)))
3988 ((equal key "FILETAGS")
3989 (when (string-match "\\S-" value)
3990 (setq ftags
3991 (append
3992 ftags
3993 (apply 'append
3994 (mapcar (lambda (x) (org-split-string x ":"))
3995 (org-split-string value)))))))
3996 ((equal key "DRAWERS")
3997 (setq drawers (org-split-string value splitre)))
3998 ((equal key "CONSTANTS")
3999 (setq const (append const (org-split-string value splitre))))
4000 ((equal key "STARTUP")
4001 (let ((opts (org-split-string value splitre))
4002 l var val)
4003 (while (setq l (pop opts))
4004 (when (setq l (assoc l org-startup-options))
4005 (setq var (nth 1 l) val (nth 2 l))
4006 (if (not (nth 3 l))
4007 (set (make-local-variable var) val)
4008 (if (not (listp (symbol-value var)))
4009 (set (make-local-variable var) nil))
4010 (set (make-local-variable var) (symbol-value var))
4011 (add-to-list var val))))))
4012 ((equal key "ARCHIVE")
4013 (string-match " *$" value)
4014 (setq arch (replace-match "" t t value))
4015 (remove-text-properties 0 (length arch)
4016 '(face t fontified t) arch))
4017 ((equal key "LATEX_CLASS")
4018 (setq beamer-p (equal value "beamer")))
4019 ((equal key "SETUPFILE")
4020 (setq setup-contents (org-file-contents
4021 (expand-file-name
4022 (org-remove-double-quotes value))
4023 'noerror))
4024 (if (not ext-setup-or-nil)
4025 (setq ext-setup-or-nil setup-contents start 0)
4026 (setq ext-setup-or-nil
4027 (concat (substring ext-setup-or-nil 0 start)
4028 "\n" setup-contents "\n"
4029 (substring ext-setup-or-nil start)))))
4030 ))))
4031 (when cat
4032 (org-set-local 'org-category (intern cat))
4033 (push (cons "CATEGORY" cat) props))
4034 (when prio
4035 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4036 (setq prio (mapcar 'string-to-char prio))
4037 (org-set-local 'org-highest-priority (nth 0 prio))
4038 (org-set-local 'org-lowest-priority (nth 1 prio))
4039 (org-set-local 'org-default-priority (nth 2 prio)))
4040 (and props (org-set-local 'org-file-properties (nreverse props)))
4041 (and ftags (org-set-local 'org-file-tags
4042 (mapcar 'org-add-prop-inherited ftags)))
4043 (and drawers (org-set-local 'org-drawers drawers))
4044 (and arch (org-set-local 'org-archive-location arch))
4045 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4046 ;; Process the TODO keywords
4047 (unless kwds
4048 ;; Use the global values as if they had been given locally.
4049 (setq kwds (default-value 'org-todo-keywords))
4050 (if (stringp (car kwds))
4051 (setq kwds (list (cons org-todo-interpretation
4052 (default-value 'org-todo-keywords)))))
4053 (setq kwds (reverse kwds)))
4054 (setq kwds (nreverse kwds))
4055 (let (inter kws kw)
4056 (while (setq kws (pop kwds))
4057 (let ((kws (or
4058 (run-hook-with-args-until-success
4059 'org-todo-setup-filter-hook kws)
4060 kws)))
4061 (setq inter (pop kws) sep (member "|" kws)
4062 kws0 (delete "|" (copy-sequence kws))
4063 kwsa nil
4064 kws1 (mapcar
4065 (lambda (x)
4066 ;; 1 2
4067 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4068 (progn
4069 (setq kw (match-string 1 x)
4070 key (and (match-end 2) (match-string 2 x))
4071 log (org-extract-log-state-settings x))
4072 (push (cons kw (and key (string-to-char key))) kwsa)
4073 (and log (push log org-todo-log-states))
4075 (error "Invalid TODO keyword %s" x)))
4076 kws0)
4077 kwsa (if kwsa (append '((:startgroup))
4078 (nreverse kwsa)
4079 '((:endgroup))))
4080 hw (car kws1)
4081 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4082 tail (list inter hw (car dws) (org-last dws))))
4083 (add-to-list 'org-todo-heads hw 'append)
4084 (push kws1 org-todo-sets)
4085 (setq org-done-keywords (append org-done-keywords dws nil))
4086 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4087 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4088 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4089 (setq org-todo-sets (nreverse org-todo-sets)
4090 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4091 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4092 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4093 ;; Process the constants
4094 (when const
4095 (let (e cst)
4096 (while (setq e (pop const))
4097 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4098 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4099 (setq org-table-formula-constants-local cst)))
4101 ;; Process the tags.
4102 (when tags
4103 (let (e tgs)
4104 (while (setq e (pop tags))
4105 (cond
4106 ((equal e "{") (push '(:startgroup) tgs))
4107 ((equal e "}") (push '(:endgroup) tgs))
4108 ((equal e "\\n") (push '(:newline) tgs))
4109 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4110 (push (cons (match-string 1 e)
4111 (string-to-char (match-string 2 e)))
4112 tgs))
4113 (t (push (list e) tgs))))
4114 (org-set-local 'org-tag-alist nil)
4115 (while (setq e (pop tgs))
4116 (or (and (stringp (car e))
4117 (assoc (car e) org-tag-alist))
4118 (push e org-tag-alist)))))
4120 ;; Compute the regular expressions and other local variables
4121 (if (not org-done-keywords)
4122 (setq org-done-keywords (and org-todo-keywords-1
4123 (list (org-last org-todo-keywords-1)))))
4124 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4125 (length org-scheduled-string)
4126 (length org-clock-string)
4127 (length org-closed-string)))
4128 org-drawer-regexp
4129 (concat "^[ \t]*:\\("
4130 (mapconcat 'regexp-quote org-drawers "\\|")
4131 "\\):[ \t]*$")
4132 org-not-done-keywords
4133 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4134 org-todo-regexp
4135 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4136 "\\|") "\\)\\>")
4137 org-not-done-regexp
4138 (concat "\\<\\("
4139 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4140 "\\)\\>")
4141 org-not-done-heading-regexp
4142 (concat "^\\(\\*+\\)[ \t]+\\("
4143 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4144 "\\)\\>")
4145 org-todo-line-regexp
4146 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4147 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4148 "\\)\\>\\)?[ \t]*\\(.*\\)")
4149 org-complex-heading-regexp
4150 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4151 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4152 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4153 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4154 org-complex-heading-regexp-format
4155 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4156 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4157 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
4158 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4159 org-nl-done-regexp
4160 (concat "\n\\*+[ \t]+"
4161 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4162 "\\)" "\\>")
4163 org-todo-line-tags-regexp
4164 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4165 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4166 (org-re
4167 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4168 org-looking-at-done-regexp
4169 (concat "^" "\\(?:"
4170 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4171 "\\>")
4172 org-deadline-regexp (concat "\\<" org-deadline-string)
4173 org-deadline-time-regexp
4174 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4175 org-deadline-line-regexp
4176 (concat "\\<\\(" org-deadline-string "\\).*")
4177 org-scheduled-regexp
4178 (concat "\\<" org-scheduled-string)
4179 org-scheduled-time-regexp
4180 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4181 org-closed-time-regexp
4182 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4183 org-keyword-time-regexp
4184 (concat "\\<\\(" org-scheduled-string
4185 "\\|" org-deadline-string
4186 "\\|" org-closed-string
4187 "\\|" org-clock-string "\\)"
4188 " *[[<]\\([^]>]+\\)[]>]")
4189 org-keyword-time-not-clock-regexp
4190 (concat "\\<\\(" org-scheduled-string
4191 "\\|" org-deadline-string
4192 "\\|" org-closed-string
4193 "\\)"
4194 " *[[<]\\([^]>]+\\)[]>]")
4195 org-maybe-keyword-time-regexp
4196 (concat "\\(\\<\\(" org-scheduled-string
4197 "\\|" org-deadline-string
4198 "\\|" org-closed-string
4199 "\\|" org-clock-string "\\)\\)?"
4200 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4201 org-planning-or-clock-line-re
4202 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4203 "\\|" org-deadline-string
4204 "\\|" org-closed-string "\\|" org-clock-string
4205 "\\)\\>\\)")
4206 org-all-time-keywords
4207 (mapcar (lambda (w) (substring w 0 -1))
4208 (list org-scheduled-string org-deadline-string
4209 org-clock-string org-closed-string))
4211 (org-compute-latex-and-specials-regexp)
4212 (org-set-font-lock-defaults))))
4214 (defun org-file-contents (file &optional noerror)
4215 "Return the contents of FILE, as a string."
4216 (if (or (not file)
4217 (not (file-readable-p file)))
4218 (if noerror
4219 (progn
4220 (message "Cannot read file %s" file)
4221 (ding) (sit-for 2)
4223 (error "Cannot read file %s" file))
4224 (with-temp-buffer
4225 (insert-file-contents file)
4226 (buffer-string))))
4228 (defun org-extract-log-state-settings (x)
4229 "Extract the log state setting from a TODO keyword string.
4230 This will extract info from a string like \"WAIT(w@/!)\"."
4231 (let (kw key log1 log2)
4232 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4233 (setq kw (match-string 1 x)
4234 key (and (match-end 2) (match-string 2 x))
4235 log1 (and (match-end 3) (match-string 3 x))
4236 log2 (and (match-end 4) (match-string 4 x)))
4237 (and (or log1 log2)
4238 (list kw
4239 (and log1 (if (equal log1 "!") 'time 'note))
4240 (and log2 (if (equal log2 "!") 'time 'note)))))))
4242 (defun org-remove-keyword-keys (list)
4243 "Remove a pair of parenthesis at the end of each string in LIST."
4244 (mapcar (lambda (x)
4245 (if (string-match "(.*)$" x)
4246 (substring x 0 (match-beginning 0))
4248 list))
4250 (defun org-assign-fast-keys (alist)
4251 "Assign fast keys to a keyword-key alist.
4252 Respect keys that are already there."
4253 (let (new e (alt ?0))
4254 (while (setq e (pop alist))
4255 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4256 (cdr e)) ;; Key already assigned.
4257 (push e new)
4258 (let ((clist (string-to-list (downcase (car e))))
4259 (used (append new alist)))
4260 (when (= (car clist) ?@)
4261 (pop clist))
4262 (while (and clist (rassoc (car clist) used))
4263 (pop clist))
4264 (unless clist
4265 (while (rassoc alt used)
4266 (incf alt)))
4267 (push (cons (car e) (or (car clist) alt)) new))))
4268 (nreverse new)))
4270 ;;; Some variables used in various places
4272 (defvar org-window-configuration nil
4273 "Used in various places to store a window configuration.")
4274 (defvar org-selected-window nil
4275 "Used in various places to store a window configuration.")
4276 (defvar org-finish-function nil
4277 "Function to be called when `C-c C-c' is used.
4278 This is for getting out of special buffers like remember.")
4281 ;; FIXME: Occasionally check by commenting these, to make sure
4282 ;; no other functions uses these, forgetting to let-bind them.
4283 (defvar entry)
4284 (defvar last-state)
4285 (defvar date)
4287 ;; Defined somewhere in this file, but used before definition.
4288 (defvar org-entities) ;; defined in org-entities.el
4289 (defvar org-struct-menu)
4290 (defvar org-org-menu)
4291 (defvar org-tbl-menu)
4293 ;;;; Define the Org-mode
4295 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4296 (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."))
4299 ;; We use a before-change function to check if a table might need
4300 ;; an update.
4301 (defvar org-table-may-need-update t
4302 "Indicates that a table might need an update.
4303 This variable is set by `org-before-change-function'.
4304 `org-table-align' sets it back to nil.")
4305 (defun org-before-change-function (beg end)
4306 "Every change indicates that a table might need an update."
4307 (setq org-table-may-need-update t))
4308 (defvar org-mode-map)
4309 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4310 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4311 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4312 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4313 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4314 (defvar org-table-buffer-is-an nil)
4315 (defconst org-outline-regexp "\\*+ ")
4317 ;;;###autoload
4318 (define-derived-mode org-mode outline-mode "Org"
4319 "Outline-based notes management and organizer, alias
4320 \"Carsten's outline-mode for keeping track of everything.\"
4322 Org-mode develops organizational tasks around a NOTES file which
4323 contains information about projects as plain text. Org-mode is
4324 implemented on top of outline-mode, which is ideal to keep the content
4325 of large files well structured. It supports ToDo items, deadlines and
4326 time stamps, which magically appear in the diary listing of the Emacs
4327 calendar. Tables are easily created with a built-in table editor.
4328 Plain text URL-like links connect to websites, emails (VM), Usenet
4329 messages (Gnus), BBDB entries, and any files related to the project.
4330 For printing and sharing of notes, an Org-mode file (or a part of it)
4331 can be exported as a structured ASCII or HTML file.
4333 The following commands are available:
4335 \\{org-mode-map}"
4337 ;; Get rid of Outline menus, they are not needed
4338 ;; Need to do this here because define-derived-mode sets up
4339 ;; the keymap so late. Still, it is a waste to call this each time
4340 ;; we switch another buffer into org-mode.
4341 (if (featurep 'xemacs)
4342 (when (boundp 'outline-mode-menu-heading)
4343 ;; Assume this is Greg's port, it used easymenu
4344 (easy-menu-remove outline-mode-menu-heading)
4345 (easy-menu-remove outline-mode-menu-show)
4346 (easy-menu-remove outline-mode-menu-hide))
4347 (define-key org-mode-map [menu-bar headings] 'undefined)
4348 (define-key org-mode-map [menu-bar hide] 'undefined)
4349 (define-key org-mode-map [menu-bar show] 'undefined))
4351 (org-load-modules-maybe)
4352 (easy-menu-add org-org-menu)
4353 (easy-menu-add org-tbl-menu)
4354 (org-install-agenda-files-menu)
4355 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4356 (org-add-to-invisibility-spec '(org-cwidth))
4357 (org-add-to-invisibility-spec '(org-hide-block . t))
4358 (when (featurep 'xemacs)
4359 (org-set-local 'line-move-ignore-invisible t))
4360 (org-set-local 'outline-regexp org-outline-regexp)
4361 (org-set-local 'outline-level 'org-outline-level)
4362 (when (and org-ellipsis
4363 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4364 (fboundp 'make-glyph-code))
4365 (unless org-display-table
4366 (setq org-display-table (make-display-table)))
4367 (set-display-table-slot
4368 org-display-table 4
4369 (vconcat (mapcar
4370 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4371 org-ellipsis)))
4372 (if (stringp org-ellipsis) org-ellipsis "..."))))
4373 (setq buffer-display-table org-display-table))
4374 (org-set-regexps-and-options)
4375 (when (and org-tag-faces (not org-tags-special-faces-re))
4376 ;; tag faces set outside customize.... force initialization.
4377 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4378 ;; Calc embedded
4379 (org-set-local 'calc-embedded-open-mode "# ")
4380 (modify-syntax-entry ?# "<")
4381 (modify-syntax-entry ?@ "w")
4382 (if org-startup-truncated (setq truncate-lines t))
4383 (org-set-local 'font-lock-unfontify-region-function
4384 'org-unfontify-region)
4385 ;; Activate before-change-function
4386 (org-set-local 'org-table-may-need-update t)
4387 (org-add-hook 'before-change-functions 'org-before-change-function nil
4388 'local)
4389 ;; Check for running clock before killing a buffer
4390 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4391 ;; Paragraphs and auto-filling
4392 (org-set-autofill-regexps)
4393 (setq indent-line-function 'org-indent-line-function)
4394 (org-update-radio-target-regexp)
4395 ;; Make sure dependence stuff works reliably, even for users who set it
4396 ;; too late :-(
4397 (if org-enforce-todo-dependencies
4398 (add-hook 'org-blocker-hook
4399 'org-block-todo-from-children-or-siblings-or-parent)
4400 (remove-hook 'org-blocker-hook
4401 'org-block-todo-from-children-or-siblings-or-parent))
4402 (if org-enforce-todo-checkbox-dependencies
4403 (add-hook 'org-blocker-hook
4404 'org-block-todo-from-checkboxes)
4405 (remove-hook 'org-blocker-hook
4406 'org-block-todo-from-checkboxes))
4408 ;; Comment characters
4409 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4410 (org-set-local 'comment-padding " ")
4412 ;; Align options lines
4413 (org-set-local
4414 'align-mode-rules-list
4415 '((org-in-buffer-settings
4416 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4417 (modes . '(org-mode)))))
4419 ;; Imenu
4420 (org-set-local 'imenu-create-index-function
4421 'org-imenu-get-tree)
4423 ;; Make isearch reveal context
4424 (if (or (featurep 'xemacs)
4425 (not (boundp 'outline-isearch-open-invisible-function)))
4426 ;; Emacs 21 and XEmacs make use of the hook
4427 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4428 ;; Emacs 22 deals with this through a special variable
4429 (org-set-local 'outline-isearch-open-invisible-function
4430 (lambda (&rest ignore) (org-show-context 'isearch))))
4432 ;; Turn on org-beamer-mode?
4433 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4435 ;; If empty file that did not turn on org-mode automatically, make it to.
4436 (if (and org-insert-mode-line-in-empty-file
4437 (interactive-p)
4438 (= (point-min) (point-max)))
4439 (insert "# -*- mode: org -*-\n\n"))
4440 (unless org-inhibit-startup
4441 (when org-startup-align-all-tables
4442 (let ((bmp (buffer-modified-p)))
4443 (org-table-map-tables 'org-table-align)
4444 (set-buffer-modified-p bmp)))
4445 (when org-startup-indented
4446 (require 'org-indent)
4447 (org-indent-mode 1))
4448 (unless org-inhibit-startup-visibility-stuff
4449 (org-set-startup-visibility))))
4451 (when (fboundp 'abbrev-table-put)
4452 (abbrev-table-put org-mode-abbrev-table
4453 :parents (list text-mode-abbrev-table)))
4455 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4457 (defun org-current-time ()
4458 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4459 (if (> (car org-time-stamp-rounding-minutes) 1)
4460 (let ((r (car org-time-stamp-rounding-minutes))
4461 (time (decode-time)))
4462 (apply 'encode-time
4463 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4464 (nthcdr 2 time))))
4465 (current-time)))
4467 ;;;; Font-Lock stuff, including the activators
4469 (defvar org-mouse-map (make-sparse-keymap))
4470 (org-defkey org-mouse-map
4471 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4472 (org-defkey org-mouse-map
4473 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4474 (when org-mouse-1-follows-link
4475 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4476 (when org-tab-follows-link
4477 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4478 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4480 (require 'font-lock)
4482 (defconst org-non-link-chars "]\t\n\r<>")
4483 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4484 "shell" "elisp"))
4485 (defvar org-link-types-re nil
4486 "Matches a link that has a url-like prefix like \"http:\"")
4487 (defvar org-link-re-with-space nil
4488 "Matches a link with spaces, optional angular brackets around it.")
4489 (defvar org-link-re-with-space2 nil
4490 "Matches a link with spaces, optional angular brackets around it.")
4491 (defvar org-link-re-with-space3 nil
4492 "Matches a link with spaces, only for internal part in bracket links.")
4493 (defvar org-angle-link-re nil
4494 "Matches link with angular brackets, spaces are allowed.")
4495 (defvar org-plain-link-re nil
4496 "Matches plain link, without spaces.")
4497 (defvar org-bracket-link-regexp nil
4498 "Matches a link in double brackets.")
4499 (defvar org-bracket-link-analytic-regexp nil
4500 "Regular expression used to analyze links.
4501 Here is what the match groups contain after a match:
4502 1: http:
4503 2: http
4504 3: path
4505 4: [desc]
4506 5: desc")
4507 (defvar org-bracket-link-analytic-regexp++ nil
4508 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4509 (defvar org-any-link-re nil
4510 "Regular expression matching any link.")
4512 (defun org-make-link-regexps ()
4513 "Update the link regular expressions.
4514 This should be called after the variable `org-link-types' has changed."
4515 (setq org-link-types-re
4516 (concat
4517 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4518 org-link-re-with-space
4519 (concat
4520 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4521 "\\([^" org-non-link-chars " ]"
4522 "[^" org-non-link-chars "]*"
4523 "[^" org-non-link-chars " ]\\)>?")
4524 org-link-re-with-space2
4525 (concat
4526 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4527 "\\([^" org-non-link-chars " ]"
4528 "[^\t\n\r]*"
4529 "[^" org-non-link-chars " ]\\)>?")
4530 org-link-re-with-space3
4531 (concat
4532 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4533 "\\([^" org-non-link-chars " ]"
4534 "[^\t\n\r]*\\)")
4535 org-angle-link-re
4536 (concat
4537 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4538 "\\([^" org-non-link-chars " ]"
4539 "[^" org-non-link-chars "]*"
4540 "\\)>")
4541 org-plain-link-re
4542 (concat
4543 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4544 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4545 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4546 org-bracket-link-regexp
4547 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4548 org-bracket-link-analytic-regexp
4549 (concat
4550 "\\[\\["
4551 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4552 "\\([^]]+\\)"
4553 "\\]"
4554 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4555 "\\]")
4556 org-bracket-link-analytic-regexp++
4557 (concat
4558 "\\[\\["
4559 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4560 "\\([^]]+\\)"
4561 "\\]"
4562 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4563 "\\]")
4564 org-any-link-re
4565 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4566 org-angle-link-re "\\)\\|\\("
4567 org-plain-link-re "\\)")))
4569 (org-make-link-regexps)
4571 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4572 "Regular expression for fast time stamp matching.")
4573 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4574 "Regular expression for fast time stamp matching.")
4575 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4576 "Regular expression matching time strings for analysis.
4577 This one does not require the space after the date, so it can be used
4578 on a string that terminates immediately after the date.")
4579 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4580 "Regular expression matching time strings for analysis.")
4581 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4582 "Regular expression matching time stamps, with groups.")
4583 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4584 "Regular expression matching time stamps (also [..]), with groups.")
4585 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4586 "Regular expression matching a time stamp range.")
4587 (defconst org-tr-regexp-both
4588 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4589 "Regular expression matching a time stamp range.")
4590 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4591 org-ts-regexp "\\)?")
4592 "Regular expression matching a time stamp or time stamp range.")
4593 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4594 org-ts-regexp-both "\\)?")
4595 "Regular expression matching a time stamp or time stamp range.
4596 The time stamps may be either active or inactive.")
4598 (defvar org-emph-face nil)
4600 (defun org-do-emphasis-faces (limit)
4601 "Run through the buffer and add overlays to links."
4602 (let (rtn a)
4603 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4604 (if (not (= (char-after (match-beginning 3))
4605 (char-after (match-beginning 4))))
4606 (progn
4607 (setq rtn t)
4608 (setq a (assoc (match-string 3) org-emphasis-alist))
4609 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4610 'face
4611 (nth 1 a))
4612 (and (nth 4 a)
4613 (org-remove-flyspell-overlays-in
4614 (match-beginning 0) (match-end 0)))
4615 (add-text-properties (match-beginning 2) (match-end 2)
4616 '(font-lock-multiline t))
4617 (when org-hide-emphasis-markers
4618 (add-text-properties (match-end 4) (match-beginning 5)
4619 '(invisible org-link))
4620 (add-text-properties (match-beginning 3) (match-end 3)
4621 '(invisible org-link)))))
4622 (backward-char 1))
4623 rtn))
4625 (defun org-emphasize (&optional char)
4626 "Insert or change an emphasis, i.e. a font like bold or italic.
4627 If there is an active region, change that region to a new emphasis.
4628 If there is no region, just insert the marker characters and position
4629 the cursor between them.
4630 CHAR should be either the marker character, or the first character of the
4631 HTML tag associated with that emphasis. If CHAR is a space, the means
4632 to remove the emphasis of the selected region.
4633 If char is not given (for example in an interactive call) it
4634 will be prompted for."
4635 (interactive)
4636 (let ((eal org-emphasis-alist) e det
4637 (erc org-emphasis-regexp-components)
4638 (prompt "")
4639 (string "") beg end move tag c s)
4640 (if (org-region-active-p)
4641 (setq beg (region-beginning) end (region-end)
4642 string (buffer-substring beg end))
4643 (setq move t))
4645 (while (setq e (pop eal))
4646 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4647 c (aref tag 0))
4648 (push (cons c (string-to-char (car e))) det)
4649 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4650 (substring tag 1)))))
4651 (setq det (nreverse det))
4652 (unless char
4653 (message "%s" (concat "Emphasis marker or tag:" prompt))
4654 (setq char (read-char-exclusive)))
4655 (setq char (or (cdr (assoc char det)) char))
4656 (if (equal char ?\ )
4657 (setq s "" move nil)
4658 (unless (assoc (char-to-string char) org-emphasis-alist)
4659 (error "No such emphasis marker: \"%c\"" char))
4660 (setq s (char-to-string char)))
4661 (while (and (> (length string) 1)
4662 (equal (substring string 0 1) (substring string -1))
4663 (assoc (substring string 0 1) org-emphasis-alist))
4664 (setq string (substring string 1 -1)))
4665 (setq string (concat s string s))
4666 (if beg (delete-region beg end))
4667 (unless (or (bolp)
4668 (string-match (concat "[" (nth 0 erc) "\n]")
4669 (char-to-string (char-before (point)))))
4670 (insert " "))
4671 (unless (or (eobp)
4672 (string-match (concat "[" (nth 1 erc) "\n]")
4673 (char-to-string (char-after (point)))))
4674 (insert " ") (backward-char 1))
4675 (insert string)
4676 (and move (backward-char 1))))
4678 (defconst org-nonsticky-props
4679 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4681 (defsubst org-rear-nonsticky-at (pos)
4682 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4684 (defun org-activate-plain-links (limit)
4685 "Run through the buffer and add overlays to links."
4686 (catch 'exit
4687 (let (f)
4688 (if (re-search-forward org-plain-link-re limit t)
4689 (progn
4690 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4691 (setq f (get-text-property (match-beginning 0) 'face))
4692 (if (or (eq f 'org-tag)
4693 (and (listp f) (memq 'org-tag f)))
4695 (add-text-properties (match-beginning 0) (match-end 0)
4696 (list 'mouse-face 'highlight
4697 'face 'org-link
4698 'keymap org-mouse-map))
4699 (org-rear-nonsticky-at (match-end 0)))
4700 t)))))
4702 (defun org-activate-code (limit)
4703 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4704 (progn
4705 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4706 (remove-text-properties (match-beginning 0) (match-end 0)
4707 '(display t invisible t intangible t))
4708 t)))
4710 (defun org-fontify-meta-lines-and-blocks (limit)
4711 "Fontify #+ lines and blocks, in the correct ways."
4712 (let ((case-fold-search t))
4713 (if (re-search-forward
4714 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4715 limit t)
4716 (let ((beg (match-beginning 0))
4717 (beg1 (line-beginning-position 2))
4718 (dc1 (downcase (match-string 2)))
4719 (dc3 (downcase (match-string 3)))
4720 end end1 quoting block-type)
4721 (cond
4722 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4723 ;; a single line of backend-specific content
4724 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4725 (remove-text-properties (match-beginning 0) (match-end 0)
4726 '(display t invisible t intangible t))
4727 (add-text-properties (match-beginning 1) (match-end 3)
4728 '(font-lock-fontified t face org-meta-line))
4729 (add-text-properties (match-beginning 6) (match-end 6)
4730 '(font-lock-fontified t face org-block))
4732 ((and (match-end 4) (equal dc3 "begin"))
4733 ;; Truely a block
4734 (setq block-type (downcase (match-string 5))
4735 quoting (member block-type org-protecting-blocks))
4736 (when (re-search-forward
4737 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4738 nil t) ;; on purpose, we look further than LIMIT
4739 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4740 (when quoting
4741 (remove-text-properties beg end
4742 '(display t invisible t intangible t)))
4743 (add-text-properties
4744 beg end
4745 '(font-lock-fontified t font-lock-multiline t))
4746 (add-text-properties beg beg1 '(face org-meta-line))
4747 (add-text-properties end1 end '(face org-meta-line))
4748 (cond
4749 (quoting
4750 (add-text-properties beg1 end1 '(face org-block)))
4751 ((not org-fontify-quote-and-verse-blocks))
4752 ((string= block-type "quote")
4753 (add-text-properties beg1 end1 '(face org-quote)))
4754 ((string= block-type "verse")
4755 (add-text-properties beg1 end1 '(face org-verse))))
4757 ((member dc1 '("title:" "author:" "email:" "date:"))
4758 (add-text-properties
4759 beg (match-end 3)
4760 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
4761 '(font-lock-fontified t invisible t)
4762 '(font-lock-fontified t face org-document-info-keyword)))
4763 (add-text-properties
4764 (match-beginning 6) (match-end 6)
4765 (if (string-equal dc1 "title:")
4766 '(font-lock-fontified t face org-document-title)
4767 '(font-lock-fontified t face org-document-info))))
4768 ((not (member (char-after beg) '(?\ ?\t)))
4769 ;; just any other in-buffer setting, but not indented
4770 (add-text-properties
4771 beg (match-end 0)
4772 '(font-lock-fontified t face org-meta-line))
4774 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4775 "orgtbl:" "tblfm:" "tblname:"))
4776 (and (match-end 4) (equal dc3 "attr")))
4777 (add-text-properties
4778 beg (match-end 0)
4779 '(font-lock-fontified t face org-meta-line))
4781 ((member dc3 '(" " ""))
4782 (add-text-properties
4783 beg (match-end 0)
4784 '(font-lock-fontified t face font-lock-comment-face)))
4785 (t nil))))))
4787 (defun org-activate-angle-links (limit)
4788 "Run through the buffer and add overlays to links."
4789 (if (re-search-forward org-angle-link-re limit t)
4790 (progn
4791 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4792 (add-text-properties (match-beginning 0) (match-end 0)
4793 (list 'mouse-face 'highlight
4794 'keymap org-mouse-map))
4795 (org-rear-nonsticky-at (match-end 0))
4796 t)))
4798 (defun org-activate-footnote-links (limit)
4799 "Run through the buffer and add overlays to links."
4800 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4801 limit t)
4802 (progn
4803 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4804 (add-text-properties (match-beginning 2) (match-end 2)
4805 (list 'mouse-face 'highlight
4806 'keymap org-mouse-map
4807 'help-echo
4808 (if (= (point-at-bol) (match-beginning 2))
4809 "Footnote definition"
4810 "Footnote reference")
4812 (org-rear-nonsticky-at (match-end 2))
4813 t)))
4815 (defun org-activate-bracket-links (limit)
4816 "Run through the buffer and add overlays to bracketed links."
4817 (if (re-search-forward org-bracket-link-regexp limit t)
4818 (let* ((help (concat "LINK: "
4819 (org-match-string-no-properties 1)))
4820 ;; FIXME: above we should remove the escapes.
4821 ;; but that requires another match, protecting match data,
4822 ;; a lot of overhead for font-lock.
4823 (ip (org-maybe-intangible
4824 (list 'invisible 'org-link
4825 'keymap org-mouse-map 'mouse-face 'highlight
4826 'font-lock-multiline t 'help-echo help)))
4827 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4828 'font-lock-multiline t 'help-echo help)))
4829 ;; We need to remove the invisible property here. Table narrowing
4830 ;; may have made some of this invisible.
4831 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4832 (remove-text-properties (match-beginning 0) (match-end 0)
4833 '(invisible nil))
4834 (if (match-end 3)
4835 (progn
4836 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4837 (org-rear-nonsticky-at (match-beginning 3))
4838 (add-text-properties (match-beginning 3) (match-end 3) vp)
4839 (org-rear-nonsticky-at (match-end 3))
4840 (add-text-properties (match-end 3) (match-end 0) ip)
4841 (org-rear-nonsticky-at (match-end 0)))
4842 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4843 (org-rear-nonsticky-at (match-beginning 1))
4844 (add-text-properties (match-beginning 1) (match-end 1) vp)
4845 (org-rear-nonsticky-at (match-end 1))
4846 (add-text-properties (match-end 1) (match-end 0) ip)
4847 (org-rear-nonsticky-at (match-end 0)))
4848 t)))
4850 (defun org-activate-dates (limit)
4851 "Run through the buffer and add overlays to dates."
4852 (if (re-search-forward org-tsr-regexp-both limit t)
4853 (progn
4854 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4855 (add-text-properties (match-beginning 0) (match-end 0)
4856 (list 'mouse-face 'highlight
4857 'keymap org-mouse-map))
4858 (org-rear-nonsticky-at (match-end 0))
4859 (when org-display-custom-times
4860 (if (match-end 3)
4861 (org-display-custom-time (match-beginning 3) (match-end 3)))
4862 (org-display-custom-time (match-beginning 1) (match-end 1)))
4863 t)))
4865 (defvar org-target-link-regexp nil
4866 "Regular expression matching radio targets in plain text.")
4867 (make-variable-buffer-local 'org-target-link-regexp)
4868 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4869 "Regular expression matching a link target.")
4870 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4871 "Regular expression matching a radio target.")
4872 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4873 "Regular expression matching any target.")
4875 (defun org-activate-target-links (limit)
4876 "Run through the buffer and add overlays to target matches."
4877 (when org-target-link-regexp
4878 (let ((case-fold-search t))
4879 (if (re-search-forward org-target-link-regexp limit t)
4880 (progn
4881 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4882 (add-text-properties (match-beginning 0) (match-end 0)
4883 (list 'mouse-face 'highlight
4884 'keymap org-mouse-map
4885 'help-echo "Radio target link"
4886 'org-linked-text t))
4887 (org-rear-nonsticky-at (match-end 0))
4888 t)))))
4890 (defun org-update-radio-target-regexp ()
4891 "Find all radio targets in this file and update the regular expression."
4892 (interactive)
4893 (when (memq 'radio org-activate-links)
4894 (setq org-target-link-regexp
4895 (org-make-target-link-regexp (org-all-targets 'radio)))
4896 (org-restart-font-lock)))
4898 (defun org-hide-wide-columns (limit)
4899 (let (s e)
4900 (setq s (text-property-any (point) (or limit (point-max))
4901 'org-cwidth t))
4902 (when s
4903 (setq e (next-single-property-change s 'org-cwidth))
4904 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4905 (goto-char e)
4906 t)))
4908 (defvar org-latex-and-specials-regexp nil
4909 "Regular expression for highlighting export special stuff.")
4910 (defvar org-match-substring-regexp)
4911 (defvar org-match-substring-with-braces-regexp)
4913 ;; This should be with the exporter code, but we also use if for font-locking
4914 (defconst org-export-html-special-string-regexps
4915 '(("\\\\-" . "&shy;")
4916 ("---\\([^-]\\)" . "&mdash;\\1")
4917 ("--\\([^-]\\)" . "&ndash;\\1")
4918 ("\\.\\.\\." . "&hellip;"))
4919 "Regular expressions for special string conversion.")
4922 (defun org-compute-latex-and-specials-regexp ()
4923 "Compute regular expression for stuff treated specially by exporters."
4924 (if (not org-highlight-latex-fragments-and-specials)
4925 (org-set-local 'org-latex-and-specials-regexp nil)
4926 (require 'org-exp)
4927 (let*
4928 ((matchers (plist-get org-format-latex-options :matchers))
4929 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4930 org-latex-regexps)))
4931 (org-export-allow-BIND nil)
4932 (options (org-combine-plists (org-default-export-plist)
4933 (org-infile-export-plist)))
4934 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4935 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4936 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4937 (org-export-html-expand (plist-get options :expand-quoted-html))
4938 (org-export-with-special-strings (plist-get options :special-strings))
4939 (re-sub
4940 (cond
4941 ((equal org-export-with-sub-superscripts '{})
4942 (list org-match-substring-with-braces-regexp))
4943 (org-export-with-sub-superscripts
4944 (list org-match-substring-regexp))
4945 (t nil)))
4946 (re-latex
4947 (if org-export-with-LaTeX-fragments
4948 (mapcar (lambda (x) (nth 1 x)) latexs)))
4949 (re-macros
4950 (if org-export-with-TeX-macros
4951 (list (concat "\\\\"
4952 (regexp-opt
4953 (append (mapcar 'car (append org-entities-user
4954 org-entities))
4955 (if (boundp 'org-latex-entities)
4956 (mapcar (lambda (x)
4957 (or (car-safe x) x))
4958 org-latex-entities)
4959 nil))
4960 'words))) ; FIXME
4962 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4963 (re-special (if org-export-with-special-strings
4964 (mapcar (lambda (x) (car x))
4965 org-export-html-special-string-regexps)))
4966 (re-rest
4967 (delq nil
4968 (list
4969 (if org-export-html-expand "@<[^>\n]+>")
4970 ))))
4971 (org-set-local
4972 'org-latex-and-specials-regexp
4973 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4974 re-rest) "\\|")))))
4976 (defun org-do-latex-and-special-faces (limit)
4977 "Run through the buffer and add overlays to links."
4978 (when org-latex-and-specials-regexp
4979 (let (rtn d)
4980 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4981 limit t))
4982 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4983 'face))
4984 '(org-code org-verbatim underline)))
4985 (progn
4986 (setq rtn t
4987 d (cond ((member (char-after (1+ (match-beginning 0)))
4988 '(?_ ?^)) 1)
4989 (t 0)))
4990 (font-lock-prepend-text-property
4991 (+ d (match-beginning 0)) (match-end 0)
4992 'face 'org-latex-and-export-specials)
4993 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4994 '(font-lock-multiline t)))))
4995 rtn)))
4997 (defun org-restart-font-lock ()
4998 "Restart font-lock-mode, to force refontification."
4999 (when (and (boundp 'font-lock-mode) font-lock-mode)
5000 (font-lock-mode -1)
5001 (font-lock-mode 1)))
5003 (defun org-all-targets (&optional radio)
5004 "Return a list of all targets in this file.
5005 With optional argument RADIO, only find radio targets."
5006 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5007 rtn)
5008 (save-excursion
5009 (goto-char (point-min))
5010 (while (re-search-forward re nil t)
5011 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5012 rtn)))
5014 (defun org-make-target-link-regexp (targets)
5015 "Make regular expression matching all strings in TARGETS.
5016 The regular expression finds the targets also if there is a line break
5017 between words."
5018 (and targets
5019 (concat
5020 "\\<\\("
5021 (mapconcat
5022 (lambda (x)
5023 (while (string-match " +" x)
5024 (setq x (replace-match "\\s-+" t t x)))
5026 targets
5027 "\\|")
5028 "\\)\\>")))
5030 (defun org-activate-tags (limit)
5031 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5032 (progn
5033 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5034 (add-text-properties (match-beginning 1) (match-end 1)
5035 (list 'mouse-face 'highlight
5036 'keymap org-mouse-map))
5037 (org-rear-nonsticky-at (match-end 1))
5038 t)))
5040 (defun org-outline-level ()
5041 "Compute the outline level of the heading at point.
5042 This function assumes that the cursor is at the beginning of a line matched
5043 by outline-regexp. Otherwise it returns garbage.
5044 If this is called at a normal headline, the level is the number of stars.
5045 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
5046 For plain list items, if they are matched by `outline-regexp', this returns
5047 1000 plus the line indentation."
5048 (save-excursion
5049 (looking-at outline-regexp)
5050 (if (match-beginning 1)
5051 (+ (org-get-string-indentation (match-string 1)) 1000)
5052 (1- (- (match-end 0) (match-beginning 0))))))
5054 (defvar org-font-lock-keywords nil)
5056 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5057 "Regular expression matching a property line.")
5059 (defvar org-font-lock-hook nil
5060 "Functions to be called for special font lock stuff.")
5062 (defun org-font-lock-hook (limit)
5063 (run-hook-with-args 'org-font-lock-hook limit))
5065 (defun org-set-font-lock-defaults ()
5066 (let* ((em org-fontify-emphasized-text)
5067 (lk org-activate-links)
5068 (org-font-lock-extra-keywords
5069 (list
5070 ;; Call the hook
5071 '(org-font-lock-hook)
5072 ;; Headlines
5073 `(,(if org-fontify-whole-heading-line
5074 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5075 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5076 (1 (org-get-level-face 1))
5077 (2 (org-get-level-face 2))
5078 (3 (org-get-level-face 3)))
5079 ;; Table lines
5080 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5081 (1 'org-table t))
5082 ;; Table internals
5083 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5084 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5085 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5086 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
5087 ;; Drawers
5088 (list org-drawer-regexp '(0 'org-special-keyword t))
5089 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5090 ;; Properties
5091 (list org-property-re
5092 '(1 'org-special-keyword t)
5093 '(3 'org-property-value t))
5094 ;; Links
5095 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5096 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5097 (if (memq 'plain lk) '(org-activate-plain-links))
5098 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5099 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5100 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5101 (if (memq 'footnote lk) '(org-activate-footnote-links
5102 (2 'org-footnote t)))
5103 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5104 '(org-hide-wide-columns (0 nil append))
5105 ;; TODO lines
5106 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5107 '(1 (org-get-todo-face 1) t))
5108 ;; DONE
5109 (if org-fontify-done-headline
5110 (list (concat "^[*]+ +\\<\\("
5111 (mapconcat 'regexp-quote org-done-keywords "\\|")
5112 "\\)\\(.*\\)")
5113 '(2 'org-headline-done t))
5114 nil)
5115 ;; Priorities
5116 '(org-font-lock-add-priority-faces)
5117 ;; Tags
5118 '(org-font-lock-add-tag-faces)
5119 ;; Special keywords
5120 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5121 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5122 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5123 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5124 ;; Emphasis
5125 (if em
5126 (if (featurep 'xemacs)
5127 '(org-do-emphasis-faces (0 nil append))
5128 '(org-do-emphasis-faces)))
5129 ;; Checkboxes
5130 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5131 2 'org-checkbox prepend)
5132 (if org-provide-checkbox-statistics
5133 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5134 (0 (org-get-checkbox-statistics-face) t)))
5135 ;; Description list items
5136 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5137 2 'bold prepend)
5138 ;; ARCHIVEd headings
5139 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5140 '(1 'org-archived prepend))
5141 ;; Specials
5142 '(org-do-latex-and-special-faces)
5143 ;; Code
5144 '(org-activate-code (1 'org-code t))
5145 ;; COMMENT
5146 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5147 "\\|" org-quote-string "\\)\\>")
5148 '(1 'org-special-keyword t))
5149 '("^#.*" (0 'font-lock-comment-face t))
5150 ;; Blocks and meta lines
5151 '(org-fontify-meta-lines-and-blocks)
5153 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5154 ;; Now set the full font-lock-keywords
5155 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5156 (org-set-local 'font-lock-defaults
5157 '(org-font-lock-keywords t nil nil backward-paragraph))
5158 (kill-local-variable 'font-lock-keywords) nil))
5160 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5161 "Fontify string S like in Org-mode"
5162 (with-temp-buffer
5163 (insert s)
5164 (let ((org-odd-levels-only odd-levels))
5165 (org-mode)
5166 (font-lock-fontify-buffer)
5167 (buffer-string))))
5169 (defvar org-m nil)
5170 (defvar org-l nil)
5171 (defvar org-f nil)
5172 (defun org-get-level-face (n)
5173 "Get the right face for match N in font-lock matching of headlines."
5174 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5175 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5176 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5177 (cond
5178 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5179 ((eq n 2) org-f)
5180 (t (if org-level-color-stars-only nil org-f))))
5182 (defun org-get-todo-face (kwd)
5183 "Get the right face for a TODO keyword KWD.
5184 If KWD is a number, get the corresponding match group."
5185 (if (numberp kwd) (setq kwd (match-string kwd)))
5186 (or (org-face-from-face-or-color
5187 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5188 (and (member kwd org-done-keywords) 'org-done)
5189 'org-todo))
5191 (defun org-face-from-face-or-color (context inherit face-or-color)
5192 "Create a face list that inherits INHERIT, but sets the foreground color.
5193 When FACE-OR-COLOR is not a string, just return it."
5194 (if (stringp face-or-color)
5195 (list :inherit inherit
5196 (cdr (assoc context org-faces-easy-properties))
5197 face-or-color)
5198 face-or-color))
5200 (defun org-font-lock-add-tag-faces (limit)
5201 "Add the special tag faces."
5202 (when (and org-tag-faces org-tags-special-faces-re)
5203 (while (re-search-forward org-tags-special-faces-re limit t)
5204 (add-text-properties (match-beginning 1) (match-end 1)
5205 (list 'face (org-get-tag-face 1)
5206 'font-lock-fontified t))
5207 (backward-char 1))))
5209 (defun org-font-lock-add-priority-faces (limit)
5210 "Add the special priority faces."
5211 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5212 (add-text-properties
5213 (match-beginning 0) (match-end 0)
5214 (list 'face (or (org-face-from-face-or-color
5215 'priority 'org-special-keyword
5216 (cdr (assoc (char-after (match-beginning 1))
5217 org-priority-faces)))
5218 'org-special-keyword)
5219 'font-lock-fontified t))))
5221 (defun org-get-tag-face (kwd)
5222 "Get the right face for a TODO keyword KWD.
5223 If KWD is a number, get the corresponding match group."
5224 (if (numberp kwd) (setq kwd (match-string kwd)))
5225 (or (org-face-from-face-or-color
5226 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5227 'org-tag))
5229 (defun org-unfontify-region (beg end &optional maybe_loudly)
5230 "Remove fontification and activation overlays from links."
5231 (font-lock-default-unfontify-region beg end)
5232 (let* ((buffer-undo-list t)
5233 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5234 (inhibit-modification-hooks t)
5235 deactivate-mark buffer-file-name buffer-file-truename)
5236 (remove-text-properties
5237 beg end
5238 (if org-indent-mode
5239 ;; also remove line-prefix and wrap-prefix properties
5240 '(mouse-face t keymap t org-linked-text t
5241 invisible t intangible t
5242 line-prefix t wrap-prefix t
5243 org-no-flyspell t)
5244 '(mouse-face t keymap t org-linked-text t
5245 invisible t intangible t
5246 org-no-flyspell t)))))
5248 ;;;; Visibility cycling, including org-goto and indirect buffer
5250 ;;; Cycling
5252 (defvar org-cycle-global-status nil)
5253 (make-variable-buffer-local 'org-cycle-global-status)
5254 (defvar org-cycle-subtree-status nil)
5255 (make-variable-buffer-local 'org-cycle-subtree-status)
5257 ;;;###autoload
5259 (defvar org-inlinetask-min-level)
5261 (defun org-cycle (&optional arg)
5262 "TAB-action and visibility cycling for Org-mode.
5264 This is the command invoked in Org-mode by the TAB key. Its main purpose
5265 is outline visibility cycling, but it also invokes other actions
5266 in special contexts.
5268 - When this function is called with a prefix argument, rotate the entire
5269 buffer through 3 states (global cycling)
5270 1. OVERVIEW: Show only top-level headlines.
5271 2. CONTENTS: Show all headlines of all levels, but no body text.
5272 3. SHOW ALL: Show everything.
5273 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5274 determined by the variable `org-startup-folded', and by any VISIBILITY
5275 properties in the buffer.
5276 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5277 including any drawers.
5279 - When inside a table, re-align the table and move to the next field.
5281 - When point is at the beginning of a headline, rotate the subtree started
5282 by this line through 3 different states (local cycling)
5283 1. FOLDED: Only the main headline is shown.
5284 2. CHILDREN: The main headline and the direct children are shown.
5285 From this state, you can move to one of the children
5286 and zoom in further.
5287 3. SUBTREE: Show the entire subtree, including body text.
5288 If there is no subtree, switch directly from CHILDREN to FOLDED.
5290 - When point is at the beginning of an empty headline and the variable
5291 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5292 of the headline by demoting and promoting it to likely levels. This
5293 speeds up creation document structure by presing TAB once or several
5294 times right after creating a new headline.
5296 - When there is a numeric prefix, go up to a heading with level ARG, do
5297 a `show-subtree' and return to the previous cursor position. If ARG
5298 is negative, go up that many levels.
5300 - When point is not at the beginning of a headline, execute the global
5301 binding for TAB, which is re-indenting the line. See the option
5302 `org-cycle-emulate-tab' for details.
5304 - Special case: if point is at the beginning of the buffer and there is
5305 no headline in line 1, this function will act as if called with prefix arg.
5306 But only if also the variable `org-cycle-global-at-bob' is t."
5307 (interactive "P")
5308 (org-load-modules-maybe)
5309 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5310 (and org-cycle-level-after-item/entry-creation
5311 (or (org-cycle-level)
5312 (org-cycle-item-indentation))))
5313 (let* ((limit-level
5314 (or org-cycle-max-level
5315 (and (boundp 'org-inlinetask-min-level)
5316 org-inlinetask-min-level
5317 (1- org-inlinetask-min-level))))
5318 (nstars (and limit-level
5319 (if org-odd-levels-only
5320 (and limit-level (1- (* limit-level 2)))
5321 limit-level)))
5322 (outline-regexp
5323 (cond
5324 ((not (org-mode-p)) outline-regexp)
5325 ((or (eq org-cycle-include-plain-lists 'integrate)
5326 (and org-cycle-include-plain-lists (org-at-item-p)))
5327 (concat "\\(?:\\*"
5328 (if nstars (format "\\{1,%d\\}" nstars) "+")
5329 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5330 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5331 (bob-special (and org-cycle-global-at-bob (bobp)
5332 (not (looking-at outline-regexp))))
5333 (org-cycle-hook
5334 (if bob-special
5335 (delq 'org-optimize-window-after-visibility-change
5336 (copy-sequence org-cycle-hook))
5337 org-cycle-hook))
5338 (pos (point)))
5340 (if (or bob-special (equal arg '(4)))
5341 ;; special case: use global cycling
5342 (setq arg t))
5344 (cond
5346 ((equal arg '(16))
5347 (org-set-startup-visibility)
5348 (message "Startup visibility, plus VISIBILITY properties"))
5350 ((equal arg '(64))
5351 (show-all)
5352 (message "Entire buffer visible, including drawers"))
5354 ((org-at-table-p 'any)
5355 ;; Enter the table or move to the next field in the table
5356 (if (org-at-table.el-p)
5357 (message "Use C-c ' to edit table.el tables")
5358 (if arg (org-table-edit-field t)
5359 (org-table-justify-field-maybe)
5360 (call-interactively 'org-table-next-field))))
5362 ((run-hook-with-args-until-success
5363 'org-tab-after-check-for-table-hook))
5365 ((eq arg t) ;; Global cycling
5366 (org-cycle-internal-global))
5368 ((and org-drawers org-drawer-regexp
5369 (save-excursion
5370 (beginning-of-line 1)
5371 (looking-at org-drawer-regexp)))
5372 ;; Toggle block visibility
5373 (org-flag-drawer
5374 (not (get-char-property (match-end 0) 'invisible))))
5376 ((integerp arg)
5377 ;; Show-subtree, ARG levels up from here.
5378 (save-excursion
5379 (org-back-to-heading)
5380 (outline-up-heading (if (< arg 0) (- arg)
5381 (- (funcall outline-level) arg)))
5382 (org-show-subtree)))
5384 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5385 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5387 (org-cycle-internal-local))
5389 ;; TAB emulation and template completion
5390 (buffer-read-only (org-back-to-heading))
5392 ((run-hook-with-args-until-success
5393 'org-tab-after-check-for-cycling-hook))
5395 ((org-try-structure-completion))
5397 ((org-try-cdlatex-tab))
5399 ((run-hook-with-args-until-success
5400 'org-tab-before-tab-emulation-hook))
5402 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5403 (or (not (bolp))
5404 (not (looking-at outline-regexp))))
5405 (call-interactively (global-key-binding "\t")))
5407 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5408 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5409 (or (and (eq org-cycle-emulate-tab 'white)
5410 (= (match-end 0) (point-at-eol)))
5411 (and (eq org-cycle-emulate-tab 'whitestart)
5412 (>= (match-end 0) pos))))
5414 (eq org-cycle-emulate-tab t))
5415 (call-interactively (global-key-binding "\t")))
5417 (t (save-excursion
5418 (org-back-to-heading)
5419 (org-cycle)))))))
5421 (defun org-cycle-internal-global ()
5422 "Do the global cycling action."
5423 (cond
5424 ((and (eq last-command this-command)
5425 (eq org-cycle-global-status 'overview))
5426 ;; We just created the overview - now do table of contents
5427 ;; This can be slow in very large buffers, so indicate action
5428 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5429 (message "CONTENTS...")
5430 (org-content)
5431 (message "CONTENTS...done")
5432 (setq org-cycle-global-status 'contents)
5433 (run-hook-with-args 'org-cycle-hook 'contents))
5435 ((and (eq last-command this-command)
5436 (eq org-cycle-global-status 'contents))
5437 ;; We just showed the table of contents - now show everything
5438 (run-hook-with-args 'org-pre-cycle-hook 'all)
5439 (show-all)
5440 (message "SHOW ALL")
5441 (setq org-cycle-global-status 'all)
5442 (run-hook-with-args 'org-cycle-hook 'all))
5445 ;; Default action: go to overview
5446 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5447 (org-overview)
5448 (message "OVERVIEW")
5449 (setq org-cycle-global-status 'overview)
5450 (run-hook-with-args 'org-cycle-hook 'overview))))
5452 (defun org-cycle-internal-local ()
5453 "Do the local cycling action."
5454 (org-back-to-heading)
5455 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5456 ;; First, some boundaries
5457 (save-excursion
5458 (org-back-to-heading)
5459 (setq level (funcall outline-level))
5460 (save-excursion
5461 (beginning-of-line 2)
5462 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5463 ; XEmacs does not have `next-single-char-property-change'
5464 ; I'm not sure about Emacs 21.
5465 (while (and (not (eobp)) ;; this is like `next-line'
5466 (get-char-property (1- (point)) 'invisible))
5467 (beginning-of-line 2))
5468 (while (and (not (eobp)) ;; this is like `next-line'
5469 (get-char-property (1- (point)) 'invisible))
5470 (goto-char (next-single-char-property-change (point) 'invisible))
5471 ;;;??? (or (bolp) (beginning-of-line 2))))
5472 (and (eolp) (beginning-of-line 2))))
5473 (setq eol (point)))
5474 (outline-end-of-heading) (setq eoh (point))
5475 (save-excursion
5476 (outline-next-heading)
5477 (setq has-children (and (org-at-heading-p t)
5478 (> (funcall outline-level) level))))
5479 (org-end-of-subtree t)
5480 (unless (eobp)
5481 (skip-chars-forward " \t\n")
5482 (beginning-of-line 1) ; in case this is an item
5484 (setq eos (if (eobp) (point) (1- (point)))))
5485 ;; Find out what to do next and set `this-command'
5486 (cond
5487 ((= eos eoh)
5488 ;; Nothing is hidden behind this heading
5489 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5490 (message "EMPTY ENTRY")
5491 (setq org-cycle-subtree-status nil)
5492 (save-excursion
5493 (goto-char eos)
5494 (outline-next-heading)
5495 (if (org-invisible-p) (org-flag-heading nil))))
5496 ((and (or (>= eol eos)
5497 (not (string-match "\\S-" (buffer-substring eol eos))))
5498 (or has-children
5499 (not (setq children-skipped
5500 org-cycle-skip-children-state-if-no-children))))
5501 ;; Entire subtree is hidden in one line: children view
5502 (run-hook-with-args 'org-pre-cycle-hook 'children)
5503 (org-show-entry)
5504 (show-children)
5505 (message "CHILDREN")
5506 (save-excursion
5507 (goto-char eos)
5508 (outline-next-heading)
5509 (if (org-invisible-p) (org-flag-heading nil)))
5510 (setq org-cycle-subtree-status 'children)
5511 (run-hook-with-args 'org-cycle-hook 'children))
5512 ((or children-skipped
5513 (and (eq last-command this-command)
5514 (eq org-cycle-subtree-status 'children)))
5515 ;; We just showed the children, or no children are there,
5516 ;; now show everything.
5517 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5518 (org-show-subtree)
5519 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5520 (setq org-cycle-subtree-status 'subtree)
5521 (run-hook-with-args 'org-cycle-hook 'subtree))
5523 ;; Default action: hide the subtree.
5524 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5525 (hide-subtree)
5526 (message "FOLDED")
5527 (setq org-cycle-subtree-status 'folded)
5528 (run-hook-with-args 'org-cycle-hook 'folded)))))
5530 ;;;###autoload
5531 (defun org-global-cycle (&optional arg)
5532 "Cycle the global visibility. For details see `org-cycle'.
5533 With C-u prefix arg, switch to startup visibility.
5534 With a numeric prefix, show all headlines up to that level."
5535 (interactive "P")
5536 (let ((org-cycle-include-plain-lists
5537 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5538 (cond
5539 ((integerp arg)
5540 (show-all)
5541 (hide-sublevels arg)
5542 (setq org-cycle-global-status 'contents))
5543 ((equal arg '(4))
5544 (org-set-startup-visibility)
5545 (message "Startup visibility, plus VISIBILITY properties."))
5547 (org-cycle '(4))))))
5549 (defun org-set-startup-visibility ()
5550 "Set the visibility required by startup options and properties."
5551 (cond
5552 ((eq org-startup-folded t)
5553 (org-cycle '(4)))
5554 ((eq org-startup-folded 'content)
5555 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5556 (org-cycle '(4)) (org-cycle '(4)))))
5557 (unless (eq org-startup-folded 'showeverything)
5558 (if org-hide-block-startup (org-hide-block-all))
5559 (org-set-visibility-according-to-property 'no-cleanup)
5560 (org-cycle-hide-archived-subtrees 'all)
5561 (org-cycle-hide-drawers 'all)
5562 (org-cycle-show-empty-lines 'all)))
5564 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5565 "Switch subtree visibilities according to :VISIBILITY: property."
5566 (interactive)
5567 (let (org-show-entry-below state)
5568 (save-excursion
5569 (goto-char (point-min))
5570 (while (re-search-forward
5571 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5572 nil t)
5573 (setq state (match-string 1))
5574 (save-excursion
5575 (org-back-to-heading t)
5576 (hide-subtree)
5577 (org-reveal)
5578 (cond
5579 ((equal state '("fold" "folded"))
5580 (hide-subtree))
5581 ((equal state "children")
5582 (org-show-hidden-entry)
5583 (show-children))
5584 ((equal state "content")
5585 (save-excursion
5586 (save-restriction
5587 (org-narrow-to-subtree)
5588 (org-content))))
5589 ((member state '("all" "showall"))
5590 (show-subtree)))))
5591 (unless no-cleanup
5592 (org-cycle-hide-archived-subtrees 'all)
5593 (org-cycle-hide-drawers 'all)
5594 (org-cycle-show-empty-lines 'all)))))
5596 (defun org-overview ()
5597 "Switch to overview mode, showing only top-level headlines.
5598 Really, this shows all headlines with level equal or greater than the level
5599 of the first headline in the buffer. This is important, because if the
5600 first headline is not level one, then (hide-sublevels 1) gives confusing
5601 results."
5602 (interactive)
5603 (let ((level (save-excursion
5604 (goto-char (point-min))
5605 (if (re-search-forward (concat "^" outline-regexp) nil t)
5606 (progn
5607 (goto-char (match-beginning 0))
5608 (funcall outline-level))))))
5609 (and level (hide-sublevels level))))
5611 (defun org-content (&optional arg)
5612 "Show all headlines in the buffer, like a table of contents.
5613 With numerical argument N, show content up to level N."
5614 (interactive "P")
5615 (save-excursion
5616 ;; Visit all headings and show their offspring
5617 (and (integerp arg) (org-overview))
5618 (goto-char (point-max))
5619 (catch 'exit
5620 (while (and (progn (condition-case nil
5621 (outline-previous-visible-heading 1)
5622 (error (goto-char (point-min))))
5624 (looking-at outline-regexp))
5625 (if (integerp arg)
5626 (show-children (1- arg))
5627 (show-branches))
5628 (if (bobp) (throw 'exit nil))))))
5631 (defun org-optimize-window-after-visibility-change (state)
5632 "Adjust the window after a change in outline visibility.
5633 This function is the default value of the hook `org-cycle-hook'."
5634 (when (get-buffer-window (current-buffer))
5635 (cond
5636 ((eq state 'content) nil)
5637 ((eq state 'all) nil)
5638 ((eq state 'folded) nil)
5639 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5640 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5642 (defun org-remove-empty-overlays-at (pos)
5643 "Remove outline overlays that do not contain non-white stuff."
5644 (mapc
5645 (lambda (o)
5646 (and (eq 'outline (overlay-get o 'invisible))
5647 (not (string-match "\\S-" (buffer-substring (overlay-start o)
5648 (overlay-end o))))
5649 (delete-overlay o)))
5650 (org-overlays-at pos)))
5652 (defun org-clean-visibility-after-subtree-move ()
5653 "Fix visibility issues after moving a subtree."
5654 ;; First, find a reasonable region to look at:
5655 ;; Start two siblings above, end three below
5656 (let* ((beg (save-excursion
5657 (and (org-get-last-sibling)
5658 (org-get-last-sibling))
5659 (point)))
5660 (end (save-excursion
5661 (and (org-get-next-sibling)
5662 (org-get-next-sibling)
5663 (org-get-next-sibling))
5664 (if (org-at-heading-p)
5665 (point-at-eol)
5666 (point))))
5667 (level (looking-at "\\*+"))
5668 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5669 (save-excursion
5670 (save-restriction
5671 (narrow-to-region beg end)
5672 (when re
5673 ;; Properly fold already folded siblings
5674 (goto-char (point-min))
5675 (while (re-search-forward re nil t)
5676 (if (and (not (org-invisible-p))
5677 (save-excursion
5678 (goto-char (point-at-eol)) (org-invisible-p)))
5679 (hide-entry))))
5680 (org-cycle-show-empty-lines 'overview)
5681 (org-cycle-hide-drawers 'overview)))))
5683 (defun org-cycle-show-empty-lines (state)
5684 "Show empty lines above all visible headlines.
5685 The region to be covered depends on STATE when called through
5686 `org-cycle-hook'. Lisp program can use t for STATE to get the
5687 entire buffer covered. Note that an empty line is only shown if there
5688 are at least `org-cycle-separator-lines' empty lines before the headline."
5689 (when (not (= org-cycle-separator-lines 0))
5690 (save-excursion
5691 (let* ((n (abs org-cycle-separator-lines))
5692 (re (cond
5693 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5694 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5695 (t (let ((ns (number-to-string (- n 2))))
5696 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5697 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5698 beg end b e)
5699 (cond
5700 ((memq state '(overview contents t))
5701 (setq beg (point-min) end (point-max)))
5702 ((memq state '(children folded))
5703 (setq beg (point) end (progn (org-end-of-subtree t t)
5704 (beginning-of-line 2)
5705 (point)))))
5706 (when beg
5707 (goto-char beg)
5708 (while (re-search-forward re end t)
5709 (unless (get-char-property (match-end 1) 'invisible)
5710 (setq e (match-end 1))
5711 (if (< org-cycle-separator-lines 0)
5712 (setq b (save-excursion
5713 (goto-char (match-beginning 0))
5714 (org-back-over-empty-lines)
5715 (if (save-excursion
5716 (goto-char (max (point-min) (1- (point))))
5717 (org-on-heading-p))
5718 (1- (point))
5719 (point))))
5720 (setq b (match-beginning 1)))
5721 (outline-flag-region b e nil)))))))
5722 ;; Never hide empty lines at the end of the file.
5723 (save-excursion
5724 (goto-char (point-max))
5725 (outline-previous-heading)
5726 (outline-end-of-heading)
5727 (if (and (looking-at "[ \t\n]+")
5728 (= (match-end 0) (point-max)))
5729 (outline-flag-region (point) (match-end 0) nil))))
5731 (defun org-show-empty-lines-in-parent ()
5732 "Move to the parent and re-show empty lines before visible headlines."
5733 (save-excursion
5734 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5735 (org-cycle-show-empty-lines context))))
5737 (defun org-files-list ()
5738 "Return `org-agenda-files' list, plus all open org-mode files.
5739 This is useful for operations that need to scan all of a user's
5740 open and agenda-wise Org files."
5741 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5742 (dolist (buf (buffer-list))
5743 (with-current-buffer buf
5744 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5745 (let ((file (expand-file-name (buffer-file-name))))
5746 (unless (member file files)
5747 (push file files))))))
5748 files))
5750 (defsubst org-entry-beginning-position ()
5751 "Return the beginning position of the current entry."
5752 (save-excursion (outline-back-to-heading t) (point)))
5754 (defsubst org-entry-end-position ()
5755 "Return the end position of the current entry."
5756 (save-excursion (outline-next-heading) (point)))
5758 (defun org-cycle-hide-drawers (state)
5759 "Re-hide all drawers after a visibility state change."
5760 (when (and (org-mode-p)
5761 (not (memq state '(overview folded contents))))
5762 (save-excursion
5763 (let* ((globalp (memq state '(contents all)))
5764 (beg (if globalp (point-min) (point)))
5765 (end (if globalp (point-max)
5766 (if (eq state 'children)
5767 (save-excursion (outline-next-heading) (point))
5768 (org-end-of-subtree t)))))
5769 (goto-char beg)
5770 (while (re-search-forward org-drawer-regexp end t)
5771 (org-flag-drawer t))))))
5773 (defun org-flag-drawer (flag)
5774 (save-excursion
5775 (beginning-of-line 1)
5776 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5777 (let ((b (match-end 0))
5778 (outline-regexp org-outline-regexp))
5779 (if (re-search-forward
5780 "^[ \t]*:END:"
5781 (save-excursion (outline-next-heading) (point)) t)
5782 (outline-flag-region b (point-at-eol) flag)
5783 (error ":END: line missing at position %s" b))))))
5785 (defun org-subtree-end-visible-p ()
5786 "Is the end of the current subtree visible?"
5787 (pos-visible-in-window-p
5788 (save-excursion (org-end-of-subtree t) (point))))
5790 (defun org-first-headline-recenter (&optional N)
5791 "Move cursor to the first headline and recenter the headline.
5792 Optional argument N means put the headline into the Nth line of the window."
5793 (goto-char (point-min))
5794 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5795 (beginning-of-line)
5796 (recenter (prefix-numeric-value N))))
5798 ;;; Saving and restoring visibility
5800 (defun org-outline-overlay-data (&optional use-markers)
5801 "Return a list of the locations of all outline overlays.
5802 The are overlays with the `invisible' property value `outline'.
5803 The return valus is a list of cons cells, with start and stop
5804 positions for each overlay.
5805 If USE-MARKERS is set, return the positions as markers."
5806 (let (beg end)
5807 (save-excursion
5808 (save-restriction
5809 (widen)
5810 (delq nil
5811 (mapcar (lambda (o)
5812 (when (eq (overlay-get o 'invisible) 'outline)
5813 (setq beg (overlay-start o)
5814 end (overlay-end o))
5815 (and beg end (> end beg)
5816 (if use-markers
5817 (cons (move-marker (make-marker) beg)
5818 (move-marker (make-marker) end))
5819 (cons beg end)))))
5820 (org-overlays-in (point-min) (point-max))))))))
5822 (defun org-set-outline-overlay-data (data)
5823 "Create visibility overlays for all positions in DATA.
5824 DATA should have been made by `org-outline-overlay-data'."
5825 (let (o)
5826 (save-excursion
5827 (save-restriction
5828 (widen)
5829 (show-all)
5830 (mapc (lambda (c)
5831 (setq o (make-overlay (car c) (cdr c)))
5832 (overlay-put o 'invisible 'outline))
5833 data)))))
5835 (defmacro org-save-outline-visibility (use-markers &rest body)
5836 "Save and restore outline visibility around BODY.
5837 If USE-MARKERS is non-nil, use markers for the positions.
5838 This means that the buffer may change while running BODY,
5839 but it also means that the buffer should stay alive
5840 during the operation, because otherwise all these markers will
5841 point nowhere."
5842 `(let ((data (org-outline-overlay-data ,use-markers)))
5843 (unwind-protect
5844 (progn
5845 ,@body
5846 (org-set-outline-overlay-data data))
5847 (when ,use-markers
5848 (mapc (lambda (c)
5849 (and (markerp (car c)) (move-marker (car c) nil))
5850 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
5851 data)))))
5854 ;;; Folding of blocks
5856 (defconst org-block-regexp
5858 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5859 "Regular expression for hiding blocks.")
5861 (defvar org-hide-block-overlays nil
5862 "Overlays hiding blocks.")
5863 (make-variable-buffer-local 'org-hide-block-overlays)
5865 (defun org-block-map (function &optional start end)
5866 "Call func at the head of all source blocks in the current
5867 buffer. Optional arguments START and END can be used to limit
5868 the range."
5869 (let ((start (or start (point-min)))
5870 (end (or end (point-max))))
5871 (save-excursion
5872 (goto-char start)
5873 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5874 (save-excursion
5875 (save-match-data
5876 (goto-char (match-beginning 0))
5877 (funcall function)))))))
5879 (defun org-hide-block-toggle-all ()
5880 "Toggle the visibility of all blocks in the current buffer."
5881 (org-block-map #'org-hide-block-toggle))
5883 (defun org-hide-block-all ()
5884 "Fold all blocks in the current buffer."
5885 (interactive)
5886 (org-show-block-all)
5887 (org-block-map #'org-hide-block-toggle-maybe))
5889 (defun org-show-block-all ()
5890 "Unfold all blocks in the current buffer."
5891 (mapc 'delete-overlay org-hide-block-overlays)
5892 (setq org-hide-block-overlays nil))
5894 (defun org-hide-block-toggle-maybe ()
5895 "Toggle visibility of block at point."
5896 (interactive)
5897 (let ((case-fold-search t))
5898 (if (save-excursion
5899 (beginning-of-line 1)
5900 (looking-at org-block-regexp))
5901 (progn (org-hide-block-toggle)
5902 t) ;; to signal that we took action
5903 nil))) ;; to signal that we did not
5905 (defun org-hide-block-toggle (&optional force)
5906 "Toggle the visibility of the current block."
5907 (interactive)
5908 (save-excursion
5909 (beginning-of-line)
5910 (if (re-search-forward org-block-regexp nil t)
5911 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5912 (end (match-end 0)) ;; end of entire body
5914 (if (memq t (mapcar (lambda (overlay)
5915 (eq (overlay-get overlay 'invisible)
5916 'org-hide-block))
5917 (org-overlays-at start)))
5918 (if (or (not force) (eq force 'off))
5919 (mapc (lambda (ov)
5920 (when (member ov org-hide-block-overlays)
5921 (setq org-hide-block-overlays
5922 (delq ov org-hide-block-overlays)))
5923 (when (eq (overlay-get ov 'invisible)
5924 'org-hide-block)
5925 (delete-overlay ov)))
5926 (org-overlays-at start)))
5927 (setq ov (make-overlay start end))
5928 (overlay-put ov 'invisible 'org-hide-block)
5929 ;; make the block accessible to isearch
5930 (overlay-put
5931 ov 'isearch-open-invisible
5932 (lambda (ov)
5933 (when (member ov org-hide-block-overlays)
5934 (setq org-hide-block-overlays
5935 (delq ov org-hide-block-overlays)))
5936 (when (eq (overlay-get ov 'invisible)
5937 'org-hide-block)
5938 (delete-overlay ov))))
5939 (push ov org-hide-block-overlays)))
5940 (error "Not looking at a source block"))))
5942 ;; org-tab-after-check-for-cycling-hook
5943 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5944 ;; Remove overlays when changing major mode
5945 (add-hook 'org-mode-hook
5946 (lambda () (org-add-hook 'change-major-mode-hook
5947 'org-show-block-all 'append 'local)))
5949 ;;; Org-goto
5951 (defvar org-goto-window-configuration nil)
5952 (defvar org-goto-marker nil)
5953 (defvar org-goto-map
5954 (let ((map (make-sparse-keymap)))
5955 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5956 (while (setq cmd (pop cmds))
5957 (substitute-key-definition cmd cmd map global-map)))
5958 (suppress-keymap map)
5959 (org-defkey map "\C-m" 'org-goto-ret)
5960 (org-defkey map [(return)] 'org-goto-ret)
5961 (org-defkey map [(left)] 'org-goto-left)
5962 (org-defkey map [(right)] 'org-goto-right)
5963 (org-defkey map [(control ?g)] 'org-goto-quit)
5964 (org-defkey map "\C-i" 'org-cycle)
5965 (org-defkey map [(tab)] 'org-cycle)
5966 (org-defkey map [(down)] 'outline-next-visible-heading)
5967 (org-defkey map [(up)] 'outline-previous-visible-heading)
5968 (if org-goto-auto-isearch
5969 (if (fboundp 'define-key-after)
5970 (define-key-after map [t] 'org-goto-local-auto-isearch)
5971 nil)
5972 (org-defkey map "q" 'org-goto-quit)
5973 (org-defkey map "n" 'outline-next-visible-heading)
5974 (org-defkey map "p" 'outline-previous-visible-heading)
5975 (org-defkey map "f" 'outline-forward-same-level)
5976 (org-defkey map "b" 'outline-backward-same-level)
5977 (org-defkey map "u" 'outline-up-heading))
5978 (org-defkey map "/" 'org-occur)
5979 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5980 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5981 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5982 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5983 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5984 map))
5986 (defconst org-goto-help
5987 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5988 RET=jump to location [Q]uit and return to previous location
5989 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5991 (defvar org-goto-start-pos) ; dynamically scoped parameter
5993 ;; FIXME: Docstring does not mention both interfaces
5994 (defun org-goto (&optional alternative-interface)
5995 "Look up a different location in the current file, keeping current visibility.
5997 When you want look-up or go to a different location in a document, the
5998 fastest way is often to fold the entire buffer and then dive into the tree.
5999 This method has the disadvantage, that the previous location will be folded,
6000 which may not be what you want.
6002 This command works around this by showing a copy of the current buffer
6003 in an indirect buffer, in overview mode. You can dive into the tree in
6004 that copy, use org-occur and incremental search to find a location.
6005 When pressing RET or `Q', the command returns to the original buffer in
6006 which the visibility is still unchanged. After RET is will also jump to
6007 the location selected in the indirect buffer and expose the
6008 the headline hierarchy above."
6009 (interactive "P")
6010 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6011 (org-refile-use-outline-path t)
6012 (org-refile-target-verify-function nil)
6013 (interface
6014 (if (not alternative-interface)
6015 org-goto-interface
6016 (if (eq org-goto-interface 'outline)
6017 'outline-path-completion
6018 'outline)))
6019 (org-goto-start-pos (point))
6020 (selected-point
6021 (if (eq interface 'outline)
6022 (car (org-get-location (current-buffer) org-goto-help))
6023 (nth 3 (org-refile-get-location "Goto: ")))))
6024 (if selected-point
6025 (progn
6026 (org-mark-ring-push org-goto-start-pos)
6027 (goto-char selected-point)
6028 (if (or (org-invisible-p) (org-invisible-p2))
6029 (org-show-context 'org-goto)))
6030 (message "Quit"))))
6032 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6033 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6034 (defvar org-goto-local-auto-isearch-map) ; defined below
6036 (defun org-get-location (buf help)
6037 "Let the user select a location in the Org-mode buffer BUF.
6038 This function uses a recursive edit. It returns the selected position
6039 or nil."
6040 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6041 (isearch-hide-immediately nil)
6042 (isearch-search-fun-function
6043 (lambda () 'org-goto-local-search-headings))
6044 (org-goto-selected-point org-goto-exit-command)
6045 (pop-up-frames nil)
6046 (special-display-buffer-names nil)
6047 (special-display-regexps nil)
6048 (special-display-function nil))
6049 (save-excursion
6050 (save-window-excursion
6051 (delete-other-windows)
6052 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6053 (switch-to-buffer
6054 (condition-case nil
6055 (make-indirect-buffer (current-buffer) "*org-goto*")
6056 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6057 (with-output-to-temp-buffer "*Help*"
6058 (princ help))
6059 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6060 (setq buffer-read-only nil)
6061 (let ((org-startup-truncated t)
6062 (org-startup-folded nil)
6063 (org-startup-align-all-tables nil))
6064 (org-mode)
6065 (org-overview))
6066 (setq buffer-read-only t)
6067 (if (and (boundp 'org-goto-start-pos)
6068 (integer-or-marker-p org-goto-start-pos))
6069 (let ((org-show-hierarchy-above t)
6070 (org-show-siblings t)
6071 (org-show-following-heading t))
6072 (goto-char org-goto-start-pos)
6073 (and (org-invisible-p) (org-show-context)))
6074 (goto-char (point-min)))
6075 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6076 (message "Select location and press RET")
6077 (use-local-map org-goto-map)
6078 (recursive-edit)
6080 (kill-buffer "*org-goto*")
6081 (cons org-goto-selected-point org-goto-exit-command)))
6083 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6084 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6085 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6086 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6088 (defun org-goto-local-search-headings (string bound noerror)
6089 "Search and make sure that any matches are in headlines."
6090 (catch 'return
6091 (while (if isearch-forward
6092 (search-forward string bound noerror)
6093 (search-backward string bound noerror))
6094 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6095 (and (member :headline context)
6096 (not (member :tags context))))
6097 (throw 'return (point))))))
6099 (defun org-goto-local-auto-isearch ()
6100 "Start isearch."
6101 (interactive)
6102 (goto-char (point-min))
6103 (let ((keys (this-command-keys)))
6104 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6105 (isearch-mode t)
6106 (isearch-process-search-char (string-to-char keys)))))
6108 (defun org-goto-ret (&optional arg)
6109 "Finish `org-goto' by going to the new location."
6110 (interactive "P")
6111 (setq org-goto-selected-point (point)
6112 org-goto-exit-command 'return)
6113 (throw 'exit nil))
6115 (defun org-goto-left ()
6116 "Finish `org-goto' by going to the new location."
6117 (interactive)
6118 (if (org-on-heading-p)
6119 (progn
6120 (beginning-of-line 1)
6121 (setq org-goto-selected-point (point)
6122 org-goto-exit-command 'left)
6123 (throw 'exit nil))
6124 (error "Not on a heading")))
6126 (defun org-goto-right ()
6127 "Finish `org-goto' by going to the new location."
6128 (interactive)
6129 (if (org-on-heading-p)
6130 (progn
6131 (setq org-goto-selected-point (point)
6132 org-goto-exit-command 'right)
6133 (throw 'exit nil))
6134 (error "Not on a heading")))
6136 (defun org-goto-quit ()
6137 "Finish `org-goto' without cursor motion."
6138 (interactive)
6139 (setq org-goto-selected-point nil)
6140 (setq org-goto-exit-command 'quit)
6141 (throw 'exit nil))
6143 ;;; Indirect buffer display of subtrees
6145 (defvar org-indirect-dedicated-frame nil
6146 "This is the frame being used for indirect tree display.")
6147 (defvar org-last-indirect-buffer nil)
6149 (defun org-tree-to-indirect-buffer (&optional arg)
6150 "Create indirect buffer and narrow it to current subtree.
6151 With numerical prefix ARG, go up to this level and then take that tree.
6152 If ARG is negative, go up that many levels.
6153 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6154 indirect buffer previously made with this command, to avoid proliferation of
6155 indirect buffers. However, when you call the command with a `C-u' prefix, or
6156 when `org-indirect-buffer-display' is `new-frame', the last buffer
6157 is kept so that you can work with several indirect buffers at the same time.
6158 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6159 requests that a new frame be made for the new buffer, so that the dedicated
6160 frame is not changed."
6161 (interactive "P")
6162 (let ((cbuf (current-buffer))
6163 (cwin (selected-window))
6164 (pos (point))
6165 beg end level heading ibuf)
6166 (save-excursion
6167 (org-back-to-heading t)
6168 (when (numberp arg)
6169 (setq level (org-outline-level))
6170 (if (< arg 0) (setq arg (+ level arg)))
6171 (while (> (setq level (org-outline-level)) arg)
6172 (outline-up-heading 1 t)))
6173 (setq beg (point)
6174 heading (org-get-heading))
6175 (org-end-of-subtree t t)
6176 (if (org-on-heading-p) (backward-char 1))
6177 (setq end (point)))
6178 (if (and (buffer-live-p org-last-indirect-buffer)
6179 (not (eq org-indirect-buffer-display 'new-frame))
6180 (not arg))
6181 (kill-buffer org-last-indirect-buffer))
6182 (setq ibuf (org-get-indirect-buffer cbuf)
6183 org-last-indirect-buffer ibuf)
6184 (cond
6185 ((or (eq org-indirect-buffer-display 'new-frame)
6186 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6187 (select-frame (make-frame))
6188 (delete-other-windows)
6189 (switch-to-buffer ibuf)
6190 (org-set-frame-title heading))
6191 ((eq org-indirect-buffer-display 'dedicated-frame)
6192 (raise-frame
6193 (select-frame (or (and org-indirect-dedicated-frame
6194 (frame-live-p org-indirect-dedicated-frame)
6195 org-indirect-dedicated-frame)
6196 (setq org-indirect-dedicated-frame (make-frame)))))
6197 (delete-other-windows)
6198 (switch-to-buffer ibuf)
6199 (org-set-frame-title (concat "Indirect: " heading)))
6200 ((eq org-indirect-buffer-display 'current-window)
6201 (switch-to-buffer ibuf))
6202 ((eq org-indirect-buffer-display 'other-window)
6203 (pop-to-buffer ibuf))
6204 (t (error "Invalid value")))
6205 (if (featurep 'xemacs)
6206 (save-excursion (org-mode) (turn-on-font-lock)))
6207 (narrow-to-region beg end)
6208 (show-all)
6209 (goto-char pos)
6210 (and (window-live-p cwin) (select-window cwin))))
6212 (defun org-get-indirect-buffer (&optional buffer)
6213 (setq buffer (or buffer (current-buffer)))
6214 (let ((n 1) (base (buffer-name buffer)) bname)
6215 (while (buffer-live-p
6216 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6217 (setq n (1+ n)))
6218 (condition-case nil
6219 (make-indirect-buffer buffer bname 'clone)
6220 (error (make-indirect-buffer buffer bname)))))
6222 (defun org-set-frame-title (title)
6223 "Set the title of the current frame to the string TITLE."
6224 ;; FIXME: how to name a single frame in XEmacs???
6225 (unless (featurep 'xemacs)
6226 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6228 ;;;; Structure editing
6230 ;;; Inserting headlines
6232 (defun org-previous-line-empty-p ()
6233 (save-excursion
6234 (and (not (bobp))
6235 (or (beginning-of-line 0) t)
6236 (save-match-data
6237 (looking-at "[ \t]*$")))))
6239 (defun org-insert-heading (&optional force-heading invisible-ok)
6240 "Insert a new heading or item with same depth at point.
6241 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6242 If point is at the beginning of a headline, insert a sibling before the
6243 current headline. If point is not at the beginning, do not split the line,
6244 but create the new headline after the current line.
6245 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6246 This is important for non-interactive uses of the command."
6247 (interactive "P")
6248 (if (or (= (buffer-size) 0)
6249 (and (not (save-excursion (and (ignore-errors (org-back-to-heading invisible-ok))
6250 (org-on-heading-p))))
6251 (not (org-in-item-p))))
6252 (insert "\n* ")
6253 (when (or force-heading (not (org-insert-item)))
6254 (let* ((empty-line-p nil)
6255 (head (save-excursion
6256 (condition-case nil
6257 (progn
6258 (org-back-to-heading invisible-ok)
6259 (setq empty-line-p (org-previous-line-empty-p))
6260 (match-string 0))
6261 (error "*"))))
6262 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6263 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6264 pos hide-previous previous-pos)
6265 (cond
6266 ((and (org-on-heading-p) (bolp)
6267 (or (bobp)
6268 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6269 ;; insert before the current line
6270 (open-line (if blank 2 1)))
6271 ((and (bolp)
6272 (not org-insert-heading-respect-content)
6273 (or (bobp)
6274 (save-excursion
6275 (backward-char 1) (not (org-invisible-p)))))
6276 ;; insert right here
6277 nil)
6279 ;; somewhere in the line
6280 (save-excursion
6281 (setq previous-pos (point-at-bol))
6282 (end-of-line)
6283 (setq hide-previous (org-invisible-p)))
6284 (and org-insert-heading-respect-content (org-show-subtree))
6285 (let ((split
6286 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6287 (save-excursion
6288 (let ((p (point)))
6289 (goto-char (point-at-bol))
6290 (and (looking-at org-complex-heading-regexp)
6291 (> p (match-beginning 4)))))))
6292 tags pos)
6293 (cond
6294 (org-insert-heading-respect-content
6295 (org-end-of-subtree nil t)
6296 (or (bolp) (newline))
6297 (or (org-previous-line-empty-p)
6298 (and blank (newline)))
6299 (open-line 1))
6300 ((org-on-heading-p)
6301 (when hide-previous
6302 (show-children)
6303 (org-show-entry))
6304 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6305 (setq tags (and (match-end 2) (match-string 2)))
6306 (and (match-end 1)
6307 (delete-region (match-beginning 1) (match-end 1)))
6308 (setq pos (point-at-bol))
6309 (or split (end-of-line 1))
6310 (delete-horizontal-space)
6311 (if (string-match "\\`\\*+\\'"
6312 (buffer-substring (point-at-bol) (point)))
6313 (insert " "))
6314 (newline (if blank 2 1))
6315 (when tags
6316 (save-excursion
6317 (goto-char pos)
6318 (end-of-line 1)
6319 (insert " " tags)
6320 (org-set-tags nil 'align))))
6322 (or split (end-of-line 1))
6323 (newline (if blank 2 1)))))))
6324 (insert head) (just-one-space)
6325 (setq pos (point))
6326 (end-of-line 1)
6327 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6328 (when (and org-insert-heading-respect-content hide-previous)
6329 (save-excursion
6330 (goto-char previous-pos)
6331 (hide-subtree)))
6332 (run-hooks 'org-insert-heading-hook)))))
6334 (defun org-get-heading (&optional no-tags)
6335 "Return the heading of the current entry, without the stars."
6336 (save-excursion
6337 (org-back-to-heading t)
6338 (if (looking-at
6339 (if no-tags
6340 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6341 "\\*+[ \t]+\\([^\r\n]*\\)"))
6342 (match-string 1) "")))
6344 (defun org-heading-components ()
6345 "Return the components of the current heading.
6346 This is a list with the following elements:
6347 - the level as an integer
6348 - the reduced level, different if `org-odd-levels-only' is set.
6349 - the TODO keyword, or nil
6350 - the priority character, like ?A, or nil if no priority is given
6351 - the headline text itself, or the tags string if no headline text
6352 - the tags string, or nil."
6353 (save-excursion
6354 (org-back-to-heading t)
6355 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6356 (list (length (match-string 1))
6357 (org-reduced-level (length (match-string 1)))
6358 (org-match-string-no-properties 2)
6359 (and (match-end 3) (aref (match-string 3) 2))
6360 (org-match-string-no-properties 4)
6361 (org-match-string-no-properties 5)))))
6363 (defun org-get-entry ()
6364 "Get the entry text, after heading, entire subtree."
6365 (save-excursion
6366 (org-back-to-heading t)
6367 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6369 (defun org-insert-heading-after-current ()
6370 "Insert a new heading with same level as current, after current subtree."
6371 (interactive)
6372 (org-back-to-heading)
6373 (org-insert-heading)
6374 (org-move-subtree-down)
6375 (end-of-line 1))
6377 (defun org-insert-heading-respect-content ()
6378 (interactive)
6379 (let ((org-insert-heading-respect-content t))
6380 (org-insert-heading t)))
6382 (defun org-insert-todo-heading-respect-content (&optional force-state)
6383 (interactive "P")
6384 (let ((org-insert-heading-respect-content t))
6385 (org-insert-todo-heading force-state t)))
6387 (defun org-insert-todo-heading (arg &optional force-heading)
6388 "Insert a new heading with the same level and TODO state as current heading.
6389 If the heading has no TODO state, or if the state is DONE, use the first
6390 state (TODO by default). Also with prefix arg, force first state."
6391 (interactive "P")
6392 (when (or force-heading (not (org-insert-item 'checkbox)))
6393 (org-insert-heading force-heading)
6394 (save-excursion
6395 (org-back-to-heading)
6396 (outline-previous-heading)
6397 (looking-at org-todo-line-regexp))
6398 (let*
6399 ((new-mark-x
6400 (if (or arg
6401 (not (match-beginning 2))
6402 (member (match-string 2) org-done-keywords))
6403 (car org-todo-keywords-1)
6404 (match-string 2)))
6405 (new-mark
6407 (run-hook-with-args-until-success
6408 'org-todo-get-default-hook new-mark-x nil)
6409 new-mark-x)))
6410 (beginning-of-line 1)
6411 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6412 (if org-treat-insert-todo-heading-as-state-change
6413 (org-todo new-mark)
6414 (insert new-mark " "))))
6415 (when org-provide-todo-statistics
6416 (org-update-parent-todo-statistics))))
6418 (defun org-insert-subheading (arg)
6419 "Insert a new subheading and demote it.
6420 Works for outline headings and for plain lists alike."
6421 (interactive "P")
6422 (org-insert-heading arg)
6423 (cond
6424 ((org-on-heading-p) (org-do-demote))
6425 ((org-at-item-p) (org-indent-item 1))))
6427 (defun org-insert-todo-subheading (arg)
6428 "Insert a new subheading with TODO keyword or checkbox and demote it.
6429 Works for outline headings and for plain lists alike."
6430 (interactive "P")
6431 (org-insert-todo-heading arg)
6432 (cond
6433 ((org-on-heading-p) (org-do-demote))
6434 ((org-at-item-p) (org-indent-item 1))))
6436 ;;; Promotion and Demotion
6438 (defvar org-after-demote-entry-hook nil
6439 "Hook run after an entry has been demoted.
6440 The cursor will be at the beginning of the entry.
6441 When a subtree is being demoted, the hook will be called for each node.")
6443 (defvar org-after-promote-entry-hook nil
6444 "Hook run after an entry has been promoted.
6445 The cursor will be at the beginning of the entry.
6446 When a subtree is being promoted, the hook will be called for each node.")
6448 (defun org-promote-subtree ()
6449 "Promote the entire subtree.
6450 See also `org-promote'."
6451 (interactive)
6452 (save-excursion
6453 (org-map-tree 'org-promote))
6454 (org-fix-position-after-promote))
6456 (defun org-demote-subtree ()
6457 "Demote the entire subtree. See `org-demote'.
6458 See also `org-promote'."
6459 (interactive)
6460 (save-excursion
6461 (org-map-tree 'org-demote))
6462 (org-fix-position-after-promote))
6465 (defun org-do-promote ()
6466 "Promote the current heading higher up the tree.
6467 If the region is active in `transient-mark-mode', promote all headings
6468 in the region."
6469 (interactive)
6470 (save-excursion
6471 (if (org-region-active-p)
6472 (org-map-region 'org-promote (region-beginning) (region-end))
6473 (org-promote)))
6474 (org-fix-position-after-promote))
6476 (defun org-do-demote ()
6477 "Demote the current heading lower down the tree.
6478 If the region is active in `transient-mark-mode', demote all headings
6479 in the region."
6480 (interactive)
6481 (save-excursion
6482 (if (org-region-active-p)
6483 (org-map-region 'org-demote (region-beginning) (region-end))
6484 (org-demote)))
6485 (org-fix-position-after-promote))
6487 (defun org-fix-position-after-promote ()
6488 "Make sure that after pro/demotion cursor position is right."
6489 (let ((pos (point)))
6490 (when (save-excursion
6491 (beginning-of-line 1)
6492 (looking-at org-todo-line-regexp)
6493 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6494 (cond ((eobp) (insert " "))
6495 ((eolp) (insert " "))
6496 ((equal (char-after) ?\ ) (forward-char 1))))))
6498 (defun org-current-level ()
6499 "Return the level of the current entry, or nil if before the first headline.
6500 The level is the number of stars at the beginning of the headline."
6501 (save-excursion
6502 (condition-case nil
6503 (progn
6504 (org-back-to-heading t)
6505 (funcall outline-level))
6506 (error nil))))
6508 (defun org-get-previous-line-level ()
6509 "Return the outline depth of the last headline before the current line.
6510 Returns 0 for the first headline in the buffer, and nil if before the
6511 first headline."
6512 (let ((current-level (org-current-level))
6513 (prev-level (when (> (line-number-at-pos) 1)
6514 (save-excursion
6515 (beginning-of-line 0)
6516 (org-current-level)))))
6517 (cond ((null current-level) nil) ; Before first headline
6518 ((null prev-level) 0) ; At first headline
6519 (prev-level))))
6521 (defun org-reduced-level (l)
6522 "Compute the effective level of a heading.
6523 This takes into account the setting of `org-odd-levels-only'."
6524 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6526 (defun org-level-increment ()
6527 "Return the number of stars that will be added or removed at a
6528 time to headlines when structure editing, based on the value of
6529 `org-odd-levels-only'."
6530 (if org-odd-levels-only 2 1))
6532 (defun org-get-valid-level (level &optional change)
6533 "Rectify a level change under the influence of `org-odd-levels-only'
6534 LEVEL is a current level, CHANGE is by how much the level should be
6535 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6536 even level numbers will become the next higher odd number."
6537 (if org-odd-levels-only
6538 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6539 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6540 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6541 (max 1 (+ level (or change 0)))))
6543 (if (boundp 'define-obsolete-function-alias)
6544 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6545 (define-obsolete-function-alias 'org-get-legal-level
6546 'org-get-valid-level)
6547 (define-obsolete-function-alias 'org-get-legal-level
6548 'org-get-valid-level "23.1")))
6550 (defun org-promote ()
6551 "Promote the current heading higher up the tree.
6552 If the region is active in `transient-mark-mode', promote all headings
6553 in the region."
6554 (org-back-to-heading t)
6555 (let* ((level (save-match-data (funcall outline-level)))
6556 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6557 (diff (abs (- level (length up-head) -1))))
6558 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6559 (replace-match up-head nil t)
6560 ;; Fixup tag positioning
6561 (and org-auto-align-tags (org-set-tags nil t))
6562 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6563 (run-hooks 'org-after-promote-entry-hook)))
6565 (defun org-demote ()
6566 "Demote the current heading lower down the tree.
6567 If the region is active in `transient-mark-mode', demote all headings
6568 in the region."
6569 (org-back-to-heading t)
6570 (let* ((level (save-match-data (funcall outline-level)))
6571 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6572 (diff (abs (- level (length down-head) -1))))
6573 (replace-match down-head nil t)
6574 ;; Fixup tag positioning
6575 (and org-auto-align-tags (org-set-tags nil t))
6576 (if org-adapt-indentation (org-fixup-indentation diff))
6577 (run-hooks 'org-after-demote-entry-hook)))
6579 (defun org-cycle-level ()
6580 "Cycle the level of an empty headline through possible states.
6581 This goes first to child, then to parent, level, then up the hierarchy.
6582 After top level, it switches back to sibling level."
6583 (interactive)
6584 (let ((org-adapt-indentation nil))
6585 (when (org-point-at-end-of-empty-headline)
6586 (setq this-command 'org-cycle-level) ; Only needed for caching
6587 (let ((cur-level (org-current-level))
6588 (prev-level (org-get-previous-line-level)))
6589 (cond
6590 ;; If first headline in file, promote to top-level.
6591 ((= prev-level 0)
6592 (loop repeat (/ (- cur-level 1) (org-level-increment))
6593 do (org-do-promote)))
6594 ;; If same level as prev, demote one.
6595 ((= prev-level cur-level)
6596 (org-do-demote))
6597 ;; If parent is top-level, promote to top level if not already.
6598 ((= prev-level 1)
6599 (loop repeat (/ (- cur-level 1) (org-level-increment))
6600 do (org-do-promote)))
6601 ;; If top-level, return to prev-level.
6602 ((= cur-level 1)
6603 (loop repeat (/ (- prev-level 1) (org-level-increment))
6604 do (org-do-demote)))
6605 ;; If less than prev-level, promote one.
6606 ((< cur-level prev-level)
6607 (org-do-promote))
6608 ;; If deeper than prev-level, promote until higher than
6609 ;; prev-level.
6610 ((> cur-level prev-level)
6611 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
6612 do (org-do-promote))))
6613 t))))
6615 (defun org-map-tree (fun)
6616 "Call FUN for every heading underneath the current one."
6617 (org-back-to-heading)
6618 (let ((level (funcall outline-level)))
6619 (save-excursion
6620 (funcall fun)
6621 (while (and (progn
6622 (outline-next-heading)
6623 (> (funcall outline-level) level))
6624 (not (eobp)))
6625 (funcall fun)))))
6627 (defun org-map-region (fun beg end)
6628 "Call FUN for every heading between BEG and END."
6629 (let ((org-ignore-region t))
6630 (save-excursion
6631 (setq end (copy-marker end))
6632 (goto-char beg)
6633 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6634 (< (point) end))
6635 (funcall fun))
6636 (while (and (progn
6637 (outline-next-heading)
6638 (< (point) end))
6639 (not (eobp)))
6640 (funcall fun)))))
6642 (defun org-fixup-indentation (diff)
6643 "Change the indentation in the current entry by DIFF
6644 However, if any line in the current entry has no indentation, or if it
6645 would end up with no indentation after the change, nothing at all is done."
6646 (save-excursion
6647 (let ((end (save-excursion (outline-next-heading)
6648 (point-marker)))
6649 (prohibit (if (> diff 0)
6650 "^\\S-"
6651 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6652 col)
6653 (unless (save-excursion (end-of-line 1)
6654 (re-search-forward prohibit end t))
6655 (while (and (< (point) end)
6656 (re-search-forward "^[ \t]+" end t))
6657 (goto-char (match-end 0))
6658 (setq col (current-column))
6659 (if (< diff 0) (replace-match ""))
6660 (org-indent-to-column (+ diff col))))
6661 (move-marker end nil))))
6663 (defun org-convert-to-odd-levels ()
6664 "Convert an org-mode file with all levels allowed to one with odd levels.
6665 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6666 level 5 etc."
6667 (interactive)
6668 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6669 (let ((outline-regexp org-outline-regexp)
6670 (outline-level 'org-outline-level)
6671 (org-odd-levels-only nil) n)
6672 (save-excursion
6673 (goto-char (point-min))
6674 (while (re-search-forward "^\\*\\*+ " nil t)
6675 (setq n (- (length (match-string 0)) 2))
6676 (while (>= (setq n (1- n)) 0)
6677 (org-demote))
6678 (end-of-line 1))))))
6680 (defun org-convert-to-oddeven-levels ()
6681 "Convert an org-mode file with only odd levels to one with odd and even levels.
6682 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6683 section with an even level, conversion would destroy the structure of the file. An error
6684 is signaled in this case."
6685 (interactive)
6686 (goto-char (point-min))
6687 ;; First check if there are no even levels
6688 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6689 (org-show-context t)
6690 (error "Not all levels are odd in this file. Conversion not possible"))
6691 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6692 (let ((outline-regexp org-outline-regexp)
6693 (outline-level 'org-outline-level)
6694 (org-odd-levels-only nil) n)
6695 (save-excursion
6696 (goto-char (point-min))
6697 (while (re-search-forward "^\\*\\*+ " nil t)
6698 (setq n (/ (1- (length (match-string 0))) 2))
6699 (while (>= (setq n (1- n)) 0)
6700 (org-promote))
6701 (end-of-line 1))))))
6703 (defun org-tr-level (n)
6704 "Make N odd if required."
6705 (if org-odd-levels-only (1+ (/ n 2)) n))
6707 ;;; Vertical tree motion, cutting and pasting of subtrees
6709 (defun org-move-subtree-up (&optional arg)
6710 "Move the current subtree up past ARG headlines of the same level."
6711 (interactive "p")
6712 (org-move-subtree-down (- (prefix-numeric-value arg))))
6714 (defun org-move-subtree-down (&optional arg)
6715 "Move the current subtree down past ARG headlines of the same level."
6716 (interactive "p")
6717 (setq arg (prefix-numeric-value arg))
6718 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6719 'org-get-last-sibling))
6720 (ins-point (make-marker))
6721 (cnt (abs arg))
6722 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6723 ;; Select the tree
6724 (org-back-to-heading)
6725 (setq beg0 (point))
6726 (save-excursion
6727 (setq ne-beg (org-back-over-empty-lines))
6728 (setq beg (point)))
6729 (save-match-data
6730 (save-excursion (outline-end-of-heading)
6731 (setq folded (org-invisible-p)))
6732 (outline-end-of-subtree))
6733 (outline-next-heading)
6734 (setq ne-end (org-back-over-empty-lines))
6735 (setq end (point))
6736 (goto-char beg0)
6737 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6738 ;; include less whitespace
6739 (save-excursion
6740 (goto-char beg)
6741 (forward-line (- ne-beg ne-end))
6742 (setq beg (point))))
6743 ;; Find insertion point, with error handling
6744 (while (> cnt 0)
6745 (or (and (funcall movfunc) (looking-at outline-regexp))
6746 (progn (goto-char beg0)
6747 (error "Cannot move past superior level or buffer limit")))
6748 (setq cnt (1- cnt)))
6749 (if (> arg 0)
6750 ;; Moving forward - still need to move over subtree
6751 (progn (org-end-of-subtree t t)
6752 (save-excursion
6753 (org-back-over-empty-lines)
6754 (or (bolp) (newline)))))
6755 (setq ne-ins (org-back-over-empty-lines))
6756 (move-marker ins-point (point))
6757 (setq txt (buffer-substring beg end))
6758 (org-save-markers-in-region beg end)
6759 (delete-region beg end)
6760 (org-remove-empty-overlays-at beg)
6761 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6762 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6763 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6764 (let ((bbb (point)))
6765 (insert-before-markers txt)
6766 (org-reinstall-markers-in-region bbb)
6767 (move-marker ins-point bbb))
6768 (or (bolp) (insert "\n"))
6769 (setq ins-end (point))
6770 (goto-char ins-point)
6771 (org-skip-whitespace)
6772 (when (and (< arg 0)
6773 (org-first-sibling-p)
6774 (> ne-ins ne-beg))
6775 ;; Move whitespace back to beginning
6776 (save-excursion
6777 (goto-char ins-end)
6778 (let ((kill-whole-line t))
6779 (kill-line (- ne-ins ne-beg)) (point)))
6780 (insert (make-string (- ne-ins ne-beg) ?\n)))
6781 (move-marker ins-point nil)
6782 (if folded
6783 (hide-subtree)
6784 (org-show-entry)
6785 (show-children)
6786 (org-cycle-hide-drawers 'children))
6787 (org-clean-visibility-after-subtree-move)))
6789 (defvar org-subtree-clip ""
6790 "Clipboard for cut and paste of subtrees.
6791 This is actually only a copy of the kill, because we use the normal kill
6792 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6794 (defvar org-subtree-clip-folded nil
6795 "Was the last copied subtree folded?
6796 This is used to fold the tree back after pasting.")
6798 (defun org-cut-subtree (&optional n)
6799 "Cut the current subtree into the clipboard.
6800 With prefix arg N, cut this many sequential subtrees.
6801 This is a short-hand for marking the subtree and then cutting it."
6802 (interactive "p")
6803 (org-copy-subtree n 'cut))
6805 (defun org-copy-subtree (&optional n cut force-store-markers)
6806 "Cut the current subtree into the clipboard.
6807 With prefix arg N, cut this many sequential subtrees.
6808 This is a short-hand for marking the subtree and then copying it.
6809 If CUT is non-nil, actually cut the subtree.
6810 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6811 of some markers in the region, even if CUT is non-nil. This is
6812 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6813 (interactive "p")
6814 (let (beg end folded (beg0 (point)))
6815 (if (interactive-p)
6816 (org-back-to-heading nil) ; take what looks like a subtree
6817 (org-back-to-heading t)) ; take what is really there
6818 (org-back-over-empty-lines)
6819 (setq beg (point))
6820 (skip-chars-forward " \t\r\n")
6821 (save-match-data
6822 (save-excursion (outline-end-of-heading)
6823 (setq folded (org-invisible-p)))
6824 (condition-case nil
6825 (org-forward-same-level (1- n) t)
6826 (error nil))
6827 (org-end-of-subtree t t))
6828 (org-back-over-empty-lines)
6829 (setq end (point))
6830 (goto-char beg0)
6831 (when (> end beg)
6832 (setq org-subtree-clip-folded folded)
6833 (when (or cut force-store-markers)
6834 (org-save-markers-in-region beg end))
6835 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6836 (setq org-subtree-clip (current-kill 0))
6837 (message "%s: Subtree(s) with %d characters"
6838 (if cut "Cut" "Copied")
6839 (length org-subtree-clip)))))
6841 (defun org-paste-subtree (&optional level tree for-yank)
6842 "Paste the clipboard as a subtree, with modification of headline level.
6843 The entire subtree is promoted or demoted in order to match a new headline
6844 level.
6846 If the cursor is at the beginning of a headline, the same level as
6847 that headline is used to paste the tree
6849 If not, the new level is derived from the *visible* headings
6850 before and after the insertion point, and taken to be the inferior headline
6851 level of the two. So if the previous visible heading is level 3 and the
6852 next is level 4 (or vice versa), level 4 will be used for insertion.
6853 This makes sure that the subtree remains an independent subtree and does
6854 not swallow low level entries.
6856 You can also force a different level, either by using a numeric prefix
6857 argument, or by inserting the heading marker by hand. For example, if the
6858 cursor is after \"*****\", then the tree will be shifted to level 5.
6860 If optional TREE is given, use this text instead of the kill ring.
6862 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6863 move back over whitespace before inserting, and move point to the end of
6864 the inserted text when done."
6865 (interactive "P")
6866 (setq tree (or tree (and kill-ring (current-kill 0))))
6867 (unless (org-kill-is-subtree-p tree)
6868 (error "%s"
6869 (substitute-command-keys
6870 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6871 (let* ((visp (not (org-invisible-p)))
6872 (txt tree)
6873 (^re (concat "^\\(" outline-regexp "\\)"))
6874 (re (concat "\\(" outline-regexp "\\)"))
6875 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6877 (old-level (if (string-match ^re txt)
6878 (- (match-end 0) (match-beginning 0) 1)
6879 -1))
6880 (force-level (cond (level (prefix-numeric-value level))
6881 ((and (looking-at "[ \t]*$")
6882 (string-match
6883 ^re_ (buffer-substring
6884 (point-at-bol) (point))))
6885 (- (match-end 1) (match-beginning 1)))
6886 ((and (bolp)
6887 (looking-at org-outline-regexp))
6888 (- (match-end 0) (point) 1))
6889 (t nil)))
6890 (previous-level (save-excursion
6891 (condition-case nil
6892 (progn
6893 (outline-previous-visible-heading 1)
6894 (if (looking-at re)
6895 (- (match-end 0) (match-beginning 0) 1)
6897 (error 1))))
6898 (next-level (save-excursion
6899 (condition-case nil
6900 (progn
6901 (or (looking-at outline-regexp)
6902 (outline-next-visible-heading 1))
6903 (if (looking-at re)
6904 (- (match-end 0) (match-beginning 0) 1)
6906 (error 1))))
6907 (new-level (or force-level (max previous-level next-level)))
6908 (shift (if (or (= old-level -1)
6909 (= new-level -1)
6910 (= old-level new-level))
6912 (- new-level old-level)))
6913 (delta (if (> shift 0) -1 1))
6914 (func (if (> shift 0) 'org-demote 'org-promote))
6915 (org-odd-levels-only nil)
6916 beg end newend)
6917 ;; Remove the forced level indicator
6918 (if force-level
6919 (delete-region (point-at-bol) (point)))
6920 ;; Paste
6921 (beginning-of-line 1)
6922 (unless for-yank (org-back-over-empty-lines))
6923 (setq beg (point))
6924 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6925 (insert-before-markers txt)
6926 (unless (string-match "\n\\'" txt) (insert "\n"))
6927 (setq newend (point))
6928 (org-reinstall-markers-in-region beg)
6929 (setq end (point))
6930 (goto-char beg)
6931 (skip-chars-forward " \t\n\r")
6932 (setq beg (point))
6933 (if (and (org-invisible-p) visp)
6934 (save-excursion (outline-show-heading)))
6935 ;; Shift if necessary
6936 (unless (= shift 0)
6937 (save-restriction
6938 (narrow-to-region beg end)
6939 (while (not (= shift 0))
6940 (org-map-region func (point-min) (point-max))
6941 (setq shift (+ delta shift)))
6942 (goto-char (point-min))
6943 (setq newend (point-max))))
6944 (when (or (interactive-p) for-yank)
6945 (message "Clipboard pasted as level %d subtree" new-level))
6946 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6947 kill-ring
6948 (eq org-subtree-clip (current-kill 0))
6949 org-subtree-clip-folded)
6950 ;; The tree was folded before it was killed/copied
6951 (hide-subtree))
6952 (and for-yank (goto-char newend))))
6954 (defun org-kill-is-subtree-p (&optional txt)
6955 "Check if the current kill is an outline subtree, or a set of trees.
6956 Returns nil if kill does not start with a headline, or if the first
6957 headline level is not the largest headline level in the tree.
6958 So this will actually accept several entries of equal levels as well,
6959 which is OK for `org-paste-subtree'.
6960 If optional TXT is given, check this string instead of the current kill."
6961 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6962 (start-level (and kill
6963 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6964 org-outline-regexp "\\)")
6965 kill)
6966 (- (match-end 2) (match-beginning 2) 1)))
6967 (re (concat "^" org-outline-regexp))
6968 (start (1+ (or (match-beginning 2) -1))))
6969 (if (not start-level)
6970 (progn
6971 nil) ;; does not even start with a heading
6972 (catch 'exit
6973 (while (setq start (string-match re kill (1+ start)))
6974 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6975 (throw 'exit nil)))
6976 t))))
6978 (defvar org-markers-to-move nil
6979 "Markers that should be moved with a cut-and-paste operation.
6980 Those markers are stored together with their positions relative to
6981 the start of the region.")
6983 (defun org-save-markers-in-region (beg end)
6984 "Check markers in region.
6985 If these markers are between BEG and END, record their position relative
6986 to BEG, so that after moving the block of text, we can put the markers back
6987 into place.
6988 This function gets called just before an entry or tree gets cut from the
6989 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6990 called immediately, to move the markers with the entries."
6991 (setq org-markers-to-move nil)
6992 (when (featurep 'org-clock)
6993 (org-clock-save-markers-for-cut-and-paste beg end))
6994 (when (featurep 'org-agenda)
6995 (org-agenda-save-markers-for-cut-and-paste beg end)))
6997 (defun org-check-and-save-marker (marker beg end)
6998 "Check if MARKER is between BEG and END.
6999 If yes, remember the marker and the distance to BEG."
7000 (when (and (marker-buffer marker)
7001 (equal (marker-buffer marker) (current-buffer)))
7002 (if (and (>= marker beg) (< marker end))
7003 (push (cons marker (- marker beg)) org-markers-to-move))))
7005 (defun org-reinstall-markers-in-region (beg)
7006 "Move all remembered markers to their position relative to BEG."
7007 (mapc (lambda (x)
7008 (move-marker (car x) (+ beg (cdr x))))
7009 org-markers-to-move)
7010 (setq org-markers-to-move nil))
7012 (defun org-narrow-to-subtree ()
7013 "Narrow buffer to the current subtree."
7014 (interactive)
7015 (save-excursion
7016 (save-match-data
7017 (narrow-to-region
7018 (progn (org-back-to-heading t) (point))
7019 (progn (org-end-of-subtree t t)
7020 (if (org-on-heading-p) (backward-char 1))
7021 (point))))))
7023 (defun org-clone-subtree-with-time-shift (n &optional shift)
7024 "Clone the task (subtree) at point N times.
7025 The clones will be inserted as siblings.
7027 In interactive use, the user will be prompted for the number of clones
7028 to be produced, and for a time SHIFT, which may be a repeater as used
7029 in time stamps, for example `+3d'.
7031 When a valid repeater is given and the entry contains any time stamps,
7032 the clones will become a sequence in time, with time stamps in the
7033 subtree shifted for each clone produced. If SHIFT is nil or the
7034 empty string, time stamps will be left alone.
7036 If the original subtree did contain time stamps with a repeater,
7037 the following will happen:
7038 - the repeater will be removed in each clone
7039 - an additional clone will be produced, with the current, unshifted
7040 date(s) in the entry.
7041 - the original entry will be placed *after* all the clones, with
7042 repeater intact.
7043 - the start days in the repeater in the original entry will be shifted
7044 to past the last clone.
7045 I this way you can spell out a number of instances of a repeating task,
7046 and still retain the repeater to cover future instances of the task."
7047 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7048 (let (beg end template task
7049 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7050 (if (not (and (integerp n) (> n 0)))
7051 (error "Invalid number of replications %s" n))
7052 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7053 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7054 shift)))
7055 (error "Invalid shift specification %s" shift))
7056 (when doshift
7057 (setq shift-n (string-to-number (match-string 1 shift))
7058 shift-what (cdr (assoc (match-string 2 shift)
7059 '(("d" . day) ("w" . week)
7060 ("m" . month) ("y" . year))))))
7061 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7062 (setq nmin 1 nmax n)
7063 (org-back-to-heading t)
7064 (setq beg (point))
7065 (org-end-of-subtree t t)
7066 (or (bolp) (insert "\n"))
7067 (setq end (point))
7068 (setq template (buffer-substring beg end))
7069 (when (and doshift
7070 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7071 (delete-region beg end)
7072 (setq end beg)
7073 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7074 (goto-char end)
7075 (loop for n from nmin to nmax do
7076 (if (not doshift)
7077 (setq task template)
7078 (with-temp-buffer
7079 (insert template)
7080 (org-mode)
7081 (goto-char (point-min))
7082 (while (re-search-forward org-ts-regexp-both nil t)
7083 (org-timestamp-change (* n shift-n) shift-what))
7084 (unless (= n n-no-remove)
7085 (goto-char (point-min))
7086 (while (re-search-forward org-ts-regexp nil t)
7087 (save-excursion
7088 (goto-char (match-beginning 0))
7089 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7090 (delete-region (match-beginning 1) (match-end 1))))))
7091 (setq task (buffer-string))))
7092 (insert task))
7093 (goto-char beg)))
7095 ;;; Outline Sorting
7097 (defun org-sort (with-case)
7098 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
7099 Optional argument WITH-CASE means sort case-sensitively.
7100 With a double prefix argument, also remove duplicate entries."
7101 (interactive "P")
7102 (if (org-at-table-p)
7103 (org-call-with-arg 'org-table-sort-lines with-case)
7104 (org-call-with-arg 'org-sort-entries-or-items with-case)))
7106 (defun org-sort-remove-invisible (s)
7107 (remove-text-properties 0 (length s) org-rm-props s)
7108 (while (string-match org-bracket-link-regexp s)
7109 (setq s (replace-match (if (match-end 2)
7110 (match-string 3 s)
7111 (match-string 1 s)) t t s)))
7114 (defvar org-priority-regexp) ; defined later in the file
7116 (defvar org-after-sorting-entries-or-items-hook nil
7117 "Hook that is run after a bunch of entries or items have been sorted.
7118 When children are sorted, the cursor is in the parent line when this
7119 hook gets called. When a region or a plain list is sorted, the cursor
7120 will be in the first entry of the sorted region/list.")
7122 (defun org-sort-entries-or-items
7123 (&optional with-case sorting-type getkey-func compare-func property)
7124 "Sort entries on a certain level of an outline tree, or plain list items.
7125 If there is an active region, the entries in the region are sorted.
7126 Else, if the cursor is before the first entry, sort the top-level items.
7127 Else, the children of the entry at point are sorted.
7128 If the cursor is at the first item in a plain list, the list items will be
7129 sorted.
7131 Sorting can be alphabetically, numerically, by date/time as given by
7132 a time stamp, by a property or by priority.
7134 The command prompts for the sorting type unless it has been given to the
7135 function through the SORTING-TYPE argument, which needs to a character,
7136 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7137 precise meaning of each character:
7139 n Numerically, by converting the beginning of the entry/item to a number.
7140 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7141 t By date/time, either the first active time stamp in the entry, or, if
7142 none exist, by the first inactive one.
7143 In items, only the first line will be checked.
7144 s By the scheduled date/time.
7145 d By deadline date/time.
7146 c By creation time, which is assumed to be the first inactive time stamp
7147 at the beginning of a line.
7148 p By priority according to the cookie.
7149 r By the value of a property.
7151 Capital letters will reverse the sort order.
7153 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7154 called with point at the beginning of the record. It must return either
7155 a string or a number that should serve as the sorting key for that record.
7157 Comparing entries ignores case by default. However, with an optional argument
7158 WITH-CASE, the sorting considers case as well."
7159 (interactive "P")
7160 (let ((case-func (if with-case 'identity 'downcase))
7161 start beg end stars re re2
7162 txt what tmp plain-list-p)
7163 ;; Find beginning and end of region to sort
7164 (cond
7165 ((org-region-active-p)
7166 ;; we will sort the region
7167 (setq end (region-end)
7168 what "region")
7169 (goto-char (region-beginning))
7170 (if (not (org-on-heading-p)) (outline-next-heading))
7171 (setq start (point)))
7172 ((org-at-item-p)
7173 ;; we will sort this plain list
7174 (org-beginning-of-item-list) (setq start (point))
7175 (org-end-of-item-list)
7176 (or (bolp) (insert "\n"))
7177 (setq end (point))
7178 (goto-char start)
7179 (setq plain-list-p t
7180 what "plain list"))
7181 ((or (org-on-heading-p)
7182 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7183 ;; we will sort the children of the current headline
7184 (org-back-to-heading)
7185 (setq start (point)
7186 end (progn (org-end-of-subtree t t)
7187 (or (bolp) (insert "\n"))
7188 (org-back-over-empty-lines)
7189 (point))
7190 what "children")
7191 (goto-char start)
7192 (show-subtree)
7193 (outline-next-heading))
7195 ;; we will sort the top-level entries in this file
7196 (goto-char (point-min))
7197 (or (org-on-heading-p) (outline-next-heading))
7198 (setq start (point))
7199 (goto-char (point-max))
7200 (beginning-of-line 1)
7201 (when (looking-at ".*?\\S-")
7202 ;; File ends in a non-white line
7203 (end-of-line 1)
7204 (insert "\n"))
7205 (setq end (point-max))
7206 (setq what "top-level")
7207 (goto-char start)
7208 (show-all)))
7210 (setq beg (point))
7211 (if (>= beg end) (error "Nothing to sort"))
7213 (unless plain-list-p
7214 (looking-at "\\(\\*+\\)")
7215 (setq stars (match-string 1)
7216 re (concat "^" (regexp-quote stars) " +")
7217 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7218 txt (buffer-substring beg end))
7219 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7220 (if (and (not (equal stars "*")) (string-match re2 txt))
7221 (error "Region to sort contains a level above the first entry")))
7223 (unless sorting-type
7224 (message
7225 (if plain-list-p
7226 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7227 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7228 [t]ime [s]cheduled [d]eadline [c]reated
7229 A/N/T/S/D/C/P/O/F means reversed:")
7230 what)
7231 (setq sorting-type (read-char-exclusive))
7233 (and (= (downcase sorting-type) ?f)
7234 (setq getkey-func
7235 (org-icompleting-read "Sort using function: "
7236 obarray 'fboundp t nil nil))
7237 (setq getkey-func (intern getkey-func)))
7239 (and (= (downcase sorting-type) ?r)
7240 (setq property
7241 (org-icompleting-read "Property: "
7242 (mapcar 'list (org-buffer-property-keys t))
7243 nil t))))
7245 (message "Sorting entries...")
7247 (save-restriction
7248 (narrow-to-region start end)
7250 (let ((dcst (downcase sorting-type))
7251 (case-fold-search nil)
7252 (now (current-time)))
7253 (sort-subr
7254 (/= dcst sorting-type)
7255 ;; This function moves to the beginning character of the "record" to
7256 ;; be sorted.
7257 (if plain-list-p
7258 (lambda nil
7259 (if (org-at-item-p) t (goto-char (point-max))))
7260 (lambda nil
7261 (if (re-search-forward re nil t)
7262 (goto-char (match-beginning 0))
7263 (goto-char (point-max)))))
7264 ;; This function moves to the last character of the "record" being
7265 ;; sorted.
7266 (if plain-list-p
7267 'org-end-of-item
7268 (lambda nil
7269 (save-match-data
7270 (condition-case nil
7271 (outline-forward-same-level 1)
7272 (error
7273 (goto-char (point-max)))))))
7275 ;; This function returns the value that gets sorted against.
7276 (if plain-list-p
7277 (lambda nil
7278 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7279 (cond
7280 ((= dcst ?n)
7281 (string-to-number (buffer-substring (match-end 0)
7282 (point-at-eol))))
7283 ((= dcst ?a)
7284 (buffer-substring (match-end 0) (point-at-eol)))
7285 ((= dcst ?t)
7286 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7287 (re-search-forward org-ts-regexp-both
7288 (point-at-eol) t))
7289 (org-time-string-to-seconds (match-string 0))
7290 (org-float-time now)))
7291 ((= dcst ?f)
7292 (if getkey-func
7293 (progn
7294 (setq tmp (funcall getkey-func))
7295 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7296 tmp)
7297 (error "Invalid key function `%s'" getkey-func)))
7298 (t (error "Invalid sorting type `%c'" sorting-type)))))
7299 (lambda nil
7300 (cond
7301 ((= dcst ?n)
7302 (if (looking-at org-complex-heading-regexp)
7303 (string-to-number (match-string 4))
7304 nil))
7305 ((= dcst ?a)
7306 (if (looking-at org-complex-heading-regexp)
7307 (funcall case-func (match-string 4))
7308 nil))
7309 ((= dcst ?t)
7310 (let ((end (save-excursion (outline-next-heading) (point))))
7311 (if (or (re-search-forward org-ts-regexp end t)
7312 (re-search-forward org-ts-regexp-both end t))
7313 (org-time-string-to-seconds (match-string 0))
7314 (org-float-time now))))
7315 ((= dcst ?c)
7316 (let ((end (save-excursion (outline-next-heading) (point))))
7317 (if (re-search-forward
7318 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7319 end t)
7320 (org-time-string-to-seconds (match-string 0))
7321 (org-float-time now))))
7322 ((= dcst ?s)
7323 (let ((end (save-excursion (outline-next-heading) (point))))
7324 (if (re-search-forward org-scheduled-time-regexp end t)
7325 (org-time-string-to-seconds (match-string 1))
7326 (org-float-time now))))
7327 ((= dcst ?d)
7328 (let ((end (save-excursion (outline-next-heading) (point))))
7329 (if (re-search-forward org-deadline-time-regexp end t)
7330 (org-time-string-to-seconds (match-string 1))
7331 (org-float-time now))))
7332 ((= dcst ?p)
7333 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7334 (string-to-char (match-string 2))
7335 org-default-priority))
7336 ((= dcst ?r)
7337 (or (org-entry-get nil property) ""))
7338 ((= dcst ?o)
7339 (if (looking-at org-complex-heading-regexp)
7340 (- 9999 (length (member (match-string 2)
7341 org-todo-keywords-1)))))
7342 ((= dcst ?f)
7343 (if getkey-func
7344 (progn
7345 (setq tmp (funcall getkey-func))
7346 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7347 tmp)
7348 (error "Invalid key function `%s'" getkey-func)))
7349 (t (error "Invalid sorting type `%c'" sorting-type)))))
7351 (cond
7352 ((= dcst ?a) 'string<)
7353 ((= dcst ?f) compare-func)
7354 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7355 (t nil)))))
7356 (run-hooks 'org-after-sorting-entries-or-items-hook)
7357 (message "Sorting entries...done")))
7359 (defun org-do-sort (table what &optional with-case sorting-type)
7360 "Sort TABLE of WHAT according to SORTING-TYPE.
7361 The user will be prompted for the SORTING-TYPE if the call to this
7362 function does not specify it. WHAT is only for the prompt, to indicate
7363 what is being sorted. The sorting key will be extracted from
7364 the car of the elements of the table.
7365 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7366 (unless sorting-type
7367 (message
7368 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7369 what)
7370 (setq sorting-type (read-char-exclusive)))
7371 (let ((dcst (downcase sorting-type))
7372 extractfun comparefun)
7373 ;; Define the appropriate functions
7374 (cond
7375 ((= dcst ?n)
7376 (setq extractfun 'string-to-number
7377 comparefun (if (= dcst sorting-type) '< '>)))
7378 ((= dcst ?a)
7379 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7380 (lambda(x) (downcase (org-sort-remove-invisible x))))
7381 comparefun (if (= dcst sorting-type)
7382 'string<
7383 (lambda (a b) (and (not (string< a b))
7384 (not (string= a b)))))))
7385 ((= dcst ?t)
7386 (setq extractfun
7387 (lambda (x)
7388 (if (or (string-match org-ts-regexp x)
7389 (string-match org-ts-regexp-both x))
7390 (org-float-time
7391 (org-time-string-to-time (match-string 0 x)))
7393 comparefun (if (= dcst sorting-type) '< '>)))
7394 (t (error "Invalid sorting type `%c'" sorting-type)))
7396 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7397 table)
7398 (lambda (a b) (funcall comparefun (car a) (car b))))))
7401 ;;; The orgstruct minor mode
7403 ;; Define a minor mode which can be used in other modes in order to
7404 ;; integrate the org-mode structure editing commands.
7406 ;; This is really a hack, because the org-mode structure commands use
7407 ;; keys which normally belong to the major mode. Here is how it
7408 ;; works: The minor mode defines all the keys necessary to operate the
7409 ;; structure commands, but wraps the commands into a function which
7410 ;; tests if the cursor is currently at a headline or a plain list
7411 ;; item. If that is the case, the structure command is used,
7412 ;; temporarily setting many Org-mode variables like regular
7413 ;; expressions for filling etc. However, when any of those keys is
7414 ;; used at a different location, function uses `key-binding' to look
7415 ;; up if the key has an associated command in another currently active
7416 ;; keymap (minor modes, major mode, global), and executes that
7417 ;; command. There might be problems if any of the keys is otherwise
7418 ;; used as a prefix key.
7420 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7421 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7422 ;; addresses this by checking explicitly for both bindings.
7424 (defvar orgstruct-mode-map (make-sparse-keymap)
7425 "Keymap for the minor `orgstruct-mode'.")
7427 (defvar org-local-vars nil
7428 "List of local variables, for use by `orgstruct-mode'")
7430 ;;;###autoload
7431 (define-minor-mode orgstruct-mode
7432 "Toggle the minor more `orgstruct-mode'.
7433 This mode is for using Org-mode structure commands in other modes.
7434 The following key behave as if Org-mode was active, if the cursor
7435 is on a headline, or on a plain list item (both in the definition
7436 of Org-mode).
7438 M-up Move entry/item up
7439 M-down Move entry/item down
7440 M-left Promote
7441 M-right Demote
7442 M-S-up Move entry/item up
7443 M-S-down Move entry/item down
7444 M-S-left Promote subtree
7445 M-S-right Demote subtree
7446 M-q Fill paragraph and items like in Org-mode
7447 C-c ^ Sort entries
7448 C-c - Cycle list bullet
7449 TAB Cycle item visibility
7450 M-RET Insert new heading/item
7451 S-M-RET Insert new TODO heading / Checkbox item
7452 C-c C-c Set tags / toggle checkbox"
7453 nil " OrgStruct" nil
7454 (org-load-modules-maybe)
7455 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7457 ;;;###autoload
7458 (defun turn-on-orgstruct ()
7459 "Unconditionally turn on `orgstruct-mode'."
7460 (orgstruct-mode 1))
7462 (defun orgstruct++-mode (&optional arg)
7463 "Toggle `orgstruct-mode', the enhanced version of it.
7464 In addition to setting orgstruct-mode, this also exports all indentation
7465 and autofilling variables from org-mode into the buffer. It will also
7466 recognize item context in multiline items.
7467 Note that turning off orgstruct-mode will *not* remove the
7468 indentation/paragraph settings. This can only be done by refreshing the
7469 major mode, for example with \\[normal-mode]."
7470 (interactive "P")
7471 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7472 (if (< arg 1)
7473 (orgstruct-mode -1)
7474 (orgstruct-mode 1)
7475 (let (var val)
7476 (mapc
7477 (lambda (x)
7478 (when (string-match
7479 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7480 (symbol-name (car x)))
7481 (setq var (car x) val (nth 1 x))
7482 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7483 org-local-vars)
7484 (org-set-local 'orgstruct-is-++ t))))
7486 (defvar orgstruct-is-++ nil
7487 "Is orgstruct-mode in ++ version in the current-buffer?")
7488 (make-variable-buffer-local 'orgstruct-is-++)
7490 ;;;###autoload
7491 (defun turn-on-orgstruct++ ()
7492 "Unconditionally turn on `orgstruct++-mode'."
7493 (orgstruct++-mode 1))
7495 (defun orgstruct-error ()
7496 "Error when there is no default binding for a structure key."
7497 (interactive)
7498 (error "This key has no function outside structure elements"))
7500 (defun orgstruct-setup ()
7501 "Setup orgstruct keymaps."
7502 (let ((nfunc 0)
7503 (bindings
7504 (list
7505 '([(meta up)] org-metaup)
7506 '([(meta down)] org-metadown)
7507 '([(meta left)] org-metaleft)
7508 '([(meta right)] org-metaright)
7509 '([(meta shift up)] org-shiftmetaup)
7510 '([(meta shift down)] org-shiftmetadown)
7511 '([(meta shift left)] org-shiftmetaleft)
7512 '([(meta shift right)] org-shiftmetaright)
7513 '([?\e (up)] org-metaup)
7514 '([?\e (down)] org-metadown)
7515 '([?\e (left)] org-metaleft)
7516 '([?\e (right)] org-metaright)
7517 '([?\e (shift up)] org-shiftmetaup)
7518 '([?\e (shift down)] org-shiftmetadown)
7519 '([?\e (shift left)] org-shiftmetaleft)
7520 '([?\e (shift right)] org-shiftmetaright)
7521 '([(shift up)] org-shiftup)
7522 '([(shift down)] org-shiftdown)
7523 '([(shift left)] org-shiftleft)
7524 '([(shift right)] org-shiftright)
7525 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7526 '("\M-q" fill-paragraph)
7527 '("\C-c^" org-sort)
7528 '("\C-c-" org-cycle-list-bullet)))
7529 elt key fun cmd)
7530 (while (setq elt (pop bindings))
7531 (setq nfunc (1+ nfunc))
7532 (setq key (org-key (car elt))
7533 fun (nth 1 elt)
7534 cmd (orgstruct-make-binding fun nfunc key))
7535 (org-defkey orgstruct-mode-map key cmd))
7537 ;; Special treatment needed for TAB and RET
7538 (org-defkey orgstruct-mode-map [(tab)]
7539 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7540 (org-defkey orgstruct-mode-map "\C-i"
7541 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7543 (org-defkey orgstruct-mode-map "\M-\C-m"
7544 (orgstruct-make-binding 'org-insert-heading 105
7545 "\M-\C-m" [(meta return)]))
7546 (org-defkey orgstruct-mode-map [(meta return)]
7547 (orgstruct-make-binding 'org-insert-heading 106
7548 [(meta return)] "\M-\C-m"))
7550 (org-defkey orgstruct-mode-map [(shift meta return)]
7551 (orgstruct-make-binding 'org-insert-todo-heading 107
7552 [(meta return)] "\M-\C-m"))
7554 (org-defkey orgstruct-mode-map "\e\C-m"
7555 (orgstruct-make-binding 'org-insert-heading 108
7556 "\e\C-m" [?\e (return)]))
7557 (org-defkey orgstruct-mode-map [?\e (return)]
7558 (orgstruct-make-binding 'org-insert-heading 109
7559 [?\e (return)] "\e\C-m"))
7560 (org-defkey orgstruct-mode-map [?\e (shift return)]
7561 (orgstruct-make-binding 'org-insert-todo-heading 110
7562 [?\e (return)] "\e\C-m"))
7564 (unless org-local-vars
7565 (setq org-local-vars (org-get-local-variables)))
7569 (defun orgstruct-make-binding (fun n &rest keys)
7570 "Create a function for binding in the structure minor mode.
7571 FUN is the command to call inside a table. N is used to create a unique
7572 command name. KEYS are keys that should be checked in for a command
7573 to execute outside of tables."
7574 (eval
7575 (list 'defun
7576 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7577 '(arg)
7578 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7579 "Outside of structure, run the binding of `"
7580 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7581 "'.")
7582 '(interactive "p")
7583 (list 'if
7584 `(org-context-p 'headline 'item
7585 (and orgstruct-is-++
7586 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7587 'item-body))
7588 (list 'org-run-like-in-org-mode (list 'quote fun))
7589 (list 'let '(orgstruct-mode)
7590 (list 'call-interactively
7591 (append '(or)
7592 (mapcar (lambda (k)
7593 (list 'key-binding k))
7594 keys)
7595 '('orgstruct-error))))))))
7597 (defun org-context-p (&rest contexts)
7598 "Check if local context is any of CONTEXTS.
7599 Possible values in the list of contexts are `table', `headline', and `item'."
7600 (let ((pos (point)))
7601 (goto-char (point-at-bol))
7602 (prog1 (or (and (memq 'table contexts)
7603 (looking-at "[ \t]*|"))
7604 (and (memq 'headline contexts)
7605 ;;????????? (looking-at "\\*+"))
7606 (looking-at outline-regexp))
7607 (and (memq 'item contexts)
7608 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7609 (and (memq 'item-body contexts)
7610 (org-in-item-p)))
7611 (goto-char pos))))
7613 (defun org-get-local-variables ()
7614 "Return a list of all local variables in an org-mode buffer."
7615 (let (varlist)
7616 (with-current-buffer (get-buffer-create "*Org tmp*")
7617 (erase-buffer)
7618 (org-mode)
7619 (setq varlist (buffer-local-variables)))
7620 (kill-buffer "*Org tmp*")
7621 (delq nil
7622 (mapcar
7623 (lambda (x)
7624 (setq x
7625 (if (symbolp x)
7626 (list x)
7627 (list (car x) (list 'quote (cdr x)))))
7628 (if (string-match
7629 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7630 (symbol-name (car x)))
7631 x nil))
7632 varlist))))
7634 ;;;###autoload
7635 (defun org-run-like-in-org-mode (cmd)
7636 "Run a command, pretending that the current buffer is in Org-mode.
7637 This will temporarily bind local variables that are typically bound in
7638 Org-mode to the values they have in Org-mode, and then interactively
7639 call CMD."
7640 (org-load-modules-maybe)
7641 (unless org-local-vars
7642 (setq org-local-vars (org-get-local-variables)))
7643 (eval (list 'let org-local-vars
7644 (list 'call-interactively (list 'quote cmd)))))
7646 ;;;; Archiving
7648 (defun org-get-category (&optional pos)
7649 "Get the category applying to position POS."
7650 (get-text-property (or pos (point)) 'org-category))
7652 (defun org-refresh-category-properties ()
7653 "Refresh category text properties in the buffer."
7654 (let ((def-cat (cond
7655 ((null org-category)
7656 (if buffer-file-name
7657 (file-name-sans-extension
7658 (file-name-nondirectory buffer-file-name))
7659 "???"))
7660 ((symbolp org-category) (symbol-name org-category))
7661 (t org-category)))
7662 beg end cat pos optionp)
7663 (org-unmodified
7664 (save-excursion
7665 (save-restriction
7666 (widen)
7667 (goto-char (point-min))
7668 (put-text-property (point) (point-max) 'org-category def-cat)
7669 (while (re-search-forward
7670 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7671 (setq pos (match-end 0)
7672 optionp (equal (char-after (match-beginning 0)) ?#)
7673 cat (org-trim (match-string 2)))
7674 (if optionp
7675 (setq beg (point-at-bol) end (point-max))
7676 (org-back-to-heading t)
7677 (setq beg (point) end (org-end-of-subtree t t)))
7678 (put-text-property beg end 'org-category cat)
7679 (goto-char pos)))))))
7682 ;;;; Link Stuff
7684 ;;; Link abbreviations
7686 (defun org-link-expand-abbrev (link)
7687 "Apply replacements as defined in `org-link-abbrev-alist."
7688 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7689 (let* ((key (match-string 1 link))
7690 (as (or (assoc key org-link-abbrev-alist-local)
7691 (assoc key org-link-abbrev-alist)))
7692 (tag (and (match-end 2) (match-string 3 link)))
7693 rpl)
7694 (if (not as)
7695 link
7696 (setq rpl (cdr as))
7697 (cond
7698 ((symbolp rpl) (funcall rpl tag))
7699 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7700 ((string-match "%h" rpl)
7701 (replace-match (url-hexify-string (or tag "")) t t rpl))
7702 (t (concat rpl tag)))))
7703 link))
7705 ;;; Storing and inserting links
7707 (defvar org-insert-link-history nil
7708 "Minibuffer history for links inserted with `org-insert-link'.")
7710 (defvar org-stored-links nil
7711 "Contains the links stored with `org-store-link'.")
7713 (defvar org-store-link-plist nil
7714 "Plist with info about the most recently link created with `org-store-link'.")
7716 (defvar org-link-protocols nil
7717 "Link protocols added to Org-mode using `org-add-link-type'.")
7719 (defvar org-store-link-functions nil
7720 "List of functions that are called to create and store a link.
7721 Each function will be called in turn until one returns a non-nil
7722 value. Each function should check if it is responsible for creating
7723 this link (for example by looking at the major mode).
7724 If not, it must exit and return nil.
7725 If yes, it should return a non-nil value after a calling
7726 `org-store-link-props' with a list of properties and values.
7727 Special properties are:
7729 :type The link prefix. like \"http\". This must be given.
7730 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7731 This is obligatory as well.
7732 :description Optional default description for the second pair
7733 of brackets in an Org-mode link. The user can still change
7734 this when inserting this link into an Org-mode buffer.
7736 In addition to these, any additional properties can be specified
7737 and then used in remember templates.")
7739 (defun org-add-link-type (type &optional follow export)
7740 "Add TYPE to the list of `org-link-types'.
7741 Re-compute all regular expressions depending on `org-link-types'
7743 FOLLOW and EXPORT are two functions.
7745 FOLLOW should take the link path as the single argument and do whatever
7746 is necessary to follow the link, for example find a file or display
7747 a mail message.
7749 EXPORT should format the link path for export to one of the export formats.
7750 It should be a function accepting three arguments:
7752 path the path of the link, the text after the prefix (like \"http:\")
7753 desc the description of the link, if any, nil if there was no description
7754 format the export format, a symbol like `html' or `latex'.
7756 The function may use the FORMAT information to return different values
7757 depending on the format. The return value will be put literally into
7758 the exported file.
7759 Org-mode has a built-in default for exporting links. If you are happy with
7760 this default, there is no need to define an export function for the link
7761 type. For a simple example of an export function, see `org-bbdb.el'."
7762 (add-to-list 'org-link-types type t)
7763 (org-make-link-regexps)
7764 (if (assoc type org-link-protocols)
7765 (setcdr (assoc type org-link-protocols) (list follow export))
7766 (push (list type follow export) org-link-protocols)))
7768 (defvar org-agenda-buffer-name)
7770 ;;;###autoload
7771 (defun org-store-link (arg)
7772 "\\<org-mode-map>Store an org-link to the current location.
7773 This link is added to `org-stored-links' and can later be inserted
7774 into an org-buffer with \\[org-insert-link].
7776 For some link types, a prefix arg is interpreted:
7777 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7778 For file links, arg negates `org-context-in-file-links'."
7779 (interactive "P")
7780 (org-load-modules-maybe)
7781 (setq org-store-link-plist nil) ; reset
7782 (let ((outline-regexp (org-get-limited-outline-regexp))
7783 link cpltxt desc description search txt custom-id)
7784 (cond
7786 ((run-hook-with-args-until-success 'org-store-link-functions)
7787 (setq link (plist-get org-store-link-plist :link)
7788 desc (or (plist-get org-store-link-plist :description) link)))
7790 ((equal (buffer-name) "*Org Edit Src Example*")
7791 (let (label gc)
7792 (while (or (not label)
7793 (save-excursion
7794 (save-restriction
7795 (widen)
7796 (goto-char (point-min))
7797 (re-search-forward
7798 (regexp-quote (format org-coderef-label-format label))
7799 nil t))))
7800 (when label (message "Label exists already") (sit-for 2))
7801 (setq label (read-string "Code line label: " label)))
7802 (end-of-line 1)
7803 (setq link (format org-coderef-label-format label))
7804 (setq gc (- 79 (length link)))
7805 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7806 (insert link)
7807 (setq link (concat "(" label ")") desc nil)))
7809 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7810 ;; We are in the agenda, link to referenced location
7811 (let ((m (or (get-text-property (point) 'org-hd-marker)
7812 (get-text-property (point) 'org-marker))))
7813 (when m
7814 (org-with-point-at m
7815 (call-interactively 'org-store-link)))))
7817 ((eq major-mode 'calendar-mode)
7818 (let ((cd (calendar-cursor-to-date)))
7819 (setq link
7820 (format-time-string
7821 (car org-time-stamp-formats)
7822 (apply 'encode-time
7823 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7824 nil nil nil))))
7825 (org-store-link-props :type "calendar" :date cd)))
7827 ((eq major-mode 'w3-mode)
7828 (setq cpltxt (if (and (buffer-name)
7829 (not (string-match "Untitled" (buffer-name))))
7830 (buffer-name)
7831 (url-view-url t))
7832 link (org-make-link (url-view-url t)))
7833 (org-store-link-props :type "w3" :url (url-view-url t)))
7835 ((eq major-mode 'w3m-mode)
7836 (setq cpltxt (or w3m-current-title w3m-current-url)
7837 link (org-make-link w3m-current-url))
7838 (org-store-link-props :type "w3m" :url (url-view-url t)))
7840 ((setq search (run-hook-with-args-until-success
7841 'org-create-file-search-functions))
7842 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7843 "::" search))
7844 (setq cpltxt (or description link)))
7846 ((eq major-mode 'image-mode)
7847 (setq cpltxt (concat "file:"
7848 (abbreviate-file-name buffer-file-name))
7849 link (org-make-link cpltxt))
7850 (org-store-link-props :type "image" :file buffer-file-name))
7852 ((eq major-mode 'dired-mode)
7853 ;; link to the file in the current line
7854 (let ((file (dired-get-filename nil t)))
7855 (setq file (if file
7856 (abbreviate-file-name
7857 (expand-file-name (dired-get-filename nil t)))
7858 ;; otherwise, no file so use current directory.
7859 default-directory))
7860 (setq cpltxt (concat "file:" file)
7861 link (org-make-link cpltxt))))
7863 ((and buffer-file-name (org-mode-p))
7864 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7865 (cond
7866 ((org-in-regexp "<<\\(.*?\\)>>")
7867 (setq cpltxt
7868 (concat "file:"
7869 (abbreviate-file-name buffer-file-name)
7870 "::" (match-string 1))
7871 link (org-make-link cpltxt)))
7872 ((and (featurep 'org-id)
7873 (or (eq org-link-to-org-use-id t)
7874 (and (eq org-link-to-org-use-id 'create-if-interactive)
7875 (interactive-p))
7876 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7877 (interactive-p)
7878 (not custom-id))
7879 (and org-link-to-org-use-id
7880 (condition-case nil
7881 (org-entry-get nil "ID")
7882 (error nil)))))
7883 ;; We can make a link using the ID.
7884 (setq link (condition-case nil
7885 (prog1 (org-id-store-link)
7886 (setq desc (plist-get org-store-link-plist
7887 :description)))
7888 (error
7889 ;; probably before first headline, link to file only
7890 (concat "file:"
7891 (abbreviate-file-name buffer-file-name))))))
7893 ;; Just link to current headline
7894 (setq cpltxt (concat "file:"
7895 (abbreviate-file-name buffer-file-name)))
7896 ;; Add a context search string
7897 (when (org-xor org-context-in-file-links arg)
7898 (setq txt (cond
7899 ((org-on-heading-p) nil)
7900 ((org-region-active-p)
7901 (buffer-substring (region-beginning) (region-end)))
7902 (t nil)))
7903 (when (or (null txt) (string-match "\\S-" txt))
7904 (setq cpltxt
7905 (concat cpltxt "::"
7906 (condition-case nil
7907 (org-make-org-heading-search-string txt)
7908 (error "")))
7909 desc (or (nth 4 (ignore-errors
7910 (org-heading-components))) "NONE"))))
7911 (if (string-match "::\\'" cpltxt)
7912 (setq cpltxt (substring cpltxt 0 -2)))
7913 (setq link (org-make-link cpltxt)))))
7915 ((buffer-file-name (buffer-base-buffer))
7916 ;; Just link to this file here.
7917 (setq cpltxt (concat "file:"
7918 (abbreviate-file-name
7919 (buffer-file-name (buffer-base-buffer)))))
7920 ;; Add a context string
7921 (when (org-xor org-context-in-file-links arg)
7922 (setq txt (if (org-region-active-p)
7923 (buffer-substring (region-beginning) (region-end))
7924 (buffer-substring (point-at-bol) (point-at-eol))))
7925 ;; Only use search option if there is some text.
7926 (when (string-match "\\S-" txt)
7927 (setq cpltxt
7928 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7929 desc "NONE")))
7930 (setq link (org-make-link cpltxt)))
7932 ((interactive-p)
7933 (error "Cannot link to a buffer which is not visiting a file"))
7935 (t (setq link nil)))
7937 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7938 (setq link (or link cpltxt)
7939 desc (or desc cpltxt))
7940 (if (equal desc "NONE") (setq desc nil))
7942 (if (and (or (interactive-p) executing-kbd-macro) link)
7943 (progn
7944 (setq org-stored-links
7945 (cons (list link desc) org-stored-links))
7946 (message "Stored: %s" (or desc link))
7947 (when custom-id
7948 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7949 "::#" custom-id))
7950 (setq org-stored-links
7951 (cons (list link desc) org-stored-links))))
7952 (and link (org-make-link-string link desc)))))
7954 (defun org-store-link-props (&rest plist)
7955 "Store link properties, extract names and addresses."
7956 (let (x adr)
7957 (when (setq x (plist-get plist :from))
7958 (setq adr (mail-extract-address-components x))
7959 (setq plist (plist-put plist :fromname (car adr)))
7960 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7961 (when (setq x (plist-get plist :to))
7962 (setq adr (mail-extract-address-components x))
7963 (setq plist (plist-put plist :toname (car adr)))
7964 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7965 (let ((from (plist-get plist :from))
7966 (to (plist-get plist :to)))
7967 (when (and from to org-from-is-user-regexp)
7968 (setq plist
7969 (plist-put plist :fromto
7970 (if (string-match org-from-is-user-regexp from)
7971 (concat "to %t")
7972 (concat "from %f"))))))
7973 (setq org-store-link-plist plist))
7975 (defun org-add-link-props (&rest plist)
7976 "Add these properties to the link property list."
7977 (let (key value)
7978 (while plist
7979 (setq key (pop plist) value (pop plist))
7980 (setq org-store-link-plist
7981 (plist-put org-store-link-plist key value)))))
7983 (defun org-email-link-description (&optional fmt)
7984 "Return the description part of an email link.
7985 This takes information from `org-store-link-plist' and formats it
7986 according to FMT (default from `org-email-link-description-format')."
7987 (setq fmt (or fmt org-email-link-description-format))
7988 (let* ((p org-store-link-plist)
7989 (to (plist-get p :toaddress))
7990 (from (plist-get p :fromaddress))
7991 (table
7992 (list
7993 (cons "%c" (plist-get p :fromto))
7994 (cons "%F" (plist-get p :from))
7995 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7996 (cons "%T" (plist-get p :to))
7997 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7998 (cons "%s" (plist-get p :subject))
7999 (cons "%m" (plist-get p :message-id)))))
8000 (when (string-match "%c" fmt)
8001 ;; Check if the user wrote this message
8002 (if (and org-from-is-user-regexp from to
8003 (save-match-data (string-match org-from-is-user-regexp from)))
8004 (setq fmt (replace-match "to %t" t t fmt))
8005 (setq fmt (replace-match "from %f" t t fmt))))
8006 (org-replace-escapes fmt table)))
8008 (defun org-make-org-heading-search-string (&optional string heading)
8009 "Make search string for STRING or current headline."
8010 (interactive)
8011 (let ((s (or string (org-get-heading))))
8012 (unless (and string (not heading))
8013 ;; We are using a headline, clean up garbage in there.
8014 (if (string-match org-todo-regexp s)
8015 (setq s (replace-match "" t t s)))
8016 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
8017 (setq s (replace-match "" t t s)))
8018 (setq s (org-trim s))
8019 (if (string-match (concat "^\\(" org-quote-string "\\|"
8020 org-comment-string "\\)") s)
8021 (setq s (replace-match "" t t s)))
8022 (while (string-match org-ts-regexp s)
8023 (setq s (replace-match "" t t s))))
8024 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8025 (setq s (replace-match " " t t s)))
8026 (or string (setq s (concat "*" s))) ; Add * for headlines
8027 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8029 (defun org-make-link (&rest strings)
8030 "Concatenate STRINGS."
8031 (apply 'concat strings))
8033 (defun org-make-link-string (link &optional description)
8034 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8035 (unless (string-match "\\S-" link)
8036 (error "Empty link"))
8037 (when (and description
8038 (stringp description)
8039 (not (string-match "\\S-" description)))
8040 (setq description nil))
8041 (when (stringp description)
8042 ;; Remove brackets from the description, they are fatal.
8043 (while (string-match "\\[" description)
8044 (setq description (replace-match "{" t t description)))
8045 (while (string-match "\\]" description)
8046 (setq description (replace-match "}" t t description))))
8047 (when (equal (org-link-escape link) description)
8048 ;; No description needed, it is identical
8049 (setq description nil))
8050 (when (and (not description)
8051 (not (equal link (org-link-escape link))))
8052 (setq description (org-extract-attributes link)))
8053 (concat "[[" (org-link-escape link) "]"
8054 (if description (concat "[" description "]") "")
8055 "]"))
8057 (defconst org-link-escape-chars
8058 '((?\ . "%20")
8059 (?\[ . "%5B")
8060 (?\] . "%5D")
8061 (?\340 . "%E0") ; `a
8062 (?\342 . "%E2") ; ^a
8063 (?\347 . "%E7") ; ,c
8064 (?\350 . "%E8") ; `e
8065 (?\351 . "%E9") ; 'e
8066 (?\352 . "%EA") ; ^e
8067 (?\356 . "%EE") ; ^i
8068 (?\364 . "%F4") ; ^o
8069 (?\371 . "%F9") ; `u
8070 (?\373 . "%FB") ; ^u
8071 (?\; . "%3B")
8072 ;; (?? . "%3F")
8073 (?= . "%3D")
8074 (?+ . "%2B")
8076 "Association list of escapes for some characters problematic in links.
8077 This is the list that is used for internal purposes.")
8079 (defvar org-url-encoding-use-url-hexify nil)
8081 (defconst org-link-escape-chars-browser
8082 '((?\ . "%20")) ; 32 for the SPC char
8083 "Association list of escapes for some characters problematic in links.
8084 This is the list that is used before handing over to the browser.")
8086 (defun org-link-escape (text &optional table)
8087 "Escape characters in TEXT that are problematic for links."
8088 (if (and org-url-encoding-use-url-hexify (not table))
8089 (url-hexify-string text)
8090 (setq table (or table org-link-escape-chars))
8091 (when text
8092 (let ((re (mapconcat (lambda (x) (regexp-quote
8093 (char-to-string (car x))))
8094 table "\\|")))
8095 (while (string-match re text)
8096 (setq text
8097 (replace-match
8098 (cdr (assoc (string-to-char (match-string 0 text))
8099 table))
8100 t t text)))
8101 text))))
8103 (defun org-link-unescape (text &optional table)
8104 "Reverse the action of `org-link-escape'."
8105 (if (and org-url-encoding-use-url-hexify (not table))
8106 (url-unhex-string text)
8107 (setq table (or table org-link-escape-chars))
8108 (when text
8109 (let ((case-fold-search t)
8110 (re (mapconcat (lambda (x) (regexp-quote (downcase (cdr x))))
8111 table "\\|")))
8112 (while (string-match re text)
8113 (setq text
8114 (replace-match
8115 (char-to-string (car (rassoc (upcase (match-string 0 text))
8116 table)))
8117 t t text)))
8118 text))))
8120 (defun org-xor (a b)
8121 "Exclusive or."
8122 (if a (not b) b))
8124 (defun org-fixup-message-id-for-http (s)
8125 "Replace special characters in a message id, so it can be used in an http query."
8126 (while (string-match "<" s)
8127 (setq s (replace-match "%3C" t t s)))
8128 (while (string-match ">" s)
8129 (setq s (replace-match "%3E" t t s)))
8130 (while (string-match "@" s)
8131 (setq s (replace-match "%40" t t s)))
8134 ;;;###autoload
8135 (defun org-insert-link-global ()
8136 "Insert a link like Org-mode does.
8137 This command can be called in any mode to insert a link in Org-mode syntax."
8138 (interactive)
8139 (org-load-modules-maybe)
8140 (org-run-like-in-org-mode 'org-insert-link))
8142 (defun org-insert-link (&optional complete-file link-location)
8143 "Insert a link. At the prompt, enter the link.
8145 Completion can be used to insert any of the link protocol prefixes like
8146 http or ftp in use.
8148 The history can be used to select a link previously stored with
8149 `org-store-link'. When the empty string is entered (i.e. if you just
8150 press RET at the prompt), the link defaults to the most recently
8151 stored link. As SPC triggers completion in the minibuffer, you need to
8152 use M-SPC or C-q SPC to force the insertion of a space character.
8154 You will also be prompted for a description, and if one is given, it will
8155 be displayed in the buffer instead of the link.
8157 If there is already a link at point, this command will allow you to edit link
8158 and description parts.
8160 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8161 be selected using completion. The path to the file will be relative to the
8162 current directory if the file is in the current directory or a subdirectory.
8163 Otherwise, the link will be the absolute path as completed in the minibuffer
8164 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8165 option `org-link-file-path-type'.
8167 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8168 the current directory or below.
8170 With three \\[universal-argument] prefixes, negate the meaning of
8171 `org-keep-stored-link-after-insertion'.
8173 If `org-make-link-description-function' is non-nil, this function will be
8174 called with the link target, and the result will be the default
8175 link description.
8177 If the LINK-LOCATION parameter is non-nil, this value will be
8178 used as the link location instead of reading one interactively."
8179 (interactive "P")
8180 (let* ((wcf (current-window-configuration))
8181 (region (if (org-region-active-p)
8182 (buffer-substring (region-beginning) (region-end))))
8183 (remove (and region (list (region-beginning) (region-end))))
8184 (desc region)
8185 tmphist ; byte-compile incorrectly complains about this
8186 (link link-location)
8187 entry file all-prefixes)
8188 (cond
8189 (link-location) ; specified by arg, just use it.
8190 ((org-in-regexp org-bracket-link-regexp 1)
8191 ;; We do have a link at point, and we are going to edit it.
8192 (setq remove (list (match-beginning 0) (match-end 0)))
8193 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8194 (setq link (read-string "Link: "
8195 (org-link-unescape
8196 (org-match-string-no-properties 1)))))
8197 ((or (org-in-regexp org-angle-link-re)
8198 (org-in-regexp org-plain-link-re))
8199 ;; Convert to bracket link
8200 (setq remove (list (match-beginning 0) (match-end 0))
8201 link (read-string "Link: "
8202 (org-remove-angle-brackets (match-string 0)))))
8203 ((member complete-file '((4) (16)))
8204 ;; Completing read for file names.
8205 (setq link (org-file-complete-link complete-file)))
8207 ;; Read link, with completion for stored links.
8208 (with-output-to-temp-buffer "*Org Links*"
8209 (princ "Insert a link.
8210 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8211 (when org-stored-links
8212 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8213 (princ (mapconcat
8214 (lambda (x)
8215 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8216 (reverse org-stored-links) "\n"))))
8217 (let ((cw (selected-window)))
8218 (select-window (get-buffer-window "*Org Links*" 'visible))
8219 (setq truncate-lines t)
8220 (unless (pos-visible-in-window-p (point-max))
8221 (org-fit-window-to-buffer))
8222 (and (window-live-p cw) (select-window cw)))
8223 ;; Fake a link history, containing the stored links.
8224 (setq tmphist (append (mapcar 'car org-stored-links)
8225 org-insert-link-history))
8226 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8227 (mapcar 'car org-link-abbrev-alist)
8228 org-link-types))
8229 (unwind-protect
8230 (progn
8231 (setq link
8232 (let ((org-completion-use-ido nil)
8233 (org-completion-use-iswitchb nil))
8234 (org-completing-read
8235 "Link: "
8236 (append
8237 (mapcar (lambda (x) (list (concat x ":")))
8238 all-prefixes)
8239 (mapcar 'car org-stored-links))
8240 nil nil nil
8241 'tmphist
8242 (car (car org-stored-links)))))
8243 (if (not (string-match "\\S-" link))
8244 (error "No link selected"))
8245 (if (or (member link all-prefixes)
8246 (and (equal ":" (substring link -1))
8247 (member (substring link 0 -1) all-prefixes)
8248 (setq link (substring link 0 -1))))
8249 (setq link (org-link-try-special-completion link))))
8250 (set-window-configuration wcf)
8251 (kill-buffer "*Org Links*"))
8252 (setq entry (assoc link org-stored-links))
8253 (or entry (push link org-insert-link-history))
8254 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8255 (not org-keep-stored-link-after-insertion))
8256 (setq org-stored-links (delq (assoc link org-stored-links)
8257 org-stored-links)))
8258 (setq desc (or desc (nth 1 entry)))))
8260 (if (string-match org-plain-link-re link)
8261 ;; URL-like link, normalize the use of angular brackets.
8262 (setq link (org-make-link (org-remove-angle-brackets link))))
8264 ;; Check if we are linking to the current file with a search option
8265 ;; If yes, simplify the link by using only the search option.
8266 (when (and buffer-file-name
8267 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8268 (let* ((path (match-string 1 link))
8269 (case-fold-search nil)
8270 (search (match-string 2 link)))
8271 (save-match-data
8272 (if (equal (file-truename buffer-file-name) (file-truename path))
8273 ;; We are linking to this same file, with a search option
8274 (setq link search)))))
8276 ;; Check if we can/should use a relative path. If yes, simplify the link
8277 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8278 (let* ((type (match-string 1 link))
8279 (path (match-string 2 link))
8280 (origpath path)
8281 (case-fold-search nil))
8282 (cond
8283 ((or (eq org-link-file-path-type 'absolute)
8284 (equal complete-file '(16)))
8285 (setq path (abbreviate-file-name (expand-file-name path))))
8286 ((eq org-link-file-path-type 'noabbrev)
8287 (setq path (expand-file-name path)))
8288 ((eq org-link-file-path-type 'relative)
8289 (setq path (file-relative-name path)))
8291 (save-match-data
8292 (if (string-match (concat "^" (regexp-quote
8293 (file-name-as-directory
8294 (expand-file-name "."))))
8295 (expand-file-name path))
8296 ;; We are linking a file with relative path name.
8297 (setq path (substring (expand-file-name path)
8298 (match-end 0)))
8299 (setq path (abbreviate-file-name (expand-file-name path)))))))
8300 (setq link (concat type path))
8301 (if (equal desc origpath)
8302 (setq desc path))))
8304 (if org-make-link-description-function
8305 (setq desc (funcall org-make-link-description-function link desc)))
8307 (setq desc (read-string "Description: " desc))
8308 (unless (string-match "\\S-" desc) (setq desc nil))
8309 (if remove (apply 'delete-region remove))
8310 (insert (org-make-link-string link desc))))
8312 (defun org-link-try-special-completion (type)
8313 "If there is completion support for link type TYPE, offer it."
8314 (let ((fun (intern (concat "org-" type "-complete-link"))))
8315 (if (functionp fun)
8316 (funcall fun)
8317 (read-string "Link (no completion support): " (concat type ":")))))
8319 (defun org-file-complete-link (&optional arg)
8320 "Create a file link using completion."
8321 (let (file link)
8322 (setq file (read-file-name "File: "))
8323 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8324 (pwd1 (file-name-as-directory (abbreviate-file-name
8325 (expand-file-name ".")))))
8326 (cond
8327 ((equal arg '(16))
8328 (setq link (org-make-link
8329 "file:"
8330 (abbreviate-file-name (expand-file-name file)))))
8331 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8332 (setq link (org-make-link "file:" (match-string 1 file))))
8333 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8334 (expand-file-name file))
8335 (setq link (org-make-link
8336 "file:" (match-string 1 (expand-file-name file)))))
8337 (t (setq link (org-make-link "file:" file)))))
8338 link))
8340 (defun org-completing-read (&rest args)
8341 "Completing-read with SPACE being a normal character."
8342 (let ((minibuffer-local-completion-map
8343 (copy-keymap minibuffer-local-completion-map)))
8344 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8345 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8346 (apply 'org-icompleting-read args)))
8348 (defun org-completing-read-no-i (&rest args)
8349 (let (org-completion-use-ido org-completion-use-iswitchb)
8350 (apply 'org-completing-read args)))
8352 (defun org-iswitchb-completing-read (prompt choices &rest args)
8353 "Use iswitch as a completing-read replacement to choose from choices.
8354 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8355 from."
8356 (let* ((iswitchb-use-virtual-buffers nil)
8357 (iswitchb-make-buflist-hook
8358 (lambda ()
8359 (setq iswitchb-temp-buflist choices))))
8360 (iswitchb-read-buffer prompt)))
8362 (defun org-icompleting-read (&rest args)
8363 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8364 (org-without-partial-completion
8365 (if (and org-completion-use-ido
8366 (fboundp 'ido-completing-read)
8367 (boundp 'ido-mode) ido-mode
8368 (listp (second args)))
8369 (let ((ido-enter-matching-directory nil))
8370 (apply 'ido-completing-read (concat (car args))
8371 (if (consp (car (nth 1 args)))
8372 (mapcar (lambda (x) (car x)) (nth 1 args))
8373 (nth 1 args))
8374 (cddr args)))
8375 (if (and org-completion-use-iswitchb
8376 (boundp 'iswitchb-mode) iswitchb-mode
8377 (listp (second args)))
8378 (apply 'org-iswitchb-completing-read (concat (car args))
8379 (if (consp (car (nth 1 args)))
8380 (mapcar (lambda (x) (car x)) (nth 1 args))
8381 (nth 1 args))
8382 (cddr args))
8383 (apply 'completing-read args)))))
8385 (defun org-extract-attributes (s)
8386 "Extract the attributes cookie from a string and set as text property."
8387 (let (a attr (start 0) key value)
8388 (save-match-data
8389 (when (string-match "{{\\([^}]+\\)}}$" s)
8390 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8391 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8392 (setq key (match-string 1 a) value (match-string 2 a)
8393 start (match-end 0)
8394 attr (plist-put attr (intern key) value))))
8395 (org-add-props s nil 'org-attr attr))
8398 (defun org-extract-attributes-from-string (tag)
8399 (let (key value attr)
8400 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8401 (setq key (match-string 1 tag) value (match-string 2 tag)
8402 tag (replace-match "" t t tag)
8403 attr (plist-put attr (intern key) value)))
8404 (cons tag attr)))
8406 (defun org-attributes-to-string (plist)
8407 "Format a property list into an HTML attribute list."
8408 (let ((s "") key value)
8409 (while plist
8410 (setq key (pop plist) value (pop plist))
8411 (and value
8412 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8415 ;;; Opening/following a link
8417 (defvar org-link-search-failed nil)
8419 (defvar org-open-link-functions nil
8420 "Hook for functions finding a plain text link.
8421 These functions must take a single argument, the link content.
8422 They will be called for links that look like [[link text][description]]
8423 when LINK TEXT does not have a protocol like \"http:\" and does not look
8424 like a filename (e.g. \"./blue.png\").
8426 These functions will be called *before* Org attempts to resolve the
8427 link by doing text searches in the current buffer - so if you want a
8428 link \"[[target]]\" to still find \"<<target>>\", your function should
8429 handle this as a special case.
8431 When the function does handle the link, it must return a non-nil value.
8432 If it decides that it is not responsible for this link, it must return
8433 nil to indicate that that Org-mode can continue with other options
8434 like exact and fuzzy text search.")
8436 (defun org-next-link ()
8437 "Move forward to the next link.
8438 If the link is in hidden text, expose it."
8439 (interactive)
8440 (when (and org-link-search-failed (eq this-command last-command))
8441 (goto-char (point-min))
8442 (message "Link search wrapped back to beginning of buffer"))
8443 (setq org-link-search-failed nil)
8444 (let* ((pos (point))
8445 (ct (org-context))
8446 (a (assoc :link ct)))
8447 (if a (goto-char (nth 2 a)))
8448 (if (re-search-forward org-any-link-re nil t)
8449 (progn
8450 (goto-char (match-beginning 0))
8451 (if (org-invisible-p) (org-show-context)))
8452 (goto-char pos)
8453 (setq org-link-search-failed t)
8454 (error "No further link found"))))
8456 (defun org-previous-link ()
8457 "Move backward to the previous link.
8458 If the link is in hidden text, expose it."
8459 (interactive)
8460 (when (and org-link-search-failed (eq this-command last-command))
8461 (goto-char (point-max))
8462 (message "Link search wrapped back to end of buffer"))
8463 (setq org-link-search-failed nil)
8464 (let* ((pos (point))
8465 (ct (org-context))
8466 (a (assoc :link ct)))
8467 (if a (goto-char (nth 1 a)))
8468 (if (re-search-backward org-any-link-re nil t)
8469 (progn
8470 (goto-char (match-beginning 0))
8471 (if (org-invisible-p) (org-show-context)))
8472 (goto-char pos)
8473 (setq org-link-search-failed t)
8474 (error "No further link found"))))
8476 (defun org-translate-link (s)
8477 "Translate a link string if a translation function has been defined."
8478 (if (and org-link-translation-function
8479 (fboundp org-link-translation-function)
8480 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8481 (progn
8482 (setq s (funcall org-link-translation-function
8483 (match-string 1) (match-string 2)))
8484 (concat (car s) ":" (cdr s)))
8487 (defun org-translate-link-from-planner (type path)
8488 "Translate a link from Emacs Planner syntax so that Org can follow it.
8489 This is still an experimental function, your mileage may vary."
8490 (cond
8491 ((member type '("http" "https" "news" "ftp"))
8492 ;; standard Internet links are the same.
8493 nil)
8494 ((and (equal type "irc") (string-match "^//" path))
8495 ;; Planner has two / at the beginning of an irc link, we have 1.
8496 ;; We should have zero, actually....
8497 (setq path (substring path 1)))
8498 ((and (equal type "lisp") (string-match "^/" path))
8499 ;; Planner has a slash, we do not.
8500 (setq type "elisp" path (substring path 1)))
8501 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8502 ;; A typical message link. Planner has the id after the final slash,
8503 ;; we separate it with a hash mark
8504 (setq path (concat (match-string 1 path) "#"
8505 (org-remove-angle-brackets (match-string 2 path)))))
8507 (cons type path))
8509 (defun org-find-file-at-mouse (ev)
8510 "Open file link or URL at mouse."
8511 (interactive "e")
8512 (mouse-set-point ev)
8513 (org-open-at-point 'in-emacs))
8515 (defun org-open-at-mouse (ev)
8516 "Open file link or URL at mouse."
8517 (interactive "e")
8518 (mouse-set-point ev)
8519 (if (eq major-mode 'org-agenda-mode)
8520 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8521 (org-open-at-point))
8523 (defvar org-window-config-before-follow-link nil
8524 "The window configuration before following a link.
8525 This is saved in case the need arises to restore it.")
8527 (defvar org-open-link-marker (make-marker)
8528 "Marker pointing to the location where `org-open-at-point; was called.")
8530 ;;;###autoload
8531 (defun org-open-at-point-global ()
8532 "Follow a link like Org-mode does.
8533 This command can be called in any mode to follow a link that has
8534 Org-mode syntax."
8535 (interactive)
8536 (org-run-like-in-org-mode 'org-open-at-point))
8538 ;;;###autoload
8539 (defun org-open-link-from-string (s &optional arg reference-buffer)
8540 "Open a link in the string S, as if it was in Org-mode."
8541 (interactive "sLink: \nP")
8542 (let ((reference-buffer (or reference-buffer (current-buffer))))
8543 (with-temp-buffer
8544 (let ((org-inhibit-startup t))
8545 (org-mode)
8546 (insert s)
8547 (goto-char (point-min))
8548 (when reference-buffer
8549 (setq org-link-abbrev-alist-local
8550 (with-current-buffer reference-buffer
8551 org-link-abbrev-alist-local)))
8552 (org-open-at-point arg reference-buffer)))))
8554 (defun org-open-at-point (&optional in-emacs reference-buffer)
8555 "Open link at or after point.
8556 If there is no link at point, this function will search forward up to
8557 the end of the current line.
8558 Normally, files will be opened by an appropriate application. If the
8559 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8560 With a double prefix argument, try to open outside of Emacs, in the
8561 application the system uses for this file type."
8562 (interactive "P")
8563 (org-load-modules-maybe)
8564 (move-marker org-open-link-marker (point))
8565 (setq org-window-config-before-follow-link (current-window-configuration))
8566 (org-remove-occur-highlights nil nil t)
8567 (cond
8568 ((and (org-on-heading-p)
8569 (not (org-in-regexp
8570 (concat org-plain-link-re "\\|"
8571 org-bracket-link-regexp "\\|"
8572 org-angle-link-re "\\|"
8573 "[ \t]:[^ \t\n]+:[ \t]*$")))
8574 (not (get-text-property (point) 'org-linked-text)))
8575 (or (org-offer-links-in-entry in-emacs)
8576 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8577 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8578 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8579 (org-footnote-action))
8581 (let (type path link line search (pos (point)))
8582 (catch 'match
8583 (save-excursion
8584 (skip-chars-forward "^]\n\r")
8585 (when (org-in-regexp org-bracket-link-regexp 1)
8586 (setq link (org-extract-attributes
8587 (org-link-unescape (org-match-string-no-properties 1))))
8588 (while (string-match " *\n *" link)
8589 (setq link (replace-match " " t t link)))
8590 (setq link (org-link-expand-abbrev link))
8591 (cond
8592 ((or (file-name-absolute-p link)
8593 (string-match "^\\.\\.?/" link))
8594 (setq type "file" path link))
8595 ((string-match org-link-re-with-space3 link)
8596 (setq type (match-string 1 link) path (match-string 2 link)))
8597 (t (setq type "thisfile" path link)))
8598 (throw 'match t)))
8600 (when (get-text-property (point) 'org-linked-text)
8601 (setq type "thisfile"
8602 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8603 (1+ (point)) (point))
8604 path (buffer-substring
8605 (previous-single-property-change pos 'org-linked-text)
8606 (next-single-property-change pos 'org-linked-text)))
8607 (throw 'match t))
8609 (save-excursion
8610 (when (or (org-in-regexp org-angle-link-re)
8611 (org-in-regexp org-plain-link-re))
8612 (setq type (match-string 1) path (match-string 2))
8613 (throw 'match t)))
8614 (save-excursion
8615 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8616 (setq type "tags"
8617 path (match-string 1))
8618 (while (string-match ":" path)
8619 (setq path (replace-match "+" t t path)))
8620 (throw 'match t)))
8621 (when (org-in-regexp "<\\([^><\n]+\\)>")
8622 (setq type "tree-match"
8623 path (match-string 1))
8624 (throw 'match t)))
8625 (unless path
8626 (error "No link found"))
8628 ;; switch back to reference buffer
8629 ;; needed when if called in a temporary buffer through
8630 ;; org-open-link-from-string
8631 (with-current-buffer (or reference-buffer (current-buffer))
8633 ;; Remove any trailing spaces in path
8634 (if (string-match " +\\'" path)
8635 (setq path (replace-match "" t t path)))
8636 (if (and org-link-translation-function
8637 (fboundp org-link-translation-function))
8638 ;; Check if we need to translate the link
8639 (let ((tmp (funcall org-link-translation-function type path)))
8640 (setq type (car tmp) path (cdr tmp))))
8642 (cond
8644 ((assoc type org-link-protocols)
8645 (funcall (nth 1 (assoc type org-link-protocols)) path))
8647 ((equal type "mailto")
8648 (let ((cmd (car org-link-mailto-program))
8649 (args (cdr org-link-mailto-program)) args1
8650 (address path) (subject "") a)
8651 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8652 (setq address (match-string 1 path)
8653 subject (org-link-escape (match-string 2 path))))
8654 (while args
8655 (cond
8656 ((not (stringp (car args))) (push (pop args) args1))
8657 (t (setq a (pop args))
8658 (if (string-match "%a" a)
8659 (setq a (replace-match address t t a)))
8660 (if (string-match "%s" a)
8661 (setq a (replace-match subject t t a)))
8662 (push a args1))))
8663 (apply cmd (nreverse args1))))
8665 ((member type '("http" "https" "ftp" "news"))
8666 (browse-url (concat type ":" (org-link-escape
8667 path org-link-escape-chars-browser))))
8669 ((member type '("message"))
8670 (browse-url (concat type ":" path)))
8672 ((string= type "tags")
8673 (org-tags-view in-emacs path))
8675 ((string= type "tree-match")
8676 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8678 ((string= type "file")
8679 (if (string-match "::\\([0-9]+\\)\\'" path)
8680 (setq line (string-to-number (match-string 1 path))
8681 path (substring path 0 (match-beginning 0)))
8682 (if (string-match "::\\(.+\\)\\'" path)
8683 (setq search (match-string 1 path)
8684 path (substring path 0 (match-beginning 0)))))
8685 (if (string-match "[*?{]" (file-name-nondirectory path))
8686 (dired path)
8687 (org-open-file path in-emacs line search)))
8689 ((string= type "news")
8690 (require 'org-gnus)
8691 (org-gnus-follow-link path))
8693 ((string= type "shell")
8694 (let ((cmd path))
8695 (if (or (not org-confirm-shell-link-function)
8696 (funcall org-confirm-shell-link-function
8697 (format "Execute \"%s\" in shell? "
8698 (org-add-props cmd nil
8699 'face 'org-warning))))
8700 (progn
8701 (message "Executing %s" cmd)
8702 (shell-command cmd))
8703 (error "Abort"))))
8705 ((string= type "elisp")
8706 (let ((cmd path))
8707 (if (or (not org-confirm-elisp-link-function)
8708 (funcall org-confirm-elisp-link-function
8709 (format "Execute \"%s\" as elisp? "
8710 (org-add-props cmd nil
8711 'face 'org-warning))))
8712 (message "%s => %s" cmd
8713 (if (equal (string-to-char cmd) ?\()
8714 (eval (read cmd))
8715 (call-interactively (read cmd))))
8716 (error "Abort"))))
8718 ((and (string= type "thisfile")
8719 (run-hook-with-args-until-success
8720 'org-open-link-functions path)))
8722 ((string= type "thisfile")
8723 (if in-emacs
8724 (switch-to-buffer-other-window
8725 (org-get-buffer-for-internal-link (current-buffer)))
8726 (org-mark-ring-push))
8727 (let ((cmd `(org-link-search
8728 ,path
8729 ,(cond ((equal in-emacs '(4)) 'occur)
8730 ((equal in-emacs '(16)) 'org-occur)
8731 (t nil))
8732 ,pos)))
8733 (condition-case nil (eval cmd)
8734 (error (progn (widen) (eval cmd))))))
8737 (browse-url-at-point)))))))
8738 (move-marker org-open-link-marker nil)
8739 (run-hook-with-args 'org-follow-link-hook))
8741 (defun org-offer-links-in-entry (&optional nth zero)
8742 "Offer links in the current entry and follow the selected link.
8743 If there is only one link, follow it immediately as well.
8744 If NTH is an integer, immediately pick the NTH link found.
8745 If ZERO is a string, check also this string for a link, and if
8746 there is one, offer it as link number zero."
8747 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8748 "\\(" org-angle-link-re "\\)\\|"
8749 "\\(" org-plain-link-re "\\)"))
8750 (cnt ?0)
8751 (in-emacs (if (integerp nth) nil nth))
8752 have-zero end links link c)
8753 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8754 (push (match-string 0 zero) links)
8755 (setq cnt (1- cnt) have-zero t))
8756 (save-excursion
8757 (org-back-to-heading t)
8758 (setq end (save-excursion (outline-next-heading) (point)))
8759 (while (re-search-forward re end t)
8760 (push (match-string 0) links))
8761 (setq links (org-uniquify (reverse links))))
8763 (cond
8764 ((null links)
8765 (message "No links"))
8766 ((equal (length links) 1)
8767 (setq link (list (car links))))
8768 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8769 (setq link (nth (if have-zero nth (1- nth)) links)))
8770 (t ; we have to select a link
8771 (save-excursion
8772 (save-window-excursion
8773 (delete-other-windows)
8774 (with-output-to-temp-buffer "*Select Link*"
8775 (mapc (lambda (l)
8776 (if (not (string-match org-bracket-link-regexp l))
8777 (princ (format "[%c] %s\n" (incf cnt)
8778 (org-remove-angle-brackets l)))
8779 (if (match-end 3)
8780 (princ (format "[%c] %s (%s)\n" (incf cnt)
8781 (match-string 3 l) (match-string 1 l)))
8782 (princ (format "[%c] %s\n" (incf cnt)
8783 (match-string 1 l))))))
8784 links))
8785 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8786 (message "Select link to open, RET to open all:")
8787 (setq c (read-char-exclusive))
8788 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8789 (when (equal c ?q) (error "Abort"))
8790 (if (equal c ?\C-m)
8791 (setq link links)
8792 (setq nth (- c ?0))
8793 (if have-zero (setq nth (1+ nth)))
8794 (unless (and (integerp nth) (>= (length links) nth))
8795 (error "Invalid link selection"))
8796 (setq link (list (nth (1- nth) links))))))
8797 (if link
8798 (let ((buf (current-buffer)))
8799 (dolist (l link)
8800 (org-open-link-from-string l in-emacs buf))
8802 nil)))
8804 ;; Add special file links that specify the way of opening
8806 (org-add-link-type "file+sys" 'org-open-file-with-system)
8807 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
8808 (defun org-open-file-with-system (path)
8809 "Open file at PATH using the system way of opeing it."
8810 (org-open-file path 'system))
8811 (defun org-open-file-with-emacs (path)
8812 "Open file at PATH in emacs."
8813 (org-open-file path 'emacs))
8814 (defun org-remove-file-link-modifiers ()
8815 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
8816 (goto-char (point-min))
8817 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
8818 (org-if-unprotected
8819 (replace-match "file:" t t))))
8820 (eval-after-load "org-exp"
8821 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
8822 'org-remove-file-link-modifiers))
8824 ;;;; Time estimates
8826 (defun org-get-effort (&optional pom)
8827 "Get the effort estimate for the current entry."
8828 (org-entry-get pom org-effort-property))
8830 ;;; File search
8832 (defvar org-create-file-search-functions nil
8833 "List of functions to construct the right search string for a file link.
8834 These functions are called in turn with point at the location to
8835 which the link should point.
8837 A function in the hook should first test if it would like to
8838 handle this file type, for example by checking the major-mode or
8839 the file extension. If it decides not to handle this file, it
8840 should just return nil to give other functions a chance. If it
8841 does handle the file, it must return the search string to be used
8842 when following the link. The search string will be part of the
8843 file link, given after a double colon, and `org-open-at-point'
8844 will automatically search for it. If special measures must be
8845 taken to make the search successful, another function should be
8846 added to the companion hook `org-execute-file-search-functions',
8847 which see.
8849 A function in this hook may also use `setq' to set the variable
8850 `description' to provide a suggestion for the descriptive text to
8851 be used for this link when it gets inserted into an Org-mode
8852 buffer with \\[org-insert-link].")
8854 (defvar org-execute-file-search-functions nil
8855 "List of functions to execute a file search triggered by a link.
8857 Functions added to this hook must accept a single argument, the
8858 search string that was part of the file link, the part after the
8859 double colon. The function must first check if it would like to
8860 handle this search, for example by checking the major-mode or the
8861 file extension. If it decides not to handle this search, it
8862 should just return nil to give other functions a chance. If it
8863 does handle the search, it must return a non-nil value to keep
8864 other functions from trying.
8866 Each function can access the current prefix argument through the
8867 variable `current-prefix-argument'. Note that a single prefix is
8868 used to force opening a link in Emacs, so it may be good to only
8869 use a numeric or double prefix to guide the search function.
8871 In case this is needed, a function in this hook can also restore
8872 the window configuration before `org-open-at-point' was called using:
8874 (set-window-configuration org-window-config-before-follow-link)")
8876 (defun org-link-search (s &optional type avoid-pos)
8877 "Search for a link search option.
8878 If S is surrounded by forward slashes, it is interpreted as a
8879 regular expression. In org-mode files, this will create an `org-occur'
8880 sparse tree. In ordinary files, `occur' will be used to list matches.
8881 If the current buffer is in `dired-mode', grep will be used to search
8882 in all files. If AVOID-POS is given, ignore matches near that position."
8883 (let ((case-fold-search t)
8884 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8885 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8886 (append '(("") (" ") ("\t") ("\n"))
8887 org-emphasis-alist)
8888 "\\|") "\\)"))
8889 (pos (point))
8890 (pre nil) (post nil)
8891 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8892 (cond
8893 ;; First check if there are any special
8894 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8895 ;; Now try the builtin stuff
8896 ((and (equal (string-to-char s0) ?#)
8897 (> (length s0) 1)
8898 (save-excursion
8899 (goto-char (point-min))
8900 (and
8901 (re-search-forward
8902 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8903 (setq type 'dedicated
8904 pos (match-beginning 0))))
8905 ;; There is an exact target for this
8906 (goto-char pos)
8907 (org-back-to-heading t)))
8908 ((save-excursion
8909 (goto-char (point-min))
8910 (and
8911 (re-search-forward
8912 (concat "<<" (regexp-quote s0) ">>") nil t)
8913 (setq type 'dedicated
8914 pos (match-beginning 0))))
8915 ;; There is an exact target for this
8916 (goto-char pos))
8917 ((and (string-match "^(\\(.*\\))$" s0)
8918 (save-excursion
8919 (goto-char (point-min))
8920 (and
8921 (re-search-forward
8922 (concat "[^[]" (regexp-quote
8923 (format org-coderef-label-format
8924 (match-string 1 s0))))
8925 nil t)
8926 (setq type 'dedicated
8927 pos (1+ (match-beginning 0))))))
8928 ;; There is a coderef target for this
8929 (goto-char pos))
8930 ((string-match "^/\\(.*\\)/$" s)
8931 ;; A regular expression
8932 (cond
8933 ((org-mode-p)
8934 (org-occur (match-string 1 s)))
8935 ;;((eq major-mode 'dired-mode)
8936 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8937 (t (org-do-occur (match-string 1 s)))))
8939 ;; A normal search strings
8940 (when (equal (string-to-char s) ?*)
8941 ;; Anchor on headlines, post may include tags.
8942 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8943 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8944 s (substring s 1)))
8945 (remove-text-properties
8946 0 (length s)
8947 '(face nil mouse-face nil keymap nil fontified nil) s)
8948 ;; Make a series of regular expressions to find a match
8949 (setq words (org-split-string s "[ \n\r\t]+")
8951 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8952 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8953 "\\)" markers)
8954 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8955 re2a (concat "[ \t\r\n]" re2a_)
8956 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8957 re4 (concat "[^a-zA-Z_]" re4_)
8959 re1 (concat pre re2 post)
8960 re3 (concat pre (if pre re4_ re4) post)
8961 re5 (concat pre ".*" re4)
8962 re2 (concat pre re2)
8963 re2a (concat pre (if pre re2a_ re2a))
8964 re4 (concat pre (if pre re4_ re4))
8965 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8966 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8967 re5 "\\)"
8969 (cond
8970 ((eq type 'org-occur) (org-occur reall))
8971 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8972 (t (goto-char (point-min))
8973 (setq type 'fuzzy)
8974 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8975 (org-search-not-self 1 re1 nil t)
8976 (org-search-not-self 1 re2 nil t)
8977 (org-search-not-self 1 re2a nil t)
8978 (org-search-not-self 1 re3 nil t)
8979 (org-search-not-self 1 re4 nil t)
8980 (org-search-not-self 1 re5 nil t)
8982 (goto-char (match-beginning 1))
8983 (goto-char pos)
8984 (error "No match")))))
8986 ;; Normal string-search
8987 (goto-char (point-min))
8988 (if (search-forward s nil t)
8989 (goto-char (match-beginning 0))
8990 (error "No match"))))
8991 (and (org-mode-p) (org-show-context 'link-search))
8992 type))
8994 (defun org-search-not-self (group &rest args)
8995 "Execute `re-search-forward', but only accept matches that do not
8996 enclose the position of `org-open-link-marker'."
8997 (let ((m org-open-link-marker))
8998 (catch 'exit
8999 (while (apply 're-search-forward args)
9000 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9001 (goto-char (match-end group))
9002 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9003 (> (match-beginning 0) (marker-position m))
9004 (< (match-end 0) (marker-position m)))
9005 (save-match-data
9006 (or (not (org-in-regexp
9007 org-bracket-link-analytic-regexp 1))
9008 (not (match-end 4)) ; no description
9009 (and (<= (match-beginning 4) (point))
9010 (>= (match-end 4) (point))))))
9011 (throw 'exit (point))))))))
9013 (defun org-get-buffer-for-internal-link (buffer)
9014 "Return a buffer to be used for displaying the link target of internal links."
9015 (cond
9016 ((not org-display-internal-link-with-indirect-buffer)
9017 buffer)
9018 ((string-match "(Clone)$" (buffer-name buffer))
9019 (message "Buffer is already a clone, not making another one")
9020 ;; we also do not modify visibility in this case
9021 buffer)
9022 (t ; make a new indirect buffer for displaying the link
9023 (let* ((bn (buffer-name buffer))
9024 (ibn (concat bn "(Clone)"))
9025 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9026 (with-current-buffer ib (org-overview))
9027 ib))))
9029 (defun org-do-occur (regexp &optional cleanup)
9030 "Call the Emacs command `occur'.
9031 If CLEANUP is non-nil, remove the printout of the regular expression
9032 in the *Occur* buffer. This is useful if the regex is long and not useful
9033 to read."
9034 (occur regexp)
9035 (when cleanup
9036 (let ((cwin (selected-window)) win beg end)
9037 (when (setq win (get-buffer-window "*Occur*"))
9038 (select-window win))
9039 (goto-char (point-min))
9040 (when (re-search-forward "match[a-z]+" nil t)
9041 (setq beg (match-end 0))
9042 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9043 (setq end (1- (match-beginning 0)))))
9044 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9045 (goto-char (point-min))
9046 (select-window cwin))))
9048 ;;; The mark ring for links jumps
9050 (defvar org-mark-ring nil
9051 "Mark ring for positions before jumps in Org-mode.")
9052 (defvar org-mark-ring-last-goto nil
9053 "Last position in the mark ring used to go back.")
9054 ;; Fill and close the ring
9055 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9056 (loop for i from 1 to org-mark-ring-length do
9057 (push (make-marker) org-mark-ring))
9058 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9059 org-mark-ring)
9061 (defun org-mark-ring-push (&optional pos buffer)
9062 "Put the current position or POS into the mark ring and rotate it."
9063 (interactive)
9064 (setq pos (or pos (point)))
9065 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9066 (move-marker (car org-mark-ring)
9067 (or pos (point))
9068 (or buffer (current-buffer)))
9069 (message "%s"
9070 (substitute-command-keys
9071 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9073 (defun org-mark-ring-goto (&optional n)
9074 "Jump to the previous position in the mark ring.
9075 With prefix arg N, jump back that many stored positions. When
9076 called several times in succession, walk through the entire ring.
9077 Org-mode commands jumping to a different position in the current file,
9078 or to another Org-mode file, automatically push the old position
9079 onto the ring."
9080 (interactive "p")
9081 (let (p m)
9082 (if (eq last-command this-command)
9083 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9084 (setq p org-mark-ring))
9085 (setq org-mark-ring-last-goto p)
9086 (setq m (car p))
9087 (switch-to-buffer (marker-buffer m))
9088 (goto-char m)
9089 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9091 (defun org-remove-angle-brackets (s)
9092 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9093 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9095 (defun org-add-angle-brackets (s)
9096 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9097 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9099 (defun org-remove-double-quotes (s)
9100 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9101 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9104 ;;; Following specific links
9106 (defun org-follow-timestamp-link ()
9107 (cond
9108 ((org-at-date-range-p t)
9109 (let ((org-agenda-start-on-weekday)
9110 (t1 (match-string 1))
9111 (t2 (match-string 2)))
9112 (setq t1 (time-to-days (org-time-string-to-time t1))
9113 t2 (time-to-days (org-time-string-to-time t2)))
9114 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9115 ((org-at-timestamp-p t)
9116 (org-agenda-list nil (time-to-days (org-time-string-to-time
9117 (substring (match-string 1) 0 10)))
9119 (t (error "This should not happen"))))
9122 ;;; Following file links
9123 (defvar org-wait nil)
9124 (defun org-open-file (path &optional in-emacs line search)
9125 "Open the file at PATH.
9126 First, this expands any special file name abbreviations. Then the
9127 configuration variable `org-file-apps' is checked if it contains an
9128 entry for this file type, and if yes, the corresponding command is launched.
9130 If no application is found, Emacs simply visits the file.
9132 With optional prefix argument IN-EMACS, Emacs will visit the file.
9133 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
9134 and to use an external application to visit the file.
9136 Optional LINE specifies a line to go to, optional SEARCH a string
9137 to search for. If LINE or SEARCH is given, the file will be
9138 opened in Emacs, unless an entry from org-file-apps that makes
9139 use of groups in a regexp matches.
9140 If the file does not exist, an error is thrown."
9141 (let* ((file (if (equal path "")
9142 buffer-file-name
9143 (substitute-in-file-name (expand-file-name path))))
9144 (file-apps (append org-file-apps (org-default-apps)))
9145 (apps (org-remove-if
9146 'org-file-apps-entry-match-against-dlink-p file-apps))
9147 (apps-dlink (org-remove-if-not
9148 'org-file-apps-entry-match-against-dlink-p file-apps))
9149 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9150 (dirp (if remp nil (file-directory-p file)))
9151 (file (if (and dirp org-open-directory-means-index-dot-org)
9152 (concat (file-name-as-directory file) "index.org")
9153 file))
9154 (a-m-a-p (assq 'auto-mode apps))
9155 (dfile (downcase file))
9156 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9157 (link (cond ((and (eq line nil)
9158 (eq search nil))
9159 file)
9160 (line
9161 (concat file "::" (number-to-string line)))
9162 (search
9163 (concat file "::" search))))
9164 (dlink (downcase link))
9165 (old-buffer (current-buffer))
9166 (old-pos (point))
9167 (old-mode major-mode)
9168 ext cmd link-match-data)
9169 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9170 (setq ext (match-string 1 dfile))
9171 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9172 (setq ext (match-string 1 dfile))))
9173 (cond
9174 ((member in-emacs '((16) system))
9175 (setq cmd (cdr (assoc 'system apps))))
9176 (in-emacs (setq cmd 'emacs))
9178 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9179 (and dirp (cdr (assoc 'directory apps)))
9180 ; first, try matching against apps-dlink
9181 ; if we get a match here, store the match data for later
9182 (let ((match (assoc-default dlink apps-dlink
9183 'string-match)))
9184 (if match
9185 (progn (setq link-match-data (match-data))
9186 match)
9187 (progn (setq in-emacs (or in-emacs line search))
9188 nil))) ; if we have no match in apps-dlink,
9189 ; always open the file in emacs if line or search
9190 ; is given (for backwards compatibility)
9191 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9192 'string-match)
9193 (cdr (assoc ext apps))
9194 (cdr (assoc t apps))))))
9195 (when (eq cmd 'system)
9196 (setq cmd (cdr (assoc 'system apps))))
9197 (when (eq cmd 'default)
9198 (setq cmd (cdr (assoc t apps))))
9199 (when (eq cmd 'mailcap)
9200 (require 'mailcap)
9201 (mailcap-parse-mailcaps)
9202 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9203 (command (mailcap-mime-info mime-type)))
9204 (if (stringp command)
9205 (setq cmd command)
9206 (setq cmd 'emacs))))
9207 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9208 (not (file-exists-p file))
9209 (not org-open-non-existing-files))
9210 (error "No such file: %s" file))
9211 (cond
9212 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9213 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9214 (while (string-match "['\"]%s['\"]" cmd)
9215 (setq cmd (replace-match "%s" t t cmd)))
9216 (while (string-match "%s" cmd)
9217 (setq cmd (replace-match
9218 (save-match-data
9219 (shell-quote-argument
9220 (convert-standard-filename file)))
9221 t t cmd)))
9223 ;; Replace "%1", "%2" etc. in command with group matches from regex
9224 (save-match-data
9225 (let ((match-index 1)
9226 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9227 (set-match-data link-match-data)
9228 (while (<= match-index number-of-groups)
9229 (let ((regex (concat "%" (number-to-string match-index)))
9230 (replace-with (match-string match-index dlink)))
9231 (while (string-match regex cmd)
9232 (setq cmd (replace-match replace-with t t cmd))))
9233 (setq match-index (+ match-index 1)))))
9235 (save-window-excursion
9236 (start-process-shell-command cmd nil cmd)
9237 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9239 ((or (stringp cmd)
9240 (eq cmd 'emacs))
9241 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9242 (widen)
9243 (if line (org-goto-line line)
9244 (if search (org-link-search search))))
9245 ((consp cmd)
9246 (let ((file (convert-standard-filename file)))
9247 (save-match-data
9248 (set-match-data link-match-data)
9249 (eval cmd))))
9250 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9251 (and (org-mode-p) (eq old-mode 'org-mode)
9252 (or (not (equal old-buffer (current-buffer)))
9253 (not (equal old-pos (point))))
9254 (org-mark-ring-push old-pos old-buffer))))
9256 (defun org-file-apps-entry-match-against-dlink-p (entry)
9257 "This function returns non-nil if `entry' uses a regular
9258 expression which should be matched against the whole link by
9259 org-open-file.
9261 It assumes that is the case when the entry uses a regular
9262 expression which has at least one grouping construct and the
9263 action is either a lisp form or a command string containing
9264 '%1', i.e. using at least one subexpression match as a
9265 parameter."
9266 (let ((selector (car entry))
9267 (action (cdr entry)))
9268 (if (stringp selector)
9269 (and (> (regexp-opt-depth selector) 0)
9270 (or (and (stringp action)
9271 (string-match "%[0-9]" action))
9272 (consp action)))
9273 nil)))
9275 (defun org-default-apps ()
9276 "Return the default applications for this operating system."
9277 (cond
9278 ((eq system-type 'darwin)
9279 org-file-apps-defaults-macosx)
9280 ((eq system-type 'windows-nt)
9281 org-file-apps-defaults-windowsnt)
9282 (t org-file-apps-defaults-gnu)))
9284 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9285 "Convert extensions to regular expressions in the cars of LIST.
9286 Also, weed out any non-string entries, because the return value is used
9287 only for regexp matching.
9288 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9289 point to the symbol `emacs', indicating that the file should
9290 be opened in Emacs."
9291 (append
9292 (delq nil
9293 (mapcar (lambda (x)
9294 (if (not (stringp (car x)))
9296 (if (string-match "\\W" (car x))
9298 (cons (concat "\\." (car x) "\\'") (cdr x)))))
9299 list))
9300 (if add-auto-mode
9301 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9303 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9304 (defun org-file-remote-p (file)
9305 "Test whether FILE specifies a location on a remote system.
9306 Return non-nil if the location is indeed remote.
9308 For example, the filename \"/user@host:/foo\" specifies a location
9309 on the system \"/user@host:\"."
9310 (cond ((fboundp 'file-remote-p)
9311 (file-remote-p file))
9312 ((fboundp 'tramp-handle-file-remote-p)
9313 (tramp-handle-file-remote-p file))
9314 ((and (boundp 'ange-ftp-name-format)
9315 (string-match (car ange-ftp-name-format) file))
9317 (t nil)))
9320 ;;;; Refiling
9322 (defun org-get-org-file ()
9323 "Read a filename, with default directory `org-directory'."
9324 (let ((default (or org-default-notes-file remember-data-file)))
9325 (read-file-name (format "File name [%s]: " default)
9326 (file-name-as-directory org-directory)
9327 default)))
9329 (defun org-notes-order-reversed-p ()
9330 "Check if the current file should receive notes in reversed order."
9331 (cond
9332 ((not org-reverse-note-order) nil)
9333 ((eq t org-reverse-note-order) t)
9334 ((not (listp org-reverse-note-order)) nil)
9335 (t (catch 'exit
9336 (let ((all org-reverse-note-order)
9337 entry)
9338 (while (setq entry (pop all))
9339 (if (string-match (car entry) buffer-file-name)
9340 (throw 'exit (cdr entry))))
9341 nil)))))
9343 (defvar org-refile-target-table nil
9344 "The list of refile targets, created by `org-refile'.")
9346 (defvar org-agenda-new-buffers nil
9347 "Buffers created to visit agenda files.")
9349 (defun org-get-refile-targets (&optional default-buffer)
9350 "Produce a table with refile targets."
9351 (let ((case-fold-search nil)
9352 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9353 (entries (or org-refile-targets '((nil . (:level . 1)))))
9354 targets txt re files f desc descre fast-path-p level pos0)
9355 (message "Getting targets...")
9356 (with-current-buffer (or default-buffer (current-buffer))
9357 (while (setq entry (pop entries))
9358 (setq files (car entry) desc (cdr entry))
9359 (setq fast-path-p nil)
9360 (cond
9361 ((null files) (setq files (list (current-buffer))))
9362 ((eq files 'org-agenda-files)
9363 (setq files (org-agenda-files 'unrestricted)))
9364 ((and (symbolp files) (fboundp files))
9365 (setq files (funcall files)))
9366 ((and (symbolp files) (boundp files))
9367 (setq files (symbol-value files))))
9368 (if (stringp files) (setq files (list files)))
9369 (cond
9370 ((eq (car desc) :tag)
9371 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9372 ((eq (car desc) :todo)
9373 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9374 ((eq (car desc) :regexp)
9375 (setq descre (cdr desc)))
9376 ((eq (car desc) :level)
9377 (setq descre (concat "^\\*\\{" (number-to-string
9378 (if org-odd-levels-only
9379 (1- (* 2 (cdr desc)))
9380 (cdr desc)))
9381 "\\}[ \t]")))
9382 ((eq (car desc) :maxlevel)
9383 (setq fast-path-p t)
9384 (setq descre (concat "^\\*\\{1," (number-to-string
9385 (if org-odd-levels-only
9386 (1- (* 2 (cdr desc)))
9387 (cdr desc)))
9388 "\\}[ \t]")))
9389 (t (error "Bad refiling target description %s" desc)))
9390 (while (setq f (pop files))
9391 (with-current-buffer
9392 (if (bufferp f) f (org-get-agenda-file-buffer f))
9393 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
9394 (setq f (and f (expand-file-name f)))
9395 (if (eq org-refile-use-outline-path 'file)
9396 (push (list (file-name-nondirectory f) f nil nil) targets))
9397 (save-excursion
9398 (save-restriction
9399 (widen)
9400 (goto-char (point-min))
9401 (while (re-search-forward descre nil t)
9402 (goto-char (setq pos0 (point-at-bol)))
9403 (catch 'next
9404 (when org-refile-target-verify-function
9405 (save-match-data
9406 (or (funcall org-refile-target-verify-function)
9407 (throw 'next t))))
9408 (when (looking-at org-complex-heading-regexp)
9409 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
9410 txt (org-link-display-format (match-string 4))
9411 re (concat "^" (regexp-quote
9412 (buffer-substring (match-beginning 1)
9413 (match-end 4)))))
9414 (if (match-end 5) (setq re (concat re "[ \t]+"
9415 (regexp-quote
9416 (match-string 5)))))
9417 (setq re (concat re "[ \t]*$"))
9418 (when org-refile-use-outline-path
9419 (setq txt (mapconcat 'org-protect-slash
9420 (append
9421 (if (eq org-refile-use-outline-path 'file)
9422 (list (file-name-nondirectory
9423 (buffer-file-name (buffer-base-buffer))))
9424 (if (eq org-refile-use-outline-path 'full-file-path)
9425 (list (buffer-file-name (buffer-base-buffer)))))
9426 (org-get-outline-path fast-path-p level txt)
9427 (list txt))
9428 "/")))
9429 (push (list txt f re (point)) targets)))
9430 (when (= (point) pos0)
9431 ;; verification function has not moved point
9432 (goto-char (point-at-eol))))))))))
9433 (message "Getting targets...done")
9434 (nreverse targets)))
9436 (defun org-protect-slash (s)
9437 (while (string-match "/" s)
9438 (setq s (replace-match "\\" t t s)))
9441 (defvar org-olpa (make-vector 20 nil))
9443 (defun org-get-outline-path (&optional fastp level heading)
9444 "Return the outline path to the current entry, as a list.
9445 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9446 routine which makes outline path derivations for an entire file,
9447 avoiding backtracing."
9448 (if fastp
9449 (progn
9450 (if (> level 19)
9451 (error "Outline path failure, more than 19 levels."))
9452 (loop for i from level upto 19 do
9453 (aset org-olpa i nil))
9454 (prog1
9455 (delq nil (append org-olpa nil))
9456 (aset org-olpa level heading)))
9457 (let (rtn case-fold-search)
9458 (save-excursion
9459 (save-restriction
9460 (widen)
9461 (while (org-up-heading-safe)
9462 (when (looking-at org-complex-heading-regexp)
9463 (push (org-match-string-no-properties 4) rtn)))
9464 rtn)))))
9466 (defun org-format-outline-path (path &optional width prefix)
9467 "Format the outlie path PATH for display.
9468 Width is the maximum number of characters that is available.
9469 Prefix is a prefix to be included in the returned string,
9470 such as the file name."
9471 (setq width (or width 79))
9472 (if prefix (setq width (- width (length prefix))))
9473 (if (not path)
9474 (or prefix "")
9475 (let* ((nsteps (length path))
9476 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9477 (maxwidth (if (<= total-width width)
9478 10000 ;; everything fits
9479 ;; we need to shorten the level headings
9480 (/ (- width nsteps) nsteps)))
9481 (org-odd-levels-only nil)
9482 (n 0)
9483 (total (1+ (length prefix))))
9484 (setq maxwidth (max maxwidth 10))
9485 (concat prefix
9486 (mapconcat
9487 (lambda (h)
9488 (setq n (1+ n))
9489 (if (and (= n nsteps) (< maxwidth 10000))
9490 (setq maxwidth (- total-width total)))
9491 (if (< (length h) maxwidth)
9492 (progn (setq total (+ total (length h) 1)) h)
9493 (setq h (substring h 0 (- maxwidth 2))
9494 total (+ total maxwidth 1))
9495 (if (string-match "[ \t]+\\'" h)
9496 (setq h (substring h 0 (match-beginning 0))))
9497 (setq h (concat h "..")))
9498 (org-add-props h nil 'face
9499 (nth (% (1- n) org-n-level-faces)
9500 org-level-faces))
9502 path "/")))))
9504 (defun org-display-outline-path (&optional file current)
9505 "Display the current outline path in the echo area."
9506 (interactive "P")
9507 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
9508 (case-fold-search nil)
9509 (path (and (org-mode-p) (org-get-outline-path))))
9510 (if current (setq path (append path
9511 (save-excursion
9512 (org-back-to-heading t)
9513 (if (looking-at org-complex-heading-regexp)
9514 (list (match-string 4)))))))
9515 (message "%s"
9516 (org-format-outline-path
9517 path
9518 (1- (frame-width))
9519 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9521 (defvar org-refile-history nil
9522 "History for refiling operations.")
9524 (defvar org-after-refile-insert-hook nil
9525 "Hook run after `org-refile' has inserted its stuff at the new location.
9526 Note that this is still *before* the stuff will be removed from
9527 the *old* location.")
9529 (defun org-refile (&optional goto default-buffer rfloc)
9530 "Move the entry at point to another heading.
9531 The list of target headings is compiled using the information in
9532 `org-refile-targets', which see. This list is created before each use
9533 and will therefore always be up-to-date.
9535 At the target location, the entry is filed as a subitem of the target heading.
9536 Depending on `org-reverse-note-order', the new subitem will either be the
9537 first or the last subitem.
9539 If there is an active region, all entries in that region will be moved.
9540 However, the region must fulfil the requirement that the first heading
9541 is the first one sets the top-level of the moved text - at most siblings
9542 below it are allowed.
9544 With prefix arg GOTO, the command will only visit the target location,
9545 not actually move anything.
9546 With a double prefix `C-u C-u', go to the location where the last refiling
9547 operation has put the subtree.
9548 With a prefix argument of `2', refile to the running clock.
9550 RFLOC can be a refile location obtained in a different way.
9552 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9553 (interactive "P")
9554 (let* ((cbuf (current-buffer))
9555 (regionp (org-region-active-p))
9556 (region-start (and regionp (region-beginning)))
9557 (region-end (and regionp (region-end)))
9558 (region-length (and regionp (- region-end region-start)))
9559 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9560 pos it nbuf file re level reversed)
9561 (setq last-command nil)
9562 (when regionp
9563 (goto-char region-start)
9564 (or (bolp) (goto-char (point-at-bol)))
9565 (setq region-start (point))
9566 (unless (org-kill-is-subtree-p
9567 (buffer-substring region-start region-end))
9568 (error "The region is not a (sequence of) subtree(s)")))
9569 (if (equal goto '(16))
9570 (org-refile-goto-last-stored)
9571 (when (or
9572 (and (equal goto 2)
9573 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9574 (prog1
9575 (setq it (list (or org-clock-heading "running clock")
9576 (buffer-file-name
9577 (marker-buffer org-clock-hd-marker))
9579 (marker-position org-clock-hd-marker)))
9580 (setq goto nil)))
9581 (setq it (or rfloc
9582 (save-excursion
9583 (org-refile-get-location
9584 (if goto "Goto: " "Refile to: ") default-buffer
9585 org-refile-allow-creating-parent-nodes)))))
9586 (setq file (nth 1 it)
9587 re (nth 2 it)
9588 pos (nth 3 it))
9589 (if (and (not goto)
9591 (equal (buffer-file-name) file)
9592 (if regionp
9593 (and (>= pos region-start)
9594 (<= pos region-end))
9595 (and (>= pos (point))
9596 (< pos (save-excursion
9597 (org-end-of-subtree t t))))))
9598 (error "Cannot refile to position inside the tree or region"))
9600 (setq nbuf (or (find-buffer-visiting file)
9601 (find-file-noselect file)))
9602 (if goto
9603 (progn
9604 (switch-to-buffer nbuf)
9605 (goto-char pos)
9606 (org-show-context 'org-goto))
9607 (if regionp
9608 (progn
9609 (org-kill-new (buffer-substring region-start region-end))
9610 (org-save-markers-in-region region-start region-end))
9611 (org-copy-subtree 1 nil t))
9612 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9613 (find-file-noselect file)))
9614 (setq reversed (org-notes-order-reversed-p))
9615 (save-excursion
9616 (save-restriction
9617 (widen)
9618 (if pos
9619 (progn
9620 (goto-char pos)
9621 (looking-at outline-regexp)
9622 (setq level (org-get-valid-level (funcall outline-level) 1))
9623 (goto-char
9624 (if reversed
9625 (or (outline-next-heading) (point-max))
9626 (or (save-excursion (org-get-next-sibling))
9627 (org-end-of-subtree t t)
9628 (point-max)))))
9629 (setq level 1)
9630 (if (not reversed)
9631 (goto-char (point-max))
9632 (goto-char (point-min))
9633 (or (outline-next-heading) (goto-char (point-max)))))
9634 (if (not (bolp)) (newline))
9635 (org-paste-subtree level)
9636 (when org-log-refile
9637 (org-add-log-setup 'refile nil nil 'findpos
9638 org-log-refile)
9639 (unless (eq org-log-refile 'note)
9640 (save-excursion (org-add-log-note))))
9641 (and org-auto-align-tags (org-set-tags nil t))
9642 (bookmark-set "org-refile-last-stored")
9643 (if (fboundp 'deactivate-mark) (deactivate-mark))
9644 (run-hooks 'org-after-refile-insert-hook))))
9645 (if regionp
9646 (delete-region (point) (+ (point) region-length))
9647 (org-cut-subtree))
9648 (when (featurep 'org-inlinetask)
9649 (org-inlinetask-remove-END-maybe))
9650 (setq org-markers-to-move nil)
9651 (message "Refiled to \"%s\"" (car it))))))
9652 (org-reveal))
9654 (defun org-refile-goto-last-stored ()
9655 "Go to the location where the last refile was stored."
9656 (interactive)
9657 (bookmark-jump "org-refile-last-stored")
9658 (message "This is the location of the last refile"))
9660 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9661 "Prompt the user for a refile location, using PROMPT."
9662 (let ((org-refile-targets org-refile-targets)
9663 (org-refile-use-outline-path org-refile-use-outline-path))
9664 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9665 (unless org-refile-target-table
9666 (error "No refile targets"))
9667 (let* ((cbuf (current-buffer))
9668 (partial-completion-mode nil)
9669 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9670 (cfunc (if (and org-refile-use-outline-path
9671 org-outline-path-complete-in-steps)
9672 'org-olpath-completing-read
9673 'org-icompleting-read))
9674 (extra (if org-refile-use-outline-path "/" ""))
9675 (filename (and cfn (expand-file-name cfn)))
9676 (tbl (mapcar
9677 (lambda (x)
9678 (if (and (not (member org-refile-use-outline-path
9679 '(file full-file-path)))
9680 (not (equal filename (nth 1 x))))
9681 (cons (concat (car x) extra " ("
9682 (file-name-nondirectory (nth 1 x)) ")")
9683 (cdr x))
9684 (cons (concat (car x) extra) (cdr x))))
9685 org-refile-target-table))
9686 (completion-ignore-case t)
9687 pa answ parent-target child parent old-hist)
9688 (setq old-hist org-refile-history)
9689 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9690 nil 'org-refile-history))
9691 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9692 (if pa
9693 (progn
9694 (when (or (not org-refile-history)
9695 (not (eq old-hist org-refile-history))
9696 (not (equal (car pa) (car org-refile-history))))
9697 (setq org-refile-history
9698 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9699 org-refile-history
9700 (cdr org-refile-history))))
9701 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9702 (pop org-refile-history)))
9704 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9705 (progn
9706 (setq parent (match-string 1 answ)
9707 child (match-string 2 answ))
9708 (setq parent-target (or (assoc parent tbl)
9709 (assoc (concat parent "/") tbl)))
9710 (when (and parent-target
9711 (or (eq new-nodes t)
9712 (and (eq new-nodes 'confirm)
9713 (y-or-n-p (format "Create new node \"%s\"? "
9714 child)))))
9715 (org-refile-new-child parent-target child)))
9716 (error "Invalid target location")))))
9718 (defun org-refile-new-child (parent-target child)
9719 "Use refile target PARENT-TARGET to add new CHILD below it."
9720 (unless parent-target
9721 (error "Cannot find parent for new node"))
9722 (let ((file (nth 1 parent-target))
9723 (pos (nth 3 parent-target))
9724 level)
9725 (with-current-buffer (or (find-buffer-visiting file)
9726 (find-file-noselect file))
9727 (save-excursion
9728 (save-restriction
9729 (widen)
9730 (if pos
9731 (goto-char pos)
9732 (goto-char (point-max))
9733 (if (not (bolp)) (newline)))
9734 (when (looking-at outline-regexp)
9735 (setq level (funcall outline-level))
9736 (org-end-of-subtree t t))
9737 (org-back-over-empty-lines)
9738 (insert "\n" (make-string
9739 (if pos (org-get-valid-level level 1) 1) ?*)
9740 " " child "\n")
9741 (beginning-of-line 0)
9742 (list (concat (car parent-target) "/" child) file "" (point)))))))
9744 (defun org-olpath-completing-read (prompt collection &rest args)
9745 "Read an outline path like a file name."
9746 (let ((thetable collection)
9747 (org-completion-use-ido nil) ; does not work with ido.
9748 (org-completion-use-iswitchb nil)) ; or iswitchb
9749 (apply
9750 'org-icompleting-read prompt
9751 (lambda (string predicate &optional flag)
9752 (let (rtn r f (l (length string)))
9753 (cond
9754 ((eq flag nil)
9755 ;; try completion
9756 (try-completion string thetable))
9757 ((eq flag t)
9758 ;; all-completions
9759 (setq rtn (all-completions string thetable predicate))
9760 (mapcar
9761 (lambda (x)
9762 (setq r (substring x l))
9763 (if (string-match " ([^)]*)$" x)
9764 (setq f (match-string 0 x))
9765 (setq f ""))
9766 (if (string-match "/" r)
9767 (concat string (substring r 0 (match-end 0)) f)
9769 rtn))
9770 ((eq flag 'lambda)
9771 ;; exact match?
9772 (assoc string thetable)))
9774 args)))
9776 ;;;; Dynamic blocks
9778 (defun org-find-dblock (name)
9779 "Find the first dynamic block with name NAME in the buffer.
9780 If not found, stay at current position and return nil."
9781 (let (pos)
9782 (save-excursion
9783 (goto-char (point-min))
9784 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9785 nil t)
9786 (match-beginning 0))))
9787 (if pos (goto-char pos))
9788 pos))
9790 (defconst org-dblock-start-re
9791 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9792 "Matches the start line of a dynamic block, with parameters.")
9794 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9795 "Matches the end of a dynamic block.")
9797 (defun org-create-dblock (plist)
9798 "Create a dynamic block section, with parameters taken from PLIST.
9799 PLIST must contain a :name entry which is used as name of the block."
9800 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9801 (end-of-line 1)
9802 (newline))
9803 (let ((col (current-column))
9804 (name (plist-get plist :name)))
9805 (insert "#+BEGIN: " name)
9806 (while plist
9807 (if (eq (car plist) :name)
9808 (setq plist (cddr plist))
9809 (insert " " (prin1-to-string (pop plist)))))
9810 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9811 (beginning-of-line -2)))
9813 (defun org-prepare-dblock ()
9814 "Prepare dynamic block for refresh.
9815 This empties the block, puts the cursor at the insert position and returns
9816 the property list including an extra property :name with the block name."
9817 (unless (looking-at org-dblock-start-re)
9818 (error "Not at a dynamic block"))
9819 (let* ((begdel (1+ (match-end 0)))
9820 (name (org-no-properties (match-string 1)))
9821 (params (append (list :name name)
9822 (read (concat "(" (match-string 3) ")")))))
9823 (save-excursion
9824 (beginning-of-line 1)
9825 (skip-chars-forward " \t")
9826 (setq params (plist-put params :indentation-column (current-column))))
9827 (unless (re-search-forward org-dblock-end-re nil t)
9828 (error "Dynamic block not terminated"))
9829 (setq params
9830 (append params
9831 (list :content (buffer-substring
9832 begdel (match-beginning 0)))))
9833 (delete-region begdel (match-beginning 0))
9834 (goto-char begdel)
9835 (open-line 1)
9836 params))
9838 (defun org-map-dblocks (&optional command)
9839 "Apply COMMAND to all dynamic blocks in the current buffer.
9840 If COMMAND is not given, use `org-update-dblock'."
9841 (let ((cmd (or command 'org-update-dblock)))
9842 (save-excursion
9843 (goto-char (point-min))
9844 (while (re-search-forward org-dblock-start-re nil t)
9845 (goto-char (match-beginning 0))
9846 (save-excursion
9847 (condition-case nil
9848 (funcall cmd)
9849 (error (message "Error during update of dynamic block"))))
9850 (unless (re-search-forward org-dblock-end-re nil t)
9851 (error "Dynamic block not terminated"))))))
9853 (defun org-dblock-update (&optional arg)
9854 "User command for updating dynamic blocks.
9855 Update the dynamic block at point. With prefix ARG, update all dynamic
9856 blocks in the buffer."
9857 (interactive "P")
9858 (if arg
9859 (org-update-all-dblocks)
9860 (or (looking-at org-dblock-start-re)
9861 (org-beginning-of-dblock))
9862 (org-update-dblock)))
9864 (defun org-update-dblock ()
9865 "Update the dynamic block at point
9866 This means to empty the block, parse for parameters and then call
9867 the correct writing function."
9868 (save-window-excursion
9869 (let* ((pos (point))
9870 (line (org-current-line))
9871 (params (org-prepare-dblock))
9872 (name (plist-get params :name))
9873 (indent (plist-get params :indentation-column))
9874 (cmd (intern (concat "org-dblock-write:" name))))
9875 (message "Updating dynamic block `%s' at line %d..." name line)
9876 (funcall cmd params)
9877 (message "Updating dynamic block `%s' at line %d...done" name line)
9878 (goto-char pos)
9879 (when (and indent (> indent 0))
9880 (setq indent (make-string indent ?\ ))
9881 (save-excursion
9882 (org-beginning-of-dblock)
9883 (forward-line 1)
9884 (while (not (looking-at org-dblock-end-re))
9885 (insert indent)
9886 (beginning-of-line 2))
9887 (when (looking-at org-dblock-end-re)
9888 (and (looking-at "[ \t]+")
9889 (replace-match ""))
9890 (insert indent)))))))
9892 (defun org-beginning-of-dblock ()
9893 "Find the beginning of the dynamic block at point.
9894 Error if there is no such block at point."
9895 (let ((pos (point))
9896 beg)
9897 (end-of-line 1)
9898 (if (and (re-search-backward org-dblock-start-re nil t)
9899 (setq beg (match-beginning 0))
9900 (re-search-forward org-dblock-end-re nil t)
9901 (> (match-end 0) pos))
9902 (goto-char beg)
9903 (goto-char pos)
9904 (error "Not in a dynamic block"))))
9906 (defun org-update-all-dblocks ()
9907 "Update all dynamic blocks in the buffer.
9908 This function can be used in a hook."
9909 (when (org-mode-p)
9910 (org-map-dblocks 'org-update-dblock)))
9913 ;;;; Completion
9915 (defconst org-additional-option-like-keywords
9916 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9917 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9918 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
9919 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
9920 "BEGIN:" "END:"
9921 "ORGTBL" "TBLFM:" "TBLNAME:"
9922 "BEGIN_EXAMPLE" "END_EXAMPLE"
9923 "BEGIN_QUOTE" "END_QUOTE"
9924 "BEGIN_VERSE" "END_VERSE"
9925 "BEGIN_CENTER" "END_CENTER"
9926 "BEGIN_SRC" "END_SRC"
9927 "CATEGORY" "COLUMNS"
9928 "CAPTION" "LABEL"
9929 "SETUPFILE"
9930 "BIND"
9931 "MACRO"))
9933 (defcustom org-structure-template-alist
9935 ("s" "#+begin_src ?\n\n#+end_src"
9936 "<src lang=\"?\">\n\n</src>")
9937 ("e" "#+begin_example\n?\n#+end_example"
9938 "<example>\n?\n</example>")
9939 ("q" "#+begin_quote\n?\n#+end_quote"
9940 "<quote>\n?\n</quote>")
9941 ("v" "#+begin_verse\n?\n#+end_verse"
9942 "<verse>\n?\n/verse>")
9943 ("c" "#+begin_center\n?\n#+end_center"
9944 "<center>\n?\n/center>")
9945 ("l" "#+begin_latex\n?\n#+end_latex"
9946 "<literal style=\"latex\">\n?\n</literal>")
9947 ("L" "#+latex: "
9948 "<literal style=\"latex\">?</literal>")
9949 ("h" "#+begin_html\n?\n#+end_html"
9950 "<literal style=\"html\">\n?\n</literal>")
9951 ("H" "#+html: "
9952 "<literal style=\"html\">?</literal>")
9953 ("a" "#+begin_ascii\n?\n#+end_ascii")
9954 ("A" "#+ascii: ")
9955 ("i" "#+include %file ?"
9956 "<include file=%file markup=\"?\">")
9958 "Structure completion elements.
9959 This is a list of abbreviation keys and values. The value gets inserted
9960 if you type `<' followed by the key and then press the completion key,
9961 usually `M-TAB'. %file will be replaced by a file name after prompting
9962 for the file using completion.
9963 There are two templates for each key, the first uses the original Org syntax,
9964 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9965 the default when the /org-mtags.el/ module has been loaded. See also the
9966 variable `org-mtags-prefer-muse-templates'.
9967 This is an experimental feature, it is undecided if it is going to stay in."
9968 :group 'org-completion
9969 :type '(repeat
9970 (string :tag "Key")
9971 (string :tag "Template")
9972 (string :tag "Muse Template")))
9974 (defun org-try-structure-completion ()
9975 "Try to complete a structure template before point.
9976 This looks for strings like \"<e\" on an otherwise empty line and
9977 expands them."
9978 (let ((l (buffer-substring (point-at-bol) (point)))
9980 (when (and (looking-at "[ \t]*$")
9981 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9982 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9983 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9984 (match-beginning 1)) a)
9985 t)))
9987 (defun org-complete-expand-structure-template (start cell)
9988 "Expand a structure template."
9989 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9990 (rpl (nth (if musep 2 1) cell))
9991 (ind ""))
9992 (delete-region start (point))
9993 (when (string-match "\\`#\\+" rpl)
9994 (cond
9995 ((bolp))
9996 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9997 (setq ind (buffer-substring (point-at-bol) (point))))
9998 (t (newline))))
9999 (setq start (point))
10000 (if (string-match "%file" rpl)
10001 (setq rpl (replace-match
10002 (concat
10003 "\""
10004 (save-match-data
10005 (abbreviate-file-name (read-file-name "Include file: ")))
10006 "\"")
10007 t t rpl)))
10008 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10009 (concat "\n" ind)))
10010 (insert rpl)
10011 (if (re-search-backward "\\?" start t) (delete-char 1))))
10014 (defun org-complete (&optional arg)
10015 "Perform completion on word at point.
10016 At the beginning of a headline, this completes TODO keywords as given in
10017 `org-todo-keywords'.
10018 If the current word is preceded by a backslash, completes the TeX symbols
10019 that are supported for HTML support.
10020 If the current word is preceded by \"#+\", completes special words for
10021 setting file options.
10022 In the line after \"#+STARTUP:, complete valid keywords.\"
10023 At all other locations, this simply calls the value of
10024 `org-completion-fallback-command'."
10025 (interactive "P")
10026 (org-without-partial-completion
10027 (catch 'exit
10028 (let* ((a nil)
10029 (end (point))
10030 (beg1 (save-excursion
10031 (skip-chars-backward (org-re "[:alnum:]_@"))
10032 (point)))
10033 (beg (save-excursion
10034 (skip-chars-backward "a-zA-Z0-9_:$")
10035 (point)))
10036 (confirm (lambda (x) (stringp (car x))))
10037 (searchhead (equal (char-before beg) ?*))
10038 (struct
10039 (when (and (member (char-before beg1) '(?. ?<))
10040 (setq a (assoc (buffer-substring beg1 (point))
10041 org-structure-template-alist)))
10042 (org-complete-expand-structure-template (1- beg1) a)
10043 (throw 'exit t)))
10044 (tag (and (equal (char-before beg1) ?:)
10045 (equal (char-after (point-at-bol)) ?*)))
10046 (prop (and (equal (char-before beg1) ?:)
10047 (not (equal (char-after (point-at-bol)) ?*))))
10048 (texp (equal (char-before beg) ?\\))
10049 (link (equal (char-before beg) ?\[))
10050 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
10051 beg)
10052 "#+"))
10053 (startup (string-match "^#\\+STARTUP:.*"
10054 (buffer-substring (point-at-bol) (point))))
10055 (completion-ignore-case opt)
10056 (type nil)
10057 (tbl nil)
10058 (table (cond
10059 (opt
10060 (setq type :opt)
10061 (require 'org-exp)
10062 (append
10063 (delq nil
10064 (mapcar
10065 (lambda (x)
10066 (if (string-match
10067 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
10068 (cons (match-string 2 x)
10069 (match-string 1 x))))
10070 (org-split-string (org-get-current-options) "\n")))
10071 (mapcar 'list org-additional-option-like-keywords)))
10072 (startup
10073 (setq type :startup)
10074 org-startup-options)
10075 (link (append org-link-abbrev-alist-local
10076 org-link-abbrev-alist))
10077 (texp
10078 (setq type :tex)
10079 (append org-entities-user org-entities))
10080 ((string-match "\\`\\*+[ \t]+\\'"
10081 (buffer-substring (point-at-bol) beg))
10082 (setq type :todo)
10083 (mapcar 'list org-todo-keywords-1))
10084 (searchhead
10085 (setq type :searchhead)
10086 (save-excursion
10087 (goto-char (point-min))
10088 (while (re-search-forward org-todo-line-regexp nil t)
10089 (push (list
10090 (org-make-org-heading-search-string
10091 (match-string 3) t))
10092 tbl)))
10093 tbl)
10094 (tag (setq type :tag beg beg1)
10095 (or org-tag-alist (org-get-buffer-tags)))
10096 (prop (setq type :prop beg beg1)
10097 (mapcar 'list (org-buffer-property-keys nil t t)))
10098 (t (progn
10099 (call-interactively org-completion-fallback-command)
10100 (throw 'exit nil)))))
10101 (pattern (buffer-substring-no-properties beg end))
10102 (completion (try-completion pattern table confirm)))
10103 (cond ((eq completion t)
10104 (if (not (assoc (upcase pattern) table))
10105 (message "Already complete")
10106 (if (and (equal type :opt)
10107 (not (member (car (assoc (upcase pattern) table))
10108 org-additional-option-like-keywords)))
10109 (insert (substring (cdr (assoc (upcase pattern) table))
10110 (length pattern)))
10111 (if (memq type '(:tag :prop)) (insert ":")))))
10112 ((null completion)
10113 (message "Can't find completion for \"%s\"" pattern)
10114 (ding))
10115 ((not (string= pattern completion))
10116 (delete-region beg end)
10117 (if (string-match " +$" completion)
10118 (setq completion (replace-match "" t t completion)))
10119 (insert completion)
10120 (if (get-buffer-window "*Completions*")
10121 (delete-window (get-buffer-window "*Completions*")))
10122 (if (assoc completion table)
10123 (if (eq type :todo) (insert " ")
10124 (if (memq type '(:tag :prop)) (insert ":"))))
10125 (if (and (equal type :opt) (assoc completion table))
10126 (message "%s" (substitute-command-keys
10127 "Press \\[org-complete] again to insert example settings"))))
10129 (message "Making completion list...")
10130 (let ((list (sort (all-completions pattern table confirm)
10131 'string<)))
10132 (with-output-to-temp-buffer "*Completions*"
10133 (condition-case nil
10134 ;; Protection needed for XEmacs and emacs 21
10135 (display-completion-list list pattern)
10136 (error (display-completion-list list)))))
10137 (message "Making completion list...%s" "done")))))))
10139 ;;;; TODO, DEADLINE, Comments
10141 (defun org-toggle-comment ()
10142 "Change the COMMENT state of an entry."
10143 (interactive)
10144 (save-excursion
10145 (org-back-to-heading)
10146 (let (case-fold-search)
10147 (if (looking-at (concat outline-regexp
10148 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10149 (replace-match "" t t nil 1)
10150 (if (looking-at outline-regexp)
10151 (progn
10152 (goto-char (match-end 0))
10153 (insert org-comment-string " ")))))))
10155 (defvar org-last-todo-state-is-todo nil
10156 "This is non-nil when the last TODO state change led to a TODO state.
10157 If the last change removed the TODO tag or switched to DONE, then
10158 this is nil.")
10160 (defvar org-setting-tags nil) ; dynamically skipped
10162 (defun org-parse-local-options (string var)
10163 "Parse STRING for startup setting relevant for variable VAR."
10164 (let ((rtn (symbol-value var))
10165 e opts)
10166 (save-match-data
10167 (if (or (not string) (not (string-match "\\S-" string)))
10169 (setq opts (delq nil (mapcar (lambda (x)
10170 (setq e (assoc x org-startup-options))
10171 (if (eq (nth 1 e) var) e nil))
10172 (org-split-string string "[ \t]+"))))
10173 (if (not opts)
10175 (setq rtn nil)
10176 (while (setq e (pop opts))
10177 (if (not (nth 3 e))
10178 (setq rtn (nth 2 e))
10179 (if (not (listp rtn)) (setq rtn nil))
10180 (push (nth 2 e) rtn)))
10181 rtn)))))
10183 (defvar org-todo-setup-filter-hook nil
10184 "Hook for functions that pre-filter todo specs.
10186 Each function takes a todo spec and returns either `nil' or the spec
10187 transformed into canonical form." )
10189 (defvar org-todo-get-default-hook nil
10190 "Hook for functions that get a default item for todo.
10192 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10193 `nil' or a string to be used for the todo mark." )
10195 (defvar org-agenda-headline-snapshot-before-repeat)
10197 (defun org-todo (&optional arg)
10198 "Change the TODO state of an item.
10199 The state of an item is given by a keyword at the start of the heading,
10200 like
10201 *** TODO Write paper
10202 *** DONE Call mom
10204 The different keywords are specified in the variable `org-todo-keywords'.
10205 By default the available states are \"TODO\" and \"DONE\".
10206 So for this example: when the item starts with TODO, it is changed to DONE.
10207 When it starts with DONE, the DONE is removed. And when neither TODO nor
10208 DONE are present, add TODO at the beginning of the heading.
10210 With C-u prefix arg, use completion to determine the new state.
10211 With numeric prefix arg, switch to that state.
10212 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
10213 With a triple C-u prefix, circumvent any state blocking.
10215 For calling through lisp, arg is also interpreted in the following way:
10216 'none -> empty state
10217 \"\"(empty string) -> switch to empty state
10218 'done -> switch to DONE
10219 'nextset -> switch to the next set of keywords
10220 'previousset -> switch to the previous set of keywords
10221 \"WAITING\" -> switch to the specified keyword, but only if it
10222 really is a member of `org-todo-keywords'."
10223 (interactive "P")
10224 (if (equal arg '(16)) (setq arg 'nextset))
10225 (let ((org-blocker-hook org-blocker-hook)
10226 (case-fold-search nil))
10227 (when (equal arg '(64))
10228 (setq arg nil org-blocker-hook nil))
10229 (when (and org-blocker-hook
10230 (or org-inhibit-blocking
10231 (org-entry-get nil "NOBLOCKING")))
10232 (setq org-blocker-hook nil))
10233 (save-excursion
10234 (catch 'exit
10235 (org-back-to-heading t)
10236 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10237 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10238 (looking-at " *"))
10239 (let* ((match-data (match-data))
10240 (startpos (point-at-bol))
10241 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
10242 (org-log-done org-log-done)
10243 (org-log-repeat org-log-repeat)
10244 (org-todo-log-states org-todo-log-states)
10245 (this (match-string 1))
10246 (hl-pos (match-beginning 0))
10247 (head (org-get-todo-sequence-head this))
10248 (ass (assoc head org-todo-kwd-alist))
10249 (interpret (nth 1 ass))
10250 (done-word (nth 3 ass))
10251 (final-done-word (nth 4 ass))
10252 (last-state (or this ""))
10253 (completion-ignore-case t)
10254 (member (member this org-todo-keywords-1))
10255 (tail (cdr member))
10256 (state (cond
10257 ((and org-todo-key-trigger
10258 (or (and (equal arg '(4))
10259 (eq org-use-fast-todo-selection 'prefix))
10260 (and (not arg) org-use-fast-todo-selection
10261 (not (eq org-use-fast-todo-selection
10262 'prefix)))))
10263 ;; Use fast selection
10264 (org-fast-todo-selection))
10265 ((and (equal arg '(4))
10266 (or (not org-use-fast-todo-selection)
10267 (not org-todo-key-trigger)))
10268 ;; Read a state with completion
10269 (org-icompleting-read
10270 "State: " (mapcar (lambda(x) (list x))
10271 org-todo-keywords-1)
10272 nil t))
10273 ((eq arg 'right)
10274 (if this
10275 (if tail (car tail) nil)
10276 (car org-todo-keywords-1)))
10277 ((eq arg 'left)
10278 (if (equal member org-todo-keywords-1)
10280 (if this
10281 (nth (- (length org-todo-keywords-1)
10282 (length tail) 2)
10283 org-todo-keywords-1)
10284 (org-last org-todo-keywords-1))))
10285 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10286 (setq arg nil))) ; hack to fall back to cycling
10287 (arg
10288 ;; user or caller requests a specific state
10289 (cond
10290 ((equal arg "") nil)
10291 ((eq arg 'none) nil)
10292 ((eq arg 'done) (or done-word (car org-done-keywords)))
10293 ((eq arg 'nextset)
10294 (or (car (cdr (member head org-todo-heads)))
10295 (car org-todo-heads)))
10296 ((eq arg 'previousset)
10297 (let ((org-todo-heads (reverse org-todo-heads)))
10298 (or (car (cdr (member head org-todo-heads)))
10299 (car org-todo-heads))))
10300 ((car (member arg org-todo-keywords-1)))
10301 ((stringp arg)
10302 (error "State `%s' not valid in this file" arg))
10303 ((nth (1- (prefix-numeric-value arg))
10304 org-todo-keywords-1))))
10305 ((null member) (or head (car org-todo-keywords-1)))
10306 ((equal this final-done-word) nil) ;; -> make empty
10307 ((null tail) nil) ;; -> first entry
10308 ((memq interpret '(type priority))
10309 (if (eq this-command last-command)
10310 (car tail)
10311 (if (> (length tail) 0)
10312 (or done-word (car org-done-keywords))
10313 nil)))
10315 (car tail))))
10316 (state (or
10317 (run-hook-with-args-until-success
10318 'org-todo-get-default-hook state last-state)
10319 state))
10320 (next (if state (concat " " state " ") " "))
10321 (change-plist (list :type 'todo-state-change :from this :to state
10322 :position startpos))
10323 dolog now-done-p)
10324 (when org-blocker-hook
10325 (setq org-last-todo-state-is-todo
10326 (not (member this org-done-keywords)))
10327 (unless (save-excursion
10328 (save-match-data
10329 (run-hook-with-args-until-failure
10330 'org-blocker-hook change-plist)))
10331 (if (interactive-p)
10332 (error "TODO state change from %s to %s blocked" this state)
10333 ;; fail silently
10334 (message "TODO state change from %s to %s blocked" this state)
10335 (throw 'exit nil))))
10336 (store-match-data match-data)
10337 (replace-match next t t)
10338 (unless (pos-visible-in-window-p hl-pos)
10339 (message "TODO state changed to %s" (org-trim next)))
10340 (unless head
10341 (setq head (org-get-todo-sequence-head state)
10342 ass (assoc head org-todo-kwd-alist)
10343 interpret (nth 1 ass)
10344 done-word (nth 3 ass)
10345 final-done-word (nth 4 ass)))
10346 (when (memq arg '(nextset previousset))
10347 (message "Keyword-Set %d/%d: %s"
10348 (- (length org-todo-sets) -1
10349 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10350 (length org-todo-sets)
10351 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10352 (setq org-last-todo-state-is-todo
10353 (not (member state org-done-keywords)))
10354 (setq now-done-p (and (member state org-done-keywords)
10355 (not (member this org-done-keywords))))
10356 (and logging (org-local-logging logging))
10357 (when (and (or org-todo-log-states org-log-done)
10358 (not (eq org-inhibit-logging t))
10359 (not (memq arg '(nextset previousset))))
10360 ;; we need to look at recording a time and note
10361 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10362 (nth 2 (assoc this org-todo-log-states))))
10363 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10364 (setq dolog 'time))
10365 (when (and state
10366 (member state org-not-done-keywords)
10367 (not (member this org-not-done-keywords)))
10368 ;; This is now a todo state and was not one before
10369 ;; If there was a CLOSED time stamp, get rid of it.
10370 (org-add-planning-info nil nil 'closed))
10371 (when (and now-done-p org-log-done)
10372 ;; It is now done, and it was not done before
10373 (org-add-planning-info 'closed (org-current-time))
10374 (if (and (not dolog) (eq 'note org-log-done))
10375 (org-add-log-setup 'done state this 'findpos 'note)))
10376 (when (and state dolog)
10377 ;; This is a non-nil state, and we need to log it
10378 (org-add-log-setup 'state state this 'findpos dolog)))
10379 ;; Fixup tag positioning
10380 (org-todo-trigger-tag-changes state)
10381 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10382 (when org-provide-todo-statistics
10383 (org-update-parent-todo-statistics))
10384 (run-hooks 'org-after-todo-state-change-hook)
10385 (if (and arg (not (member state org-done-keywords)))
10386 (setq head (org-get-todo-sequence-head state)))
10387 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10388 ;; Do we need to trigger a repeat?
10389 (when now-done-p
10390 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10391 ;; This is for the agenda, take a snapshot of the headline.
10392 (save-match-data
10393 (setq org-agenda-headline-snapshot-before-repeat
10394 (org-get-heading))))
10395 (org-auto-repeat-maybe state))
10396 ;; Fixup cursor location if close to the keyword
10397 (if (and (outline-on-heading-p)
10398 (not (bolp))
10399 (save-excursion (beginning-of-line 1)
10400 (looking-at org-todo-line-regexp))
10401 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10402 (progn
10403 (goto-char (or (match-end 2) (match-end 1)))
10404 (and (looking-at " ") (just-one-space))))
10405 (when org-trigger-hook
10406 (save-excursion
10407 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10409 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10410 "Block turning an entry into a TODO, using the hierarchy.
10411 This checks whether the current task should be blocked from state
10412 changes. Such blocking occurs when:
10414 1. The task has children which are not all in a completed state.
10416 2. A task has a parent with the property :ORDERED:, and there
10417 are siblings prior to the current task with incomplete
10418 status.
10420 3. The parent of the task is blocked because it has siblings that should
10421 be done first, or is child of a block grandparent TODO entry."
10423 (if (not org-enforce-todo-dependencies)
10424 t ; if locally turned off don't block
10425 (catch 'dont-block
10426 ;; If this is not a todo state change, or if this entry is already DONE,
10427 ;; do not block
10428 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10429 (member (plist-get change-plist :from)
10430 (cons 'done org-done-keywords))
10431 (member (plist-get change-plist :to)
10432 (cons 'todo org-not-done-keywords))
10433 (not (plist-get change-plist :to)))
10434 (throw 'dont-block t))
10435 ;; If this task has children, and any are undone, it's blocked
10436 (save-excursion
10437 (org-back-to-heading t)
10438 (let ((this-level (funcall outline-level)))
10439 (outline-next-heading)
10440 (let ((child-level (funcall outline-level)))
10441 (while (and (not (eobp))
10442 (> child-level this-level))
10443 ;; this todo has children, check whether they are all
10444 ;; completed
10445 (if (and (not (org-entry-is-done-p))
10446 (org-entry-is-todo-p))
10447 (throw 'dont-block nil))
10448 (outline-next-heading)
10449 (setq child-level (funcall outline-level))))))
10450 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10451 ;; any previous siblings are undone, it's blocked
10452 (save-excursion
10453 (org-back-to-heading t)
10454 (let* ((pos (point))
10455 (parent-pos (and (org-up-heading-safe) (point))))
10456 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10457 (when (and (org-entry-get (point) "ORDERED")
10458 (forward-line 1)
10459 (re-search-forward org-not-done-heading-regexp pos t))
10460 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10461 ;; Search further up the hierarchy, to see if an anchestor is blocked
10462 (while t
10463 (goto-char parent-pos)
10464 (if (not (looking-at org-not-done-heading-regexp))
10465 (throw 'dont-block t)) ; do not block, parent is not a TODO
10466 (setq pos (point))
10467 (setq parent-pos (and (org-up-heading-safe) (point)))
10468 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10469 (when (and (org-entry-get (point) "ORDERED")
10470 (forward-line 1)
10471 (re-search-forward org-not-done-heading-regexp pos t))
10472 (throw 'dont-block nil)))))))) ; block, older sibling not done.
10474 (defcustom org-track-ordered-property-with-tag nil
10475 "Should the ORDERED property also be shown as a tag?
10476 The ORDERED property decides if an entry should require subtasks to be
10477 completed in sequence. Since a property is not very visible, setting
10478 this option means that toggling the ORDERED property with the command
10479 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10480 not relevant for the behavior, but it makes things more visible.
10482 Note that toggling the tag with tags commands will not change the property
10483 and therefore not influence behavior!
10485 This can be t, meaning the tag ORDERED should be used, It can also be a
10486 string to select a different tag for this task."
10487 :group 'org-todo
10488 :type '(choice
10489 (const :tag "No tracking" nil)
10490 (const :tag "Track with ORDERED tag" t)
10491 (string :tag "Use other tag")))
10493 (defun org-toggle-ordered-property ()
10494 "Toggle the ORDERED property of the current entry.
10495 For better visibility, you can track the value of this property with a tag.
10496 See variable `org-track-ordered-property-with-tag'."
10497 (interactive)
10498 (let* ((t1 org-track-ordered-property-with-tag)
10499 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10500 (save-excursion
10501 (org-back-to-heading)
10502 (if (org-entry-get nil "ORDERED")
10503 (progn
10504 (org-delete-property "ORDERED")
10505 (and tag (org-toggle-tag tag 'off))
10506 (message "Subtasks can be completed in arbitrary order"))
10507 (org-entry-put nil "ORDERED" "t")
10508 (and tag (org-toggle-tag tag 'on))
10509 (message "Subtasks must be completed in sequence")))))
10511 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10512 (defun org-block-todo-from-checkboxes (change-plist)
10513 "Block turning an entry into a TODO, using checkboxes.
10514 This checks whether the current task should be blocked from state
10515 changes because there are unchecked boxes in this entry."
10516 (if (not org-enforce-todo-checkbox-dependencies)
10517 t ; if locally turned off don't block
10518 (catch 'dont-block
10519 ;; If this is not a todo state change, or if this entry is already DONE,
10520 ;; do not block
10521 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10522 (member (plist-get change-plist :from)
10523 (cons 'done org-done-keywords))
10524 (member (plist-get change-plist :to)
10525 (cons 'todo org-not-done-keywords))
10526 (not (plist-get change-plist :to)))
10527 (throw 'dont-block t))
10528 ;; If this task has checkboxes that are not checked, it's blocked
10529 (save-excursion
10530 (org-back-to-heading t)
10531 (let ((beg (point)) end)
10532 (outline-next-heading)
10533 (setq end (point))
10534 (goto-char beg)
10535 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10536 end t)
10537 (progn
10538 (if (boundp 'org-blocked-by-checkboxes)
10539 (setq org-blocked-by-checkboxes t))
10540 (throw 'dont-block nil)))))
10541 t))) ; do not block
10543 (defun org-entry-blocked-p ()
10544 "Is the current entry blocked?"
10545 (if (org-entry-get nil "NOBLOCKING")
10546 nil ;; Never block this entry
10547 (not
10548 (run-hook-with-args-until-failure
10549 'org-blocker-hook
10550 (list :type 'todo-state-change
10551 :position (point)
10552 :from 'todo
10553 :to 'done)))))
10555 (defun org-update-statistics-cookies (all)
10556 "Update the statistics cookie, either from TODO or from checkboxes.
10557 This should be called with the cursor in a line with a statistics cookie."
10558 (interactive "P")
10559 (if all
10560 (progn
10561 (org-update-checkbox-count 'all)
10562 (org-map-entries 'org-update-parent-todo-statistics))
10563 (if (not (org-on-heading-p))
10564 (org-update-checkbox-count)
10565 (let ((pos (move-marker (make-marker) (point)))
10566 end l1 l2)
10567 (ignore-errors (org-back-to-heading t))
10568 (if (not (org-on-heading-p))
10569 (org-update-checkbox-count)
10570 (setq l1 (org-outline-level))
10571 (setq end (save-excursion
10572 (outline-next-heading)
10573 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10574 (point)))
10575 (if (and (save-excursion
10576 (re-search-forward
10577 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
10578 (not (save-excursion (re-search-forward
10579 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10580 (org-update-checkbox-count)
10581 (if (and l2 (> l2 l1))
10582 (progn
10583 (goto-char end)
10584 (org-update-parent-todo-statistics))
10585 (goto-char pos)
10586 (beginning-of-line 1)
10587 (while (re-search-forward
10588 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
10589 (point-at-eol) t)
10590 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
10591 (goto-char pos)
10592 (move-marker pos nil)))))
10594 (defvar org-entry-property-inherited-from) ;; defined below
10595 (defun org-update-parent-todo-statistics ()
10596 "Update any statistics cookie in the parent of the current headline.
10597 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10598 the entire subtree and this will travel up the hierarchy and update
10599 statistics everywhere."
10600 (interactive)
10601 (let* ((lim 0) prop
10602 (recursive (or (not org-hierarchical-todo-statistics)
10603 (string-match
10604 "\\<recursive\\>"
10605 (or (setq prop (org-entry-get
10606 nil "COOKIE_DATA" 'inherit)) ""))))
10607 (lim (or (and prop (marker-position
10608 org-entry-property-inherited-from))
10609 lim))
10610 (first t)
10611 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10612 level ltoggle l1 new ndel
10613 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10614 (catch 'exit
10615 (save-excursion
10616 (beginning-of-line 1)
10617 (if (org-at-heading-p)
10618 (setq ltoggle (funcall outline-level))
10619 (error "This should not happen"))
10620 (while (and (setq level (org-up-heading-safe))
10621 (or recursive first)
10622 (>= (point) lim))
10623 (setq first nil cookie-present nil)
10624 (unless (and level
10625 (not (string-match
10626 "\\<checkbox\\>"
10627 (downcase
10628 (or (org-entry-get
10629 nil "COOKIE_DATA")
10630 "")))))
10631 (throw 'exit nil))
10632 (while (re-search-forward box-re (point-at-eol) t)
10633 (setq cnt-all 0 cnt-done 0 cookie-present t)
10634 (setq is-percent (match-end 2))
10635 (save-match-data
10636 (unless (outline-next-heading) (throw 'exit nil))
10637 (while (and (looking-at org-complex-heading-regexp)
10638 (> (setq l1 (length (match-string 1))) level))
10639 (setq kwd (and (or recursive (= l1 ltoggle))
10640 (match-string 2)))
10641 (if (or (eq org-provide-todo-statistics 'all-headlines)
10642 (and (listp org-provide-todo-statistics)
10643 (or (member kwd org-provide-todo-statistics)
10644 (member kwd org-done-keywords))))
10645 (setq cnt-all (1+ cnt-all))
10646 (if (eq org-provide-todo-statistics t)
10647 (and kwd (setq cnt-all (1+ cnt-all)))))
10648 (and (member kwd org-done-keywords)
10649 (setq cnt-done (1+ cnt-done)))
10650 (outline-next-heading)))
10651 (setq new
10652 (if is-percent
10653 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10654 (format "[%d/%d]" cnt-done cnt-all))
10655 ndel (- (match-end 0) (match-beginning 0)))
10656 (goto-char (match-beginning 0))
10657 (insert new)
10658 (delete-region (point) (+ (point) ndel)))
10659 (when cookie-present
10660 (run-hook-with-args 'org-after-todo-statistics-hook
10661 cnt-done (- cnt-all cnt-done))))))
10662 (run-hooks 'org-todo-statistics-hook)))
10664 (defvar org-after-todo-statistics-hook nil
10665 "Hook that is called after a TODO statistics cookie has been updated.
10666 Each function is called with two arguments: the number of not-done entries
10667 and the number of done entries.
10669 For example, the following function, when added to this hook, will switch
10670 an entry to DONE when all children are done, and back to TODO when new
10671 entries are set to a TODO status. Note that this hook is only called
10672 when there is a statistics cookie in the headline!
10674 (defun org-summary-todo (n-done n-not-done)
10675 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10676 (let (org-log-done org-log-states) ; turn off logging
10677 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10680 (defvar org-todo-statistics-hook nil
10681 "Hook that is run whenever Org thinks TODO statistics should be updated.
10682 This hook runs even if there is no statistics cookie present, in which case
10683 `org-after-todo-statistics-hook' would not run.")
10685 (defun org-todo-trigger-tag-changes (state)
10686 "Apply the changes defined in `org-todo-state-tags-triggers'."
10687 (let ((l org-todo-state-tags-triggers)
10688 changes)
10689 (when (or (not state) (equal state ""))
10690 (setq changes (append changes (cdr (assoc "" l)))))
10691 (when (and (stringp state) (> (length state) 0))
10692 (setq changes (append changes (cdr (assoc state l)))))
10693 (when (member state org-not-done-keywords)
10694 (setq changes (append changes (cdr (assoc 'todo l)))))
10695 (when (member state org-done-keywords)
10696 (setq changes (append changes (cdr (assoc 'done l)))))
10697 (dolist (c changes)
10698 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10700 (defun org-local-logging (value)
10701 "Get logging settings from a property VALUE."
10702 (let* (words w a)
10703 ;; directly set the variables, they are already local.
10704 (setq org-log-done nil
10705 org-log-repeat nil
10706 org-todo-log-states nil)
10707 (setq words (org-split-string value))
10708 (while (setq w (pop words))
10709 (cond
10710 ((setq a (assoc w org-startup-options))
10711 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10712 (set (nth 1 a) (nth 2 a))))
10713 ((setq a (org-extract-log-state-settings w))
10714 (and (member (car a) org-todo-keywords-1)
10715 (push a org-todo-log-states)))))))
10717 (defun org-get-todo-sequence-head (kwd)
10718 "Return the head of the TODO sequence to which KWD belongs.
10719 If KWD is not set, check if there is a text property remembering the
10720 right sequence."
10721 (let (p)
10722 (cond
10723 ((not kwd)
10724 (or (get-text-property (point-at-bol) 'org-todo-head)
10725 (progn
10726 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10727 nil (point-at-eol)))
10728 (get-text-property p 'org-todo-head))))
10729 ((not (member kwd org-todo-keywords-1))
10730 (car org-todo-keywords-1))
10731 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10733 (defun org-fast-todo-selection ()
10734 "Fast TODO keyword selection with single keys.
10735 Returns the new TODO keyword, or nil if no state change should occur."
10736 (let* ((fulltable org-todo-key-alist)
10737 (done-keywords org-done-keywords) ;; needed for the faces.
10738 (maxlen (apply 'max (mapcar
10739 (lambda (x)
10740 (if (stringp (car x)) (string-width (car x)) 0))
10741 fulltable)))
10742 (expert nil)
10743 (fwidth (+ maxlen 3 1 3))
10744 (ncol (/ (- (window-width) 4) fwidth))
10745 tg cnt e c tbl
10746 groups ingroup)
10747 (save-excursion
10748 (save-window-excursion
10749 (if expert
10750 (set-buffer (get-buffer-create " *Org todo*"))
10751 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10752 (erase-buffer)
10753 (org-set-local 'org-done-keywords done-keywords)
10754 (setq tbl fulltable cnt 0)
10755 (while (setq e (pop tbl))
10756 (cond
10757 ((equal e '(:startgroup))
10758 (push '() groups) (setq ingroup t)
10759 (when (not (= cnt 0))
10760 (setq cnt 0)
10761 (insert "\n"))
10762 (insert "{ "))
10763 ((equal e '(:endgroup))
10764 (setq ingroup nil cnt 0)
10765 (insert "}\n"))
10766 ((equal e '(:newline))
10767 (when (not (= cnt 0))
10768 (setq cnt 0)
10769 (insert "\n")
10770 (setq e (car tbl))
10771 (while (equal (car tbl) '(:newline))
10772 (insert "\n")
10773 (setq tbl (cdr tbl)))))
10775 (setq tg (car e) c (cdr e))
10776 (if ingroup (push tg (car groups)))
10777 (setq tg (org-add-props tg nil 'face
10778 (org-get-todo-face tg)))
10779 (if (and (= cnt 0) (not ingroup)) (insert " "))
10780 (insert "[" c "] " tg (make-string
10781 (- fwidth 4 (length tg)) ?\ ))
10782 (when (= (setq cnt (1+ cnt)) ncol)
10783 (insert "\n")
10784 (if ingroup (insert " "))
10785 (setq cnt 0)))))
10786 (insert "\n")
10787 (goto-char (point-min))
10788 (if (not expert) (org-fit-window-to-buffer))
10789 (message "[a-z..]:Set [SPC]:clear")
10790 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10791 (cond
10792 ((or (= c ?\C-g)
10793 (and (= c ?q) (not (rassoc c fulltable))))
10794 (setq quit-flag t))
10795 ((= c ?\ ) nil)
10796 ((setq e (rassoc c fulltable) tg (car e))
10798 (t (setq quit-flag t)))))))
10800 (defun org-entry-is-todo-p ()
10801 (member (org-get-todo-state) org-not-done-keywords))
10803 (defun org-entry-is-done-p ()
10804 (member (org-get-todo-state) org-done-keywords))
10806 (defun org-get-todo-state ()
10807 (save-excursion
10808 (org-back-to-heading t)
10809 (and (looking-at org-todo-line-regexp)
10810 (match-end 2)
10811 (match-string 2))))
10813 (defun org-at-date-range-p (&optional inactive-ok)
10814 "Is the cursor inside a date range?"
10815 (interactive)
10816 (save-excursion
10817 (catch 'exit
10818 (let ((pos (point)))
10819 (skip-chars-backward "^[<\r\n")
10820 (skip-chars-backward "<[")
10821 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10822 (>= (match-end 0) pos)
10823 (throw 'exit t))
10824 (skip-chars-backward "^<[\r\n")
10825 (skip-chars-backward "<[")
10826 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10827 (>= (match-end 0) pos)
10828 (throw 'exit t)))
10829 nil)))
10831 (defun org-get-repeat (&optional tagline)
10832 "Check if there is a deadline/schedule with repeater in this entry."
10833 (save-match-data
10834 (save-excursion
10835 (org-back-to-heading t)
10836 (and (re-search-forward (if tagline
10837 (concat tagline "\\s-*" org-repeat-re)
10838 org-repeat-re)
10839 (org-entry-end-position) t)
10840 (match-string-no-properties 1)))))
10842 (defvar org-last-changed-timestamp)
10843 (defvar org-last-inserted-timestamp)
10844 (defvar org-log-post-message)
10845 (defvar org-log-note-purpose)
10846 (defvar org-log-note-how)
10847 (defvar org-log-note-extra)
10848 (defun org-auto-repeat-maybe (done-word)
10849 "Check if the current headline contains a repeated deadline/schedule.
10850 If yes, set TODO state back to what it was and change the base date
10851 of repeating deadline/scheduled time stamps to new date.
10852 This function is run automatically after each state change to a DONE state."
10853 ;; last-state is dynamically scoped into this function
10854 (let* ((repeat (org-get-repeat))
10855 (aa (assoc last-state org-todo-kwd-alist))
10856 (interpret (nth 1 aa))
10857 (head (nth 2 aa))
10858 (whata '(("d" . day) ("m" . month) ("y" . year)))
10859 (msg "Entry repeats: ")
10860 (org-log-done nil)
10861 (org-todo-log-states nil)
10862 (nshiftmax 10) (nshift 0)
10863 re type n what ts time to-state)
10864 (when repeat
10865 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10866 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
10867 org-todo-repeat-to-state))
10868 (unless (and to-state (member to-state org-todo-keywords-1))
10869 (setq to-state (if (eq interpret 'type) last-state head)))
10870 (org-todo to-state)
10871 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
10872 (org-entry-put nil "LAST_REPEAT" (format-time-string
10873 (org-time-stamp-format t t))))
10874 (when org-log-repeat
10875 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10876 (memq 'org-add-log-note post-command-hook))
10877 ;; OK, we are already setup for some record
10878 (if (eq org-log-repeat 'note)
10879 ;; make sure we take a note, not only a time stamp
10880 (setq org-log-note-how 'note))
10881 ;; Set up for taking a record
10882 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10883 last-state
10884 'findpos org-log-repeat)))
10885 (org-back-to-heading t)
10886 (org-add-planning-info nil nil 'closed)
10887 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10888 org-deadline-time-regexp "\\)\\|\\("
10889 org-ts-regexp "\\)"))
10890 (while (re-search-forward
10891 re (save-excursion (outline-next-heading) (point)) t)
10892 (setq type (if (match-end 1) org-scheduled-string
10893 (if (match-end 3) org-deadline-string "Plain:"))
10894 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10895 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10896 (setq n (string-to-number (match-string 2 ts))
10897 what (match-string 3 ts))
10898 (if (equal what "w") (setq n (* n 7) what "d"))
10899 ;; Preparation, see if we need to modify the start date for the change
10900 (when (match-end 1)
10901 (setq time (save-match-data (org-time-string-to-time ts)))
10902 (cond
10903 ((equal (match-string 1 ts) ".")
10904 ;; Shift starting date to today
10905 (org-timestamp-change
10906 (- (time-to-days (current-time)) (time-to-days time))
10907 'day))
10908 ((equal (match-string 1 ts) "+")
10909 (while (or (= nshift 0)
10910 (<= (time-to-days time) (time-to-days (current-time))))
10911 (when (= (incf nshift) nshiftmax)
10912 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10913 (error "Abort")))
10914 (org-timestamp-change n (cdr (assoc what whata)))
10915 (org-at-timestamp-p t)
10916 (setq ts (match-string 1))
10917 (setq time (save-match-data (org-time-string-to-time ts))))
10918 (org-timestamp-change (- n) (cdr (assoc what whata)))
10919 ;; rematch, so that we have everything in place for the real shift
10920 (org-at-timestamp-p t)
10921 (setq ts (match-string 1))
10922 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10923 (org-timestamp-change n (cdr (assoc what whata)))
10924 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10925 (setq org-log-post-message msg)
10926 (message "%s" msg))))
10928 (defun org-show-todo-tree (arg)
10929 "Make a compact tree which shows all headlines marked with TODO.
10930 The tree will show the lines where the regexp matches, and all higher
10931 headlines above the match.
10932 With a \\[universal-argument] prefix, prompt for a regexp to match.
10933 With a numeric prefix N, construct a sparse tree for the Nth element
10934 of `org-todo-keywords-1'."
10935 (interactive "P")
10936 (let ((case-fold-search nil)
10937 (kwd-re
10938 (cond ((null arg) org-not-done-regexp)
10939 ((equal arg '(4))
10940 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10941 (mapcar 'list org-todo-keywords-1))))
10942 (concat "\\("
10943 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10944 "\\)\\>")))
10945 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10946 (regexp-quote (nth (1- (prefix-numeric-value arg))
10947 org-todo-keywords-1)))
10948 (t (error "Invalid prefix argument: %s" arg)))))
10949 (message "%d TODO entries found"
10950 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10952 (defun org-deadline (&optional remove time)
10953 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10954 With argument REMOVE, remove any deadline from the item.
10955 When TIME is set, it should be an internal time specification, and the
10956 scheduling will use the corresponding date."
10957 (interactive "P")
10958 (let* ((old-date (org-entry-get nil "DEADLINE"))
10959 (repeater (and old-date
10960 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
10961 (match-string 1 old-date))))
10962 (if remove
10963 (progn
10964 (when (and old-date org-log-redeadline)
10965 (org-add-log-setup 'deldeadline nil old-date 'findpos
10966 org-log-redeadline))
10967 (org-remove-timestamp-with-keyword org-deadline-string)
10968 (message "Item no longer has a deadline."))
10969 (org-add-planning-info 'deadline time 'closed)
10970 (when (and old-date org-log-redeadline
10971 (not (equal old-date
10972 (substring org-last-inserted-timestamp 1 -1))))
10973 (org-add-log-setup 'redeadline nil old-date 'findpos
10974 org-log-redeadline))
10975 (when repeater
10976 (save-excursion
10977 (org-back-to-heading t)
10978 (when (re-search-forward (concat org-deadline-string " "
10979 org-last-inserted-timestamp)
10980 (save-excursion
10981 (outline-next-heading) (point)) t)
10982 (goto-char (1- (match-end 0)))
10983 (insert " " repeater)
10984 (setq org-last-inserted-timestamp
10985 (concat (substring org-last-inserted-timestamp 0 -1)
10986 " " repeater
10987 (substring org-last-inserted-timestamp -1))))))
10988 (message "Deadline on %s" org-last-inserted-timestamp))))
10990 (defun org-schedule (&optional remove time)
10991 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10992 With argument REMOVE, remove any scheduling date from the item.
10993 When TIME is set, it should be an internal time specification, and the
10994 scheduling will use the corresponding date."
10995 (interactive "P")
10996 (let* ((old-date (org-entry-get nil "SCHEDULED"))
10997 (repeater (and old-date
10998 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
10999 (match-string 1 old-date))))
11000 (if remove
11001 (progn
11002 (when (and old-date org-log-reschedule)
11003 (org-add-log-setup 'delschedule nil old-date 'findpos
11004 org-log-reschedule))
11005 (org-remove-timestamp-with-keyword org-scheduled-string)
11006 (message "Item is no longer scheduled."))
11007 (org-add-planning-info 'scheduled time 'closed)
11008 (when (and old-date org-log-reschedule
11009 (not (equal old-date
11010 (substring org-last-inserted-timestamp 1 -1))))
11011 (org-add-log-setup 'reschedule nil old-date 'findpos
11012 org-log-reschedule))
11013 (when repeater
11014 (save-excursion
11015 (org-back-to-heading t)
11016 (when (re-search-forward (concat org-scheduled-string " "
11017 org-last-inserted-timestamp)
11018 (save-excursion
11019 (outline-next-heading) (point)) t)
11020 (goto-char (1- (match-end 0)))
11021 (insert " " repeater)
11022 (setq org-last-inserted-timestamp
11023 (concat (substring org-last-inserted-timestamp 0 -1)
11024 " " repeater
11025 (substring org-last-inserted-timestamp -1))))))
11026 (message "Scheduled to %s" org-last-inserted-timestamp))))
11028 (defun org-get-scheduled-time (pom &optional inherit)
11029 "Get the scheduled time as a time tuple, of a format suitable
11030 for calling org-schedule with, or if there is no scheduling,
11031 returns nil."
11032 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11033 (when time
11034 (apply 'encode-time (org-parse-time-string time)))))
11036 (defun org-get-deadline-time (pom &optional inherit)
11037 "Get the deadine as a time tuple, of a format suitable for
11038 calling org-deadline with, or if there is no scheduling, returns
11039 nil."
11040 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11041 (when time
11042 (apply 'encode-time (org-parse-time-string time)))))
11044 (defun org-remove-timestamp-with-keyword (keyword)
11045 "Remove all time stamps with KEYWORD in the current entry."
11046 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11047 beg)
11048 (save-excursion
11049 (org-back-to-heading t)
11050 (setq beg (point))
11051 (outline-next-heading)
11052 (while (re-search-backward re beg t)
11053 (replace-match "")
11054 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11055 (equal (char-before) ?\ ))
11056 (backward-delete-char 1)
11057 (if (string-match "^[ \t]*$" (buffer-substring
11058 (point-at-bol) (point-at-eol)))
11059 (delete-region (point-at-bol)
11060 (min (point-max) (1+ (point-at-eol))))))))))
11062 (defun org-add-planning-info (what &optional time &rest remove)
11063 "Insert new timestamp with keyword in the line directly after the headline.
11064 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11065 If non is given, the user is prompted for a date.
11066 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11067 be removed."
11068 (interactive)
11069 (let (org-time-was-given org-end-time-was-given ts
11070 end default-time default-input)
11072 (catch 'exit
11073 (when (and (not time) (memq what '(scheduled deadline)))
11074 ;; Try to get a default date/time from existing timestamp
11075 (save-excursion
11076 (org-back-to-heading t)
11077 (setq end (save-excursion (outline-next-heading) (point)))
11078 (when (re-search-forward (if (eq what 'scheduled)
11079 org-scheduled-time-regexp
11080 org-deadline-time-regexp)
11081 end t)
11082 (setq ts (match-string 1)
11083 default-time
11084 (apply 'encode-time (org-parse-time-string ts))
11085 default-input (and ts (org-get-compact-tod ts))))))
11086 (when what
11087 ;; If necessary, get the time from the user
11088 (setq time (or time (org-read-date nil 'to-time nil nil
11089 default-time default-input))))
11091 (when (and org-insert-labeled-timestamps-at-point
11092 (member what '(scheduled deadline)))
11093 (insert
11094 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11095 (org-insert-time-stamp time org-time-was-given
11096 nil nil nil (list org-end-time-was-given))
11097 (setq what nil))
11098 (save-excursion
11099 (save-restriction
11100 (let (col list elt ts buffer-invisibility-spec)
11101 (org-back-to-heading t)
11102 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11103 (goto-char (match-end 1))
11104 (setq col (current-column))
11105 (goto-char (match-end 0))
11106 (if (eobp) (insert "\n") (forward-char 1))
11107 (when (and (not what)
11108 (not (looking-at
11109 (concat "[ \t]*"
11110 org-keyword-time-not-clock-regexp))))
11111 ;; Nothing to add, nothing to remove...... :-)
11112 (throw 'exit nil))
11113 (if (and (not (looking-at outline-regexp))
11114 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11115 "[^\r\n]*"))
11116 (not (equal (match-string 1) org-clock-string)))
11117 (narrow-to-region (match-beginning 0) (match-end 0))
11118 (insert-before-markers "\n")
11119 (backward-char 1)
11120 (narrow-to-region (point) (point))
11121 (and org-adapt-indentation (org-indent-to-column col)))
11122 ;; Check if we have to remove something.
11123 (setq list (cons what remove))
11124 (while list
11125 (setq elt (pop list))
11126 (goto-char (point-min))
11127 (when (or (and (eq elt 'scheduled)
11128 (re-search-forward org-scheduled-time-regexp nil t))
11129 (and (eq elt 'deadline)
11130 (re-search-forward org-deadline-time-regexp nil t))
11131 (and (eq elt 'closed)
11132 (re-search-forward org-closed-time-regexp nil t)))
11133 (replace-match "")
11134 (if (looking-at "--+<[^>]+>") (replace-match ""))
11135 (skip-chars-backward " ")
11136 (if (looking-at " +") (replace-match ""))))
11137 (goto-char (point-max))
11138 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11139 (when what
11140 (insert
11141 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11142 (cond ((eq what 'scheduled) org-scheduled-string)
11143 ((eq what 'deadline) org-deadline-string)
11144 ((eq what 'closed) org-closed-string))
11145 " ")
11146 (setq ts (org-insert-time-stamp
11147 time
11148 (or org-time-was-given
11149 (and (eq what 'closed) org-log-done-with-time))
11150 (eq what 'closed)
11151 nil nil (list org-end-time-was-given)))
11152 (end-of-line 1))
11153 (goto-char (point-min))
11154 (widen)
11155 (if (and (looking-at "[ \t]+\n")
11156 (equal (char-before) ?\n))
11157 (delete-region (1- (point)) (point-at-eol)))
11158 ts))))))
11160 (defvar org-log-note-marker (make-marker))
11161 (defvar org-log-note-purpose nil)
11162 (defvar org-log-note-state nil)
11163 (defvar org-log-note-previous-state nil)
11164 (defvar org-log-note-how nil)
11165 (defvar org-log-note-extra nil)
11166 (defvar org-log-note-window-configuration nil)
11167 (defvar org-log-note-return-to (make-marker))
11168 (defvar org-log-post-message nil
11169 "Message to be displayed after a log note has been stored.
11170 The auto-repeater uses this.")
11172 (defun org-add-note ()
11173 "Add a note to the current entry.
11174 This is done in the same way as adding a state change note."
11175 (interactive)
11176 (org-add-log-setup 'note nil nil 'findpos nil))
11178 (defvar org-property-end-re)
11179 (defun org-add-log-setup (&optional purpose state prev-state
11180 findpos how &optional extra)
11181 "Set up the post command hook to take a note.
11182 If this is about to TODO state change, the new state is expected in STATE.
11183 When FINDPOS is non-nil, find the correct position for the note in
11184 the current entry. If not, assume that it can be inserted at point.
11185 HOW is an indicator what kind of note should be created.
11186 EXTRA is additional text that will be inserted into the notes buffer."
11187 (let* ((org-log-into-drawer (org-log-into-drawer))
11188 (drawer (cond ((stringp org-log-into-drawer)
11189 org-log-into-drawer)
11190 (org-log-into-drawer "LOGBOOK")
11191 (t nil))))
11192 (save-restriction
11193 (save-excursion
11194 (when findpos
11195 (org-back-to-heading t)
11196 (narrow-to-region (point) (save-excursion
11197 (outline-next-heading) (point)))
11198 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11199 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11200 "[^\r\n]*\\)?"))
11201 (goto-char (match-end 0))
11202 (cond
11203 (drawer
11204 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11205 nil t)
11206 (progn
11207 (goto-char (match-end 0))
11208 (or org-log-states-order-reversed
11209 (and (re-search-forward org-property-end-re nil t)
11210 (goto-char (1- (match-beginning 0))))))
11211 (insert "\n:" drawer ":\n:END:")
11212 (beginning-of-line 0)
11213 (org-indent-line-function)
11214 (beginning-of-line 2)
11215 (org-indent-line-function)
11216 (end-of-line 0)))
11217 ((and org-log-state-notes-insert-after-drawers
11218 (save-excursion
11219 (forward-line) (looking-at org-drawer-regexp)))
11220 (forward-line)
11221 (while (looking-at org-drawer-regexp)
11222 (goto-char (match-end 0))
11223 (re-search-forward org-property-end-re (point-max) t)
11224 (forward-line))
11225 (forward-line -1)))
11226 (unless org-log-states-order-reversed
11227 (and (= (char-after) ?\n) (forward-char 1))
11228 (org-skip-over-state-notes)
11229 (skip-chars-backward " \t\n\r")))
11230 (move-marker org-log-note-marker (point))
11231 (setq org-log-note-purpose purpose
11232 org-log-note-state state
11233 org-log-note-previous-state prev-state
11234 org-log-note-how how
11235 org-log-note-extra extra)
11236 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11238 (defun org-skip-over-state-notes ()
11239 "Skip past the list of State notes in an entry."
11240 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11241 (while (looking-at "[ \t]*- State")
11242 (condition-case nil
11243 (org-next-item)
11244 (error (org-end-of-item)))))
11246 (defun org-add-log-note (&optional purpose)
11247 "Pop up a window for taking a note, and add this note later at point."
11248 (remove-hook 'post-command-hook 'org-add-log-note)
11249 (setq org-log-note-window-configuration (current-window-configuration))
11250 (delete-other-windows)
11251 (move-marker org-log-note-return-to (point))
11252 (switch-to-buffer (marker-buffer org-log-note-marker))
11253 (goto-char org-log-note-marker)
11254 (org-switch-to-buffer-other-window "*Org Note*")
11255 (erase-buffer)
11256 (if (memq org-log-note-how '(time state))
11257 (let (current-prefix-arg) (org-store-log-note))
11258 (let ((org-inhibit-startup t)) (org-mode))
11259 (insert (format "# Insert note for %s.
11260 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11261 (cond
11262 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11263 ((eq org-log-note-purpose 'done) "closed todo item")
11264 ((eq org-log-note-purpose 'state)
11265 (format "state change from \"%s\" to \"%s\""
11266 (or org-log-note-previous-state "")
11267 (or org-log-note-state "")))
11268 ((eq org-log-note-purpose 'reschedule)
11269 "rescheduling")
11270 ((eq org-log-note-purpose 'delschedule)
11271 "no longer scheduled")
11272 ((eq org-log-note-purpose 'redeadline)
11273 "changing deadline")
11274 ((eq org-log-note-purpose 'deldeadline)
11275 "removing deadline")
11276 ((eq org-log-note-purpose 'refile)
11277 "refiling")
11278 ((eq org-log-note-purpose 'note)
11279 "this entry")
11280 (t (error "This should not happen")))))
11281 (if org-log-note-extra (insert org-log-note-extra))
11282 (org-set-local 'org-finish-function 'org-store-log-note)))
11284 (defvar org-note-abort nil) ; dynamically scoped
11285 (defun org-store-log-note ()
11286 "Finish taking a log note, and insert it to where it belongs."
11287 (let ((txt (buffer-string))
11288 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11289 lines ind)
11290 (kill-buffer (current-buffer))
11291 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11292 (setq txt (replace-match "" t t txt)))
11293 (if (string-match "\\s-+\\'" txt)
11294 (setq txt (replace-match "" t t txt)))
11295 (setq lines (org-split-string txt "\n"))
11296 (when (and note (string-match "\\S-" note))
11297 (setq note
11298 (org-replace-escapes
11299 note
11300 (list (cons "%u" (user-login-name))
11301 (cons "%U" user-full-name)
11302 (cons "%t" (format-time-string
11303 (org-time-stamp-format 'long 'inactive)
11304 (current-time)))
11305 (cons "%s" (if org-log-note-state
11306 (concat "\"" org-log-note-state "\"")
11307 ""))
11308 (cons "%S" (if org-log-note-previous-state
11309 (concat "\"" org-log-note-previous-state "\"")
11310 "\"\"")))))
11311 (if lines (setq note (concat note " \\\\")))
11312 (push note lines))
11313 (when (or current-prefix-arg org-note-abort)
11314 (when org-log-into-drawer
11315 (org-remove-empty-drawer-at
11316 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11317 org-log-note-marker))
11318 (setq lines nil))
11319 (when lines
11320 (with-current-buffer (marker-buffer org-log-note-marker)
11321 (save-excursion
11322 (goto-char org-log-note-marker)
11323 (move-marker org-log-note-marker nil)
11324 (end-of-line 1)
11325 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11326 (insert "- " (pop lines))
11327 (org-indent-line-function)
11328 (beginning-of-line 1)
11329 (looking-at "[ \t]*")
11330 (setq ind (concat (match-string 0) " "))
11331 (end-of-line 1)
11332 (while lines (insert "\n" ind (pop lines)))
11333 (message "Note stored")
11334 (org-back-to-heading t)
11335 (org-cycle-hide-drawers 'children)))))
11336 (set-window-configuration org-log-note-window-configuration)
11337 (with-current-buffer (marker-buffer org-log-note-return-to)
11338 (goto-char org-log-note-return-to))
11339 (move-marker org-log-note-return-to nil)
11340 (and org-log-post-message (message "%s" org-log-post-message)))
11342 (defun org-remove-empty-drawer-at (drawer pos)
11343 "Remove an empty drawer DRAWER at position POS.
11344 POS may also be a marker."
11345 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11346 (save-excursion
11347 (save-restriction
11348 (widen)
11349 (goto-char pos)
11350 (if (org-in-regexp
11351 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11352 (replace-match ""))))))
11354 (defun org-sparse-tree (&optional arg)
11355 "Create a sparse tree, prompt for the details.
11356 This command can create sparse trees. You first need to select the type
11357 of match used to create the tree:
11359 t Show entries with a specific TODO keyword.
11360 m Show entries selected by a tags/property match.
11361 p Enter a property name and its value (both with completion on existing
11362 names/values) and show entries with that property.
11363 / Show entries matching a regular expression (`r' can be used as well)
11364 d Show deadlines due within `org-deadline-warning-days'.
11365 b Show deadlines and scheduled items before a date.
11366 a Show deadlines and scheduled items after a date."
11367 (interactive "P")
11368 (let (ans kwd value)
11369 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
11370 (setq ans (read-char-exclusive))
11371 (cond
11372 ((equal ans ?d)
11373 (call-interactively 'org-check-deadlines))
11374 ((equal ans ?b)
11375 (call-interactively 'org-check-before-date))
11376 ((equal ans ?a)
11377 (call-interactively 'org-check-after-date))
11378 ((equal ans ?t)
11379 (org-show-todo-tree '(4)))
11380 ((member ans '(?T ?m))
11381 (call-interactively 'org-match-sparse-tree))
11382 ((member ans '(?p ?P))
11383 (setq kwd (org-icompleting-read "Property: "
11384 (mapcar 'list (org-buffer-property-keys))))
11385 (setq value (org-icompleting-read "Value: "
11386 (mapcar 'list (org-property-values kwd))))
11387 (unless (string-match "\\`{.*}\\'" value)
11388 (setq value (concat "\"" value "\"")))
11389 (org-match-sparse-tree arg (concat kwd "=" value)))
11390 ((member ans '(?r ?R ?/))
11391 (call-interactively 'org-occur))
11392 (t (error "No such sparse tree command \"%c\"" ans)))))
11394 (defvar org-occur-highlights nil
11395 "List of overlays used for occur matches.")
11396 (make-variable-buffer-local 'org-occur-highlights)
11397 (defvar org-occur-parameters nil
11398 "Parameters of the active org-occur calls.
11399 This is a list, each call to org-occur pushes as cons cell,
11400 containing the regular expression and the callback, onto the list.
11401 The list can contain several entries if `org-occur' has been called
11402 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11403 will only contain one set of parameters. When the highlights are
11404 removed (for example with `C-c C-c', or with the next edit (depending
11405 on `org-remove-highlights-with-change'), this variable is emptied
11406 as well.")
11407 (make-variable-buffer-local 'org-occur-parameters)
11409 (defun org-occur (regexp &optional keep-previous callback)
11410 "Make a compact tree which shows all matches of REGEXP.
11411 The tree will show the lines where the regexp matches, and all higher
11412 headlines above the match. It will also show the heading after the match,
11413 to make sure editing the matching entry is easy.
11414 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11415 call to `org-occur' will be kept, to allow stacking of calls to this
11416 command.
11417 If CALLBACK is non-nil, it is a function which is called to confirm
11418 that the match should indeed be shown."
11419 (interactive "sRegexp: \nP")
11420 (when (equal regexp "")
11421 (error "Regexp cannot be empty"))
11422 (unless keep-previous
11423 (org-remove-occur-highlights nil nil t))
11424 (push (cons regexp callback) org-occur-parameters)
11425 (let ((cnt 0))
11426 (save-excursion
11427 (goto-char (point-min))
11428 (if (or (not keep-previous) ; do not want to keep
11429 (not org-occur-highlights)) ; no previous matches
11430 ;; hide everything
11431 (org-overview))
11432 (while (re-search-forward regexp nil t)
11433 (when (or (not callback)
11434 (save-match-data (funcall callback)))
11435 (setq cnt (1+ cnt))
11436 (when org-highlight-sparse-tree-matches
11437 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11438 (org-show-context 'occur-tree))))
11439 (when org-remove-highlights-with-change
11440 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11441 nil 'local))
11442 (unless org-sparse-tree-open-archived-trees
11443 (org-hide-archived-subtrees (point-min) (point-max)))
11444 (run-hooks 'org-occur-hook)
11445 (if (interactive-p)
11446 (message "%d match(es) for regexp %s" cnt regexp))
11447 cnt))
11449 (defun org-show-context (&optional key)
11450 "Make sure point and context and visible.
11451 How much context is shown depends upon the variables
11452 `org-show-hierarchy-above', `org-show-following-heading'. and
11453 `org-show-siblings'."
11454 (let ((heading-p (org-on-heading-p t))
11455 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11456 (following-p (org-get-alist-option org-show-following-heading key))
11457 (entry-p (org-get-alist-option org-show-entry-below key))
11458 (siblings-p (org-get-alist-option org-show-siblings key)))
11459 (catch 'exit
11460 ;; Show heading or entry text
11461 (if (and heading-p (not entry-p))
11462 (org-flag-heading nil) ; only show the heading
11463 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11464 (org-show-hidden-entry))) ; show entire entry
11465 (when following-p
11466 ;; Show next sibling, or heading below text
11467 (save-excursion
11468 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11469 (org-flag-heading nil))))
11470 (when siblings-p (org-show-siblings))
11471 (when hierarchy-p
11472 ;; show all higher headings, possibly with siblings
11473 (save-excursion
11474 (while (and (condition-case nil
11475 (progn (org-up-heading-all 1) t)
11476 (error nil))
11477 (not (bobp)))
11478 (org-flag-heading nil)
11479 (when siblings-p (org-show-siblings))))))))
11481 (defvar org-reveal-start-hook nil
11482 "Hook run before revealing a location.")
11484 (defun org-reveal (&optional siblings)
11485 "Show current entry, hierarchy above it, and the following headline.
11486 This can be used to show a consistent set of context around locations
11487 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11488 not t for the search context.
11490 With optional argument SIBLINGS, on each level of the hierarchy all
11491 siblings are shown. This repairs the tree structure to what it would
11492 look like when opened with hierarchical calls to `org-cycle'.
11493 With double optional argument `C-u C-u', go to the parent and show the
11494 entire tree."
11495 (interactive "P")
11496 (run-hooks 'org-reveal-start-hook)
11497 (let ((org-show-hierarchy-above t)
11498 (org-show-following-heading t)
11499 (org-show-siblings (if siblings t org-show-siblings)))
11500 (org-show-context nil))
11501 (when (equal siblings '(16))
11502 (save-excursion
11503 (when (org-up-heading-safe)
11504 (org-show-subtree)
11505 (run-hook-with-args 'org-cycle-hook 'subtree)))))
11507 (defun org-highlight-new-match (beg end)
11508 "Highlight from BEG to END and mark the highlight is an occur headline."
11509 (let ((ov (make-overlay beg end)))
11510 (overlay-put ov 'face 'secondary-selection)
11511 (push ov org-occur-highlights)))
11513 (defun org-remove-occur-highlights (&optional beg end noremove)
11514 "Remove the occur highlights from the buffer.
11515 BEG and END are ignored. If NOREMOVE is nil, remove this function
11516 from the `before-change-functions' in the current buffer."
11517 (interactive)
11518 (unless org-inhibit-highlight-removal
11519 (mapc 'delete-overlay org-occur-highlights)
11520 (setq org-occur-highlights nil)
11521 (setq org-occur-parameters nil)
11522 (unless noremove
11523 (remove-hook 'before-change-functions
11524 'org-remove-occur-highlights 'local))))
11526 ;;;; Priorities
11528 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11529 "Regular expression matching the priority indicator.")
11531 (defvar org-remove-priority-next-time nil)
11533 (defun org-priority-up ()
11534 "Increase the priority of the current item."
11535 (interactive)
11536 (org-priority 'up))
11538 (defun org-priority-down ()
11539 "Decrease the priority of the current item."
11540 (interactive)
11541 (org-priority 'down))
11543 (defun org-priority (&optional action)
11544 "Change the priority of an item by ARG.
11545 ACTION can be `set', `up', `down', or a character."
11546 (interactive)
11547 (unless org-enable-priority-commands
11548 (error "Priority commands are disabled"))
11549 (setq action (or action 'set))
11550 (let (current new news have remove)
11551 (save-excursion
11552 (org-back-to-heading t)
11553 (if (looking-at org-priority-regexp)
11554 (setq current (string-to-char (match-string 2))
11555 have t)
11556 (setq current org-default-priority))
11557 (cond
11558 ((eq action 'remove)
11559 (setq remove t new ?\ ))
11560 ((or (eq action 'set)
11561 (if (featurep 'xemacs) (characterp action) (integerp action)))
11562 (if (not (eq action 'set))
11563 (setq new action)
11564 (message "Priority %c-%c, SPC to remove: "
11565 org-highest-priority org-lowest-priority)
11566 (setq new (read-char-exclusive)))
11567 (if (and (= (upcase org-highest-priority) org-highest-priority)
11568 (= (upcase org-lowest-priority) org-lowest-priority))
11569 (setq new (upcase new)))
11570 (cond ((equal new ?\ ) (setq remove t))
11571 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11572 (error "Priority must be between `%c' and `%c'"
11573 org-highest-priority org-lowest-priority))))
11574 ((eq action 'up)
11575 (if (and (not have) (eq last-command this-command))
11576 (setq new org-lowest-priority)
11577 (setq new (if (and org-priority-start-cycle-with-default (not have))
11578 org-default-priority (1- current)))))
11579 ((eq action 'down)
11580 (if (and (not have) (eq last-command this-command))
11581 (setq new org-highest-priority)
11582 (setq new (if (and org-priority-start-cycle-with-default (not have))
11583 org-default-priority (1+ current)))))
11584 (t (error "Invalid action")))
11585 (if (or (< (upcase new) org-highest-priority)
11586 (> (upcase new) org-lowest-priority))
11587 (setq remove t))
11588 (setq news (format "%c" new))
11589 (if have
11590 (if remove
11591 (replace-match "" t t nil 1)
11592 (replace-match news t t nil 2))
11593 (if remove
11594 (error "No priority cookie found in line")
11595 (let ((case-fold-search nil))
11596 (looking-at org-todo-line-regexp))
11597 (if (match-end 2)
11598 (progn
11599 (goto-char (match-end 2))
11600 (insert " [#" news "]"))
11601 (goto-char (match-beginning 3))
11602 (insert "[#" news "] "))))
11603 (org-preserve-lc (org-set-tags nil 'align)))
11604 (if remove
11605 (message "Priority removed")
11606 (message "Priority of current item set to %s" news))))
11608 (defun org-get-priority (s)
11609 "Find priority cookie and return priority."
11610 (save-match-data
11611 (if (not (string-match org-priority-regexp s))
11612 (* 1000 (- org-lowest-priority org-default-priority))
11613 (* 1000 (- org-lowest-priority
11614 (string-to-char (match-string 2 s)))))))
11616 ;;;; Tags
11618 (defvar org-agenda-archives-mode)
11619 (defvar org-map-continue-from nil
11620 "Position from where mapping should continue.
11621 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11623 (defvar org-scanner-tags nil
11624 "The current tag list while the tags scanner is running.")
11625 (defvar org-trust-scanner-tags nil
11626 "Should `org-get-tags-at' use the tags fro the scanner.
11627 This is for internal dynamical scoping only.
11628 When this is non-nil, the function `org-get-tags-at' will return the value
11629 of `org-scanner-tags' instead of building the list by itself. This
11630 can lead to large speed-ups when the tags scanner is used in a file with
11631 many entries, and when the list of tags is retrieved, for example to
11632 obtain a list of properties. Building the tags list for each entry in such
11633 a file becomes an N^2 operation - but with this variable set, it scales
11634 as N.")
11636 (defun org-scan-tags (action matcher &optional todo-only)
11637 "Scan headline tags with inheritance and produce output ACTION.
11639 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11640 or `agenda' to produce an entry list for an agenda view. It can also be
11641 a Lisp form or a function that should be called at each matched headline, in
11642 this case the return value is a list of all return values from these calls.
11644 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11645 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11646 only lines with a TODO keyword are included in the output."
11647 (require 'org-agenda)
11648 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11649 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11650 (org-re
11651 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11652 (props (list 'face 'default
11653 'done-face 'org-agenda-done
11654 'undone-face 'default
11655 'mouse-face 'highlight
11656 'org-not-done-regexp org-not-done-regexp
11657 'org-todo-regexp org-todo-regexp
11658 'help-echo
11659 (format "mouse-2 or RET jump to org file %s"
11660 (abbreviate-file-name
11661 (or (buffer-file-name (buffer-base-buffer))
11662 (buffer-name (buffer-base-buffer)))))))
11663 (case-fold-search nil)
11664 (org-map-continue-from nil)
11665 lspos tags tags-list
11666 (tags-alist (list (cons 0 org-file-tags)))
11667 (llast 0) rtn rtn1 level category i txt
11668 todo marker entry priority)
11669 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11670 (setq action (list 'lambda nil action)))
11671 (save-excursion
11672 (goto-char (point-min))
11673 (when (eq action 'sparse-tree)
11674 (org-overview)
11675 (org-remove-occur-highlights))
11676 (while (re-search-forward re nil t)
11677 (catch :skip
11678 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11679 tags (if (match-end 4) (org-match-string-no-properties 4)))
11680 (goto-char (setq lspos (match-beginning 0)))
11681 (setq level (org-reduced-level (funcall outline-level))
11682 category (org-get-category))
11683 (setq i llast llast level)
11684 ;; remove tag lists from same and sublevels
11685 (while (>= i level)
11686 (when (setq entry (assoc i tags-alist))
11687 (setq tags-alist (delete entry tags-alist)))
11688 (setq i (1- i)))
11689 ;; add the next tags
11690 (when tags
11691 (setq tags (org-split-string tags ":")
11692 tags-alist
11693 (cons (cons level tags) tags-alist)))
11694 ;; compile tags for current headline
11695 (setq tags-list
11696 (if org-use-tag-inheritance
11697 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11698 tags)
11699 org-scanner-tags tags-list)
11700 (when org-use-tag-inheritance
11701 (setcdr (car tags-alist)
11702 (mapcar (lambda (x)
11703 (setq x (copy-sequence x))
11704 (org-add-prop-inherited x))
11705 (cdar tags-alist))))
11706 (when (and tags org-use-tag-inheritance
11707 (or (not (eq t org-use-tag-inheritance))
11708 org-tags-exclude-from-inheritance))
11709 ;; selective inheritance, remove uninherited ones
11710 (setcdr (car tags-alist)
11711 (org-remove-uniherited-tags (cdar tags-alist))))
11712 (when (and (or (not todo-only)
11713 (and (member todo org-not-done-keywords)
11714 (or (not org-agenda-tags-todo-honor-ignore-options)
11715 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11716 (let ((case-fold-search t)) (eval matcher))
11718 (not (member org-archive-tag tags-list))
11719 ;; we have an archive tag, should we use this anyway?
11720 (or (not org-agenda-skip-archived-trees)
11721 (and (eq action 'agenda) org-agenda-archives-mode))))
11722 (unless (eq action 'sparse-tree) (org-agenda-skip))
11724 ;; select this headline
11726 (cond
11727 ((eq action 'sparse-tree)
11728 (and org-highlight-sparse-tree-matches
11729 (org-get-heading) (match-end 0)
11730 (org-highlight-new-match
11731 (match-beginning 0) (match-beginning 1)))
11732 (org-show-context 'tags-tree))
11733 ((eq action 'agenda)
11734 (setq txt (org-format-agenda-item
11736 (concat
11737 (if (eq org-tags-match-list-sublevels 'indented)
11738 (make-string (1- level) ?.) "")
11739 (org-get-heading))
11740 category
11741 tags-list
11743 priority (org-get-priority txt))
11744 (goto-char lspos)
11745 (setq marker (org-agenda-new-marker))
11746 (org-add-props txt props
11747 'org-marker marker 'org-hd-marker marker 'org-category category
11748 'todo-state todo
11749 'priority priority 'type "tagsmatch")
11750 (push txt rtn))
11751 ((functionp action)
11752 (setq org-map-continue-from nil)
11753 (save-excursion
11754 (setq rtn1 (funcall action))
11755 (push rtn1 rtn)))
11756 (t (error "Invalid action")))
11758 ;; if we are to skip sublevels, jump to end of subtree
11759 (unless org-tags-match-list-sublevels
11760 (org-end-of-subtree t)
11761 (backward-char 1))))
11762 ;; Get the correct position from where to continue
11763 (if org-map-continue-from
11764 (goto-char org-map-continue-from)
11765 (and (= (point) lspos) (end-of-line 1)))))
11766 (when (and (eq action 'sparse-tree)
11767 (not org-sparse-tree-open-archived-trees))
11768 (org-hide-archived-subtrees (point-min) (point-max)))
11769 (nreverse rtn)))
11771 (defun org-remove-uniherited-tags (tags)
11772 "Remove all tags that are not inherited from the list TAGS."
11773 (cond
11774 ((eq org-use-tag-inheritance t)
11775 (if org-tags-exclude-from-inheritance
11776 (org-delete-all org-tags-exclude-from-inheritance tags)
11777 tags))
11778 ((not org-use-tag-inheritance) nil)
11779 ((stringp org-use-tag-inheritance)
11780 (delq nil (mapcar
11781 (lambda (x)
11782 (if (and (string-match org-use-tag-inheritance x)
11783 (not (member x org-tags-exclude-from-inheritance)))
11784 x nil))
11785 tags)))
11786 ((listp org-use-tag-inheritance)
11787 (delq nil (mapcar
11788 (lambda (x)
11789 (if (member x org-use-tag-inheritance) x nil))
11790 tags)))))
11792 (defvar todo-only) ;; dynamically scoped
11794 (defun org-match-sparse-tree (&optional todo-only match)
11795 "Create a sparse tree according to tags string MATCH.
11796 MATCH can contain positive and negative selection of tags, like
11797 \"+WORK+URGENT-WITHBOSS\".
11798 If optional argument TODO-ONLY is non-nil, only select lines that are
11799 also TODO lines."
11800 (interactive "P")
11801 (org-prepare-agenda-buffers (list (current-buffer)))
11802 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11804 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11806 (defvar org-cached-props nil)
11807 (defun org-cached-entry-get (pom property)
11808 (if (or (eq t org-use-property-inheritance)
11809 (and (stringp org-use-property-inheritance)
11810 (string-match org-use-property-inheritance property))
11811 (and (listp org-use-property-inheritance)
11812 (member property org-use-property-inheritance)))
11813 ;; Caching is not possible, check it directly
11814 (org-entry-get pom property 'inherit)
11815 ;; Get all properties, so that we can do complicated checks easily
11816 (cdr (assoc property (or org-cached-props
11817 (setq org-cached-props
11818 (org-entry-properties pom)))))))
11820 (defun org-global-tags-completion-table (&optional files)
11821 "Return the list of all tags in all agenda buffer/files."
11822 (save-excursion
11823 (org-uniquify
11824 (delq nil
11825 (apply 'append
11826 (mapcar
11827 (lambda (file)
11828 (set-buffer (find-file-noselect file))
11829 (append (org-get-buffer-tags)
11830 (mapcar (lambda (x) (if (stringp (car-safe x))
11831 (list (car-safe x)) nil))
11832 org-tag-alist)))
11833 (if (and files (car files))
11834 files
11835 (org-agenda-files))))))))
11837 (defun org-make-tags-matcher (match)
11838 "Create the TAGS//TODO matcher form for the selection string MATCH."
11839 ;; todo-only is scoped dynamically into this function, and the function
11840 ;; may change it if the matcher asks for it.
11841 (unless match
11842 ;; Get a new match request, with completion
11843 (let ((org-last-tags-completion-table
11844 (org-global-tags-completion-table)))
11845 (setq match (org-completing-read-no-i
11846 "Match: " 'org-tags-completion-function nil nil nil
11847 'org-tags-history))))
11849 ;; Parse the string and create a lisp form
11850 (let ((match0 match)
11851 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11852 minus tag mm
11853 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11854 orterms term orlist re-p str-p level-p level-op time-p
11855 prop-p pn pv po cat-p gv rest)
11856 (if (string-match "/+" match)
11857 ;; match contains also a todo-matching request
11858 (progn
11859 (setq tagsmatch (substring match 0 (match-beginning 0))
11860 todomatch (substring match (match-end 0)))
11861 (if (string-match "^!" todomatch)
11862 (setq todo-only t todomatch (substring todomatch 1)))
11863 (if (string-match "^\\s-*$" todomatch)
11864 (setq todomatch nil)))
11865 ;; only matching tags
11866 (setq tagsmatch match todomatch nil))
11868 ;; Make the tags matcher
11869 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11870 (setq tagsmatcher t)
11871 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11872 (while (setq term (pop orterms))
11873 (while (and (equal (substring term -1) "\\") orterms)
11874 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11875 (while (string-match re term)
11876 (setq rest (substring term (match-end 0))
11877 minus (and (match-end 1)
11878 (equal (match-string 1 term) "-"))
11879 tag (match-string 2 term)
11880 re-p (equal (string-to-char tag) ?{)
11881 level-p (match-end 4)
11882 prop-p (match-end 5)
11883 mm (cond
11884 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11885 (level-p
11886 (setq level-op (org-op-to-function (match-string 3 term)))
11887 `(,level-op level ,(string-to-number
11888 (match-string 4 term))))
11889 (prop-p
11890 (setq pn (match-string 5 term)
11891 po (match-string 6 term)
11892 pv (match-string 7 term)
11893 cat-p (equal pn "CATEGORY")
11894 re-p (equal (string-to-char pv) ?{)
11895 str-p (equal (string-to-char pv) ?\")
11896 time-p (save-match-data
11897 (string-match "^\"[[<].*[]>]\"$" pv))
11898 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11899 (if time-p (setq pv (org-matcher-time pv)))
11900 (setq po (org-op-to-function po (if time-p 'time str-p)))
11901 (cond
11902 ((equal pn "CATEGORY")
11903 (setq gv '(get-text-property (point) 'org-category)))
11904 ((equal pn "TODO")
11905 (setq gv 'todo))
11907 (setq gv `(org-cached-entry-get nil ,pn))))
11908 (if re-p
11909 (if (eq po 'org<>)
11910 `(not (string-match ,pv (or ,gv "")))
11911 `(string-match ,pv (or ,gv "")))
11912 (if str-p
11913 `(,po (or ,gv "") ,pv)
11914 `(,po (string-to-number (or ,gv ""))
11915 ,(string-to-number pv) ))))
11916 (t `(member ,tag tags-list)))
11917 mm (if minus (list 'not mm) mm)
11918 term rest)
11919 (push mm tagsmatcher))
11920 (push (if (> (length tagsmatcher) 1)
11921 (cons 'and tagsmatcher)
11922 (car tagsmatcher))
11923 orlist)
11924 (setq tagsmatcher nil))
11925 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11926 (setq tagsmatcher
11927 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11928 ;; Make the todo matcher
11929 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11930 (setq todomatcher t)
11931 (setq orterms (org-split-string todomatch "|") orlist nil)
11932 (while (setq term (pop orterms))
11933 (while (string-match re term)
11934 (setq minus (and (match-end 1)
11935 (equal (match-string 1 term) "-"))
11936 kwd (match-string 2 term)
11937 re-p (equal (string-to-char kwd) ?{)
11938 term (substring term (match-end 0))
11939 mm (if re-p
11940 `(string-match ,(substring kwd 1 -1) todo)
11941 (list 'equal 'todo kwd))
11942 mm (if minus (list 'not mm) mm))
11943 (push mm todomatcher))
11944 (push (if (> (length todomatcher) 1)
11945 (cons 'and todomatcher)
11946 (car todomatcher))
11947 orlist)
11948 (setq todomatcher nil))
11949 (setq todomatcher (if (> (length orlist) 1)
11950 (cons 'or orlist) (car orlist))))
11952 ;; Return the string and lisp forms of the matcher
11953 (setq matcher (if todomatcher
11954 (list 'and tagsmatcher todomatcher)
11955 tagsmatcher))
11956 (cons match0 matcher)))
11958 (defun org-op-to-function (op &optional stringp)
11959 "Turn an operator into the appropriate function."
11960 (setq op
11961 (cond
11962 ((equal op "<" ) '(< string< org-time<))
11963 ((equal op ">" ) '(> org-string> org-time>))
11964 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11965 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11966 ((member op '("=" "==")) '(= string= org-time=))
11967 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11968 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11970 (defun org<> (a b) (not (= a b)))
11971 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11972 (defun org-string>= (a b) (not (string< a b)))
11973 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11974 (defun org-string<> (a b) (not (string= a b)))
11975 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11976 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11977 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11978 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11979 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11980 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11981 (defun org-2ft (s)
11982 "Convert S to a floating point time.
11983 If S is already a number, just return it. If it is a string, parse
11984 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11985 (cond
11986 ((numberp s) s)
11987 ((stringp s)
11988 (condition-case nil
11989 (float-time (apply 'encode-time (org-parse-time-string s)))
11990 (error 0.)))
11991 (t 0.)))
11993 (defun org-time-today ()
11994 "Time in seconds today at 0:00.
11995 Returns the float number of seconds since the beginning of the
11996 epoch to the beginning of today (00:00)."
11997 (float-time (apply 'encode-time
11998 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12000 (defun org-matcher-time (s)
12001 "Interpret a time comparison value."
12002 (save-match-data
12003 (cond
12004 ((string= s "<now>") (float-time))
12005 ((string= s "<today>") (org-time-today))
12006 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12007 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12008 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12009 (+ (org-time-today)
12010 (* (string-to-number (match-string 1 s))
12011 (cdr (assoc (match-string 2 s)
12012 '(("d" . 86400.0) ("w" . 604800.0)
12013 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12014 (t (org-2ft s)))))
12016 (defun org-match-any-p (re list)
12017 "Does re match any element of list?"
12018 (setq list (mapcar (lambda (x) (string-match re x)) list))
12019 (delq nil list))
12021 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12022 (defvar org-tags-overlay (make-overlay 1 1))
12023 (org-detach-overlay org-tags-overlay)
12025 (defun org-get-local-tags-at (&optional pos)
12026 "Get a list of tags defined in the current headline."
12027 (org-get-tags-at pos 'local))
12029 (defun org-get-local-tags ()
12030 "Get a list of tags defined in the current headline."
12031 (org-get-tags-at nil 'local))
12033 (defun org-get-tags-at (&optional pos local)
12034 "Get a list of all headline tags applicable at POS.
12035 POS defaults to point. If tags are inherited, the list contains
12036 the targets in the same sequence as the headlines appear, i.e.
12037 the tags of the current headline come last.
12038 When LOCAL is non-nil, only return tags from the current headline,
12039 ignore inherited ones."
12040 (interactive)
12041 (if (and org-trust-scanner-tags
12042 (or (not pos) (equal pos (point)))
12043 (not local))
12044 org-scanner-tags
12045 (let (tags ltags lastpos parent)
12046 (save-excursion
12047 (save-restriction
12048 (widen)
12049 (goto-char (or pos (point)))
12050 (save-match-data
12051 (catch 'done
12052 (condition-case nil
12053 (progn
12054 (org-back-to-heading t)
12055 (while (not (equal lastpos (point)))
12056 (setq lastpos (point))
12057 (when (looking-at
12058 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
12059 (setq ltags (org-split-string
12060 (org-match-string-no-properties 1) ":"))
12061 (when parent
12062 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12063 (setq tags (append
12064 (if parent
12065 (org-remove-uniherited-tags ltags)
12066 ltags)
12067 tags)))
12068 (or org-use-tag-inheritance (throw 'done t))
12069 (if local (throw 'done t))
12070 (or (org-up-heading-safe) (error nil))
12071 (setq parent t)))
12072 (error nil)))))
12073 (append (org-remove-uniherited-tags org-file-tags) tags)))))
12075 (defun org-add-prop-inherited (s)
12076 (add-text-properties 0 (length s) '(inherited t) s)
12079 (defun org-toggle-tag (tag &optional onoff)
12080 "Toggle the tag TAG for the current line.
12081 If ONOFF is `on' or `off', don't toggle but set to this state."
12082 (let (res current)
12083 (save-excursion
12084 (org-back-to-heading t)
12085 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
12086 (point-at-eol) t)
12087 (progn
12088 (setq current (match-string 1))
12089 (replace-match ""))
12090 (setq current ""))
12091 (setq current (nreverse (org-split-string current ":")))
12092 (cond
12093 ((eq onoff 'on)
12094 (setq res t)
12095 (or (member tag current) (push tag current)))
12096 ((eq onoff 'off)
12097 (or (not (member tag current)) (setq current (delete tag current))))
12098 (t (if (member tag current)
12099 (setq current (delete tag current))
12100 (setq res t)
12101 (push tag current))))
12102 (end-of-line 1)
12103 (if current
12104 (progn
12105 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12106 (org-set-tags nil t))
12107 (delete-horizontal-space))
12108 (run-hooks 'org-after-tags-change-hook))
12109 res))
12111 (defun org-align-tags-here (to-col)
12112 ;; Assumes that this is a headline
12113 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12114 (beginning-of-line 1)
12115 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12116 (< pos (match-beginning 2)))
12117 (progn
12118 (setq tags-l (- (match-end 2) (match-beginning 2)))
12119 (goto-char (match-beginning 1))
12120 (insert " ")
12121 (delete-region (point) (1+ (match-beginning 2)))
12122 (setq ncol (max (1+ (current-column))
12123 (1+ col)
12124 (if (> to-col 0)
12125 to-col
12126 (- (abs to-col) tags-l))))
12127 (setq p (point))
12128 (insert (make-string (- ncol (current-column)) ?\ ))
12129 (setq ncol (current-column))
12130 (when indent-tabs-mode (tabify p (point-at-eol)))
12131 (org-move-to-column (min ncol col) t))
12132 (goto-char pos))))
12134 (defun org-set-tags-command (&optional arg just-align)
12135 "Call the set-tags command for the current entry."
12136 (interactive "P")
12137 (if (org-on-heading-p)
12138 (org-set-tags arg just-align)
12139 (save-excursion
12140 (org-back-to-heading t)
12141 (org-set-tags arg just-align))))
12143 (defun org-set-tags-to (data)
12144 "Set the tags of the current entry to DATA, replacing the current tags.
12145 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12146 If DATA is nil or the empty string, any tags will be removed."
12147 (interactive "sTags: ")
12148 (setq data
12149 (cond
12150 ((eq data nil) "")
12151 ((equal data "") "")
12152 ((stringp data)
12153 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12154 ":"))
12155 ((listp data)
12156 (concat ":" (mapconcat 'identity data ":") ":"))
12157 (t nil)))
12158 (when data
12159 (save-excursion
12160 (org-back-to-heading t)
12161 (when (looking-at org-complex-heading-regexp)
12162 (if (match-end 5)
12163 (progn
12164 (goto-char (match-beginning 5))
12165 (insert data)
12166 (delete-region (point) (point-at-eol))
12167 (org-set-tags nil 'align))
12168 (goto-char (point-at-eol))
12169 (insert " " data)
12170 (org-set-tags nil 'align)))
12171 (beginning-of-line 1)
12172 (if (looking-at ".*?\\([ \t]+\\)$")
12173 (delete-region (match-beginning 1) (match-end 1))))))
12175 (defun org-align-all-tags ()
12176 "Align the tags i all headings."
12177 (interactive)
12178 (save-excursion
12179 (or (ignore-errors (org-back-to-heading t))
12180 (outline-next-heading))
12181 (if (org-on-heading-p)
12182 (org-set-tags t)
12183 (message "No headings"))))
12185 (defun org-set-tags (&optional arg just-align)
12186 "Set the tags for the current headline.
12187 With prefix ARG, realign all tags in headings in the current buffer."
12188 (interactive "P")
12189 (let* ((re (concat "^" outline-regexp))
12190 (current (org-get-tags-string))
12191 (col (current-column))
12192 (org-setting-tags t)
12193 table current-tags inherited-tags ; computed below when needed
12194 tags p0 c0 c1 rpl)
12195 (if arg
12196 (save-excursion
12197 (goto-char (point-min))
12198 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12199 (while (re-search-forward re nil t)
12200 (org-set-tags nil t)
12201 (end-of-line 1)))
12202 (message "All tags realigned to column %d" org-tags-column))
12203 (if just-align
12204 (setq tags current)
12205 ;; Get a new set of tags from the user
12206 (save-excursion
12207 (setq table (append org-tag-persistent-alist
12208 (or org-tag-alist (org-get-buffer-tags))
12209 (and org-complete-tags-always-offer-all-agenda-tags
12210 (org-global-tags-completion-table (org-agenda-files))))
12211 org-last-tags-completion-table table
12212 current-tags (org-split-string current ":")
12213 inherited-tags (nreverse
12214 (nthcdr (length current-tags)
12215 (nreverse (org-get-tags-at))))
12216 tags
12217 (if (or (eq t org-use-fast-tag-selection)
12218 (and org-use-fast-tag-selection
12219 (delq nil (mapcar 'cdr table))))
12220 (org-fast-tag-selection
12221 current-tags inherited-tags table
12222 (if org-fast-tag-selection-include-todo org-todo-key-alist))
12223 (let ((org-add-colon-after-tag-completion t))
12224 (org-trim
12225 (org-without-partial-completion
12226 (org-icompleting-read "Tags: " 'org-tags-completion-function
12227 nil nil current 'org-tags-history)))))))
12228 (while (string-match "[-+&]+" tags)
12229 ;; No boolean logic, just a list
12230 (setq tags (replace-match ":" t t tags))))
12232 (if org-tags-sort-function
12233 (setq tags (mapconcat 'identity
12234 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
12235 org-tags-sort-function) ":")))
12237 (if (string-match "\\`[\t ]*\\'" tags)
12238 (setq tags "")
12239 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12240 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12242 ;; Insert new tags at the correct column
12243 (beginning-of-line 1)
12244 (cond
12245 ((and (equal current "") (equal tags "")))
12246 ((re-search-forward
12247 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12248 (point-at-eol) t)
12249 (if (equal tags "")
12250 (setq rpl "")
12251 (goto-char (match-beginning 0))
12252 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
12253 (1+ (point)) (point))
12254 c1 (max (1+ c0) (if (> org-tags-column 0)
12255 org-tags-column
12256 (- (- org-tags-column) (length tags))))
12257 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12258 (replace-match rpl t t)
12259 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
12260 tags)
12261 (t (error "Tags alignment failed")))
12262 (org-move-to-column col)
12263 (unless just-align
12264 (run-hooks 'org-after-tags-change-hook)))))
12266 (defun org-change-tag-in-region (beg end tag off)
12267 "Add or remove TAG for each entry in the region.
12268 This works in the agenda, and also in an org-mode buffer."
12269 (interactive
12270 (list (region-beginning) (region-end)
12271 (let ((org-last-tags-completion-table
12272 (if (org-mode-p)
12273 (org-get-buffer-tags)
12274 (org-global-tags-completion-table))))
12275 (org-icompleting-read
12276 "Tag: " 'org-tags-completion-function nil nil nil
12277 'org-tags-history))
12278 (progn
12279 (message "[s]et or [r]emove? ")
12280 (equal (read-char-exclusive) ?r))))
12281 (if (fboundp 'deactivate-mark) (deactivate-mark))
12282 (let ((agendap (equal major-mode 'org-agenda-mode))
12283 l1 l2 m buf pos newhead (cnt 0))
12284 (goto-char end)
12285 (setq l2 (1- (org-current-line)))
12286 (goto-char beg)
12287 (setq l1 (org-current-line))
12288 (loop for l from l1 to l2 do
12289 (org-goto-line l)
12290 (setq m (get-text-property (point) 'org-hd-marker))
12291 (when (or (and (org-mode-p) (org-on-heading-p))
12292 (and agendap m))
12293 (setq buf (if agendap (marker-buffer m) (current-buffer))
12294 pos (if agendap m (point)))
12295 (with-current-buffer buf
12296 (save-excursion
12297 (save-restriction
12298 (goto-char pos)
12299 (setq cnt (1+ cnt))
12300 (org-toggle-tag tag (if off 'off 'on))
12301 (setq newhead (org-get-heading)))))
12302 (and agendap (org-agenda-change-all-lines newhead m))))
12303 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12305 (defun org-tags-completion-function (string predicate &optional flag)
12306 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12307 (confirm (lambda (x) (stringp (car x)))))
12308 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12309 (setq s1 (match-string 1 string)
12310 s2 (match-string 2 string))
12311 (setq s1 "" s2 string))
12312 (cond
12313 ((eq flag nil)
12314 ;; try completion
12315 (setq rtn (try-completion s2 ctable confirm))
12316 (if (stringp rtn)
12317 (setq rtn
12318 (concat s1 s2 (substring rtn (length s2))
12319 (if (and org-add-colon-after-tag-completion
12320 (assoc rtn ctable))
12321 ":" ""))))
12322 rtn)
12323 ((eq flag t)
12324 ;; all-completions
12325 (all-completions s2 ctable confirm)
12327 ((eq flag 'lambda)
12328 ;; exact match?
12329 (assoc s2 ctable)))
12332 (defun org-fast-tag-insert (kwd tags face &optional end)
12333 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12334 (insert (format "%-12s" (concat kwd ":"))
12335 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12336 (or end "")))
12338 (defun org-fast-tag-show-exit (flag)
12339 (save-excursion
12340 (org-goto-line 3)
12341 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12342 (replace-match ""))
12343 (when flag
12344 (end-of-line 1)
12345 (org-move-to-column (- (window-width) 19) t)
12346 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12348 (defun org-set-current-tags-overlay (current prefix)
12349 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12350 (if (featurep 'xemacs)
12351 (org-overlay-display org-tags-overlay (concat prefix s)
12352 'secondary-selection)
12353 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12354 (org-overlay-display org-tags-overlay (concat prefix s)))))
12356 (defvar org-last-tag-selection-key nil)
12357 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12358 "Fast tag selection with single keys.
12359 CURRENT is the current list of tags in the headline, INHERITED is the
12360 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12361 possibly with grouping information. TODO-TABLE is a similar table with
12362 TODO keywords, should these have keys assigned to them.
12363 If the keys are nil, a-z are automatically assigned.
12364 Returns the new tags string, or nil to not change the current settings."
12365 (let* ((fulltable (append table todo-table))
12366 (maxlen (apply 'max (mapcar
12367 (lambda (x)
12368 (if (stringp (car x)) (string-width (car x)) 0))
12369 fulltable)))
12370 (buf (current-buffer))
12371 (expert (eq org-fast-tag-selection-single-key 'expert))
12372 (buffer-tags nil)
12373 (fwidth (+ maxlen 3 1 3))
12374 (ncol (/ (- (window-width) 4) fwidth))
12375 (i-face 'org-done)
12376 (c-face 'org-todo)
12377 tg cnt e c char c1 c2 ntable tbl rtn
12378 ov-start ov-end ov-prefix
12379 (exit-after-next org-fast-tag-selection-single-key)
12380 (done-keywords org-done-keywords)
12381 groups ingroup)
12382 (save-excursion
12383 (beginning-of-line 1)
12384 (if (looking-at
12385 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12386 (setq ov-start (match-beginning 1)
12387 ov-end (match-end 1)
12388 ov-prefix "")
12389 (setq ov-start (1- (point-at-eol))
12390 ov-end (1+ ov-start))
12391 (skip-chars-forward "^\n\r")
12392 (setq ov-prefix
12393 (concat
12394 (buffer-substring (1- (point)) (point))
12395 (if (> (current-column) org-tags-column)
12397 (make-string (- org-tags-column (current-column)) ?\ ))))))
12398 (move-overlay org-tags-overlay ov-start ov-end)
12399 (save-window-excursion
12400 (if expert
12401 (set-buffer (get-buffer-create " *Org tags*"))
12402 (delete-other-windows)
12403 (split-window-vertically)
12404 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12405 (erase-buffer)
12406 (org-set-local 'org-done-keywords done-keywords)
12407 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12408 (org-fast-tag-insert "Current" current c-face "\n\n")
12409 (org-fast-tag-show-exit exit-after-next)
12410 (org-set-current-tags-overlay current ov-prefix)
12411 (setq tbl fulltable char ?a cnt 0)
12412 (while (setq e (pop tbl))
12413 (cond
12414 ((equal (car e) :startgroup)
12415 (push '() groups) (setq ingroup t)
12416 (when (not (= cnt 0))
12417 (setq cnt 0)
12418 (insert "\n"))
12419 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12420 ((equal (car e) :endgroup)
12421 (setq ingroup nil cnt 0)
12422 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12423 ((equal e '(:newline))
12424 (when (not (= cnt 0))
12425 (setq cnt 0)
12426 (insert "\n")
12427 (setq e (car tbl))
12428 (while (equal (car tbl) '(:newline))
12429 (insert "\n")
12430 (setq tbl (cdr tbl)))))
12432 (setq tg (copy-sequence (car e)) c2 nil)
12433 (if (cdr e)
12434 (setq c (cdr e))
12435 ;; automatically assign a character.
12436 (setq c1 (string-to-char
12437 (downcase (substring
12438 tg (if (= (string-to-char tg) ?@) 1 0)))))
12439 (if (or (rassoc c1 ntable) (rassoc c1 table))
12440 (while (or (rassoc char ntable) (rassoc char table))
12441 (setq char (1+ char)))
12442 (setq c2 c1))
12443 (setq c (or c2 char)))
12444 (if ingroup (push tg (car groups)))
12445 (setq tg (org-add-props tg nil 'face
12446 (cond
12447 ((not (assoc tg table))
12448 (org-get-todo-face tg))
12449 ((member tg current) c-face)
12450 ((member tg inherited) i-face)
12451 (t nil))))
12452 (if (and (= cnt 0) (not ingroup)) (insert " "))
12453 (insert "[" c "] " tg (make-string
12454 (- fwidth 4 (length tg)) ?\ ))
12455 (push (cons tg c) ntable)
12456 (when (= (setq cnt (1+ cnt)) ncol)
12457 (insert "\n")
12458 (if ingroup (insert " "))
12459 (setq cnt 0)))))
12460 (setq ntable (nreverse ntable))
12461 (insert "\n")
12462 (goto-char (point-min))
12463 (if (not expert) (org-fit-window-to-buffer))
12464 (setq rtn
12465 (catch 'exit
12466 (while t
12467 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12468 (if (not groups) "no " "")
12469 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12470 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12471 (setq org-last-tag-selection-key c)
12472 (cond
12473 ((= c ?\r) (throw 'exit t))
12474 ((= c ?!)
12475 (setq groups (not groups))
12476 (goto-char (point-min))
12477 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12478 ((= c ?\C-c)
12479 (if (not expert)
12480 (org-fast-tag-show-exit
12481 (setq exit-after-next (not exit-after-next)))
12482 (setq expert nil)
12483 (delete-other-windows)
12484 (split-window-vertically)
12485 (org-switch-to-buffer-other-window " *Org tags*")
12486 (org-fit-window-to-buffer)))
12487 ((or (= c ?\C-g)
12488 (and (= c ?q) (not (rassoc c ntable))))
12489 (org-detach-overlay org-tags-overlay)
12490 (setq quit-flag t))
12491 ((= c ?\ )
12492 (setq current nil)
12493 (if exit-after-next (setq exit-after-next 'now)))
12494 ((= c ?\t)
12495 (condition-case nil
12496 (setq tg (org-icompleting-read
12497 "Tag: "
12498 (or buffer-tags
12499 (with-current-buffer buf
12500 (org-get-buffer-tags)))))
12501 (quit (setq tg "")))
12502 (when (string-match "\\S-" tg)
12503 (add-to-list 'buffer-tags (list tg))
12504 (if (member tg current)
12505 (setq current (delete tg current))
12506 (push tg current)))
12507 (if exit-after-next (setq exit-after-next 'now)))
12508 ((setq e (rassoc c todo-table) tg (car e))
12509 (with-current-buffer buf
12510 (save-excursion (org-todo tg)))
12511 (if exit-after-next (setq exit-after-next 'now)))
12512 ((setq e (rassoc c ntable) tg (car e))
12513 (if (member tg current)
12514 (setq current (delete tg current))
12515 (loop for g in groups do
12516 (if (member tg g)
12517 (mapc (lambda (x)
12518 (setq current (delete x current)))
12519 g)))
12520 (push tg current))
12521 (if exit-after-next (setq exit-after-next 'now))))
12523 ;; Create a sorted list
12524 (setq current
12525 (sort current
12526 (lambda (a b)
12527 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12528 (if (eq exit-after-next 'now) (throw 'exit t))
12529 (goto-char (point-min))
12530 (beginning-of-line 2)
12531 (delete-region (point) (point-at-eol))
12532 (org-fast-tag-insert "Current" current c-face)
12533 (org-set-current-tags-overlay current ov-prefix)
12534 (while (re-search-forward
12535 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12536 (setq tg (match-string 1))
12537 (add-text-properties
12538 (match-beginning 1) (match-end 1)
12539 (list 'face
12540 (cond
12541 ((member tg current) c-face)
12542 ((member tg inherited) i-face)
12543 (t (get-text-property (match-beginning 1) 'face))))))
12544 (goto-char (point-min)))))
12545 (org-detach-overlay org-tags-overlay)
12546 (if rtn
12547 (mapconcat 'identity current ":")
12548 nil))))
12550 (defun org-get-tags-string ()
12551 "Get the TAGS string in the current headline."
12552 (unless (org-on-heading-p t)
12553 (error "Not on a heading"))
12554 (save-excursion
12555 (beginning-of-line 1)
12556 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12557 (org-match-string-no-properties 1)
12558 "")))
12560 (defun org-get-tags ()
12561 "Get the list of tags specified in the current headline."
12562 (org-split-string (org-get-tags-string) ":"))
12564 (defun org-get-buffer-tags ()
12565 "Get a table of all tags used in the buffer, for completion."
12566 (let (tags)
12567 (save-excursion
12568 (goto-char (point-min))
12569 (while (re-search-forward
12570 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12571 (when (equal (char-after (point-at-bol 0)) ?*)
12572 (mapc (lambda (x) (add-to-list 'tags x))
12573 (org-split-string (org-match-string-no-properties 1) ":")))))
12574 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12575 (mapcar 'list tags)))
12577 ;;;; The mapping API
12579 ;;;###autoload
12580 (defun org-map-entries (func &optional match scope &rest skip)
12581 "Call FUNC at each headline selected by MATCH in SCOPE.
12583 FUNC is a function or a lisp form. The function will be called without
12584 arguments, with the cursor positioned at the beginning of the headline.
12585 The return values of all calls to the function will be collected and
12586 returned as a list.
12588 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12589 does not need to preserve point. After evaluation, the cursor will be
12590 moved to the end of the line (presumably of the headline of the
12591 processed entry) and search continues from there. Under some
12592 circumstances, this may not produce the wanted results. For example,
12593 if you have removed (e.g. archived) the current (sub)tree it could
12594 mean that the next entry will be skipped entirely. In such cases, you
12595 can specify the position from where search should continue by making
12596 FUNC set the variable `org-map-continue-from' to the desired buffer
12597 position.
12599 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12600 Only headlines that are matched by this query will be considered during
12601 the iteration. When MATCH is nil or t, all headlines will be
12602 visited by the iteration.
12604 SCOPE determines the scope of this command. It can be any of:
12606 nil The current buffer, respecting the restriction if any
12607 tree The subtree started with the entry at point
12608 file The current buffer, without restriction
12609 file-with-archives
12610 The current buffer, and any archives associated with it
12611 agenda All agenda files
12612 agenda-with-archives
12613 All agenda files with any archive files associated with them
12614 \(file1 file2 ...)
12615 If this is a list, all files in the list will be scanned
12617 The remaining args are treated as settings for the skipping facilities of
12618 the scanner. The following items can be given here:
12620 archive skip trees with the archive tag.
12621 comment skip trees with the COMMENT keyword
12622 function or Emacs Lisp form:
12623 will be used as value for `org-agenda-skip-function', so whenever
12624 the function returns t, FUNC will not be called for that
12625 entry and search will continue from the point where the
12626 function leaves it.
12628 If your function needs to retrieve the tags including inherited tags
12629 at the *current* entry, you can use the value of the variable
12630 `org-scanner-tags' which will be much faster than getting the value
12631 with `org-get-tags-at'. If your function gets properties with
12632 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12633 to t around the call to `org-entry-properties' to get the same speedup.
12634 Note that if your function moves around to retrieve tags and properties at
12635 a *different* entry, you cannot use these techniques."
12636 (let* ((org-agenda-archives-mode nil) ; just to make sure
12637 (org-agenda-skip-archived-trees (memq 'archive skip))
12638 (org-agenda-skip-comment-trees (memq 'comment skip))
12639 (org-agenda-skip-function
12640 (car (org-delete-all '(comment archive) skip)))
12641 (org-tags-match-list-sublevels t)
12642 matcher file res
12643 org-todo-keywords-for-agenda
12644 org-done-keywords-for-agenda
12645 org-todo-keyword-alist-for-agenda
12646 org-drawers-for-agenda
12647 org-tag-alist-for-agenda)
12649 (cond
12650 ((eq match t) (setq matcher t))
12651 ((eq match nil) (setq matcher t))
12652 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12654 (save-excursion
12655 (save-restriction
12656 (when (eq scope 'tree)
12657 (org-back-to-heading t)
12658 (org-narrow-to-subtree)
12659 (setq scope nil))
12661 (if (not scope)
12662 (progn
12663 (org-prepare-agenda-buffers
12664 (list (buffer-file-name (current-buffer))))
12665 (setq res (org-scan-tags func matcher)))
12666 ;; Get the right scope
12667 (cond
12668 ((and scope (listp scope) (symbolp (car scope)))
12669 (setq scope (eval scope)))
12670 ((eq scope 'agenda)
12671 (setq scope (org-agenda-files t)))
12672 ((eq scope 'agenda-with-archives)
12673 (setq scope (org-agenda-files t))
12674 (setq scope (org-add-archive-files scope)))
12675 ((eq scope 'file)
12676 (setq scope (list (buffer-file-name))))
12677 ((eq scope 'file-with-archives)
12678 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12679 (org-prepare-agenda-buffers scope)
12680 (while (setq file (pop scope))
12681 (with-current-buffer (org-find-base-buffer-visiting file)
12682 (save-excursion
12683 (save-restriction
12684 (widen)
12685 (goto-char (point-min))
12686 (setq res (append res (org-scan-tags func matcher))))))))))
12687 res))
12689 ;;;; Properties
12691 ;;; Setting and retrieving properties
12693 (defconst org-special-properties
12694 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12695 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
12696 "The special properties valid in Org-mode.
12698 These are properties that are not defined in the property drawer,
12699 but in some other way.")
12701 (defconst org-default-properties
12702 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12703 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12704 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12705 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12706 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
12707 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
12708 "Some properties that are used by Org-mode for various purposes.
12709 Being in this list makes sure that they are offered for completion.")
12711 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12712 "Regular expression matching the first line of a property drawer.")
12714 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12715 "Regular expression matching the last line of a property drawer.")
12717 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12718 "Regular expression matching the first line of a property drawer.")
12720 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12721 "Regular expression matching the first line of a property drawer.")
12723 (defconst org-property-drawer-re
12724 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12725 org-property-end-re "\\)\n?")
12726 "Matches an entire property drawer.")
12728 (defconst org-clock-drawer-re
12729 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12730 org-property-end-re "\\)\n?")
12731 "Matches an entire clock drawer.")
12733 (defun org-property-action ()
12734 "Do an action on properties."
12735 (interactive)
12736 (let (c)
12737 (org-at-property-p)
12738 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12739 (setq c (read-char-exclusive))
12740 (cond
12741 ((equal c ?s)
12742 (call-interactively 'org-set-property))
12743 ((equal c ?d)
12744 (call-interactively 'org-delete-property))
12745 ((equal c ?D)
12746 (call-interactively 'org-delete-property-globally))
12747 ((equal c ?c)
12748 (call-interactively 'org-compute-property-at-point))
12749 (t (error "No such property action %c" c)))))
12751 (defun org-set-effort (&optional value)
12752 "Set the effort property of the current entry.
12753 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12754 allowed value."
12755 (interactive "P")
12756 (if (equal value 0) (setq value 10))
12757 (let* ((completion-ignore-case t)
12758 (prop org-effort-property)
12759 (cur (org-entry-get nil prop))
12760 (allowed (org-property-get-allowed-values nil prop 'table))
12761 (existing (mapcar 'list (org-property-values prop)))
12763 (val (cond
12764 ((stringp value) value)
12765 ((and allowed (integerp value))
12766 (or (car (nth (1- value) allowed))
12767 (car (org-last allowed))))
12768 (allowed
12769 (message "Select 1-9,0, [RET%s]: %s"
12770 (if cur (concat "=" cur) "")
12771 (mapconcat 'car allowed " "))
12772 (setq rpl (read-char-exclusive))
12773 (if (equal rpl ?\r)
12775 (setq rpl (- rpl ?0))
12776 (if (equal rpl 0) (setq rpl 10))
12777 (if (and (> rpl 0) (<= rpl (length allowed)))
12778 (car (nth (1- rpl) allowed))
12779 (org-completing-read "Effort: " allowed nil))))
12781 (let (org-completion-use-ido org-completion-use-iswitchb)
12782 (org-completing-read
12783 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12784 (concat "[" cur "]") "")
12785 ": ")
12786 existing nil nil "" nil cur))))))
12787 (unless (equal (org-entry-get nil prop) val)
12788 (org-entry-put nil prop val))
12789 (message "%s is now %s" prop val)))
12791 (defun org-at-property-p ()
12792 "Is cursor inside a property drawer?"
12793 (save-excursion
12794 (beginning-of-line 1)
12795 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
12796 (let ((match (match-data)) ;; Keep match-data for use by calling
12797 (p (point)) ;; procedures.
12798 (range (unless (org-before-first-heading-p)
12799 (org-get-property-block))))
12800 (prog1 (and range (<= (car range) p) (< p (cdr range)))
12801 (set-match-data match))))))
12803 (defun org-get-property-block (&optional beg end force)
12804 "Return the (beg . end) range of the body of the property drawer.
12805 BEG and END can be beginning and end of subtree, if not given
12806 they will be found.
12807 If the drawer does not exist and FORCE is non-nil, create the drawer."
12808 (catch 'exit
12809 (save-excursion
12810 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12811 (end (or end (progn (outline-next-heading) (point)))))
12812 (goto-char beg)
12813 (if (re-search-forward org-property-start-re end t)
12814 (setq beg (1+ (match-end 0)))
12815 (if force
12816 (save-excursion
12817 (org-insert-property-drawer)
12818 (setq end (progn (outline-next-heading) (point))))
12819 (throw 'exit nil))
12820 (goto-char beg)
12821 (if (re-search-forward org-property-start-re end t)
12822 (setq beg (1+ (match-end 0)))))
12823 (if (re-search-forward org-property-end-re end t)
12824 (setq end (match-beginning 0))
12825 (or force (throw 'exit nil))
12826 (goto-char beg)
12827 (setq end beg)
12828 (org-indent-line-function)
12829 (insert ":END:\n"))
12830 (cons beg end)))))
12832 (defun org-entry-properties (&optional pom which specific)
12833 "Get all properties of the entry at point-or-marker POM.
12834 This includes the TODO keyword, the tags, time strings for deadline,
12835 scheduled, and clocking, and any additional properties defined in the
12836 entry. The return value is an alist, keys may occur multiple times
12837 if the property key was used several times.
12838 POM may also be nil, in which case the current entry is used.
12839 If WHICH is nil or `all', get all properties. If WHICH is
12840 `special' or `standard', only get that subclass. If WHICH
12841 is a string only get exactly this property. Specific can be a string, the
12842 specific property we are interested in. Specifying it can speed
12843 things up because then unnecessary parsing is avoided."
12844 (setq which (or which 'all))
12845 (org-with-point-at pom
12846 (let ((clockstr (substring org-clock-string 0 -1))
12847 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
12848 (case-fold-search nil)
12849 beg end range props sum-props key value string clocksum)
12850 (save-excursion
12851 (when (condition-case nil
12852 (and (org-mode-p) (org-back-to-heading t))
12853 (error nil))
12854 (setq beg (point))
12855 (setq sum-props (get-text-property (point) 'org-summaries))
12856 (setq clocksum (get-text-property (point) :org-clock-minutes))
12857 (outline-next-heading)
12858 (setq end (point))
12859 (when (memq which '(all special))
12860 ;; Get the special properties, like TODO and tags
12861 (goto-char beg)
12862 (when (and (or (not specific) (string= specific "TODO"))
12863 (looking-at org-todo-line-regexp) (match-end 2))
12864 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12865 (when (and (or (not specific) (string= specific "PRIORITY"))
12866 (looking-at org-priority-regexp))
12867 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12868 (when (and (or (not specific) (string= specific "TAGS"))
12869 (setq value (org-get-tags-string))
12870 (string-match "\\S-" value))
12871 (push (cons "TAGS" value) props))
12872 (when (and (or (not specific) (string= specific "ALLTAGS"))
12873 (setq value (org-get-tags-at)))
12874 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
12875 ":"))
12876 props))
12877 (when (or (not specific) (string= specific "BLOCKED"))
12878 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
12879 (when (or (not specific)
12880 (member specific org-all-time-keywords)
12881 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
12882 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12883 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12884 string (if (equal key clockstr)
12885 (org-no-properties
12886 (org-trim
12887 (buffer-substring
12888 (match-beginning 3) (goto-char (point-at-eol)))))
12889 (substring (org-match-string-no-properties 3) 1 -1)))
12890 (unless key
12891 (if (= (char-after (match-beginning 3)) ?\[)
12892 (setq key "TIMESTAMP_IA")
12893 (setq key "TIMESTAMP")))
12894 (when (or (equal key clockstr) (not (assoc key props)))
12895 (push (cons key string) props))))
12899 (when (memq which '(all standard))
12900 ;; Get the standard properties, like :PROP: ...
12901 (setq range (org-get-property-block beg end))
12902 (when range
12903 (goto-char (car range))
12904 (while (re-search-forward
12905 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12906 (cdr range) t)
12907 (setq key (org-match-string-no-properties 1)
12908 value (org-trim (or (org-match-string-no-properties 2) "")))
12909 (unless (member key excluded)
12910 (push (cons key (or value "")) props)))))
12911 (if clocksum
12912 (push (cons "CLOCKSUM"
12913 (org-columns-number-to-string (/ (float clocksum) 60.)
12914 'add_times))
12915 props))
12916 (unless (assoc "CATEGORY" props)
12917 (setq value (or (org-get-category)
12918 (progn (org-refresh-category-properties)
12919 (org-get-category))))
12920 (push (cons "CATEGORY" value) props))
12921 (append sum-props (nreverse props)))))))
12923 (defun org-entry-get (pom property &optional inherit)
12924 "Get value of PROPERTY for entry at point-or-marker POM.
12925 If INHERIT is non-nil and the entry does not have the property,
12926 then also check higher levels of the hierarchy.
12927 If INHERIT is the symbol `selective', use inheritance only if the setting
12928 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12929 If the property is present but empty, the return value is the empty string.
12930 If the property is not present at all, nil is returned."
12931 (org-with-point-at pom
12932 (if (and inherit (if (eq inherit 'selective)
12933 (org-property-inherit-p property)
12935 (org-entry-get-with-inheritance property)
12936 (if (member property org-special-properties)
12937 ;; We need a special property. Use `org-entry-properties' to
12938 ;; retrieve it, but specify the wanted property
12939 (cdr (assoc property (org-entry-properties nil 'special property)))
12940 (let ((range (org-get-property-block)))
12941 (if (and range
12942 (goto-char (car range))
12943 (re-search-forward
12944 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12945 (cdr range) t))
12946 ;; Found the property, return it.
12947 (if (match-end 1)
12948 (org-match-string-no-properties 1)
12949 "")))))))
12951 (defun org-property-or-variable-value (var &optional inherit)
12952 "Check if there is a property fixing the value of VAR.
12953 If yes, return this value. If not, return the current value of the variable."
12954 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12955 (if (and prop (stringp prop) (string-match "\\S-" prop))
12956 (read prop)
12957 (symbol-value var))))
12959 (defun org-entry-delete (pom property)
12960 "Delete the property PROPERTY from entry at point-or-marker POM."
12961 (org-with-point-at pom
12962 (if (member property org-special-properties)
12963 nil ; cannot delete these properties.
12964 (let ((range (org-get-property-block)))
12965 (if (and range
12966 (goto-char (car range))
12967 (re-search-forward
12968 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12969 (cdr range) t))
12970 (progn
12971 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12973 nil)))))
12975 ;; Multi-values properties are properties that contain multiple values
12976 ;; These values are assumed to be single words, separated by whitespace.
12977 (defun org-entry-add-to-multivalued-property (pom property value)
12978 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12979 (let* ((old (org-entry-get pom property))
12980 (values (and old (org-split-string old "[ \t]"))))
12981 (setq value (org-entry-protect-space value))
12982 (unless (member value values)
12983 (setq values (cons value values))
12984 (org-entry-put pom property
12985 (mapconcat 'identity values " ")))))
12987 (defun org-entry-remove-from-multivalued-property (pom property value)
12988 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12989 (let* ((old (org-entry-get pom property))
12990 (values (and old (org-split-string old "[ \t]"))))
12991 (setq value (org-entry-protect-space value))
12992 (when (member value values)
12993 (setq values (delete value values))
12994 (org-entry-put pom property
12995 (mapconcat 'identity values " ")))))
12997 (defun org-entry-member-in-multivalued-property (pom property value)
12998 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12999 (let* ((old (org-entry-get pom property))
13000 (values (and old (org-split-string old "[ \t]"))))
13001 (setq value (org-entry-protect-space value))
13002 (member value values)))
13004 (defun org-entry-get-multivalued-property (pom property)
13005 "Return a list of values in a multivalued property."
13006 (let* ((value (org-entry-get pom property))
13007 (values (and value (org-split-string value "[ \t]"))))
13008 (mapcar 'org-entry-restore-space values)))
13010 (defun org-entry-put-multivalued-property (pom property &rest values)
13011 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13012 VALUES should be a list of strings. Spaces will be protected."
13013 (org-entry-put pom property
13014 (mapconcat 'org-entry-protect-space values " "))
13015 (let* ((value (org-entry-get pom property))
13016 (values (and value (org-split-string value "[ \t]"))))
13017 (mapcar 'org-entry-restore-space values)))
13019 (defun org-entry-protect-space (s)
13020 "Protect spaces and newline in string S."
13021 (while (string-match " " s)
13022 (setq s (replace-match "%20" t t s)))
13023 (while (string-match "\n" s)
13024 (setq s (replace-match "%0A" t t s)))
13027 (defun org-entry-restore-space (s)
13028 "Restore spaces and newline in string S."
13029 (while (string-match "%20" s)
13030 (setq s (replace-match " " t t s)))
13031 (while (string-match "%0A" s)
13032 (setq s (replace-match "\n" t t s)))
13035 (defvar org-entry-property-inherited-from (make-marker)
13036 "Marker pointing to the entry from where a property was inherited.
13037 Each call to `org-entry-get-with-inheritance' will set this marker to the
13038 location of the entry where the inheritance search matched. If there was
13039 no match, the marker will point nowhere.
13040 Note that also `org-entry-get' calls this function, if the INHERIT flag
13041 is set.")
13043 (defun org-entry-get-with-inheritance (property)
13044 "Get entry property, and search higher levels if not present."
13045 (move-marker org-entry-property-inherited-from nil)
13046 (let (tmp)
13047 (save-excursion
13048 (save-restriction
13049 (widen)
13050 (catch 'ex
13051 (while t
13052 (when (setq tmp (org-entry-get nil property))
13053 (org-back-to-heading t)
13054 (move-marker org-entry-property-inherited-from (point))
13055 (throw 'ex tmp))
13056 (or (org-up-heading-safe) (throw 'ex nil)))))
13057 (or tmp
13058 (cdr (assoc property org-file-properties))
13059 (cdr (assoc property org-global-properties))
13060 (cdr (assoc property org-global-properties-fixed))))))
13062 (defvar org-property-changed-functions nil
13063 "Hook called when the value of a property has changed.
13064 Each hook function should accept two arguments, the name of the property
13065 and the new value.")
13067 (defun org-entry-put (pom property value)
13068 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13069 (org-with-point-at pom
13070 (org-back-to-heading t)
13071 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13072 range)
13073 (cond
13074 ((equal property "TODO")
13075 (when (and (stringp value) (string-match "\\S-" value)
13076 (not (member value org-todo-keywords-1)))
13077 (error "\"%s\" is not a valid TODO state" value))
13078 (if (or (not value)
13079 (not (string-match "\\S-" value)))
13080 (setq value 'none))
13081 (org-todo value)
13082 (org-set-tags nil 'align))
13083 ((equal property "PRIORITY")
13084 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13085 (string-to-char value) ?\ ))
13086 (org-set-tags nil 'align))
13087 ((equal property "SCHEDULED")
13088 (if (re-search-forward org-scheduled-time-regexp end t)
13089 (cond
13090 ((eq value 'earlier) (org-timestamp-change -1 'day))
13091 ((eq value 'later) (org-timestamp-change 1 'day))
13092 (t (call-interactively 'org-schedule)))
13093 (call-interactively 'org-schedule)))
13094 ((equal property "DEADLINE")
13095 (if (re-search-forward org-deadline-time-regexp end t)
13096 (cond
13097 ((eq value 'earlier) (org-timestamp-change -1 'day))
13098 ((eq value 'later) (org-timestamp-change 1 'day))
13099 (t (call-interactively 'org-deadline)))
13100 (call-interactively 'org-deadline)))
13101 ((member property org-special-properties)
13102 (error "The %s property can not yet be set with `org-entry-put'"
13103 property))
13104 (t ; a non-special property
13105 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13106 (setq range (org-get-property-block beg end 'force))
13107 (goto-char (car range))
13108 (if (re-search-forward
13109 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13110 (progn
13111 (delete-region (match-beginning 1) (match-end 1))
13112 (goto-char (match-beginning 1)))
13113 (goto-char (cdr range))
13114 (insert "\n")
13115 (backward-char 1)
13116 (org-indent-line-function)
13117 (insert ":" property ":"))
13118 (and value (insert " " value))
13119 (org-indent-line-function)))))
13120 (run-hook-with-args 'org-property-changed-functions property value)))
13122 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13123 "Get all property keys in the current buffer.
13124 With INCLUDE-SPECIALS, also list the special properties that reflect things
13125 like tags and TODO state.
13126 With INCLUDE-DEFAULTS, also include properties that has special meaning
13127 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
13128 With INCLUDE-COLUMNS, also include property names given in COLUMN
13129 formats in the current buffer."
13130 (let (rtn range cfmt s p)
13131 (save-excursion
13132 (save-restriction
13133 (widen)
13134 (goto-char (point-min))
13135 (while (re-search-forward org-property-start-re nil t)
13136 (setq range (org-get-property-block))
13137 (goto-char (car range))
13138 (while (re-search-forward
13139 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13140 (cdr range) t)
13141 (add-to-list 'rtn (org-match-string-no-properties 1)))
13142 (outline-next-heading))))
13144 (when include-specials
13145 (setq rtn (append org-special-properties rtn)))
13147 (when include-defaults
13148 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13149 (add-to-list 'rtn org-effort-property))
13151 (when include-columns
13152 (save-excursion
13153 (save-restriction
13154 (widen)
13155 (goto-char (point-min))
13156 (while (re-search-forward
13157 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13158 nil t)
13159 (setq cfmt (match-string 2) s 0)
13160 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13161 cfmt s)
13162 (setq s (match-end 0)
13163 p (match-string 1 cfmt))
13164 (unless (or (equal p "ITEM")
13165 (member p org-special-properties))
13166 (add-to-list 'rtn (match-string 1 cfmt))))))))
13168 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13170 (defun org-property-values (key)
13171 "Return a list of all values of property KEY."
13172 (save-excursion
13173 (save-restriction
13174 (widen)
13175 (goto-char (point-min))
13176 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
13177 values)
13178 (while (re-search-forward re nil t)
13179 (add-to-list 'values (org-trim (match-string 1))))
13180 (delete "" values)))))
13182 (defun org-insert-property-drawer ()
13183 "Insert a property drawer into the current entry."
13184 (interactive)
13185 (org-back-to-heading t)
13186 (looking-at outline-regexp)
13187 (let ((indent (if org-adapt-indentation
13188 (- (match-end 0)(match-beginning 0))
13190 (beg (point))
13191 (re (concat "^[ \t]*" org-keyword-time-regexp))
13192 end hiddenp)
13193 (outline-next-heading)
13194 (setq end (point))
13195 (goto-char beg)
13196 (while (re-search-forward re end t))
13197 (setq hiddenp (org-invisible-p))
13198 (end-of-line 1)
13199 (and (equal (char-after) ?\n) (forward-char 1))
13200 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
13201 (if (member (match-string 1) '("CLOCK:" ":END:"))
13202 ;; just skip this line
13203 (beginning-of-line 2)
13204 ;; Drawer start, find the end
13205 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
13206 (beginning-of-line 1)))
13207 (org-skip-over-state-notes)
13208 (skip-chars-backward " \t\n\r")
13209 (if (eq (char-before) ?*) (forward-char 1))
13210 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
13211 (beginning-of-line 0)
13212 (org-indent-to-column indent)
13213 (beginning-of-line 2)
13214 (org-indent-to-column indent)
13215 (beginning-of-line 0)
13216 (if hiddenp
13217 (save-excursion
13218 (org-back-to-heading t)
13219 (hide-entry))
13220 (org-flag-drawer t))))
13222 (defun org-set-property (property value)
13223 "In the current entry, set PROPERTY to VALUE.
13224 When called interactively, this will prompt for a property name, offering
13225 completion on existing and default properties. And then it will prompt
13226 for a value, offering completion either on allowed values (via an inherited
13227 xxx_ALL property) or on existing values in other instances of this property
13228 in the current file."
13229 (interactive
13230 (let* ((completion-ignore-case t)
13231 (keys (org-buffer-property-keys nil t t))
13232 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
13233 (prop (if (member prop0 keys)
13234 prop0
13235 (or (cdr (assoc (downcase prop0)
13236 (mapcar (lambda (x) (cons (downcase x) x))
13237 keys)))
13238 prop0)))
13239 (cur (org-entry-get nil prop))
13240 (prompt (concat prop " value"
13241 (if (and cur (string-match "\\S-" cur))
13242 (concat " [" cur "]") "") ": "))
13243 (allowed (org-property-get-allowed-values nil prop 'table))
13244 (existing (mapcar 'list (org-property-values prop)))
13245 (val (if allowed
13246 (org-completing-read prompt allowed nil
13247 (not (get-text-property 0 'org-unrestricted
13248 (caar allowed))))
13249 (let (org-completion-use-ido org-completion-use-iswitchb)
13250 (org-completing-read prompt existing nil nil "" nil cur)))))
13251 (list prop (if (equal val "") cur val))))
13252 (unless (equal (org-entry-get nil property) value)
13253 (org-entry-put nil property value)))
13255 (defun org-delete-property (property)
13256 "In the current entry, delete PROPERTY."
13257 (interactive
13258 (let* ((completion-ignore-case t)
13259 (prop (org-icompleting-read "Property: " (org-entry-properties nil 'standard))))
13260 (list prop)))
13261 (message "Property %s %s" property
13262 (if (org-entry-delete nil property)
13263 "deleted"
13264 "was not present in the entry")))
13266 (defun org-delete-property-globally (property)
13267 "Remove PROPERTY globally, from all entries."
13268 (interactive
13269 (let* ((completion-ignore-case t)
13270 (prop (org-icompleting-read
13271 "Globally remove property: "
13272 (mapcar 'list (org-buffer-property-keys)))))
13273 (list prop)))
13274 (save-excursion
13275 (save-restriction
13276 (widen)
13277 (goto-char (point-min))
13278 (let ((cnt 0))
13279 (while (re-search-forward
13280 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
13281 nil t)
13282 (setq cnt (1+ cnt))
13283 (replace-match ""))
13284 (message "Property \"%s\" removed from %d entries" property cnt)))))
13286 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
13288 (defun org-compute-property-at-point ()
13289 "Compute the property at point.
13290 This looks for an enclosing column format, extracts the operator and
13291 then applies it to the property in the column format's scope."
13292 (interactive)
13293 (unless (org-at-property-p)
13294 (error "Not at a property"))
13295 (let ((prop (org-match-string-no-properties 2)))
13296 (org-columns-get-format-and-top-level)
13297 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
13298 (error "No operator defined for property %s" prop))
13299 (org-columns-compute prop)))
13301 (defvar org-property-allowed-value-functions nil
13302 "Hook for functions supplying allowed values for a specific property.
13303 The functions must take a single argument, the name of the property, and
13304 return a flat list of allowed values. If \":ETC\" is one of
13305 the values, this means that these values are intended as defaults for
13306 completion, but that other values should be allowed too.
13307 The functions must return nil if they are not responsible for this
13308 property.")
13310 (defun org-property-get-allowed-values (pom property &optional table)
13311 "Get allowed values for the property PROPERTY.
13312 When TABLE is non-nil, return an alist that can directly be used for
13313 completion."
13314 (let (vals)
13315 (cond
13316 ((equal property "TODO")
13317 (setq vals (org-with-point-at pom
13318 (append org-todo-keywords-1 '("")))))
13319 ((equal property "PRIORITY")
13320 (let ((n org-lowest-priority))
13321 (while (>= n org-highest-priority)
13322 (push (char-to-string n) vals)
13323 (setq n (1- n)))))
13324 ((member property org-special-properties))
13325 ((setq vals (run-hook-with-args-until-success
13326 'org-property-allowed-value-functions property)))
13328 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13329 (when (and vals (string-match "\\S-" vals))
13330 (setq vals (car (read-from-string (concat "(" vals ")"))))
13331 (setq vals (mapcar (lambda (x)
13332 (cond ((stringp x) x)
13333 ((numberp x) (number-to-string x))
13334 ((symbolp x) (symbol-name x))
13335 (t "???")))
13336 vals)))))
13337 (when (member ":ETC" vals)
13338 (setq vals (remove ":ETC" vals))
13339 (org-add-props (car vals) '(org-unrestricted t)))
13340 (if table (mapcar 'list vals) vals)))
13342 (defun org-property-previous-allowed-value (&optional previous)
13343 "Switch to the next allowed value for this property."
13344 (interactive)
13345 (org-property-next-allowed-value t))
13347 (defun org-property-next-allowed-value (&optional previous)
13348 "Switch to the next allowed value for this property."
13349 (interactive)
13350 (unless (org-at-property-p)
13351 (error "Not at a property"))
13352 (let* ((key (match-string 2))
13353 (value (match-string 3))
13354 (allowed (or (org-property-get-allowed-values (point) key)
13355 (and (member value '("[ ]" "[-]" "[X]"))
13356 '("[ ]" "[X]"))))
13357 nval)
13358 (unless allowed
13359 (error "Allowed values for this property have not been defined"))
13360 (if previous (setq allowed (reverse allowed)))
13361 (if (member value allowed)
13362 (setq nval (car (cdr (member value allowed)))))
13363 (setq nval (or nval (car allowed)))
13364 (if (equal nval value)
13365 (error "Only one allowed value for this property"))
13366 (org-at-property-p)
13367 (replace-match (concat " :" key ": " nval) t t)
13368 (org-indent-line-function)
13369 (beginning-of-line 1)
13370 (skip-chars-forward " \t")
13371 (run-hook-with-args 'org-property-changed-functions key nval)))
13373 (defun org-find-entry-with-id (ident)
13374 "Locate the entry that contains the ID property with exact value IDENT.
13375 IDENT can be a string, a symbol or a number, this function will search for
13376 the string representation of it.
13377 Return the position where this entry starts, or nil if there is no such entry."
13378 (interactive "sID: ")
13379 (let ((id (cond
13380 ((stringp ident) ident)
13381 ((symbol-name ident) (symbol-name ident))
13382 ((numberp ident) (number-to-string ident))
13383 (t (error "IDENT %s must be a string, symbol or number" ident))))
13384 (case-fold-search nil))
13385 (save-excursion
13386 (save-restriction
13387 (widen)
13388 (goto-char (point-min))
13389 (when (re-search-forward
13390 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13391 nil t)
13392 (org-back-to-heading t)
13393 (point))))))
13395 ;;;; Timestamps
13397 (defvar org-last-changed-timestamp nil)
13398 (defvar org-last-inserted-timestamp nil
13399 "The last time stamp inserted with `org-insert-time-stamp'.")
13400 (defvar org-time-was-given) ; dynamically scoped parameter
13401 (defvar org-end-time-was-given) ; dynamically scoped parameter
13402 (defvar org-ts-what) ; dynamically scoped parameter
13404 (defun org-time-stamp (arg &optional inactive)
13405 "Prompt for a date/time and insert a time stamp.
13406 If the user specifies a time like HH:MM, or if this command is called
13407 with a prefix argument, the time stamp will contain date and time.
13408 Otherwise, only the date will be included. All parts of a date not
13409 specified by the user will be filled in from the current date/time.
13410 So if you press just return without typing anything, the time stamp
13411 will represent the current date/time. If there is already a timestamp
13412 at the cursor, it will be modified."
13413 (interactive "P")
13414 (let* ((ts nil)
13415 (default-time
13416 ;; Default time is either today, or, when entering a range,
13417 ;; the range start.
13418 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13419 (save-excursion
13420 (re-search-backward
13421 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13422 (- (point) 20) t)))
13423 (apply 'encode-time (org-parse-time-string (match-string 1)))
13424 (current-time)))
13425 (default-input (and ts (org-get-compact-tod ts)))
13426 org-time-was-given org-end-time-was-given time)
13427 (cond
13428 ((and (org-at-timestamp-p t)
13429 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13430 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13431 (insert "--")
13432 (setq time (let ((this-command this-command))
13433 (org-read-date arg 'totime nil nil
13434 default-time default-input)))
13435 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13436 ((org-at-timestamp-p t)
13437 (setq time (let ((this-command this-command))
13438 (org-read-date arg 'totime nil nil default-time default-input)))
13439 (when (org-at-timestamp-p t) ; just to get the match data
13440 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13441 (replace-match "")
13442 (setq org-last-changed-timestamp
13443 (org-insert-time-stamp
13444 time (or org-time-was-given arg)
13445 inactive nil nil (list org-end-time-was-given))))
13446 (message "Timestamp updated"))
13448 (setq time (let ((this-command this-command))
13449 (org-read-date arg 'totime nil nil default-time default-input)))
13450 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13451 nil nil (list org-end-time-was-given))))))
13453 ;; FIXME: can we use this for something else, like computing time differences?
13454 (defun org-get-compact-tod (s)
13455 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13456 (let* ((t1 (match-string 1 s))
13457 (h1 (string-to-number (match-string 2 s)))
13458 (m1 (string-to-number (match-string 3 s)))
13459 (t2 (and (match-end 4) (match-string 5 s)))
13460 (h2 (and t2 (string-to-number (match-string 6 s))))
13461 (m2 (and t2 (string-to-number (match-string 7 s))))
13462 dh dm)
13463 (if (not t2)
13465 (setq dh (- h2 h1) dm (- m2 m1))
13466 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13467 (concat t1 "+" (number-to-string dh)
13468 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13470 (defun org-time-stamp-inactive (&optional arg)
13471 "Insert an inactive time stamp.
13472 An inactive time stamp is enclosed in square brackets instead of angle
13473 brackets. It is inactive in the sense that it does not trigger agenda entries,
13474 does not link to the calendar and cannot be changed with the S-cursor keys.
13475 So these are more for recording a certain time/date."
13476 (interactive "P")
13477 (org-time-stamp arg 'inactive))
13479 (defvar org-date-ovl (make-overlay 1 1))
13480 (overlay-put org-date-ovl 'face 'org-warning)
13481 (org-detach-overlay org-date-ovl)
13483 (defvar org-ans1) ; dynamically scoped parameter
13484 (defvar org-ans2) ; dynamically scoped parameter
13486 (defvar org-plain-time-of-day-regexp) ; defined below
13488 (defvar org-overriding-default-time nil) ; dynamically scoped
13489 (defvar org-read-date-overlay nil)
13490 (defvar org-dcst nil) ; dynamically scoped
13491 (defvar org-read-date-history nil)
13492 (defvar org-read-date-final-answer nil)
13494 (defun org-read-date (&optional with-time to-time from-string prompt
13495 default-time default-input)
13496 "Read a date, possibly a time, and make things smooth for the user.
13497 The prompt will suggest to enter an ISO date, but you can also enter anything
13498 which will at least partially be understood by `parse-time-string'.
13499 Unrecognized parts of the date will default to the current day, month, year,
13500 hour and minute. If this command is called to replace a timestamp at point,
13501 of to enter the second timestamp of a range, the default time is taken from the
13502 existing stamp. For example,
13503 3-2-5 --> 2003-02-05
13504 feb 15 --> currentyear-02-15
13505 sep 12 9 --> 2009-09-12
13506 12:45 --> today 12:45
13507 22 sept 0:34 --> currentyear-09-22 0:34
13508 12 --> currentyear-currentmonth-12
13509 Fri --> nearest Friday (today or later)
13510 etc.
13512 Furthermore you can specify a relative date by giving, as the *first* thing
13513 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13514 change in days weeks, months, years.
13515 With a single plus or minus, the date is relative to today. With a double
13516 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13517 +4d --> four days from today
13518 +4 --> same as above
13519 +2w --> two weeks from today
13520 ++5 --> five days from default date
13522 The function understands only English month and weekday abbreviations,
13523 but this can be configured with the variables `parse-time-months' and
13524 `parse-time-weekdays'.
13526 While prompting, a calendar is popped up - you can also select the
13527 date with the mouse (button 1). The calendar shows a period of three
13528 months. To scroll it to other months, use the keys `>' and `<'.
13529 If you don't like the calendar, turn it off with
13530 \(setq org-read-date-popup-calendar nil)
13532 With optional argument TO-TIME, the date will immediately be converted
13533 to an internal time.
13534 With an optional argument WITH-TIME, the prompt will suggest to also
13535 insert a time. Note that when WITH-TIME is not set, you can still
13536 enter a time, and this function will inform the calling routine about
13537 this change. The calling routine may then choose to change the format
13538 used to insert the time stamp into the buffer to include the time.
13539 With optional argument FROM-STRING, read from this string instead from
13540 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13541 the time/date that is used for everything that is not specified by the
13542 user."
13543 (require 'parse-time)
13544 (let* ((org-time-stamp-rounding-minutes
13545 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13546 (org-dcst org-display-custom-times)
13547 (ct (org-current-time))
13548 (def (or org-overriding-default-time default-time ct))
13549 (defdecode (decode-time def))
13550 (dummy (progn
13551 (when (< (nth 2 defdecode) org-extend-today-until)
13552 (setcar (nthcdr 2 defdecode) -1)
13553 (setcar (nthcdr 1 defdecode) 59)
13554 (setq def (apply 'encode-time defdecode)
13555 defdecode (decode-time def)))))
13556 (calendar-frame-setup nil)
13557 (calendar-move-hook nil)
13558 (calendar-view-diary-initially-flag nil)
13559 (view-diary-entries-initially nil)
13560 (calendar-view-holidays-initially-flag nil)
13561 (view-calendar-holidays-initially nil)
13562 (timestr (format-time-string
13563 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
13564 (prompt (concat (if prompt (concat prompt " ") "")
13565 (format "Date+time [%s]: " timestr)))
13566 ans (org-ans0 "") org-ans1 org-ans2 final)
13568 (cond
13569 (from-string (setq ans from-string))
13570 (org-read-date-popup-calendar
13571 (save-excursion
13572 (save-window-excursion
13573 (calendar)
13574 (calendar-forward-day (- (time-to-days def)
13575 (calendar-absolute-from-gregorian
13576 (calendar-current-date))))
13577 (org-eval-in-calendar nil t)
13578 (let* ((old-map (current-local-map))
13579 (map (copy-keymap calendar-mode-map))
13580 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13581 (org-defkey map (kbd "RET") 'org-calendar-select)
13582 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
13583 'org-calendar-select-mouse)
13584 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
13585 'org-calendar-select-mouse)
13586 (org-defkey minibuffer-local-map [(meta shift left)]
13587 (lambda () (interactive)
13588 (org-eval-in-calendar '(calendar-backward-month 1))))
13589 (org-defkey minibuffer-local-map [(meta shift right)]
13590 (lambda () (interactive)
13591 (org-eval-in-calendar '(calendar-forward-month 1))))
13592 (org-defkey minibuffer-local-map [(meta shift up)]
13593 (lambda () (interactive)
13594 (org-eval-in-calendar '(calendar-backward-year 1))))
13595 (org-defkey minibuffer-local-map [(meta shift down)]
13596 (lambda () (interactive)
13597 (org-eval-in-calendar '(calendar-forward-year 1))))
13598 (org-defkey minibuffer-local-map [?\e (shift left)]
13599 (lambda () (interactive)
13600 (org-eval-in-calendar '(calendar-backward-month 1))))
13601 (org-defkey minibuffer-local-map [?\e (shift right)]
13602 (lambda () (interactive)
13603 (org-eval-in-calendar '(calendar-forward-month 1))))
13604 (org-defkey minibuffer-local-map [?\e (shift up)]
13605 (lambda () (interactive)
13606 (org-eval-in-calendar '(calendar-backward-year 1))))
13607 (org-defkey minibuffer-local-map [?\e (shift down)]
13608 (lambda () (interactive)
13609 (org-eval-in-calendar '(calendar-forward-year 1))))
13610 (org-defkey minibuffer-local-map [(shift up)]
13611 (lambda () (interactive)
13612 (org-eval-in-calendar '(calendar-backward-week 1))))
13613 (org-defkey minibuffer-local-map [(shift down)]
13614 (lambda () (interactive)
13615 (org-eval-in-calendar '(calendar-forward-week 1))))
13616 (org-defkey minibuffer-local-map [(shift left)]
13617 (lambda () (interactive)
13618 (org-eval-in-calendar '(calendar-backward-day 1))))
13619 (org-defkey minibuffer-local-map [(shift right)]
13620 (lambda () (interactive)
13621 (org-eval-in-calendar '(calendar-forward-day 1))))
13622 (org-defkey minibuffer-local-map ">"
13623 (lambda () (interactive)
13624 (org-eval-in-calendar '(scroll-calendar-left 1))))
13625 (org-defkey minibuffer-local-map "<"
13626 (lambda () (interactive)
13627 (org-eval-in-calendar '(scroll-calendar-right 1))))
13628 (run-hooks 'org-read-date-minibuffer-setup-hook)
13629 (unwind-protect
13630 (progn
13631 (use-local-map map)
13632 (add-hook 'post-command-hook 'org-read-date-display)
13633 (setq org-ans0 (read-string prompt default-input
13634 'org-read-date-history nil))
13635 ;; org-ans0: from prompt
13636 ;; org-ans1: from mouse click
13637 ;; org-ans2: from calendar motion
13638 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13639 (remove-hook 'post-command-hook 'org-read-date-display)
13640 (use-local-map old-map)
13641 (when org-read-date-overlay
13642 (delete-overlay org-read-date-overlay)
13643 (setq org-read-date-overlay nil)))))))
13645 (t ; Naked prompt only
13646 (unwind-protect
13647 (setq ans (read-string prompt default-input
13648 'org-read-date-history timestr))
13649 (when org-read-date-overlay
13650 (delete-overlay org-read-date-overlay)
13651 (setq org-read-date-overlay nil)))))
13653 (setq final (org-read-date-analyze ans def defdecode))
13654 (setq org-read-date-final-answer ans)
13656 (if to-time
13657 (apply 'encode-time final)
13658 (if (and (boundp 'org-time-was-given) org-time-was-given)
13659 (format "%04d-%02d-%02d %02d:%02d"
13660 (nth 5 final) (nth 4 final) (nth 3 final)
13661 (nth 2 final) (nth 1 final))
13662 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13664 (defvar def)
13665 (defvar defdecode)
13666 (defvar with-time)
13667 (defvar org-read-date-analyze-futurep nil)
13668 (defun org-read-date-display ()
13669 "Display the current date prompt interpretation in the minibuffer."
13670 (when org-read-date-display-live
13671 (when org-read-date-overlay
13672 (delete-overlay org-read-date-overlay))
13673 (let ((p (point)))
13674 (end-of-line 1)
13675 (while (not (equal (buffer-substring
13676 (max (point-min) (- (point) 4)) (point))
13677 " "))
13678 (insert " "))
13679 (goto-char p))
13680 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13681 " " (or org-ans1 org-ans2)))
13682 (org-end-time-was-given nil)
13683 (f (org-read-date-analyze ans def defdecode))
13684 (fmts (if org-dcst
13685 org-time-stamp-custom-formats
13686 org-time-stamp-formats))
13687 (fmt (if (or with-time
13688 (and (boundp 'org-time-was-given) org-time-was-given))
13689 (cdr fmts)
13690 (car fmts)))
13691 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13692 (when (and org-end-time-was-given
13693 (string-match org-plain-time-of-day-regexp txt))
13694 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13695 org-end-time-was-given
13696 (substring txt (match-end 0)))))
13697 (when org-read-date-analyze-futurep
13698 (setq txt (concat txt " (=>F)")))
13699 (setq org-read-date-overlay
13700 (make-overlay (1- (point-at-eol)) (point-at-eol)))
13701 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13703 (defun org-read-date-analyze (ans def defdecode)
13704 "Analyse the combined answer of the date prompt."
13705 ;; FIXME: cleanup and comment
13706 (let ((nowdecode (decode-time (current-time)))
13707 delta deltan deltaw deltadef year month day
13708 hour minute second wday pm h2 m2 tl wday1
13709 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
13710 (setq org-read-date-analyze-futurep nil)
13711 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13712 (setq ans "+0"))
13714 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13715 (setq ans (replace-match "" t t ans)
13716 deltan (car delta)
13717 deltaw (nth 1 delta)
13718 deltadef (nth 2 delta)))
13720 ;; Check if there is an iso week date in there
13721 ;; If yes, store the info and postpone interpreting it until the rest
13722 ;; of the parsing is done
13723 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13724 (setq iso-year (if (match-end 1)
13725 (org-small-year-to-year
13726 (string-to-number (match-string 1 ans))))
13727 iso-weekday (if (match-end 3)
13728 (string-to-number (match-string 3 ans)))
13729 iso-week (string-to-number (match-string 2 ans)))
13730 (setq ans (replace-match "" t t ans)))
13732 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
13733 (when (string-match
13734 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13735 (setq year (if (match-end 2)
13736 (string-to-number (match-string 2 ans))
13737 (progn (setq kill-year t)
13738 (string-to-number (format-time-string "%Y"))))
13739 month (string-to-number (match-string 3 ans))
13740 day (string-to-number (match-string 4 ans)))
13741 (if (< year 100) (setq year (+ 2000 year)))
13742 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13743 t nil ans)))
13744 ;; Help matching american dates, like 5/30 or 5/30/7
13745 (when (string-match
13746 "^ *\\([0-3]?[0-9]\\)/\\([0-1]?[0-9]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
13747 (setq year (if (match-end 4)
13748 (string-to-number (match-string 4 ans))
13749 (progn (setq kill-year t)
13750 (string-to-number (format-time-string "%Y"))))
13751 month (string-to-number (match-string 1 ans))
13752 day (string-to-number (match-string 2 ans)))
13753 (if (< year 100) (setq year (+ 2000 year)))
13754 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13755 t nil ans)))
13756 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13757 ;; If there is a time with am/pm, and *no* time without it, we convert
13758 ;; so that matching will be successful.
13759 (loop for i from 1 to 2 do ; twice, for end time as well
13760 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13761 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13762 (setq hour (string-to-number (match-string 1 ans))
13763 minute (if (match-end 3)
13764 (string-to-number (match-string 3 ans))
13766 pm (equal ?p
13767 (string-to-char (downcase (match-string 4 ans)))))
13768 (if (and (= hour 12) (not pm))
13769 (setq hour 0)
13770 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13771 (setq ans (replace-match (format "%02d:%02d" hour minute)
13772 t t ans))))
13774 ;; Check if a time range is given as a duration
13775 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13776 (setq hour (string-to-number (match-string 1 ans))
13777 h2 (+ hour (string-to-number (match-string 3 ans)))
13778 minute (string-to-number (match-string 2 ans))
13779 m2 (+ minute (if (match-end 5) (string-to-number
13780 (match-string 5 ans))0)))
13781 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13782 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13783 t t ans)))
13785 ;; Check if there is a time range
13786 (when (boundp 'org-end-time-was-given)
13787 (setq org-time-was-given nil)
13788 (when (and (string-match org-plain-time-of-day-regexp ans)
13789 (match-end 8))
13790 (setq org-end-time-was-given (match-string 8 ans))
13791 (setq ans (concat (substring ans 0 (match-beginning 7))
13792 (substring ans (match-end 7))))))
13794 (setq tl (parse-time-string ans)
13795 day (or (nth 3 tl) (nth 3 defdecode))
13796 month (or (nth 4 tl)
13797 (if (and org-read-date-prefer-future
13798 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
13799 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
13800 (nth 4 defdecode)))
13801 year (or (and (not kill-year) (nth 5 tl))
13802 (if (and org-read-date-prefer-future
13803 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
13804 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
13805 (nth 5 defdecode)))
13806 hour (or (nth 2 tl) (nth 2 defdecode))
13807 minute (or (nth 1 tl) (nth 1 defdecode))
13808 second (or (nth 0 tl) 0)
13809 wday (nth 6 tl))
13811 (when (and (eq org-read-date-prefer-future 'time)
13812 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13813 (equal day (nth 3 nowdecode))
13814 (equal month (nth 4 nowdecode))
13815 (equal year (nth 5 nowdecode))
13816 (nth 2 tl)
13817 (or (< (nth 2 tl) (nth 2 nowdecode))
13818 (and (= (nth 2 tl) (nth 2 nowdecode))
13819 (nth 1 tl)
13820 (< (nth 1 tl) (nth 1 nowdecode)))))
13821 (setq day (1+ day)
13822 futurep t))
13824 ;; Special date definitions below
13825 (cond
13826 (iso-week
13827 ;; There was an iso week
13828 (require 'cal-iso)
13829 (setq futurep nil)
13830 (setq year (or iso-year year)
13831 day (or iso-weekday wday 1)
13832 wday nil ; to make sure that the trigger below does not match
13833 iso-date (calendar-gregorian-from-absolute
13834 (calendar-absolute-from-iso
13835 (list iso-week day year))))
13836 ; FIXME: Should we also push ISO weeks into the future?
13837 ; (when (and org-read-date-prefer-future
13838 ; (not iso-year)
13839 ; (< (calendar-absolute-from-gregorian iso-date)
13840 ; (time-to-days (current-time))))
13841 ; (setq year (1+ year)
13842 ; iso-date (calendar-gregorian-from-absolute
13843 ; (calendar-absolute-from-iso
13844 ; (list iso-week day year)))))
13845 (setq month (car iso-date)
13846 year (nth 2 iso-date)
13847 day (nth 1 iso-date)))
13848 (deltan
13849 (setq futurep nil)
13850 (unless deltadef
13851 (let ((now (decode-time (current-time))))
13852 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13853 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13854 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13855 ((equal deltaw "m") (setq month (+ month deltan)))
13856 ((equal deltaw "y") (setq year (+ year deltan)))))
13857 ((and wday (not (nth 3 tl)))
13858 (setq futurep nil)
13859 ;; Weekday was given, but no day, so pick that day in the week
13860 ;; on or after the derived date.
13861 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13862 (unless (equal wday wday1)
13863 (setq day (+ day (% (- wday wday1 -7) 7))))))
13864 (if (and (boundp 'org-time-was-given)
13865 (nth 2 tl))
13866 (setq org-time-was-given t))
13867 (if (< year 100) (setq year (+ 2000 year)))
13868 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13869 (setq org-read-date-analyze-futurep futurep)
13870 (list second minute hour day month year)))
13872 (defvar parse-time-weekdays)
13874 (defun org-read-date-get-relative (s today default)
13875 "Check string S for special relative date string.
13876 TODAY and DEFAULT are internal times, for today and for a default.
13877 Return shift list (N what def-flag)
13878 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13879 N is the number of WHATs to shift.
13880 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13881 the DEFAULT date rather than TODAY."
13882 (when (and
13883 (string-match
13884 (concat
13885 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13886 "\\([0-9]+\\)?"
13887 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13888 "\\([ \t]\\|$\\)") s)
13889 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13890 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13891 (string-to-char (substring (match-string 1 s) -1))
13892 ?+))
13893 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13894 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13895 (what (if (match-end 3) (match-string 3 s) "d"))
13896 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13897 (date (if rel default today))
13898 (wday (nth 6 (decode-time date)))
13899 delta)
13900 (if wday1
13901 (progn
13902 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13903 (if (= dir ?-) (setq delta (- delta 7)))
13904 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13905 (list delta "d" rel))
13906 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13908 (defun org-order-calendar-date-args (arg1 arg2 arg3)
13909 "Turn a user-specified date into the internal representation.
13910 The internal representation needed by the calendar is (month day year).
13911 This is a wrapper to handle the brain-dead convention in calendar that
13912 user function argument order change dependent on argument order."
13913 (if (boundp 'calendar-date-style)
13914 (cond
13915 ((eq calendar-date-style 'american)
13916 (list arg1 arg2 arg3))
13917 ((eq calendar-date-style 'european)
13918 (list arg2 arg1 arg3))
13919 ((eq calendar-date-style 'iso)
13920 (list arg2 arg3 arg1)))
13921 (if (org-bound-and-true-p european-calendar-style)
13922 (list arg2 arg1 arg3)
13923 (list arg1 arg2 arg3))))
13925 (defun org-eval-in-calendar (form &optional keepdate)
13926 "Eval FORM in the calendar window and return to current window.
13927 Also, store the cursor date in variable org-ans2."
13928 (let ((sf (selected-frame))
13929 (sw (selected-window)))
13930 (select-window (get-buffer-window "*Calendar*" t))
13931 (eval form)
13932 (when (and (not keepdate) (calendar-cursor-to-date))
13933 (let* ((date (calendar-cursor-to-date))
13934 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13935 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13936 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13937 (select-window sw)
13938 (org-select-frame-set-input-focus sf)))
13940 (defun org-calendar-select ()
13941 "Return to `org-read-date' with the date currently selected.
13942 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13943 (interactive)
13944 (when (calendar-cursor-to-date)
13945 (let* ((date (calendar-cursor-to-date))
13946 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13947 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13948 (if (active-minibuffer-window) (exit-minibuffer))))
13950 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13951 "Insert a date stamp for the date given by the internal TIME.
13952 WITH-HM means use the stamp format that includes the time of the day.
13953 INACTIVE means use square brackets instead of angular ones, so that the
13954 stamp will not contribute to the agenda.
13955 PRE and POST are optional strings to be inserted before and after the
13956 stamp.
13957 The command returns the inserted time stamp."
13958 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13959 stamp)
13960 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13961 (insert-before-markers (or pre ""))
13962 (insert-before-markers (setq stamp (format-time-string fmt time)))
13963 (when (listp extra)
13964 (setq extra (car extra))
13965 (if (and (stringp extra)
13966 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13967 (setq extra (format "-%02d:%02d"
13968 (string-to-number (match-string 1 extra))
13969 (string-to-number (match-string 2 extra))))
13970 (setq extra nil)))
13971 (when extra
13972 (backward-char 1)
13973 (insert-before-markers extra)
13974 (forward-char 1))
13975 (insert-before-markers (or post ""))
13976 (setq org-last-inserted-timestamp stamp)))
13978 (defun org-toggle-time-stamp-overlays ()
13979 "Toggle the use of custom time stamp formats."
13980 (interactive)
13981 (setq org-display-custom-times (not org-display-custom-times))
13982 (unless org-display-custom-times
13983 (let ((p (point-min)) (bmp (buffer-modified-p)))
13984 (while (setq p (next-single-property-change p 'display))
13985 (if (and (get-text-property p 'display)
13986 (eq (get-text-property p 'face) 'org-date))
13987 (remove-text-properties
13988 p (setq p (next-single-property-change p 'display))
13989 '(display t))))
13990 (set-buffer-modified-p bmp)))
13991 (if (featurep 'xemacs)
13992 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13993 (org-restart-font-lock)
13994 (setq org-table-may-need-update t)
13995 (if org-display-custom-times
13996 (message "Time stamps are overlayed with custom format")
13997 (message "Time stamp overlays removed")))
13999 (defun org-display-custom-time (beg end)
14000 "Overlay modified time stamp format over timestamp between BEG and END."
14001 (let* ((ts (buffer-substring beg end))
14002 t1 w1 with-hm tf time str w2 (off 0))
14003 (save-match-data
14004 (setq t1 (org-parse-time-string ts t))
14005 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
14006 (setq off (- (match-end 0) (match-beginning 0)))))
14007 (setq end (- end off))
14008 (setq w1 (- end beg)
14009 with-hm (and (nth 1 t1) (nth 2 t1))
14010 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
14011 time (org-fix-decoded-time t1)
14012 str (org-add-props
14013 (format-time-string
14014 (substring tf 1 -1) (apply 'encode-time time))
14015 nil 'mouse-face 'highlight)
14016 w2 (length str))
14017 (if (not (= w2 w1))
14018 (add-text-properties (1+ beg) (+ 2 beg)
14019 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
14020 (if (featurep 'xemacs)
14021 (progn
14022 (put-text-property beg end 'invisible t)
14023 (put-text-property beg end 'end-glyph (make-glyph str)))
14024 (put-text-property beg end 'display str))))
14026 (defun org-translate-time (string)
14027 "Translate all timestamps in STRING to custom format.
14028 But do this only if the variable `org-display-custom-times' is set."
14029 (when org-display-custom-times
14030 (save-match-data
14031 (let* ((start 0)
14032 (re org-ts-regexp-both)
14033 t1 with-hm inactive tf time str beg end)
14034 (while (setq start (string-match re string start))
14035 (setq beg (match-beginning 0)
14036 end (match-end 0)
14037 t1 (save-match-data
14038 (org-parse-time-string (substring string beg end) t))
14039 with-hm (and (nth 1 t1) (nth 2 t1))
14040 inactive (equal (substring string beg (1+ beg)) "[")
14041 tf (funcall (if with-hm 'cdr 'car)
14042 org-time-stamp-custom-formats)
14043 time (org-fix-decoded-time t1)
14044 str (format-time-string
14045 (concat
14046 (if inactive "[" "<") (substring tf 1 -1)
14047 (if inactive "]" ">"))
14048 (apply 'encode-time time))
14049 string (replace-match str t t string)
14050 start (+ start (length str)))))))
14051 string)
14053 (defun org-fix-decoded-time (time)
14054 "Set 0 instead of nil for the first 6 elements of time.
14055 Don't touch the rest."
14056 (let ((n 0))
14057 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
14059 (defun org-days-to-time (timestamp-string)
14060 "Difference between TIMESTAMP-STRING and now in days."
14061 (- (time-to-days (org-time-string-to-time timestamp-string))
14062 (time-to-days (current-time))))
14064 (defun org-deadline-close (timestamp-string &optional ndays)
14065 "Is the time in TIMESTAMP-STRING close to the current date?"
14066 (setq ndays (or ndays (org-get-wdays timestamp-string)))
14067 (and (< (org-days-to-time timestamp-string) ndays)
14068 (not (org-entry-is-done-p))))
14070 (defun org-get-wdays (ts)
14071 "Get the deadline lead time appropriate for timestring TS."
14072 (cond
14073 ((<= org-deadline-warning-days 0)
14074 ;; 0 or negative, enforce this value no matter what
14075 (- org-deadline-warning-days))
14076 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
14077 ;; lead time is specified.
14078 (floor (* (string-to-number (match-string 1 ts))
14079 (cdr (assoc (match-string 2 ts)
14080 '(("d" . 1) ("w" . 7)
14081 ("m" . 30.4) ("y" . 365.25)))))))
14082 ;; go for the default.
14083 (t org-deadline-warning-days)))
14085 (defun org-calendar-select-mouse (ev)
14086 "Return to `org-read-date' with the date currently selected.
14087 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14088 (interactive "e")
14089 (mouse-set-point ev)
14090 (when (calendar-cursor-to-date)
14091 (let* ((date (calendar-cursor-to-date))
14092 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14093 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14094 (if (active-minibuffer-window) (exit-minibuffer))))
14096 (defun org-check-deadlines (ndays)
14097 "Check if there are any deadlines due or past due.
14098 A deadline is considered due if it happens within `org-deadline-warning-days'
14099 days from today's date. If the deadline appears in an entry marked DONE,
14100 it is not shown. The prefix arg NDAYS can be used to test that many
14101 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
14102 (interactive "P")
14103 (let* ((org-warn-days
14104 (cond
14105 ((equal ndays '(4)) 100000)
14106 (ndays (prefix-numeric-value ndays))
14107 (t (abs org-deadline-warning-days))))
14108 (case-fold-search nil)
14109 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
14110 (callback
14111 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
14113 (message "%d deadlines past-due or due within %d days"
14114 (org-occur regexp nil callback)
14115 org-warn-days)))
14117 (defun org-check-before-date (date)
14118 "Check if there are deadlines or scheduled entries before DATE."
14119 (interactive (list (org-read-date)))
14120 (let ((case-fold-search nil)
14121 (regexp (concat "\\<\\(" org-deadline-string
14122 "\\|" org-scheduled-string
14123 "\\) *<\\([^>]+\\)>"))
14124 (callback
14125 (lambda () (time-less-p
14126 (org-time-string-to-time (match-string 2))
14127 (org-time-string-to-time date)))))
14128 (message "%d entries before %s"
14129 (org-occur regexp nil callback) date)))
14131 (defun org-check-after-date (date)
14132 "Check if there are deadlines or scheduled entries after DATE."
14133 (interactive (list (org-read-date)))
14134 (let ((case-fold-search nil)
14135 (regexp (concat "\\<\\(" org-deadline-string
14136 "\\|" org-scheduled-string
14137 "\\) *<\\([^>]+\\)>"))
14138 (callback
14139 (lambda () (not
14140 (time-less-p
14141 (org-time-string-to-time (match-string 2))
14142 (org-time-string-to-time date))))))
14143 (message "%d entries after %s"
14144 (org-occur regexp nil callback) date)))
14146 (defun org-evaluate-time-range (&optional to-buffer)
14147 "Evaluate a time range by computing the difference between start and end.
14148 Normally the result is just printed in the echo area, but with prefix arg
14149 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
14150 If the time range is actually in a table, the result is inserted into the
14151 next column.
14152 For time difference computation, a year is assumed to be exactly 365
14153 days in order to avoid rounding problems."
14154 (interactive "P")
14156 (org-clock-update-time-maybe)
14157 (save-excursion
14158 (unless (org-at-date-range-p t)
14159 (goto-char (point-at-bol))
14160 (re-search-forward org-tr-regexp-both (point-at-eol) t))
14161 (if (not (org-at-date-range-p t))
14162 (error "Not at a time-stamp range, and none found in current line")))
14163 (let* ((ts1 (match-string 1))
14164 (ts2 (match-string 2))
14165 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
14166 (match-end (match-end 0))
14167 (time1 (org-time-string-to-time ts1))
14168 (time2 (org-time-string-to-time ts2))
14169 (t1 (org-float-time time1))
14170 (t2 (org-float-time time2))
14171 (diff (abs (- t2 t1)))
14172 (negative (< (- t2 t1) 0))
14173 ;; (ys (floor (* 365 24 60 60)))
14174 (ds (* 24 60 60))
14175 (hs (* 60 60))
14176 (fy "%dy %dd %02d:%02d")
14177 (fy1 "%dy %dd")
14178 (fd "%dd %02d:%02d")
14179 (fd1 "%dd")
14180 (fh "%02d:%02d")
14181 y d h m align)
14182 (if havetime
14183 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14185 d (floor (/ diff ds)) diff (mod diff ds)
14186 h (floor (/ diff hs)) diff (mod diff hs)
14187 m (floor (/ diff 60)))
14188 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14190 d (floor (+ (/ diff ds) 0.5))
14191 h 0 m 0))
14192 (if (not to-buffer)
14193 (message "%s" (org-make-tdiff-string y d h m))
14194 (if (org-at-table-p)
14195 (progn
14196 (goto-char match-end)
14197 (setq align t)
14198 (and (looking-at " *|") (goto-char (match-end 0))))
14199 (goto-char match-end))
14200 (if (looking-at
14201 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
14202 (replace-match ""))
14203 (if negative (insert " -"))
14204 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
14205 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
14206 (insert " " (format fh h m))))
14207 (if align (org-table-align))
14208 (message "Time difference inserted")))))
14210 (defun org-make-tdiff-string (y d h m)
14211 (let ((fmt "")
14212 (l nil))
14213 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
14214 l (push y l)))
14215 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
14216 l (push d l)))
14217 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
14218 l (push h l)))
14219 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
14220 l (push m l)))
14221 (apply 'format fmt (nreverse l))))
14223 (defun org-time-string-to-time (s)
14224 (apply 'encode-time (org-parse-time-string s)))
14225 (defun org-time-string-to-seconds (s)
14226 (org-float-time (org-time-string-to-time s)))
14228 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
14229 "Convert a time stamp to an absolute day number.
14230 If there is a specifyer for a cyclic time stamp, get the closest date to
14231 DAYNR.
14232 PREFER and SHOW-ALL are passed through to `org-closest-date'.
14233 the variable date is bound by the calendar when this is called."
14234 (cond
14235 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
14236 (if (org-diary-sexp-entry (match-string 1 s) "" date)
14237 daynr
14238 (+ daynr 1000)))
14239 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
14240 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
14241 (time-to-days (current-time))) (match-string 0 s)
14242 prefer show-all))
14243 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
14245 (defun org-days-to-iso-week (days)
14246 "Return the iso week number."
14247 (require 'cal-iso)
14248 (car (calendar-iso-from-absolute days)))
14250 (defun org-small-year-to-year (year)
14251 "Convert 2-digit years into 4-digit years.
14252 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
14253 The year 2000 cannot be abbreviated. Any year larger than 99
14254 is returned unchanged."
14255 (if (< year 38)
14256 (setq year (+ 2000 year))
14257 (if (< year 100)
14258 (setq year (+ 1900 year))))
14259 year)
14261 (defun org-time-from-absolute (d)
14262 "Return the time corresponding to date D.
14263 D may be an absolute day number, or a calendar-type list (month day year)."
14264 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
14265 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
14267 (defun org-calendar-holiday ()
14268 "List of holidays, for Diary display in Org-mode."
14269 (require 'holidays)
14270 (let ((hl (funcall
14271 (if (fboundp 'calendar-check-holidays)
14272 'calendar-check-holidays 'check-calendar-holidays) date)))
14273 (if hl (mapconcat 'identity hl "; "))))
14275 (defun org-diary-sexp-entry (sexp entry date)
14276 "Process a SEXP diary ENTRY for DATE."
14277 (require 'diary-lib)
14278 (let ((result (if calendar-debug-sexp
14279 (let ((stack-trace-on-error t))
14280 (eval (car (read-from-string sexp))))
14281 (condition-case nil
14282 (eval (car (read-from-string sexp)))
14283 (error
14284 (beep)
14285 (message "Bad sexp at line %d in %s: %s"
14286 (org-current-line)
14287 (buffer-file-name) sexp)
14288 (sleep-for 2))))))
14289 (cond ((stringp result) result)
14290 ((and (consp result)
14291 (stringp (cdr result))) (cdr result))
14292 (result entry)
14293 (t nil))))
14295 (defun org-diary-to-ical-string (frombuf)
14296 "Get iCalendar entries from diary entries in buffer FROMBUF.
14297 This uses the icalendar.el library."
14298 (let* ((tmpdir (if (featurep 'xemacs)
14299 (temp-directory)
14300 temporary-file-directory))
14301 (tmpfile (make-temp-name
14302 (expand-file-name "orgics" tmpdir)))
14303 buf rtn b e)
14304 (with-current-buffer frombuf
14305 (icalendar-export-region (point-min) (point-max) tmpfile)
14306 (setq buf (find-buffer-visiting tmpfile))
14307 (set-buffer buf)
14308 (goto-char (point-min))
14309 (if (re-search-forward "^BEGIN:VEVENT" nil t)
14310 (setq b (match-beginning 0)))
14311 (goto-char (point-max))
14312 (if (re-search-backward "^END:VEVENT" nil t)
14313 (setq e (match-end 0)))
14314 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
14315 (kill-buffer buf)
14316 (delete-file tmpfile)
14317 rtn))
14319 (defun org-closest-date (start current change prefer show-all)
14320 "Find the date closest to CURRENT that is consistent with START and CHANGE.
14321 When PREFER is `past' return a date that is either CURRENT or past.
14322 When PREFER is `future', return a date that is either CURRENT or future.
14323 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
14324 ;; Make the proper lists from the dates
14325 (catch 'exit
14326 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
14327 dn dw sday cday n1 n2 n0
14328 d m y y1 y2 date1 date2 nmonths nm ny m2)
14330 (setq start (org-date-to-gregorian start)
14331 current (org-date-to-gregorian
14332 (if show-all
14333 current
14334 (time-to-days (current-time))))
14335 sday (calendar-absolute-from-gregorian start)
14336 cday (calendar-absolute-from-gregorian current))
14338 (if (<= cday sday) (throw 'exit sday))
14340 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
14341 (setq dn (string-to-number (match-string 1 change))
14342 dw (cdr (assoc (match-string 2 change) a1)))
14343 (error "Invalid change specifyer: %s" change))
14344 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
14345 (cond
14346 ((eq dw 'day)
14347 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
14348 n2 (+ n1 dn)))
14349 ((eq dw 'year)
14350 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
14351 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
14352 (setq date1 (list m d y1)
14353 n1 (calendar-absolute-from-gregorian date1)
14354 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
14355 n2 (calendar-absolute-from-gregorian date2)))
14356 ((eq dw 'month)
14357 ;; approx number of month between the two dates
14358 (setq nmonths (floor (/ (- cday sday) 30.436875)))
14359 ;; How often does dn fit in there?
14360 (setq d (nth 1 start) m (car start) y (nth 2 start)
14361 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
14362 m (+ m nm)
14363 ny (floor (/ m 12))
14364 y (+ y ny)
14365 m (- m (* ny 12)))
14366 (while (> m 12) (setq m (- m 12) y (1+ y)))
14367 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14368 (setq m2 (+ m dn) y2 y)
14369 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14370 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14371 (while (<= n2 cday)
14372 (setq n1 n2 m m2 y y2)
14373 (setq m2 (+ m dn) y2 y)
14374 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14375 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14376 ;; Make sure n1 is the earlier date
14377 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14378 (if show-all
14379 (cond
14380 ((eq prefer 'past) (if (= cday n2) n2 n1))
14381 ((eq prefer 'future) (if (= cday n1) n1 n2))
14382 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14383 (cond
14384 ((eq prefer 'past) (if (= cday n2) n2 n1))
14385 ((eq prefer 'future) (if (= cday n1) n1 n2))
14386 (t (if (= cday n1) n1 n2)))))))
14388 (defun org-date-to-gregorian (date)
14389 "Turn any specification of DATE into a gregorian date for the calendar."
14390 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14391 ((and (listp date) (= (length date) 3)) date)
14392 ((stringp date)
14393 (setq date (org-parse-time-string date))
14394 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14395 ((listp date)
14396 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14398 (defun org-parse-time-string (s &optional nodefault)
14399 "Parse the standard Org-mode time string.
14400 This should be a lot faster than the normal `parse-time-string'.
14401 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14402 hour and minute fields will be nil if not given."
14403 (if (string-match org-ts-regexp0 s)
14404 (list 0
14405 (if (or (match-beginning 8) (not nodefault))
14406 (string-to-number (or (match-string 8 s) "0")))
14407 (if (or (match-beginning 7) (not nodefault))
14408 (string-to-number (or (match-string 7 s) "0")))
14409 (string-to-number (match-string 4 s))
14410 (string-to-number (match-string 3 s))
14411 (string-to-number (match-string 2 s))
14412 nil nil nil)
14413 (error "Not a standard Org-mode time string: %s" s)))
14415 (defun org-timestamp-up (&optional arg)
14416 "Increase the date item at the cursor by one.
14417 If the cursor is on the year, change the year. If it is on the month or
14418 the day, change that.
14419 With prefix ARG, change by that many units."
14420 (interactive "p")
14421 (org-timestamp-change (prefix-numeric-value arg)))
14423 (defun org-timestamp-down (&optional arg)
14424 "Decrease the date item at the cursor by one.
14425 If the cursor is on the year, change the year. If it is on the month or
14426 the day, change that.
14427 With prefix ARG, change by that many units."
14428 (interactive "p")
14429 (org-timestamp-change (- (prefix-numeric-value arg))))
14431 (defun org-timestamp-up-day (&optional arg)
14432 "Increase the date in the time stamp by one day.
14433 With prefix ARG, change that many days."
14434 (interactive "p")
14435 (if (and (not (org-at-timestamp-p t))
14436 (org-on-heading-p))
14437 (org-todo 'up)
14438 (org-timestamp-change (prefix-numeric-value arg) 'day)))
14440 (defun org-timestamp-down-day (&optional arg)
14441 "Decrease the date in the time stamp by one day.
14442 With prefix ARG, change that many days."
14443 (interactive "p")
14444 (if (and (not (org-at-timestamp-p t))
14445 (org-on-heading-p))
14446 (org-todo 'down)
14447 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
14449 (defun org-at-timestamp-p (&optional inactive-ok)
14450 "Determine if the cursor is in or at a timestamp."
14451 (interactive)
14452 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
14453 (pos (point))
14454 (ans (or (looking-at tsr)
14455 (save-excursion
14456 (skip-chars-backward "^[<\n\r\t")
14457 (if (> (point) (point-min)) (backward-char 1))
14458 (and (looking-at tsr)
14459 (> (- (match-end 0) pos) -1))))))
14460 (and ans
14461 (boundp 'org-ts-what)
14462 (setq org-ts-what
14463 (cond
14464 ((= pos (match-beginning 0)) 'bracket)
14465 ((= pos (1- (match-end 0))) 'bracket)
14466 ((org-pos-in-match-range pos 2) 'year)
14467 ((org-pos-in-match-range pos 3) 'month)
14468 ((org-pos-in-match-range pos 7) 'hour)
14469 ((org-pos-in-match-range pos 8) 'minute)
14470 ((or (org-pos-in-match-range pos 4)
14471 (org-pos-in-match-range pos 5)) 'day)
14472 ((and (> pos (or (match-end 8) (match-end 5)))
14473 (< pos (match-end 0)))
14474 (- pos (or (match-end 8) (match-end 5))))
14475 (t 'day))))
14476 ans))
14478 (defun org-toggle-timestamp-type ()
14479 "Toggle the type (<active> or [inactive]) of a time stamp."
14480 (interactive)
14481 (when (org-at-timestamp-p t)
14482 (let ((beg (match-beginning 0)) (end (match-end 0))
14483 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14484 (save-excursion
14485 (goto-char beg)
14486 (while (re-search-forward "[][<>]" end t)
14487 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14488 t t)))
14489 (message "Timestamp is now %sactive"
14490 (if (equal (char-after beg) ?<) "" "in")))))
14492 (defun org-timestamp-change (n &optional what)
14493 "Change the date in the time stamp at point.
14494 The date will be changed by N times WHAT. WHAT can be `day', `month',
14495 `year', `minute', `second'. If WHAT is not given, the cursor position
14496 in the timestamp determines what will be changed."
14497 (let ((pos (point))
14498 with-hm inactive
14499 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14500 org-ts-what
14501 extra rem
14502 ts time time0)
14503 (if (not (org-at-timestamp-p t))
14504 (error "Not at a timestamp"))
14505 (if (and (not what) (eq org-ts-what 'bracket))
14506 (org-toggle-timestamp-type)
14507 (if (and (not what) (not (eq org-ts-what 'day))
14508 org-display-custom-times
14509 (get-text-property (point) 'display)
14510 (not (get-text-property (1- (point)) 'display)))
14511 (setq org-ts-what 'day))
14512 (setq org-ts-what (or what org-ts-what)
14513 inactive (= (char-after (match-beginning 0)) ?\[)
14514 ts (match-string 0))
14515 (replace-match "")
14516 (if (string-match
14517 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14519 (setq extra (match-string 1 ts)))
14520 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14521 (setq with-hm t))
14522 (setq time0 (org-parse-time-string ts))
14523 (when (and (eq org-ts-what 'minute)
14524 (eq current-prefix-arg nil))
14525 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14526 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14527 (setcar (cdr time0) (+ (nth 1 time0)
14528 (if (> n 0) (- rem) (- dm rem))))))
14529 (setq time
14530 (encode-time (or (car time0) 0)
14531 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14532 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14533 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14534 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14535 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14536 (nthcdr 6 time0)))
14537 (when (and (member org-ts-what '(hour minute))
14538 extra
14539 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14540 (setq extra (org-modify-ts-extra
14541 extra
14542 (if (eq org-ts-what 'hour) 2 5)
14543 n dm)))
14544 (when (integerp org-ts-what)
14545 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14546 (if (eq what 'calendar)
14547 (let ((cal-date (org-get-date-from-calendar)))
14548 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14549 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14550 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14551 (setcar time0 (or (car time0) 0))
14552 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
14553 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
14554 (setq time (apply 'encode-time time0))))
14555 (setq org-last-changed-timestamp
14556 (org-insert-time-stamp time with-hm inactive nil nil extra))
14557 (org-clock-update-time-maybe)
14558 (goto-char pos)
14559 ;; Try to recenter the calendar window, if any
14560 (if (and org-calendar-follow-timestamp-change
14561 (get-buffer-window "*Calendar*" t)
14562 (memq org-ts-what '(day month year)))
14563 (org-recenter-calendar (time-to-days time))))))
14565 (defun org-modify-ts-extra (s pos n dm)
14566 "Change the different parts of the lead-time and repeat fields in timestamp."
14567 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
14568 ng h m new rem)
14569 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
14570 (cond
14571 ((or (org-pos-in-match-range pos 2)
14572 (org-pos-in-match-range pos 3))
14573 (setq m (string-to-number (match-string 3 s))
14574 h (string-to-number (match-string 2 s)))
14575 (if (org-pos-in-match-range pos 2)
14576 (setq h (+ h n))
14577 (setq n (* dm (org-no-warnings (signum n))))
14578 (when (not (= 0 (setq rem (% m dm))))
14579 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
14580 (setq m (+ m n)))
14581 (if (< m 0) (setq m (+ m 60) h (1- h)))
14582 (if (> m 59) (setq m (- m 60) h (1+ h)))
14583 (setq h (min 24 (max 0 h)))
14584 (setq ng 1 new (format "-%02d:%02d" h m)))
14585 ((org-pos-in-match-range pos 6)
14586 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
14587 ((org-pos-in-match-range pos 5)
14588 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
14590 ((org-pos-in-match-range pos 9)
14591 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
14592 ((org-pos-in-match-range pos 8)
14593 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
14595 (when ng
14596 (setq s (concat
14597 (substring s 0 (match-beginning ng))
14599 (substring s (match-end ng))))))
14602 (defun org-recenter-calendar (date)
14603 "If the calendar is visible, recenter it to DATE."
14604 (let* ((win (selected-window))
14605 (cwin (get-buffer-window "*Calendar*" t))
14606 (calendar-move-hook nil))
14607 (when cwin
14608 (select-window cwin)
14609 (calendar-goto-date (if (listp date) date
14610 (calendar-gregorian-from-absolute date)))
14611 (select-window win))))
14613 (defun org-goto-calendar (&optional arg)
14614 "Go to the Emacs calendar at the current date.
14615 If there is a time stamp in the current line, go to that date.
14616 A prefix ARG can be used to force the current date."
14617 (interactive "P")
14618 (let ((tsr org-ts-regexp) diff
14619 (calendar-move-hook nil)
14620 (calendar-view-holidays-initially-flag nil)
14621 (view-calendar-holidays-initially nil)
14622 (calendar-view-diary-initially-flag nil)
14623 (view-diary-entries-initially nil))
14624 (if (or (org-at-timestamp-p)
14625 (save-excursion
14626 (beginning-of-line 1)
14627 (looking-at (concat ".*" tsr))))
14628 (let ((d1 (time-to-days (current-time)))
14629 (d2 (time-to-days
14630 (org-time-string-to-time (match-string 1)))))
14631 (setq diff (- d2 d1))))
14632 (calendar)
14633 (calendar-goto-today)
14634 (if (and diff (not arg)) (calendar-forward-day diff))))
14636 (defun org-get-date-from-calendar ()
14637 "Return a list (month day year) of date at point in calendar."
14638 (with-current-buffer "*Calendar*"
14639 (save-match-data
14640 (calendar-cursor-to-date))))
14642 (defun org-date-from-calendar ()
14643 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14644 If there is already a time stamp at the cursor position, update it."
14645 (interactive)
14646 (if (org-at-timestamp-p t)
14647 (org-timestamp-change 0 'calendar)
14648 (let ((cal-date (org-get-date-from-calendar)))
14649 (org-insert-time-stamp
14650 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14652 (defun org-minutes-to-hh:mm-string (m)
14653 "Compute H:MM from a number of minutes."
14654 (let ((h (/ m 60)))
14655 (setq m (- m (* 60 h)))
14656 (format org-time-clocksum-format h m)))
14658 (defun org-hh:mm-string-to-minutes (s)
14659 "Convert a string H:MM to a number of minutes.
14660 If the string is just a number, interpret it as minutes.
14661 In fact, the first hh:mm or number in the string will be taken,
14662 there can be extra stuff in the string.
14663 If no number is found, the return value is 0."
14664 (cond
14665 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14666 (+ (* (string-to-number (match-string 1 s)) 60)
14667 (string-to-number (match-string 2 s))))
14668 ((string-match "\\([0-9]+\\)" s)
14669 (string-to-number (match-string 1 s)))
14670 (t 0)))
14672 ;;;; Files
14674 (defun org-save-all-org-buffers ()
14675 "Save all Org-mode buffers without user confirmation."
14676 (interactive)
14677 (message "Saving all Org-mode buffers...")
14678 (save-some-buffers t 'org-mode-p)
14679 (when (featurep 'org-id) (org-id-locations-save))
14680 (message "Saving all Org-mode buffers... done"))
14682 (defun org-revert-all-org-buffers ()
14683 "Revert all Org-mode buffers.
14684 Prompt for confirmation when there are unsaved changes.
14685 Be sure you know what you are doing before letting this function
14686 overwrite your changes.
14688 This function is useful in a setup where one tracks org files
14689 with a version control system, to revert on one machine after pulling
14690 changes from another. I believe the procedure must be like this:
14692 1. M-x org-save-all-org-buffers
14693 2. Pull changes from the other machine, resolve conflicts
14694 3. M-x org-revert-all-org-buffers"
14695 (interactive)
14696 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14697 (error "Abort"))
14698 (save-excursion
14699 (save-window-excursion
14700 (mapc
14701 (lambda (b)
14702 (when (and (with-current-buffer b (org-mode-p))
14703 (with-current-buffer b buffer-file-name))
14704 (switch-to-buffer b)
14705 (revert-buffer t 'no-confirm)))
14706 (buffer-list))
14707 (when (and (featurep 'org-id) org-id-track-globally)
14708 (org-id-locations-load)))))
14710 ;;;; Agenda files
14712 ;;;###autoload
14713 (defun org-iswitchb (&optional arg)
14714 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14715 With a prefix argument, restrict available to files.
14716 With two prefix arguments, restrict available buffers to agenda files."
14717 (interactive "P")
14718 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14719 ((equal arg '(16)) (org-buffer-list 'agenda))
14720 (t (org-buffer-list)))))
14721 (switch-to-buffer
14722 (org-icompleting-read "Org buffer: "
14723 (mapcar 'list (mapcar 'buffer-name blist))
14724 nil t))))
14726 ;;;###autoload
14727 (defalias 'org-ido-switchb 'org-iswitchb)
14729 (defun org-buffer-list (&optional predicate exclude-tmp)
14730 "Return a list of Org buffers.
14731 PREDICATE can be `export', `files' or `agenda'.
14733 export restrict the list to Export buffers.
14734 files restrict the list to buffers visiting Org files.
14735 agenda restrict the list to buffers visiting agenda files.
14737 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14738 (let* ((bfn nil)
14739 (agenda-files (and (eq predicate 'agenda)
14740 (mapcar 'file-truename (org-agenda-files t))))
14741 (filter
14742 (cond
14743 ((eq predicate 'files)
14744 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14745 ((eq predicate 'export)
14746 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14747 ((eq predicate 'agenda)
14748 (lambda (b)
14749 (with-current-buffer b
14750 (and (eq major-mode 'org-mode)
14751 (setq bfn (buffer-file-name b))
14752 (member (file-truename bfn) agenda-files)))))
14753 (t (lambda (b) (with-current-buffer b
14754 (or (eq major-mode 'org-mode)
14755 (string-match "\*Org .*Export"
14756 (buffer-name b)))))))))
14757 (delq nil
14758 (mapcar
14759 (lambda(b)
14760 (if (and (funcall filter b)
14761 (or (not exclude-tmp)
14762 (not (string-match "tmp" (buffer-name b)))))
14764 nil))
14765 (buffer-list)))))
14767 (defun org-agenda-files (&optional unrestricted archives)
14768 "Get the list of agenda files.
14769 Optional UNRESTRICTED means return the full list even if a restriction
14770 is currently in place.
14771 When ARCHIVES is t, include all archive files that are really being
14772 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14773 `org-agenda-archives-mode' is t."
14774 (let ((files
14775 (cond
14776 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14777 ((stringp org-agenda-files) (org-read-agenda-file-list))
14778 ((listp org-agenda-files) org-agenda-files)
14779 (t (error "Invalid value of `org-agenda-files'")))))
14780 (setq files (apply 'append
14781 (mapcar (lambda (f)
14782 (if (file-directory-p f)
14783 (directory-files
14784 f t org-agenda-file-regexp)
14785 (list f)))
14786 files)))
14787 (when org-agenda-skip-unavailable-files
14788 (setq files (delq nil
14789 (mapcar (function
14790 (lambda (file)
14791 (and (file-readable-p file) file)))
14792 files))))
14793 (when (or (eq archives t)
14794 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14795 (setq files (org-add-archive-files files)))
14796 files))
14798 (defun org-edit-agenda-file-list ()
14799 "Edit the list of agenda files.
14800 Depending on setup, this either uses customize to edit the variable
14801 `org-agenda-files', or it visits the file that is holding the list. In the
14802 latter case, the buffer is set up in a way that saving it automatically kills
14803 the buffer and restores the previous window configuration."
14804 (interactive)
14805 (if (stringp org-agenda-files)
14806 (let ((cw (current-window-configuration)))
14807 (find-file org-agenda-files)
14808 (org-set-local 'org-window-configuration cw)
14809 (org-add-hook 'after-save-hook
14810 (lambda ()
14811 (set-window-configuration
14812 (prog1 org-window-configuration
14813 (kill-buffer (current-buffer))))
14814 (org-install-agenda-files-menu)
14815 (message "New agenda file list installed"))
14816 nil 'local)
14817 (message "%s" (substitute-command-keys
14818 "Edit list and finish with \\[save-buffer]")))
14819 (customize-variable 'org-agenda-files)))
14821 (defun org-store-new-agenda-file-list (list)
14822 "Set new value for the agenda file list and save it correctly."
14823 (if (stringp org-agenda-files)
14824 (let ((fe (org-read-agenda-file-list t)) b u)
14825 (while (setq b (find-buffer-visiting org-agenda-files))
14826 (kill-buffer b))
14827 (with-temp-file org-agenda-files
14828 (insert
14829 (mapconcat
14830 (lambda (f) ;; Keep un-expanded entries.
14831 (if (setq u (assoc f fe))
14832 (cdr u)
14834 list "\n")
14835 "\n")))
14836 (let ((org-mode-hook nil) (org-inhibit-startup t)
14837 (org-insert-mode-line-in-empty-file nil))
14838 (setq org-agenda-files list)
14839 (customize-save-variable 'org-agenda-files org-agenda-files))))
14841 (defun org-read-agenda-file-list (&optional pair-with-expansion)
14842 "Read the list of agenda files from a file.
14843 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
14844 filenames, used by `org-store-new-agenda-file-list' to write back
14845 un-expanded file names."
14846 (when (file-directory-p org-agenda-files)
14847 (error "`org-agenda-files' cannot be a single directory"))
14848 (when (stringp org-agenda-files)
14849 (with-temp-buffer
14850 (insert-file-contents org-agenda-files)
14851 (mapcar
14852 (lambda (f)
14853 (let ((e (expand-file-name (substitute-in-file-name f)
14854 org-directory)))
14855 (if pair-with-expansion
14856 (cons e f)
14857 e)))
14858 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
14860 ;;;###autoload
14861 (defun org-cycle-agenda-files ()
14862 "Cycle through the files in `org-agenda-files'.
14863 If the current buffer visits an agenda file, find the next one in the list.
14864 If the current buffer does not, find the first agenda file."
14865 (interactive)
14866 (let* ((fs (org-agenda-files t))
14867 (files (append fs (list (car fs))))
14868 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14869 file)
14870 (unless files (error "No agenda files"))
14871 (catch 'exit
14872 (while (setq file (pop files))
14873 (if (equal (file-truename file) tcf)
14874 (when (car files)
14875 (find-file (car files))
14876 (throw 'exit t))))
14877 (find-file (car fs)))
14878 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14880 (defun org-agenda-file-to-front (&optional to-end)
14881 "Move/add the current file to the top of the agenda file list.
14882 If the file is not present in the list, it is added to the front. If it is
14883 present, it is moved there. With optional argument TO-END, add/move to the
14884 end of the list."
14885 (interactive "P")
14886 (let ((org-agenda-skip-unavailable-files nil)
14887 (file-alist (mapcar (lambda (x)
14888 (cons (file-truename x) x))
14889 (org-agenda-files t)))
14890 (ctf (file-truename buffer-file-name))
14891 x had)
14892 (setq x (assoc ctf file-alist) had x)
14894 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14895 (if to-end
14896 (setq file-alist (append (delq x file-alist) (list x)))
14897 (setq file-alist (cons x (delq x file-alist))))
14898 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14899 (org-install-agenda-files-menu)
14900 (message "File %s to %s of agenda file list"
14901 (if had "moved" "added") (if to-end "end" "front"))))
14903 (defun org-remove-file (&optional file)
14904 "Remove current file from the list of files in variable `org-agenda-files'.
14905 These are the files which are being checked for agenda entries.
14906 Optional argument FILE means use this file instead of the current."
14907 (interactive)
14908 (let* ((org-agenda-skip-unavailable-files nil)
14909 (file (or file buffer-file-name))
14910 (true-file (file-truename file))
14911 (afile (abbreviate-file-name file))
14912 (files (delq nil (mapcar
14913 (lambda (x)
14914 (if (equal true-file
14915 (file-truename x))
14916 nil x))
14917 (org-agenda-files t)))))
14918 (if (not (= (length files) (length (org-agenda-files t))))
14919 (progn
14920 (org-store-new-agenda-file-list files)
14921 (org-install-agenda-files-menu)
14922 (message "Removed file: %s" afile))
14923 (message "File was not in list: %s (not removed)" afile))))
14925 (defun org-file-menu-entry (file)
14926 (vector file (list 'find-file file) t))
14928 (defun org-check-agenda-file (file)
14929 "Make sure FILE exists. If not, ask user what to do."
14930 (when (not (file-exists-p file))
14931 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14932 (abbreviate-file-name file))
14933 (let ((r (downcase (read-char-exclusive))))
14934 (cond
14935 ((equal r ?r)
14936 (org-remove-file file)
14937 (throw 'nextfile t))
14938 (t (error "Abort"))))))
14940 (defun org-get-agenda-file-buffer (file)
14941 "Get a buffer visiting FILE. If the buffer needs to be created, add
14942 it to the list of buffers which might be released later."
14943 (let ((buf (org-find-base-buffer-visiting file)))
14944 (if buf
14945 buf ; just return it
14946 ;; Make a new buffer and remember it
14947 (setq buf (find-file-noselect file))
14948 (if buf (push buf org-agenda-new-buffers))
14949 buf)))
14951 (defun org-release-buffers (blist)
14952 "Release all buffers in list, asking the user for confirmation when needed.
14953 When a buffer is unmodified, it is just killed. When modified, it is saved
14954 \(if the user agrees) and then killed."
14955 (let (buf file)
14956 (while (setq buf (pop blist))
14957 (setq file (buffer-file-name buf))
14958 (when (and (buffer-modified-p buf)
14959 file
14960 (y-or-n-p (format "Save file %s? " file)))
14961 (with-current-buffer buf (save-buffer)))
14962 (kill-buffer buf))))
14964 (defun org-prepare-agenda-buffers (files)
14965 "Create buffers for all agenda files, protect archived trees and comments."
14966 (interactive)
14967 (let ((pa '(:org-archived t))
14968 (pc '(:org-comment t))
14969 (pall '(:org-archived t :org-comment t))
14970 (inhibit-read-only t)
14971 (rea (concat ":" org-archive-tag ":"))
14972 bmp file re)
14973 (save-excursion
14974 (save-restriction
14975 (while (setq file (pop files))
14976 (catch 'nextfile
14977 (if (bufferp file)
14978 (set-buffer file)
14979 (org-check-agenda-file file)
14980 (set-buffer (org-get-agenda-file-buffer file)))
14981 (widen)
14982 (setq bmp (buffer-modified-p))
14983 (org-refresh-category-properties)
14984 (setq org-todo-keywords-for-agenda
14985 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14986 (setq org-done-keywords-for-agenda
14987 (append org-done-keywords-for-agenda org-done-keywords))
14988 (setq org-todo-keyword-alist-for-agenda
14989 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14990 (setq org-drawers-for-agenda
14991 (append org-drawers-for-agenda org-drawers))
14992 (setq org-tag-alist-for-agenda
14993 (append org-tag-alist-for-agenda org-tag-alist))
14995 (save-excursion
14996 (remove-text-properties (point-min) (point-max) pall)
14997 (when org-agenda-skip-archived-trees
14998 (goto-char (point-min))
14999 (while (re-search-forward rea nil t)
15000 (if (org-on-heading-p t)
15001 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
15002 (goto-char (point-min))
15003 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
15004 (while (re-search-forward re nil t)
15005 (add-text-properties
15006 (match-beginning 0) (org-end-of-subtree t) pc)))
15007 (set-buffer-modified-p bmp)))))
15008 (setq org-todo-keywords-for-agenda
15009 (org-uniquify org-todo-keywords-for-agenda))
15010 (setq org-todo-keyword-alist-for-agenda
15011 (org-uniquify org-todo-keyword-alist-for-agenda)
15012 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
15014 ;;;; Embedded LaTeX
15016 (defvar org-cdlatex-mode-map (make-sparse-keymap)
15017 "Keymap for the minor `org-cdlatex-mode'.")
15019 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
15020 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
15021 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
15022 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
15023 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
15025 (defvar org-cdlatex-texmathp-advice-is-done nil
15026 "Flag remembering if we have applied the advice to texmathp already.")
15028 (define-minor-mode org-cdlatex-mode
15029 "Toggle the minor `org-cdlatex-mode'.
15030 This mode supports entering LaTeX environment and math in LaTeX fragments
15031 in Org-mode.
15032 \\{org-cdlatex-mode-map}"
15033 nil " OCDL" nil
15034 (when org-cdlatex-mode (require 'cdlatex))
15035 (unless org-cdlatex-texmathp-advice-is-done
15036 (setq org-cdlatex-texmathp-advice-is-done t)
15037 (defadvice texmathp (around org-math-always-on activate)
15038 "Always return t in org-mode buffers.
15039 This is because we want to insert math symbols without dollars even outside
15040 the LaTeX math segments. If Orgmode thinks that point is actually inside
15041 an embedded LaTeX fragment, let texmathp do its job.
15042 \\[org-cdlatex-mode-map]"
15043 (interactive)
15044 (let (p)
15045 (cond
15046 ((not (org-mode-p)) ad-do-it)
15047 ((eq this-command 'cdlatex-math-symbol)
15048 (setq ad-return-value t
15049 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15051 (let ((p (org-inside-LaTeX-fragment-p)))
15052 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15053 (setq ad-return-value t
15054 texmathp-why '("Org-mode embedded math" . 0))
15055 (if p ad-do-it)))))))))
15057 (defun turn-on-org-cdlatex ()
15058 "Unconditionally turn on `org-cdlatex-mode'."
15059 (org-cdlatex-mode 1))
15061 (defun org-inside-LaTeX-fragment-p ()
15062 "Test if point is inside a LaTeX fragment.
15063 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15064 sequence appearing also before point.
15065 Even though the matchers for math are configurable, this function assumes
15066 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15067 delimiters are skipped when they have been removed by customization.
15068 The return value is nil, or a cons cell with the delimiter and
15069 and the position of this delimiter.
15071 This function does a reasonably good job, but can locally be fooled by
15072 for example currency specifications. For example it will assume being in
15073 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15074 fragments that are properly closed, but during editing, we have to live
15075 with the uncertainty caused by missing closing delimiters. This function
15076 looks only before point, not after."
15077 (catch 'exit
15078 (let ((pos (point))
15079 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15080 (lim (progn
15081 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15082 (point)))
15083 dd-on str (start 0) m re)
15084 (goto-char pos)
15085 (when dodollar
15086 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15087 re (nth 1 (assoc "$" org-latex-regexps)))
15088 (while (string-match re str start)
15089 (cond
15090 ((= (match-end 0) (length str))
15091 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
15092 ((= (match-end 0) (- (length str) 5))
15093 (throw 'exit nil))
15094 (t (setq start (match-end 0))))))
15095 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15096 (goto-char pos)
15097 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15098 (and (match-beginning 2) (throw 'exit nil))
15099 ;; count $$
15100 (while (re-search-backward "\\$\\$" lim t)
15101 (setq dd-on (not dd-on)))
15102 (goto-char pos)
15103 (if dd-on (cons "$$" m))))))
15105 (defun org-inside-latex-macro-p ()
15106 "Is point inside a LaTeX macro or its arguments?"
15107 (save-match-data
15108 (org-in-regexp
15109 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
15111 (defun test ()
15112 (interactive)
15113 (message "%s" (org-inside-latex-macro-p)))
15115 (defun org-try-cdlatex-tab ()
15116 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15117 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15118 - inside a LaTeX fragment, or
15119 - after the first word in a line, where an abbreviation expansion could
15120 insert a LaTeX environment."
15121 (when org-cdlatex-mode
15122 (cond
15123 ((save-excursion
15124 (skip-chars-backward "a-zA-Z0-9*")
15125 (skip-chars-backward " \t")
15126 (bolp))
15127 (cdlatex-tab) t)
15128 ((org-inside-LaTeX-fragment-p)
15129 (cdlatex-tab) t)
15130 (t nil))))
15132 (defun org-cdlatex-underscore-caret (&optional arg)
15133 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15134 Revert to the normal definition outside of these fragments."
15135 (interactive "P")
15136 (if (org-inside-LaTeX-fragment-p)
15137 (call-interactively 'cdlatex-sub-superscript)
15138 (let (org-cdlatex-mode)
15139 (call-interactively (key-binding (vector last-input-event))))))
15141 (defun org-cdlatex-math-modify (&optional arg)
15142 "Execute `cdlatex-math-modify' in LaTeX fragments.
15143 Revert to the normal definition outside of these fragments."
15144 (interactive "P")
15145 (if (org-inside-LaTeX-fragment-p)
15146 (call-interactively 'cdlatex-math-modify)
15147 (let (org-cdlatex-mode)
15148 (call-interactively (key-binding (vector last-input-event))))))
15150 (defvar org-latex-fragment-image-overlays nil
15151 "List of overlays carrying the images of latex fragments.")
15152 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15154 (defun org-remove-latex-fragment-image-overlays ()
15155 "Remove all overlays with LaTeX fragment images in current buffer."
15156 (mapc 'delete-overlay org-latex-fragment-image-overlays)
15157 (setq org-latex-fragment-image-overlays nil))
15159 (defun org-preview-latex-fragment (&optional subtree)
15160 "Preview the LaTeX fragment at point, or all locally or globally.
15161 If the cursor is in a LaTeX fragment, create the image and overlay
15162 it over the source code. If there is no fragment at point, display
15163 all fragments in the current text, from one headline to the next. With
15164 prefix SUBTREE, display all fragments in the current subtree. With a
15165 double prefix `C-u C-u', or when the cursor is before the first headline,
15166 display all fragments in the buffer.
15167 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15168 (interactive "P")
15169 (org-remove-latex-fragment-image-overlays)
15170 (save-excursion
15171 (save-restriction
15172 (let (beg end at msg)
15173 (cond
15174 ((or (equal subtree '(16))
15175 (not (save-excursion
15176 (re-search-backward (concat "^" outline-regexp) nil t))))
15177 (setq beg (point-min) end (point-max)
15178 msg "Creating images for buffer...%s"))
15179 ((equal subtree '(4))
15180 (org-back-to-heading)
15181 (setq beg (point) end (org-end-of-subtree t)
15182 msg "Creating images for subtree...%s"))
15184 (if (setq at (org-inside-LaTeX-fragment-p))
15185 (goto-char (max (point-min) (- (cdr at) 2)))
15186 (org-back-to-heading))
15187 (setq beg (point) end (progn (outline-next-heading) (point))
15188 msg (if at "Creating image...%s"
15189 "Creating images for entry...%s"))))
15190 (message msg "")
15191 (narrow-to-region beg end)
15192 (goto-char beg)
15193 (org-format-latex
15194 (concat "ltxpng/" (file-name-sans-extension
15195 (file-name-nondirectory
15196 buffer-file-name)))
15197 default-directory 'overlays msg at 'forbuffer)
15198 (message msg "done. Use `C-c C-c' to remove images.")))))
15200 (defvar org-latex-regexps
15201 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15202 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15203 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15204 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15205 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15206 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15207 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
15208 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
15209 "Regular expressions for matching embedded LaTeX.")
15211 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
15212 "Replace LaTeX fragments with links to an image, and produce images.
15213 Some of the options can be changed using the variable
15214 `org-format-latex-options'."
15215 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15216 (let* ((prefixnodir (file-name-nondirectory prefix))
15217 (absprefix (expand-file-name prefix dir))
15218 (todir (file-name-directory absprefix))
15219 (opt org-format-latex-options)
15220 (matchers (plist-get opt :matchers))
15221 (re-list org-latex-regexps)
15222 (org-format-latex-header-extra
15223 (plist-get (org-infile-export-plist) :latex-header-extra))
15224 (cnt 0) txt hash link beg end re e checkdir
15225 executables-checked
15226 m n block linkfile movefile ov)
15227 ;; Check the different regular expressions
15228 (while (setq e (pop re-list))
15229 (setq m (car e) re (nth 1 e) n (nth 2 e)
15230 block (if (nth 3 e) "\n\n" ""))
15231 (when (member m matchers)
15232 (goto-char (point-min))
15233 (while (re-search-forward re nil t)
15234 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
15235 (not (get-text-property (match-beginning n)
15236 'org-protected))
15237 (or (not overlays)
15238 (not (eq (get-char-property (match-beginning n)
15239 'org-overlay-type)
15240 'org-latex-overlay))))
15241 (setq txt (match-string n)
15242 beg (match-beginning n) end (match-end n)
15243 cnt (1+ cnt))
15244 (let (print-length print-level) ; make sure full list is printed
15245 (setq hash (sha1 (prin1-to-string
15246 (list org-format-latex-header
15247 org-format-latex-header-extra
15248 org-export-latex-default-packages-alist
15249 org-export-latex-packages-alist
15250 org-format-latex-options
15251 forbuffer txt)))
15252 linkfile (format "%s_%s.png" prefix hash)
15253 movefile (format "%s_%s.png" absprefix hash)))
15254 (setq link (concat block "[[file:" linkfile "]]" block))
15255 (if msg (message msg cnt))
15256 (goto-char beg)
15257 (unless checkdir ; make sure the directory exists
15258 (setq checkdir t)
15259 (or (file-directory-p todir) (make-directory todir)))
15261 (unless executables-checked
15262 (org-check-external-command
15263 "latex" "needed to convert LaTeX fragments to images")
15264 (org-check-external-command
15265 "dvipng" "needed to convert LaTeX fragments to images")
15266 (setq executables-checked t))
15268 (unless (file-exists-p movefile)
15269 (org-create-formula-image
15270 txt movefile opt forbuffer))
15271 (if overlays
15272 (progn
15273 (mapc (lambda (o)
15274 (if (eq (overlay-get o 'org-overlay-type)
15275 'org-latex-overlay)
15276 (delete-overlay o)))
15277 (org-overlays-in beg end))
15278 (setq ov (make-overlay beg end))
15279 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
15280 (if (featurep 'xemacs)
15281 (progn
15282 (overlay-put ov 'invisible t)
15283 (overlay-put
15284 ov 'end-glyph
15285 (make-glyph (vector 'png :file movefile))))
15286 (overlay-put
15287 ov 'display
15288 (list 'image :type 'png :file movefile :ascent 'center)))
15289 (push ov org-latex-fragment-image-overlays)
15290 (goto-char end))
15291 (delete-region beg end)
15292 (insert (org-add-props link
15293 (list 'org-latex-src
15294 (replace-regexp-in-string "\"" "" txt)))))))))))
15296 ;; This function borrows from Ganesh Swami's latex2png.el
15297 (defun org-create-formula-image (string tofile options buffer)
15298 "This calls dvipng."
15299 (require 'org-latex)
15300 (let* ((tmpdir (if (featurep 'xemacs)
15301 (temp-directory)
15302 temporary-file-directory))
15303 (texfilebase (make-temp-name
15304 (expand-file-name "orgtex" tmpdir)))
15305 (texfile (concat texfilebase ".tex"))
15306 (dvifile (concat texfilebase ".dvi"))
15307 (pngfile (concat texfilebase ".png"))
15308 (fnh (if (featurep 'xemacs)
15309 (font-height (get-face-font 'default))
15310 (face-attribute 'default :height nil)))
15311 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
15312 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
15313 (fg (or (plist-get options (if buffer :foreground :html-foreground))
15314 "Black"))
15315 (bg (or (plist-get options (if buffer :background :html-background))
15316 "Transparent")))
15317 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
15318 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
15319 (with-temp-file texfile
15320 (insert (org-splice-latex-header
15321 org-format-latex-header
15322 org-export-latex-default-packages-alist
15323 org-export-latex-packages-alist
15324 org-format-latex-header-extra))
15325 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
15326 (require 'org-latex)
15327 (org-export-latex-fix-inputenc))
15328 (let ((dir default-directory))
15329 (condition-case nil
15330 (progn
15331 (cd tmpdir)
15332 (call-process "latex" nil nil nil texfile))
15333 (error nil))
15334 (cd dir))
15335 (if (not (file-exists-p dvifile))
15336 (progn (message "Failed to create dvi file from %s" texfile) nil)
15337 (condition-case nil
15338 (call-process "dvipng" nil nil nil
15339 "-fg" fg "-bg" bg
15340 "-D" dpi
15341 ;;"-x" scale "-y" scale
15342 "-T" "tight"
15343 "-o" pngfile
15344 dvifile)
15345 (error nil))
15346 (if (not (file-exists-p pngfile))
15347 (if org-format-latex-signal-error
15348 (error "Failed to create png file from %s" texfile)
15349 (message "Failed to create png file from %s" texfile)
15350 nil)
15351 ;; Use the requested file name and clean up
15352 (copy-file pngfile tofile 'replace)
15353 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15354 (delete-file (concat texfilebase e)))
15355 pngfile))))
15357 (defun org-splice-latex-header (tpl def-pkg pkg &optional extra)
15358 "Fill a LaTeX header template TPL.
15359 In the template, the following place holders will be recognized:
15361 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
15362 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
15363 [PACKAGES] \\usepackage statements for PKG
15364 [NO-PACKAGES] do not include PKG
15365 [EXTRA] the string EXTRA
15366 [NO-EXTRA] do not include EXTRA
15368 For backward compatibility, if both the positive and the negative place
15369 holder is missing, the positive one (without the \"NO-\") will be
15370 assumed to be present at the end of the template.
15371 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
15372 EXTRA is a string."
15373 (let (rpl (end ""))
15374 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
15375 (setq rpl (if (or (match-end 1) (not def-pkg))
15376 "" (org-latex-packages-to-string def-pkg t))
15377 tpl (replace-match rpl t t tpl))
15378 (if def-pkg (setq end (org-latex-packages-to-string def-pkg))))
15380 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
15381 (setq rpl (if (or (match-end 1) (not pkg))
15382 "" (org-latex-packages-to-string pkg t))
15383 tpl (replace-match rpl t t tpl))
15384 (if pkg (setq end (concat end "\n" (org-latex-packages-to-string pkg)))))
15386 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
15387 (setq rpl (if (or (match-end 1) (not extra))
15388 "" (concat extra "\n"))
15389 tpl (replace-match rpl t t tpl))
15390 (if (and extra (string-match "\\S-" extra))
15391 (setq end (concat end "\n" extra))))
15393 (if (string-match "\\S-" end)
15394 (concat tpl "\n" end)
15395 tpl)))
15397 (defun org-latex-packages-to-string (pkg &optional newline)
15398 "Turn an alist of packages into a string with the \\usepackage macros."
15399 (setq pkg (mapconcat (lambda(p)
15400 (cond
15401 ((stringp p) p)
15402 ((equal "" (car p))
15403 (format "\\usepackage{%s}" (cadr p)))
15405 (format "\\usepackage[%s]{%s}"
15406 (car p) (cadr p)))))
15408 "\n"))
15409 (if newline (concat pkg "\n") pkg))
15411 (defun org-dvipng-color (attr)
15412 "Return an rgb color specification for dvipng."
15413 (apply 'format "rgb %s %s %s"
15414 (mapcar 'org-normalize-color
15415 (color-values (face-attribute 'default attr nil)))))
15417 (defun org-normalize-color (value)
15418 "Return string to be used as color value for an RGB component."
15419 (format "%g" (/ value 65535.0)))
15421 ;;;; Key bindings
15423 ;; Make `C-c C-x' a prefix key
15424 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
15426 ;; TAB key with modifiers
15427 (org-defkey org-mode-map "\C-i" 'org-cycle)
15428 (org-defkey org-mode-map [(tab)] 'org-cycle)
15429 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
15430 (org-defkey org-mode-map [(meta tab)] 'org-complete)
15431 (org-defkey org-mode-map "\M-\t" 'org-complete)
15432 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
15433 ;; The following line is necessary under Suse GNU/Linux
15434 (unless (featurep 'xemacs)
15435 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
15436 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
15437 (define-key org-mode-map [backtab] 'org-shifttab)
15439 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
15440 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15441 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
15443 ;; Cursor keys with modifiers
15444 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
15445 (org-defkey org-mode-map [(meta right)] 'org-metaright)
15446 (org-defkey org-mode-map [(meta up)] 'org-metaup)
15447 (org-defkey org-mode-map [(meta down)] 'org-metadown)
15449 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15450 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
15451 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
15452 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
15454 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
15455 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
15456 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
15457 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
15459 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
15460 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
15462 ;;; Extra keys for tty access.
15463 ;; We only set them when really needed because otherwise the
15464 ;; menus don't show the simple keys
15466 (when (or org-use-extra-keys
15467 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
15468 (not window-system))
15469 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
15470 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
15471 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
15472 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
15473 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
15474 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
15475 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
15476 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
15477 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
15478 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
15479 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
15480 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
15481 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
15482 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
15483 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
15484 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
15485 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
15486 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
15487 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
15488 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
15489 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
15490 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
15491 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
15492 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
15493 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
15494 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
15495 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
15496 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
15498 ;; All the other keys
15500 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15501 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
15502 (if (boundp 'narrow-map)
15503 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
15504 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
15505 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
15506 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
15507 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
15508 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
15509 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
15510 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
15511 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
15512 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
15513 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
15514 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
15515 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
15516 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
15517 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
15518 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
15519 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15520 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
15521 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
15522 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
15523 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
15524 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
15525 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
15526 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
15527 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
15528 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
15529 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
15530 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
15531 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
15532 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
15533 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
15534 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
15535 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15536 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15537 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15538 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15539 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
15540 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
15541 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15542 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
15543 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
15544 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
15545 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
15546 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15547 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
15548 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
15549 (org-defkey org-mode-map "\C-c^" 'org-sort)
15550 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15551 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
15552 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
15553 (org-defkey org-mode-map "\C-m" 'org-return)
15554 (org-defkey org-mode-map "\C-j" 'org-return-indent)
15555 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
15556 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
15557 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
15558 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
15559 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
15560 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
15561 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15562 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15563 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
15564 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
15565 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
15566 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
15567 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
15568 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15569 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
15570 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
15571 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
15572 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
15573 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
15574 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
15576 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
15577 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15578 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15579 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15581 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
15582 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15583 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15584 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
15585 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15586 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15587 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15588 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15589 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15590 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15591 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
15592 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
15593 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
15594 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
15595 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
15597 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
15598 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
15599 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
15600 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
15602 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
15604 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
15606 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
15607 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
15609 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
15612 (when (featurep 'xemacs)
15613 (org-defkey org-mode-map 'button3 'popup-mode-menu))
15616 (defconst org-speed-commands-default
15618 ("Outline Navigation")
15619 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
15620 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
15621 ("f" . (org-speed-move-safe 'org-forward-same-level))
15622 ("b" . (org-speed-move-safe 'org-backward-same-level))
15623 ("u" . (org-speed-move-safe 'outline-up-heading))
15624 ("j" . org-goto)
15625 ("g" . (org-refile t))
15626 ("Outline Visibility")
15627 ("c" . org-cycle)
15628 ("C" . org-shifttab)
15629 (" " . org-display-outline-path)
15630 ("Outline Structure Editing")
15631 ("U" . org-shiftmetaup)
15632 ("D" . org-shiftmetadown)
15633 ("r" . org-metaright)
15634 ("l" . org-metaleft)
15635 ("R" . org-shiftmetaright)
15636 ("L" . org-shiftmetaleft)
15637 ("i" . (progn (forward-char 1) (call-interactively
15638 'org-insert-heading-respect-content)))
15639 ("^" . org-sort)
15640 ("w" . org-refile)
15641 ("a" . org-archive-subtree-default-with-confirmation)
15642 ("." . outline-mark-subtree)
15643 ("Clock Commands")
15644 ("I" . org-clock-in)
15645 ("O" . org-clock-out)
15646 ("Meta Data Editing")
15647 ("t" . org-todo)
15648 ("0" . (org-priority ?\ ))
15649 ("1" . (org-priority ?A))
15650 ("2" . (org-priority ?B))
15651 ("3" . (org-priority ?C))
15652 (";" . org-set-tags-command)
15653 ("e" . org-set-effort)
15654 ("Agenda Views etc")
15655 ("v" . org-agenda)
15656 ("/" . org-sparse-tree)
15657 ("Misc")
15658 ("o" . org-open-at-point)
15659 ("?" . org-speed-command-help)
15661 "The default speed commands.")
15663 (defun org-print-speed-command (e)
15664 (if (> (length (car e)) 1)
15665 (progn
15666 (princ "\n")
15667 (princ (car e))
15668 (princ "\n")
15669 (princ (make-string (length (car e)) ?-))
15670 (princ "\n"))
15671 (princ (car e))
15672 (princ " ")
15673 (if (symbolp (cdr e))
15674 (princ (symbol-name (cdr e)))
15675 (prin1 (cdr e)))
15676 (princ "\n")))
15678 (defun org-speed-command-help ()
15679 "Show the available speed commands."
15680 (interactive)
15681 (if (not org-use-speed-commands)
15682 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
15683 (with-output-to-temp-buffer "*Help*"
15684 (princ "User-defined Speed commands\n===========================\n")
15685 (mapc 'org-print-speed-command org-speed-commands-user)
15686 (princ "\n")
15687 (princ "Built-in Speed commands\n=======================\n")
15688 (mapc 'org-print-speed-command org-speed-commands-default))
15689 (with-current-buffer "*Help*"
15690 (setq truncate-lines t))))
15692 (defun org-speed-move-safe (cmd)
15693 "Execute CMD, but make sure that the cursor always ends up in a headline.
15694 If not, return to the original position and throw an error."
15695 (interactive)
15696 (let ((pos (point)))
15697 (call-interactively cmd)
15698 (unless (and (bolp) (org-on-heading-p))
15699 (goto-char pos)
15700 (error "Boundary reached while executing %s" cmd))))
15702 (defvar org-self-insert-command-undo-counter 0)
15704 (defvar org-table-auto-blank-field) ; defined in org-table.el
15705 (defvar org-speed-command nil)
15706 (defun org-self-insert-command (N)
15707 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15708 If the cursor is in a table looking at whitespace, the whitespace is
15709 overwritten, and the table is not marked as requiring realignment."
15710 (interactive "p")
15711 (cond
15712 ((and org-use-speed-commands
15713 (or (and (bolp) (looking-at outline-regexp))
15714 (and (functionp org-use-speed-commands)
15715 (funcall org-use-speed-commands)))
15716 (setq
15717 org-speed-command
15718 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15719 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15720 (cond
15721 ((commandp org-speed-command)
15722 (setq this-command org-speed-command)
15723 (call-interactively org-speed-command))
15724 ((functionp org-speed-command)
15725 (funcall org-speed-command))
15726 ((and org-speed-command (listp org-speed-command))
15727 (eval org-speed-command))
15728 (t (let (org-use-speed-commands)
15729 (call-interactively 'org-self-insert-command)))))
15730 ((and
15731 (org-table-p)
15732 (progn
15733 ;; check if we blank the field, and if that triggers align
15734 (and (featurep 'org-table) org-table-auto-blank-field
15735 (member last-command
15736 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15737 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15738 ;; got extra space, this field does not determine column width
15739 (let (org-table-may-need-update) (org-table-blank-field))
15740 ;; no extra space, this field may determine column width
15741 (org-table-blank-field)))
15743 (eq N 1)
15744 (looking-at "[^|\n]* |"))
15745 (let (org-table-may-need-update)
15746 (goto-char (1- (match-end 0)))
15747 (delete-backward-char 1)
15748 (goto-char (match-beginning 0))
15749 (self-insert-command N)))
15751 (setq org-table-may-need-update t)
15752 (self-insert-command N)
15753 (org-fix-tags-on-the-fly)
15754 (if org-self-insert-cluster-for-undo
15755 (if (not (eq last-command 'org-self-insert-command))
15756 (setq org-self-insert-command-undo-counter 1)
15757 (if (>= org-self-insert-command-undo-counter 20)
15758 (setq org-self-insert-command-undo-counter 1)
15759 (and (> org-self-insert-command-undo-counter 0)
15760 buffer-undo-list
15761 (not (cadr buffer-undo-list)) ; remove nil entry
15762 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15763 (setq org-self-insert-command-undo-counter
15764 (1+ org-self-insert-command-undo-counter))))))))
15766 (defun org-fix-tags-on-the-fly ()
15767 (when (and (equal (char-after (point-at-bol)) ?*)
15768 (org-on-heading-p))
15769 (org-align-tags-here org-tags-column)))
15771 (defun org-delete-backward-char (N)
15772 "Like `delete-backward-char', insert whitespace at field end in tables.
15773 When deleting backwards, in tables this function will insert whitespace in
15774 front of the next \"|\" separator, to keep the table aligned. The table will
15775 still be marked for re-alignment if the field did fill the entire column,
15776 because, in this case the deletion might narrow the column."
15777 (interactive "p")
15778 (if (and (org-table-p)
15779 (eq N 1)
15780 (string-match "|" (buffer-substring (point-at-bol) (point)))
15781 (looking-at ".*?|"))
15782 (let ((pos (point))
15783 (noalign (looking-at "[^|\n\r]* |"))
15784 (c org-table-may-need-update))
15785 (backward-delete-char N)
15786 (skip-chars-forward "^|")
15787 (insert " ")
15788 (goto-char (1- pos))
15789 ;; noalign: if there were two spaces at the end, this field
15790 ;; does not determine the width of the column.
15791 (if noalign (setq org-table-may-need-update c)))
15792 (backward-delete-char N)
15793 (org-fix-tags-on-the-fly)))
15795 (defun org-delete-char (N)
15796 "Like `delete-char', but insert whitespace at field end in tables.
15797 When deleting characters, in tables this function will insert whitespace in
15798 front of the next \"|\" separator, to keep the table aligned. The table will
15799 still be marked for re-alignment if the field did fill the entire column,
15800 because, in this case the deletion might narrow the column."
15801 (interactive "p")
15802 (if (and (org-table-p)
15803 (not (bolp))
15804 (not (= (char-after) ?|))
15805 (eq N 1))
15806 (if (looking-at ".*?|")
15807 (let ((pos (point))
15808 (noalign (looking-at "[^|\n\r]* |"))
15809 (c org-table-may-need-update))
15810 (replace-match (concat
15811 (substring (match-string 0) 1 -1)
15812 " |"))
15813 (goto-char pos)
15814 ;; noalign: if there were two spaces at the end, this field
15815 ;; does not determine the width of the column.
15816 (if noalign (setq org-table-may-need-update c)))
15817 (delete-char N))
15818 (delete-char N)
15819 (org-fix-tags-on-the-fly)))
15821 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15822 (put 'org-self-insert-command 'delete-selection t)
15823 (put 'orgtbl-self-insert-command 'delete-selection t)
15824 (put 'org-delete-char 'delete-selection 'supersede)
15825 (put 'org-delete-backward-char 'delete-selection 'supersede)
15826 (put 'org-yank 'delete-selection 'yank)
15828 ;; Make `flyspell-mode' delay after some commands
15829 (put 'org-self-insert-command 'flyspell-delayed t)
15830 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15831 (put 'org-delete-char 'flyspell-delayed t)
15832 (put 'org-delete-backward-char 'flyspell-delayed t)
15834 ;; Make pabbrev-mode expand after org-mode commands
15835 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15836 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15838 ;; How to do this: Measure non-white length of current string
15839 ;; If equal to column width, we should realign.
15841 (defun org-remap (map &rest commands)
15842 "In MAP, remap the functions given in COMMANDS.
15843 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15844 (let (new old)
15845 (while commands
15846 (setq old (pop commands) new (pop commands))
15847 (if (fboundp 'command-remapping)
15848 (org-defkey map (vector 'remap old) new)
15849 (substitute-key-definition old new map global-map)))))
15851 (when (eq org-enable-table-editor 'optimized)
15852 ;; If the user wants maximum table support, we need to hijack
15853 ;; some standard editing functions
15854 (org-remap org-mode-map
15855 'self-insert-command 'org-self-insert-command
15856 'delete-char 'org-delete-char
15857 'delete-backward-char 'org-delete-backward-char)
15858 (org-defkey org-mode-map "|" 'org-force-self-insert))
15860 (defvar org-ctrl-c-ctrl-c-hook nil
15861 "Hook for functions attaching themselves to `C-c C-c'.
15862 This can be used to add additional functionality to the C-c C-c key which
15863 executes context-dependent commands.
15864 Each function will be called with no arguments. The function must check
15865 if the context is appropriate for it to act. If yes, it should do its
15866 thing and then return a non-nil value. If the context is wrong,
15867 just do nothing and return nil.")
15869 (defvar org-tab-first-hook nil
15870 "Hook for functions to attach themselves to TAB.
15871 See `org-ctrl-c-ctrl-c-hook' for more information.
15872 This hook runs as the first action when TAB is pressed, even before
15873 `org-cycle' messes around with the `outline-regexp' to cater for
15874 inline tasks and plain list item folding.
15875 If any function in this hook returns t, not other actions like table
15876 field motion visibility cycling will be done.")
15878 (defvar org-tab-after-check-for-table-hook nil
15879 "Hook for functions to attach themselves to TAB.
15880 See `org-ctrl-c-ctrl-c-hook' for more information.
15881 This hook runs after it has been established that the cursor is not in a
15882 table, but before checking if the cursor is in a headline or if global cycling
15883 should be done.
15884 If any function in this hook returns t, not other actions like visibility
15885 cycling will be done.")
15887 (defvar org-tab-after-check-for-cycling-hook nil
15888 "Hook for functions to attach themselves to TAB.
15889 See `org-ctrl-c-ctrl-c-hook' for more information.
15890 This hook runs after it has been established that not table field motion and
15891 not visibility should be done because of current context. This is probably
15892 the place where a package like yasnippets can hook in.")
15894 (defvar org-tab-before-tab-emulation-hook nil
15895 "Hook for functions to attach themselves to TAB.
15896 See `org-ctrl-c-ctrl-c-hook' for more information.
15897 This hook runs after every other options for TAB have been exhausted, but
15898 before indentation and \t insertion takes place.")
15900 (defvar org-metaleft-hook nil
15901 "Hook for functions attaching themselves to `M-left'.
15902 See `org-ctrl-c-ctrl-c-hook' for more information.")
15903 (defvar org-metaright-hook nil
15904 "Hook for functions attaching themselves to `M-right'.
15905 See `org-ctrl-c-ctrl-c-hook' for more information.")
15906 (defvar org-metaup-hook nil
15907 "Hook for functions attaching themselves to `M-up'.
15908 See `org-ctrl-c-ctrl-c-hook' for more information.")
15909 (defvar org-metadown-hook nil
15910 "Hook for functions attaching themselves to `M-down'.
15911 See `org-ctrl-c-ctrl-c-hook' for more information.")
15912 (defvar org-shiftmetaleft-hook nil
15913 "Hook for functions attaching themselves to `M-S-left'.
15914 See `org-ctrl-c-ctrl-c-hook' for more information.")
15915 (defvar org-shiftmetaright-hook nil
15916 "Hook for functions attaching themselves to `M-S-right'.
15917 See `org-ctrl-c-ctrl-c-hook' for more information.")
15918 (defvar org-shiftmetaup-hook nil
15919 "Hook for functions attaching themselves to `M-S-up'.
15920 See `org-ctrl-c-ctrl-c-hook' for more information.")
15921 (defvar org-shiftmetadown-hook nil
15922 "Hook for functions attaching themselves to `M-S-down'.
15923 See `org-ctrl-c-ctrl-c-hook' for more information.")
15924 (defvar org-metareturn-hook nil
15925 "Hook for functions attaching themselves to `M-RET'.
15926 See `org-ctrl-c-ctrl-c-hook' for more information.")
15928 (defun org-modifier-cursor-error ()
15929 "Throw an error, a modified cursor command was applied in wrong context."
15930 (error "This command is active in special context like tables, headlines or items"))
15932 (defun org-shiftselect-error ()
15933 "Throw an error because Shift-Cursor command was applied in wrong context."
15934 (if (and (boundp 'shift-select-mode) shift-select-mode)
15935 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15936 (error "This command works only in special context like headlines or timestamps")))
15938 (defun org-call-for-shift-select (cmd)
15939 (let ((this-command-keys-shift-translated t))
15940 (call-interactively cmd)))
15942 (defun org-shifttab (&optional arg)
15943 "Global visibility cycling or move to previous table field.
15944 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15945 on context.
15946 See the individual commands for more information."
15947 (interactive "P")
15948 (cond
15949 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15950 ((integerp arg)
15951 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15952 (message "Content view to level: %d" arg)
15953 (org-content (prefix-numeric-value arg2))
15954 (setq org-cycle-global-status 'overview)))
15955 (t (call-interactively 'org-global-cycle))))
15957 (defun org-shiftmetaleft ()
15958 "Promote subtree or delete table column.
15959 Calls `org-promote-subtree', `org-outdent-item',
15960 or `org-table-delete-column', depending on context.
15961 See the individual commands for more information."
15962 (interactive)
15963 (cond
15964 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15965 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15966 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15967 ((org-at-item-p) (call-interactively 'org-outdent-item))
15968 (t (org-modifier-cursor-error))))
15970 (defun org-shiftmetaright ()
15971 "Demote subtree or insert table column.
15972 Calls `org-demote-subtree', `org-indent-item',
15973 or `org-table-insert-column', depending on context.
15974 See the individual commands for more information."
15975 (interactive)
15976 (cond
15977 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15978 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15979 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15980 ((org-at-item-p) (call-interactively 'org-indent-item))
15981 (t (org-modifier-cursor-error))))
15983 (defun org-shiftmetaup (&optional arg)
15984 "Move subtree up or kill table row.
15985 Calls `org-move-subtree-up' or `org-table-kill-row' or
15986 `org-move-item-up' depending on context. See the individual commands
15987 for more information."
15988 (interactive "P")
15989 (cond
15990 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15991 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15992 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15993 ((org-at-item-p) (call-interactively 'org-move-item-up))
15994 (t (org-modifier-cursor-error))))
15996 (defun org-shiftmetadown (&optional arg)
15997 "Move subtree down or insert table row.
15998 Calls `org-move-subtree-down' or `org-table-insert-row' or
15999 `org-move-item-down', depending on context. See the individual
16000 commands for more information."
16001 (interactive "P")
16002 (cond
16003 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
16004 ((org-at-table-p) (call-interactively 'org-table-insert-row))
16005 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16006 ((org-at-item-p) (call-interactively 'org-move-item-down))
16007 (t (org-modifier-cursor-error))))
16009 (defun org-metaleft (&optional arg)
16010 "Promote heading or move table column to left.
16011 Calls `org-do-promote' or `org-table-move-column', depending on context.
16012 With no specific context, calls the Emacs default `backward-word'.
16013 See the individual commands for more information."
16014 (interactive "P")
16015 (cond
16016 ((run-hook-with-args-until-success 'org-metaleft-hook))
16017 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
16018 ((or (org-on-heading-p)
16019 (and (org-region-active-p)
16020 (save-excursion
16021 (goto-char (region-beginning))
16022 (org-on-heading-p))))
16023 (call-interactively 'org-do-promote))
16024 ((or (org-at-item-p)
16025 (and (org-region-active-p)
16026 (save-excursion
16027 (goto-char (region-beginning))
16028 (org-at-item-p))))
16029 (call-interactively 'org-outdent-item))
16030 (t (call-interactively 'backward-word))))
16032 (defun org-metaright (&optional arg)
16033 "Demote subtree or move table column to right.
16034 Calls `org-do-demote' or `org-table-move-column', depending on context.
16035 With no specific context, calls the Emacs default `forward-word'.
16036 See the individual commands for more information."
16037 (interactive "P")
16038 (cond
16039 ((run-hook-with-args-until-success 'org-metaright-hook))
16040 ((org-at-table-p) (call-interactively 'org-table-move-column))
16041 ((or (org-on-heading-p)
16042 (and (org-region-active-p)
16043 (save-excursion
16044 (goto-char (region-beginning))
16045 (org-on-heading-p))))
16046 (call-interactively 'org-do-demote))
16047 ((or (org-at-item-p)
16048 (and (org-region-active-p)
16049 (save-excursion
16050 (goto-char (region-beginning))
16051 (org-at-item-p))))
16052 (call-interactively 'org-indent-item))
16053 (t (call-interactively 'forward-word))))
16055 (defun org-metaup (&optional arg)
16056 "Move subtree up or move table row up.
16057 Calls `org-move-subtree-up' or `org-table-move-row' or
16058 `org-move-item-up', depending on context. See the individual commands
16059 for more information."
16060 (interactive "P")
16061 (cond
16062 ((run-hook-with-args-until-success 'org-metaup-hook))
16063 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
16064 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16065 ((org-at-item-p) (call-interactively 'org-move-item-up))
16066 (t (transpose-lines 1) (beginning-of-line -1))))
16068 (defun org-metadown (&optional arg)
16069 "Move subtree down or move table row down.
16070 Calls `org-move-subtree-down' or `org-table-move-row' or
16071 `org-move-item-down', depending on context. See the individual
16072 commands for more information."
16073 (interactive "P")
16074 (cond
16075 ((run-hook-with-args-until-success 'org-metadown-hook))
16076 ((org-at-table-p) (call-interactively 'org-table-move-row))
16077 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16078 ((org-at-item-p) (call-interactively 'org-move-item-down))
16079 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
16081 (defun org-shiftup (&optional arg)
16082 "Increase item in timestamp or increase priority of current headline.
16083 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
16084 depending on context. See the individual commands for more information."
16085 (interactive "P")
16086 (cond
16087 ((and org-support-shift-select (org-region-active-p))
16088 (org-call-for-shift-select 'previous-line))
16089 ((org-at-timestamp-p t)
16090 (call-interactively (if org-edit-timestamp-down-means-later
16091 'org-timestamp-down 'org-timestamp-up)))
16092 ((and (not (eq org-support-shift-select 'always))
16093 org-enable-priority-commands
16094 (org-on-heading-p))
16095 (call-interactively 'org-priority-up))
16096 ((and (not org-support-shift-select) (org-at-item-p))
16097 (call-interactively 'org-previous-item))
16098 ((org-clocktable-try-shift 'up arg))
16099 (org-support-shift-select
16100 (org-call-for-shift-select 'previous-line))
16101 (t (org-shiftselect-error))))
16103 (defun org-shiftdown (&optional arg)
16104 "Decrease item in timestamp or decrease priority of current headline.
16105 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
16106 depending on context. See the individual commands for more information."
16107 (interactive "P")
16108 (cond
16109 ((and org-support-shift-select (org-region-active-p))
16110 (org-call-for-shift-select 'next-line))
16111 ((org-at-timestamp-p t)
16112 (call-interactively (if org-edit-timestamp-down-means-later
16113 'org-timestamp-up 'org-timestamp-down)))
16114 ((and (not (eq org-support-shift-select 'always))
16115 org-enable-priority-commands
16116 (org-on-heading-p))
16117 (call-interactively 'org-priority-down))
16118 ((and (not org-support-shift-select) (org-at-item-p))
16119 (call-interactively 'org-next-item))
16120 ((org-clocktable-try-shift 'down arg))
16121 (org-support-shift-select
16122 (org-call-for-shift-select 'next-line))
16123 (t (org-shiftselect-error))))
16125 (defun org-shiftright (&optional arg)
16126 "Cycle the thing at point or in the current line, depending on context.
16127 Depending on context, this does one of the following:
16129 - switch a timestamp at point one day into the future
16130 - on a headline, switch to the next TODO keyword.
16131 - on an item, switch entire list to the next bullet type
16132 - on a property line, switch to the next allowed value
16133 - on a clocktable definition line, move time block into the future"
16134 (interactive "P")
16135 (cond
16136 ((and org-support-shift-select (org-region-active-p))
16137 (org-call-for-shift-select 'forward-char))
16138 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
16139 ((and (not (eq org-support-shift-select 'always))
16140 (org-on-heading-p))
16141 (let ((org-inhibit-logging
16142 (not org-treat-S-cursor-todo-selection-as-state-change))
16143 (org-inhibit-blocking
16144 (not org-treat-S-cursor-todo-selection-as-state-change)))
16145 (org-call-with-arg 'org-todo 'right)))
16146 ((or (and org-support-shift-select
16147 (not (eq org-support-shift-select 'always))
16148 (org-at-item-bullet-p))
16149 (and (not org-support-shift-select) (org-at-item-p)))
16150 (org-call-with-arg 'org-cycle-list-bullet nil))
16151 ((and (not (eq org-support-shift-select 'always))
16152 (org-at-property-p))
16153 (call-interactively 'org-property-next-allowed-value))
16154 ((org-clocktable-try-shift 'right arg))
16155 (org-support-shift-select
16156 (org-call-for-shift-select 'forward-char))
16157 (t (org-shiftselect-error))))
16159 (defun org-shiftleft (&optional arg)
16160 "Cycle the thing at point or in the current line, depending on context.
16161 Depending on context, this does one of the following:
16163 - switch a timestamp at point one day into the past
16164 - on a headline, switch to the previous TODO keyword.
16165 - on an item, switch entire list to the previous bullet type
16166 - on a property line, switch to the previous allowed value
16167 - on a clocktable definition line, move time block into the past"
16168 (interactive "P")
16169 (cond
16170 ((and org-support-shift-select (org-region-active-p))
16171 (org-call-for-shift-select 'backward-char))
16172 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
16173 ((and (not (eq org-support-shift-select 'always))
16174 (org-on-heading-p))
16175 (let ((org-inhibit-logging
16176 (not org-treat-S-cursor-todo-selection-as-state-change))
16177 (org-inhibit-blocking
16178 (not org-treat-S-cursor-todo-selection-as-state-change)))
16179 (org-call-with-arg 'org-todo 'left)))
16180 ((or (and org-support-shift-select
16181 (not (eq org-support-shift-select 'always))
16182 (org-at-item-bullet-p))
16183 (and (not org-support-shift-select) (org-at-item-p)))
16184 (org-call-with-arg 'org-cycle-list-bullet 'previous))
16185 ((and (not (eq org-support-shift-select 'always))
16186 (org-at-property-p))
16187 (call-interactively 'org-property-previous-allowed-value))
16188 ((org-clocktable-try-shift 'left arg))
16189 (org-support-shift-select
16190 (org-call-for-shift-select 'backward-char))
16191 (t (org-shiftselect-error))))
16193 (defun org-shiftcontrolright ()
16194 "Switch to next TODO set."
16195 (interactive)
16196 (cond
16197 ((and org-support-shift-select (org-region-active-p))
16198 (org-call-for-shift-select 'forward-word))
16199 ((and (not (eq org-support-shift-select 'always))
16200 (org-on-heading-p))
16201 (org-call-with-arg 'org-todo 'nextset))
16202 (org-support-shift-select
16203 (org-call-for-shift-select 'forward-word))
16204 (t (org-shiftselect-error))))
16206 (defun org-shiftcontrolleft ()
16207 "Switch to previous TODO set."
16208 (interactive)
16209 (cond
16210 ((and org-support-shift-select (org-region-active-p))
16211 (org-call-for-shift-select 'backward-word))
16212 ((and (not (eq org-support-shift-select 'always))
16213 (org-on-heading-p))
16214 (org-call-with-arg 'org-todo 'previousset))
16215 (org-support-shift-select
16216 (org-call-for-shift-select 'backward-word))
16217 (t (org-shiftselect-error))))
16219 (defun org-ctrl-c-ret ()
16220 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
16221 (interactive)
16222 (cond
16223 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
16224 (t (call-interactively 'org-insert-heading))))
16226 (defun org-copy-special ()
16227 "Copy region in table or copy current subtree.
16228 Calls `org-table-copy' or `org-copy-subtree', depending on context.
16229 See the individual commands for more information."
16230 (interactive)
16231 (call-interactively
16232 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
16234 (defun org-cut-special ()
16235 "Cut region in table or cut current subtree.
16236 Calls `org-table-copy' or `org-cut-subtree', depending on context.
16237 See the individual commands for more information."
16238 (interactive)
16239 (call-interactively
16240 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
16242 (defun org-paste-special (arg)
16243 "Paste rectangular region into table, or past subtree relative to level.
16244 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
16245 See the individual commands for more information."
16246 (interactive "P")
16247 (if (org-at-table-p)
16248 (org-table-paste-rectangle)
16249 (org-paste-subtree arg)))
16251 (defun org-edit-special ()
16252 "Call a special editor for the stuff at point.
16253 When at a table, call the formula editor with `org-table-edit-formulas'.
16254 When at the first line of an src example, call `org-edit-src-code'.
16255 When in an #+include line, visit the include file. Otherwise call
16256 `ffap' to visit the file at point."
16257 (interactive)
16258 (cond
16259 ((org-at-table.el-p)
16260 (org-edit-src-code))
16261 ((org-at-table-p)
16262 (call-interactively 'org-table-edit-formulas))
16263 ((save-excursion
16264 (beginning-of-line 1)
16265 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
16266 (find-file (org-trim (match-string 1))))
16267 ((org-edit-src-code))
16268 ((org-edit-fixed-width-region))
16269 (t (call-interactively 'ffap))))
16272 (defun org-ctrl-c-ctrl-c (&optional arg)
16273 "Set tags in headline, or update according to changed information at point.
16275 This command does many different things, depending on context:
16277 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
16278 this is what we do.
16280 - If the cursor is on a statistics cookie, update it.
16282 - If the cursor is in a headline, prompt for tags and insert them
16283 into the current line, aligned to `org-tags-column'. When called
16284 with prefix arg, realign all tags in the current buffer.
16286 - If the cursor is in one of the special #+KEYWORD lines, this
16287 triggers scanning the buffer for these lines and updating the
16288 information.
16290 - If the cursor is inside a table, realign the table. This command
16291 works even if the automatic table editor has been turned off.
16293 - If the cursor is on a #+TBLFM line, re-apply the formulas to
16294 the entire table.
16296 - If the cursor is at a footnote reference or definition, jump to
16297 the corresponding definition or references, respectively.
16299 - If the cursor is a the beginning of a dynamic block, update it.
16301 - If the current buffer is a remember buffer, close note and file
16302 it. A prefix argument of 1 files to the default location
16303 without further interaction. A prefix argument of 2 files to
16304 the currently clocking task.
16306 - If the cursor is on a <<<target>>>, update radio targets and corresponding
16307 links in this buffer.
16309 - If the cursor is on a numbered item in a plain list, renumber the
16310 ordered list.
16312 - If the cursor is on a checkbox, toggle it."
16313 (interactive "P")
16314 (let ((org-enable-table-editor t))
16315 (cond
16316 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
16317 org-occur-highlights
16318 org-latex-fragment-image-overlays)
16319 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
16320 (org-remove-occur-highlights)
16321 (org-remove-latex-fragment-image-overlays)
16322 (message "Temporary highlights/overlays removed from current buffer"))
16323 ((and (local-variable-p 'org-finish-function (current-buffer))
16324 (fboundp org-finish-function))
16325 (funcall org-finish-function))
16326 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
16327 ((or (looking-at org-property-start-re)
16328 (org-at-property-p))
16329 (call-interactively 'org-property-action))
16330 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
16331 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
16332 (or (org-on-heading-p) (org-at-item-p)))
16333 (call-interactively 'org-update-statistics-cookies))
16334 ((org-on-heading-p) (call-interactively 'org-set-tags))
16335 ((org-at-table.el-p)
16336 (message "Use C-c ' to edit table.el tables"))
16337 ((org-at-table-p)
16338 (org-table-maybe-eval-formula)
16339 (if arg
16340 (call-interactively 'org-table-recalculate)
16341 (org-table-maybe-recalculate-line))
16342 (call-interactively 'org-table-align))
16343 ((or (org-footnote-at-reference-p)
16344 (org-footnote-at-definition-p))
16345 (call-interactively 'org-footnote-action))
16346 ((org-at-item-checkbox-p)
16347 (call-interactively 'org-toggle-checkbox))
16348 ((org-at-item-p)
16349 (if arg
16350 (call-interactively 'org-toggle-checkbox)
16351 (call-interactively 'org-maybe-renumber-ordered-list)))
16352 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
16353 ;; Dynamic block
16354 (beginning-of-line 1)
16355 (save-excursion (org-update-dblock)))
16356 ((save-excursion
16357 (beginning-of-line 1)
16358 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
16359 (cond
16360 ((equal (match-string 1) "TBLFM")
16361 ;; Recalculate the table before this line
16362 (save-excursion
16363 (beginning-of-line 1)
16364 (skip-chars-backward " \r\n\t")
16365 (if (org-at-table-p)
16366 (org-call-with-arg 'org-table-recalculate (or arg t)))))
16368 (let ((org-inhibit-startup-visibility-stuff t)
16369 (org-startup-align-all-tables nil))
16370 (org-save-outline-visibility 'use-markers (org-mode-restart)))
16371 (message "Local setup has been refreshed"))))
16372 ((org-clock-update-time-maybe))
16373 (t (error "C-c C-c can do nothing useful at this location")))))
16375 (defun org-mode-restart ()
16376 "Restart Org-mode, to scan again for special lines.
16377 Also updates the keyword regular expressions."
16378 (interactive)
16379 (org-mode)
16380 (message "Org-mode restarted"))
16382 (defun org-kill-note-or-show-branches ()
16383 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
16384 (interactive)
16385 (if (not org-finish-function)
16386 (call-interactively 'show-branches)
16387 (let ((org-note-abort t))
16388 (funcall org-finish-function))))
16390 (defun org-return (&optional indent)
16391 "Goto next table row or insert a newline.
16392 Calls `org-table-next-row' or `newline', depending on context.
16393 See the individual commands for more information."
16394 (interactive)
16395 (cond
16396 ((bobp) (if indent (newline-and-indent) (newline)))
16397 ((org-at-table-p)
16398 (org-table-justify-field-maybe)
16399 (call-interactively 'org-table-next-row))
16400 ((and org-return-follows-link
16401 (eq (get-text-property (point) 'face) 'org-link))
16402 (call-interactively 'org-open-at-point))
16403 ((and (org-at-heading-p)
16404 (looking-at
16405 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
16406 (org-show-entry)
16407 (end-of-line 1)
16408 (newline))
16409 (t (if indent (newline-and-indent) (newline)))))
16411 (defun org-return-indent ()
16412 "Goto next table row or insert a newline and indent.
16413 Calls `org-table-next-row' or `newline-and-indent', depending on
16414 context. See the individual commands for more information."
16415 (interactive)
16416 (org-return t))
16418 (defun org-ctrl-c-star ()
16419 "Compute table, or change heading status of lines.
16420 Calls `org-table-recalculate' or `org-toggle-heading',
16421 depending on context."
16422 (interactive)
16423 (cond
16424 ((org-at-table-p)
16425 (call-interactively 'org-table-recalculate))
16427 ;; Convert all lines in region to list items
16428 (call-interactively 'org-toggle-heading))))
16430 (defun org-ctrl-c-minus ()
16431 "Insert separator line in table or modify bullet status of line.
16432 Also turns a plain line or a region of lines into list items.
16433 Calls `org-table-insert-hline', `org-toggle-item', or
16434 `org-cycle-list-bullet', depending on context."
16435 (interactive)
16436 (cond
16437 ((org-at-table-p)
16438 (call-interactively 'org-table-insert-hline))
16439 ((org-region-active-p)
16440 (call-interactively 'org-toggle-item))
16441 ((org-in-item-p)
16442 (call-interactively 'org-cycle-list-bullet))
16444 (call-interactively 'org-toggle-item))))
16446 (defun org-toggle-item ()
16447 "Convert headings or normal lines to items, items to normal lines.
16448 If there is no active region, only the current line is considered.
16450 If the first line in the region is a headline, convert all headlines to items.
16452 If the first line in the region is an item, convert all items to normal lines.
16454 If the first line is normal text, add an item bullet to each line."
16455 (interactive)
16456 (let (l2 l beg end)
16457 (if (org-region-active-p)
16458 (setq beg (region-beginning) end (region-end))
16459 (setq beg (point-at-bol)
16460 end (min (1+ (point-at-eol)) (point-max))))
16461 (save-excursion
16462 (goto-char end)
16463 (setq l2 (org-current-line))
16464 (goto-char beg)
16465 (beginning-of-line 1)
16466 (setq l (1- (org-current-line)))
16467 (if (org-at-item-p)
16468 ;; We already have items, de-itemize
16469 (while (< (setq l (1+ l)) l2)
16470 (when (org-at-item-p)
16471 (goto-char (match-beginning 2))
16472 (delete-region (match-beginning 2) (match-end 2))
16473 (and (looking-at "[ \t]+") (replace-match "")))
16474 (beginning-of-line 2))
16475 (if (org-on-heading-p)
16476 ;; Headings, convert to items
16477 (while (< (setq l (1+ l)) l2)
16478 (if (looking-at org-outline-regexp)
16479 (replace-match "- " t t))
16480 (beginning-of-line 2))
16481 ;; normal lines, turn them into items
16482 (while (< (setq l (1+ l)) l2)
16483 (unless (org-at-item-p)
16484 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16485 (replace-match "\\1- \\2")))
16486 (beginning-of-line 2)))))))
16488 (defun org-toggle-heading (&optional nstars)
16489 "Convert headings to normal text, or items or text to headings.
16490 If there is no active region, only the current line is considered.
16492 If the first line is a heading, remove the stars from all headlines
16493 in the region.
16495 If the first line is a plain list item, turn all plain list items
16496 into headings.
16498 If the first line is a normal line, turn each and every line in the
16499 region into a heading.
16501 When converting a line into a heading, the number of stars is chosen
16502 such that the lines become children of the current entry. However,
16503 when a prefix argument is given, its value determines the number of
16504 stars to add."
16505 (interactive "P")
16506 (let (l2 l itemp beg end)
16507 (if (org-region-active-p)
16508 (setq beg (region-beginning) end (region-end))
16509 (setq beg (point-at-bol)
16510 end (min (1+ (point-at-eol)) (point-max))))
16511 (save-excursion
16512 (goto-char end)
16513 (setq l2 (org-current-line))
16514 (goto-char beg)
16515 (beginning-of-line 1)
16516 (setq l (1- (org-current-line)))
16517 (if (org-on-heading-p)
16518 ;; We already have headlines, de-star them
16519 (while (< (setq l (1+ l)) l2)
16520 (when (org-on-heading-p t)
16521 (and (looking-at outline-regexp) (replace-match "")))
16522 (beginning-of-line 2))
16523 (setq itemp (org-at-item-p))
16524 (let* ((stars
16525 (if nstars
16526 (make-string (prefix-numeric-value current-prefix-arg)
16528 (save-excursion
16529 (if (re-search-backward org-complex-heading-regexp nil t)
16530 (match-string 1) ""))))
16531 (add-stars (cond (nstars "")
16532 ((equal stars "") "*")
16533 (org-odd-levels-only "**")
16534 (t "*")))
16535 (rpl (concat stars add-stars " ")))
16536 (while (< (setq l (1+ l)) l2)
16537 (if itemp
16538 (and (org-at-item-p) (replace-match rpl t t))
16539 (unless (org-on-heading-p)
16540 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16541 (replace-match (concat rpl (match-string 2))))))
16542 (beginning-of-line 2)))))))
16544 (defun org-meta-return (&optional arg)
16545 "Insert a new heading or wrap a region in a table.
16546 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16547 See the individual commands for more information."
16548 (interactive "P")
16549 (cond
16550 ((run-hook-with-args-until-success 'org-metareturn-hook))
16551 ((org-at-table-p)
16552 (call-interactively 'org-table-wrap-region))
16553 (t (call-interactively 'org-insert-heading))))
16555 ;;; Menu entries
16557 ;; Define the Org-mode menus
16558 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16559 '("Tbl"
16560 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
16561 ["Next Field" org-cycle (org-at-table-p)]
16562 ["Previous Field" org-shifttab (org-at-table-p)]
16563 ["Next Row" org-return (org-at-table-p)]
16564 "--"
16565 ["Blank Field" org-table-blank-field (org-at-table-p)]
16566 ["Edit Field" org-table-edit-field (org-at-table-p)]
16567 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16568 "--"
16569 ("Column"
16570 ["Move Column Left" org-metaleft (org-at-table-p)]
16571 ["Move Column Right" org-metaright (org-at-table-p)]
16572 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16573 ["Insert Column" org-shiftmetaright (org-at-table-p)])
16574 ("Row"
16575 ["Move Row Up" org-metaup (org-at-table-p)]
16576 ["Move Row Down" org-metadown (org-at-table-p)]
16577 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16578 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16579 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16580 "--"
16581 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
16582 ("Rectangle"
16583 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16584 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16585 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16586 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16587 "--"
16588 ("Calculate"
16589 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16590 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16591 ["Edit Formulas" org-edit-special (org-at-table-p)]
16592 "--"
16593 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16594 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16595 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
16596 "--"
16597 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16598 "--"
16599 ["Sum Column/Rectangle" org-table-sum
16600 (or (org-at-table-p) (org-region-active-p))]
16601 ["Which Column?" org-table-current-column (org-at-table-p)])
16602 ["Debug Formulas"
16603 org-table-toggle-formula-debugger
16604 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
16605 ["Show Col/Row Numbers"
16606 org-table-toggle-coordinate-overlays
16607 :style toggle
16608 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
16609 "--"
16610 ["Create" org-table-create (and (not (org-at-table-p))
16611 org-enable-table-editor)]
16612 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16613 ["Import from File" org-table-import (not (org-at-table-p))]
16614 ["Export to File" org-table-export (org-at-table-p)]
16615 "--"
16616 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16618 (easy-menu-define org-org-menu org-mode-map "Org menu"
16619 '("Org"
16620 ("Show/Hide"
16621 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
16622 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
16623 ["Sparse Tree..." org-sparse-tree t]
16624 ["Reveal Context" org-reveal t]
16625 ["Show All" show-all t]
16626 "--"
16627 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
16628 "--"
16629 ["New Heading" org-insert-heading t]
16630 ("Navigate Headings"
16631 ["Up" outline-up-heading t]
16632 ["Next" outline-next-visible-heading t]
16633 ["Previous" outline-previous-visible-heading t]
16634 ["Next Same Level" outline-forward-same-level t]
16635 ["Previous Same Level" outline-backward-same-level t]
16636 "--"
16637 ["Jump" org-goto t])
16638 ("Edit Structure"
16639 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16640 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16641 "--"
16642 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16643 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16644 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16645 "--"
16646 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
16647 "--"
16648 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16649 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16650 ["Demote Heading" org-metaright (not (org-at-table-p))]
16651 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16652 "--"
16653 ["Sort Region/Children" org-sort (not (org-at-table-p))]
16654 "--"
16655 ["Convert to odd levels" org-convert-to-odd-levels t]
16656 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16657 ("Editing"
16658 ["Emphasis..." org-emphasize t]
16659 ["Edit Source Example" org-edit-special t]
16660 "--"
16661 ["Footnote new/jump" org-footnote-action t]
16662 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
16663 ("Archive"
16664 ["Archive (default method)" org-archive-subtree-default t]
16665 "--"
16666 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
16667 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16668 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
16670 "--"
16671 ("Hyperlinks"
16672 ["Store Link (Global)" org-store-link t]
16673 ["Find existing link to here" org-occur-link-in-agenda-files t]
16674 ["Insert Link" org-insert-link t]
16675 ["Follow Link" org-open-at-point t]
16676 "--"
16677 ["Next link" org-next-link t]
16678 ["Previous link" org-previous-link t]
16679 "--"
16680 ["Descriptive Links"
16681 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16682 :style radio
16683 :selected (member '(org-link) buffer-invisibility-spec)]
16684 ["Literal Links"
16685 (progn
16686 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16687 :style radio
16688 :selected (not (member '(org-link) buffer-invisibility-spec))])
16689 "--"
16690 ("TODO Lists"
16691 ["TODO/DONE/-" org-todo t]
16692 ("Select keyword"
16693 ["Next keyword" org-shiftright (org-on-heading-p)]
16694 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16695 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
16696 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
16697 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
16698 ["Show TODO Tree" org-show-todo-tree t]
16699 ["Global TODO list" org-todo-list t]
16700 "--"
16701 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
16702 :selected org-enforce-todo-dependencies :style toggle :active t]
16703 "Settings for tree at point"
16704 ["Do Children sequentially" org-toggle-ordered-property :style radio
16705 :selected (ignore-errors (org-entry-get nil "ORDERED"))
16706 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16707 ["Do Children parallel" org-toggle-ordered-property :style radio
16708 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
16709 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16710 "--"
16711 ["Set Priority" org-priority t]
16712 ["Priority Up" org-shiftup t]
16713 ["Priority Down" org-shiftdown t]
16714 "--"
16715 ["Get news from all feeds" org-feed-update-all t]
16716 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16717 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16718 ("TAGS and Properties"
16719 ["Set Tags" org-set-tags-command t]
16720 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16721 "--"
16722 ["Set property" org-set-property t]
16723 ["Column view of properties" org-columns t]
16724 ["Insert Column View DBlock" org-insert-columns-dblock t])
16725 ("Dates and Scheduling"
16726 ["Timestamp" org-time-stamp t]
16727 ["Timestamp (inactive)" org-time-stamp-inactive t]
16728 ("Change Date"
16729 ["1 Day Later" org-shiftright t]
16730 ["1 Day Earlier" org-shiftleft t]
16731 ["1 ... Later" org-shiftup t]
16732 ["1 ... Earlier" org-shiftdown t])
16733 ["Compute Time Range" org-evaluate-time-range t]
16734 ["Schedule Item" org-schedule t]
16735 ["Deadline" org-deadline t]
16736 "--"
16737 ["Custom time format" org-toggle-time-stamp-overlays
16738 :style radio :selected org-display-custom-times]
16739 "--"
16740 ["Goto Calendar" org-goto-calendar t]
16741 ["Date from Calendar" org-date-from-calendar t]
16742 "--"
16743 ["Start/Restart Timer" org-timer-start t]
16744 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16745 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16746 ["Insert Timer String" org-timer t]
16747 ["Insert Timer Item" org-timer-item t])
16748 ("Logging work"
16749 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16750 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16751 ["Clock out" org-clock-out t]
16752 ["Clock cancel" org-clock-cancel t]
16753 "--"
16754 ["Mark as default task" org-clock-mark-default-task t]
16755 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16756 ["Goto running clock" org-clock-goto t]
16757 "--"
16758 ["Display times" org-clock-display t]
16759 ["Create clock table" org-clock-report t]
16760 "--"
16761 ["Record DONE time"
16762 (progn (setq org-log-done (not org-log-done))
16763 (message "Switching to %s will %s record a timestamp"
16764 (car org-done-keywords)
16765 (if org-log-done "automatically" "not")))
16766 :style toggle :selected org-log-done])
16767 "--"
16768 ["Agenda Command..." org-agenda t]
16769 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16770 ("File List for Agenda")
16771 ("Special views current file"
16772 ["TODO Tree" org-show-todo-tree t]
16773 ["Check Deadlines" org-check-deadlines t]
16774 ["Timeline" org-timeline t]
16775 ["Tags/Property tree" org-match-sparse-tree t])
16776 "--"
16777 ["Export/Publish..." org-export t]
16778 ("LaTeX"
16779 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16780 :selected org-cdlatex-mode]
16781 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16782 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16783 ["Modify math symbol" org-cdlatex-math-modify
16784 (org-inside-LaTeX-fragment-p)]
16785 ["Insert citation" org-reftex-citation t]
16786 "--"
16787 ["Export LaTeX fragments as images"
16788 (if (featurep 'org-exp)
16789 (setq org-export-with-LaTeX-fragments
16790 (not org-export-with-LaTeX-fragments))
16791 (require 'org-exp))
16792 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16793 org-export-with-LaTeX-fragments)]
16794 "--"
16795 ["Template for BEAMER" org-beamer-settings-template t])
16796 "--"
16797 ("MobileOrg"
16798 ["Push Files and Views" org-mobile-push t]
16799 ["Get Captured and Flagged" org-mobile-pull t]
16800 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16801 "--"
16802 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16803 "--"
16804 ("Documentation"
16805 ["Show Version" org-version t]
16806 ["Info Documentation" org-info t])
16807 ("Customize"
16808 ["Browse Org Group" org-customize t]
16809 "--"
16810 ["Expand This Menu" org-create-customize-menu
16811 (fboundp 'customize-menu-create)])
16812 ["Send bug report" org-submit-bug-report t]
16813 "--"
16814 ("Refresh/Reload"
16815 ["Refresh setup current buffer" org-mode-restart t]
16816 ["Reload Org (after update)" org-reload t]
16817 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16820 (defun org-info (&optional node)
16821 "Read documentation for Org-mode in the info system.
16822 With optional NODE, go directly to that node."
16823 (interactive)
16824 (info (format "(org)%s" (or node ""))))
16826 ;;;###autoload
16827 (defun org-submit-bug-report ()
16828 "Submit a bug report on Org-mode via mail.
16830 Don't hesitate to report any problems or inaccurate documentation.
16832 If you don't have setup sending mail from (X)Emacs, please copy the
16833 output buffer into your mail program, as it gives us important
16834 information about your Org-mode version and configuration."
16835 (interactive)
16836 (require 'reporter)
16837 (org-load-modules-maybe)
16838 (org-require-autoloaded-modules)
16839 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16840 (reporter-submit-bug-report
16841 "emacs-orgmode@gnu.org"
16842 (org-version)
16843 (let (list)
16844 (save-window-excursion
16845 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16846 (delete-other-windows)
16847 (erase-buffer)
16848 (insert "You are about to submit a bug report to the Org-mode mailing list.
16850 We would like to add your full Org-mode and Outline configuration to the
16851 bug report. This greatly simplifies the work of the maintainer and
16852 other experts on the mailing list.
16854 HOWEVER, some variables you have customized may contain private
16855 information. The names of customers, colleagues, or friends, might
16856 appear in the form of file names, tags, todo states, or search strings.
16857 If you answer yes to the prompt, you might want to check and remove
16858 such private information before sending the email.")
16859 (add-text-properties (point-min) (point-max) '(face org-warning))
16860 (when (yes-or-no-p "Include your Org-mode configuration ")
16861 (mapatoms
16862 (lambda (v)
16863 (and (boundp v)
16864 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16865 (or (and (symbol-value v)
16866 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16867 (and
16868 (get v 'custom-type) (get v 'standard-value)
16869 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16870 (push v list)))))
16871 (kill-buffer (get-buffer "*Warn about privacy*"))
16872 list))
16873 nil nil
16874 "Remember to cover the basics, that is, what you expected to happen and
16875 what in fact did happen. You don't know how to make a good report? See
16877 http://orgmode.org/manual/Feedback.html#Feedback
16879 Your bug report will be posted to the Org-mode mailing list.
16880 ------------------------------------------------------------------------")
16881 (save-excursion
16882 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16883 (replace-match "\\1Bug: \\3 [\\2]")))))
16886 (defun org-install-agenda-files-menu ()
16887 (let ((bl (buffer-list)))
16888 (save-excursion
16889 (while bl
16890 (set-buffer (pop bl))
16891 (if (org-mode-p) (setq bl nil)))
16892 (when (org-mode-p)
16893 (easy-menu-change
16894 '("Org") "File List for Agenda"
16895 (append
16896 (list
16897 ["Edit File List" (org-edit-agenda-file-list) t]
16898 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16899 ["Remove Current File from List" org-remove-file t]
16900 ["Cycle through agenda files" org-cycle-agenda-files t]
16901 ["Occur in all agenda files" org-occur-in-agenda-files t]
16902 "--")
16903 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16905 ;;;; Documentation
16907 ;;;###autoload
16908 (defun org-require-autoloaded-modules ()
16909 (interactive)
16910 (mapc 'require
16911 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16912 org-docbook org-exp org-html org-icalendar
16913 org-id org-latex
16914 org-publish org-remember org-table
16915 org-timer org-xoxo)))
16917 ;;;###autoload
16918 (defun org-reload (&optional uncompiled)
16919 "Reload all org lisp files.
16920 With prefix arg UNCOMPILED, load the uncompiled versions."
16921 (interactive "P")
16922 (require 'find-func)
16923 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16924 (dir-org (file-name-directory (org-find-library-name "org")))
16925 (dir-org-contrib (ignore-errors
16926 (file-name-directory
16927 (org-find-library-name "org-contribdir"))))
16928 (files
16929 (append (directory-files dir-org t file-re)
16930 (and dir-org-contrib
16931 (directory-files dir-org-contrib t file-re))))
16932 (remove-re (concat (if (featurep 'xemacs)
16933 "org-colview" "org-colview-xemacs")
16934 "\\'")))
16935 (setq files (mapcar 'file-name-sans-extension files))
16936 (setq files (mapcar
16937 (lambda (x) (if (string-match remove-re x) nil x))
16938 files))
16939 (setq files (delq nil files))
16940 (mapc
16941 (lambda (f)
16942 (when (featurep (intern (file-name-nondirectory f)))
16943 (if (and (not uncompiled)
16944 (file-exists-p (concat f ".elc")))
16945 (load (concat f ".elc") nil nil t)
16946 (load (concat f ".el") nil nil t))))
16947 files))
16948 (org-version))
16950 ;;;###autoload
16951 (defun org-customize ()
16952 "Call the customize function with org as argument."
16953 (interactive)
16954 (org-load-modules-maybe)
16955 (org-require-autoloaded-modules)
16956 (customize-browse 'org))
16958 (defun org-create-customize-menu ()
16959 "Create a full customization menu for Org-mode, insert it into the menu."
16960 (interactive)
16961 (org-load-modules-maybe)
16962 (org-require-autoloaded-modules)
16963 (if (fboundp 'customize-menu-create)
16964 (progn
16965 (easy-menu-change
16966 '("Org") "Customize"
16967 `(["Browse Org group" org-customize t]
16968 "--"
16969 ,(customize-menu-create 'org)
16970 ["Set" Custom-set t]
16971 ["Save" Custom-save t]
16972 ["Reset to Current" Custom-reset-current t]
16973 ["Reset to Saved" Custom-reset-saved t]
16974 ["Reset to Standard Settings" Custom-reset-standard t]))
16975 (message "\"Org\"-menu now contains full customization menu"))
16976 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16978 ;;;; Miscellaneous stuff
16980 ;;; Generally useful functions
16982 (defun org-get-at-bol (property)
16983 "Get text property PROPERTY at beginning of line."
16984 (get-text-property (point-at-bol) property))
16986 (defun org-find-text-property-in-string (prop s)
16987 "Return the first non-nil value of property PROP in string S."
16988 (or (get-text-property 0 prop s)
16989 (get-text-property (or (next-single-property-change 0 prop s) 0)
16990 prop s)))
16992 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16993 "Display the given MESSAGE as a warning."
16994 (if (fboundp 'display-warning)
16995 (display-warning 'org message
16996 (if (featurep 'xemacs)
16997 'warning
16998 :warning))
16999 (let ((buf (get-buffer-create "*Org warnings*")))
17000 (with-current-buffer buf
17001 (goto-char (point-max))
17002 (insert "Warning (Org): " message)
17003 (unless (bolp)
17004 (newline)))
17005 (display-buffer buf)
17006 (sit-for 0))))
17008 (defun org-in-commented-line ()
17009 "Is point in a line starting with `#'?"
17010 (equal (char-after (point-at-bol)) ?#))
17012 (defun org-in-verbatim-emphasis ()
17013 (save-match-data
17014 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
17016 (defun org-goto-marker-or-bmk (marker &optional bookmark)
17017 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
17018 (if (and marker (marker-buffer marker)
17019 (buffer-live-p (marker-buffer marker)))
17020 (progn
17021 (switch-to-buffer (marker-buffer marker))
17022 (if (or (> marker (point-max)) (< marker (point-min)))
17023 (widen))
17024 (goto-char marker)
17025 (org-show-context 'org-goto))
17026 (if bookmark
17027 (bookmark-jump bookmark)
17028 (error "Cannot find location"))))
17030 (defun org-quote-csv-field (s)
17031 "Quote field for inclusion in CSV material."
17032 (if (string-match "[\",]" s)
17033 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
17036 (defun org-plist-delete (plist property)
17037 "Delete PROPERTY from PLIST.
17038 This is in contrast to merely setting it to 0."
17039 (let (p)
17040 (while plist
17041 (if (not (eq property (car plist)))
17042 (setq p (plist-put p (car plist) (nth 1 plist))))
17043 (setq plist (cddr plist)))
17046 (defun org-force-self-insert (N)
17047 "Needed to enforce self-insert under remapping."
17048 (interactive "p")
17049 (self-insert-command N))
17051 (defun org-string-width (s)
17052 "Compute width of string, ignoring invisible characters.
17053 This ignores character with invisibility property `org-link', and also
17054 characters with property `org-cwidth', because these will become invisible
17055 upon the next fontification round."
17056 (let (b l)
17057 (when (or (eq t buffer-invisibility-spec)
17058 (assq 'org-link buffer-invisibility-spec))
17059 (while (setq b (text-property-any 0 (length s)
17060 'invisible 'org-link s))
17061 (setq s (concat (substring s 0 b)
17062 (substring s (or (next-single-property-change
17063 b 'invisible s) (length s)))))))
17064 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
17065 (setq s (concat (substring s 0 b)
17066 (substring s (or (next-single-property-change
17067 b 'org-cwidth s) (length s))))))
17068 (setq l (string-width s) b -1)
17069 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
17070 (setq l (- l (get-text-property b 'org-dwidth-n s))))
17073 (defun org-get-indentation (&optional line)
17074 "Get the indentation of the current line, interpreting tabs.
17075 When LINE is given, assume it represents a line and compute its indentation."
17076 (if line
17077 (if (string-match "^ *" (org-remove-tabs line))
17078 (match-end 0))
17079 (save-excursion
17080 (beginning-of-line 1)
17081 (skip-chars-forward " \t")
17082 (current-column))))
17084 (defun org-remove-tabs (s &optional width)
17085 "Replace tabulators in S with spaces.
17086 Assumes that s is a single line, starting in column 0."
17087 (setq width (or width tab-width))
17088 (while (string-match "\t" s)
17089 (setq s (replace-match
17090 (make-string
17091 (- (* width (/ (+ (match-beginning 0) width) width))
17092 (match-beginning 0)) ?\ )
17093 t t s)))
17096 (defun org-fix-indentation (line ind)
17097 "Fix indentation in LINE.
17098 IND is a cons cell with target and minimum indentation.
17099 If the current indentation in LINE is smaller than the minimum,
17100 leave it alone. If it is larger than ind, set it to the target."
17101 (let* ((l (org-remove-tabs line))
17102 (i (org-get-indentation l))
17103 (i1 (car ind)) (i2 (cdr ind)))
17104 (if (>= i i2) (setq l (substring line i2)))
17105 (if (> i1 0)
17106 (concat (make-string i1 ?\ ) l)
17107 l)))
17109 (defun org-remove-indentation (code &optional n)
17110 "Remove the maximum common indentation from the lines in CODE.
17111 N may optionally be the number of spaces to remove."
17112 (with-temp-buffer
17113 (insert code)
17114 (org-do-remove-indentation n)
17115 (buffer-string)))
17117 (defun org-do-remove-indentation (&optional n)
17118 "Remove the maximum common indentation from the buffer."
17119 (untabify (point-min) (point-max))
17120 (let ((min 10000) re)
17121 (if n
17122 (setq min n)
17123 (goto-char (point-min))
17124 (while (re-search-forward "^ *[^ \n]" nil t)
17125 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
17126 (unless (or (= min 0) (= min 10000))
17127 (setq re (format "^ \\{%d\\}" min))
17128 (goto-char (point-min))
17129 (while (re-search-forward re nil t)
17130 (replace-match "")
17131 (end-of-line 1))
17132 min)))
17134 (defun org-fill-template (template alist)
17135 "Find each %key of ALIST in TEMPLATE and replace it."
17136 (let ((case-fold-search nil)
17137 entry key value)
17138 (setq alist (sort (copy-sequence alist)
17139 (lambda (a b) (< (length (car a)) (length (car b))))))
17140 (while (setq entry (pop alist))
17141 (setq template
17142 (replace-regexp-in-string
17143 (concat "%" (regexp-quote (car entry)))
17144 (cdr entry) template t t)))
17145 template))
17147 (defun org-base-buffer (buffer)
17148 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
17149 (if (not buffer)
17150 buffer
17151 (or (buffer-base-buffer buffer)
17152 buffer)))
17154 (defun org-trim (s)
17155 "Remove whitespace at beginning and end of string."
17156 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
17157 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
17160 (defun org-wrap (string &optional width lines)
17161 "Wrap string to either a number of lines, or a width in characters.
17162 If WIDTH is non-nil, the string is wrapped to that width, however many lines
17163 that costs. If there is a word longer than WIDTH, the text is actually
17164 wrapped to the length of that word.
17165 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
17166 many lines, whatever width that takes.
17167 The return value is a list of lines, without newlines at the end."
17168 (let* ((words (org-split-string string "[ \t\n]+"))
17169 (maxword (apply 'max (mapcar 'org-string-width words)))
17170 w ll)
17171 (cond (width
17172 (org-do-wrap words (max maxword width)))
17173 (lines
17174 (setq w maxword)
17175 (setq ll (org-do-wrap words maxword))
17176 (if (<= (length ll) lines)
17178 (setq ll words)
17179 (while (> (length ll) lines)
17180 (setq w (1+ w))
17181 (setq ll (org-do-wrap words w)))
17182 ll))
17183 (t (error "Cannot wrap this")))))
17185 (defun org-do-wrap (words width)
17186 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
17187 (let (lines line)
17188 (while words
17189 (setq line (pop words))
17190 (while (and words (< (+ (length line) (length (car words))) width))
17191 (setq line (concat line " " (pop words))))
17192 (setq lines (push line lines)))
17193 (nreverse lines)))
17195 (defun org-split-string (string &optional separators)
17196 "Splits STRING into substrings at SEPARATORS.
17197 No empty strings are returned if there are matches at the beginning
17198 and end of string."
17199 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
17200 (start 0)
17201 notfirst
17202 (list nil))
17203 (while (and (string-match rexp string
17204 (if (and notfirst
17205 (= start (match-beginning 0))
17206 (< start (length string)))
17207 (1+ start) start))
17208 (< (match-beginning 0) (length string)))
17209 (setq notfirst t)
17210 (or (eq (match-beginning 0) 0)
17211 (and (eq (match-beginning 0) (match-end 0))
17212 (eq (match-beginning 0) start))
17213 (setq list
17214 (cons (substring string start (match-beginning 0))
17215 list)))
17216 (setq start (match-end 0)))
17217 (or (eq start (length string))
17218 (setq list
17219 (cons (substring string start)
17220 list)))
17221 (nreverse list)))
17223 (defun org-quote-vert (s)
17224 "Replace \"|\" with \"\\vert\"."
17225 (while (string-match "|" s)
17226 (setq s (replace-match "\\vert" t t s)))
17229 (defun org-uuidgen-p (s)
17230 "Is S an ID created by UUIDGEN?"
17231 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
17233 (defun org-context ()
17234 "Return a list of contexts of the current cursor position.
17235 If several contexts apply, all are returned.
17236 Each context entry is a list with a symbol naming the context, and
17237 two positions indicating start and end of the context. Possible
17238 contexts are:
17240 :headline anywhere in a headline
17241 :headline-stars on the leading stars in a headline
17242 :todo-keyword on a TODO keyword (including DONE) in a headline
17243 :tags on the TAGS in a headline
17244 :priority on the priority cookie in a headline
17245 :item on the first line of a plain list item
17246 :item-bullet on the bullet/number of a plain list item
17247 :checkbox on the checkbox in a plain list item
17248 :table in an org-mode table
17249 :table-special on a special filed in a table
17250 :table-table in a table.el table
17251 :link on a hyperlink
17252 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
17253 :target on a <<target>>
17254 :radio-target on a <<<radio-target>>>
17255 :latex-fragment on a LaTeX fragment
17256 :latex-preview on a LaTeX fragment with overlayed preview image
17258 This function expects the position to be visible because it uses font-lock
17259 faces as a help to recognize the following contexts: :table-special, :link,
17260 and :keyword."
17261 (let* ((f (get-text-property (point) 'face))
17262 (faces (if (listp f) f (list f)))
17263 (p (point)) clist o)
17264 ;; First the large context
17265 (cond
17266 ((org-on-heading-p t)
17267 (push (list :headline (point-at-bol) (point-at-eol)) clist)
17268 (when (progn
17269 (beginning-of-line 1)
17270 (looking-at org-todo-line-tags-regexp))
17271 (push (org-point-in-group p 1 :headline-stars) clist)
17272 (push (org-point-in-group p 2 :todo-keyword) clist)
17273 (push (org-point-in-group p 4 :tags) clist))
17274 (goto-char p)
17275 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
17276 (if (looking-at "\\[#[A-Z0-9]\\]")
17277 (push (org-point-in-group p 0 :priority) clist)))
17279 ((org-at-item-p)
17280 (push (org-point-in-group p 2 :item-bullet) clist)
17281 (push (list :item (point-at-bol)
17282 (save-excursion (org-end-of-item) (point)))
17283 clist)
17284 (and (org-at-item-checkbox-p)
17285 (push (org-point-in-group p 0 :checkbox) clist)))
17287 ((org-at-table-p)
17288 (push (list :table (org-table-begin) (org-table-end)) clist)
17289 (if (memq 'org-formula faces)
17290 (push (list :table-special
17291 (previous-single-property-change p 'face)
17292 (next-single-property-change p 'face)) clist)))
17293 ((org-at-table-p 'any)
17294 (push (list :table-table) clist)))
17295 (goto-char p)
17297 ;; Now the small context
17298 (cond
17299 ((org-at-timestamp-p)
17300 (push (org-point-in-group p 0 :timestamp) clist))
17301 ((memq 'org-link faces)
17302 (push (list :link
17303 (previous-single-property-change p 'face)
17304 (next-single-property-change p 'face)) clist))
17305 ((memq 'org-special-keyword faces)
17306 (push (list :keyword
17307 (previous-single-property-change p 'face)
17308 (next-single-property-change p 'face)) clist))
17309 ((org-on-target-p)
17310 (push (org-point-in-group p 0 :target) clist)
17311 (goto-char (1- (match-beginning 0)))
17312 (if (looking-at org-radio-target-regexp)
17313 (push (org-point-in-group p 0 :radio-target) clist))
17314 (goto-char p))
17315 ((setq o (car (delq nil
17316 (mapcar
17317 (lambda (x)
17318 (if (memq x org-latex-fragment-image-overlays) x))
17319 (org-overlays-at (point))))))
17320 (push (list :latex-fragment
17321 (overlay-start o) (overlay-end o)) clist)
17322 (push (list :latex-preview
17323 (overlay-start o) (overlay-end o)) clist))
17324 ((org-inside-LaTeX-fragment-p)
17325 ;; FIXME: positions wrong.
17326 (push (list :latex-fragment (point) (point)) clist)))
17328 (setq clist (nreverse (delq nil clist)))
17329 clist))
17331 ;; FIXME: Compare with at-regexp-p Do we need both?
17332 (defun org-in-regexp (re &optional nlines visually)
17333 "Check if point is inside a match of regexp.
17334 Normally only the current line is checked, but you can include NLINES extra
17335 lines both before and after point into the search.
17336 If VISUALLY is set, require that the cursor is not after the match but
17337 really on, so that the block visually is on the match."
17338 (catch 'exit
17339 (let ((pos (point))
17340 (eol (point-at-eol (+ 1 (or nlines 0))))
17341 (inc (if visually 1 0)))
17342 (save-excursion
17343 (beginning-of-line (- 1 (or nlines 0)))
17344 (while (re-search-forward re eol t)
17345 (if (and (<= (match-beginning 0) pos)
17346 (>= (+ inc (match-end 0)) pos))
17347 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
17349 (defun org-at-regexp-p (regexp)
17350 "Is point inside a match of REGEXP in the current line?"
17351 (catch 'exit
17352 (save-excursion
17353 (let ((pos (point)) (end (point-at-eol)))
17354 (beginning-of-line 1)
17355 (while (re-search-forward regexp end t)
17356 (if (and (<= (match-beginning 0) pos)
17357 (>= (match-end 0) pos))
17358 (throw 'exit t)))
17359 nil))))
17361 (defun org-in-regexps-block-p (start-re end-re)
17362 "Returns t if the current point is between matches of START-RE and END-RE.
17363 This will also return to if point is on one of the two matches."
17364 (interactive)
17365 (let ((p (point)))
17366 (save-excursion
17367 (and (or (org-at-regexp-p start-re)
17368 (re-search-backward start-re nil t))
17369 (re-search-forward end-re nil t)
17370 (>= (point) p)))))
17372 (defun org-occur-in-agenda-files (regexp &optional nlines)
17373 "Call `multi-occur' with buffers for all agenda files."
17374 (interactive "sOrg-files matching: \np")
17375 (let* ((files (org-agenda-files))
17376 (tnames (mapcar 'file-truename files))
17377 (extra org-agenda-text-search-extra-files)
17379 (when (eq (car extra) 'agenda-archives)
17380 (setq extra (cdr extra))
17381 (setq files (org-add-archive-files files)))
17382 (while (setq f (pop extra))
17383 (unless (member (file-truename f) tnames)
17384 (add-to-list 'files f 'append)
17385 (add-to-list 'tnames (file-truename f) 'append)))
17386 (multi-occur
17387 (mapcar (lambda (x)
17388 (with-current-buffer
17389 (or (get-file-buffer x) (find-file-noselect x))
17390 (widen)
17391 (current-buffer)))
17392 files)
17393 regexp)))
17395 (if (boundp 'occur-mode-find-occurrence-hook)
17396 ;; Emacs 23
17397 (add-hook 'occur-mode-find-occurrence-hook
17398 (lambda ()
17399 (when (org-mode-p)
17400 (org-reveal))))
17401 ;; Emacs 22
17402 (defadvice occur-mode-goto-occurrence
17403 (after org-occur-reveal activate)
17404 (and (org-mode-p) (org-reveal)))
17405 (defadvice occur-mode-goto-occurrence-other-window
17406 (after org-occur-reveal activate)
17407 (and (org-mode-p) (org-reveal)))
17408 (defadvice occur-mode-display-occurrence
17409 (after org-occur-reveal activate)
17410 (when (org-mode-p)
17411 (let ((pos (occur-mode-find-occurrence)))
17412 (with-current-buffer (marker-buffer pos)
17413 (save-excursion
17414 (goto-char pos)
17415 (org-reveal)))))))
17417 (defun org-occur-link-in-agenda-files ()
17418 "Create a link and search for it in the agendas.
17419 The link is not stored in `org-stored-links', it is just created
17420 for the search purpose."
17421 (interactive)
17422 (let ((link (condition-case nil
17423 (org-store-link nil)
17424 (error "Unable to create a link to here"))))
17425 (org-occur-in-agenda-files (regexp-quote link))))
17427 (defun org-uniquify (list)
17428 "Remove duplicate elements from LIST."
17429 (let (res)
17430 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
17431 res))
17433 (defun org-delete-all (elts list)
17434 "Remove all elements in ELTS from LIST."
17435 (while elts
17436 (setq list (delete (pop elts) list)))
17437 list)
17439 (defun org-remove-if (predicate seq)
17440 "Remove everything from SEQ that fulfills PREDICATE."
17441 (let (res e)
17442 (while seq
17443 (setq e (pop seq))
17444 (if (not (funcall predicate e)) (push e res)))
17445 (nreverse res)))
17447 (defun org-remove-if-not (predicate seq)
17448 "Remove everything from SEQ that does not fulfill PREDICATE."
17449 (let (res e)
17450 (while seq
17451 (setq e (pop seq))
17452 (if (funcall predicate e) (push e res)))
17453 (nreverse res)))
17455 (defun org-back-over-empty-lines ()
17456 "Move backwards over whitespace, to the beginning of the first empty line.
17457 Returns the number of empty lines passed."
17458 (let ((pos (point)))
17459 (skip-chars-backward " \t\n\r")
17460 (beginning-of-line 2)
17461 (goto-char (min (point) pos))
17462 (count-lines (point) pos)))
17464 (defun org-skip-whitespace ()
17465 (skip-chars-forward " \t\n\r"))
17467 (defun org-point-in-group (point group &optional context)
17468 "Check if POINT is in match-group GROUP.
17469 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
17470 match. If the match group does ot exist or point is not inside it,
17471 return nil."
17472 (and (match-beginning group)
17473 (>= point (match-beginning group))
17474 (<= point (match-end group))
17475 (if context
17476 (list context (match-beginning group) (match-end group))
17477 t)))
17479 (defun org-switch-to-buffer-other-window (&rest args)
17480 "Switch to buffer in a second window on the current frame.
17481 In particular, do not allow pop-up frames."
17482 (let (pop-up-frames special-display-buffer-names special-display-regexps
17483 special-display-function)
17484 (apply 'switch-to-buffer-other-window args)))
17486 (defun org-combine-plists (&rest plists)
17487 "Create a single property list from all plists in PLISTS.
17488 The process starts by copying the first list, and then setting properties
17489 from the other lists. Settings in the last list are the most significant
17490 ones and overrule settings in the other lists."
17491 (let ((rtn (copy-sequence (pop plists)))
17492 p v ls)
17493 (while plists
17494 (setq ls (pop plists))
17495 (while ls
17496 (setq p (pop ls) v (pop ls))
17497 (setq rtn (plist-put rtn p v))))
17498 rtn))
17500 (defun org-move-line-down (arg)
17501 "Move the current line down. With prefix argument, move it past ARG lines."
17502 (interactive "p")
17503 (let ((col (current-column))
17504 beg end pos)
17505 (beginning-of-line 1) (setq beg (point))
17506 (beginning-of-line 2) (setq end (point))
17507 (beginning-of-line (+ 1 arg))
17508 (setq pos (move-marker (make-marker) (point)))
17509 (insert (delete-and-extract-region beg end))
17510 (goto-char pos)
17511 (org-move-to-column col)))
17513 (defun org-move-line-up (arg)
17514 "Move the current line up. With prefix argument, move it past ARG lines."
17515 (interactive "p")
17516 (let ((col (current-column))
17517 beg end pos)
17518 (beginning-of-line 1) (setq beg (point))
17519 (beginning-of-line 2) (setq end (point))
17520 (beginning-of-line (- arg))
17521 (setq pos (move-marker (make-marker) (point)))
17522 (insert (delete-and-extract-region beg end))
17523 (goto-char pos)
17524 (org-move-to-column col)))
17526 (defun org-replace-escapes (string table)
17527 "Replace %-escapes in STRING with values in TABLE.
17528 TABLE is an association list with keys like \"%a\" and string values.
17529 The sequences in STRING may contain normal field width and padding information,
17530 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
17531 so values can contain further %-escapes if they are define later in TABLE."
17532 (let ((case-fold-search nil)
17533 e re rpl)
17534 (while (setq e (pop table))
17535 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
17536 (while (string-match re string)
17537 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
17538 (cdr e)))
17539 (setq string (replace-match rpl t t string))))
17540 string))
17543 (defun org-sublist (list start end)
17544 "Return a section of LIST, from START to END.
17545 Counting starts at 1."
17546 (let (rtn (c start))
17547 (setq list (nthcdr (1- start) list))
17548 (while (and list (<= c end))
17549 (push (pop list) rtn)
17550 (setq c (1+ c)))
17551 (nreverse rtn)))
17553 (defun org-find-base-buffer-visiting (file)
17554 "Like `find-buffer-visiting' but always return the base buffer and
17555 not an indirect buffer."
17556 (let ((buf (or (get-file-buffer file)
17557 (find-buffer-visiting file))))
17558 (if buf
17559 (or (buffer-base-buffer buf) buf)
17560 nil)))
17562 (defun org-image-file-name-regexp (&optional extensions)
17563 "Return regexp matching the file names of images.
17564 If EXTENSIONS is given, only match these."
17565 (if (and (not extensions) (fboundp 'image-file-name-regexp))
17566 (image-file-name-regexp)
17567 (let ((image-file-name-extensions
17568 (or extensions
17569 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
17570 "xbm" "xpm" "pbm" "pgm" "ppm"))))
17571 (concat "\\."
17572 (regexp-opt (nconc (mapcar 'upcase
17573 image-file-name-extensions)
17574 image-file-name-extensions)
17576 "\\'"))))
17578 (defun org-file-image-p (file &optional extensions)
17579 "Return non-nil if FILE is an image."
17580 (save-match-data
17581 (string-match (org-image-file-name-regexp extensions) file)))
17583 (defun org-get-cursor-date ()
17584 "Return the date at cursor in as a time.
17585 This works in the calendar and in the agenda, anywhere else it just
17586 returns the current time."
17587 (let (date day defd)
17588 (cond
17589 ((eq major-mode 'calendar-mode)
17590 (setq date (calendar-cursor-to-date)
17591 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17592 ((eq major-mode 'org-agenda-mode)
17593 (setq day (get-text-property (point) 'day))
17594 (if day
17595 (setq date (calendar-gregorian-from-absolute day)
17596 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
17597 (nth 2 date))))))
17598 (or defd (current-time))))
17600 (defvar org-agenda-action-marker (make-marker)
17601 "Marker pointing to the entry for the next agenda action.")
17603 (defun org-mark-entry-for-agenda-action ()
17604 "Mark the current entry as target of an agenda action.
17605 Agenda actions are actions executed from the agenda with the key `k',
17606 which make use of the date at the cursor."
17607 (interactive)
17608 (move-marker org-agenda-action-marker
17609 (save-excursion (org-back-to-heading t) (point))
17610 (current-buffer))
17611 (message
17612 "Entry marked for action; press `k' at desired date in agenda or calendar"))
17614 ;;; Paragraph filling stuff.
17615 ;; We want this to be just right, so use the full arsenal.
17617 (defun org-indent-line-function ()
17618 "Indent line like previous, but further if previous was headline or item."
17619 (interactive)
17620 (let* ((pos (point))
17621 (itemp (org-at-item-p))
17622 (case-fold-search t)
17623 (org-drawer-regexp (or org-drawer-regexp "\000"))
17624 column bpos bcol tpos tcol bullet btype bullet-type)
17625 ;; Find the previous relevant line
17626 (beginning-of-line 1)
17627 (cond
17628 ((looking-at "#") (setq column 0))
17629 ((looking-at "\\*+ ") (setq column 0))
17630 ((and (looking-at "[ \t]*:END:")
17631 (save-excursion (re-search-backward org-drawer-regexp nil t)))
17632 (save-excursion
17633 (goto-char (1- (match-beginning 1)))
17634 (setq column (current-column))))
17635 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
17636 (save-excursion
17637 (re-search-backward
17638 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
17639 (setq column (org-get-indentation (match-string 0))))
17641 (beginning-of-line 0)
17642 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
17643 (not (looking-at "[ \t]*:END:"))
17644 (not (looking-at org-drawer-regexp)))
17645 (beginning-of-line 0))
17646 (cond
17647 ((looking-at "\\*+[ \t]+")
17648 (if (not org-adapt-indentation)
17649 (setq column 0)
17650 (goto-char (match-end 0))
17651 (setq column (current-column))))
17652 ((looking-at org-drawer-regexp)
17653 (goto-char (1- (match-beginning 1)))
17654 (setq column (current-column)))
17655 ((looking-at "\\([ \t]*\\):END:")
17656 (goto-char (match-end 1))
17657 (setq column (current-column)))
17658 ((org-in-item-p)
17659 (org-beginning-of-item)
17660 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
17661 (setq bpos (match-beginning 1) tpos (match-end 0)
17662 bcol (progn (goto-char bpos) (current-column))
17663 tcol (progn (goto-char tpos) (current-column))
17664 bullet (match-string 1)
17665 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
17666 (if (> tcol (+ bcol org-description-max-indent))
17667 (setq tcol (+ bcol 5)))
17668 (if (not itemp)
17669 (setq column tcol)
17670 (goto-char pos)
17671 (beginning-of-line 1)
17672 (if (looking-at "\\S-")
17673 (progn
17674 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
17675 (setq bullet (match-string 1)
17676 btype (if (string-match "[0-9]" bullet) "n" bullet))
17677 (setq column (if (equal btype bullet-type) bcol tcol)))
17678 (setq column (org-get-indentation)))))
17679 (t (setq column (org-get-indentation))))))
17680 (goto-char pos)
17681 (if (<= (current-column) (current-indentation))
17682 (org-indent-line-to column)
17683 (save-excursion (org-indent-line-to column)))
17684 (setq column (current-column))
17685 (beginning-of-line 1)
17686 (if (looking-at
17687 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
17688 (replace-match (concat (match-string 1)
17689 (format org-property-format
17690 (match-string 2) (match-string 3)))
17691 t t))
17692 (org-move-to-column column)))
17694 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
17695 "Variable to store copy of `adaptive-fill-regexp'.
17696 Since `adaptive-fill-regexp' is set to never match, we need to
17697 store a backup of its value before entering `org-mode' so that
17698 the functionality can be provided as a fall-back.")
17700 (defun org-set-autofill-regexps ()
17701 (interactive)
17702 ;; In the paragraph separator we include headlines, because filling
17703 ;; text in a line directly attached to a headline would otherwise
17704 ;; fill the headline as well.
17705 (org-set-local 'comment-start-skip "^#+[ \t]*")
17706 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
17707 ;; The paragraph starter includes hand-formatted lists.
17708 (org-set-local
17709 'paragraph-start
17710 (concat
17711 "\f" "\\|"
17712 "[ ]*$" "\\|"
17713 "\\*+ " "\\|"
17714 "[ \t]*#" "\\|"
17715 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
17716 "[ \t]*[:|]" "\\|"
17717 "\\$\\$" "\\|"
17718 "\\\\\\(begin\\|end\\|[][]\\)"))
17719 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17720 ;; But only if the user has not turned off tables or fixed-width regions
17721 (org-set-local
17722 'auto-fill-inhibit-regexp
17723 (concat "\\*+ \\|#\\+"
17724 "\\|[ \t]*" org-keyword-time-regexp
17725 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17726 (concat
17727 "\\|[ \t]*["
17728 (if org-enable-table-editor "|" "")
17729 (if org-enable-fixed-width-editor ":" "")
17730 "]"))))
17731 ;; We use our own fill-paragraph function, to make sure that tables
17732 ;; and fixed-width regions are not wrapped. That function will pass
17733 ;; through to `fill-paragraph' when appropriate.
17734 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17735 ;; Adaptive filling: To get full control, first make sure that
17736 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17737 (unless (local-variable-p 'adaptive-fill-regexp)
17738 (org-set-local 'org-adaptive-fill-regexp-backup
17739 adaptive-fill-regexp))
17740 (org-set-local 'adaptive-fill-regexp "\000")
17741 (org-set-local 'adaptive-fill-function
17742 'org-adaptive-fill-function)
17743 (org-set-local
17744 'align-mode-rules-list
17745 '((org-in-buffer-settings
17746 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
17747 (modes . '(org-mode))))))
17749 (defun org-fill-paragraph (&optional justify)
17750 "Re-align a table, pass through to fill-paragraph if no table."
17751 (let ((table-p (org-at-table-p))
17752 (table.el-p (org-at-table.el-p)))
17753 (cond ((and (equal (char-after (point-at-bol)) ?*)
17754 (save-excursion (goto-char (point-at-bol))
17755 (looking-at outline-regexp)))
17756 t) ; skip headlines
17757 (table.el-p t) ; skip table.el tables
17758 (table-p (org-table-align) t) ; align org-mode tables
17759 (t nil)))) ; call paragraph-fill
17761 ;; For reference, this is the default value of adaptive-fill-regexp
17762 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17764 (defun org-adaptive-fill-function ()
17765 "Return a fill prefix for org-mode files.
17766 In particular, this makes sure hanging paragraphs for hand-formatted lists
17767 work correctly."
17768 (cond
17769 ;; Comment line
17770 ((looking-at "#[ \t]+")
17771 (match-string-no-properties 0))
17772 ;; Description list
17773 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17774 (save-excursion
17775 (if (> (match-end 1) (+ (match-beginning 1)
17776 org-description-max-indent))
17777 (goto-char (+ (match-beginning 1) 5))
17778 (goto-char (match-end 0)))
17779 (make-string (current-column) ?\ )))
17780 ;; Ordered or unordered list
17781 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)")
17782 (save-excursion
17783 (goto-char (match-end 0))
17784 (make-string (current-column) ?\ )))
17785 ;; Other text
17786 ((looking-at org-adaptive-fill-regexp-backup)
17787 (match-string-no-properties 0))))
17789 ;;; Other stuff.
17791 (defun org-toggle-fixed-width-section (arg)
17792 "Toggle the fixed-width export.
17793 If there is no active region, the QUOTE keyword at the current headline is
17794 inserted or removed. When present, it causes the text between this headline
17795 and the next to be exported as fixed-width text, and unmodified.
17796 If there is an active region, this command adds or removes a colon as the
17797 first character of this line. If the first character of a line is a colon,
17798 this line is also exported in fixed-width font."
17799 (interactive "P")
17800 (let* ((cc 0)
17801 (regionp (org-region-active-p))
17802 (beg (if regionp (region-beginning) (point)))
17803 (end (if regionp (region-end)))
17804 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17805 (case-fold-search nil)
17806 (re "[ \t]*\\(: \\)")
17807 off)
17808 (if regionp
17809 (save-excursion
17810 (goto-char beg)
17811 (setq cc (current-column))
17812 (beginning-of-line 1)
17813 (setq off (looking-at re))
17814 (while (> nlines 0)
17815 (setq nlines (1- nlines))
17816 (beginning-of-line 1)
17817 (cond
17818 (arg
17819 (org-move-to-column cc t)
17820 (insert ": \n")
17821 (forward-line -1))
17822 ((and off (looking-at re))
17823 (replace-match "" t t nil 1))
17824 ((not off) (org-move-to-column cc t) (insert ": ")))
17825 (forward-line 1)))
17826 (save-excursion
17827 (org-back-to-heading)
17828 (if (looking-at (concat outline-regexp
17829 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17830 (replace-match "" t t nil 1)
17831 (if (looking-at outline-regexp)
17832 (progn
17833 (goto-char (match-end 0))
17834 (insert org-quote-string " "))))))))
17836 (defun org-reftex-citation ()
17837 "Use reftex-citation to insert a citation into the buffer.
17838 This looks for a line like
17840 #+BIBLIOGRAPHY: foo plain option:-d
17842 and derives from it that foo.bib is the bibliography file relevant
17843 for this document. It then installs the necessary environment for RefTeX
17844 to work in this buffer and calls `reftex-citation' to insert a citation
17845 into the buffer.
17847 Export of such citations to both LaTeX and HTML is handled by the contributed
17848 package org-exp-bibtex by Taru Karttunen."
17849 (interactive)
17850 (let ((reftex-docstruct-symbol 'rds)
17851 (reftex-cite-format "\\cite{%l}")
17852 rds bib)
17853 (save-excursion
17854 (save-restriction
17855 (widen)
17856 (let ((case-fold-search t)
17857 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17858 (if (not (save-excursion
17859 (or (re-search-forward re nil t)
17860 (re-search-backward re nil t))))
17861 (error "No bibliography defined in file")
17862 (setq bib (concat (match-string 1) ".bib")
17863 rds (list (list 'bib bib)))))))
17864 (call-interactively 'reftex-citation)))
17866 ;;;; Functions extending outline functionality
17868 (defun org-beginning-of-line (&optional arg)
17869 "Go to the beginning of the current line. If that is invisible, continue
17870 to a visible line beginning. This makes the function of C-a more intuitive.
17871 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17872 first attempt, and only move to after the tags when the cursor is already
17873 beyond the end of the headline."
17874 (interactive "P")
17875 (let ((pos (point))
17876 (special (if (consp org-special-ctrl-a/e)
17877 (car org-special-ctrl-a/e)
17878 org-special-ctrl-a/e))
17879 refpos)
17880 (if (org-bound-and-true-p line-move-visual)
17881 (beginning-of-visual-line 1)
17882 (beginning-of-line 1))
17883 (if (and arg (fboundp 'move-beginning-of-line))
17884 (call-interactively 'move-beginning-of-line)
17885 (if (bobp)
17887 (backward-char 1)
17888 (if (org-invisible-p)
17889 (while (and (not (bobp)) (org-invisible-p))
17890 (backward-char 1)
17891 (beginning-of-line 1))
17892 (forward-char 1))))
17893 (when special
17894 (cond
17895 ((and (looking-at org-complex-heading-regexp)
17896 (= (char-after (match-end 1)) ?\ ))
17897 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17898 (point-at-eol)))
17899 (goto-char
17900 (if (eq special t)
17901 (cond ((> pos refpos) refpos)
17902 ((= pos (point)) refpos)
17903 (t (point)))
17904 (cond ((> pos (point)) (point))
17905 ((not (eq last-command this-command)) (point))
17906 (t refpos)))))
17907 ((org-at-item-p)
17908 (goto-char
17909 (if (eq special t)
17910 (cond ((> pos (match-end 4)) (match-end 4))
17911 ((= pos (point)) (match-end 4))
17912 (t (point)))
17913 (cond ((> pos (point)) (point))
17914 ((not (eq last-command this-command)) (point))
17915 (t (match-end 4))))))))
17916 (org-no-warnings
17917 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17919 (defun org-end-of-line (&optional arg)
17920 "Go to the end of the line.
17921 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17922 first attempt, and only move to after the tags when the cursor is already
17923 beyond the end of the headline."
17924 (interactive "P")
17925 (let ((special (if (consp org-special-ctrl-a/e)
17926 (cdr org-special-ctrl-a/e)
17927 org-special-ctrl-a/e)))
17928 (if (or (not special)
17929 (not (org-on-heading-p))
17930 arg)
17931 (call-interactively
17932 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17933 ((fboundp 'move-end-of-line) 'move-end-of-line)
17934 (t 'end-of-line)))
17935 (let ((pos (point)))
17936 (beginning-of-line 1)
17937 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17938 (if (eq special t)
17939 (if (or (< pos (match-beginning 1))
17940 (= pos (match-end 0)))
17941 (goto-char (match-beginning 1))
17942 (goto-char (match-end 0)))
17943 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17944 (goto-char (match-end 0))
17945 (goto-char (match-beginning 1))))
17946 (call-interactively (if (fboundp 'move-end-of-line)
17947 'move-end-of-line
17948 'end-of-line)))))
17949 (org-no-warnings
17950 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17952 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17953 (define-key org-mode-map "\C-e" 'org-end-of-line)
17954 (define-key org-mode-map [home] 'org-beginning-of-line)
17955 (define-key org-mode-map [end] 'org-end-of-line)
17957 (defun org-backward-sentence (&optional arg)
17958 "Go to beginning of sentence, or beginning of table field.
17959 This will call `backward-sentence' or `org-table-beginning-of-field',
17960 depending on context."
17961 (interactive "P")
17962 (cond
17963 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17964 (t (call-interactively 'backward-sentence))))
17966 (defun org-forward-sentence (&optional arg)
17967 "Go to end of sentence, or end of table field.
17968 This will call `forward-sentence' or `org-table-end-of-field',
17969 depending on context."
17970 (interactive "P")
17971 (cond
17972 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17973 (t (call-interactively 'forward-sentence))))
17975 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17976 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17978 (defun org-kill-line (&optional arg)
17979 "Kill line, to tags or end of line."
17980 (interactive "P")
17981 (cond
17982 ((or (not org-special-ctrl-k)
17983 (bolp)
17984 (not (org-on-heading-p)))
17985 (call-interactively 'kill-line))
17986 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17987 (kill-region (point) (match-beginning 1))
17988 (org-set-tags nil t))
17989 (t (kill-region (point) (point-at-eol)))))
17991 (define-key org-mode-map "\C-k" 'org-kill-line)
17993 (defun org-yank (&optional arg)
17994 "Yank. If the kill is a subtree, treat it specially.
17995 This command will look at the current kill and check if is a single
17996 subtree, or a series of subtrees[1]. If it passes the test, and if the
17997 cursor is at the beginning of a line or after the stars of a currently
17998 empty headline, then the yank is handled specially. How exactly depends
17999 on the value of the following variables, both set by default.
18001 org-yank-folded-subtrees
18002 When set, the subtree(s) will be folded after insertion, but only
18003 if doing so would now swallow text after the yanked text.
18005 org-yank-adjusted-subtrees
18006 When set, the subtree will be promoted or demoted in order to
18007 fit into the local outline tree structure, which means that the level
18008 will be adjusted so that it becomes the smaller one of the two
18009 *visible* surrounding headings.
18011 Any prefix to this command will cause `yank' to be called directly with
18012 no special treatment. In particular, a simple `C-u' prefix will just
18013 plainly yank the text as it is.
18015 \[1] The test checks if the first non-white line is a heading
18016 and if there are no other headings with fewer stars."
18017 (interactive "P")
18018 (org-yank-generic 'yank arg))
18020 (defun org-yank-generic (command arg)
18021 "Perform some yank-like command.
18023 This function implements the behavior described in the `org-yank'
18024 documentation. However, it has been generalized to work for any
18025 interactive command with similar behavior."
18027 ;; pretend to be command COMMAND
18028 (setq this-command command)
18030 (if arg
18031 (call-interactively command)
18033 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
18034 (and (org-kill-is-subtree-p)
18035 (or (bolp)
18036 (and (looking-at "[ \t]*$")
18037 (string-match
18038 "\\`\\*+\\'"
18039 (buffer-substring (point-at-bol) (point)))))))
18040 swallowp)
18041 (cond
18042 ((and subtreep org-yank-folded-subtrees)
18043 (let ((beg (point))
18044 end)
18045 (if (and subtreep org-yank-adjusted-subtrees)
18046 (org-paste-subtree nil nil 'for-yank)
18047 (call-interactively command))
18049 (setq end (point))
18050 (goto-char beg)
18051 (when (and (bolp) subtreep
18052 (not (setq swallowp
18053 (org-yank-folding-would-swallow-text beg end))))
18054 (or (looking-at outline-regexp)
18055 (re-search-forward (concat "^" outline-regexp) end t))
18056 (while (and (< (point) end) (looking-at outline-regexp))
18057 (hide-subtree)
18058 (org-cycle-show-empty-lines 'folded)
18059 (condition-case nil
18060 (outline-forward-same-level 1)
18061 (error (goto-char end)))))
18062 (when swallowp
18063 (message
18064 "Inserted text not folded because that would swallow text"))
18066 (goto-char end)
18067 (skip-chars-forward " \t\n\r")
18068 (beginning-of-line 1)
18069 (push-mark beg 'nomsg)))
18070 ((and subtreep org-yank-adjusted-subtrees)
18071 (let ((beg (point-at-bol)))
18072 (org-paste-subtree nil nil 'for-yank)
18073 (push-mark beg 'nomsg)))
18075 (call-interactively command))))))
18077 (defun org-yank-folding-would-swallow-text (beg end)
18078 "Would hide-subtree at BEG swallow any text after END?"
18079 (let (level)
18080 (save-excursion
18081 (goto-char beg)
18082 (when (or (looking-at outline-regexp)
18083 (re-search-forward (concat "^" outline-regexp) end t))
18084 (setq level (org-outline-level)))
18085 (goto-char end)
18086 (skip-chars-forward " \t\r\n\v\f")
18087 (if (or (eobp)
18088 (and (bolp) (looking-at org-outline-regexp)
18089 (<= (org-outline-level) level)))
18090 nil ; Nothing would be swallowed
18091 t)))) ; something would swallow
18093 (define-key org-mode-map "\C-y" 'org-yank)
18095 (defun org-invisible-p ()
18096 "Check if point is at a character currently not visible."
18097 ;; Early versions of noutline don't have `outline-invisible-p'.
18098 (if (fboundp 'outline-invisible-p)
18099 (outline-invisible-p)
18100 (get-char-property (point) 'invisible)))
18102 (defun org-invisible-p2 ()
18103 "Check if point is at a character currently not visible."
18104 (save-excursion
18105 (if (and (eolp) (not (bobp))) (backward-char 1))
18106 ;; Early versions of noutline don't have `outline-invisible-p'.
18107 (if (fboundp 'outline-invisible-p)
18108 (outline-invisible-p)
18109 (get-char-property (point) 'invisible))))
18111 (defun org-back-to-heading (&optional invisible-ok)
18112 "Call `outline-back-to-heading', but provide a better error message."
18113 (condition-case nil
18114 (outline-back-to-heading invisible-ok)
18115 (error (error "Before first headline at position %d in buffer %s"
18116 (point) (current-buffer)))))
18118 (defun org-before-first-heading-p ()
18119 "Before first heading?"
18120 (save-excursion
18121 (null (re-search-backward "^\\*+ " nil t))))
18123 (defun org-on-heading-p (&optional ignored)
18124 (outline-on-heading-p t))
18125 (defun org-at-heading-p (&optional ignored)
18126 (outline-on-heading-p t))
18128 (defun org-point-at-end-of-empty-headline ()
18129 "If point is at the end of an empty headline, return t, else nil.
18130 If the heading only contains a TODO keyword, it is still still considered
18131 empty."
18132 (and (looking-at "[ \t]*$")
18133 (save-excursion
18134 (beginning-of-line 1)
18135 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
18136 "\\)?[ \t]*$")))))
18137 (defun org-at-heading-or-item-p ()
18138 (or (org-on-heading-p) (org-at-item-p)))
18140 (defun org-on-target-p ()
18141 (or (org-in-regexp org-radio-target-regexp)
18142 (org-in-regexp org-target-regexp)))
18144 (defun org-up-heading-all (arg)
18145 "Move to the heading line of which the present line is a subheading.
18146 This function considers both visible and invisible heading lines.
18147 With argument, move up ARG levels."
18148 (if (fboundp 'outline-up-heading-all)
18149 (outline-up-heading-all arg) ; emacs 21 version of outline.el
18150 (outline-up-heading arg t))) ; emacs 22 version of outline.el
18152 (defun org-up-heading-safe ()
18153 "Move to the heading line of which the present line is a subheading.
18154 This version will not throw an error. It will return the level of the
18155 headline found, or nil if no higher level is found.
18157 Also, this function will be a lot faster than `outline-up-heading',
18158 because it relies on stars being the outline starters. This can really
18159 make a significant difference in outlines with very many siblings."
18160 (let (start-level re)
18161 (org-back-to-heading t)
18162 (setq start-level (funcall outline-level))
18163 (if (equal start-level 1)
18165 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
18166 (if (re-search-backward re nil t)
18167 (funcall outline-level)))))
18169 (defun org-first-sibling-p ()
18170 "Is this heading the first child of its parents?"
18171 (interactive)
18172 (let ((re (concat "^" outline-regexp))
18173 level l)
18174 (unless (org-at-heading-p t)
18175 (error "Not at a heading"))
18176 (setq level (funcall outline-level))
18177 (save-excursion
18178 (if (not (re-search-backward re nil t))
18180 (setq l (funcall outline-level))
18181 (< l level)))))
18183 (defun org-goto-sibling (&optional previous)
18184 "Goto the next sibling, even if it is invisible.
18185 When PREVIOUS is set, go to the previous sibling instead. Returns t
18186 when a sibling was found. When none is found, return nil and don't
18187 move point."
18188 (let ((fun (if previous 're-search-backward 're-search-forward))
18189 (pos (point))
18190 (re (concat "^" outline-regexp))
18191 level l)
18192 (when (condition-case nil (org-back-to-heading t) (error nil))
18193 (setq level (funcall outline-level))
18194 (catch 'exit
18195 (or previous (forward-char 1))
18196 (while (funcall fun re nil t)
18197 (setq l (funcall outline-level))
18198 (when (< l level) (goto-char pos) (throw 'exit nil))
18199 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
18200 (goto-char pos)
18201 nil))))
18203 (defun org-show-siblings ()
18204 "Show all siblings of the current headline."
18205 (save-excursion
18206 (while (org-goto-sibling) (org-flag-heading nil)))
18207 (save-excursion
18208 (while (org-goto-sibling 'previous)
18209 (org-flag-heading nil))))
18211 (defun org-show-hidden-entry ()
18212 "Show an entry where even the heading is hidden."
18213 (save-excursion
18214 (org-show-entry)))
18216 (defun org-flag-heading (flag &optional entry)
18217 "Flag the current heading. FLAG non-nil means make invisible.
18218 When ENTRY is non-nil, show the entire entry."
18219 (save-excursion
18220 (org-back-to-heading t)
18221 ;; Check if we should show the entire entry
18222 (if entry
18223 (progn
18224 (org-show-entry)
18225 (save-excursion
18226 (and (outline-next-heading)
18227 (org-flag-heading nil))))
18228 (outline-flag-region (max (point-min) (1- (point)))
18229 (save-excursion (outline-end-of-heading) (point))
18230 flag))))
18232 (defun org-get-next-sibling ()
18233 "Move to next heading of the same level, and return point.
18234 If there is no such heading, return nil.
18235 This is like outline-next-sibling, but invisible headings are ok."
18236 (let ((level (funcall outline-level)))
18237 (outline-next-heading)
18238 (while (and (not (eobp)) (> (funcall outline-level) level))
18239 (outline-next-heading))
18240 (if (or (eobp) (< (funcall outline-level) level))
18242 (point))))
18244 (defun org-get-last-sibling ()
18245 "Move to previous heading of the same level, and return point.
18246 If there is no such heading, return nil."
18247 (let ((opoint (point))
18248 (level (funcall outline-level)))
18249 (outline-previous-heading)
18250 (when (and (/= (point) opoint) (outline-on-heading-p t))
18251 (while (and (> (funcall outline-level) level)
18252 (not (bobp)))
18253 (outline-previous-heading))
18254 (if (< (funcall outline-level) level)
18256 (point)))))
18258 (defun org-end-of-subtree (&optional invisible-OK to-heading)
18259 ;; This contains an exact copy of the original function, but it uses
18260 ;; `org-back-to-heading', to make it work also in invisible
18261 ;; trees. And is uses an invisible-OK argument.
18262 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
18263 ;; Furthermore, when used inside Org, finding the end of a large subtree
18264 ;; with many children and grandchildren etc, this can be much faster
18265 ;; than the outline version.
18266 (org-back-to-heading invisible-OK)
18267 (let ((first t)
18268 (level (funcall outline-level)))
18269 (if (and (org-mode-p) (< level 1000))
18270 ;; A true heading (not a plain list item), in Org-mode
18271 ;; This means we can easily find the end by looking
18272 ;; only for the right number of stars. Using a regexp to do
18273 ;; this is so much faster than using a Lisp loop.
18274 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
18275 (forward-char 1)
18276 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
18277 ;; something else, do it the slow way
18278 (while (and (not (eobp))
18279 (or first (> (funcall outline-level) level)))
18280 (setq first nil)
18281 (outline-next-heading)))
18282 (unless to-heading
18283 (if (memq (preceding-char) '(?\n ?\^M))
18284 (progn
18285 ;; Go to end of line before heading
18286 (forward-char -1)
18287 (if (memq (preceding-char) '(?\n ?\^M))
18288 ;; leave blank line before heading
18289 (forward-char -1))))))
18290 (point))
18292 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
18293 "Use Org version in org-mode, for dramatic speed-up."
18294 (if (eq major-mode 'org-mode)
18295 (progn
18296 (org-end-of-subtree nil t)
18297 (unless (eobp) (backward-char 1)))
18298 ad-do-it))
18300 (defun org-forward-same-level (arg &optional invisible-ok)
18301 "Move forward to the arg'th subheading at same level as this one.
18302 Stop at the first and last subheadings of a superior heading."
18303 (interactive "p")
18304 (org-back-to-heading invisible-ok)
18305 (org-on-heading-p)
18306 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18307 (re (format "^\\*\\{1,%d\\} " level))
18309 (forward-char 1)
18310 (while (> arg 0)
18311 (while (and (re-search-forward re nil 'move)
18312 (setq l (- (match-end 0) (match-beginning 0) 1))
18313 (= l level)
18314 (not invisible-ok)
18315 (progn (backward-char 1) (org-invisible-p)))
18316 (if (< l level) (setq arg 1)))
18317 (setq arg (1- arg)))
18318 (beginning-of-line 1)))
18320 (defun org-backward-same-level (arg &optional invisible-ok)
18321 "Move backward to the arg'th subheading at same level as this one.
18322 Stop at the first and last subheadings of a superior heading."
18323 (interactive "p")
18324 (org-back-to-heading)
18325 (org-on-heading-p)
18326 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18327 (re (format "^\\*\\{1,%d\\} " level))
18329 (while (> arg 0)
18330 (while (and (re-search-backward re nil 'move)
18331 (setq l (- (match-end 0) (match-beginning 0) 1))
18332 (= l level)
18333 (not invisible-ok)
18334 (org-invisible-p))
18335 (if (< l level) (setq arg 1)))
18336 (setq arg (1- arg)))))
18338 (defun org-show-subtree ()
18339 "Show everything after this heading at deeper levels."
18340 (outline-flag-region
18341 (point)
18342 (save-excursion
18343 (org-end-of-subtree t t))
18344 nil))
18346 (defun org-show-entry ()
18347 "Show the body directly following this heading.
18348 Show the heading too, if it is currently invisible."
18349 (interactive)
18350 (save-excursion
18351 (condition-case nil
18352 (progn
18353 (org-back-to-heading t)
18354 (outline-flag-region
18355 (max (point-min) (1- (point)))
18356 (save-excursion
18357 (if (re-search-forward
18358 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
18359 (match-beginning 1)
18360 (point-max)))
18361 nil)
18362 (org-cycle-hide-drawers 'children))
18363 (error nil))))
18365 (defun org-make-options-regexp (kwds &optional extra)
18366 "Make a regular expression for keyword lines."
18367 (concat
18369 "#?[ \t]*\\+\\("
18370 (mapconcat 'regexp-quote kwds "\\|")
18371 (if extra (concat "\\|" extra))
18372 "\\):[ \t]*"
18373 "\\(.*\\)"))
18375 ;; Make isearch reveal the necessary context
18376 (defun org-isearch-end ()
18377 "Reveal context after isearch exits."
18378 (when isearch-success ; only if search was successful
18379 (if (featurep 'xemacs)
18380 ;; Under XEmacs, the hook is run in the correct place,
18381 ;; we directly show the context.
18382 (org-show-context 'isearch)
18383 ;; In Emacs the hook runs *before* restoring the overlays.
18384 ;; So we have to use a one-time post-command-hook to do this.
18385 ;; (Emacs 22 has a special variable, see function `org-mode')
18386 (unless (and (boundp 'isearch-mode-end-hook-quit)
18387 isearch-mode-end-hook-quit)
18388 ;; Only when the isearch was not quitted.
18389 (org-add-hook 'post-command-hook 'org-isearch-post-command
18390 'append 'local)))))
18392 (defun org-isearch-post-command ()
18393 "Remove self from hook, and show context."
18394 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
18395 (org-show-context 'isearch))
18398 ;;;; Integration with and fixes for other packages
18400 ;;; Imenu support
18402 (defvar org-imenu-markers nil
18403 "All markers currently used by Imenu.")
18404 (make-variable-buffer-local 'org-imenu-markers)
18406 (defun org-imenu-new-marker (&optional pos)
18407 "Return a new marker for use by Imenu, and remember the marker."
18408 (let ((m (make-marker)))
18409 (move-marker m (or pos (point)))
18410 (push m org-imenu-markers)
18413 (defun org-imenu-get-tree ()
18414 "Produce the index for Imenu."
18415 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
18416 (setq org-imenu-markers nil)
18417 (let* ((n org-imenu-depth)
18418 (re (concat "^" outline-regexp))
18419 (subs (make-vector (1+ n) nil))
18420 (last-level 0)
18421 m level head)
18422 (save-excursion
18423 (save-restriction
18424 (widen)
18425 (goto-char (point-max))
18426 (while (re-search-backward re nil t)
18427 (setq level (org-reduced-level (funcall outline-level)))
18428 (when (<= level n)
18429 (looking-at org-complex-heading-regexp)
18430 (setq head (org-link-display-format
18431 (org-match-string-no-properties 4))
18432 m (org-imenu-new-marker))
18433 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
18434 (if (>= level last-level)
18435 (push (cons head m) (aref subs level))
18436 (push (cons head (aref subs (1+ level))) (aref subs level))
18437 (loop for i from (1+ level) to n do (aset subs i nil)))
18438 (setq last-level level)))))
18439 (aref subs 1)))
18441 (eval-after-load "imenu"
18442 '(progn
18443 (add-hook 'imenu-after-jump-hook
18444 (lambda ()
18445 (if (eq major-mode 'org-mode)
18446 (org-show-context 'org-goto))))))
18448 (defun org-link-display-format (link)
18449 "Replace a link with either the description, or the link target
18450 if no description is present"
18451 (save-match-data
18452 (if (string-match org-bracket-link-analytic-regexp link)
18453 (replace-match (if (match-end 5)
18454 (match-string 5 link)
18455 (concat (match-string 1 link)
18456 (match-string 3 link)))
18457 nil t link)
18458 link)))
18460 ;; Speedbar support
18462 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
18463 "Overlay marking the agenda restriction line in speedbar.")
18464 (overlay-put org-speedbar-restriction-lock-overlay
18465 'face 'org-agenda-restriction-lock)
18466 (overlay-put org-speedbar-restriction-lock-overlay
18467 'help-echo "Agendas are currently limited to this item.")
18468 (org-detach-overlay org-speedbar-restriction-lock-overlay)
18470 (defun org-speedbar-set-agenda-restriction ()
18471 "Restrict future agenda commands to the location at point in speedbar.
18472 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
18473 (interactive)
18474 (require 'org-agenda)
18475 (let (p m tp np dir txt)
18476 (cond
18477 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18478 'org-imenu t))
18479 (setq m (get-text-property p 'org-imenu-marker))
18480 (with-current-buffer (marker-buffer m)
18481 (goto-char m)
18482 (org-agenda-set-restriction-lock 'subtree)))
18483 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18484 'speedbar-function 'speedbar-find-file))
18485 (setq tp (previous-single-property-change
18486 (1+ p) 'speedbar-function)
18487 np (next-single-property-change
18488 tp 'speedbar-function)
18489 dir (speedbar-line-directory)
18490 txt (buffer-substring-no-properties (or tp (point-min))
18491 (or np (point-max))))
18492 (with-current-buffer (find-file-noselect
18493 (let ((default-directory dir))
18494 (expand-file-name txt)))
18495 (unless (org-mode-p)
18496 (error "Cannot restrict to non-Org-mode file"))
18497 (org-agenda-set-restriction-lock 'file)))
18498 (t (error "Don't know how to restrict Org-mode's agenda")))
18499 (move-overlay org-speedbar-restriction-lock-overlay
18500 (point-at-bol) (point-at-eol))
18501 (setq current-prefix-arg nil)
18502 (org-agenda-maybe-redo)))
18504 (eval-after-load "speedbar"
18505 '(progn
18506 (speedbar-add-supported-extension ".org")
18507 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
18508 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
18509 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
18510 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18511 (add-hook 'speedbar-visiting-tag-hook
18512 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
18515 ;;; Fixes and Hacks for problems with other packages
18517 ;; Make flyspell not check words in links, to not mess up our keymap
18518 (defun org-mode-flyspell-verify ()
18519 "Don't let flyspell put overlays at active buttons."
18520 (and (not (get-text-property (point) 'keymap))
18521 (not (get-text-property (point) 'org-no-flyspell))))
18523 (defun org-remove-flyspell-overlays-in (beg end)
18524 "Remove flyspell overlays in region."
18525 (and (org-bound-and-true-p flyspell-mode)
18526 (fboundp 'flyspell-delete-region-overlays)
18527 (flyspell-delete-region-overlays beg end))
18528 (add-text-properties beg end '(org-no-flyspell t)))
18530 ;; Make `bookmark-jump' shows the jump location if it was hidden.
18531 (eval-after-load "bookmark"
18532 '(if (boundp 'bookmark-after-jump-hook)
18533 ;; We can use the hook
18534 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
18535 ;; Hook not available, use advice
18536 (defadvice bookmark-jump (after org-make-visible activate)
18537 "Make the position visible."
18538 (org-bookmark-jump-unhide))))
18540 ;; Make sure saveplace shows the location if it was hidden
18541 (eval-after-load "saveplace"
18542 '(defadvice save-place-find-file-hook (after org-make-visible activate)
18543 "Make the position visible."
18544 (org-bookmark-jump-unhide)))
18546 ;; Make sure ecb shows the location if it was hidden
18547 (eval-after-load "ecb"
18548 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
18549 "Make hierarchy visible when jumping into location from ECB tree buffer."
18550 (if (eq major-mode 'org-mode)
18551 (org-show-context))))
18553 (defun org-bookmark-jump-unhide ()
18554 "Unhide the current position, to show the bookmark location."
18555 (and (org-mode-p)
18556 (or (org-invisible-p)
18557 (save-excursion (goto-char (max (point-min) (1- (point))))
18558 (org-invisible-p)))
18559 (org-show-context 'bookmark-jump)))
18561 ;; Make session.el ignore our circular variable
18562 (eval-after-load "session"
18563 '(add-to-list 'session-globals-exclude 'org-mark-ring))
18565 ;;;; Experimental code
18567 (defun org-closed-in-range ()
18568 "Sparse tree of items closed in a certain time range.
18569 Still experimental, may disappear in the future."
18570 (interactive)
18571 ;; Get the time interval from the user.
18572 (let* ((time1 (org-float-time
18573 (org-read-date nil 'to-time nil "Starting date: ")))
18574 (time2 (org-float-time
18575 (org-read-date nil 'to-time nil "End date:")))
18576 ;; callback function
18577 (callback (lambda ()
18578 (let ((time
18579 (org-float-time
18580 (apply 'encode-time
18581 (org-parse-time-string
18582 (match-string 1))))))
18583 ;; check if time in interval
18584 (and (>= time time1) (<= time time2))))))
18585 ;; make tree, check each match with the callback
18586 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
18588 ;;;; Finish up
18590 (provide 'org)
18592 (run-hooks 'org-load-hook)
18594 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
18596 ;;; org.el ends here