Stop table mapping from emitting messages
[org-mode.git] / lisp / org.el
blob9c2f848fa6ee66c0601b65795c8b9e4469c28cb3
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))
77 (require 'calendar)
78 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
79 (unless (boundp 'calendar-view-holidays-initially-flag)
80 (defvaralias 'calendar-view-holidays-initially-flag
81 'view-calendar-holidays-initially))
82 (unless (boundp 'calendar-view-diary-initially-flag)
83 (defvaralias 'calendar-view-diary-initially-flag
84 'view-diary-entries-initially))
85 (unless (boundp 'diary-fancy-buffer)
86 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
88 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
89 ;; the file noutline.el being loaded.
90 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
91 ;; We require noutline, which might be provided in outline.el
92 (require 'outline) (require 'noutline)
93 ;; Other stuff we need.
94 (require 'time-date)
95 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
96 (require 'easymenu)
97 (require 'overlay)
99 (require 'org-macs)
100 (require 'org-entities)
101 (require 'org-compat)
102 (require 'org-faces)
103 (require 'org-list)
104 (require 'org-src)
105 (require 'org-footnote)
107 ;;;; Customization variables
109 ;;; Version
111 (defconst org-version "6.35trans"
112 "The version number of the file org.el.")
114 (defun org-version (&optional here)
115 "Show the org-mode version in the echo area.
116 With prefix arg HERE, insert it at point."
117 (interactive "P")
118 (let* ((origin default-directory)
119 (version org-version)
120 (git-version)
121 (dir (concat (file-name-directory (locate-library "org")) "../" )))
122 (when (and (file-exists-p (expand-file-name ".git" dir))
123 (executable-find "git"))
124 (unwind-protect
125 (progn
126 (cd dir)
127 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
128 (with-current-buffer "*Shell Command Output*"
129 (goto-char (point-min))
130 (setq git-version (buffer-substring (point) (point-at-eol))))
131 (subst-char-in-string ?- ?. git-version t)
132 (when (string-match "\\S-"
133 (shell-command-to-string
134 "git diff-index --name-only HEAD --"))
135 (setq git-version (concat git-version ".dirty")))
136 (setq version (concat version " (" git-version ")"))))
137 (cd origin)))
138 (setq version (format "Org-mode version %s" version))
139 (if here (insert version))
140 (message version)))
142 ;;; Compatibility constants
144 ;;; The custom variables
146 (defgroup org nil
147 "Outline-based notes management and organizer."
148 :tag "Org"
149 :group 'outlines
150 :group 'calendar)
152 (defcustom org-mode-hook nil
153 "Mode hook for Org-mode, run after the mode was turned on."
154 :group 'org
155 :type 'hook)
157 (defcustom org-load-hook nil
158 "Hook that is run after org.el has been loaded."
159 :group 'org
160 :type 'hook)
162 (defvar org-modules) ; defined below
163 (defvar org-modules-loaded nil
164 "Have the modules been loaded already?")
166 (defun org-load-modules-maybe (&optional force)
167 "Load all extensions listed in `org-modules'."
168 (when (or force (not org-modules-loaded))
169 (mapc (lambda (ext)
170 (condition-case nil (require ext)
171 (error (message "Problems while trying to load feature `%s'" ext))))
172 org-modules)
173 (setq org-modules-loaded t)))
175 (defun org-set-modules (var value)
176 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
177 (set var value)
178 (when (featurep 'org)
179 (org-load-modules-maybe 'force)))
181 (when (org-bound-and-true-p org-modules)
182 (let ((a (member 'org-infojs org-modules)))
183 (and a (setcar a 'org-jsinfo))))
185 (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)
186 "Modules that should always be loaded together with org.el.
187 If a description starts with <C>, the file is not part of Emacs
188 and loading it will require that you have downloaded and properly installed
189 the org-mode distribution.
191 You can also use this system to load external packages (i.e. neither Org
192 core modules, nor modules from the CONTRIB directory). Just add symbols
193 to the end of the list. If the package is called org-xyz.el, then you need
194 to add the symbol `xyz', and the package must have a call to
196 (provide 'org-xyz)"
197 :group 'org
198 :set 'org-set-modules
199 :type
200 '(set :greedy t
201 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
202 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
203 (const :tag " crypt: Encryption of subtrees" org-crypt)
204 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
205 (const :tag " docview: Links to doc-view buffers" org-docview)
206 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
207 (const :tag " id: Global IDs for identifying entries" org-id)
208 (const :tag " info: Links to Info nodes" org-info)
209 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
210 (const :tag " habit: Track your consistency with habits" org-habit)
211 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
212 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
213 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
214 (const :tag " mew Links to Mew folders/messages" org-mew)
215 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
216 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
217 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
218 (const :tag " vm: Links to VM folders/messages" org-vm)
219 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
220 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
221 (const :tag " mouse: Additional mouse support" org-mouse)
223 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
224 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
225 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
226 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
227 (const :tag "C collector: Collect properties into tables" org-collector)
228 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
229 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
230 (const :tag "C eval: Include command output as text" org-eval)
231 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
232 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
233 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
234 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
235 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
237 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
239 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
240 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
241 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
242 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
243 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
244 (const :tag "C mtags: Support for muse-like tags" org-mtags)
245 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
246 (const :tag "C registry: A registry for Org-mode links" org-registry)
247 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
248 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
249 (const :tag "C secretary: Team management with org-mode" org-secretary)
250 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
251 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
252 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
253 (const :tag "C track: Keep up with Org-mode development" org-track)
254 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
256 (defcustom org-support-shift-select nil
257 "Non-nil means make shift-cursor commands select text when possible.
259 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
260 selecting a region, or enlarge thusly regions started in this way.
261 In Org-mode, in special contexts, these same keys are used for other
262 purposes, important enough to compete with shift selection. Org tries
263 to balance these needs by supporting `shift-select-mode' outside these
264 special contexts, under control of this variable.
266 The default of this variable is nil, to avoid confusing behavior. Shifted
267 cursor keys will then execute Org commands in the following contexts:
268 - on a headline, changing TODO state (left/right) and priority (up/down)
269 - on a time stamp, changing the time
270 - in a plain list item, changing the bullet type
271 - in a property definition line, switching between allowed values
272 - in the BEGIN line of a clock table (changing the time block).
273 Outside these contexts, the commands will throw an error.
275 When this variable is t and the cursor is not in a special context,
276 Org-mode will support shift-selection for making and enlarging regions.
277 To make this more effective, the bullet cycling will no longer happen
278 anywhere in an item line, but only if the cursor is exactly on the bullet.
280 If you set this variable to the symbol `always', then the keys
281 will not be special in headlines, property lines, and item lines, to make
282 shift selection work there as well. If this is what you want, you can
283 use the following alternative commands: `C-c C-t' and `C-c ,' to
284 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
285 TODO sets, `C-c -' to cycle item bullet types, and properties can be
286 edited by hand or in column view.
288 However, when the cursor is on a timestamp, shift-cursor commands
289 will still edit the time stamp - this is just too good to give up.
291 XEmacs user should have this variable set to nil, because shift-select-mode
292 is Emacs 23 only."
293 :group 'org
294 :type '(choice
295 (const :tag "Never" nil)
296 (const :tag "When outside special context" t)
297 (const :tag "Everywhere except timestamps" always)))
299 (defgroup org-startup nil
300 "Options concerning startup of Org-mode."
301 :tag "Org Startup"
302 :group 'org)
304 (defcustom org-startup-folded t
305 "Non-nil means entering Org-mode will switch to OVERVIEW.
306 This can also be configured on a per-file basis by adding one of
307 the following lines anywhere in the buffer:
309 #+STARTUP: fold (or `overview', this is equivalent)
310 #+STARTUP: nofold (or `showall', this is equivalent)
311 #+STARTUP: content
312 #+STARTUP: showeverything"
313 :group 'org-startup
314 :type '(choice
315 (const :tag "nofold: show all" nil)
316 (const :tag "fold: overview" t)
317 (const :tag "content: all headlines" content)
318 (const :tag "show everything, even drawers" showeverything)))
320 (defcustom org-startup-truncated t
321 "Non-nil means entering Org-mode will set `truncate-lines'.
322 This is useful since some lines containing links can be very long and
323 uninteresting. Also tables look terrible when wrapped."
324 :group 'org-startup
325 :type 'boolean)
327 (defcustom org-startup-indented nil
328 "Non-nil means turn on `org-indent-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: indent
333 #+STARTUP: noindent"
334 :group 'org-structure
335 :type '(choice
336 (const :tag "Not" nil)
337 (const :tag "Globally (slow on startup in large files)" t)))
339 (defcustom org-startup-with-beamer-mode nil
340 "Non-nil means turn on `org-beamer-mode' on startup.
341 This can also be configured on a per-file basis by adding one of
342 the following lines anywhere in the buffer:
344 #+STARTUP: beamer"
345 :group 'org-startup
346 :type 'boolean)
348 (defcustom org-startup-align-all-tables nil
349 "Non-nil means align all tables when visiting a file.
350 This is useful when the column width in tables is forced with <N> cookies
351 in table fields. Such tables will look correct only after the first re-align.
352 This can also be configured on a per-file basis by adding one of
353 the following lines anywhere in the buffer:
354 #+STARTUP: align
355 #+STARTUP: noalign"
356 :group 'org-startup
357 :type 'boolean)
359 (defcustom org-insert-mode-line-in-empty-file nil
360 "Non-nil means insert the first line setting Org-mode in empty files.
361 When the function `org-mode' is called interactively in an empty file, this
362 normally means that the file name does not automatically trigger Org-mode.
363 To ensure that the file will always be in Org-mode in the future, a
364 line enforcing Org-mode will be inserted into the buffer, if this option
365 has been set."
366 :group 'org-startup
367 :type 'boolean)
369 (defcustom org-replace-disputed-keys nil
370 "Non-nil means use alternative key bindings for some keys.
371 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
372 These keys are also used by other packages like shift-selection-mode'
373 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
374 If you want to use Org-mode together with one of these other modes,
375 or more generally if you would like to move some Org-mode commands to
376 other keys, set this variable and configure the keys with the variable
377 `org-disputed-keys'.
379 This option is only relevant at load-time of Org-mode, and must be set
380 *before* org.el is loaded. Changing it requires a restart of Emacs to
381 become effective."
382 :group 'org-startup
383 :type 'boolean)
385 (defcustom org-use-extra-keys nil
386 "Non-nil means use extra key sequence definitions for certain
387 commands. This happens automatically if you run XEmacs or if
388 window-system is nil. This variable lets you do the same
389 manually. You must set it before loading org.
391 Example: on Carbon Emacs 22 running graphically, with an external
392 keyboard on a Powerbook, the default way of setting M-left might
393 not work for either Alt or ESC. Setting this variable will make
394 it work for ESC."
395 :group 'org-startup
396 :type 'boolean)
398 (if (fboundp 'defvaralias)
399 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
401 (defcustom org-disputed-keys
402 '(([(shift up)] . [(meta p)])
403 ([(shift down)] . [(meta n)])
404 ([(shift left)] . [(meta -)])
405 ([(shift right)] . [(meta +)])
406 ([(control shift right)] . [(meta shift +)])
407 ([(control shift left)] . [(meta shift -)]))
408 "Keys for which Org-mode and other modes compete.
409 This is an alist, cars are the default keys, second element specifies
410 the alternative to use when `org-replace-disputed-keys' is t.
412 Keys can be specified in any syntax supported by `define-key'.
413 The value of this option takes effect only at Org-mode's startup,
414 therefore you'll have to restart Emacs to apply it after changing."
415 :group 'org-startup
416 :type 'alist)
418 (defun org-key (key)
419 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
420 Or return the original if not disputed.
421 Also apply the trnaslations defined in `org-xemacs-key-equivalents'."
422 (when org-replace-disputed-keys
423 (let* ((nkey (key-description key))
424 (x (org-find-if (lambda (x)
425 (equal (key-description (car x)) nkey))
426 org-disputed-keys)))
427 (setq key (if x (cdr x) key))))
428 (when (featurep 'xemacs)
429 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
430 key)
432 (defun org-find-if (predicate seq)
433 (catch 'exit
434 (while seq
435 (if (funcall predicate (car seq))
436 (throw 'exit (car seq))
437 (pop seq)))))
439 (defun org-defkey (keymap key def)
440 "Define a key, possibly translated, as returned by `org-key'."
441 (define-key keymap (org-key key) def))
443 (defcustom org-ellipsis nil
444 "The ellipsis to use in the Org-mode outline.
445 When nil, just use the standard three dots. When a string, use that instead,
446 When a face, use the standard 3 dots, but with the specified face.
447 The change affects only Org-mode (which will then use its own display table).
448 Changing this requires executing `M-x org-mode' in a buffer to become
449 effective."
450 :group 'org-startup
451 :type '(choice (const :tag "Default" nil)
452 (face :tag "Face" :value org-warning)
453 (string :tag "String" :value "...#")))
455 (defvar org-display-table nil
456 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
458 (defgroup org-keywords nil
459 "Keywords in Org-mode."
460 :tag "Org Keywords"
461 :group 'org)
463 (defcustom org-deadline-string "DEADLINE:"
464 "String to mark deadline entries.
465 A deadline is this string, followed by a time stamp. Should be a word,
466 terminated by a colon. You can insert a schedule keyword and
467 a timestamp with \\[org-deadline].
468 Changes become only effective after restarting Emacs."
469 :group 'org-keywords
470 :type 'string)
472 (defcustom org-scheduled-string "SCHEDULED:"
473 "String to mark scheduled TODO entries.
474 A schedule is this string, followed by a time stamp. Should be a word,
475 terminated by a colon. You can insert a schedule keyword and
476 a timestamp with \\[org-schedule].
477 Changes become only effective after restarting Emacs."
478 :group 'org-keywords
479 :type 'string)
481 (defcustom org-closed-string "CLOSED:"
482 "String used as the prefix for timestamps logging closing a TODO entry."
483 :group 'org-keywords
484 :type 'string)
486 (defcustom org-clock-string "CLOCK:"
487 "String used as prefix for timestamps clocking work hours on an item."
488 :group 'org-keywords
489 :type 'string)
491 (defcustom org-comment-string "COMMENT"
492 "Entries starting with this keyword will never be exported.
493 An entry can be toggled between COMMENT and normal with
494 \\[org-toggle-comment].
495 Changes become only effective after restarting Emacs."
496 :group 'org-keywords
497 :type 'string)
499 (defcustom org-quote-string "QUOTE"
500 "Entries starting with this keyword will be exported in fixed-width font.
501 Quoting applies only to the text in the entry following the headline, and does
502 not extend beyond the next headline, even if that is lower level.
503 An entry can be toggled between QUOTE and normal with
504 \\[org-toggle-fixed-width-section]."
505 :group 'org-keywords
506 :type 'string)
508 (defconst org-repeat-re
509 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
510 "Regular expression for specifying repeated events.
511 After a match, group 1 contains the repeat expression.")
513 (defgroup org-structure nil
514 "Options concerning the general structure of Org-mode files."
515 :tag "Org Structure"
516 :group 'org)
518 (defgroup org-reveal-location nil
519 "Options about how to make context of a location visible."
520 :tag "Org Reveal Location"
521 :group 'org-structure)
523 (defconst org-context-choice
524 '(choice
525 (const :tag "Always" t)
526 (const :tag "Never" nil)
527 (repeat :greedy t :tag "Individual contexts"
528 (cons
529 (choice :tag "Context"
530 (const agenda)
531 (const org-goto)
532 (const occur-tree)
533 (const tags-tree)
534 (const link-search)
535 (const mark-goto)
536 (const bookmark-jump)
537 (const isearch)
538 (const default))
539 (boolean))))
540 "Contexts for the reveal options.")
542 (defcustom org-show-hierarchy-above '((default . t))
543 "Non-nil means show full hierarchy when revealing a location.
544 Org-mode often shows locations in an org-mode file which might have
545 been invisible before. When this is set, the hierarchy of headings
546 above the exposed location is shown.
547 Turning this off for example for sparse trees makes them very compact.
548 Instead of t, this can also be an alist specifying this option for different
549 contexts. Valid contexts are
550 agenda when exposing an entry from the agenda
551 org-goto when using the command `org-goto' on key C-c C-j
552 occur-tree when using the command `org-occur' on key C-c /
553 tags-tree when constructing a sparse tree based on tags matches
554 link-search when exposing search matches associated with a link
555 mark-goto when exposing the jump goal of a mark
556 bookmark-jump when exposing a bookmark location
557 isearch when exiting from an incremental search
558 default default for all contexts not set explicitly"
559 :group 'org-reveal-location
560 :type org-context-choice)
562 (defcustom org-show-following-heading '((default . nil))
563 "Non-nil means show following heading when revealing a location.
564 Org-mode often shows locations in an org-mode file which might have
565 been invisible before. When this is set, the heading following the
566 match is shown.
567 Turning this off for example for sparse trees makes them very compact,
568 but makes it harder to edit the location of the match. In such a case,
569 use the command \\[org-reveal] to show more context.
570 Instead of t, this can also be an alist specifying this option for different
571 contexts. See `org-show-hierarchy-above' for valid contexts."
572 :group 'org-reveal-location
573 :type org-context-choice)
575 (defcustom org-show-siblings '((default . nil) (isearch t))
576 "Non-nil means show all sibling heading when revealing a location.
577 Org-mode often shows locations in an org-mode file which might have
578 been invisible before. When this is set, the sibling of the current entry
579 heading are all made visible. If `org-show-hierarchy-above' is t,
580 the same happens on each level of the hierarchy above the current entry.
582 By default this is on for the isearch context, off for all other contexts.
583 Turning this off for example for sparse trees makes them very compact,
584 but makes it harder to edit the location of the match. In such a case,
585 use the command \\[org-reveal] to show more context.
586 Instead of t, this can also be an alist specifying this option for different
587 contexts. See `org-show-hierarchy-above' for valid contexts."
588 :group 'org-reveal-location
589 :type org-context-choice)
591 (defcustom org-show-entry-below '((default . nil))
592 "Non-nil means show the entry below a headline when revealing a location.
593 Org-mode often shows locations in an org-mode file which might have
594 been invisible before. When this is set, the text below the headline that is
595 exposed is also shown.
597 By default this is off for all contexts.
598 Instead of t, this can also be an alist specifying this option for different
599 contexts. See `org-show-hierarchy-above' for valid contexts."
600 :group 'org-reveal-location
601 :type org-context-choice)
603 (defcustom org-indirect-buffer-display 'other-window
604 "How should indirect tree buffers be displayed?
605 This applies to indirect buffers created with the commands
606 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
607 Valid values are:
608 current-window Display in the current window
609 other-window Just display in another window.
610 dedicated-frame Create one new frame, and re-use it each time.
611 new-frame Make a new frame each time. Note that in this case
612 previously-made indirect buffers are kept, and you need to
613 kill these buffers yourself."
614 :group 'org-structure
615 :group 'org-agenda-windows
616 :type '(choice
617 (const :tag "In current window" current-window)
618 (const :tag "In current frame, other window" other-window)
619 (const :tag "Each time a new frame" new-frame)
620 (const :tag "One dedicated frame" dedicated-frame)))
622 (defcustom org-use-speed-commands nil
623 "Non-nil means activate single letter commands at beginning of a headline.
624 This may also be a function to test for appropriate locations where speed
625 commands should be active."
626 :group 'org-structure
627 :type '(choice
628 (const :tag "Never" nil)
629 (const :tag "At beginning of headline stars" t)
630 (function)))
632 (defcustom org-speed-commands-user nil
633 "Alist of additional speed commands.
634 This list will be checked before `org-speed-commands-default'
635 when the variable `org-use-speed-commands' is non-nil
636 and when the cursor is at the beginning of a headline.
637 The car if each entry is a string with a single letter, which must
638 be assigned to `self-insert-command' in the global map.
639 The cdr is either a command to be called interactively, a function
640 to be called, or a form to be evaluated.
641 An entry that is just a list with a single string will be interpreted
642 as a descriptive headline that will be added when listing the speed
643 copmmands in the Help buffer using the `?' speed command."
644 :group 'org-structure
645 :type '(repeat :value ("k" . ignore)
646 (choice :value ("k" . ignore)
647 (list :tag "Descriptive Headline" (string :tag "Headline"))
648 (cons :tag "Letter and Command"
649 (string :tag "Command letter")
650 (choice
651 (function)
652 (sexp))))))
654 (defgroup org-cycle nil
655 "Options concerning visibility cycling in Org-mode."
656 :tag "Org Cycle"
657 :group 'org-structure)
659 (defcustom org-cycle-skip-children-state-if-no-children t
660 "Non-nil means skip CHILDREN state in entries that don't have any."
661 :group 'org-cycle
662 :type 'boolean)
664 (defcustom org-cycle-max-level nil
665 "Maximum level which should still be subject to visibility cycling.
666 Levels higher than this will, for cycling, be treated as text, not a headline.
667 When `org-odd-levels-only' is set, a value of N in this variable actually
668 means 2N-1 stars as the limiting headline.
669 When nil, cycle all levels.
670 Note that the limiting level of cycling is also influenced by
671 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
672 `org-inlinetask-min-level' is, cycling will be limited to levels one less
673 than its value."
674 :group 'org-cycle
675 :type '(choice
676 (const :tag "No limit" nil)
677 (integer :tag "Maximum level")))
679 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
680 "Names of drawers. Drawers are not opened by cycling on the headline above.
681 Drawers only open with a TAB on the drawer line itself. A drawer looks like
682 this:
683 :DRAWERNAME:
684 .....
685 :END:
686 The drawer \"PROPERTIES\" is special for capturing properties through
687 the property API.
689 Drawers can be defined on the per-file basis with a line like:
691 #+DRAWERS: HIDDEN STATE PROPERTIES"
692 :group 'org-structure
693 :group 'org-cycle
694 :type '(repeat (string :tag "Drawer Name")))
696 (defcustom org-hide-block-startup nil
697 "Non-nil means entering Org-mode will fold all blocks.
698 This can also be set in on a per-file basis with
700 #+STARTUP: hideblocks
701 #+STARTUP: showblocks"
702 :group 'org-startup
703 :group 'org-cycle
704 :type 'boolean)
706 (defcustom org-cycle-global-at-bob nil
707 "Cycle globally if cursor is at beginning of buffer and not at a headline.
708 This makes it possible to do global cycling without having to use S-TAB or
709 C-u TAB. For this special case to work, the first line of the buffer
710 must not be a headline - it may be empty or some other text. When used in
711 this way, `org-cycle-hook' is disables temporarily, to make sure the
712 cursor stays at the beginning of the buffer.
713 When this option is nil, don't do anything special at the beginning
714 of the buffer."
715 :group 'org-cycle
716 :type 'boolean)
718 (defcustom org-cycle-level-after-item/entry-creation t
719 "Non-nil means cycle entry level or item indentation in new empty entries.
721 When the cursor is at the end of an empty headline, i.e with only stars
722 and maybe a TODO keyword, TAB will then switch the entry to become a child,
723 and then all possible anchestor states, before returning to the original state.
724 This makes data entry extremely fast: M-RET to create a new headline,
725 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
727 When the cursor is at the end of an empty plain list item, one TAB will
728 make it a subitem, two or more tabs will back up to make this an item
729 higher up in the item hierarchy."
730 :group 'org-cycle
731 :type 'boolean)
733 (defcustom org-cycle-emulate-tab t
734 "Where should `org-cycle' emulate TAB.
735 nil Never
736 white Only in completely white lines
737 whitestart Only at the beginning of lines, before the first non-white char
738 t Everywhere except in headlines
739 exc-hl-bol Everywhere except at the start of a headline
740 If TAB is used in a place where it does not emulate TAB, the current subtree
741 visibility is cycled."
742 :group 'org-cycle
743 :type '(choice (const :tag "Never" nil)
744 (const :tag "Only in completely white lines" white)
745 (const :tag "Before first char in a line" whitestart)
746 (const :tag "Everywhere except in headlines" t)
747 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
750 (defcustom org-cycle-separator-lines 2
751 "Number of empty lines needed to keep an empty line between collapsed trees.
752 If you leave an empty line between the end of a subtree and the following
753 headline, this empty line is hidden when the subtree is folded.
754 Org-mode will leave (exactly) one empty line visible if the number of
755 empty lines is equal or larger to the number given in this variable.
756 So the default 2 means at least 2 empty lines after the end of a subtree
757 are needed to produce free space between a collapsed subtree and the
758 following headline.
760 If the number is negative, and the number of empty lines is at least -N,
761 all empty lines are shown.
763 Special case: when 0, never leave empty lines in collapsed view."
764 :group 'org-cycle
765 :type 'integer)
766 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
768 (defcustom org-pre-cycle-hook nil
769 "Hook that is run before visibility cycling is happening.
770 The function(s) in this hook must accept a single argument which indicates
771 the new state that will be set right after running this hook. The
772 argument is a symbol. Before a global state change, it can have the values
773 `overview', `content', or `all'. Before a local state change, it can have
774 the values `folded', `children', or `subtree'."
775 :group 'org-cycle
776 :type 'hook)
778 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
779 org-cycle-hide-drawers
780 org-cycle-show-empty-lines
781 org-optimize-window-after-visibility-change)
782 "Hook that is run after `org-cycle' has changed the buffer visibility.
783 The function(s) in this hook must accept a single argument which indicates
784 the new state that was set by the most recent `org-cycle' command. The
785 argument is a symbol. After a global state change, it can have the values
786 `overview', `content', or `all'. After a local state change, it can have
787 the values `folded', `children', or `subtree'."
788 :group 'org-cycle
789 :type 'hook)
791 (defgroup org-edit-structure nil
792 "Options concerning structure editing in Org-mode."
793 :tag "Org Edit Structure"
794 :group 'org-structure)
796 (defcustom org-odd-levels-only nil
797 "Non-nil means skip even levels and only use odd levels for the outline.
798 This has the effect that two stars are being added/taken away in
799 promotion/demotion commands. It also influences how levels are
800 handled by the exporters.
801 Changing it requires restart of `font-lock-mode' to become effective
802 for fontification also in regions already fontified.
803 You may also set this on a per-file basis by adding one of the following
804 lines to the buffer:
806 #+STARTUP: odd
807 #+STARTUP: oddeven"
808 :group 'org-edit-structure
809 :group 'org-appearance
810 :type 'boolean)
812 (defcustom org-adapt-indentation t
813 "Non-nil means adapt indentation to outline node level.
815 When this variable is set, Org assumes that you write outlines by
816 indenting text in each node to align with the headline (after the stars).
817 The following issues are influenced by this variable:
819 - When this is set and the *entire* text in an entry is indented, the
820 indentation is increased by one space in a demotion command, and
821 decreased by one in a promotion command. If any line in the entry
822 body starts with text at column 0, indentation is not changed at all.
824 - Property drawers and planning information is inserted indented when
825 this variable s set. When nil, they will not be indented.
827 - TAB indents a line relative to context. The lines below a headline
828 will be indented when this variable is set.
830 Note that this is all about true indentation, by adding and removing
831 space characters. See also `org-indent.el' which does level-dependent
832 indentation in a virtual way, i.e. at display time in Emacs."
833 :group 'org-edit-structure
834 :type 'boolean)
836 (defcustom org-special-ctrl-a/e nil
837 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
839 When t, `C-a' will bring back the cursor to the beginning of the
840 headline text, i.e. after the stars and after a possible TODO keyword.
841 In an item, this will be the position after the bullet.
842 When the cursor is already at that position, another `C-a' will bring
843 it to the beginning of the line.
845 `C-e' will jump to the end of the headline, ignoring the presence of tags
846 in the headline. A second `C-e' will then jump to the true end of the
847 line, after any tags. This also means that, when this variable is
848 non-nil, `C-e' also will never jump beyond the end of the heading of a
849 folded section, i.e. not after the ellipses.
851 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
852 going to the true line boundary first. Only a directly following, identical
853 keypress will bring the cursor to the special positions.
855 This may also be a cons cell where the behavior for `C-a' and `C-e' is
856 set separately."
857 :group 'org-edit-structure
858 :type '(choice
859 (const :tag "off" nil)
860 (const :tag "on: after stars/bullet and before tags first" t)
861 (const :tag "reversed: true line boundary first" reversed)
862 (cons :tag "Set C-a and C-e separately"
863 (choice :tag "Special C-a"
864 (const :tag "off" nil)
865 (const :tag "on: after stars/bullet first" t)
866 (const :tag "reversed: before stars/bullet first" reversed))
867 (choice :tag "Special C-e"
868 (const :tag "off" nil)
869 (const :tag "on: before tags first" t)
870 (const :tag "reversed: after tags first" reversed)))))
871 (if (fboundp 'defvaralias)
872 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
874 (defcustom org-special-ctrl-k nil
875 "Non-nil means `C-k' will behave specially in headlines.
876 When nil, `C-k' will call the default `kill-line' command.
877 When t, the following will happen while the cursor is in the headline:
879 - When the cursor is at the beginning of a headline, kill the entire
880 line and possible the folded subtree below the line.
881 - When in the middle of the headline text, kill the headline up to the tags.
882 - When after the headline text, kill the tags."
883 :group 'org-edit-structure
884 :type 'boolean)
886 (defcustom org-yank-folded-subtrees t
887 "Non-nil means when yanking subtrees, fold them.
888 If the kill is a single subtree, or a sequence of subtrees, i.e. if
889 it starts with a heading and all other headings in it are either children
890 or siblings, then fold all the subtrees. However, do this only if no
891 text after the yank would be swallowed into a folded tree by this action."
892 :group 'org-edit-structure
893 :type 'boolean)
895 (defcustom org-yank-adjusted-subtrees nil
896 "Non-nil means when yanking subtrees, adjust the level.
897 With this setting, `org-paste-subtree' is used to insert the subtree, see
898 this function for details."
899 :group 'org-edit-structure
900 :type 'boolean)
902 (defcustom org-M-RET-may-split-line '((default . t))
903 "Non-nil means M-RET will split the line at the cursor position.
904 When nil, it will go to the end of the line before making a
905 new line.
906 You may also set this option in a different way for different
907 contexts. Valid contexts are:
909 headline when creating a new headline
910 item when creating a new item
911 table in a table field
912 default the value to be used for all contexts not explicitly
913 customized"
914 :group 'org-structure
915 :group 'org-table
916 :type '(choice
917 (const :tag "Always" t)
918 (const :tag "Never" nil)
919 (repeat :greedy t :tag "Individual contexts"
920 (cons
921 (choice :tag "Context"
922 (const headline)
923 (const item)
924 (const table)
925 (const default))
926 (boolean)))))
929 (defcustom org-insert-heading-respect-content nil
930 "Non-nil means insert new headings after the current subtree.
931 When nil, the new heading is created directly after the current line.
932 The commands \\[org-insert-heading-respect-content] and
933 \\[org-insert-todo-heading-respect-content] turn this variable on
934 for the duration of the command."
935 :group 'org-structure
936 :type 'boolean)
938 (defcustom org-blank-before-new-entry '((heading . auto)
939 (plain-list-item . auto))
940 "Should `org-insert-heading' leave a blank line before new heading/item?
941 The value is an alist, with `heading' and `plain-list-item' as car,
942 and a boolean flag as cdr. For plain lists, if the variable
943 `org-empty-line-terminates-plain-lists' is set, the setting here
944 is ignored and no empty line is inserted, to keep the list in tact."
945 :group 'org-edit-structure
946 :type '(list
947 (cons (const heading)
948 (choice (const :tag "Never" nil)
949 (const :tag "Always" t)
950 (const :tag "Auto" auto)))
951 (cons (const plain-list-item)
952 (choice (const :tag "Never" nil)
953 (const :tag "Always" t)
954 (const :tag "Auto" auto)))))
956 (defcustom org-insert-heading-hook nil
957 "Hook being run after inserting a new heading."
958 :group 'org-edit-structure
959 :type 'hook)
961 (defcustom org-enable-fixed-width-editor t
962 "Non-nil means lines starting with \":\" are treated as fixed-width.
963 This currently only means they are never auto-wrapped.
964 When nil, such lines will be treated like ordinary lines.
965 See also the QUOTE keyword."
966 :group 'org-edit-structure
967 :type 'boolean)
970 (defcustom org-goto-auto-isearch t
971 "Non-nil means typing characters in org-goto starts incremental search."
972 :group 'org-edit-structure
973 :type 'boolean)
975 (defgroup org-sparse-trees nil
976 "Options concerning sparse trees in Org-mode."
977 :tag "Org Sparse Trees"
978 :group 'org-structure)
980 (defcustom org-highlight-sparse-tree-matches t
981 "Non-nil means highlight all matches that define a sparse tree.
982 The highlights will automatically disappear the next time the buffer is
983 changed by an edit command."
984 :group 'org-sparse-trees
985 :type 'boolean)
987 (defcustom org-remove-highlights-with-change t
988 "Non-nil means any change to the buffer will remove temporary highlights.
989 Such highlights are created by `org-occur' and `org-clock-display'.
990 When nil, `C-c C-c needs to be used to get rid of the highlights.
991 The highlights created by `org-preview-latex-fragment' always need
992 `C-c C-c' to be removed."
993 :group 'org-sparse-trees
994 :group 'org-time
995 :type 'boolean)
998 (defcustom org-occur-hook '(org-first-headline-recenter)
999 "Hook that is run after `org-occur' has constructed a sparse tree.
1000 This can be used to recenter the window to show as much of the structure
1001 as possible."
1002 :group 'org-sparse-trees
1003 :type 'hook)
1005 (defgroup org-imenu-and-speedbar nil
1006 "Options concerning imenu and speedbar in Org-mode."
1007 :tag "Org Imenu and Speedbar"
1008 :group 'org-structure)
1010 (defcustom org-imenu-depth 2
1011 "The maximum level for Imenu access to Org-mode headlines.
1012 This also applied for speedbar access."
1013 :group 'org-imenu-and-speedbar
1014 :type 'integer)
1016 (defgroup org-table nil
1017 "Options concerning tables in Org-mode."
1018 :tag "Org Table"
1019 :group 'org)
1021 (defcustom org-enable-table-editor 'optimized
1022 "Non-nil means lines starting with \"|\" are handled by the table editor.
1023 When nil, such lines will be treated like ordinary lines.
1025 When equal to the symbol `optimized', the table editor will be optimized to
1026 do the following:
1027 - Automatic overwrite mode in front of whitespace in table fields.
1028 This makes the structure of the table stay in tact as long as the edited
1029 field does not exceed the column width.
1030 - Minimize the number of realigns. Normally, the table is aligned each time
1031 TAB or RET are pressed to move to another field. With optimization this
1032 happens only if changes to a field might have changed the column width.
1033 Optimization requires replacing the functions `self-insert-command',
1034 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1035 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1036 very good at guessing when a re-align will be necessary, but you can always
1037 force one with \\[org-ctrl-c-ctrl-c].
1039 If you would like to use the optimized version in Org-mode, but the
1040 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1042 This variable can be used to turn on and off the table editor during a session,
1043 but in order to toggle optimization, a restart is required.
1045 See also the variable `org-table-auto-blank-field'."
1046 :group 'org-table
1047 :type '(choice
1048 (const :tag "off" nil)
1049 (const :tag "on" t)
1050 (const :tag "on, optimized" optimized)))
1052 (defcustom org-self-insert-cluster-for-undo t
1053 "Non-nil means cluster self-insert commands for undo when possible.
1054 If this is set, then, like in the Emacs command loop, 20 consecutive
1055 characters will be undone together.
1056 This is configurable, because there is some impact on typing performance."
1057 :group 'org-table
1058 :type 'boolean)
1060 (defcustom org-table-tab-recognizes-table.el t
1061 "Non-nil means TAB will automatically notice a table.el table.
1062 When it sees such a table, it moves point into it and - if necessary -
1063 calls `table-recognize-table'."
1064 :group 'org-table-editing
1065 :type 'boolean)
1067 (defgroup org-link nil
1068 "Options concerning links in Org-mode."
1069 :tag "Org Link"
1070 :group 'org)
1072 (defvar org-link-abbrev-alist-local nil
1073 "Buffer-local version of `org-link-abbrev-alist', which see.
1074 The value of this is taken from the #+LINK lines.")
1075 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1077 (defcustom org-link-abbrev-alist nil
1078 "Alist of link abbreviations.
1079 The car of each element is a string, to be replaced at the start of a link.
1080 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1081 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1083 [[linkkey:tag][description]]
1085 The 'linkkey' must be a word word, starting with a letter, followed
1086 by letters, numbers, '-' or '_'.
1088 If REPLACE is a string, the tag will simply be appended to create the link.
1089 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1090 the placeholder \"%h\" will cause a url-encoded version of the tag to
1091 be inserted at that point (see the function `url-hexify-string').
1093 REPLACE may also be a function that will be called with the tag as the
1094 only argument to create the link, which should be returned as a string.
1096 See the manual for examples."
1097 :group 'org-link
1098 :type '(repeat
1099 (cons
1100 (string :tag "Protocol")
1101 (choice
1102 (string :tag "Format")
1103 (function)))))
1105 (defcustom org-descriptive-links t
1106 "Non-nil means hide link part and only show description of bracket links.
1107 Bracket links are like [[link][description]]. This variable sets the initial
1108 state in new org-mode buffers. The setting can then be toggled on a
1109 per-buffer basis from the Org->Hyperlinks menu."
1110 :group 'org-link
1111 :type 'boolean)
1113 (defcustom org-link-file-path-type 'adaptive
1114 "How the path name in file links should be stored.
1115 Valid values are:
1117 relative Relative to the current directory, i.e. the directory of the file
1118 into which the link is being inserted.
1119 absolute Absolute path, if possible with ~ for home directory.
1120 noabbrev Absolute path, no abbreviation of home directory.
1121 adaptive Use relative path for files in the current directory and sub-
1122 directories of it. For other files, use an absolute path."
1123 :group 'org-link
1124 :type '(choice
1125 (const relative)
1126 (const absolute)
1127 (const noabbrev)
1128 (const adaptive)))
1130 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1131 "Types of links that should be activated in Org-mode files.
1132 This is a list of symbols, each leading to the activation of a certain link
1133 type. In principle, it does not hurt to turn on most link types - there may
1134 be a small gain when turning off unused link types. The types are:
1136 bracket The recommended [[link][description]] or [[link]] links with hiding.
1137 angular Links in angular brackets that may contain whitespace like
1138 <bbdb:Carsten Dominik>.
1139 plain Plain links in normal text, no whitespace, like http://google.com.
1140 radio Text that is matched by a radio target, see manual for details.
1141 tag Tag settings in a headline (link to tag search).
1142 date Time stamps (link to calendar).
1143 footnote Footnote labels.
1145 Changing this variable requires a restart of Emacs to become effective."
1146 :group 'org-link
1147 :type '(set :greedy t
1148 (const :tag "Double bracket links (new style)" bracket)
1149 (const :tag "Angular bracket links (old style)" angular)
1150 (const :tag "Plain text links" plain)
1151 (const :tag "Radio target matches" radio)
1152 (const :tag "Tags" tag)
1153 (const :tag "Timestamps" date)
1154 (const :tag "Footnotes" footnote)))
1156 (defcustom org-make-link-description-function nil
1157 "Function to use to generate link descriptions from links. If
1158 nil the link location will be used. This function must take two
1159 parameters; the first is the link and the second the description
1160 org-insert-link has generated, and should return the description
1161 to use."
1162 :group 'org-link
1163 :type 'function)
1165 (defgroup org-link-store nil
1166 "Options concerning storing links in Org-mode."
1167 :tag "Org Store Link"
1168 :group 'org-link)
1170 (defcustom org-email-link-description-format "Email %c: %.30s"
1171 "Format of the description part of a link to an email or usenet message.
1172 The following %-escapes will be replaced by corresponding information:
1174 %F full \"From\" field
1175 %f name, taken from \"From\" field, address if no name
1176 %T full \"To\" field
1177 %t first name in \"To\" field, address if no name
1178 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1179 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1180 %s subject
1181 %m message-id.
1183 You may use normal field width specification between the % and the letter.
1184 This is for example useful to limit the length of the subject.
1186 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1187 :group 'org-link-store
1188 :type 'string)
1190 (defcustom org-from-is-user-regexp
1191 (let (r1 r2)
1192 (when (and user-mail-address (not (string= user-mail-address "")))
1193 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1194 (when (and user-full-name (not (string= user-full-name "")))
1195 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1196 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1197 "Regexp matched against the \"From:\" header of an email or usenet message.
1198 It should match if the message is from the user him/herself."
1199 :group 'org-link-store
1200 :type 'regexp)
1202 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1203 "Non-nil means storing a link to an Org file will use entry IDs.
1205 Note that before this variable is even considered, org-id must be loaded,
1206 so please customize `org-modules' and turn it on.
1208 The variable can have the following values:
1210 t Create an ID if needed to make a link to the current entry.
1212 create-if-interactive
1213 If `org-store-link' is called directly (interactively, as a user
1214 command), do create an ID to support the link. But when doing the
1215 job for remember, only use the ID if it already exists. The
1216 purpose of this setting is to avoid proliferation of unwanted
1217 IDs, just because you happen to be in an Org file when you
1218 call `org-remember' that automatically and preemptively
1219 creates a link. If you do want to get an ID link in a remember
1220 template to an entry not having an ID, create it first by
1221 explicitly creating a link to it, using `C-c C-l' first.
1223 create-if-interactive-and-no-custom-id
1224 Like create-if-interactive, but do not create an ID if there is
1225 a CUSTOM_ID property defined in the entry. This is the default.
1227 use-existing
1228 Use existing ID, do not create one.
1230 nil Never use an ID to make a link, instead link using a text search for
1231 the headline text."
1232 :group 'org-link-store
1233 :type '(choice
1234 (const :tag "Create ID to make link" t)
1235 (const :tag "Create if storing link interactively"
1236 create-if-interactive)
1237 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1238 create-if-interactive-and-no-custom-id)
1239 (const :tag "Only use existing" use-existing)
1240 (const :tag "Do not use ID to create link" nil)))
1242 (defcustom org-context-in-file-links t
1243 "Non-nil means file links from `org-store-link' contain context.
1244 A search string will be added to the file name with :: as separator and
1245 used to find the context when the link is activated by the command
1246 `org-open-at-point'.
1247 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1248 negates this setting for the duration of the command."
1249 :group 'org-link-store
1250 :type 'boolean)
1252 (defcustom org-keep-stored-link-after-insertion nil
1253 "Non-nil means keep link in list for entire session.
1255 The command `org-store-link' adds a link pointing to the current
1256 location to an internal list. These links accumulate during a session.
1257 The command `org-insert-link' can be used to insert links into any
1258 Org-mode file (offering completion for all stored links). When this
1259 option is nil, every link which has been inserted once using \\[org-insert-link]
1260 will be removed from the list, to make completing the unused links
1261 more efficient."
1262 :group 'org-link-store
1263 :type 'boolean)
1265 (defgroup org-link-follow nil
1266 "Options concerning following links in Org-mode."
1267 :tag "Org Follow Link"
1268 :group 'org-link)
1270 (defcustom org-link-translation-function nil
1271 "Function to translate links with different syntax to Org syntax.
1272 This can be used to translate links created for example by the Planner
1273 or emacs-wiki packages to Org syntax.
1274 The function must accept two parameters, a TYPE containing the link
1275 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1276 which is everything after the link protocol. It should return a cons
1277 with possibly modified values of type and path.
1278 Org contains a function for this, so if you set this variable to
1279 `org-translate-link-from-planner', you should be able follow many
1280 links created by planner."
1281 :group 'org-link-follow
1282 :type 'function)
1284 (defcustom org-follow-link-hook nil
1285 "Hook that is run after a link has been followed."
1286 :group 'org-link-follow
1287 :type 'hook)
1289 (defcustom org-tab-follows-link nil
1290 "Non-nil means on links TAB will follow the link.
1291 Needs to be set before org.el is loaded.
1292 This really should not be used, it does not make sense, and the
1293 implementation is bad."
1294 :group 'org-link-follow
1295 :type 'boolean)
1297 (defcustom org-return-follows-link nil
1298 "Non-nil means on links RET will follow the link.
1299 Needs to be set before org.el is loaded."
1300 :group 'org-link-follow
1301 :type 'boolean)
1303 (defcustom org-mouse-1-follows-link
1304 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1305 "Non-nil means mouse-1 on a link will follow the link.
1306 A longer mouse click will still set point. Does not work on XEmacs.
1307 Needs to be set before org.el is loaded."
1308 :group 'org-link-follow
1309 :type 'boolean)
1311 (defcustom org-mark-ring-length 4
1312 "Number of different positions to be recorded in the ring
1313 Changing this requires a restart of Emacs to work correctly."
1314 :group 'org-link-follow
1315 :type 'integer)
1317 (defcustom org-link-frame-setup
1318 '((vm . vm-visit-folder-other-frame)
1319 (gnus . gnus-other-frame)
1320 (file . find-file-other-window))
1321 "Setup the frame configuration for following links.
1322 When following a link with Emacs, it may often be useful to display
1323 this link in another window or frame. This variable can be used to
1324 set this up for the different types of links.
1325 For VM, use any of
1326 `vm-visit-folder'
1327 `vm-visit-folder-other-frame'
1328 For Gnus, use any of
1329 `gnus'
1330 `gnus-other-frame'
1331 `org-gnus-no-new-news'
1332 For FILE, use any of
1333 `find-file'
1334 `find-file-other-window'
1335 `find-file-other-frame'
1336 For the calendar, use the variable `calendar-setup'.
1337 For BBDB, it is currently only possible to display the matches in
1338 another window."
1339 :group 'org-link-follow
1340 :type '(list
1341 (cons (const vm)
1342 (choice
1343 (const vm-visit-folder)
1344 (const vm-visit-folder-other-window)
1345 (const vm-visit-folder-other-frame)))
1346 (cons (const gnus)
1347 (choice
1348 (const gnus)
1349 (const gnus-other-frame)
1350 (const org-gnus-no-new-news)))
1351 (cons (const file)
1352 (choice
1353 (const find-file)
1354 (const find-file-other-window)
1355 (const find-file-other-frame)))))
1357 (defcustom org-display-internal-link-with-indirect-buffer nil
1358 "Non-nil means use indirect buffer to display infile links.
1359 Activating internal links (from one location in a file to another location
1360 in the same file) normally just jumps to the location. When the link is
1361 activated with a C-u prefix (or with mouse-3), the link is displayed in
1362 another window. When this option is set, the other window actually displays
1363 an indirect buffer clone of the current buffer, to avoid any visibility
1364 changes to the current buffer."
1365 :group 'org-link-follow
1366 :type 'boolean)
1368 (defcustom org-open-non-existing-files nil
1369 "Non-nil means `org-open-file' will open non-existing files.
1370 When nil, an error will be generated.
1371 This variable applies only to external applications because they
1372 might choke on non-existing files. If the link is to a file that
1373 will be opened in Emacs, the variable is ignored."
1374 :group 'org-link-follow
1375 :type 'boolean)
1377 (defcustom org-open-directory-means-index-dot-org nil
1378 "Non-nil means a link to a directory really means to index.org.
1379 When nil, following a directory link will run dired or open a finder/explorer
1380 window on that directory."
1381 :group 'org-link-follow
1382 :type 'boolean)
1384 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1385 "Function and arguments to call for following mailto links.
1386 This is a list with the first element being a lisp function, and the
1387 remaining elements being arguments to the function. In string arguments,
1388 %a will be replaced by the address, and %s will be replaced by the subject
1389 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1390 :group 'org-link-follow
1391 :type '(choice
1392 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1393 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1394 (const :tag "message-mail" (message-mail "%a" "%s"))
1395 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1397 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1398 "Non-nil means ask for confirmation before executing shell links.
1399 Shell links can be dangerous: just think about a link
1401 [[shell:rm -rf ~/*][Google Search]]
1403 This link would show up in your Org-mode document as \"Google Search\",
1404 but really it would remove your entire home directory.
1405 Therefore we advise against setting this variable to nil.
1406 Just change it to `y-or-n-p' if you want to confirm with a
1407 single keystroke rather than having to type \"yes\"."
1408 :group 'org-link-follow
1409 :type '(choice
1410 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1411 (const :tag "with y-or-n (faster)" y-or-n-p)
1412 (const :tag "no confirmation (dangerous)" nil)))
1414 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1415 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1416 Elisp links can be dangerous: just think about a link
1418 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1420 This link would show up in your Org-mode document as \"Google Search\",
1421 but really it would remove your entire home directory.
1422 Therefore we advise against setting this variable to nil.
1423 Just change it to `y-or-n-p' if you want to confirm with a
1424 single keystroke rather than having to type \"yes\"."
1425 :group 'org-link-follow
1426 :type '(choice
1427 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1428 (const :tag "with y-or-n (faster)" y-or-n-p)
1429 (const :tag "no confirmation (dangerous)" nil)))
1431 (defconst org-file-apps-defaults-gnu
1432 '((remote . emacs)
1433 (system . mailcap)
1434 (t . mailcap))
1435 "Default file applications on a UNIX or GNU/Linux system.
1436 See `org-file-apps'.")
1438 (defconst org-file-apps-defaults-macosx
1439 '((remote . emacs)
1440 (t . "open %s")
1441 (system . "open %s")
1442 ("ps.gz" . "gv %s")
1443 ("eps.gz" . "gv %s")
1444 ("dvi" . "xdvi %s")
1445 ("fig" . "xfig %s"))
1446 "Default file applications on a MacOS X system.
1447 The system \"open\" is known as a default, but we use X11 applications
1448 for some files for which the OS does not have a good default.
1449 See `org-file-apps'.")
1451 (defconst org-file-apps-defaults-windowsnt
1452 (list
1453 '(remote . emacs)
1454 (cons t
1455 (list (if (featurep 'xemacs)
1456 'mswindows-shell-execute
1457 'w32-shell-execute)
1458 "open" 'file))
1459 (cons 'system
1460 (list (if (featurep 'xemacs)
1461 'mswindows-shell-execute
1462 'w32-shell-execute)
1463 "open" 'file)))
1464 "Default file applications on a Windows NT system.
1465 The system \"open\" is used for most files.
1466 See `org-file-apps'.")
1468 (defcustom org-file-apps
1470 (auto-mode . emacs)
1471 ("\\.mm\\'" . default)
1472 ("\\.x?html?\\'" . default)
1473 ("\\.pdf\\'" . default)
1475 "External applications for opening `file:path' items in a document.
1476 Org-mode uses system defaults for different file types, but
1477 you can use this variable to set the application for a given file
1478 extension. The entries in this list are cons cells where the car identifies
1479 files and the cdr the corresponding command. Possible values for the
1480 file identifier are
1481 \"regex\" Regular expression matched against the file name. For backward
1482 compatibility, this can also be a string with only alphanumeric
1483 characters, which is then interpreted as an extension.
1484 `directory' Matches a directory
1485 `remote' Matches a remote file, accessible through tramp or efs.
1486 Remote files most likely should be visited through Emacs
1487 because external applications cannot handle such paths.
1488 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1489 so all files Emacs knows how to handle. Using this with
1490 command `emacs' will open most files in Emacs. Beware that this
1491 will also open html files inside Emacs, unless you add
1492 (\"html\" . default) to the list as well.
1493 t Default for files not matched by any of the other options.
1494 `system' The system command to open files, like `open' on Windows
1495 and Mac OS X, and mailcap under GNU/Linux. This is the command
1496 that will be selected if you call `C-c C-o' with a double
1497 `C-u C-u' prefix.
1499 Possible values for the command are:
1500 `emacs' The file will be visited by the current Emacs process.
1501 `default' Use the default application for this file type, which is the
1502 association for t in the list, most likely in the system-specific
1503 part.
1504 This can be used to overrule an unwanted setting in the
1505 system-specific variable.
1506 `system' Use the system command for opening files, like \"open\".
1507 This command is specified by the entry whose car is `system'.
1508 Most likely, the system-specific version of this variable
1509 does define this command, but you can overrule/replace it
1510 here.
1511 string A command to be executed by a shell; %s will be replaced
1512 by the path to the file.
1513 sexp A Lisp form which will be evaluated. The file path will
1514 be available in the Lisp variable `file'.
1515 For more examples, see the system specific constants
1516 `org-file-apps-defaults-macosx'
1517 `org-file-apps-defaults-windowsnt'
1518 `org-file-apps-defaults-gnu'."
1519 :group 'org-link-follow
1520 :type '(repeat
1521 (cons (choice :value ""
1522 (string :tag "Extension")
1523 (const :tag "System command to open files" system)
1524 (const :tag "Default for unrecognized files" t)
1525 (const :tag "Remote file" remote)
1526 (const :tag "Links to a directory" directory)
1527 (const :tag "Any files that have Emacs modes"
1528 auto-mode))
1529 (choice :value ""
1530 (const :tag "Visit with Emacs" emacs)
1531 (const :tag "Use default" default)
1532 (const :tag "Use the system command" system)
1533 (string :tag "Command")
1534 (sexp :tag "Lisp form")))))
1538 (defgroup org-refile nil
1539 "Options concerning refiling entries in Org-mode."
1540 :tag "Org Refile"
1541 :group 'org)
1543 (defcustom org-directory "~/org"
1544 "Directory with org files.
1545 This is just a default location to look for Org files. There is no need
1546 at all to put your files into this directory. It is only used in the
1547 following situations:
1549 1. When a remember template specifies a target file that is not an
1550 absolute path. The path will then be interpreted relative to
1551 `org-directory'
1552 2. When a remember note is filed away in an interactive way (when exiting the
1553 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1554 with `org-directory' as the default path."
1555 :group 'org-refile
1556 :group 'org-remember
1557 :type 'directory)
1559 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1560 "Default target for storing notes.
1561 Used by the hooks for remember.el. This can be a string, or nil to mean
1562 the value of `remember-data-file'.
1563 You can set this on a per-template basis with the variable
1564 `org-remember-templates'."
1565 :group 'org-refile
1566 :group 'org-remember
1567 :type '(choice
1568 (const :tag "Default from remember-data-file" nil)
1569 file))
1571 (defcustom org-goto-interface 'outline
1572 "The default interface to be used for `org-goto'.
1573 Allowed values are:
1574 outline The interface shows an outline of the relevant file
1575 and the correct heading is found by moving through
1576 the outline or by searching with incremental search.
1577 outline-path-completion Headlines in the current buffer are offered via
1578 completion. This is the interface also used by
1579 the refile command."
1580 :group 'org-refile
1581 :type '(choice
1582 (const :tag "Outline" outline)
1583 (const :tag "Outline-path-completion" outline-path-completion)))
1585 (defcustom org-goto-max-level 5
1586 "Maximum level to be considered when running org-goto with refile interface."
1587 :group 'org-refile
1588 :type 'integer)
1590 (defcustom org-reverse-note-order nil
1591 "Non-nil means store new notes at the beginning of a file or entry.
1592 When nil, new notes will be filed to the end of a file or entry.
1593 This can also be a list with cons cells of regular expressions that
1594 are matched against file names, and values."
1595 :group 'org-remember
1596 :group 'org-refile
1597 :type '(choice
1598 (const :tag "Reverse always" t)
1599 (const :tag "Reverse never" nil)
1600 (repeat :tag "By file name regexp"
1601 (cons regexp boolean))))
1603 (defcustom org-log-refile nil
1604 "Information to record when a task is refiled.
1606 Possible values are:
1608 nil Don't add anything
1609 time Add a time stamp to the task
1610 note Prompt for a note and add it with template `org-log-note-headings'
1612 This option can also be set with on a per-file-basis with
1614 #+STARTUP: nologrefile
1615 #+STARTUP: logrefile
1616 #+STARTUP: lognoterefile
1618 You can have local logging settings for a subtree by setting the LOGGING
1619 property to one or more of these keywords.
1621 When bulk-refiling from the agenda, the value `note' is forbidden and
1622 will temporarily be changed to `time'."
1623 :group 'org-refile
1624 :group 'org-progress
1625 :type '(choice
1626 (const :tag "No logging" nil)
1627 (const :tag "Record timestamp" time)
1628 (const :tag "Record timestamp with note." note)))
1630 (defcustom org-refile-targets nil
1631 "Targets for refiling entries with \\[org-refile].
1632 This is list of cons cells. Each cell contains:
1633 - a specification of the files to be considered, either a list of files,
1634 or a symbol whose function or variable value will be used to retrieve
1635 a file name or a list of file names. If you use `org-agenda-files' for
1636 that, all agenda files will be scanned for targets. Nil means consider
1637 headings in the current buffer.
1638 - A specification of how to find candidate refile targets. This may be
1639 any of:
1640 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1641 This tag has to be present in all target headlines, inheritance will
1642 not be considered.
1643 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1644 todo keyword.
1645 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1646 headlines that are refiling targets.
1647 - a cons cell (:level . N). Any headline of level N is considered a target.
1648 Note that, when `org-odd-levels-only' is set, level corresponds to
1649 order in hierarchy, not to the number of stars.
1650 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1651 Note that, when `org-odd-levels-only' is set, level corresponds to
1652 order in hierarchy, not to the number of stars.
1654 You can set the variable `org-refile-target-verify-function' to a function
1655 to verify each headline found by the simple critery above.
1657 When this variable is nil, all top-level headlines in the current buffer
1658 are used, equivalent to the value `((nil . (:level . 1))'."
1659 :group 'org-refile
1660 :type '(repeat
1661 (cons
1662 (choice :value org-agenda-files
1663 (const :tag "All agenda files" org-agenda-files)
1664 (const :tag "Current buffer" nil)
1665 (function) (variable) (file))
1666 (choice :tag "Identify target headline by"
1667 (cons :tag "Specific tag" (const :value :tag) (string))
1668 (cons :tag "TODO keyword" (const :value :todo) (string))
1669 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1670 (cons :tag "Level number" (const :value :level) (integer))
1671 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1673 (defcustom org-refile-target-verify-function nil
1674 "Function to verify if the headline at point should be a refile target.
1675 The function will be called without arguments, with point at the
1676 beginning of the headline. It should return t and leave point
1677 where it is if the headline is a valid target for refiling.
1679 If the target should not be selected, the function must return nil.
1680 In addition to this, it may move point to a place from where the search
1681 should be continued. For example, the function may decide that the entire
1682 subtree of the current entry should be excluded and move point to the end
1683 of the subtree."
1684 :group 'org-refile
1685 :type 'function)
1687 (defcustom org-refile-use-outline-path nil
1688 "Non-nil means provide refile targets as paths.
1689 So a level 3 headline will be available as level1/level2/level3.
1691 When the value is `file', also include the file name (without directory)
1692 into the path. In this case, you can also stop the completion after
1693 the file name, to get entries inserted as top level in the file.
1695 When `full-file-path', include the full file path."
1696 :group 'org-refile
1697 :type '(choice
1698 (const :tag "Not" nil)
1699 (const :tag "Yes" t)
1700 (const :tag "Start with file name" file)
1701 (const :tag "Start with full file path" full-file-path)))
1703 (defcustom org-outline-path-complete-in-steps t
1704 "Non-nil means complete the outline path in hierarchical steps.
1705 When Org-mode uses the refile interface to select an outline path
1706 \(see variable `org-refile-use-outline-path'), the completion of
1707 the path can be done is a single go, or if can be done in steps down
1708 the headline hierarchy. Going in steps is probably the best if you
1709 do not use a special completion package like `ido' or `icicles'.
1710 However, when using these packages, going in one step can be very
1711 fast, while still showing the whole path to the entry."
1712 :group 'org-refile
1713 :type 'boolean)
1715 (defcustom org-refile-allow-creating-parent-nodes nil
1716 "Non-nil means allow to create new nodes as refile targets.
1717 New nodes are then created by adding \"/new node name\" to the completion
1718 of an existing node. When the value of this variable is `confirm',
1719 new node creation must be confirmed by the user (recommended)
1720 When nil, the completion must match an existing entry.
1722 Note that, if the new heading is not seen by the criteria
1723 listed in `org-refile-targets', multiple instances of the same
1724 heading would be created by trying again to file under the new
1725 heading."
1726 :group 'org-refile
1727 :type '(choice
1728 (const :tag "Never" nil)
1729 (const :tag "Always" t)
1730 (const :tag "Prompt for confirmation" confirm)))
1732 (defgroup org-todo nil
1733 "Options concerning TODO items in Org-mode."
1734 :tag "Org TODO"
1735 :group 'org)
1737 (defgroup org-progress nil
1738 "Options concerning Progress logging in Org-mode."
1739 :tag "Org Progress"
1740 :group 'org-time)
1742 (defvar org-todo-interpretation-widgets
1744 (:tag "Sequence (cycling hits every state)" sequence)
1745 (:tag "Type (cycling directly to DONE)" type))
1746 "The available interpretation symbols for customizing
1747 `org-todo-keywords'.
1748 Interested libraries should add to this list.")
1750 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1751 "List of TODO entry keyword sequences and their interpretation.
1752 \\<org-mode-map>This is a list of sequences.
1754 Each sequence starts with a symbol, either `sequence' or `type',
1755 indicating if the keywords should be interpreted as a sequence of
1756 action steps, or as different types of TODO items. The first
1757 keywords are states requiring action - these states will select a headline
1758 for inclusion into the global TODO list Org-mode produces. If one of
1759 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1760 signify that no further action is necessary. If \"|\" is not found,
1761 the last keyword is treated as the only DONE state of the sequence.
1763 The command \\[org-todo] cycles an entry through these states, and one
1764 additional state where no keyword is present. For details about this
1765 cycling, see the manual.
1767 TODO keywords and interpretation can also be set on a per-file basis with
1768 the special #+SEQ_TODO and #+TYP_TODO lines.
1770 Each keyword can optionally specify a character for fast state selection
1771 \(in combination with the variable `org-use-fast-todo-selection')
1772 and specifiers for state change logging, using the same syntax
1773 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1774 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1775 indicates to record a time stamp each time this state is selected.
1777 Each keyword may also specify if a timestamp or a note should be
1778 recorded when entering or leaving the state, by adding additional
1779 characters in the parenthesis after the keyword. This looks like this:
1780 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1781 record only the time of the state change. With X and Y being either
1782 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1783 Y when leaving the state if and only if the *target* state does not
1784 define X. You may omit any of the fast-selection key or X or /Y,
1785 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1787 For backward compatibility, this variable may also be just a list
1788 of keywords - in this case the interpretation (sequence or type) will be
1789 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1790 :group 'org-todo
1791 :group 'org-keywords
1792 :type '(choice
1793 (repeat :tag "Old syntax, just keywords"
1794 (string :tag "Keyword"))
1795 (repeat :tag "New syntax"
1796 (cons
1797 (choice
1798 :tag "Interpretation"
1799 ;;Quick and dirty way to see
1800 ;;`org-todo-interpretations'. This takes the
1801 ;;place of item arguments
1802 :convert-widget
1803 (lambda (widget)
1804 (widget-put widget
1805 :args (mapcar
1806 #'(lambda (x)
1807 (widget-convert
1808 (cons 'const x)))
1809 org-todo-interpretation-widgets))
1810 widget))
1811 (repeat
1812 (string :tag "Keyword"))))))
1814 (defvar org-todo-keywords-1 nil
1815 "All TODO and DONE keywords active in a buffer.")
1816 (make-variable-buffer-local 'org-todo-keywords-1)
1817 (defvar org-todo-keywords-for-agenda nil)
1818 (defvar org-done-keywords-for-agenda nil)
1819 (defvar org-drawers-for-agenda nil)
1820 (defvar org-todo-keyword-alist-for-agenda nil)
1821 (defvar org-tag-alist-for-agenda nil)
1822 (defvar org-agenda-contributing-files nil)
1823 (defvar org-not-done-keywords nil)
1824 (make-variable-buffer-local 'org-not-done-keywords)
1825 (defvar org-done-keywords nil)
1826 (make-variable-buffer-local 'org-done-keywords)
1827 (defvar org-todo-heads nil)
1828 (make-variable-buffer-local 'org-todo-heads)
1829 (defvar org-todo-sets nil)
1830 (make-variable-buffer-local 'org-todo-sets)
1831 (defvar org-todo-log-states nil)
1832 (make-variable-buffer-local 'org-todo-log-states)
1833 (defvar org-todo-kwd-alist nil)
1834 (make-variable-buffer-local 'org-todo-kwd-alist)
1835 (defvar org-todo-key-alist nil)
1836 (make-variable-buffer-local 'org-todo-key-alist)
1837 (defvar org-todo-key-trigger nil)
1838 (make-variable-buffer-local 'org-todo-key-trigger)
1840 (defcustom org-todo-interpretation 'sequence
1841 "Controls how TODO keywords are interpreted.
1842 This variable is in principle obsolete and is only used for
1843 backward compatibility, if the interpretation of todo keywords is
1844 not given already in `org-todo-keywords'. See that variable for
1845 more information."
1846 :group 'org-todo
1847 :group 'org-keywords
1848 :type '(choice (const sequence)
1849 (const type)))
1851 (defcustom org-use-fast-todo-selection t
1852 "Non-nil means use the fast todo selection scheme with C-c C-t.
1853 This variable describes if and under what circumstances the cycling
1854 mechanism for TODO keywords will be replaced by a single-key, direct
1855 selection scheme.
1857 When nil, fast selection is never used.
1859 When the symbol `prefix', it will be used when `org-todo' is called with
1860 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1861 in an agenda buffer.
1863 When t, fast selection is used by default. In this case, the prefix
1864 argument forces cycling instead.
1866 In all cases, the special interface is only used if access keys have actually
1867 been assigned by the user, i.e. if keywords in the configuration are followed
1868 by a letter in parenthesis, like TODO(t)."
1869 :group 'org-todo
1870 :type '(choice
1871 (const :tag "Never" nil)
1872 (const :tag "By default" t)
1873 (const :tag "Only with C-u C-c C-t" prefix)))
1875 (defcustom org-provide-todo-statistics t
1876 "Non-nil means update todo statistics after insert and toggle.
1877 ALL-HEADLINES means update todo statistics by including headlines
1878 with no TODO keyword as well, counting them as not done.
1879 A list of TODO keywords means the same, but skip keywords that are
1880 not in this list.
1882 When this is set, todo statistics is updated in the parent of the
1883 current entry each time a todo state is changed."
1884 :group 'org-todo
1885 :type '(choice
1886 (const :tag "Yes, only for TODO entries" t)
1887 (const :tag "Yes, including all entries" 'all-headlines)
1888 (repeat :tag "Yes, for TODOs in this list"
1889 (string :tag "TODO keyword"))
1890 (other :tag "No TODO statistics" nil)))
1892 (defcustom org-hierarchical-todo-statistics t
1893 "Non-nil means TODO statistics covers just direct children.
1894 When nil, all entries in the subtree are considered.
1895 This has only an effect if `org-provide-todo-statistics' is set.
1896 To set this to nil for only a single subtree, use a COOKIE_DATA
1897 property and include the word \"recursive\" into the value."
1898 :group 'org-todo
1899 :type 'boolean)
1901 (defcustom org-after-todo-state-change-hook nil
1902 "Hook which is run after the state of a TODO item was changed.
1903 The new state (a string with a TODO keyword, or nil) is available in the
1904 Lisp variable `state'."
1905 :group 'org-todo
1906 :type 'hook)
1908 (defvar org-blocker-hook nil
1909 "Hook for functions that are allowed to block a state change.
1911 Each function gets as its single argument a property list, see
1912 `org-trigger-hook' for more information about this list.
1914 If any of the functions in this hook returns nil, the state change
1915 is blocked.")
1917 (defvar org-trigger-hook nil
1918 "Hook for functions that are triggered by a state change.
1920 Each function gets as its single argument a property list with at least
1921 the following elements:
1923 (:type type-of-change :position pos-at-entry-start
1924 :from old-state :to new-state)
1926 Depending on the type, more properties may be present.
1928 This mechanism is currently implemented for:
1930 TODO state changes
1931 ------------------
1932 :type todo-state-change
1933 :from previous state (keyword as a string), or nil, or a symbol
1934 'todo' or 'done', to indicate the general type of state.
1935 :to new state, like in :from")
1937 (defcustom org-enforce-todo-dependencies nil
1938 "Non-nil means undone TODO entries will block switching the parent to DONE.
1939 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1940 be blocked if any prior sibling is not yet done.
1941 Finally, if the parent is blocked because of ordered siblings of its own,
1942 the child will also be blocked.
1943 This variable needs to be set before org.el is loaded, and you need to
1944 restart Emacs after a change to make the change effective. The only way
1945 to change is while Emacs is running is through the customize interface."
1946 :set (lambda (var val)
1947 (set var val)
1948 (if val
1949 (add-hook 'org-blocker-hook
1950 'org-block-todo-from-children-or-siblings-or-parent)
1951 (remove-hook 'org-blocker-hook
1952 'org-block-todo-from-children-or-siblings-or-parent)))
1953 :group 'org-todo
1954 :type 'boolean)
1956 (defcustom org-enforce-todo-checkbox-dependencies nil
1957 "Non-nil means unchecked boxes will block switching the parent to DONE.
1958 When this is nil, checkboxes have no influence on switching TODO states.
1959 When non-nil, you first need to check off all check boxes before the TODO
1960 entry can be switched to DONE.
1961 This variable needs to be set before org.el is loaded, and you need to
1962 restart Emacs after a change to make the change effective. The only way
1963 to change is while Emacs is running is through the customize interface."
1964 :set (lambda (var val)
1965 (set var val)
1966 (if val
1967 (add-hook 'org-blocker-hook
1968 'org-block-todo-from-checkboxes)
1969 (remove-hook 'org-blocker-hook
1970 'org-block-todo-from-checkboxes)))
1971 :group 'org-todo
1972 :type 'boolean)
1974 (defcustom org-treat-insert-todo-heading-as-state-change nil
1975 "Non-nil means inserting a TODO heading is treated as state change.
1976 So when the command \\[org-insert-todo-heading] is used, state change
1977 logging will apply if appropriate. When nil, the new TODO item will
1978 be inserted directly, and no logging will take place."
1979 :group 'org-todo
1980 :type 'boolean)
1982 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1983 "Non-nil means switching TODO states with S-cursor counts as state change.
1984 This is the default behavior. However, setting this to nil allows a
1985 convenient way to select a TODO state and bypass any logging associated
1986 with that."
1987 :group 'org-todo
1988 :type 'boolean)
1990 (defcustom org-todo-state-tags-triggers nil
1991 "Tag changes that should be triggered by TODO state changes.
1992 This is a list. Each entry is
1994 (state-change (tag . flag) .......)
1996 State-change can be a string with a state, and empty string to indicate the
1997 state that has no TODO keyword, or it can be one of the symbols `todo'
1998 or `done', meaning any not-done or done state, respectively."
1999 :group 'org-todo
2000 :group 'org-tags
2001 :type '(repeat
2002 (cons (choice :tag "When changing to"
2003 (const :tag "Not-done state" todo)
2004 (const :tag "Done state" done)
2005 (string :tag "State"))
2006 (repeat
2007 (cons :tag "Tag action"
2008 (string :tag "Tag")
2009 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2011 (defcustom org-log-done nil
2012 "Information to record when a task moves to the DONE state.
2014 Possible values are:
2016 nil Don't add anything, just change the keyword
2017 time Add a time stamp to the task
2018 note Prompt for a note and add it with template `org-log-note-headings'
2020 This option can also be set with on a per-file-basis with
2022 #+STARTUP: nologdone
2023 #+STARTUP: logdone
2024 #+STARTUP: lognotedone
2026 You can have local logging settings for a subtree by setting the LOGGING
2027 property to one or more of these keywords."
2028 :group 'org-todo
2029 :group 'org-progress
2030 :type '(choice
2031 (const :tag "No logging" nil)
2032 (const :tag "Record CLOSED timestamp" time)
2033 (const :tag "Record CLOSED timestamp with note." note)))
2035 ;; Normalize old uses of org-log-done.
2036 (cond
2037 ((eq org-log-done t) (setq org-log-done 'time))
2038 ((and (listp org-log-done) (memq 'done org-log-done))
2039 (setq org-log-done 'note)))
2041 (defcustom org-log-reschedule nil
2042 "Information to record when the scheduling date of a tasks is modified.
2044 Possible values are:
2046 nil Don't add anything, just change the date
2047 time Add a time stamp to the task
2048 note Prompt for a note and add it with template `org-log-note-headings'
2050 This option can also be set with on a per-file-basis with
2052 #+STARTUP: nologreschedule
2053 #+STARTUP: logreschedule
2054 #+STARTUP: lognotereschedule"
2055 :group 'org-todo
2056 :group 'org-progress
2057 :type '(choice
2058 (const :tag "No logging" nil)
2059 (const :tag "Record timestamp" time)
2060 (const :tag "Record timestamp with note." note)))
2062 (defcustom org-log-redeadline nil
2063 "Information to record when the deadline date of a tasks is modified.
2065 Possible values are:
2067 nil Don't add anything, just change the date
2068 time Add a time stamp to the task
2069 note Prompt for a note and add it with template `org-log-note-headings'
2071 This option can also be set with on a per-file-basis with
2073 #+STARTUP: nologredeadline
2074 #+STARTUP: logredeadline
2075 #+STARTUP: lognoteredeadline
2077 You can have local logging settings for a subtree by setting the LOGGING
2078 property to one or more of these keywords."
2079 :group 'org-todo
2080 :group 'org-progress
2081 :type '(choice
2082 (const :tag "No logging" nil)
2083 (const :tag "Record timestamp" time)
2084 (const :tag "Record timestamp with note." note)))
2086 (defcustom org-log-note-clock-out nil
2087 "Non-nil means record a note when clocking out of an item.
2088 This can also be configured on a per-file basis by adding one of
2089 the following lines anywhere in the buffer:
2091 #+STARTUP: lognoteclock-out
2092 #+STARTUP: nolognoteclock-out"
2093 :group 'org-todo
2094 :group 'org-progress
2095 :type 'boolean)
2097 (defcustom org-log-done-with-time t
2098 "Non-nil means the CLOSED time stamp will contain date and time.
2099 When nil, only the date will be recorded."
2100 :group 'org-progress
2101 :type 'boolean)
2103 (defcustom org-log-note-headings
2104 '((done . "CLOSING NOTE %t")
2105 (state . "State %-12s from %-12S %t")
2106 (note . "Note taken on %t")
2107 (reschedule . "Rescheduled from %S on %t")
2108 (delschedule . "Not scheduled, was %S on %t")
2109 (redeadline . "New deadline from %S on %t")
2110 (deldeadline . "Removed deadline, was %S on %t")
2111 (refile . "Refiled on %t")
2112 (clock-out . ""))
2113 "Headings for notes added to entries.
2114 The value is an alist, with the car being a symbol indicating the note
2115 context, and the cdr is the heading to be used. The heading may also be the
2116 empty string.
2117 %t in the heading will be replaced by a time stamp.
2118 %s will be replaced by the new TODO state, in double quotes.
2119 %S will be replaced by the old TODO state, in double quotes.
2120 %u will be replaced by the user name.
2121 %U will be replaced by the full user name.
2123 In fact, it is not a good idea to change the `state' entry, because
2124 agenda log mode depends on the format of these entries."
2125 :group 'org-todo
2126 :group 'org-progress
2127 :type '(list :greedy t
2128 (cons (const :tag "Heading when closing an item" done) string)
2129 (cons (const :tag
2130 "Heading when changing todo state (todo sequence only)"
2131 state) string)
2132 (cons (const :tag "Heading when just taking a note" note) string)
2133 (cons (const :tag "Heading when clocking out" clock-out) string)
2134 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2135 (cons (const :tag "Heading when rescheduling" reschedule) string)
2136 (cons (const :tag "Heading when changing deadline" redeadline) string)
2137 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2138 (cons (const :tag "Heading when refiling" refile) string)))
2140 (unless (assq 'note org-log-note-headings)
2141 (push '(note . "%t") org-log-note-headings))
2143 (defcustom org-log-into-drawer nil
2144 "Non-nil means insert state change notes and time stamps into a drawer.
2145 When nil, state changes notes will be inserted after the headline and
2146 any scheduling and clock lines, but not inside a drawer.
2148 The value of this variable should be the name of the drawer to use.
2149 LOGBOOK is proposed at the default drawer for this purpose, you can
2150 also set this to a string to define the drawer of your choice.
2152 A value of t is also allowed, representing \"LOGBOOK\".
2154 If this variable is set, `org-log-state-notes-insert-after-drawers'
2155 will be ignored.
2157 You can set the property LOG_INTO_DRAWER to overrule this setting for
2158 a subtree."
2159 :group 'org-todo
2160 :group 'org-progress
2161 :type '(choice
2162 (const :tag "Not into a drawer" nil)
2163 (const :tag "LOGBOOK" t)
2164 (string :tag "Other")))
2166 (if (fboundp 'defvaralias)
2167 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2169 (defun org-log-into-drawer ()
2170 "Return the value of `org-log-into-drawer', but let properties overrule.
2171 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2172 used instead of the default value."
2173 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2174 (cond
2175 ((or (not p) (equal p "nil")) org-log-into-drawer)
2176 ((equal p "t") "LOGBOOK")
2177 (t p))))
2179 (defcustom org-log-state-notes-insert-after-drawers nil
2180 "Non-nil means insert state change notes after any drawers in entry.
2181 Only the drawers that *immediately* follow the headline and the
2182 deadline/scheduled line are skipped.
2183 When nil, insert notes right after the heading and perhaps the line
2184 with deadline/scheduling if present.
2186 This variable will have no effect if `org-log-into-drawer' is
2187 set."
2188 :group 'org-todo
2189 :group 'org-progress
2190 :type 'boolean)
2192 (defcustom org-log-states-order-reversed t
2193 "Non-nil means the latest state note will be directly after heading.
2194 When nil, the state change notes will be ordered according to time."
2195 :group 'org-todo
2196 :group 'org-progress
2197 :type 'boolean)
2199 (defcustom org-todo-repeat-to-state nil
2200 "The TODO state to which a repeater should return the repeating task.
2201 By default this is the first task in a TODO sequence, or the previous state
2202 in a TODO_TYP set. But you can specify another task here.
2203 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2204 :group 'org-todo
2205 :type '(choice (const :tag "Head of sequence" nil)
2206 (string :tag "Specific state")))
2208 (defcustom org-log-repeat 'time
2209 "Non-nil means record moving through the DONE state when triggering repeat.
2210 An auto-repeating task is immediately switched back to TODO when
2211 marked DONE. If you are not logging state changes (by adding \"@\"
2212 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2213 record a closing note, there will be no record of the task moving
2214 through DONE. This variable forces taking a note anyway.
2216 nil Don't force a record
2217 time Record a time stamp
2218 note Record a note
2220 This option can also be set with on a per-file-basis with
2222 #+STARTUP: logrepeat
2223 #+STARTUP: lognoterepeat
2224 #+STARTUP: nologrepeat
2226 You can have local logging settings for a subtree by setting the LOGGING
2227 property to one or more of these keywords."
2228 :group 'org-todo
2229 :group 'org-progress
2230 :type '(choice
2231 (const :tag "Don't force a record" nil)
2232 (const :tag "Force recording the DONE state" time)
2233 (const :tag "Force recording a note with the DONE state" note)))
2236 (defgroup org-priorities nil
2237 "Priorities in Org-mode."
2238 :tag "Org Priorities"
2239 :group 'org-todo)
2241 (defcustom org-enable-priority-commands t
2242 "Non-nil means priority commands are active.
2243 When nil, these commands will be disabled, so that you never accidentally
2244 set a priority."
2245 :group 'org-priorities
2246 :type 'boolean)
2248 (defcustom org-highest-priority ?A
2249 "The highest priority of TODO items. A character like ?A, ?B etc.
2250 Must have a smaller ASCII number than `org-lowest-priority'."
2251 :group 'org-priorities
2252 :type 'character)
2254 (defcustom org-lowest-priority ?C
2255 "The lowest priority of TODO items. A character like ?A, ?B etc.
2256 Must have a larger ASCII number than `org-highest-priority'."
2257 :group 'org-priorities
2258 :type 'character)
2260 (defcustom org-default-priority ?B
2261 "The default priority of TODO items.
2262 This is the priority an item get if no explicit priority is given."
2263 :group 'org-priorities
2264 :type 'character)
2266 (defcustom org-priority-start-cycle-with-default t
2267 "Non-nil means start with default priority when starting to cycle.
2268 When this is nil, the first step in the cycle will be (depending on the
2269 command used) one higher or lower that the default priority."
2270 :group 'org-priorities
2271 :type 'boolean)
2273 (defgroup org-time nil
2274 "Options concerning time stamps and deadlines in Org-mode."
2275 :tag "Org Time"
2276 :group 'org)
2278 (defcustom org-insert-labeled-timestamps-at-point nil
2279 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2280 When nil, these labeled time stamps are forces into the second line of an
2281 entry, just after the headline. When scheduling from the global TODO list,
2282 the time stamp will always be forced into the second line."
2283 :group 'org-time
2284 :type 'boolean)
2286 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2287 "Formats for `format-time-string' which are used for time stamps.
2288 It is not recommended to change this constant.")
2290 (defcustom org-time-stamp-rounding-minutes '(0 5)
2291 "Number of minutes to round time stamps to.
2292 These are two values, the first applies when first creating a time stamp.
2293 The second applies when changing it with the commands `S-up' and `S-down'.
2294 When changing the time stamp, this means that it will change in steps
2295 of N minutes, as given by the second value.
2297 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2298 numbers should be factors of 60, so for example 5, 10, 15.
2300 When this is larger than 1, you can still force an exact time-stamp by using
2301 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2302 and by using a prefix arg to `S-up/down' to specify the exact number
2303 of minutes to shift."
2304 :group 'org-time
2305 :get '(lambda (var) ; Make sure all entries have 5 elements
2306 (if (integerp (default-value var))
2307 (list (default-value var) 5)
2308 (default-value var)))
2309 :type '(list
2310 (integer :tag "when inserting times")
2311 (integer :tag "when modifying times")))
2313 ;; Normalize old customizations of this variable.
2314 (when (integerp org-time-stamp-rounding-minutes)
2315 (setq org-time-stamp-rounding-minutes
2316 (list org-time-stamp-rounding-minutes
2317 org-time-stamp-rounding-minutes)))
2319 (defcustom org-display-custom-times nil
2320 "Non-nil means overlay custom formats over all time stamps.
2321 The formats are defined through the variable `org-time-stamp-custom-formats'.
2322 To turn this on on a per-file basis, insert anywhere in the file:
2323 #+STARTUP: customtime"
2324 :group 'org-time
2325 :set 'set-default
2326 :type 'sexp)
2327 (make-variable-buffer-local 'org-display-custom-times)
2329 (defcustom org-time-stamp-custom-formats
2330 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2331 "Custom formats for time stamps. See `format-time-string' for the syntax.
2332 These are overlayed over the default ISO format if the variable
2333 `org-display-custom-times' is set. Time like %H:%M should be at the
2334 end of the second format. The custom formats are also honored by export
2335 commands, if custom time display is turned on at the time of export."
2336 :group 'org-time
2337 :type 'sexp)
2339 (defun org-time-stamp-format (&optional long inactive)
2340 "Get the right format for a time string."
2341 (let ((f (if long (cdr org-time-stamp-formats)
2342 (car org-time-stamp-formats))))
2343 (if inactive
2344 (concat "[" (substring f 1 -1) "]")
2345 f)))
2347 (defcustom org-time-clocksum-format "%d:%02d"
2348 "The format string used when creating CLOCKSUM lines, or when
2349 org-mode generates a time duration."
2350 :group 'org-time
2351 :type 'string)
2353 (defcustom org-time-clocksum-use-fractional nil
2354 "If non-nil, \\[org-clock-display] uses fractional times.
2355 org-mode generates a time duration."
2356 :group 'org-time
2357 :type 'boolean)
2359 (defcustom org-time-clocksum-fractional-format "%.2f"
2360 "The format string used when creating CLOCKSUM lines, or when
2361 org-mode generates a time duration."
2362 :group 'org-time
2363 :type 'string)
2365 (defcustom org-deadline-warning-days 14
2366 "No. of days before expiration during which a deadline becomes active.
2367 This variable governs the display in sparse trees and in the agenda.
2368 When 0 or negative, it means use this number (the absolute value of it)
2369 even if a deadline has a different individual lead time specified.
2371 Custom commands can set this variable in the options section."
2372 :group 'org-time
2373 :group 'org-agenda-daily/weekly
2374 :type 'integer)
2376 (defcustom org-read-date-prefer-future t
2377 "Non-nil means assume future for incomplete date input from user.
2378 This affects the following situations:
2379 1. The user gives a month but not a year.
2380 For example, if it is april and you enter \"feb 2\", this will be read
2381 as feb 2, *next* year. \"May 5\", however, will be this year.
2382 2. The user gives a day, but no month.
2383 For example, if today is the 15th, and you enter \"3\", Org-mode will
2384 read this as the third of *next* month. However, if you enter \"17\",
2385 it will be considered as *this* month.
2387 If you set this variable to the symbol `time', then also the following
2388 will work:
2390 3. If the user gives a time, but no day. If the time is before now,
2391 to will be interpreted as tomorrow.
2393 Currently none of this works for ISO week specifications.
2395 When this option is nil, the current day, month and year will always be
2396 used as defaults."
2397 :group 'org-time
2398 :type '(choice
2399 (const :tag "Never" nil)
2400 (const :tag "Check month and day" t)
2401 (const :tag "Check month, day, and time" time)))
2403 (defcustom org-read-date-display-live t
2404 "Non-nil means display current interpretation of date prompt live.
2405 This display will be in an overlay, in the minibuffer."
2406 :group 'org-time
2407 :type 'boolean)
2409 (defcustom org-read-date-popup-calendar t
2410 "Non-nil means pop up a calendar when prompting for a date.
2411 In the calendar, the date can be selected with mouse-1. However, the
2412 minibuffer will also be active, and you can simply enter the date as well.
2413 When nil, only the minibuffer will be available."
2414 :group 'org-time
2415 :type 'boolean)
2416 (if (fboundp 'defvaralias)
2417 (defvaralias 'org-popup-calendar-for-date-prompt
2418 'org-read-date-popup-calendar))
2420 (defcustom org-read-date-minibuffer-setup-hook nil
2421 "Hook to be used to set up keys for the date/time interface.
2422 Add key definitions to `minibuffer-local-map', which will be a temporary
2423 copy."
2424 :group 'org-time
2425 :type 'hook)
2427 (defcustom org-extend-today-until 0
2428 "The hour when your day really ends. Must be an integer.
2429 This has influence for the following applications:
2430 - When switching the agenda to \"today\". It it is still earlier than
2431 the time given here, the day recognized as TODAY is actually yesterday.
2432 - When a date is read from the user and it is still before the time given
2433 here, the current date and time will be assumed to be yesterday, 23:59.
2434 Also, timestamps inserted in remember templates follow this rule.
2436 IMPORTANT: This is a feature whose implementation is and likely will
2437 remain incomplete. Really, it is only here because past midnight seems to
2438 be the favorite working time of John Wiegley :-)"
2439 :group 'org-time
2440 :type 'integer)
2442 (defcustom org-edit-timestamp-down-means-later nil
2443 "Non-nil means S-down will increase the time in a time stamp.
2444 When nil, S-up will increase."
2445 :group 'org-time
2446 :type 'boolean)
2448 (defcustom org-calendar-follow-timestamp-change t
2449 "Non-nil means make the calendar window follow timestamp changes.
2450 When a timestamp is modified and the calendar window is visible, it will be
2451 moved to the new date."
2452 :group 'org-time
2453 :type 'boolean)
2455 (defgroup org-tags nil
2456 "Options concerning tags in Org-mode."
2457 :tag "Org Tags"
2458 :group 'org)
2460 (defcustom org-tag-alist nil
2461 "List of tags allowed in Org-mode files.
2462 When this list is nil, Org-mode will base TAG input on what is already in the
2463 buffer.
2464 The value of this variable is an alist, the car of each entry must be a
2465 keyword as a string, the cdr may be a character that is used to select
2466 that tag through the fast-tag-selection interface.
2467 See the manual for details."
2468 :group 'org-tags
2469 :type '(repeat
2470 (choice
2471 (cons (string :tag "Tag name")
2472 (character :tag "Access char"))
2473 (list :tag "Start radio group"
2474 (const :startgroup)
2475 (option (string :tag "Group description")))
2476 (list :tag "End radio group"
2477 (const :endgroup)
2478 (option (string :tag "Group description")))
2479 (const :tag "New line" (:newline)))))
2481 (defcustom org-tag-persistent-alist nil
2482 "List of tags that will always appear in all Org-mode files.
2483 This is in addition to any in buffer settings or customizations
2484 of `org-tag-alist'.
2485 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2486 The value of this variable is an alist, the car of each entry must be a
2487 keyword as a string, the cdr may be a character that is used to select
2488 that tag through the fast-tag-selection interface.
2489 See the manual for details.
2490 To disable these tags on a per-file basis, insert anywhere in the file:
2491 #+STARTUP: noptag"
2492 :group 'org-tags
2493 :type '(repeat
2494 (choice
2495 (cons (string :tag "Tag name")
2496 (character :tag "Access char"))
2497 (const :tag "Start radio group" (:startgroup))
2498 (const :tag "End radio group" (:endgroup))
2499 (const :tag "New line" (:newline)))))
2501 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2502 "If non-nil, always offer completion for all tags of all agenda files.
2503 Instead of customizing this variable directly, you might want to
2504 set it locally for remember buffers, because there no list of
2505 tags in that file can be created dynamically (there are none).
2507 (add-hook 'org-remember-mode-hook
2508 (lambda ()
2509 (set (make-local-variable
2510 'org-complete-tags-always-offer-all-agenda-tags)
2511 t)))"
2512 :group 'org-tags
2513 :type 'boolean)
2515 (defvar org-file-tags nil
2516 "List of tags that can be inherited by all entries in the file.
2517 The tags will be inherited if the variable `org-use-tag-inheritance'
2518 says they should be.
2519 This variable is populated from #+FILETAGS lines.")
2521 (defcustom org-use-fast-tag-selection 'auto
2522 "Non-nil means use fast tag selection scheme.
2523 This is a special interface to select and deselect tags with single keys.
2524 When nil, fast selection is never used.
2525 When the symbol `auto', fast selection is used if and only if selection
2526 characters for tags have been configured, either through the variable
2527 `org-tag-alist' or through a #+TAGS line in the buffer.
2528 When t, fast selection is always used and selection keys are assigned
2529 automatically if necessary."
2530 :group 'org-tags
2531 :type '(choice
2532 (const :tag "Always" t)
2533 (const :tag "Never" nil)
2534 (const :tag "When selection characters are configured" 'auto)))
2536 (defcustom org-fast-tag-selection-single-key nil
2537 "Non-nil means fast tag selection exits after first change.
2538 When nil, you have to press RET to exit it.
2539 During fast tag selection, you can toggle this flag with `C-c'.
2540 This variable can also have the value `expert'. In this case, the window
2541 displaying the tags menu is not even shown, until you press C-c again."
2542 :group 'org-tags
2543 :type '(choice
2544 (const :tag "No" nil)
2545 (const :tag "Yes" t)
2546 (const :tag "Expert" expert)))
2548 (defvar org-fast-tag-selection-include-todo nil
2549 "Non-nil means fast tags selection interface will also offer TODO states.
2550 This is an undocumented feature, you should not rely on it.")
2552 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2553 "The column to which tags should be indented in a headline.
2554 If this number is positive, it specifies the column. If it is negative,
2555 it means that the tags should be flushright to that column. For example,
2556 -80 works well for a normal 80 character screen."
2557 :group 'org-tags
2558 :type 'integer)
2560 (defcustom org-auto-align-tags t
2561 "Non-nil means realign tags after pro/demotion of TODO state change.
2562 These operations change the length of a headline and therefore shift
2563 the tags around. With this options turned on, after each such operation
2564 the tags are again aligned to `org-tags-column'."
2565 :group 'org-tags
2566 :type 'boolean)
2568 (defcustom org-use-tag-inheritance t
2569 "Non-nil means tags in levels apply also for sublevels.
2570 When nil, only the tags directly given in a specific line apply there.
2571 This may also be a list of tags that should be inherited, or a regexp that
2572 matches tags that should be inherited. Additional control is possible
2573 with the variable `org-tags-exclude-from-inheritance' which gives an
2574 explicit list of tags to be excluded from inheritance., even if the value of
2575 `org-use-tag-inheritance' would select it for inheritance.
2577 If this option is t, a match early-on in a tree can lead to a large
2578 number of matches in the subtree when constructing the agenda or creating
2579 a sparse tree. If you only want to see the first match in a tree during
2580 a search, check out the variable `org-tags-match-list-sublevels'."
2581 :group 'org-tags
2582 :type '(choice
2583 (const :tag "Not" nil)
2584 (const :tag "Always" t)
2585 (repeat :tag "Specific tags" (string :tag "Tag"))
2586 (regexp :tag "Tags matched by regexp")))
2588 (defcustom org-tags-exclude-from-inheritance nil
2589 "List of tags that should never be inherited.
2590 This is a way to exclude a few tags from inheritance. For way to do
2591 the opposite, to actively allow inheritance for selected tags,
2592 see the variable `org-use-tag-inheritance'."
2593 :group 'org-tags
2594 :type '(repeat (string :tag "Tag")))
2596 (defun org-tag-inherit-p (tag)
2597 "Check if TAG is one that should be inherited."
2598 (cond
2599 ((member tag org-tags-exclude-from-inheritance) nil)
2600 ((eq org-use-tag-inheritance t) t)
2601 ((not org-use-tag-inheritance) nil)
2602 ((stringp org-use-tag-inheritance)
2603 (string-match org-use-tag-inheritance tag))
2604 ((listp org-use-tag-inheritance)
2605 (member tag org-use-tag-inheritance))
2606 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2608 (defcustom org-tags-match-list-sublevels t
2609 "Non-nil means list also sublevels of headlines matching a search.
2610 This variable applies to tags/property searches, and also to stuck
2611 projects because this search is based on a tags match as well.
2613 When set to the symbol `indented', sublevels are indented with
2614 leading dots.
2616 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2617 the sublevels of a headline matching a tag search often also match
2618 the same search. Listing all of them can create very long lists.
2619 Setting this variable to nil causes subtrees of a match to be skipped.
2621 This variable is semi-obsolete and probably should always be true. It
2622 is better to limit inheritance to certain tags using the variables
2623 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2624 :group 'org-tags
2625 :type '(choice
2626 (const :tag "No, don't list them" nil)
2627 (const :tag "Yes, do list them" t)
2628 (const :tag "List them, indented with leading dots" indented)))
2630 (defcustom org-tags-sort-function nil
2631 "When set, tags are sorted using this function as a comparator"
2632 :group 'org-tags
2633 :type '(choice
2634 (const :tag "No sorting" nil)
2635 (const :tag "Alphabetical" string<)
2636 (const :tag "Reverse alphabetical" string>)
2637 (function :tag "Custom function" nil)))
2639 (defvar org-tags-history nil
2640 "History of minibuffer reads for tags.")
2641 (defvar org-last-tags-completion-table nil
2642 "The last used completion table for tags.")
2643 (defvar org-after-tags-change-hook nil
2644 "Hook that is run after the tags in a line have changed.")
2646 (defgroup org-properties nil
2647 "Options concerning properties in Org-mode."
2648 :tag "Org Properties"
2649 :group 'org)
2651 (defcustom org-property-format "%-10s %s"
2652 "How property key/value pairs should be formatted by `indent-line'.
2653 When `indent-line' hits a property definition, it will format the line
2654 according to this format, mainly to make sure that the values are
2655 lined-up with respect to each other."
2656 :group 'org-properties
2657 :type 'string)
2659 (defcustom org-use-property-inheritance nil
2660 "Non-nil means properties apply also for sublevels.
2662 This setting is chiefly used during property searches. Turning it on can
2663 cause significant overhead when doing a search, which is why it is not
2664 on by default.
2666 When nil, only the properties directly given in the current entry count.
2667 When t, every property is inherited. The value may also be a list of
2668 properties that should have inheritance, or a regular expression matching
2669 properties that should be inherited.
2671 However, note that some special properties use inheritance under special
2672 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2673 and the properties ending in \"_ALL\" when they are used as descriptor
2674 for valid values of a property.
2676 Note for programmers:
2677 When querying an entry with `org-entry-get', you can control if inheritance
2678 should be used. By default, `org-entry-get' looks only at the local
2679 properties. You can request inheritance by setting the inherit argument
2680 to t (to force inheritance) or to `selective' (to respect the setting
2681 in this variable)."
2682 :group 'org-properties
2683 :type '(choice
2684 (const :tag "Not" nil)
2685 (const :tag "Always" t)
2686 (repeat :tag "Specific properties" (string :tag "Property"))
2687 (regexp :tag "Properties matched by regexp")))
2689 (defun org-property-inherit-p (property)
2690 "Check if PROPERTY is one that should be inherited."
2691 (cond
2692 ((eq org-use-property-inheritance t) t)
2693 ((not org-use-property-inheritance) nil)
2694 ((stringp org-use-property-inheritance)
2695 (string-match org-use-property-inheritance property))
2696 ((listp org-use-property-inheritance)
2697 (member property org-use-property-inheritance))
2698 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2700 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2701 "The default column format, if no other format has been defined.
2702 This variable can be set on the per-file basis by inserting a line
2704 #+COLUMNS: %25ITEM ....."
2705 :group 'org-properties
2706 :type 'string)
2708 (defcustom org-columns-ellipses ".."
2709 "The ellipses to be used when a field in column view is truncated.
2710 When this is the empty string, as many characters as possible are shown,
2711 but then there will be no visual indication that the field has been truncated.
2712 When this is a string of length N, the last N characters of a truncated
2713 field are replaced by this string. If the column is narrower than the
2714 ellipses string, only part of the ellipses string will be shown."
2715 :group 'org-properties
2716 :type 'string)
2718 (defcustom org-columns-modify-value-for-display-function nil
2719 "Function that modifies values for display in column view.
2720 For example, it can be used to cut out a certain part from a time stamp.
2721 The function must take 2 arguments:
2723 column-title The title of the column (*not* the property name)
2724 value The value that should be modified.
2726 The function should return the value that should be displayed,
2727 or nil if the normal value should be used."
2728 :group 'org-properties
2729 :type 'function)
2731 (defcustom org-effort-property "Effort"
2732 "The property that is being used to keep track of effort estimates.
2733 Effort estimates given in this property need to have the format H:MM."
2734 :group 'org-properties
2735 :group 'org-progress
2736 :type '(string :tag "Property"))
2738 (defconst org-global-properties-fixed
2739 '(("VISIBILITY_ALL" . "folded children content all")
2740 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2741 "List of property/value pairs that can be inherited by any entry.
2743 These are fixed values, for the preset properties. The user variable
2744 that can be used to add to this list is `org-global-properties'.
2746 The entries in this list are cons cells where the car is a property
2747 name and cdr is a string with the value. If the value represents
2748 multiple items like an \"_ALL\" property, separate the items by
2749 spaces.")
2751 (defcustom org-global-properties nil
2752 "List of property/value pairs that can be inherited by any entry.
2754 This list will be combined with the constant `org-global-properties-fixed'.
2756 The entries in this list are cons cells where the car is a property
2757 name and cdr is a string with the value.
2759 You can set buffer-local values for the same purpose in the variable
2760 `org-file-properties' this by adding lines like
2762 #+PROPERTY: NAME VALUE"
2763 :group 'org-properties
2764 :type '(repeat
2765 (cons (string :tag "Property")
2766 (string :tag "Value"))))
2768 (defvar org-file-properties nil
2769 "List of property/value pairs that can be inherited by any entry.
2770 Valid for the current buffer.
2771 This variable is populated from #+PROPERTY lines.")
2772 (make-variable-buffer-local 'org-file-properties)
2774 (defgroup org-agenda nil
2775 "Options concerning agenda views in Org-mode."
2776 :tag "Org Agenda"
2777 :group 'org)
2779 (defvar org-category nil
2780 "Variable used by org files to set a category for agenda display.
2781 Such files should use a file variable to set it, for example
2783 # -*- mode: org; org-category: \"ELisp\"
2785 or contain a special line
2787 #+CATEGORY: ELisp
2789 If the file does not specify a category, then file's base name
2790 is used instead.")
2791 (make-variable-buffer-local 'org-category)
2792 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2794 (defcustom org-agenda-files nil
2795 "The files to be used for agenda display.
2796 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2797 \\[org-remove-file]. You can also use customize to edit the list.
2799 If an entry is a directory, all files in that directory that are matched by
2800 `org-agenda-file-regexp' will be part of the file list.
2802 If the value of the variable is not a list but a single file name, then
2803 the list of agenda files is actually stored and maintained in that file, one
2804 agenda file per line. In this file paths can be given relative to
2805 `org-directory'. Tilde expansion and environment variable substitution
2806 are also made."
2807 :group 'org-agenda
2808 :type '(choice
2809 (repeat :tag "List of files and directories" file)
2810 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2812 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2813 "Regular expression to match files for `org-agenda-files'.
2814 If any element in the list in that variable contains a directory instead
2815 of a normal file, all files in that directory that are matched by this
2816 regular expression will be included."
2817 :group 'org-agenda
2818 :type 'regexp)
2820 (defcustom org-agenda-text-search-extra-files nil
2821 "List of extra files to be searched by text search commands.
2822 These files will be search in addition to the agenda files by the
2823 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2824 Note that these files will only be searched for text search commands,
2825 not for the other agenda views like todo lists, tag searches or the weekly
2826 agenda. This variable is intended to list notes and possibly archive files
2827 that should also be searched by these two commands.
2828 In fact, if the first element in the list is the symbol `agenda-archives',
2829 than all archive files of all agenda files will be added to the search
2830 scope."
2831 :group 'org-agenda
2832 :type '(set :greedy t
2833 (const :tag "Agenda Archives" agenda-archives)
2834 (repeat :inline t (file))))
2836 (if (fboundp 'defvaralias)
2837 (defvaralias 'org-agenda-multi-occur-extra-files
2838 'org-agenda-text-search-extra-files))
2840 (defcustom org-agenda-skip-unavailable-files nil
2841 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2842 A nil value means to remove them, after a query, from the list."
2843 :group 'org-agenda
2844 :type 'boolean)
2846 (defcustom org-calendar-to-agenda-key [?c]
2847 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2848 The command `org-calendar-goto-agenda' will be bound to this key. The
2849 default is the character `c' because then `c' can be used to switch back and
2850 forth between agenda and calendar."
2851 :group 'org-agenda
2852 :type 'sexp)
2854 (defcustom org-calendar-agenda-action-key [?k]
2855 "The key to be installed in `calendar-mode-map' for agenda-action.
2856 The command `org-agenda-action' will be bound to this key. The
2857 default is the character `k' because we use the same key in the agenda."
2858 :group 'org-agenda
2859 :type 'sexp)
2861 (defcustom org-calendar-insert-diary-entry-key [?i]
2862 "The key to be installed in `calendar-mode-map' for adding diary entries.
2863 This option is irrelevant until `org-agenda-diary-file' has been configured
2864 to point to an Org-mode file. When that is the case, the command
2865 `org-agenda-diary-entry' will be bound to the key given here, by default
2866 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2867 if you want to continue doing this, you need to change this to a different
2868 key."
2869 :group 'org-agenda
2870 :type 'sexp)
2872 (defcustom org-agenda-diary-file 'diary-file
2873 "File to which to add new entries with the `i' key in agenda and calendar.
2874 When this is the symbol `diary-file', the functionality in the Emacs
2875 calendar will be used to add entries to the `diary-file'. But when this
2876 points to a file, `org-agenda-diary-entry' will be used instead."
2877 :group 'org-agenda
2878 :type '(choice
2879 (const :tag "The standard Emacs diary file" diary-file)
2880 (file :tag "Special Org file diary entries")))
2882 (eval-after-load "calendar"
2883 '(progn
2884 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2885 'org-calendar-goto-agenda)
2886 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2887 'org-agenda-action)
2888 (add-hook 'calendar-mode-hook
2889 (lambda ()
2890 (unless (eq org-agenda-diary-file 'diary-file)
2891 (define-key calendar-mode-map
2892 org-calendar-insert-diary-entry-key
2893 'org-agenda-diary-entry))))))
2895 (defgroup org-latex nil
2896 "Options for embedding LaTeX code into Org-mode."
2897 :tag "Org LaTeX"
2898 :group 'org)
2900 (defcustom org-format-latex-options
2901 '(:foreground default :background default :scale 1.0
2902 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2903 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2904 "Options for creating images from LaTeX fragments.
2905 This is a property list with the following properties:
2906 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2907 `default' means use the foreground of the default face.
2908 :background the background color, or \"Transparent\".
2909 `default' means use the background of the default face.
2910 :scale a scaling factor for the size of the images.
2911 :html-foreground, :html-background, :html-scale
2912 the same numbers for HTML export.
2913 :matchers a list indicating which matchers should be used to
2914 find LaTeX fragments. Valid members of this list are:
2915 \"begin\" find environments
2916 \"$1\" find single characters surrounded by $.$
2917 \"$\" find math expressions surrounded by $...$
2918 \"$$\" find math expressions surrounded by $$....$$
2919 \"\\(\" find math expressions surrounded by \\(...\\)
2920 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2921 :group 'org-latex
2922 :type 'plist)
2924 (defcustom org-format-latex-signal-error t
2925 "Non-nil means signal an error when image creation of LaTeX snippets fails.
2926 When nil, just push out a message."
2927 :group 'org-latex
2928 :type 'boolean)
2930 (defcustom org-format-latex-header "\\documentclass{article}
2931 \\usepackage[usenames]{color}
2932 \\usepackage{amsmath}
2933 \\usepackage[mathscr]{eucal}
2934 \\pagestyle{empty} % do not remove
2935 \[PACKAGES]
2936 \[DEFAULT-PACKAGES]
2937 % The settings below are copied from fullpage.sty
2938 \\setlength{\\textwidth}{\\paperwidth}
2939 \\addtolength{\\textwidth}{-3cm}
2940 \\setlength{\\oddsidemargin}{1.5cm}
2941 \\addtolength{\\oddsidemargin}{-2.54cm}
2942 \\setlength{\\evensidemargin}{\\oddsidemargin}
2943 \\setlength{\\textheight}{\\paperheight}
2944 \\addtolength{\\textheight}{-\\headheight}
2945 \\addtolength{\\textheight}{-\\headsep}
2946 \\addtolength{\\textheight}{-\\footskip}
2947 \\addtolength{\\textheight}{-3cm}
2948 \\setlength{\\topmargin}{1.5cm}
2949 \\addtolength{\\topmargin}{-2.54cm}"
2950 "The document header used for processing LaTeX fragments.
2951 It is imperative that this header make sure that no page number
2952 appears on the page. The package defined in the variables
2953 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
2954 will either replace the placeholder \"[PACKAGES]\" in this header, or they
2955 will be appended."
2956 :group 'org-latex
2957 :type 'string)
2959 (defvar org-format-latex-header-extra nil)
2961 ;; The following variables are defined here because is it also used
2962 ;; when formatting latex fragments. Originally it was part of the
2963 ;; LaTeX exporter, which is why the name includes "export".
2964 (defcustom org-export-latex-default-packages-alist
2965 '(("AUTO" "inputenc")
2966 ("T1" "fontenc")
2967 ("" "fixltx2e")
2968 ("" "graphicx")
2969 ("" "longtable")
2970 ("" "float")
2971 ("" "wrapfig")
2972 ("" "soul")
2973 ("" "t1enc")
2974 ("" "textcomp")
2975 ("" "marvosym")
2976 ("" "wasysym")
2977 ("" "latexsym")
2978 ("" "amssymb")
2979 ("" "hyperref")
2980 "\\tolerance=1000"
2982 "Alist of default packages to be inserted in the header.
2983 Change this only if one of the packages here causes an incompatibility
2984 with another package you are using.
2985 The packages in this list are needed by one part or another of Org-mode
2986 to function properly.
2988 - inputenc, fontenc, t1enc: for basic font and character selection
2989 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
2990 for interpreting the entities in `org-entities'. You can skip some of these
2991 packages if you don't use any of the symbols in it.
2992 - graphicx: for including images
2993 - float, wrapfig: for figure placement
2994 - longtable: for long tables
2995 - hyperref: for cross references
2997 Therefore you should not modify this variable unless you know what you
2998 are doing. The one reason to change it anyway is that you might be loading
2999 some other package that conflicts with one of the default packages.
3000 Each cell is of the format \( \"options\" \"package\" \)."
3001 :group 'org-export-latex
3002 :type '(repeat
3003 (choice
3004 (string :tag "A line of LaTeX")
3005 (list :tag "options/package pair"
3006 (string :tag "options")
3007 (string :tag "package")))))
3009 (defcustom org-export-latex-packages-alist nil
3010 "Alist of packages to be inserted in every LaTeX the header.
3011 These will be inserted after `org-export-latex-default-packages-alist'.
3012 Each cell is of the format \( \"options\" \"package\" \).
3013 Make sure that you only lis packages here which:
3014 - you want in every file
3015 - do not conflict with the default packages in
3016 `org-export-latex-default-packages-alist'
3017 - do not conflict with the setup in `org-format-latex-header'."
3018 :group 'org-export-latex
3019 :type '(repeat
3020 (choice
3021 (string :tag "A line of LaTeX")
3022 (list :tag "options/package pair"
3023 (string :tag "options")
3024 (string :tag "package")))))
3026 (defgroup org-appearance nil
3027 "Settings for Org-mode appearance."
3028 :tag "Org Appearance"
3029 :group 'org)
3031 (defcustom org-level-color-stars-only nil
3032 "Non-nil means fontify only the stars in each headline.
3033 When nil, the entire headline is fontified.
3034 Changing it requires restart of `font-lock-mode' to become effective
3035 also in regions already fontified."
3036 :group 'org-appearance
3037 :type 'boolean)
3039 (defcustom org-hide-leading-stars nil
3040 "Non-nil means hide the first N-1 stars in a headline.
3041 This works by using the face `org-hide' for these stars. This
3042 face is white for a light background, and black for a dark
3043 background. You may have to customize the face `org-hide' to
3044 make this work.
3045 Changing it requires restart of `font-lock-mode' to become effective
3046 also in regions already fontified.
3047 You may also set this on a per-file basis by adding one of the following
3048 lines to the buffer:
3050 #+STARTUP: hidestars
3051 #+STARTUP: showstars"
3052 :group 'org-appearance
3053 :type 'boolean)
3055 (defcustom org-hidden-keywords nil
3056 "List of keywords that should be hidden when typed in the org buffer.
3057 For example, add #+TITLE to this list in order to make the
3058 document title appear in the buffer without the initial #+TITLE:
3059 keyword."
3060 :group 'org-appearance
3061 :type '(set (const :tag "#+AUTHOR" author)
3062 (const :tag "#+DATE" date)
3063 (const :tag "#+EMAIL" email)
3064 (const :tag "#+TITLE" title)))
3066 (defcustom org-fontify-done-headline nil
3067 "Non-nil means change the face of a headline if it is marked DONE.
3068 Normally, only the TODO/DONE keyword indicates the state of a headline.
3069 When this is non-nil, the headline after the keyword is set to the
3070 `org-headline-done' as an additional indication."
3071 :group 'org-appearance
3072 :type 'boolean)
3074 (defcustom org-fontify-emphasized-text t
3075 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3076 Changing this variable requires a restart of Emacs to take effect."
3077 :group 'org-appearance
3078 :type 'boolean)
3080 (defcustom org-fontify-whole-heading-line nil
3081 "Non-nil means fontify the whole line for headings.
3082 This is useful when setting a background color for the
3083 org-level-* faces."
3084 :group 'org-appearance
3085 :type 'boolean)
3087 (defcustom org-highlight-latex-fragments-and-specials nil
3088 "Non-nil means fontify what is treated specially by the exporters."
3089 :group 'org-appearance
3090 :type 'boolean)
3092 (defcustom org-hide-emphasis-markers nil
3093 "Non-nil mean font-lock should hide the emphasis marker characters."
3094 :group 'org-appearance
3095 :type 'boolean)
3097 (defvar org-emph-re nil
3098 "Regular expression for matching emphasis.")
3099 (defvar org-verbatim-re nil
3100 "Regular expression for matching verbatim text.")
3101 (defvar org-emphasis-regexp-components) ; defined just below
3102 (defvar org-emphasis-alist) ; defined just below
3103 (defun org-set-emph-re (var val)
3104 "Set variable and compute the emphasis regular expression."
3105 (set var val)
3106 (when (and (boundp 'org-emphasis-alist)
3107 (boundp 'org-emphasis-regexp-components)
3108 org-emphasis-alist org-emphasis-regexp-components)
3109 (let* ((e org-emphasis-regexp-components)
3110 (pre (car e))
3111 (post (nth 1 e))
3112 (border (nth 2 e))
3113 (body (nth 3 e))
3114 (nl (nth 4 e))
3115 (body1 (concat body "*?"))
3116 (markers (mapconcat 'car org-emphasis-alist ""))
3117 (vmarkers (mapconcat
3118 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3119 org-emphasis-alist "")))
3120 ;; make sure special characters appear at the right position in the class
3121 (if (string-match "\\^" markers)
3122 (setq markers (concat (replace-match "" t t markers) "^")))
3123 (if (string-match "-" markers)
3124 (setq markers (concat (replace-match "" t t markers) "-")))
3125 (if (string-match "\\^" vmarkers)
3126 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3127 (if (string-match "-" vmarkers)
3128 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3129 (if (> nl 0)
3130 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3131 (int-to-string nl) "\\}")))
3132 ;; Make the regexp
3133 (setq org-emph-re
3134 (concat "\\([" pre "]\\|^\\)"
3135 "\\("
3136 "\\([" markers "]\\)"
3137 "\\("
3138 "[^" border "]\\|"
3139 "[^" border "]"
3140 body1
3141 "[^" border "]"
3142 "\\)"
3143 "\\3\\)"
3144 "\\([" post "]\\|$\\)"))
3145 (setq org-verbatim-re
3146 (concat "\\([" pre "]\\|^\\)"
3147 "\\("
3148 "\\([" vmarkers "]\\)"
3149 "\\("
3150 "[^" border "]\\|"
3151 "[^" border "]"
3152 body1
3153 "[^" border "]"
3154 "\\)"
3155 "\\3\\)"
3156 "\\([" post "]\\|$\\)")))))
3158 (defcustom org-emphasis-regexp-components
3159 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3160 "Components used to build the regular expression for emphasis.
3161 This is a list with 6 entries. Terminology: In an emphasis string
3162 like \" *strong word* \", we call the initial space PREMATCH, the final
3163 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3164 and \"trong wor\" is the body. The different components in this variable
3165 specify what is allowed/forbidden in each part:
3167 pre Chars allowed as prematch. Beginning of line will be allowed too.
3168 post Chars allowed as postmatch. End of line will be allowed too.
3169 border The chars *forbidden* as border characters.
3170 body-regexp A regexp like \".\" to match a body character. Don't use
3171 non-shy groups here, and don't allow newline here.
3172 newline The maximum number of newlines allowed in an emphasis exp.
3174 Use customize to modify this, or restart Emacs after changing it."
3175 :group 'org-appearance
3176 :set 'org-set-emph-re
3177 :type '(list
3178 (sexp :tag "Allowed chars in pre ")
3179 (sexp :tag "Allowed chars in post ")
3180 (sexp :tag "Forbidden chars in border ")
3181 (sexp :tag "Regexp for body ")
3182 (integer :tag "number of newlines allowed")
3183 (option (boolean :tag "Please ignore this button"))))
3185 (defcustom org-emphasis-alist
3186 `(("*" bold "<b>" "</b>")
3187 ("/" italic "<i>" "</i>")
3188 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3189 ("=" org-code "<code>" "</code>" verbatim)
3190 ("~" org-verbatim "<code>" "</code>" verbatim)
3191 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3192 "<del>" "</del>")
3194 "Special syntax for emphasized text.
3195 Text starting and ending with a special character will be emphasized, for
3196 example *bold*, _underlined_ and /italic/. This variable sets the marker
3197 characters, the face to be used by font-lock for highlighting in Org-mode
3198 Emacs buffers, and the HTML tags to be used for this.
3199 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3200 Use customize to modify this, or restart Emacs after changing it."
3201 :group 'org-appearance
3202 :set 'org-set-emph-re
3203 :type '(repeat
3204 (list
3205 (string :tag "Marker character")
3206 (choice
3207 (face :tag "Font-lock-face")
3208 (plist :tag "Face property list"))
3209 (string :tag "HTML start tag")
3210 (string :tag "HTML end tag")
3211 (option (const verbatim)))))
3213 (defvar org-protecting-blocks
3214 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3215 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3216 This is needed for font-lock setup.")
3218 ;;; Miscellaneous options
3220 (defgroup org-completion nil
3221 "Completion in Org-mode."
3222 :tag "Org Completion"
3223 :group 'org)
3225 (defcustom org-completion-use-ido nil
3226 "Non-nil means use ido completion wherever possible.
3227 Note that `ido-mode' must be active for this variable to be relevant.
3228 If you decide to turn this variable on, you might well want to turn off
3229 `org-outline-path-complete-in-steps'.
3230 See also `org-completion-use-iswitchb'."
3231 :group 'org-completion
3232 :type 'boolean)
3234 (defcustom org-completion-use-iswitchb nil
3235 "Non-nil means use iswitchb completion wherever possible.
3236 Note that `iswitchb-mode' must be active for this variable to be relevant.
3237 If you decide to turn this variable on, you might well want to turn off
3238 `org-outline-path-complete-in-steps'.
3239 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3240 :group 'org-completion
3241 :type 'boolean)
3243 (defcustom org-completion-fallback-command 'hippie-expand
3244 "The expansion command called by \\[org-complete] in normal context.
3245 Normal means no org-mode-specific context."
3246 :group 'org-completion
3247 :type 'function)
3249 ;;; Functions and variables from their packages
3250 ;; Declared here to avoid compiler warnings
3252 ;; XEmacs only
3253 (defvar outline-mode-menu-heading)
3254 (defvar outline-mode-menu-show)
3255 (defvar outline-mode-menu-hide)
3256 (defvar zmacs-regions) ; XEmacs regions
3258 ;; Emacs only
3259 (defvar mark-active)
3261 ;; Various packages
3262 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3263 (declare-function calendar-forward-day "cal-move" (arg))
3264 (declare-function calendar-goto-date "cal-move" (date))
3265 (declare-function calendar-goto-today "cal-move" ())
3266 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3267 (defvar calc-embedded-close-formula)
3268 (defvar calc-embedded-open-formula)
3269 (declare-function cdlatex-tab "ext:cdlatex" ())
3270 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3271 (defvar font-lock-unfontify-region-function)
3272 (declare-function iswitchb-read-buffer "iswitchb"
3273 (prompt &optional default require-match start matches-set))
3274 (defvar iswitchb-temp-buflist)
3275 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3276 (defvar org-agenda-tags-todo-honor-ignore-options)
3277 (declare-function org-agenda-skip "org-agenda" ())
3278 (declare-function
3279 org-format-agenda-item "org-agenda"
3280 (extra txt &optional category tags dotime noprefix remove-re habitp))
3281 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3282 (declare-function org-agenda-change-all-lines "org-agenda"
3283 (newhead hdmarker &optional fixface just-this))
3284 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3285 (declare-function org-agenda-maybe-redo "org-agenda" ())
3286 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3287 (beg end))
3288 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3289 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3290 "org-agenda" (&optional end))
3291 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3292 (declare-function org-indent-mode "org-indent" (&optional arg))
3293 (declare-function parse-time-string "parse-time" (string))
3294 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3295 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3296 (defvar remember-data-file)
3297 (defvar texmathp-why)
3298 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3299 (declare-function table--at-cell-p "table" (position &optional object at-column))
3301 (defvar w3m-current-url)
3302 (defvar w3m-current-title)
3304 (defvar org-latex-regexps)
3306 ;;; Autoload and prepare some org modules
3308 ;; Some table stuff that needs to be defined here, because it is used
3309 ;; by the functions setting up org-mode or checking for table context.
3311 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3312 "Detects an org-type or table-type table.")
3313 (defconst org-table-line-regexp "^[ \t]*|"
3314 "Detects an org-type table line.")
3315 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3316 "Detects an org-type table line.")
3317 (defconst org-table-hline-regexp "^[ \t]*|-"
3318 "Detects an org-type table hline.")
3319 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3320 "Detects a table-type table hline.")
3321 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3322 "Searching from within a table (any type) this finds the first line
3323 outside the table.")
3325 ;; Autoload the functions in org-table.el that are needed by functions here.
3327 (eval-and-compile
3328 (org-autoload "org-table"
3329 '(org-table-align org-table-begin org-table-blank-field
3330 org-table-convert org-table-convert-region org-table-copy-down
3331 org-table-copy-region org-table-create
3332 org-table-create-or-convert-from-region
3333 org-table-create-with-table.el org-table-current-dline
3334 org-table-cut-region org-table-delete-column org-table-edit-field
3335 org-table-edit-formulas org-table-end org-table-eval-formula
3336 org-table-export org-table-field-info
3337 org-table-get-stored-formulas org-table-goto-column
3338 org-table-hline-and-move org-table-import org-table-insert-column
3339 org-table-insert-hline org-table-insert-row org-table-iterate
3340 org-table-justify-field-maybe org-table-kill-row
3341 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3342 org-table-move-column org-table-move-column-left
3343 org-table-move-column-right org-table-move-row
3344 org-table-move-row-down org-table-move-row-up
3345 org-table-next-field org-table-next-row org-table-paste-rectangle
3346 org-table-previous-field org-table-recalculate
3347 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3348 org-table-toggle-coordinate-overlays
3349 org-table-toggle-formula-debugger org-table-wrap-region
3350 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3352 (defun org-at-table-p (&optional table-type)
3353 "Return t if the cursor is inside an org-type table.
3354 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3355 (if org-enable-table-editor
3356 (save-excursion
3357 (beginning-of-line 1)
3358 (looking-at (if table-type org-table-any-line-regexp
3359 org-table-line-regexp)))
3360 nil))
3361 (defsubst org-table-p () (org-at-table-p))
3363 (defun org-at-table.el-p ()
3364 "Return t if and only if we are at a table.el table."
3365 (and (org-at-table-p 'any)
3366 (save-excursion
3367 (goto-char (org-table-begin 'any))
3368 (looking-at org-table1-hline-regexp))))
3369 (defun org-table-recognize-table.el ()
3370 "If there is a table.el table nearby, recognize it and move into it."
3371 (if org-table-tab-recognizes-table.el
3372 (if (org-at-table.el-p)
3373 (progn
3374 (beginning-of-line 1)
3375 (if (looking-at org-table-dataline-regexp)
3377 (if (looking-at org-table1-hline-regexp)
3378 (progn
3379 (beginning-of-line 2)
3380 (if (looking-at org-table-any-border-regexp)
3381 (beginning-of-line -1)))))
3382 (if (re-search-forward "|" (org-table-end t) t)
3383 (progn
3384 (require 'table)
3385 (if (table--at-cell-p (point))
3387 (message "recognizing table.el table...")
3388 (table-recognize-table)
3389 (message "recognizing table.el table...done")))
3390 (error "This should not happen..."))
3392 nil)
3393 nil))
3395 (defun org-at-table-hline-p ()
3396 "Return t if the cursor is inside a hline in a table."
3397 (if org-enable-table-editor
3398 (save-excursion
3399 (beginning-of-line 1)
3400 (looking-at org-table-hline-regexp))
3401 nil))
3403 (defvar org-table-clean-did-remove-column nil)
3405 (defun org-table-map-tables (function &optional quietly)
3406 "Apply FUNCTION to the start of all tables in the buffer."
3407 (save-excursion
3408 (save-restriction
3409 (widen)
3410 (goto-char (point-min))
3411 (while (re-search-forward org-table-any-line-regexp nil t)
3412 (unless quietly
3413 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3414 (beginning-of-line 1)
3415 (when (looking-at org-table-line-regexp)
3416 (save-excursion (funcall function))
3417 (or (looking-at org-table-line-regexp)
3418 (forward-char 1)))
3419 (re-search-forward org-table-any-border-regexp nil 1))))
3420 (unless quietly (message "Mapping tables: done")))
3422 ;; Declare and autoload functions from org-exp.el & Co
3424 (declare-function org-default-export-plist "org-exp")
3425 (declare-function org-infile-export-plist "org-exp")
3426 (declare-function org-get-current-options "org-exp")
3427 (eval-and-compile
3428 (org-autoload "org-exp"
3429 '(org-export org-export-visible
3430 org-insert-export-options-template
3431 org-table-clean-before-export))
3432 (org-autoload "org-ascii"
3433 '(org-export-as-ascii org-export-ascii-preprocess
3434 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3435 org-export-region-as-ascii))
3436 (org-autoload "org-latex"
3437 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3438 org-replace-region-by-latex org-export-region-as-latex
3439 org-export-as-latex org-export-as-pdf
3440 org-export-as-pdf-and-open))
3441 (org-autoload "org-html"
3442 '(org-export-as-html-and-open
3443 org-export-as-html-batch org-export-as-html-to-buffer
3444 org-replace-region-by-html org-export-region-as-html
3445 org-export-as-html))
3446 (org-autoload "org-docbook"
3447 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3448 org-replace-region-by-docbook org-export-region-as-docbook
3449 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3450 org-export-as-docbook))
3451 (org-autoload "org-icalendar"
3452 '(org-export-icalendar-this-file
3453 org-export-icalendar-all-agenda-files
3454 org-export-icalendar-combine-agenda-files))
3455 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3456 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3458 ;; Declare and autoload functions from org-agenda.el
3460 (eval-and-compile
3461 (org-autoload "org-agenda"
3462 '(org-agenda org-agenda-list org-search-view
3463 org-todo-list org-tags-view org-agenda-list-stuck-projects
3464 org-diary org-agenda-to-appt
3465 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3467 ;; Autoload org-remember
3469 (eval-and-compile
3470 (org-autoload "org-remember"
3471 '(org-remember-insinuate org-remember-annotation
3472 org-remember-apply-template org-remember org-remember-handler)))
3474 ;; Autoload org-clock.el
3477 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3478 (beg end))
3479 (declare-function org-clock-update-mode-line "org-clock" ())
3480 (declare-function org-resolve-clocks "org-clock"
3481 (&optional also-non-dangling-p prompt last-valid))
3482 (defvar org-clock-start-time)
3483 (defvar org-clock-marker (make-marker)
3484 "Marker recording the last clock-in.")
3485 (defvar org-clock-hd-marker (make-marker)
3486 "Marker recording the last clock-in, but the headline position.")
3487 (defvar org-clock-heading ""
3488 "The heading of the current clock entry.")
3489 (defun org-clock-is-active ()
3490 "Return non-nil if clock is currently running.
3491 The return value is actually the clock marker."
3492 (marker-buffer org-clock-marker))
3494 (eval-and-compile
3495 (org-autoload
3496 "org-clock"
3497 '(org-clock-in org-clock-out org-clock-cancel
3498 org-clock-goto org-clock-sum org-clock-display
3499 org-clock-remove-overlays org-clock-report
3500 org-clocktable-shift org-dblock-write:clocktable
3501 org-get-clocktable org-resolve-clocks)))
3503 (defun org-clock-update-time-maybe ()
3504 "If this is a CLOCK line, update it and return t.
3505 Otherwise, return nil."
3506 (interactive)
3507 (save-excursion
3508 (beginning-of-line 1)
3509 (skip-chars-forward " \t")
3510 (when (looking-at org-clock-string)
3511 (let ((re (concat "[ \t]*" org-clock-string
3512 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3513 "\\([ \t]*=>.*\\)?\\)?"))
3514 ts te h m s neg)
3515 (cond
3516 ((not (looking-at re))
3517 nil)
3518 ((not (match-end 2))
3519 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3520 (> org-clock-marker (point))
3521 (<= org-clock-marker (point-at-eol)))
3522 ;; The clock is running here
3523 (setq org-clock-start-time
3524 (apply 'encode-time
3525 (org-parse-time-string (match-string 1))))
3526 (org-clock-update-mode-line)))
3528 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3529 (end-of-line 1)
3530 (setq ts (match-string 1)
3531 te (match-string 3))
3532 (setq s (- (org-float-time
3533 (apply 'encode-time (org-parse-time-string te)))
3534 (org-float-time
3535 (apply 'encode-time (org-parse-time-string ts))))
3536 neg (< s 0)
3537 s (abs s)
3538 h (floor (/ s 3600))
3539 s (- s (* 3600 h))
3540 m (floor (/ s 60))
3541 s (- s (* 60 s)))
3542 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3543 t))))))
3545 (defun org-check-running-clock ()
3546 "Check if the current buffer contains the running clock.
3547 If yes, offer to stop it and to save the buffer with the changes."
3548 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3549 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3550 (buffer-name))))
3551 (org-clock-out)
3552 (when (y-or-n-p "Save changed buffer?")
3553 (save-buffer))))
3555 (defun org-clocktable-try-shift (dir n)
3556 "Check if this line starts a clock table, if yes, shift the time block."
3557 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3558 (org-clocktable-shift dir n)))
3560 ;; Autoload org-timer.el
3562 (eval-and-compile
3563 (org-autoload
3564 "org-timer"
3565 '(org-timer-start org-timer org-timer-item
3566 org-timer-change-times-in-region
3567 org-timer-set-timer
3568 org-timer-reset-timers
3569 org-timer-show-remaining-time)))
3571 ;; Autoload org-feed.el
3573 (eval-and-compile
3574 (org-autoload
3575 "org-feed"
3576 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3579 ;; Autoload org-indent.el
3581 ;; Define the variable already here, to make sure we have it.
3582 (defvar org-indent-mode nil
3583 "Non-nil if Org-Indent mode is enabled.
3584 Use the command `org-indent-mode' to change this variable.")
3586 (eval-and-compile
3587 (org-autoload
3588 "org-indent"
3589 '(org-indent-mode)))
3591 ;; Autoload org-mobile.el
3593 (eval-and-compile
3594 (org-autoload
3595 "org-mobile"
3596 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3598 ;; Autoload archiving code
3599 ;; The stuff that is needed for cycling and tags has to be defined here.
3601 (defgroup org-archive nil
3602 "Options concerning archiving in Org-mode."
3603 :tag "Org Archive"
3604 :group 'org-structure)
3606 (defcustom org-archive-location "%s_archive::"
3607 "The location where subtrees should be archived.
3609 The value of this variable is a string, consisting of two parts,
3610 separated by a double-colon. The first part is a filename and
3611 the second part is a headline.
3613 When the filename is omitted, archiving happens in the same file.
3614 %s in the filename will be replaced by the current file
3615 name (without the directory part). Archiving to a different file
3616 is useful to keep archived entries from contributing to the
3617 Org-mode Agenda.
3619 The archived entries will be filed as subtrees of the specified
3620 headline. When the headline is omitted, the subtrees are simply
3621 filed away at the end of the file, as top-level entries. Also in
3622 the heading you can use %s to represent the file name, this can be
3623 useful when using the same archive for a number of different files.
3625 Here are a few examples:
3626 \"%s_archive::\"
3627 If the current file is Projects.org, archive in file
3628 Projects.org_archive, as top-level trees. This is the default.
3630 \"::* Archived Tasks\"
3631 Archive in the current file, under the top-level headline
3632 \"* Archived Tasks\".
3634 \"~/org/archive.org::\"
3635 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3637 \"~/org/archive.org::From %s\"
3638 Archive in file ~/org/archive.org (absolute path), under headlines
3639 \"From FILENAME\" where file name is the current file name.
3641 \"basement::** Finished Tasks\"
3642 Archive in file ./basement (relative path), as level 3 trees
3643 below the level 2 heading \"** Finished Tasks\".
3645 You may set this option on a per-file basis by adding to the buffer a
3646 line like
3648 #+ARCHIVE: basement::** Finished Tasks
3650 You may also define it locally for a subtree by setting an ARCHIVE property
3651 in the entry. If such a property is found in an entry, or anywhere up
3652 the hierarchy, it will be used."
3653 :group 'org-archive
3654 :type 'string)
3656 (defcustom org-archive-tag "ARCHIVE"
3657 "The tag that marks a subtree as archived.
3658 An archived subtree does not open during visibility cycling, and does
3659 not contribute to the agenda listings.
3660 After changing this, font-lock must be restarted in the relevant buffers to
3661 get the proper fontification."
3662 :group 'org-archive
3663 :group 'org-keywords
3664 :type 'string)
3666 (defcustom org-agenda-skip-archived-trees t
3667 "Non-nil means the agenda will skip any items located in archived trees.
3668 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3669 variable is no longer recommended, you should leave it at the value t.
3670 Instead, use the key `v' to cycle the archives-mode in the agenda."
3671 :group 'org-archive
3672 :group 'org-agenda-skip
3673 :type 'boolean)
3675 (defcustom org-columns-skip-archived-trees t
3676 "Non-nil means ignore archived trees when creating column view."
3677 :group 'org-archive
3678 :group 'org-properties
3679 :type 'boolean)
3681 (defcustom org-cycle-open-archived-trees nil
3682 "Non-nil means `org-cycle' will open archived trees.
3683 An archived tree is a tree marked with the tag ARCHIVE.
3684 When nil, archived trees will stay folded. You can still open them with
3685 normal outline commands like `show-all', but not with the cycling commands."
3686 :group 'org-archive
3687 :group 'org-cycle
3688 :type 'boolean)
3690 (defcustom org-sparse-tree-open-archived-trees nil
3691 "Non-nil means sparse tree construction shows matches in archived trees.
3692 When nil, matches in these trees are highlighted, but the trees are kept in
3693 collapsed state."
3694 :group 'org-archive
3695 :group 'org-sparse-trees
3696 :type 'boolean)
3698 (defun org-cycle-hide-archived-subtrees (state)
3699 "Re-hide all archived subtrees after a visibility state change."
3700 (when (and (not org-cycle-open-archived-trees)
3701 (not (memq state '(overview folded))))
3702 (save-excursion
3703 (let* ((globalp (memq state '(contents all)))
3704 (beg (if globalp (point-min) (point)))
3705 (end (if globalp (point-max) (org-end-of-subtree t))))
3706 (org-hide-archived-subtrees beg end)
3707 (goto-char beg)
3708 (if (looking-at (concat ".*:" org-archive-tag ":"))
3709 (message "%s" (substitute-command-keys
3710 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3712 (defun org-force-cycle-archived ()
3713 "Cycle subtree even if it is archived."
3714 (interactive)
3715 (setq this-command 'org-cycle)
3716 (let ((org-cycle-open-archived-trees t))
3717 (call-interactively 'org-cycle)))
3719 (defun org-hide-archived-subtrees (beg end)
3720 "Re-hide all archived subtrees after a visibility state change."
3721 (save-excursion
3722 (let* ((re (concat ":" org-archive-tag ":")))
3723 (goto-char beg)
3724 (while (re-search-forward re end t)
3725 (when (org-on-heading-p)
3726 (org-flag-subtree t)
3727 (org-end-of-subtree t))))))
3729 (defun org-flag-subtree (flag)
3730 (save-excursion
3731 (org-back-to-heading t)
3732 (outline-end-of-heading)
3733 (outline-flag-region (point)
3734 (progn (org-end-of-subtree t) (point))
3735 flag)))
3737 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3739 (eval-and-compile
3740 (org-autoload "org-archive"
3741 '(org-add-archive-files org-archive-subtree
3742 org-archive-to-archive-sibling org-toggle-archive-tag
3743 org-archive-subtree-default
3744 org-archive-subtree-default-with-confirmation)))
3746 ;; Autoload Column View Code
3748 (declare-function org-columns-number-to-string "org-colview")
3749 (declare-function org-columns-get-format-and-top-level "org-colview")
3750 (declare-function org-columns-compute "org-colview")
3752 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3753 '(org-columns-number-to-string org-columns-get-format-and-top-level
3754 org-columns-compute org-agenda-columns org-columns-remove-overlays
3755 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3757 ;; Autoload ID code
3759 (declare-function org-id-store-link "org-id")
3760 (declare-function org-id-locations-load "org-id")
3761 (declare-function org-id-locations-save "org-id")
3762 (defvar org-id-track-globally)
3763 (org-autoload "org-id"
3764 '(org-id-get-create org-id-new org-id-copy org-id-get
3765 org-id-get-with-outline-path-completion
3766 org-id-get-with-outline-drilling
3767 org-id-goto org-id-find org-id-store-link))
3769 ;; Autoload Plotting Code
3771 (org-autoload "org-plot"
3772 '(org-plot/gnuplot))
3774 ;;; Variables for pre-computed regular expressions, all buffer local
3776 (defvar org-drawer-regexp nil
3777 "Matches first line of a hidden block.")
3778 (make-variable-buffer-local 'org-drawer-regexp)
3779 (defvar org-todo-regexp nil
3780 "Matches any of the TODO state keywords.")
3781 (make-variable-buffer-local 'org-todo-regexp)
3782 (defvar org-not-done-regexp nil
3783 "Matches any of the TODO state keywords except the last one.")
3784 (make-variable-buffer-local 'org-not-done-regexp)
3785 (defvar org-not-done-heading-regexp nil
3786 "Matches a TODO headline that is not done.")
3787 (make-variable-buffer-local 'org-not-done-regexp)
3788 (defvar org-todo-line-regexp nil
3789 "Matches a headline and puts TODO state into group 2 if present.")
3790 (make-variable-buffer-local 'org-todo-line-regexp)
3791 (defvar org-complex-heading-regexp nil
3792 "Matches a headline and puts everything into groups:
3793 group 1: the stars
3794 group 2: The todo keyword, maybe
3795 group 3: Priority cookie
3796 group 4: True headline
3797 group 5: Tags")
3798 (make-variable-buffer-local 'org-complex-heading-regexp)
3799 (defvar org-complex-heading-regexp-format nil)
3800 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3801 (defvar org-todo-line-tags-regexp nil
3802 "Matches a headline and puts TODO state into group 2 if present.
3803 Also put tags into group 4 if tags are present.")
3804 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3805 (defvar org-nl-done-regexp nil
3806 "Matches newline followed by a headline with the DONE keyword.")
3807 (make-variable-buffer-local 'org-nl-done-regexp)
3808 (defvar org-looking-at-done-regexp nil
3809 "Matches the DONE keyword a point.")
3810 (make-variable-buffer-local 'org-looking-at-done-regexp)
3811 (defvar org-ds-keyword-length 12
3812 "Maximum length of the Deadline and SCHEDULED keywords.")
3813 (make-variable-buffer-local 'org-ds-keyword-length)
3814 (defvar org-deadline-regexp nil
3815 "Matches the DEADLINE keyword.")
3816 (make-variable-buffer-local 'org-deadline-regexp)
3817 (defvar org-deadline-time-regexp nil
3818 "Matches the DEADLINE keyword together with a time stamp.")
3819 (make-variable-buffer-local 'org-deadline-time-regexp)
3820 (defvar org-deadline-line-regexp nil
3821 "Matches the DEADLINE keyword and the rest of the line.")
3822 (make-variable-buffer-local 'org-deadline-line-regexp)
3823 (defvar org-scheduled-regexp nil
3824 "Matches the SCHEDULED keyword.")
3825 (make-variable-buffer-local 'org-scheduled-regexp)
3826 (defvar org-scheduled-time-regexp nil
3827 "Matches the SCHEDULED keyword together with a time stamp.")
3828 (make-variable-buffer-local 'org-scheduled-time-regexp)
3829 (defvar org-closed-time-regexp nil
3830 "Matches the CLOSED keyword together with a time stamp.")
3831 (make-variable-buffer-local 'org-closed-time-regexp)
3833 (defvar org-keyword-time-regexp nil
3834 "Matches any of the 4 keywords, together with the time stamp.")
3835 (make-variable-buffer-local 'org-keyword-time-regexp)
3836 (defvar org-keyword-time-not-clock-regexp nil
3837 "Matches any of the 3 keywords, together with the time stamp.")
3838 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3839 (defvar org-maybe-keyword-time-regexp nil
3840 "Matches a timestamp, possibly preceeded by a keyword.")
3841 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3842 (defvar org-planning-or-clock-line-re nil
3843 "Matches a line with planning or clock info.")
3844 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3845 (defvar org-all-time-keywords nil
3846 "List of time keywords.")
3847 (make-variable-buffer-local 'org-all-time-keywords)
3849 (defconst org-plain-time-of-day-regexp
3850 (concat
3851 "\\(\\<[012]?[0-9]"
3852 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3853 "\\(--?"
3854 "\\(\\<[012]?[0-9]"
3855 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3856 "\\)?")
3857 "Regular expression to match a plain time or time range.
3858 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3859 groups carry important information:
3860 0 the full match
3861 1 the first time, range or not
3862 8 the second time, if it is a range.")
3864 (defconst org-plain-time-extension-regexp
3865 (concat
3866 "\\(\\<[012]?[0-9]"
3867 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3868 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3869 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3870 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3871 groups carry important information:
3872 0 the full match
3873 7 hours of duration
3874 9 minutes of duration")
3876 (defconst org-stamp-time-of-day-regexp
3877 (concat
3878 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3879 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3880 "\\(--?"
3881 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3882 "Regular expression to match a timestamp time or time range.
3883 After a match, the following groups carry important information:
3884 0 the full match
3885 1 date plus weekday, for back referencing to make sure both times are on the same day
3886 2 the first time, range or not
3887 4 the second time, if it is a range.")
3889 (defconst org-startup-options
3890 '(("fold" org-startup-folded t)
3891 ("overview" org-startup-folded t)
3892 ("nofold" org-startup-folded nil)
3893 ("showall" org-startup-folded nil)
3894 ("showeverything" org-startup-folded showeverything)
3895 ("content" org-startup-folded content)
3896 ("indent" org-startup-indented t)
3897 ("noindent" org-startup-indented nil)
3898 ("hidestars" org-hide-leading-stars t)
3899 ("showstars" org-hide-leading-stars nil)
3900 ("odd" org-odd-levels-only t)
3901 ("oddeven" org-odd-levels-only nil)
3902 ("align" org-startup-align-all-tables t)
3903 ("noalign" org-startup-align-all-tables nil)
3904 ("customtime" org-display-custom-times t)
3905 ("logdone" org-log-done time)
3906 ("lognotedone" org-log-done note)
3907 ("nologdone" org-log-done nil)
3908 ("lognoteclock-out" org-log-note-clock-out t)
3909 ("nolognoteclock-out" org-log-note-clock-out nil)
3910 ("logrepeat" org-log-repeat state)
3911 ("lognoterepeat" org-log-repeat note)
3912 ("nologrepeat" org-log-repeat nil)
3913 ("logreschedule" org-log-reschedule time)
3914 ("lognotereschedule" org-log-reschedule note)
3915 ("nologreschedule" org-log-reschedule nil)
3916 ("logredeadline" org-log-redeadline time)
3917 ("lognoteredeadline" org-log-redeadline note)
3918 ("nologredeadline" org-log-redeadline nil)
3919 ("logrefile" org-log-refile time)
3920 ("lognoterefile" org-log-refile note)
3921 ("nologrefile" org-log-refile nil)
3922 ("fninline" org-footnote-define-inline t)
3923 ("nofninline" org-footnote-define-inline nil)
3924 ("fnlocal" org-footnote-section nil)
3925 ("fnauto" org-footnote-auto-label t)
3926 ("fnprompt" org-footnote-auto-label nil)
3927 ("fnconfirm" org-footnote-auto-label confirm)
3928 ("fnplain" org-footnote-auto-label plain)
3929 ("fnadjust" org-footnote-auto-adjust t)
3930 ("nofnadjust" org-footnote-auto-adjust nil)
3931 ("constcgs" constants-unit-system cgs)
3932 ("constSI" constants-unit-system SI)
3933 ("noptag" org-tag-persistent-alist nil)
3934 ("hideblocks" org-hide-block-startup t)
3935 ("nohideblocks" org-hide-block-startup nil)
3936 ("beamer" org-startup-with-beamer-mode t))
3937 "Variable associated with STARTUP options for org-mode.
3938 Each element is a list of three items: The startup options as written
3939 in the #+STARTUP line, the corresponding variable, and the value to
3940 set this variable to if the option is found. An optional forth element PUSH
3941 means to push this value onto the list in the variable.")
3943 (defun org-set-regexps-and-options ()
3944 "Precompute regular expressions for current buffer."
3945 (when (org-mode-p)
3946 (org-set-local 'org-todo-kwd-alist nil)
3947 (org-set-local 'org-todo-key-alist nil)
3948 (org-set-local 'org-todo-key-trigger nil)
3949 (org-set-local 'org-todo-keywords-1 nil)
3950 (org-set-local 'org-done-keywords nil)
3951 (org-set-local 'org-todo-heads nil)
3952 (org-set-local 'org-todo-sets nil)
3953 (org-set-local 'org-todo-log-states nil)
3954 (org-set-local 'org-file-properties nil)
3955 (org-set-local 'org-file-tags nil)
3956 (let ((re (org-make-options-regexp
3957 '("CATEGORY" "TODO" "COLUMNS"
3958 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3959 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS")
3960 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3961 (splitre "[ \t]+")
3962 kwds kws0 kwsa key log value cat arch tags const links hw dws
3963 tail sep kws1 prio props ftags drawers beamer-p
3964 ext-setup-or-nil setup-contents (start 0))
3965 (save-excursion
3966 (save-restriction
3967 (widen)
3968 (goto-char (point-min))
3969 (while (or (and ext-setup-or-nil
3970 (string-match re ext-setup-or-nil start)
3971 (setq start (match-end 0)))
3972 (and (setq ext-setup-or-nil nil start 0)
3973 (re-search-forward re nil t)))
3974 (setq key (upcase (match-string 1 ext-setup-or-nil))
3975 value (org-match-string-no-properties 2 ext-setup-or-nil))
3976 (cond
3977 ((equal key "CATEGORY")
3978 (if (string-match "[ \t]+$" value)
3979 (setq value (replace-match "" t t value)))
3980 (setq cat value))
3981 ((member key '("SEQ_TODO" "TODO"))
3982 (push (cons 'sequence (org-split-string value splitre)) kwds))
3983 ((equal key "TYP_TODO")
3984 (push (cons 'type (org-split-string value splitre)) kwds))
3985 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3986 ;; general TODO-like setup
3987 (push (cons (intern (downcase (match-string 1 key)))
3988 (org-split-string value splitre)) kwds))
3989 ((equal key "TAGS")
3990 (setq tags (append tags (if tags '("\\n") nil)
3991 (org-split-string value splitre))))
3992 ((equal key "COLUMNS")
3993 (org-set-local 'org-columns-default-format value))
3994 ((equal key "LINK")
3995 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3996 (push (cons (match-string 1 value)
3997 (org-trim (match-string 2 value)))
3998 links)))
3999 ((equal key "PRIORITIES")
4000 (setq prio (org-split-string value " +")))
4001 ((equal key "PROPERTY")
4002 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4003 (push (cons (match-string 1 value) (match-string 2 value))
4004 props)))
4005 ((equal key "FILETAGS")
4006 (when (string-match "\\S-" value)
4007 (setq ftags
4008 (append
4009 ftags
4010 (apply 'append
4011 (mapcar (lambda (x) (org-split-string x ":"))
4012 (org-split-string value)))))))
4013 ((equal key "DRAWERS")
4014 (setq drawers (org-split-string value splitre)))
4015 ((equal key "CONSTANTS")
4016 (setq const (append const (org-split-string value splitre))))
4017 ((equal key "STARTUP")
4018 (let ((opts (org-split-string value splitre))
4019 l var val)
4020 (while (setq l (pop opts))
4021 (when (setq l (assoc l org-startup-options))
4022 (setq var (nth 1 l) val (nth 2 l))
4023 (if (not (nth 3 l))
4024 (set (make-local-variable var) val)
4025 (if (not (listp (symbol-value var)))
4026 (set (make-local-variable var) nil))
4027 (set (make-local-variable var) (symbol-value var))
4028 (add-to-list var val))))))
4029 ((equal key "ARCHIVE")
4030 (string-match " *$" value)
4031 (setq arch (replace-match "" t t value))
4032 (remove-text-properties 0 (length arch)
4033 '(face t fontified t) arch))
4034 ((equal key "LATEX_CLASS")
4035 (setq beamer-p (equal value "beamer")))
4036 ((equal key "SETUPFILE")
4037 (setq setup-contents (org-file-contents
4038 (expand-file-name
4039 (org-remove-double-quotes value))
4040 'noerror))
4041 (if (not ext-setup-or-nil)
4042 (setq ext-setup-or-nil setup-contents start 0)
4043 (setq ext-setup-or-nil
4044 (concat (substring ext-setup-or-nil 0 start)
4045 "\n" setup-contents "\n"
4046 (substring ext-setup-or-nil start)))))
4047 ))))
4048 (when cat
4049 (org-set-local 'org-category (intern cat))
4050 (push (cons "CATEGORY" cat) props))
4051 (when prio
4052 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4053 (setq prio (mapcar 'string-to-char prio))
4054 (org-set-local 'org-highest-priority (nth 0 prio))
4055 (org-set-local 'org-lowest-priority (nth 1 prio))
4056 (org-set-local 'org-default-priority (nth 2 prio)))
4057 (and props (org-set-local 'org-file-properties (nreverse props)))
4058 (and ftags (org-set-local 'org-file-tags
4059 (mapcar 'org-add-prop-inherited ftags)))
4060 (and drawers (org-set-local 'org-drawers drawers))
4061 (and arch (org-set-local 'org-archive-location arch))
4062 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4063 ;; Process the TODO keywords
4064 (unless kwds
4065 ;; Use the global values as if they had been given locally.
4066 (setq kwds (default-value 'org-todo-keywords))
4067 (if (stringp (car kwds))
4068 (setq kwds (list (cons org-todo-interpretation
4069 (default-value 'org-todo-keywords)))))
4070 (setq kwds (reverse kwds)))
4071 (setq kwds (nreverse kwds))
4072 (let (inter kws kw)
4073 (while (setq kws (pop kwds))
4074 (let ((kws (or
4075 (run-hook-with-args-until-success
4076 'org-todo-setup-filter-hook kws)
4077 kws)))
4078 (setq inter (pop kws) sep (member "|" kws)
4079 kws0 (delete "|" (copy-sequence kws))
4080 kwsa nil
4081 kws1 (mapcar
4082 (lambda (x)
4083 ;; 1 2
4084 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4085 (progn
4086 (setq kw (match-string 1 x)
4087 key (and (match-end 2) (match-string 2 x))
4088 log (org-extract-log-state-settings x))
4089 (push (cons kw (and key (string-to-char key))) kwsa)
4090 (and log (push log org-todo-log-states))
4092 (error "Invalid TODO keyword %s" x)))
4093 kws0)
4094 kwsa (if kwsa (append '((:startgroup))
4095 (nreverse kwsa)
4096 '((:endgroup))))
4097 hw (car kws1)
4098 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4099 tail (list inter hw (car dws) (org-last dws))))
4100 (add-to-list 'org-todo-heads hw 'append)
4101 (push kws1 org-todo-sets)
4102 (setq org-done-keywords (append org-done-keywords dws nil))
4103 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4104 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4105 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4106 (setq org-todo-sets (nreverse org-todo-sets)
4107 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4108 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4109 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4110 ;; Process the constants
4111 (when const
4112 (let (e cst)
4113 (while (setq e (pop const))
4114 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4115 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4116 (setq org-table-formula-constants-local cst)))
4118 ;; Process the tags.
4119 (when tags
4120 (let (e tgs)
4121 (while (setq e (pop tags))
4122 (cond
4123 ((equal e "{") (push '(:startgroup) tgs))
4124 ((equal e "}") (push '(:endgroup) tgs))
4125 ((equal e "\\n") (push '(:newline) tgs))
4126 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4127 (push (cons (match-string 1 e)
4128 (string-to-char (match-string 2 e)))
4129 tgs))
4130 (t (push (list e) tgs))))
4131 (org-set-local 'org-tag-alist nil)
4132 (while (setq e (pop tgs))
4133 (or (and (stringp (car e))
4134 (assoc (car e) org-tag-alist))
4135 (push e org-tag-alist)))))
4137 ;; Compute the regular expressions and other local variables
4138 (if (not org-done-keywords)
4139 (setq org-done-keywords (and org-todo-keywords-1
4140 (list (org-last org-todo-keywords-1)))))
4141 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4142 (length org-scheduled-string)
4143 (length org-clock-string)
4144 (length org-closed-string)))
4145 org-drawer-regexp
4146 (concat "^[ \t]*:\\("
4147 (mapconcat 'regexp-quote org-drawers "\\|")
4148 "\\):[ \t]*$")
4149 org-not-done-keywords
4150 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4151 org-todo-regexp
4152 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4153 "\\|") "\\)\\>")
4154 org-not-done-regexp
4155 (concat "\\<\\("
4156 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4157 "\\)\\>")
4158 org-not-done-heading-regexp
4159 (concat "^\\(\\*+\\)[ \t]+\\("
4160 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4161 "\\)\\>")
4162 org-todo-line-regexp
4163 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4164 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4165 "\\)\\>\\)?[ \t]*\\(.*\\)")
4166 org-complex-heading-regexp
4167 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4168 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4169 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4170 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4171 org-complex-heading-regexp-format
4172 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4173 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4174 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
4175 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4176 org-nl-done-regexp
4177 (concat "\n\\*+[ \t]+"
4178 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4179 "\\)" "\\>")
4180 org-todo-line-tags-regexp
4181 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4182 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4183 (org-re
4184 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4185 org-looking-at-done-regexp
4186 (concat "^" "\\(?:"
4187 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4188 "\\>")
4189 org-deadline-regexp (concat "\\<" org-deadline-string)
4190 org-deadline-time-regexp
4191 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4192 org-deadline-line-regexp
4193 (concat "\\<\\(" org-deadline-string "\\).*")
4194 org-scheduled-regexp
4195 (concat "\\<" org-scheduled-string)
4196 org-scheduled-time-regexp
4197 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4198 org-closed-time-regexp
4199 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4200 org-keyword-time-regexp
4201 (concat "\\<\\(" org-scheduled-string
4202 "\\|" org-deadline-string
4203 "\\|" org-closed-string
4204 "\\|" org-clock-string "\\)"
4205 " *[[<]\\([^]>]+\\)[]>]")
4206 org-keyword-time-not-clock-regexp
4207 (concat "\\<\\(" org-scheduled-string
4208 "\\|" org-deadline-string
4209 "\\|" org-closed-string
4210 "\\)"
4211 " *[[<]\\([^]>]+\\)[]>]")
4212 org-maybe-keyword-time-regexp
4213 (concat "\\(\\<\\(" org-scheduled-string
4214 "\\|" org-deadline-string
4215 "\\|" org-closed-string
4216 "\\|" org-clock-string "\\)\\)?"
4217 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4218 org-planning-or-clock-line-re
4219 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4220 "\\|" org-deadline-string
4221 "\\|" org-closed-string "\\|" org-clock-string
4222 "\\)\\>\\)")
4223 org-all-time-keywords
4224 (mapcar (lambda (w) (substring w 0 -1))
4225 (list org-scheduled-string org-deadline-string
4226 org-clock-string org-closed-string))
4228 (org-compute-latex-and-specials-regexp)
4229 (org-set-font-lock-defaults))))
4231 (defun org-file-contents (file &optional noerror)
4232 "Return the contents of FILE, as a string."
4233 (if (or (not file)
4234 (not (file-readable-p file)))
4235 (if noerror
4236 (progn
4237 (message "Cannot read file %s" file)
4238 (ding) (sit-for 2)
4240 (error "Cannot read file %s" file))
4241 (with-temp-buffer
4242 (insert-file-contents file)
4243 (buffer-string))))
4245 (defun org-extract-log-state-settings (x)
4246 "Extract the log state setting from a TODO keyword string.
4247 This will extract info from a string like \"WAIT(w@/!)\"."
4248 (let (kw key log1 log2)
4249 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4250 (setq kw (match-string 1 x)
4251 key (and (match-end 2) (match-string 2 x))
4252 log1 (and (match-end 3) (match-string 3 x))
4253 log2 (and (match-end 4) (match-string 4 x)))
4254 (and (or log1 log2)
4255 (list kw
4256 (and log1 (if (equal log1 "!") 'time 'note))
4257 (and log2 (if (equal log2 "!") 'time 'note)))))))
4259 (defun org-remove-keyword-keys (list)
4260 "Remove a pair of parenthesis at the end of each string in LIST."
4261 (mapcar (lambda (x)
4262 (if (string-match "(.*)$" x)
4263 (substring x 0 (match-beginning 0))
4265 list))
4267 (defun org-assign-fast-keys (alist)
4268 "Assign fast keys to a keyword-key alist.
4269 Respect keys that are already there."
4270 (let (new e (alt ?0))
4271 (while (setq e (pop alist))
4272 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4273 (cdr e)) ;; Key already assigned.
4274 (push e new)
4275 (let ((clist (string-to-list (downcase (car e))))
4276 (used (append new alist)))
4277 (when (= (car clist) ?@)
4278 (pop clist))
4279 (while (and clist (rassoc (car clist) used))
4280 (pop clist))
4281 (unless clist
4282 (while (rassoc alt used)
4283 (incf alt)))
4284 (push (cons (car e) (or (car clist) alt)) new))))
4285 (nreverse new)))
4287 ;;; Some variables used in various places
4289 (defvar org-window-configuration nil
4290 "Used in various places to store a window configuration.")
4291 (defvar org-selected-window nil
4292 "Used in various places to store a window configuration.")
4293 (defvar org-finish-function nil
4294 "Function to be called when `C-c C-c' is used.
4295 This is for getting out of special buffers like remember.")
4298 ;; FIXME: Occasionally check by commenting these, to make sure
4299 ;; no other functions uses these, forgetting to let-bind them.
4300 (defvar entry)
4301 (defvar last-state)
4302 (defvar date)
4304 ;; Defined somewhere in this file, but used before definition.
4305 (defvar org-entities) ;; defined in org-entities.el
4306 (defvar org-struct-menu)
4307 (defvar org-org-menu)
4308 (defvar org-tbl-menu)
4310 ;;;; Define the Org-mode
4312 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4313 (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."))
4316 ;; We use a before-change function to check if a table might need
4317 ;; an update.
4318 (defvar org-table-may-need-update t
4319 "Indicates that a table might need an update.
4320 This variable is set by `org-before-change-function'.
4321 `org-table-align' sets it back to nil.")
4322 (defun org-before-change-function (beg end)
4323 "Every change indicates that a table might need an update."
4324 (setq org-table-may-need-update t))
4325 (defvar org-mode-map)
4326 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4327 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4328 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4329 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4330 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4331 (defvar org-table-buffer-is-an nil)
4332 (defconst org-outline-regexp "\\*+ ")
4334 ;;;###autoload
4335 (define-derived-mode org-mode outline-mode "Org"
4336 "Outline-based notes management and organizer, alias
4337 \"Carsten's outline-mode for keeping track of everything.\"
4339 Org-mode develops organizational tasks around a NOTES file which
4340 contains information about projects as plain text. Org-mode is
4341 implemented on top of outline-mode, which is ideal to keep the content
4342 of large files well structured. It supports ToDo items, deadlines and
4343 time stamps, which magically appear in the diary listing of the Emacs
4344 calendar. Tables are easily created with a built-in table editor.
4345 Plain text URL-like links connect to websites, emails (VM), Usenet
4346 messages (Gnus), BBDB entries, and any files related to the project.
4347 For printing and sharing of notes, an Org-mode file (or a part of it)
4348 can be exported as a structured ASCII or HTML file.
4350 The following commands are available:
4352 \\{org-mode-map}"
4354 ;; Get rid of Outline menus, they are not needed
4355 ;; Need to do this here because define-derived-mode sets up
4356 ;; the keymap so late. Still, it is a waste to call this each time
4357 ;; we switch another buffer into org-mode.
4358 (if (featurep 'xemacs)
4359 (when (boundp 'outline-mode-menu-heading)
4360 ;; Assume this is Greg's port, it uses easymenu
4361 (easy-menu-remove outline-mode-menu-heading)
4362 (easy-menu-remove outline-mode-menu-show)
4363 (easy-menu-remove outline-mode-menu-hide))
4364 (define-key org-mode-map [menu-bar headings] 'undefined)
4365 (define-key org-mode-map [menu-bar hide] 'undefined)
4366 (define-key org-mode-map [menu-bar show] 'undefined))
4368 (org-load-modules-maybe)
4369 (easy-menu-add org-org-menu)
4370 (easy-menu-add org-tbl-menu)
4371 (org-install-agenda-files-menu)
4372 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4373 (add-to-invisibility-spec '(org-cwidth))
4374 (add-to-invisibility-spec '(org-hide-block . t))
4375 (when (featurep 'xemacs)
4376 (org-set-local 'line-move-ignore-invisible t))
4377 (org-set-local 'outline-regexp org-outline-regexp)
4378 (org-set-local 'outline-level 'org-outline-level)
4379 (when (and org-ellipsis
4380 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4381 (fboundp 'make-glyph-code))
4382 (unless org-display-table
4383 (setq org-display-table (make-display-table)))
4384 (set-display-table-slot
4385 org-display-table 4
4386 (vconcat (mapcar
4387 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4388 org-ellipsis)))
4389 (if (stringp org-ellipsis) org-ellipsis "..."))))
4390 (setq buffer-display-table org-display-table))
4391 (org-set-regexps-and-options)
4392 (when (and org-tag-faces (not org-tags-special-faces-re))
4393 ;; tag faces set outside customize.... force initialization.
4394 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4395 ;; Calc embedded
4396 (org-set-local 'calc-embedded-open-mode "# ")
4397 (modify-syntax-entry ?# "<")
4398 (modify-syntax-entry ?@ "w")
4399 (if org-startup-truncated (setq truncate-lines t))
4400 (org-set-local 'font-lock-unfontify-region-function
4401 'org-unfontify-region)
4402 ;; Activate before-change-function
4403 (org-set-local 'org-table-may-need-update t)
4404 (org-add-hook 'before-change-functions 'org-before-change-function nil
4405 'local)
4406 ;; Check for running clock before killing a buffer
4407 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4408 ;; Paragraphs and auto-filling
4409 (org-set-autofill-regexps)
4410 (setq indent-line-function 'org-indent-line-function)
4411 (org-update-radio-target-regexp)
4412 ;; Make sure dependence stuff works reliably, even for users who set it
4413 ;; too late :-(
4414 (if org-enforce-todo-dependencies
4415 (add-hook 'org-blocker-hook
4416 'org-block-todo-from-children-or-siblings-or-parent)
4417 (remove-hook 'org-blocker-hook
4418 'org-block-todo-from-children-or-siblings-or-parent))
4419 (if org-enforce-todo-checkbox-dependencies
4420 (add-hook 'org-blocker-hook
4421 'org-block-todo-from-checkboxes)
4422 (remove-hook 'org-blocker-hook
4423 'org-block-todo-from-checkboxes))
4425 ;; Comment characters
4426 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4427 (org-set-local 'comment-padding " ")
4429 ;; Align options lines
4430 (org-set-local
4431 'align-mode-rules-list
4432 '((org-in-buffer-settings
4433 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4434 (modes . '(org-mode)))))
4436 ;; Imenu
4437 (org-set-local 'imenu-create-index-function
4438 'org-imenu-get-tree)
4440 ;; Make isearch reveal context
4441 (if (or (featurep 'xemacs)
4442 (not (boundp 'outline-isearch-open-invisible-function)))
4443 ;; Emacs 21 and XEmacs make use of the hook
4444 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4445 ;; Emacs 22 deals with this through a special variable
4446 (org-set-local 'outline-isearch-open-invisible-function
4447 (lambda (&rest ignore) (org-show-context 'isearch))))
4449 ;; Turn on org-beamer-mode?
4450 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4452 ;; If empty file that did not turn on org-mode automatically, make it to.
4453 (if (and org-insert-mode-line-in-empty-file
4454 (interactive-p)
4455 (= (point-min) (point-max)))
4456 (insert "# -*- mode: org -*-\n\n"))
4457 (unless org-inhibit-startup
4458 (when org-startup-align-all-tables
4459 (let ((bmp (buffer-modified-p)))
4460 (org-table-map-tables 'org-table-align 'quietly)
4461 (set-buffer-modified-p bmp)))
4462 (when org-startup-indented
4463 (require 'org-indent)
4464 (org-indent-mode 1))
4465 (unless org-inhibit-startup-visibility-stuff
4466 (org-set-startup-visibility))))
4468 (when (fboundp 'abbrev-table-put)
4469 (abbrev-table-put org-mode-abbrev-table
4470 :parents (list text-mode-abbrev-table)))
4472 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4474 (defun org-current-time ()
4475 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4476 (if (> (car org-time-stamp-rounding-minutes) 1)
4477 (let ((r (car org-time-stamp-rounding-minutes))
4478 (time (decode-time)))
4479 (apply 'encode-time
4480 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4481 (nthcdr 2 time))))
4482 (current-time)))
4484 ;;;; Font-Lock stuff, including the activators
4486 (defvar org-mouse-map (make-sparse-keymap))
4487 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
4488 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
4489 (when org-mouse-1-follows-link
4490 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4491 (when org-tab-follows-link
4492 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4493 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4495 (require 'font-lock)
4497 (defconst org-non-link-chars "]\t\n\r<>")
4498 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4499 "shell" "elisp"))
4500 (defvar org-link-types-re nil
4501 "Matches a link that has a url-like prefix like \"http:\"")
4502 (defvar org-link-re-with-space nil
4503 "Matches a link with spaces, optional angular brackets around it.")
4504 (defvar org-link-re-with-space2 nil
4505 "Matches a link with spaces, optional angular brackets around it.")
4506 (defvar org-link-re-with-space3 nil
4507 "Matches a link with spaces, only for internal part in bracket links.")
4508 (defvar org-angle-link-re nil
4509 "Matches link with angular brackets, spaces are allowed.")
4510 (defvar org-plain-link-re nil
4511 "Matches plain link, without spaces.")
4512 (defvar org-bracket-link-regexp nil
4513 "Matches a link in double brackets.")
4514 (defvar org-bracket-link-analytic-regexp nil
4515 "Regular expression used to analyze links.
4516 Here is what the match groups contain after a match:
4517 1: http:
4518 2: http
4519 3: path
4520 4: [desc]
4521 5: desc")
4522 (defvar org-bracket-link-analytic-regexp++ nil
4523 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4524 (defvar org-any-link-re nil
4525 "Regular expression matching any link.")
4527 (defun org-make-link-regexps ()
4528 "Update the link regular expressions.
4529 This should be called after the variable `org-link-types' has changed."
4530 (setq org-link-types-re
4531 (concat
4532 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4533 org-link-re-with-space
4534 (concat
4535 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4536 "\\([^" org-non-link-chars " ]"
4537 "[^" org-non-link-chars "]*"
4538 "[^" org-non-link-chars " ]\\)>?")
4539 org-link-re-with-space2
4540 (concat
4541 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4542 "\\([^" org-non-link-chars " ]"
4543 "[^\t\n\r]*"
4544 "[^" org-non-link-chars " ]\\)>?")
4545 org-link-re-with-space3
4546 (concat
4547 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4548 "\\([^" org-non-link-chars " ]"
4549 "[^\t\n\r]*\\)")
4550 org-angle-link-re
4551 (concat
4552 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4553 "\\([^" org-non-link-chars " ]"
4554 "[^" org-non-link-chars "]*"
4555 "\\)>")
4556 org-plain-link-re
4557 (concat
4558 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4559 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4560 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4561 org-bracket-link-regexp
4562 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4563 org-bracket-link-analytic-regexp
4564 (concat
4565 "\\[\\["
4566 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4567 "\\([^]]+\\)"
4568 "\\]"
4569 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4570 "\\]")
4571 org-bracket-link-analytic-regexp++
4572 (concat
4573 "\\[\\["
4574 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4575 "\\([^]]+\\)"
4576 "\\]"
4577 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4578 "\\]")
4579 org-any-link-re
4580 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4581 org-angle-link-re "\\)\\|\\("
4582 org-plain-link-re "\\)")))
4584 (org-make-link-regexps)
4586 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4587 "Regular expression for fast time stamp matching.")
4588 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4589 "Regular expression for fast time stamp matching.")
4590 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4591 "Regular expression matching time strings for analysis.
4592 This one does not require the space after the date, so it can be used
4593 on a string that terminates immediately after the date.")
4594 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4595 "Regular expression matching time strings for analysis.")
4596 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4597 "Regular expression matching time stamps, with groups.")
4598 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4599 "Regular expression matching time stamps (also [..]), with groups.")
4600 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4601 "Regular expression matching a time stamp range.")
4602 (defconst org-tr-regexp-both
4603 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4604 "Regular expression matching a time stamp range.")
4605 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4606 org-ts-regexp "\\)?")
4607 "Regular expression matching a time stamp or time stamp range.")
4608 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4609 org-ts-regexp-both "\\)?")
4610 "Regular expression matching a time stamp or time stamp range.
4611 The time stamps may be either active or inactive.")
4613 (defvar org-emph-face nil)
4615 (defun org-do-emphasis-faces (limit)
4616 "Run through the buffer and add overlays to links."
4617 (let (rtn a)
4618 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4619 (if (not (= (char-after (match-beginning 3))
4620 (char-after (match-beginning 4))))
4621 (progn
4622 (setq rtn t)
4623 (setq a (assoc (match-string 3) org-emphasis-alist))
4624 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4625 'face
4626 (nth 1 a))
4627 (and (nth 4 a)
4628 (org-remove-flyspell-overlays-in
4629 (match-beginning 0) (match-end 0)))
4630 (add-text-properties (match-beginning 2) (match-end 2)
4631 '(font-lock-multiline t))
4632 (when org-hide-emphasis-markers
4633 (add-text-properties (match-end 4) (match-beginning 5)
4634 '(invisible org-link))
4635 (add-text-properties (match-beginning 3) (match-end 3)
4636 '(invisible org-link)))))
4637 (backward-char 1))
4638 rtn))
4640 (defun org-emphasize (&optional char)
4641 "Insert or change an emphasis, i.e. a font like bold or italic.
4642 If there is an active region, change that region to a new emphasis.
4643 If there is no region, just insert the marker characters and position
4644 the cursor between them.
4645 CHAR should be either the marker character, or the first character of the
4646 HTML tag associated with that emphasis. If CHAR is a space, the means
4647 to remove the emphasis of the selected region.
4648 If char is not given (for example in an interactive call) it
4649 will be prompted for."
4650 (interactive)
4651 (let ((eal org-emphasis-alist) e det
4652 (erc org-emphasis-regexp-components)
4653 (prompt "")
4654 (string "") beg end move tag c s)
4655 (if (org-region-active-p)
4656 (setq beg (region-beginning) end (region-end)
4657 string (buffer-substring beg end))
4658 (setq move t))
4660 (while (setq e (pop eal))
4661 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4662 c (aref tag 0))
4663 (push (cons c (string-to-char (car e))) det)
4664 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4665 (substring tag 1)))))
4666 (setq det (nreverse det))
4667 (unless char
4668 (message "%s" (concat "Emphasis marker or tag:" prompt))
4669 (setq char (read-char-exclusive)))
4670 (setq char (or (cdr (assoc char det)) char))
4671 (if (equal char ?\ )
4672 (setq s "" move nil)
4673 (unless (assoc (char-to-string char) org-emphasis-alist)
4674 (error "No such emphasis marker: \"%c\"" char))
4675 (setq s (char-to-string char)))
4676 (while (and (> (length string) 1)
4677 (equal (substring string 0 1) (substring string -1))
4678 (assoc (substring string 0 1) org-emphasis-alist))
4679 (setq string (substring string 1 -1)))
4680 (setq string (concat s string s))
4681 (if beg (delete-region beg end))
4682 (unless (or (bolp)
4683 (string-match (concat "[" (nth 0 erc) "\n]")
4684 (char-to-string (char-before (point)))))
4685 (insert " "))
4686 (unless (or (eobp)
4687 (string-match (concat "[" (nth 1 erc) "\n]")
4688 (char-to-string (char-after (point)))))
4689 (insert " ") (backward-char 1))
4690 (insert string)
4691 (and move (backward-char 1))))
4693 (defconst org-nonsticky-props
4694 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4696 (defsubst org-rear-nonsticky-at (pos)
4697 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4699 (defun org-activate-plain-links (limit)
4700 "Run through the buffer and add overlays to links."
4701 (catch 'exit
4702 (let (f)
4703 (if (re-search-forward org-plain-link-re limit t)
4704 (progn
4705 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4706 (setq f (get-text-property (match-beginning 0) 'face))
4707 (if (or (eq f 'org-tag)
4708 (and (listp f) (memq 'org-tag f)))
4710 (add-text-properties (match-beginning 0) (match-end 0)
4711 (list 'mouse-face 'highlight
4712 'face 'org-link
4713 'keymap org-mouse-map))
4714 (org-rear-nonsticky-at (match-end 0)))
4715 t)))))
4717 (defun org-activate-code (limit)
4718 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4719 (progn
4720 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4721 (remove-text-properties (match-beginning 0) (match-end 0)
4722 '(display t invisible t intangible t))
4723 t)))
4725 (defun org-fontify-meta-lines-and-blocks (limit)
4726 "Fontify #+ lines and blocks, in the correct ways."
4727 (let ((case-fold-search t))
4728 (if (re-search-forward
4729 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4730 limit t)
4731 (let ((beg (match-beginning 0))
4732 (beg1 (line-beginning-position 2))
4733 (dc1 (downcase (match-string 2)))
4734 (dc3 (downcase (match-string 3)))
4735 end end1 quoting block-type)
4736 (cond
4737 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4738 ;; a single line of backend-specific content
4739 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4740 (remove-text-properties (match-beginning 0) (match-end 0)
4741 '(display t invisible t intangible t))
4742 (add-text-properties (match-beginning 1) (match-end 3)
4743 '(font-lock-fontified t face org-meta-line))
4744 (add-text-properties (match-beginning 6) (match-end 6)
4745 '(font-lock-fontified t face org-block))
4747 ((and (match-end 4) (equal dc3 "begin"))
4748 ;; Truely a block
4749 (setq block-type (downcase (match-string 5))
4750 quoting (member block-type org-protecting-blocks))
4751 (when (re-search-forward
4752 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4753 nil t) ;; on purpose, we look further than LIMIT
4754 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4755 (when quoting
4756 (remove-text-properties beg end
4757 '(display t invisible t intangible t)))
4758 (add-text-properties
4759 beg end
4760 '(font-lock-fontified t font-lock-multiline t))
4761 (add-text-properties beg beg1 '(face org-meta-line))
4762 (add-text-properties end1 end '(face org-meta-line))
4763 (cond
4764 (quoting
4765 (add-text-properties beg1 end1 '(face org-block)))
4766 ((not org-fontify-quote-and-verse-blocks))
4767 ((string= block-type "quote")
4768 (add-text-properties beg1 end1 '(face org-quote)))
4769 ((string= block-type "verse")
4770 (add-text-properties beg1 end1 '(face org-verse))))
4772 ((member dc1 '("title:" "author:" "email:" "date:"))
4773 (add-text-properties
4774 beg (match-end 3)
4775 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
4776 '(font-lock-fontified t invisible t)
4777 '(font-lock-fontified t face org-document-info-keyword)))
4778 (add-text-properties
4779 (match-beginning 6) (match-end 6)
4780 (if (string-equal dc1 "title:")
4781 '(font-lock-fontified t face org-document-title)
4782 '(font-lock-fontified t face org-document-info))))
4783 ((not (member (char-after beg) '(?\ ?\t)))
4784 ;; just any other in-buffer setting, but not indented
4785 (add-text-properties
4786 beg (match-end 0)
4787 '(font-lock-fontified t face org-meta-line))
4789 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4790 "orgtbl:" "tblfm:" "tblname:"))
4791 (and (match-end 4) (equal dc3 "attr")))
4792 (add-text-properties
4793 beg (match-end 0)
4794 '(font-lock-fontified t face org-meta-line))
4796 ((member dc3 '(" " ""))
4797 (add-text-properties
4798 beg (match-end 0)
4799 '(font-lock-fontified t face font-lock-comment-face)))
4800 (t nil))))))
4802 (defun org-activate-angle-links (limit)
4803 "Run through the buffer and add overlays to links."
4804 (if (re-search-forward org-angle-link-re limit t)
4805 (progn
4806 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4807 (add-text-properties (match-beginning 0) (match-end 0)
4808 (list 'mouse-face 'highlight
4809 'keymap org-mouse-map))
4810 (org-rear-nonsticky-at (match-end 0))
4811 t)))
4813 (defun org-activate-footnote-links (limit)
4814 "Run through the buffer and add overlays to links."
4815 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4816 limit t)
4817 (progn
4818 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4819 (add-text-properties (match-beginning 2) (match-end 2)
4820 (list 'mouse-face 'highlight
4821 'keymap org-mouse-map
4822 'help-echo
4823 (if (= (point-at-bol) (match-beginning 2))
4824 "Footnote definition"
4825 "Footnote reference")
4827 (org-rear-nonsticky-at (match-end 2))
4828 t)))
4830 (defun org-activate-bracket-links (limit)
4831 "Run through the buffer and add overlays to bracketed links."
4832 (if (re-search-forward org-bracket-link-regexp limit t)
4833 (let* ((help (concat "LINK: "
4834 (org-match-string-no-properties 1)))
4835 ;; FIXME: above we should remove the escapes.
4836 ;; but that requires another match, protecting match data,
4837 ;; a lot of overhead for font-lock.
4838 (ip (org-maybe-intangible
4839 (list 'invisible 'org-link
4840 'keymap org-mouse-map 'mouse-face 'highlight
4841 'font-lock-multiline t 'help-echo help)))
4842 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4843 'font-lock-multiline t 'help-echo help)))
4844 ;; We need to remove the invisible property here. Table narrowing
4845 ;; may have made some of this invisible.
4846 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4847 (remove-text-properties (match-beginning 0) (match-end 0)
4848 '(invisible nil))
4849 (if (match-end 3)
4850 (progn
4851 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4852 (org-rear-nonsticky-at (match-beginning 3))
4853 (add-text-properties (match-beginning 3) (match-end 3) vp)
4854 (org-rear-nonsticky-at (match-end 3))
4855 (add-text-properties (match-end 3) (match-end 0) ip)
4856 (org-rear-nonsticky-at (match-end 0)))
4857 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4858 (org-rear-nonsticky-at (match-beginning 1))
4859 (add-text-properties (match-beginning 1) (match-end 1) vp)
4860 (org-rear-nonsticky-at (match-end 1))
4861 (add-text-properties (match-end 1) (match-end 0) ip)
4862 (org-rear-nonsticky-at (match-end 0)))
4863 t)))
4865 (defun org-activate-dates (limit)
4866 "Run through the buffer and add overlays to dates."
4867 (if (re-search-forward org-tsr-regexp-both limit t)
4868 (progn
4869 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4870 (add-text-properties (match-beginning 0) (match-end 0)
4871 (list 'mouse-face 'highlight
4872 'keymap org-mouse-map))
4873 (org-rear-nonsticky-at (match-end 0))
4874 (when org-display-custom-times
4875 (if (match-end 3)
4876 (org-display-custom-time (match-beginning 3) (match-end 3)))
4877 (org-display-custom-time (match-beginning 1) (match-end 1)))
4878 t)))
4880 (defvar org-target-link-regexp nil
4881 "Regular expression matching radio targets in plain text.")
4882 (make-variable-buffer-local 'org-target-link-regexp)
4883 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4884 "Regular expression matching a link target.")
4885 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4886 "Regular expression matching a radio target.")
4887 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4888 "Regular expression matching any target.")
4890 (defun org-activate-target-links (limit)
4891 "Run through the buffer and add overlays to target matches."
4892 (when org-target-link-regexp
4893 (let ((case-fold-search t))
4894 (if (re-search-forward org-target-link-regexp limit t)
4895 (progn
4896 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4897 (add-text-properties (match-beginning 0) (match-end 0)
4898 (list 'mouse-face 'highlight
4899 'keymap org-mouse-map
4900 'help-echo "Radio target link"
4901 'org-linked-text t))
4902 (org-rear-nonsticky-at (match-end 0))
4903 t)))))
4905 (defun org-update-radio-target-regexp ()
4906 "Find all radio targets in this file and update the regular expression."
4907 (interactive)
4908 (when (memq 'radio org-activate-links)
4909 (setq org-target-link-regexp
4910 (org-make-target-link-regexp (org-all-targets 'radio)))
4911 (org-restart-font-lock)))
4913 (defun org-hide-wide-columns (limit)
4914 (let (s e)
4915 (setq s (text-property-any (point) (or limit (point-max))
4916 'org-cwidth t))
4917 (when s
4918 (setq e (next-single-property-change s 'org-cwidth))
4919 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4920 (goto-char e)
4921 t)))
4923 (defvar org-latex-and-specials-regexp nil
4924 "Regular expression for highlighting export special stuff.")
4925 (defvar org-match-substring-regexp)
4926 (defvar org-match-substring-with-braces-regexp)
4928 ;; This should be with the exporter code, but we also use if for font-locking
4929 (defconst org-export-html-special-string-regexps
4930 '(("\\\\-" . "&shy;")
4931 ("---\\([^-]\\)" . "&mdash;\\1")
4932 ("--\\([^-]\\)" . "&ndash;\\1")
4933 ("\\.\\.\\." . "&hellip;"))
4934 "Regular expressions for special string conversion.")
4937 (defun org-compute-latex-and-specials-regexp ()
4938 "Compute regular expression for stuff treated specially by exporters."
4939 (if (not org-highlight-latex-fragments-and-specials)
4940 (org-set-local 'org-latex-and-specials-regexp nil)
4941 (require 'org-exp)
4942 (let*
4943 ((matchers (plist-get org-format-latex-options :matchers))
4944 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4945 org-latex-regexps)))
4946 (org-export-allow-BIND nil)
4947 (options (org-combine-plists (org-default-export-plist)
4948 (org-infile-export-plist)))
4949 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4950 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4951 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4952 (org-export-html-expand (plist-get options :expand-quoted-html))
4953 (org-export-with-special-strings (plist-get options :special-strings))
4954 (re-sub
4955 (cond
4956 ((equal org-export-with-sub-superscripts '{})
4957 (list org-match-substring-with-braces-regexp))
4958 (org-export-with-sub-superscripts
4959 (list org-match-substring-regexp))
4960 (t nil)))
4961 (re-latex
4962 (if org-export-with-LaTeX-fragments
4963 (mapcar (lambda (x) (nth 1 x)) latexs)))
4964 (re-macros
4965 (if org-export-with-TeX-macros
4966 (list (concat "\\\\"
4967 (regexp-opt
4968 (append (mapcar 'car (append org-entities-user
4969 org-entities))
4970 (if (boundp 'org-latex-entities)
4971 (mapcar (lambda (x)
4972 (or (car-safe x) x))
4973 org-latex-entities)
4974 nil))
4975 'words))) ; FIXME
4977 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4978 (re-special (if org-export-with-special-strings
4979 (mapcar (lambda (x) (car x))
4980 org-export-html-special-string-regexps)))
4981 (re-rest
4982 (delq nil
4983 (list
4984 (if org-export-html-expand "@<[^>\n]+>")
4985 ))))
4986 (org-set-local
4987 'org-latex-and-specials-regexp
4988 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4989 re-rest) "\\|")))))
4991 (defun org-do-latex-and-special-faces (limit)
4992 "Run through the buffer and add overlays to links."
4993 (when org-latex-and-specials-regexp
4994 (let (rtn d)
4995 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4996 limit t))
4997 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4998 'face))
4999 '(org-code org-verbatim underline)))
5000 (progn
5001 (setq rtn t
5002 d (cond ((member (char-after (1+ (match-beginning 0)))
5003 '(?_ ?^)) 1)
5004 (t 0)))
5005 (font-lock-prepend-text-property
5006 (+ d (match-beginning 0)) (match-end 0)
5007 'face 'org-latex-and-export-specials)
5008 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5009 '(font-lock-multiline t)))))
5010 rtn)))
5012 (defun org-restart-font-lock ()
5013 "Restart font-lock-mode, to force refontification."
5014 (when (and (boundp 'font-lock-mode) font-lock-mode)
5015 (font-lock-mode -1)
5016 (font-lock-mode 1)))
5018 (defun org-all-targets (&optional radio)
5019 "Return a list of all targets in this file.
5020 With optional argument RADIO, only find radio targets."
5021 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5022 rtn)
5023 (save-excursion
5024 (goto-char (point-min))
5025 (while (re-search-forward re nil t)
5026 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5027 rtn)))
5029 (defun org-make-target-link-regexp (targets)
5030 "Make regular expression matching all strings in TARGETS.
5031 The regular expression finds the targets also if there is a line break
5032 between words."
5033 (and targets
5034 (concat
5035 "\\<\\("
5036 (mapconcat
5037 (lambda (x)
5038 (while (string-match " +" x)
5039 (setq x (replace-match "\\s-+" t t x)))
5041 targets
5042 "\\|")
5043 "\\)\\>")))
5045 (defun org-activate-tags (limit)
5046 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5047 (progn
5048 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5049 (add-text-properties (match-beginning 1) (match-end 1)
5050 (list 'mouse-face 'highlight
5051 'keymap org-mouse-map))
5052 (org-rear-nonsticky-at (match-end 1))
5053 t)))
5055 (defun org-outline-level ()
5056 "Compute the outline level of the heading at point.
5057 This function assumes that the cursor is at the beginning of a line matched
5058 by outline-regexp. Otherwise it returns garbage.
5059 If this is called at a normal headline, the level is the number of stars.
5060 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
5061 For plain list items, if they are matched by `outline-regexp', this returns
5062 1000 plus the line indentation."
5063 (save-excursion
5064 (looking-at outline-regexp)
5065 (if (match-beginning 1)
5066 (+ (org-get-string-indentation (match-string 1)) 1000)
5067 (1- (- (match-end 0) (match-beginning 0))))))
5069 (defvar org-font-lock-keywords nil)
5071 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5072 "Regular expression matching a property line.")
5074 (defvar org-font-lock-hook nil
5075 "Functions to be called for special font lock stuff.")
5077 (defun org-font-lock-hook (limit)
5078 (run-hook-with-args 'org-font-lock-hook limit))
5080 (defun org-set-font-lock-defaults ()
5081 (let* ((em org-fontify-emphasized-text)
5082 (lk org-activate-links)
5083 (org-font-lock-extra-keywords
5084 (list
5085 ;; Call the hook
5086 '(org-font-lock-hook)
5087 ;; Headlines
5088 `(,(if org-fontify-whole-heading-line
5089 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5090 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5091 (1 (org-get-level-face 1))
5092 (2 (org-get-level-face 2))
5093 (3 (org-get-level-face 3)))
5094 ;; Table lines
5095 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5096 (1 'org-table t))
5097 ;; Table internals
5098 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5099 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5100 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5101 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
5102 ;; Drawers
5103 (list org-drawer-regexp '(0 'org-special-keyword t))
5104 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5105 ;; Properties
5106 (list org-property-re
5107 '(1 'org-special-keyword t)
5108 '(3 'org-property-value t))
5109 ;; Links
5110 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5111 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5112 (if (memq 'plain lk) '(org-activate-plain-links))
5113 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5114 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5115 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5116 (if (memq 'footnote lk) '(org-activate-footnote-links
5117 (2 'org-footnote t)))
5118 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5119 '(org-hide-wide-columns (0 nil append))
5120 ;; TODO lines
5121 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5122 '(1 (org-get-todo-face 1) t))
5123 ;; DONE
5124 (if org-fontify-done-headline
5125 (list (concat "^[*]+ +\\<\\("
5126 (mapconcat 'regexp-quote org-done-keywords "\\|")
5127 "\\)\\(.*\\)")
5128 '(2 'org-headline-done t))
5129 nil)
5130 ;; Priorities
5131 '(org-font-lock-add-priority-faces)
5132 ;; Tags
5133 '(org-font-lock-add-tag-faces)
5134 ;; Special keywords
5135 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5136 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5137 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5138 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5139 ;; Emphasis
5140 (if em
5141 (if (featurep 'xemacs)
5142 '(org-do-emphasis-faces (0 nil append))
5143 '(org-do-emphasis-faces)))
5144 ;; Checkboxes
5145 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5146 2 'org-checkbox prepend)
5147 (if org-provide-checkbox-statistics
5148 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5149 (0 (org-get-checkbox-statistics-face) t)))
5150 ;; Description list items
5151 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5152 2 'bold prepend)
5153 ;; ARCHIVEd headings
5154 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5155 '(1 'org-archived prepend))
5156 ;; Specials
5157 '(org-do-latex-and-special-faces)
5158 ;; Code
5159 '(org-activate-code (1 'org-code t))
5160 ;; COMMENT
5161 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5162 "\\|" org-quote-string "\\)\\>")
5163 '(1 'org-special-keyword t))
5164 '("^#.*" (0 'font-lock-comment-face t))
5165 ;; Blocks and meta lines
5166 '(org-fontify-meta-lines-and-blocks)
5168 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5169 ;; Now set the full font-lock-keywords
5170 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5171 (org-set-local 'font-lock-defaults
5172 '(org-font-lock-keywords t nil nil backward-paragraph))
5173 (kill-local-variable 'font-lock-keywords) nil))
5175 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5176 "Fontify string S like in Org-mode"
5177 (with-temp-buffer
5178 (insert s)
5179 (let ((org-odd-levels-only odd-levels))
5180 (org-mode)
5181 (font-lock-fontify-buffer)
5182 (buffer-string))))
5184 (defvar org-m nil)
5185 (defvar org-l nil)
5186 (defvar org-f nil)
5187 (defun org-get-level-face (n)
5188 "Get the right face for match N in font-lock matching of headlines."
5189 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5190 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5191 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5192 (cond
5193 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5194 ((eq n 2) org-f)
5195 (t (if org-level-color-stars-only nil org-f))))
5197 (defun org-get-todo-face (kwd)
5198 "Get the right face for a TODO keyword KWD.
5199 If KWD is a number, get the corresponding match group."
5200 (if (numberp kwd) (setq kwd (match-string kwd)))
5201 (or (org-face-from-face-or-color
5202 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5203 (and (member kwd org-done-keywords) 'org-done)
5204 'org-todo))
5206 (defun org-face-from-face-or-color (context inherit face-or-color)
5207 "Create a face list that inherits INHERIT, but sets the foreground color.
5208 When FACE-OR-COLOR is not a string, just return it."
5209 (if (stringp face-or-color)
5210 (list :inherit inherit
5211 (cdr (assoc context org-faces-easy-properties))
5212 face-or-color)
5213 face-or-color))
5215 (defun org-font-lock-add-tag-faces (limit)
5216 "Add the special tag faces."
5217 (when (and org-tag-faces org-tags-special-faces-re)
5218 (while (re-search-forward org-tags-special-faces-re limit t)
5219 (add-text-properties (match-beginning 1) (match-end 1)
5220 (list 'face (org-get-tag-face 1)
5221 'font-lock-fontified t))
5222 (backward-char 1))))
5224 (defun org-font-lock-add-priority-faces (limit)
5225 "Add the special priority faces."
5226 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5227 (add-text-properties
5228 (match-beginning 0) (match-end 0)
5229 (list 'face (or (org-face-from-face-or-color
5230 'priority 'org-special-keyword
5231 (cdr (assoc (char-after (match-beginning 1))
5232 org-priority-faces)))
5233 'org-special-keyword)
5234 'font-lock-fontified t))))
5236 (defun org-get-tag-face (kwd)
5237 "Get the right face for a TODO keyword KWD.
5238 If KWD is a number, get the corresponding match group."
5239 (if (numberp kwd) (setq kwd (match-string kwd)))
5240 (or (org-face-from-face-or-color
5241 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5242 'org-tag))
5244 (defun org-unfontify-region (beg end &optional maybe_loudly)
5245 "Remove fontification and activation overlays from links."
5246 (font-lock-default-unfontify-region beg end)
5247 (let* ((buffer-undo-list t)
5248 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5249 (inhibit-modification-hooks t)
5250 deactivate-mark buffer-file-name buffer-file-truename)
5251 (remove-text-properties
5252 beg end
5253 (if org-indent-mode
5254 ;; also remove line-prefix and wrap-prefix properties
5255 '(mouse-face t keymap t org-linked-text t
5256 invisible t intangible t
5257 line-prefix t wrap-prefix t
5258 org-no-flyspell t)
5259 '(mouse-face t keymap t org-linked-text t
5260 invisible t intangible t
5261 org-no-flyspell t)))))
5263 ;;;; Visibility cycling, including org-goto and indirect buffer
5265 ;;; Cycling
5267 (defvar org-cycle-global-status nil)
5268 (make-variable-buffer-local 'org-cycle-global-status)
5269 (defvar org-cycle-subtree-status nil)
5270 (make-variable-buffer-local 'org-cycle-subtree-status)
5272 ;;;###autoload
5274 (defvar org-inlinetask-min-level)
5276 (defun org-cycle (&optional arg)
5277 "TAB-action and visibility cycling for Org-mode.
5279 This is the command invoked in Org-mode by the TAB key. Its main purpose
5280 is outline visibility cycling, but it also invokes other actions
5281 in special contexts.
5283 - When this function is called with a prefix argument, rotate the entire
5284 buffer through 3 states (global cycling)
5285 1. OVERVIEW: Show only top-level headlines.
5286 2. CONTENTS: Show all headlines of all levels, but no body text.
5287 3. SHOW ALL: Show everything.
5288 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5289 determined by the variable `org-startup-folded', and by any VISIBILITY
5290 properties in the buffer.
5291 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5292 including any drawers.
5294 - When inside a table, re-align the table and move to the next field.
5296 - When point is at the beginning of a headline, rotate the subtree started
5297 by this line through 3 different states (local cycling)
5298 1. FOLDED: Only the main headline is shown.
5299 2. CHILDREN: The main headline and the direct children are shown.
5300 From this state, you can move to one of the children
5301 and zoom in further.
5302 3. SUBTREE: Show the entire subtree, including body text.
5303 If there is no subtree, switch directly from CHILDREN to FOLDED.
5305 - When point is at the beginning of an empty headline and the variable
5306 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5307 of the headline by demoting and promoting it to likely levels. This
5308 speeds up creation document structure by presing TAB once or several
5309 times right after creating a new headline.
5311 - When there is a numeric prefix, go up to a heading with level ARG, do
5312 a `show-subtree' and return to the previous cursor position. If ARG
5313 is negative, go up that many levels.
5315 - When point is not at the beginning of a headline, execute the global
5316 binding for TAB, which is re-indenting the line. See the option
5317 `org-cycle-emulate-tab' for details.
5319 - Special case: if point is at the beginning of the buffer and there is
5320 no headline in line 1, this function will act as if called with prefix arg.
5321 But only if also the variable `org-cycle-global-at-bob' is t."
5322 (interactive "P")
5323 (org-load-modules-maybe)
5324 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5325 (and org-cycle-level-after-item/entry-creation
5326 (or (org-cycle-level)
5327 (org-cycle-item-indentation))))
5328 (let* ((limit-level
5329 (or org-cycle-max-level
5330 (and (boundp 'org-inlinetask-min-level)
5331 org-inlinetask-min-level
5332 (1- org-inlinetask-min-level))))
5333 (nstars (and limit-level
5334 (if org-odd-levels-only
5335 (and limit-level (1- (* limit-level 2)))
5336 limit-level)))
5337 (outline-regexp
5338 (cond
5339 ((not (org-mode-p)) outline-regexp)
5340 ((or (eq org-cycle-include-plain-lists 'integrate)
5341 (and org-cycle-include-plain-lists (org-at-item-p)))
5342 (concat "\\(?:\\*"
5343 (if nstars (format "\\{1,%d\\}" nstars) "+")
5344 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5345 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5346 (bob-special (and org-cycle-global-at-bob (bobp)
5347 (not (looking-at outline-regexp))))
5348 (org-cycle-hook
5349 (if bob-special
5350 (delq 'org-optimize-window-after-visibility-change
5351 (copy-sequence org-cycle-hook))
5352 org-cycle-hook))
5353 (pos (point)))
5355 (if (or bob-special (equal arg '(4)))
5356 ;; special case: use global cycling
5357 (setq arg t))
5359 (cond
5361 ((equal arg '(16))
5362 (org-set-startup-visibility)
5363 (message "Startup visibility, plus VISIBILITY properties"))
5365 ((equal arg '(64))
5366 (show-all)
5367 (message "Entire buffer visible, including drawers"))
5369 ((org-at-table-p 'any)
5370 ;; Enter the table or move to the next field in the table
5371 (if (org-at-table.el-p)
5372 (message "Use C-c ' to edit table.el tables")
5373 (if arg (org-table-edit-field t)
5374 (org-table-justify-field-maybe)
5375 (call-interactively 'org-table-next-field))))
5377 ((run-hook-with-args-until-success
5378 'org-tab-after-check-for-table-hook))
5380 ((eq arg t) ;; Global cycling
5381 (org-cycle-internal-global))
5383 ((and org-drawers org-drawer-regexp
5384 (save-excursion
5385 (beginning-of-line 1)
5386 (looking-at org-drawer-regexp)))
5387 ;; Toggle block visibility
5388 (org-flag-drawer
5389 (not (get-char-property (match-end 0) 'invisible))))
5391 ((integerp arg)
5392 ;; Show-subtree, ARG levels up from here.
5393 (save-excursion
5394 (org-back-to-heading)
5395 (outline-up-heading (if (< arg 0) (- arg)
5396 (- (funcall outline-level) arg)))
5397 (org-show-subtree)))
5399 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5400 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5402 (org-cycle-internal-local))
5404 ;; TAB emulation and template completion
5405 (buffer-read-only (org-back-to-heading))
5407 ((run-hook-with-args-until-success
5408 'org-tab-after-check-for-cycling-hook))
5410 ((org-try-structure-completion))
5412 ((org-try-cdlatex-tab))
5414 ((run-hook-with-args-until-success
5415 'org-tab-before-tab-emulation-hook))
5417 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5418 (or (not (bolp))
5419 (not (looking-at outline-regexp))))
5420 (call-interactively (global-key-binding "\t")))
5422 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5423 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5424 (or (and (eq org-cycle-emulate-tab 'white)
5425 (= (match-end 0) (point-at-eol)))
5426 (and (eq org-cycle-emulate-tab 'whitestart)
5427 (>= (match-end 0) pos))))
5429 (eq org-cycle-emulate-tab t))
5430 (call-interactively (global-key-binding "\t")))
5432 (t (save-excursion
5433 (org-back-to-heading)
5434 (org-cycle)))))))
5436 (defun org-cycle-internal-global ()
5437 "Do the global cycling action."
5438 (cond
5439 ((and (eq last-command this-command)
5440 (eq org-cycle-global-status 'overview))
5441 ;; We just created the overview - now do table of contents
5442 ;; This can be slow in very large buffers, so indicate action
5443 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5444 (message "CONTENTS...")
5445 (org-content)
5446 (message "CONTENTS...done")
5447 (setq org-cycle-global-status 'contents)
5448 (run-hook-with-args 'org-cycle-hook 'contents))
5450 ((and (eq last-command this-command)
5451 (eq org-cycle-global-status 'contents))
5452 ;; We just showed the table of contents - now show everything
5453 (run-hook-with-args 'org-pre-cycle-hook 'all)
5454 (show-all)
5455 (message "SHOW ALL")
5456 (setq org-cycle-global-status 'all)
5457 (run-hook-with-args 'org-cycle-hook 'all))
5460 ;; Default action: go to overview
5461 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5462 (org-overview)
5463 (message "OVERVIEW")
5464 (setq org-cycle-global-status 'overview)
5465 (run-hook-with-args 'org-cycle-hook 'overview))))
5467 (defun org-cycle-internal-local ()
5468 "Do the local cycling action."
5469 (org-back-to-heading)
5470 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5471 ;; First, some boundaries
5472 (save-excursion
5473 (org-back-to-heading)
5474 (setq level (funcall outline-level))
5475 (save-excursion
5476 (beginning-of-line 2)
5477 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5478 ; XEmacs does not have `next-single-char-property-change'
5479 ; I'm not sure about Emacs 21.
5480 (while (and (not (eobp)) ;; this is like `next-line'
5481 (get-char-property (1- (point)) 'invisible))
5482 (beginning-of-line 2))
5483 (while (and (not (eobp)) ;; this is like `next-line'
5484 (get-char-property (1- (point)) 'invisible))
5485 (goto-char (next-single-char-property-change (point) 'invisible))
5486 (and (eolp) (beginning-of-line 2))))
5487 (setq eol (point)))
5488 (outline-end-of-heading) (setq eoh (point))
5489 (save-excursion
5490 (outline-next-heading)
5491 (setq has-children (and (org-at-heading-p t)
5492 (> (funcall outline-level) level))))
5493 (org-end-of-subtree t)
5494 (unless (eobp)
5495 (skip-chars-forward " \t\n")
5496 (beginning-of-line 1) ; in case this is an item
5498 (setq eos (if (eobp) (point) (1- (point)))))
5499 ;; Find out what to do next and set `this-command'
5500 (cond
5501 ((= eos eoh)
5502 ;; Nothing is hidden behind this heading
5503 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5504 (message "EMPTY ENTRY")
5505 (setq org-cycle-subtree-status nil)
5506 (save-excursion
5507 (goto-char eos)
5508 (outline-next-heading)
5509 (if (org-invisible-p) (org-flag-heading nil))))
5510 ((and (or (>= eol eos)
5511 (not (string-match "\\S-" (buffer-substring eol eos))))
5512 (or has-children
5513 (not (setq children-skipped
5514 org-cycle-skip-children-state-if-no-children))))
5515 ;; Entire subtree is hidden in one line: children view
5516 (run-hook-with-args 'org-pre-cycle-hook 'children)
5517 (org-show-entry)
5518 (show-children)
5519 (message "CHILDREN")
5520 (save-excursion
5521 (goto-char eos)
5522 (outline-next-heading)
5523 (if (org-invisible-p) (org-flag-heading nil)))
5524 (setq org-cycle-subtree-status 'children)
5525 (run-hook-with-args 'org-cycle-hook 'children))
5526 ((or children-skipped
5527 (and (eq last-command this-command)
5528 (eq org-cycle-subtree-status 'children)))
5529 ;; We just showed the children, or no children are there,
5530 ;; now show everything.
5531 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5532 (org-show-subtree)
5533 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5534 (setq org-cycle-subtree-status 'subtree)
5535 (run-hook-with-args 'org-cycle-hook 'subtree))
5537 ;; Default action: hide the subtree.
5538 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5539 (hide-subtree)
5540 (message "FOLDED")
5541 (setq org-cycle-subtree-status 'folded)
5542 (run-hook-with-args 'org-cycle-hook 'folded)))))
5544 ;;;###autoload
5545 (defun org-global-cycle (&optional arg)
5546 "Cycle the global visibility. For details see `org-cycle'.
5547 With C-u prefix arg, switch to startup visibility.
5548 With a numeric prefix, show all headlines up to that level."
5549 (interactive "P")
5550 (let ((org-cycle-include-plain-lists
5551 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5552 (cond
5553 ((integerp arg)
5554 (show-all)
5555 (hide-sublevels arg)
5556 (setq org-cycle-global-status 'contents))
5557 ((equal arg '(4))
5558 (org-set-startup-visibility)
5559 (message "Startup visibility, plus VISIBILITY properties."))
5561 (org-cycle '(4))))))
5563 (defun org-set-startup-visibility ()
5564 "Set the visibility required by startup options and properties."
5565 (cond
5566 ((eq org-startup-folded t)
5567 (org-cycle '(4)))
5568 ((eq org-startup-folded 'content)
5569 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5570 (org-cycle '(4)) (org-cycle '(4)))))
5571 (unless (eq org-startup-folded 'showeverything)
5572 (if org-hide-block-startup (org-hide-block-all))
5573 (org-set-visibility-according-to-property 'no-cleanup)
5574 (org-cycle-hide-archived-subtrees 'all)
5575 (org-cycle-hide-drawers 'all)
5576 (org-cycle-show-empty-lines 'all)))
5578 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5579 "Switch subtree visibilities according to :VISIBILITY: property."
5580 (interactive)
5581 (let (org-show-entry-below state)
5582 (save-excursion
5583 (goto-char (point-min))
5584 (while (re-search-forward
5585 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5586 nil t)
5587 (setq state (match-string 1))
5588 (save-excursion
5589 (org-back-to-heading t)
5590 (hide-subtree)
5591 (org-reveal)
5592 (cond
5593 ((equal state '("fold" "folded"))
5594 (hide-subtree))
5595 ((equal state "children")
5596 (org-show-hidden-entry)
5597 (show-children))
5598 ((equal state "content")
5599 (save-excursion
5600 (save-restriction
5601 (org-narrow-to-subtree)
5602 (org-content))))
5603 ((member state '("all" "showall"))
5604 (show-subtree)))))
5605 (unless no-cleanup
5606 (org-cycle-hide-archived-subtrees 'all)
5607 (org-cycle-hide-drawers 'all)
5608 (org-cycle-show-empty-lines 'all)))))
5610 (defun org-overview ()
5611 "Switch to overview mode, showing only top-level headlines.
5612 Really, this shows all headlines with level equal or greater than the level
5613 of the first headline in the buffer. This is important, because if the
5614 first headline is not level one, then (hide-sublevels 1) gives confusing
5615 results."
5616 (interactive)
5617 (let ((level (save-excursion
5618 (goto-char (point-min))
5619 (if (re-search-forward (concat "^" outline-regexp) nil t)
5620 (progn
5621 (goto-char (match-beginning 0))
5622 (funcall outline-level))))))
5623 (and level (hide-sublevels level))))
5625 (defun org-content (&optional arg)
5626 "Show all headlines in the buffer, like a table of contents.
5627 With numerical argument N, show content up to level N."
5628 (interactive "P")
5629 (save-excursion
5630 ;; Visit all headings and show their offspring
5631 (and (integerp arg) (org-overview))
5632 (goto-char (point-max))
5633 (catch 'exit
5634 (while (and (progn (condition-case nil
5635 (outline-previous-visible-heading 1)
5636 (error (goto-char (point-min))))
5638 (looking-at outline-regexp))
5639 (if (integerp arg)
5640 (show-children (1- arg))
5641 (show-branches))
5642 (if (bobp) (throw 'exit nil))))))
5645 (defun org-optimize-window-after-visibility-change (state)
5646 "Adjust the window after a change in outline visibility.
5647 This function is the default value of the hook `org-cycle-hook'."
5648 (when (get-buffer-window (current-buffer))
5649 (cond
5650 ((eq state 'content) nil)
5651 ((eq state 'all) nil)
5652 ((eq state 'folded) nil)
5653 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5654 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5656 (defun org-remove-empty-overlays-at (pos)
5657 "Remove outline overlays that do not contain non-white stuff."
5658 (mapc
5659 (lambda (o)
5660 (and (eq 'outline (overlay-get o 'invisible))
5661 (not (string-match "\\S-" (buffer-substring (overlay-start o)
5662 (overlay-end o))))
5663 (delete-overlay o)))
5664 (overlays-at pos)))
5666 (defun org-clean-visibility-after-subtree-move ()
5667 "Fix visibility issues after moving a subtree."
5668 ;; First, find a reasonable region to look at:
5669 ;; Start two siblings above, end three below
5670 (let* ((beg (save-excursion
5671 (and (org-get-last-sibling)
5672 (org-get-last-sibling))
5673 (point)))
5674 (end (save-excursion
5675 (and (org-get-next-sibling)
5676 (org-get-next-sibling)
5677 (org-get-next-sibling))
5678 (if (org-at-heading-p)
5679 (point-at-eol)
5680 (point))))
5681 (level (looking-at "\\*+"))
5682 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5683 (save-excursion
5684 (save-restriction
5685 (narrow-to-region beg end)
5686 (when re
5687 ;; Properly fold already folded siblings
5688 (goto-char (point-min))
5689 (while (re-search-forward re nil t)
5690 (if (and (not (org-invisible-p))
5691 (save-excursion
5692 (goto-char (point-at-eol)) (org-invisible-p)))
5693 (hide-entry))))
5694 (org-cycle-show-empty-lines 'overview)
5695 (org-cycle-hide-drawers 'overview)))))
5697 (defun org-cycle-show-empty-lines (state)
5698 "Show empty lines above all visible headlines.
5699 The region to be covered depends on STATE when called through
5700 `org-cycle-hook'. Lisp program can use t for STATE to get the
5701 entire buffer covered. Note that an empty line is only shown if there
5702 are at least `org-cycle-separator-lines' empty lines before the headline."
5703 (when (not (= org-cycle-separator-lines 0))
5704 (save-excursion
5705 (let* ((n (abs org-cycle-separator-lines))
5706 (re (cond
5707 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5708 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5709 (t (let ((ns (number-to-string (- n 2))))
5710 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5711 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5712 beg end b e)
5713 (cond
5714 ((memq state '(overview contents t))
5715 (setq beg (point-min) end (point-max)))
5716 ((memq state '(children folded))
5717 (setq beg (point) end (progn (org-end-of-subtree t t)
5718 (beginning-of-line 2)
5719 (point)))))
5720 (when beg
5721 (goto-char beg)
5722 (while (re-search-forward re end t)
5723 (unless (get-char-property (match-end 1) 'invisible)
5724 (setq e (match-end 1))
5725 (if (< org-cycle-separator-lines 0)
5726 (setq b (save-excursion
5727 (goto-char (match-beginning 0))
5728 (org-back-over-empty-lines)
5729 (if (save-excursion
5730 (goto-char (max (point-min) (1- (point))))
5731 (org-on-heading-p))
5732 (1- (point))
5733 (point))))
5734 (setq b (match-beginning 1)))
5735 (outline-flag-region b e nil)))))))
5736 ;; Never hide empty lines at the end of the file.
5737 (save-excursion
5738 (goto-char (point-max))
5739 (outline-previous-heading)
5740 (outline-end-of-heading)
5741 (if (and (looking-at "[ \t\n]+")
5742 (= (match-end 0) (point-max)))
5743 (outline-flag-region (point) (match-end 0) nil))))
5745 (defun org-show-empty-lines-in-parent ()
5746 "Move to the parent and re-show empty lines before visible headlines."
5747 (save-excursion
5748 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5749 (org-cycle-show-empty-lines context))))
5751 (defun org-files-list ()
5752 "Return `org-agenda-files' list, plus all open org-mode files.
5753 This is useful for operations that need to scan all of a user's
5754 open and agenda-wise Org files."
5755 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5756 (dolist (buf (buffer-list))
5757 (with-current-buffer buf
5758 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5759 (let ((file (expand-file-name (buffer-file-name))))
5760 (unless (member file files)
5761 (push file files))))))
5762 files))
5764 (defsubst org-entry-beginning-position ()
5765 "Return the beginning position of the current entry."
5766 (save-excursion (outline-back-to-heading t) (point)))
5768 (defsubst org-entry-end-position ()
5769 "Return the end position of the current entry."
5770 (save-excursion (outline-next-heading) (point)))
5772 (defun org-cycle-hide-drawers (state)
5773 "Re-hide all drawers after a visibility state change."
5774 (when (and (org-mode-p)
5775 (not (memq state '(overview folded contents))))
5776 (save-excursion
5777 (let* ((globalp (memq state '(contents all)))
5778 (beg (if globalp (point-min) (point)))
5779 (end (if globalp (point-max)
5780 (if (eq state 'children)
5781 (save-excursion (outline-next-heading) (point))
5782 (org-end-of-subtree t)))))
5783 (goto-char beg)
5784 (while (re-search-forward org-drawer-regexp end t)
5785 (org-flag-drawer t))))))
5787 (defun org-flag-drawer (flag)
5788 (save-excursion
5789 (beginning-of-line 1)
5790 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5791 (let ((b (match-end 0))
5792 (outline-regexp org-outline-regexp))
5793 (if (re-search-forward
5794 "^[ \t]*:END:"
5795 (save-excursion (outline-next-heading) (point)) t)
5796 (outline-flag-region b (point-at-eol) flag)
5797 (error ":END: line missing at position %s" b))))))
5799 (defun org-subtree-end-visible-p ()
5800 "Is the end of the current subtree visible?"
5801 (pos-visible-in-window-p
5802 (save-excursion (org-end-of-subtree t) (point))))
5804 (defun org-first-headline-recenter (&optional N)
5805 "Move cursor to the first headline and recenter the headline.
5806 Optional argument N means put the headline into the Nth line of the window."
5807 (goto-char (point-min))
5808 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5809 (beginning-of-line)
5810 (recenter (prefix-numeric-value N))))
5812 ;;; Saving and restoring visibility
5814 (defun org-outline-overlay-data (&optional use-markers)
5815 "Return a list of the locations of all outline overlays.
5816 The are overlays with the `invisible' property value `outline'.
5817 The return valus is a list of cons cells, with start and stop
5818 positions for each overlay.
5819 If USE-MARKERS is set, return the positions as markers."
5820 (let (beg end)
5821 (save-excursion
5822 (save-restriction
5823 (widen)
5824 (delq nil
5825 (mapcar (lambda (o)
5826 (when (eq (overlay-get o 'invisible) 'outline)
5827 (setq beg (overlay-start o)
5828 end (overlay-end o))
5829 (and beg end (> end beg)
5830 (if use-markers
5831 (cons (move-marker (make-marker) beg)
5832 (move-marker (make-marker) end))
5833 (cons beg end)))))
5834 (overlays-in (point-min) (point-max))))))))
5836 (defun org-set-outline-overlay-data (data)
5837 "Create visibility overlays for all positions in DATA.
5838 DATA should have been made by `org-outline-overlay-data'."
5839 (let (o)
5840 (save-excursion
5841 (save-restriction
5842 (widen)
5843 (show-all)
5844 (mapc (lambda (c)
5845 (setq o (make-overlay (car c) (cdr c)))
5846 (overlay-put o 'invisible 'outline))
5847 data)))))
5849 (defmacro org-save-outline-visibility (use-markers &rest body)
5850 "Save and restore outline visibility around BODY.
5851 If USE-MARKERS is non-nil, use markers for the positions.
5852 This means that the buffer may change while running BODY,
5853 but it also means that the buffer should stay alive
5854 during the operation, because otherwise all these markers will
5855 point nowhere."
5856 `(let ((data (org-outline-overlay-data ,use-markers)))
5857 (unwind-protect
5858 (progn
5859 ,@body
5860 (org-set-outline-overlay-data data))
5861 (when ,use-markers
5862 (mapc (lambda (c)
5863 (and (markerp (car c)) (move-marker (car c) nil))
5864 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
5865 data)))))
5868 ;;; Folding of blocks
5870 (defconst org-block-regexp
5872 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5873 "Regular expression for hiding blocks.")
5875 (defvar org-hide-block-overlays nil
5876 "Overlays hiding blocks.")
5877 (make-variable-buffer-local 'org-hide-block-overlays)
5879 (defun org-block-map (function &optional start end)
5880 "Call func at the head of all source blocks in the current
5881 buffer. Optional arguments START and END can be used to limit
5882 the range."
5883 (let ((start (or start (point-min)))
5884 (end (or end (point-max))))
5885 (save-excursion
5886 (goto-char start)
5887 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5888 (save-excursion
5889 (save-match-data
5890 (goto-char (match-beginning 0))
5891 (funcall function)))))))
5893 (defun org-hide-block-toggle-all ()
5894 "Toggle the visibility of all blocks in the current buffer."
5895 (org-block-map #'org-hide-block-toggle))
5897 (defun org-hide-block-all ()
5898 "Fold all blocks in the current buffer."
5899 (interactive)
5900 (org-show-block-all)
5901 (org-block-map #'org-hide-block-toggle-maybe))
5903 (defun org-show-block-all ()
5904 "Unfold all blocks in the current buffer."
5905 (mapc 'delete-overlay org-hide-block-overlays)
5906 (setq org-hide-block-overlays nil))
5908 (defun org-hide-block-toggle-maybe ()
5909 "Toggle visibility of block at point."
5910 (interactive)
5911 (let ((case-fold-search t))
5912 (if (save-excursion
5913 (beginning-of-line 1)
5914 (looking-at org-block-regexp))
5915 (progn (org-hide-block-toggle)
5916 t) ;; to signal that we took action
5917 nil))) ;; to signal that we did not
5919 (defun org-hide-block-toggle (&optional force)
5920 "Toggle the visibility of the current block."
5921 (interactive)
5922 (save-excursion
5923 (beginning-of-line)
5924 (if (re-search-forward org-block-regexp nil t)
5925 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5926 (end (match-end 0)) ;; end of entire body
5928 (if (memq t (mapcar (lambda (overlay)
5929 (eq (overlay-get overlay 'invisible)
5930 'org-hide-block))
5931 (overlays-at start)))
5932 (if (or (not force) (eq force 'off))
5933 (mapc (lambda (ov)
5934 (when (member ov org-hide-block-overlays)
5935 (setq org-hide-block-overlays
5936 (delq ov org-hide-block-overlays)))
5937 (when (eq (overlay-get ov 'invisible)
5938 'org-hide-block)
5939 (delete-overlay ov)))
5940 (overlays-at start)))
5941 (setq ov (make-overlay start end))
5942 (overlay-put ov 'invisible 'org-hide-block)
5943 ;; make the block accessible to isearch
5944 (overlay-put
5945 ov 'isearch-open-invisible
5946 (lambda (ov)
5947 (when (member ov org-hide-block-overlays)
5948 (setq org-hide-block-overlays
5949 (delq ov org-hide-block-overlays)))
5950 (when (eq (overlay-get ov 'invisible)
5951 'org-hide-block)
5952 (delete-overlay ov))))
5953 (push ov org-hide-block-overlays)))
5954 (error "Not looking at a source block"))))
5956 ;; org-tab-after-check-for-cycling-hook
5957 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5958 ;; Remove overlays when changing major mode
5959 (add-hook 'org-mode-hook
5960 (lambda () (org-add-hook 'change-major-mode-hook
5961 'org-show-block-all 'append 'local)))
5963 ;;; Org-goto
5965 (defvar org-goto-window-configuration nil)
5966 (defvar org-goto-marker nil)
5967 (defvar org-goto-map
5968 (let ((map (make-sparse-keymap)))
5969 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5970 (while (setq cmd (pop cmds))
5971 (substitute-key-definition cmd cmd map global-map)))
5972 (suppress-keymap map)
5973 (org-defkey map "\C-m" 'org-goto-ret)
5974 (org-defkey map [(return)] 'org-goto-ret)
5975 (org-defkey map [(left)] 'org-goto-left)
5976 (org-defkey map [(right)] 'org-goto-right)
5977 (org-defkey map [(control ?g)] 'org-goto-quit)
5978 (org-defkey map "\C-i" 'org-cycle)
5979 (org-defkey map [(tab)] 'org-cycle)
5980 (org-defkey map [(down)] 'outline-next-visible-heading)
5981 (org-defkey map [(up)] 'outline-previous-visible-heading)
5982 (if org-goto-auto-isearch
5983 (if (fboundp 'define-key-after)
5984 (define-key-after map [t] 'org-goto-local-auto-isearch)
5985 nil)
5986 (org-defkey map "q" 'org-goto-quit)
5987 (org-defkey map "n" 'outline-next-visible-heading)
5988 (org-defkey map "p" 'outline-previous-visible-heading)
5989 (org-defkey map "f" 'outline-forward-same-level)
5990 (org-defkey map "b" 'outline-backward-same-level)
5991 (org-defkey map "u" 'outline-up-heading))
5992 (org-defkey map "/" 'org-occur)
5993 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5994 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5995 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5996 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5997 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5998 map))
6000 (defconst org-goto-help
6001 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6002 RET=jump to location [Q]uit and return to previous location
6003 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6005 (defvar org-goto-start-pos) ; dynamically scoped parameter
6007 ;; FIXME: Docstring does not mention both interfaces
6008 (defun org-goto (&optional alternative-interface)
6009 "Look up a different location in the current file, keeping current visibility.
6011 When you want look-up or go to a different location in a document, the
6012 fastest way is often to fold the entire buffer and then dive into the tree.
6013 This method has the disadvantage, that the previous location will be folded,
6014 which may not be what you want.
6016 This command works around this by showing a copy of the current buffer
6017 in an indirect buffer, in overview mode. You can dive into the tree in
6018 that copy, use org-occur and incremental search to find a location.
6019 When pressing RET or `Q', the command returns to the original buffer in
6020 which the visibility is still unchanged. After RET is will also jump to
6021 the location selected in the indirect buffer and expose the
6022 the headline hierarchy above."
6023 (interactive "P")
6024 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6025 (org-refile-use-outline-path t)
6026 (org-refile-target-verify-function nil)
6027 (interface
6028 (if (not alternative-interface)
6029 org-goto-interface
6030 (if (eq org-goto-interface 'outline)
6031 'outline-path-completion
6032 'outline)))
6033 (org-goto-start-pos (point))
6034 (selected-point
6035 (if (eq interface 'outline)
6036 (car (org-get-location (current-buffer) org-goto-help))
6037 (nth 3 (org-refile-get-location "Goto: ")))))
6038 (if selected-point
6039 (progn
6040 (org-mark-ring-push org-goto-start-pos)
6041 (goto-char selected-point)
6042 (if (or (org-invisible-p) (org-invisible-p2))
6043 (org-show-context 'org-goto)))
6044 (message "Quit"))))
6046 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6047 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6048 (defvar org-goto-local-auto-isearch-map) ; defined below
6050 (defun org-get-location (buf help)
6051 "Let the user select a location in the Org-mode buffer BUF.
6052 This function uses a recursive edit. It returns the selected position
6053 or nil."
6054 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6055 (isearch-hide-immediately nil)
6056 (isearch-search-fun-function
6057 (lambda () 'org-goto-local-search-headings))
6058 (org-goto-selected-point org-goto-exit-command)
6059 (pop-up-frames nil)
6060 (special-display-buffer-names nil)
6061 (special-display-regexps nil)
6062 (special-display-function nil))
6063 (save-excursion
6064 (save-window-excursion
6065 (delete-other-windows)
6066 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6067 (switch-to-buffer
6068 (condition-case nil
6069 (make-indirect-buffer (current-buffer) "*org-goto*")
6070 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6071 (with-output-to-temp-buffer "*Help*"
6072 (princ help))
6073 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6074 (setq buffer-read-only nil)
6075 (let ((org-startup-truncated t)
6076 (org-startup-folded nil)
6077 (org-startup-align-all-tables nil))
6078 (org-mode)
6079 (org-overview))
6080 (setq buffer-read-only t)
6081 (if (and (boundp 'org-goto-start-pos)
6082 (integer-or-marker-p org-goto-start-pos))
6083 (let ((org-show-hierarchy-above t)
6084 (org-show-siblings t)
6085 (org-show-following-heading t))
6086 (goto-char org-goto-start-pos)
6087 (and (org-invisible-p) (org-show-context)))
6088 (goto-char (point-min)))
6089 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6090 (message "Select location and press RET")
6091 (use-local-map org-goto-map)
6092 (recursive-edit)
6094 (kill-buffer "*org-goto*")
6095 (cons org-goto-selected-point org-goto-exit-command)))
6097 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6098 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6099 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6100 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6102 (defun org-goto-local-search-headings (string bound noerror)
6103 "Search and make sure that any matches are in headlines."
6104 (catch 'return
6105 (while (if isearch-forward
6106 (search-forward string bound noerror)
6107 (search-backward string bound noerror))
6108 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6109 (and (member :headline context)
6110 (not (member :tags context))))
6111 (throw 'return (point))))))
6113 (defun org-goto-local-auto-isearch ()
6114 "Start isearch."
6115 (interactive)
6116 (goto-char (point-min))
6117 (let ((keys (this-command-keys)))
6118 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6119 (isearch-mode t)
6120 (isearch-process-search-char (string-to-char keys)))))
6122 (defun org-goto-ret (&optional arg)
6123 "Finish `org-goto' by going to the new location."
6124 (interactive "P")
6125 (setq org-goto-selected-point (point)
6126 org-goto-exit-command 'return)
6127 (throw 'exit nil))
6129 (defun org-goto-left ()
6130 "Finish `org-goto' by going to the new location."
6131 (interactive)
6132 (if (org-on-heading-p)
6133 (progn
6134 (beginning-of-line 1)
6135 (setq org-goto-selected-point (point)
6136 org-goto-exit-command 'left)
6137 (throw 'exit nil))
6138 (error "Not on a heading")))
6140 (defun org-goto-right ()
6141 "Finish `org-goto' by going to the new location."
6142 (interactive)
6143 (if (org-on-heading-p)
6144 (progn
6145 (setq org-goto-selected-point (point)
6146 org-goto-exit-command 'right)
6147 (throw 'exit nil))
6148 (error "Not on a heading")))
6150 (defun org-goto-quit ()
6151 "Finish `org-goto' without cursor motion."
6152 (interactive)
6153 (setq org-goto-selected-point nil)
6154 (setq org-goto-exit-command 'quit)
6155 (throw 'exit nil))
6157 ;;; Indirect buffer display of subtrees
6159 (defvar org-indirect-dedicated-frame nil
6160 "This is the frame being used for indirect tree display.")
6161 (defvar org-last-indirect-buffer nil)
6163 (defun org-tree-to-indirect-buffer (&optional arg)
6164 "Create indirect buffer and narrow it to current subtree.
6165 With numerical prefix ARG, go up to this level and then take that tree.
6166 If ARG is negative, go up that many levels.
6167 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6168 indirect buffer previously made with this command, to avoid proliferation of
6169 indirect buffers. However, when you call the command with a `C-u' prefix, or
6170 when `org-indirect-buffer-display' is `new-frame', the last buffer
6171 is kept so that you can work with several indirect buffers at the same time.
6172 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6173 requests that a new frame be made for the new buffer, so that the dedicated
6174 frame is not changed."
6175 (interactive "P")
6176 (let ((cbuf (current-buffer))
6177 (cwin (selected-window))
6178 (pos (point))
6179 beg end level heading ibuf)
6180 (save-excursion
6181 (org-back-to-heading t)
6182 (when (numberp arg)
6183 (setq level (org-outline-level))
6184 (if (< arg 0) (setq arg (+ level arg)))
6185 (while (> (setq level (org-outline-level)) arg)
6186 (outline-up-heading 1 t)))
6187 (setq beg (point)
6188 heading (org-get-heading))
6189 (org-end-of-subtree t t)
6190 (if (org-on-heading-p) (backward-char 1))
6191 (setq end (point)))
6192 (if (and (buffer-live-p org-last-indirect-buffer)
6193 (not (eq org-indirect-buffer-display 'new-frame))
6194 (not arg))
6195 (kill-buffer org-last-indirect-buffer))
6196 (setq ibuf (org-get-indirect-buffer cbuf)
6197 org-last-indirect-buffer ibuf)
6198 (cond
6199 ((or (eq org-indirect-buffer-display 'new-frame)
6200 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6201 (select-frame (make-frame))
6202 (delete-other-windows)
6203 (switch-to-buffer ibuf)
6204 (org-set-frame-title heading))
6205 ((eq org-indirect-buffer-display 'dedicated-frame)
6206 (raise-frame
6207 (select-frame (or (and org-indirect-dedicated-frame
6208 (frame-live-p org-indirect-dedicated-frame)
6209 org-indirect-dedicated-frame)
6210 (setq org-indirect-dedicated-frame (make-frame)))))
6211 (delete-other-windows)
6212 (switch-to-buffer ibuf)
6213 (org-set-frame-title (concat "Indirect: " heading)))
6214 ((eq org-indirect-buffer-display 'current-window)
6215 (switch-to-buffer ibuf))
6216 ((eq org-indirect-buffer-display 'other-window)
6217 (pop-to-buffer ibuf))
6218 (t (error "Invalid value")))
6219 (if (featurep 'xemacs)
6220 (save-excursion (org-mode) (turn-on-font-lock)))
6221 (narrow-to-region beg end)
6222 (show-all)
6223 (goto-char pos)
6224 (and (window-live-p cwin) (select-window cwin))))
6226 (defun org-get-indirect-buffer (&optional buffer)
6227 (setq buffer (or buffer (current-buffer)))
6228 (let ((n 1) (base (buffer-name buffer)) bname)
6229 (while (buffer-live-p
6230 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6231 (setq n (1+ n)))
6232 (condition-case nil
6233 (make-indirect-buffer buffer bname 'clone)
6234 (error (make-indirect-buffer buffer bname)))))
6236 (defun org-set-frame-title (title)
6237 "Set the title of the current frame to the string TITLE."
6238 ;; FIXME: how to name a single frame in XEmacs???
6239 (unless (featurep 'xemacs)
6240 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6242 ;;;; Structure editing
6244 ;;; Inserting headlines
6246 (defun org-previous-line-empty-p ()
6247 (save-excursion
6248 (and (not (bobp))
6249 (or (beginning-of-line 0) t)
6250 (save-match-data
6251 (looking-at "[ \t]*$")))))
6253 (defun org-insert-heading (&optional force-heading invisible-ok)
6254 "Insert a new heading or item with same depth at point.
6255 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6256 If point is at the beginning of a headline, insert a sibling before the
6257 current headline. If point is not at the beginning, do not split the line,
6258 but create the new headline after the current line.
6259 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6260 This is important for non-interactive uses of the command."
6261 (interactive "P")
6262 (if (or (= (buffer-size) 0)
6263 (and (not (save-excursion (and (ignore-errors (org-back-to-heading invisible-ok))
6264 (org-on-heading-p))))
6265 (not (org-in-item-p))))
6266 (insert "\n* ")
6267 (when (or force-heading (not (org-insert-item)))
6268 (let* ((empty-line-p nil)
6269 (head (save-excursion
6270 (condition-case nil
6271 (progn
6272 (org-back-to-heading invisible-ok)
6273 (setq empty-line-p (org-previous-line-empty-p))
6274 (match-string 0))
6275 (error "*"))))
6276 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6277 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6278 pos hide-previous previous-pos)
6279 (cond
6280 ((and (org-on-heading-p) (bolp)
6281 (or (bobp)
6282 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6283 ;; insert before the current line
6284 (open-line (if blank 2 1)))
6285 ((and (bolp)
6286 (not org-insert-heading-respect-content)
6287 (or (bobp)
6288 (save-excursion
6289 (backward-char 1) (not (org-invisible-p)))))
6290 ;; insert right here
6291 nil)
6293 ;; somewhere in the line
6294 (save-excursion
6295 (setq previous-pos (point-at-bol))
6296 (end-of-line)
6297 (setq hide-previous (org-invisible-p)))
6298 (and org-insert-heading-respect-content (org-show-subtree))
6299 (let ((split
6300 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6301 (save-excursion
6302 (let ((p (point)))
6303 (goto-char (point-at-bol))
6304 (and (looking-at org-complex-heading-regexp)
6305 (> p (match-beginning 4)))))))
6306 tags pos)
6307 (cond
6308 (org-insert-heading-respect-content
6309 (org-end-of-subtree nil t)
6310 (or (bolp) (newline))
6311 (or (org-previous-line-empty-p)
6312 (and blank (newline)))
6313 (open-line 1))
6314 ((org-on-heading-p)
6315 (when hide-previous
6316 (show-children)
6317 (org-show-entry))
6318 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6319 (setq tags (and (match-end 2) (match-string 2)))
6320 (and (match-end 1)
6321 (delete-region (match-beginning 1) (match-end 1)))
6322 (setq pos (point-at-bol))
6323 (or split (end-of-line 1))
6324 (delete-horizontal-space)
6325 (if (string-match "\\`\\*+\\'"
6326 (buffer-substring (point-at-bol) (point)))
6327 (insert " "))
6328 (newline (if blank 2 1))
6329 (when tags
6330 (save-excursion
6331 (goto-char pos)
6332 (end-of-line 1)
6333 (insert " " tags)
6334 (org-set-tags nil 'align))))
6336 (or split (end-of-line 1))
6337 (newline (if blank 2 1)))))))
6338 (insert head) (just-one-space)
6339 (setq pos (point))
6340 (end-of-line 1)
6341 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6342 (when (and org-insert-heading-respect-content hide-previous)
6343 (save-excursion
6344 (goto-char previous-pos)
6345 (hide-subtree)))
6346 (run-hooks 'org-insert-heading-hook)))))
6348 (defun org-get-heading (&optional no-tags)
6349 "Return the heading of the current entry, without the stars."
6350 (save-excursion
6351 (org-back-to-heading t)
6352 (if (looking-at
6353 (if no-tags
6354 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6355 "\\*+[ \t]+\\([^\r\n]*\\)"))
6356 (match-string 1) "")))
6358 (defun org-heading-components ()
6359 "Return the components of the current heading.
6360 This is a list with the following elements:
6361 - the level as an integer
6362 - the reduced level, different if `org-odd-levels-only' is set.
6363 - the TODO keyword, or nil
6364 - the priority character, like ?A, or nil if no priority is given
6365 - the headline text itself, or the tags string if no headline text
6366 - the tags string, or nil."
6367 (save-excursion
6368 (org-back-to-heading t)
6369 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6370 (list (length (match-string 1))
6371 (org-reduced-level (length (match-string 1)))
6372 (org-match-string-no-properties 2)
6373 (and (match-end 3) (aref (match-string 3) 2))
6374 (org-match-string-no-properties 4)
6375 (org-match-string-no-properties 5)))))
6377 (defun org-get-entry ()
6378 "Get the entry text, after heading, entire subtree."
6379 (save-excursion
6380 (org-back-to-heading t)
6381 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6383 (defun org-insert-heading-after-current ()
6384 "Insert a new heading with same level as current, after current subtree."
6385 (interactive)
6386 (org-back-to-heading)
6387 (org-insert-heading)
6388 (org-move-subtree-down)
6389 (end-of-line 1))
6391 (defun org-insert-heading-respect-content ()
6392 (interactive)
6393 (let ((org-insert-heading-respect-content t))
6394 (org-insert-heading t)))
6396 (defun org-insert-todo-heading-respect-content (&optional force-state)
6397 (interactive "P")
6398 (let ((org-insert-heading-respect-content t))
6399 (org-insert-todo-heading force-state t)))
6401 (defun org-insert-todo-heading (arg &optional force-heading)
6402 "Insert a new heading with the same level and TODO state as current heading.
6403 If the heading has no TODO state, or if the state is DONE, use the first
6404 state (TODO by default). Also with prefix arg, force first state."
6405 (interactive "P")
6406 (when (or force-heading (not (org-insert-item 'checkbox)))
6407 (org-insert-heading force-heading)
6408 (save-excursion
6409 (org-back-to-heading)
6410 (outline-previous-heading)
6411 (looking-at org-todo-line-regexp))
6412 (let*
6413 ((new-mark-x
6414 (if (or arg
6415 (not (match-beginning 2))
6416 (member (match-string 2) org-done-keywords))
6417 (car org-todo-keywords-1)
6418 (match-string 2)))
6419 (new-mark
6421 (run-hook-with-args-until-success
6422 'org-todo-get-default-hook new-mark-x nil)
6423 new-mark-x)))
6424 (beginning-of-line 1)
6425 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6426 (if org-treat-insert-todo-heading-as-state-change
6427 (org-todo new-mark)
6428 (insert new-mark " "))))
6429 (when org-provide-todo-statistics
6430 (org-update-parent-todo-statistics))))
6432 (defun org-insert-subheading (arg)
6433 "Insert a new subheading and demote it.
6434 Works for outline headings and for plain lists alike."
6435 (interactive "P")
6436 (org-insert-heading arg)
6437 (cond
6438 ((org-on-heading-p) (org-do-demote))
6439 ((org-at-item-p) (org-indent-item 1))))
6441 (defun org-insert-todo-subheading (arg)
6442 "Insert a new subheading with TODO keyword or checkbox and demote it.
6443 Works for outline headings and for plain lists alike."
6444 (interactive "P")
6445 (org-insert-todo-heading arg)
6446 (cond
6447 ((org-on-heading-p) (org-do-demote))
6448 ((org-at-item-p) (org-indent-item 1))))
6450 ;;; Promotion and Demotion
6452 (defvar org-after-demote-entry-hook nil
6453 "Hook run after an entry has been demoted.
6454 The cursor will be at the beginning of the entry.
6455 When a subtree is being demoted, the hook will be called for each node.")
6457 (defvar org-after-promote-entry-hook nil
6458 "Hook run after an entry has been promoted.
6459 The cursor will be at the beginning of the entry.
6460 When a subtree is being promoted, the hook will be called for each node.")
6462 (defun org-promote-subtree ()
6463 "Promote the entire subtree.
6464 See also `org-promote'."
6465 (interactive)
6466 (save-excursion
6467 (org-map-tree 'org-promote))
6468 (org-fix-position-after-promote))
6470 (defun org-demote-subtree ()
6471 "Demote the entire subtree. See `org-demote'.
6472 See also `org-promote'."
6473 (interactive)
6474 (save-excursion
6475 (org-map-tree 'org-demote))
6476 (org-fix-position-after-promote))
6479 (defun org-do-promote ()
6480 "Promote the current heading higher up the tree.
6481 If the region is active in `transient-mark-mode', promote all headings
6482 in the region."
6483 (interactive)
6484 (save-excursion
6485 (if (org-region-active-p)
6486 (org-map-region 'org-promote (region-beginning) (region-end))
6487 (org-promote)))
6488 (org-fix-position-after-promote))
6490 (defun org-do-demote ()
6491 "Demote the current heading lower down the tree.
6492 If the region is active in `transient-mark-mode', demote all headings
6493 in the region."
6494 (interactive)
6495 (save-excursion
6496 (if (org-region-active-p)
6497 (org-map-region 'org-demote (region-beginning) (region-end))
6498 (org-demote)))
6499 (org-fix-position-after-promote))
6501 (defun org-fix-position-after-promote ()
6502 "Make sure that after pro/demotion cursor position is right."
6503 (let ((pos (point)))
6504 (when (save-excursion
6505 (beginning-of-line 1)
6506 (looking-at org-todo-line-regexp)
6507 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6508 (cond ((eobp) (insert " "))
6509 ((eolp) (insert " "))
6510 ((equal (char-after) ?\ ) (forward-char 1))))))
6512 (defun org-current-level ()
6513 "Return the level of the current entry, or nil if before the first headline.
6514 The level is the number of stars at the beginning of the headline."
6515 (save-excursion
6516 (condition-case nil
6517 (progn
6518 (org-back-to-heading t)
6519 (funcall outline-level))
6520 (error nil))))
6522 (defun org-get-previous-line-level ()
6523 "Return the outline depth of the last headline before the current line.
6524 Returns 0 for the first headline in the buffer, and nil if before the
6525 first headline."
6526 (let ((current-level (org-current-level))
6527 (prev-level (when (> (line-number-at-pos) 1)
6528 (save-excursion
6529 (beginning-of-line 0)
6530 (org-current-level)))))
6531 (cond ((null current-level) nil) ; Before first headline
6532 ((null prev-level) 0) ; At first headline
6533 (prev-level))))
6535 (defun org-reduced-level (l)
6536 "Compute the effective level of a heading.
6537 This takes into account the setting of `org-odd-levels-only'."
6538 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6540 (defun org-level-increment ()
6541 "Return the number of stars that will be added or removed at a
6542 time to headlines when structure editing, based on the value of
6543 `org-odd-levels-only'."
6544 (if org-odd-levels-only 2 1))
6546 (defun org-get-valid-level (level &optional change)
6547 "Rectify a level change under the influence of `org-odd-levels-only'
6548 LEVEL is a current level, CHANGE is by how much the level should be
6549 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6550 even level numbers will become the next higher odd number."
6551 (if org-odd-levels-only
6552 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6553 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6554 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6555 (max 1 (+ level (or change 0)))))
6557 (if (boundp 'define-obsolete-function-alias)
6558 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6559 (define-obsolete-function-alias 'org-get-legal-level
6560 'org-get-valid-level)
6561 (define-obsolete-function-alias 'org-get-legal-level
6562 'org-get-valid-level "23.1")))
6564 (defun org-promote ()
6565 "Promote the current heading higher up the tree.
6566 If the region is active in `transient-mark-mode', promote all headings
6567 in the region."
6568 (org-back-to-heading t)
6569 (let* ((level (save-match-data (funcall outline-level)))
6570 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6571 (diff (abs (- level (length up-head) -1))))
6572 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6573 (replace-match up-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-promote-entry-hook)))
6579 (defun org-demote ()
6580 "Demote the current heading lower down the tree.
6581 If the region is active in `transient-mark-mode', demote all headings
6582 in the region."
6583 (org-back-to-heading t)
6584 (let* ((level (save-match-data (funcall outline-level)))
6585 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6586 (diff (abs (- level (length down-head) -1))))
6587 (replace-match down-head nil t)
6588 ;; Fixup tag positioning
6589 (and org-auto-align-tags (org-set-tags nil t))
6590 (if org-adapt-indentation (org-fixup-indentation diff))
6591 (run-hooks 'org-after-demote-entry-hook)))
6593 (defun org-cycle-level ()
6594 "Cycle the level of an empty headline through possible states.
6595 This goes first to child, then to parent, level, then up the hierarchy.
6596 After top level, it switches back to sibling level."
6597 (interactive)
6598 (let ((org-adapt-indentation nil))
6599 (when (org-point-at-end-of-empty-headline)
6600 (setq this-command 'org-cycle-level) ; Only needed for caching
6601 (let ((cur-level (org-current-level))
6602 (prev-level (org-get-previous-line-level)))
6603 (cond
6604 ;; If first headline in file, promote to top-level.
6605 ((= prev-level 0)
6606 (loop repeat (/ (- cur-level 1) (org-level-increment))
6607 do (org-do-promote)))
6608 ;; If same level as prev, demote one.
6609 ((= prev-level cur-level)
6610 (org-do-demote))
6611 ;; If parent is top-level, promote to top level if not already.
6612 ((= prev-level 1)
6613 (loop repeat (/ (- cur-level 1) (org-level-increment))
6614 do (org-do-promote)))
6615 ;; If top-level, return to prev-level.
6616 ((= cur-level 1)
6617 (loop repeat (/ (- prev-level 1) (org-level-increment))
6618 do (org-do-demote)))
6619 ;; If less than prev-level, promote one.
6620 ((< cur-level prev-level)
6621 (org-do-promote))
6622 ;; If deeper than prev-level, promote until higher than
6623 ;; prev-level.
6624 ((> cur-level prev-level)
6625 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
6626 do (org-do-promote))))
6627 t))))
6629 (defun org-map-tree (fun)
6630 "Call FUN for every heading underneath the current one."
6631 (org-back-to-heading)
6632 (let ((level (funcall outline-level)))
6633 (save-excursion
6634 (funcall fun)
6635 (while (and (progn
6636 (outline-next-heading)
6637 (> (funcall outline-level) level))
6638 (not (eobp)))
6639 (funcall fun)))))
6641 (defun org-map-region (fun beg end)
6642 "Call FUN for every heading between BEG and END."
6643 (let ((org-ignore-region t))
6644 (save-excursion
6645 (setq end (copy-marker end))
6646 (goto-char beg)
6647 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6648 (< (point) end))
6649 (funcall fun))
6650 (while (and (progn
6651 (outline-next-heading)
6652 (< (point) end))
6653 (not (eobp)))
6654 (funcall fun)))))
6656 (defun org-fixup-indentation (diff)
6657 "Change the indentation in the current entry by DIFF
6658 However, if any line in the current entry has no indentation, or if it
6659 would end up with no indentation after the change, nothing at all is done."
6660 (save-excursion
6661 (let ((end (save-excursion (outline-next-heading)
6662 (point-marker)))
6663 (prohibit (if (> diff 0)
6664 "^\\S-"
6665 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6666 col)
6667 (unless (save-excursion (end-of-line 1)
6668 (re-search-forward prohibit end t))
6669 (while (and (< (point) end)
6670 (re-search-forward "^[ \t]+" end t))
6671 (goto-char (match-end 0))
6672 (setq col (current-column))
6673 (if (< diff 0) (replace-match ""))
6674 (org-indent-to-column (+ diff col))))
6675 (move-marker end nil))))
6677 (defun org-convert-to-odd-levels ()
6678 "Convert an org-mode file with all levels allowed to one with odd levels.
6679 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6680 level 5 etc."
6681 (interactive)
6682 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6683 (let ((outline-regexp org-outline-regexp)
6684 (outline-level 'org-outline-level)
6685 (org-odd-levels-only nil) n)
6686 (save-excursion
6687 (goto-char (point-min))
6688 (while (re-search-forward "^\\*\\*+ " nil t)
6689 (setq n (- (length (match-string 0)) 2))
6690 (while (>= (setq n (1- n)) 0)
6691 (org-demote))
6692 (end-of-line 1))))))
6694 (defun org-convert-to-oddeven-levels ()
6695 "Convert an org-mode file with only odd levels to one with odd and even levels.
6696 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6697 section with an even level, conversion would destroy the structure of the file. An error
6698 is signaled in this case."
6699 (interactive)
6700 (goto-char (point-min))
6701 ;; First check if there are no even levels
6702 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6703 (org-show-context t)
6704 (error "Not all levels are odd in this file. Conversion not possible"))
6705 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6706 (let ((outline-regexp org-outline-regexp)
6707 (outline-level 'org-outline-level)
6708 (org-odd-levels-only nil) n)
6709 (save-excursion
6710 (goto-char (point-min))
6711 (while (re-search-forward "^\\*\\*+ " nil t)
6712 (setq n (/ (1- (length (match-string 0))) 2))
6713 (while (>= (setq n (1- n)) 0)
6714 (org-promote))
6715 (end-of-line 1))))))
6717 (defun org-tr-level (n)
6718 "Make N odd if required."
6719 (if org-odd-levels-only (1+ (/ n 2)) n))
6721 ;;; Vertical tree motion, cutting and pasting of subtrees
6723 (defun org-move-subtree-up (&optional arg)
6724 "Move the current subtree up past ARG headlines of the same level."
6725 (interactive "p")
6726 (org-move-subtree-down (- (prefix-numeric-value arg))))
6728 (defun org-move-subtree-down (&optional arg)
6729 "Move the current subtree down past ARG headlines of the same level."
6730 (interactive "p")
6731 (setq arg (prefix-numeric-value arg))
6732 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6733 'org-get-last-sibling))
6734 (ins-point (make-marker))
6735 (cnt (abs arg))
6736 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6737 ;; Select the tree
6738 (org-back-to-heading)
6739 (setq beg0 (point))
6740 (save-excursion
6741 (setq ne-beg (org-back-over-empty-lines))
6742 (setq beg (point)))
6743 (save-match-data
6744 (save-excursion (outline-end-of-heading)
6745 (setq folded (org-invisible-p)))
6746 (outline-end-of-subtree))
6747 (outline-next-heading)
6748 (setq ne-end (org-back-over-empty-lines))
6749 (setq end (point))
6750 (goto-char beg0)
6751 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6752 ;; include less whitespace
6753 (save-excursion
6754 (goto-char beg)
6755 (forward-line (- ne-beg ne-end))
6756 (setq beg (point))))
6757 ;; Find insertion point, with error handling
6758 (while (> cnt 0)
6759 (or (and (funcall movfunc) (looking-at outline-regexp))
6760 (progn (goto-char beg0)
6761 (error "Cannot move past superior level or buffer limit")))
6762 (setq cnt (1- cnt)))
6763 (if (> arg 0)
6764 ;; Moving forward - still need to move over subtree
6765 (progn (org-end-of-subtree t t)
6766 (save-excursion
6767 (org-back-over-empty-lines)
6768 (or (bolp) (newline)))))
6769 (setq ne-ins (org-back-over-empty-lines))
6770 (move-marker ins-point (point))
6771 (setq txt (buffer-substring beg end))
6772 (org-save-markers-in-region beg end)
6773 (delete-region beg end)
6774 (org-remove-empty-overlays-at beg)
6775 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6776 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6777 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6778 (let ((bbb (point)))
6779 (insert-before-markers txt)
6780 (org-reinstall-markers-in-region bbb)
6781 (move-marker ins-point bbb))
6782 (or (bolp) (insert "\n"))
6783 (setq ins-end (point))
6784 (goto-char ins-point)
6785 (org-skip-whitespace)
6786 (when (and (< arg 0)
6787 (org-first-sibling-p)
6788 (> ne-ins ne-beg))
6789 ;; Move whitespace back to beginning
6790 (save-excursion
6791 (goto-char ins-end)
6792 (let ((kill-whole-line t))
6793 (kill-line (- ne-ins ne-beg)) (point)))
6794 (insert (make-string (- ne-ins ne-beg) ?\n)))
6795 (move-marker ins-point nil)
6796 (if folded
6797 (hide-subtree)
6798 (org-show-entry)
6799 (show-children)
6800 (org-cycle-hide-drawers 'children))
6801 (org-clean-visibility-after-subtree-move)))
6803 (defvar org-subtree-clip ""
6804 "Clipboard for cut and paste of subtrees.
6805 This is actually only a copy of the kill, because we use the normal kill
6806 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6808 (defvar org-subtree-clip-folded nil
6809 "Was the last copied subtree folded?
6810 This is used to fold the tree back after pasting.")
6812 (defun org-cut-subtree (&optional n)
6813 "Cut the current subtree into the clipboard.
6814 With prefix arg N, cut this many sequential subtrees.
6815 This is a short-hand for marking the subtree and then cutting it."
6816 (interactive "p")
6817 (org-copy-subtree n 'cut))
6819 (defun org-copy-subtree (&optional n cut force-store-markers)
6820 "Cut the current subtree into the clipboard.
6821 With prefix arg N, cut this many sequential subtrees.
6822 This is a short-hand for marking the subtree and then copying it.
6823 If CUT is non-nil, actually cut the subtree.
6824 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6825 of some markers in the region, even if CUT is non-nil. This is
6826 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6827 (interactive "p")
6828 (let (beg end folded (beg0 (point)))
6829 (if (interactive-p)
6830 (org-back-to-heading nil) ; take what looks like a subtree
6831 (org-back-to-heading t)) ; take what is really there
6832 (org-back-over-empty-lines)
6833 (setq beg (point))
6834 (skip-chars-forward " \t\r\n")
6835 (save-match-data
6836 (save-excursion (outline-end-of-heading)
6837 (setq folded (org-invisible-p)))
6838 (condition-case nil
6839 (org-forward-same-level (1- n) t)
6840 (error nil))
6841 (org-end-of-subtree t t))
6842 (org-back-over-empty-lines)
6843 (setq end (point))
6844 (goto-char beg0)
6845 (when (> end beg)
6846 (setq org-subtree-clip-folded folded)
6847 (when (or cut force-store-markers)
6848 (org-save-markers-in-region beg end))
6849 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6850 (setq org-subtree-clip (current-kill 0))
6851 (message "%s: Subtree(s) with %d characters"
6852 (if cut "Cut" "Copied")
6853 (length org-subtree-clip)))))
6855 (defun org-paste-subtree (&optional level tree for-yank)
6856 "Paste the clipboard as a subtree, with modification of headline level.
6857 The entire subtree is promoted or demoted in order to match a new headline
6858 level.
6860 If the cursor is at the beginning of a headline, the same level as
6861 that headline is used to paste the tree
6863 If not, the new level is derived from the *visible* headings
6864 before and after the insertion point, and taken to be the inferior headline
6865 level of the two. So if the previous visible heading is level 3 and the
6866 next is level 4 (or vice versa), level 4 will be used for insertion.
6867 This makes sure that the subtree remains an independent subtree and does
6868 not swallow low level entries.
6870 You can also force a different level, either by using a numeric prefix
6871 argument, or by inserting the heading marker by hand. For example, if the
6872 cursor is after \"*****\", then the tree will be shifted to level 5.
6874 If optional TREE is given, use this text instead of the kill ring.
6876 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6877 move back over whitespace before inserting, and move point to the end of
6878 the inserted text when done."
6879 (interactive "P")
6880 (setq tree (or tree (and kill-ring (current-kill 0))))
6881 (unless (org-kill-is-subtree-p tree)
6882 (error "%s"
6883 (substitute-command-keys
6884 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6885 (let* ((visp (not (org-invisible-p)))
6886 (txt tree)
6887 (^re (concat "^\\(" outline-regexp "\\)"))
6888 (re (concat "\\(" outline-regexp "\\)"))
6889 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6891 (old-level (if (string-match ^re txt)
6892 (- (match-end 0) (match-beginning 0) 1)
6893 -1))
6894 (force-level (cond (level (prefix-numeric-value level))
6895 ((and (looking-at "[ \t]*$")
6896 (string-match
6897 ^re_ (buffer-substring
6898 (point-at-bol) (point))))
6899 (- (match-end 1) (match-beginning 1)))
6900 ((and (bolp)
6901 (looking-at org-outline-regexp))
6902 (- (match-end 0) (point) 1))
6903 (t nil)))
6904 (previous-level (save-excursion
6905 (condition-case nil
6906 (progn
6907 (outline-previous-visible-heading 1)
6908 (if (looking-at re)
6909 (- (match-end 0) (match-beginning 0) 1)
6911 (error 1))))
6912 (next-level (save-excursion
6913 (condition-case nil
6914 (progn
6915 (or (looking-at outline-regexp)
6916 (outline-next-visible-heading 1))
6917 (if (looking-at re)
6918 (- (match-end 0) (match-beginning 0) 1)
6920 (error 1))))
6921 (new-level (or force-level (max previous-level next-level)))
6922 (shift (if (or (= old-level -1)
6923 (= new-level -1)
6924 (= old-level new-level))
6926 (- new-level old-level)))
6927 (delta (if (> shift 0) -1 1))
6928 (func (if (> shift 0) 'org-demote 'org-promote))
6929 (org-odd-levels-only nil)
6930 beg end newend)
6931 ;; Remove the forced level indicator
6932 (if force-level
6933 (delete-region (point-at-bol) (point)))
6934 ;; Paste
6935 (beginning-of-line 1)
6936 (unless for-yank (org-back-over-empty-lines))
6937 (setq beg (point))
6938 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6939 (insert-before-markers txt)
6940 (unless (string-match "\n\\'" txt) (insert "\n"))
6941 (setq newend (point))
6942 (org-reinstall-markers-in-region beg)
6943 (setq end (point))
6944 (goto-char beg)
6945 (skip-chars-forward " \t\n\r")
6946 (setq beg (point))
6947 (if (and (org-invisible-p) visp)
6948 (save-excursion (outline-show-heading)))
6949 ;; Shift if necessary
6950 (unless (= shift 0)
6951 (save-restriction
6952 (narrow-to-region beg end)
6953 (while (not (= shift 0))
6954 (org-map-region func (point-min) (point-max))
6955 (setq shift (+ delta shift)))
6956 (goto-char (point-min))
6957 (setq newend (point-max))))
6958 (when (or (interactive-p) for-yank)
6959 (message "Clipboard pasted as level %d subtree" new-level))
6960 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6961 kill-ring
6962 (eq org-subtree-clip (current-kill 0))
6963 org-subtree-clip-folded)
6964 ;; The tree was folded before it was killed/copied
6965 (hide-subtree))
6966 (and for-yank (goto-char newend))))
6968 (defun org-kill-is-subtree-p (&optional txt)
6969 "Check if the current kill is an outline subtree, or a set of trees.
6970 Returns nil if kill does not start with a headline, or if the first
6971 headline level is not the largest headline level in the tree.
6972 So this will actually accept several entries of equal levels as well,
6973 which is OK for `org-paste-subtree'.
6974 If optional TXT is given, check this string instead of the current kill."
6975 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6976 (start-level (and kill
6977 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6978 org-outline-regexp "\\)")
6979 kill)
6980 (- (match-end 2) (match-beginning 2) 1)))
6981 (re (concat "^" org-outline-regexp))
6982 (start (1+ (or (match-beginning 2) -1))))
6983 (if (not start-level)
6984 (progn
6985 nil) ;; does not even start with a heading
6986 (catch 'exit
6987 (while (setq start (string-match re kill (1+ start)))
6988 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6989 (throw 'exit nil)))
6990 t))))
6992 (defvar org-markers-to-move nil
6993 "Markers that should be moved with a cut-and-paste operation.
6994 Those markers are stored together with their positions relative to
6995 the start of the region.")
6997 (defun org-save-markers-in-region (beg end)
6998 "Check markers in region.
6999 If these markers are between BEG and END, record their position relative
7000 to BEG, so that after moving the block of text, we can put the markers back
7001 into place.
7002 This function gets called just before an entry or tree gets cut from the
7003 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7004 called immediately, to move the markers with the entries."
7005 (setq org-markers-to-move nil)
7006 (when (featurep 'org-clock)
7007 (org-clock-save-markers-for-cut-and-paste beg end))
7008 (when (featurep 'org-agenda)
7009 (org-agenda-save-markers-for-cut-and-paste beg end)))
7011 (defun org-check-and-save-marker (marker beg end)
7012 "Check if MARKER is between BEG and END.
7013 If yes, remember the marker and the distance to BEG."
7014 (when (and (marker-buffer marker)
7015 (equal (marker-buffer marker) (current-buffer)))
7016 (if (and (>= marker beg) (< marker end))
7017 (push (cons marker (- marker beg)) org-markers-to-move))))
7019 (defun org-reinstall-markers-in-region (beg)
7020 "Move all remembered markers to their position relative to BEG."
7021 (mapc (lambda (x)
7022 (move-marker (car x) (+ beg (cdr x))))
7023 org-markers-to-move)
7024 (setq org-markers-to-move nil))
7026 (defun org-narrow-to-subtree ()
7027 "Narrow buffer to the current subtree."
7028 (interactive)
7029 (save-excursion
7030 (save-match-data
7031 (narrow-to-region
7032 (progn (org-back-to-heading t) (point))
7033 (progn (org-end-of-subtree t t)
7034 (if (org-on-heading-p) (backward-char 1))
7035 (point))))))
7037 (defun org-clone-subtree-with-time-shift (n &optional shift)
7038 "Clone the task (subtree) at point N times.
7039 The clones will be inserted as siblings.
7041 In interactive use, the user will be prompted for the number of clones
7042 to be produced, and for a time SHIFT, which may be a repeater as used
7043 in time stamps, for example `+3d'.
7045 When a valid repeater is given and the entry contains any time stamps,
7046 the clones will become a sequence in time, with time stamps in the
7047 subtree shifted for each clone produced. If SHIFT is nil or the
7048 empty string, time stamps will be left alone.
7050 If the original subtree did contain time stamps with a repeater,
7051 the following will happen:
7052 - the repeater will be removed in each clone
7053 - an additional clone will be produced, with the current, unshifted
7054 date(s) in the entry.
7055 - the original entry will be placed *after* all the clones, with
7056 repeater intact.
7057 - the start days in the repeater in the original entry will be shifted
7058 to past the last clone.
7059 I this way you can spell out a number of instances of a repeating task,
7060 and still retain the repeater to cover future instances of the task."
7061 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7062 (let (beg end template task
7063 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7064 (if (not (and (integerp n) (> n 0)))
7065 (error "Invalid number of replications %s" n))
7066 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7067 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7068 shift)))
7069 (error "Invalid shift specification %s" shift))
7070 (when doshift
7071 (setq shift-n (string-to-number (match-string 1 shift))
7072 shift-what (cdr (assoc (match-string 2 shift)
7073 '(("d" . day) ("w" . week)
7074 ("m" . month) ("y" . year))))))
7075 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7076 (setq nmin 1 nmax n)
7077 (org-back-to-heading t)
7078 (setq beg (point))
7079 (org-end-of-subtree t t)
7080 (or (bolp) (insert "\n"))
7081 (setq end (point))
7082 (setq template (buffer-substring beg end))
7083 (when (and doshift
7084 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7085 (delete-region beg end)
7086 (setq end beg)
7087 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7088 (goto-char end)
7089 (loop for n from nmin to nmax do
7090 (if (not doshift)
7091 (setq task template)
7092 (with-temp-buffer
7093 (insert template)
7094 (org-mode)
7095 (goto-char (point-min))
7096 (while (re-search-forward org-ts-regexp-both nil t)
7097 (org-timestamp-change (* n shift-n) shift-what))
7098 (unless (= n n-no-remove)
7099 (goto-char (point-min))
7100 (while (re-search-forward org-ts-regexp nil t)
7101 (save-excursion
7102 (goto-char (match-beginning 0))
7103 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7104 (delete-region (match-beginning 1) (match-end 1))))))
7105 (setq task (buffer-string))))
7106 (insert task))
7107 (goto-char beg)))
7109 ;;; Outline Sorting
7111 (defun org-sort (with-case)
7112 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
7113 Optional argument WITH-CASE means sort case-sensitively.
7114 With a double prefix argument, also remove duplicate entries."
7115 (interactive "P")
7116 (if (org-at-table-p)
7117 (org-call-with-arg 'org-table-sort-lines with-case)
7118 (org-call-with-arg 'org-sort-entries-or-items with-case)))
7120 (defun org-sort-remove-invisible (s)
7121 (remove-text-properties 0 (length s) org-rm-props s)
7122 (while (string-match org-bracket-link-regexp s)
7123 (setq s (replace-match (if (match-end 2)
7124 (match-string 3 s)
7125 (match-string 1 s)) t t s)))
7128 (defvar org-priority-regexp) ; defined later in the file
7130 (defvar org-after-sorting-entries-or-items-hook nil
7131 "Hook that is run after a bunch of entries or items have been sorted.
7132 When children are sorted, the cursor is in the parent line when this
7133 hook gets called. When a region or a plain list is sorted, the cursor
7134 will be in the first entry of the sorted region/list.")
7136 (defun org-sort-entries-or-items
7137 (&optional with-case sorting-type getkey-func compare-func property)
7138 "Sort entries on a certain level of an outline tree, or plain list items.
7139 If there is an active region, the entries in the region are sorted.
7140 Else, if the cursor is before the first entry, sort the top-level items.
7141 Else, the children of the entry at point are sorted.
7142 If the cursor is at the first item in a plain list, the list items will be
7143 sorted.
7145 Sorting can be alphabetically, numerically, by date/time as given by
7146 a time stamp, by a property or by priority.
7148 The command prompts for the sorting type unless it has been given to the
7149 function through the SORTING-TYPE argument, which needs to a character,
7150 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7151 precise meaning of each character:
7153 n Numerically, by converting the beginning of the entry/item to a number.
7154 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7155 t By date/time, either the first active time stamp in the entry, or, if
7156 none exist, by the first inactive one.
7157 In items, only the first line will be checked.
7158 s By the scheduled date/time.
7159 d By deadline date/time.
7160 c By creation time, which is assumed to be the first inactive time stamp
7161 at the beginning of a line.
7162 p By priority according to the cookie.
7163 r By the value of a property.
7165 Capital letters will reverse the sort order.
7167 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7168 called with point at the beginning of the record. It must return either
7169 a string or a number that should serve as the sorting key for that record.
7171 Comparing entries ignores case by default. However, with an optional argument
7172 WITH-CASE, the sorting considers case as well."
7173 (interactive "P")
7174 (let ((case-func (if with-case 'identity 'downcase))
7175 start beg end stars re re2
7176 txt what tmp plain-list-p)
7177 ;; Find beginning and end of region to sort
7178 (cond
7179 ((org-region-active-p)
7180 ;; we will sort the region
7181 (setq end (region-end)
7182 what "region")
7183 (goto-char (region-beginning))
7184 (if (not (org-on-heading-p)) (outline-next-heading))
7185 (setq start (point)))
7186 ((org-at-item-p)
7187 ;; we will sort this plain list
7188 (org-beginning-of-item-list) (setq start (point))
7189 (org-end-of-item-list)
7190 (or (bolp) (insert "\n"))
7191 (setq end (point))
7192 (goto-char start)
7193 (setq plain-list-p t
7194 what "plain list"))
7195 ((or (org-on-heading-p)
7196 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7197 ;; we will sort the children of the current headline
7198 (org-back-to-heading)
7199 (setq start (point)
7200 end (progn (org-end-of-subtree t t)
7201 (or (bolp) (insert "\n"))
7202 (org-back-over-empty-lines)
7203 (point))
7204 what "children")
7205 (goto-char start)
7206 (show-subtree)
7207 (outline-next-heading))
7209 ;; we will sort the top-level entries in this file
7210 (goto-char (point-min))
7211 (or (org-on-heading-p) (outline-next-heading))
7212 (setq start (point))
7213 (goto-char (point-max))
7214 (beginning-of-line 1)
7215 (when (looking-at ".*?\\S-")
7216 ;; File ends in a non-white line
7217 (end-of-line 1)
7218 (insert "\n"))
7219 (setq end (point-max))
7220 (setq what "top-level")
7221 (goto-char start)
7222 (show-all)))
7224 (setq beg (point))
7225 (if (>= beg end) (error "Nothing to sort"))
7227 (unless plain-list-p
7228 (looking-at "\\(\\*+\\)")
7229 (setq stars (match-string 1)
7230 re (concat "^" (regexp-quote stars) " +")
7231 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7232 txt (buffer-substring beg end))
7233 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7234 (if (and (not (equal stars "*")) (string-match re2 txt))
7235 (error "Region to sort contains a level above the first entry")))
7237 (unless sorting-type
7238 (message
7239 (if plain-list-p
7240 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7241 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7242 [t]ime [s]cheduled [d]eadline [c]reated
7243 A/N/T/S/D/C/P/O/F means reversed:")
7244 what)
7245 (setq sorting-type (read-char-exclusive))
7247 (and (= (downcase sorting-type) ?f)
7248 (setq getkey-func
7249 (org-icompleting-read "Sort using function: "
7250 obarray 'fboundp t nil nil))
7251 (setq getkey-func (intern getkey-func)))
7253 (and (= (downcase sorting-type) ?r)
7254 (setq property
7255 (org-icompleting-read "Property: "
7256 (mapcar 'list (org-buffer-property-keys t))
7257 nil t))))
7259 (message "Sorting entries...")
7261 (save-restriction
7262 (narrow-to-region start end)
7264 (let ((dcst (downcase sorting-type))
7265 (case-fold-search nil)
7266 (now (current-time)))
7267 (sort-subr
7268 (/= dcst sorting-type)
7269 ;; This function moves to the beginning character of the "record" to
7270 ;; be sorted.
7271 (if plain-list-p
7272 (lambda nil
7273 (if (org-at-item-p) t (goto-char (point-max))))
7274 (lambda nil
7275 (if (re-search-forward re nil t)
7276 (goto-char (match-beginning 0))
7277 (goto-char (point-max)))))
7278 ;; This function moves to the last character of the "record" being
7279 ;; sorted.
7280 (if plain-list-p
7281 'org-end-of-item
7282 (lambda nil
7283 (save-match-data
7284 (condition-case nil
7285 (outline-forward-same-level 1)
7286 (error
7287 (goto-char (point-max)))))))
7289 ;; This function returns the value that gets sorted against.
7290 (if plain-list-p
7291 (lambda nil
7292 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7293 (cond
7294 ((= dcst ?n)
7295 (string-to-number (buffer-substring (match-end 0)
7296 (point-at-eol))))
7297 ((= dcst ?a)
7298 (buffer-substring (match-end 0) (point-at-eol)))
7299 ((= dcst ?t)
7300 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7301 (re-search-forward org-ts-regexp-both
7302 (point-at-eol) t))
7303 (org-time-string-to-seconds (match-string 0))
7304 (org-float-time now)))
7305 ((= dcst ?f)
7306 (if getkey-func
7307 (progn
7308 (setq tmp (funcall getkey-func))
7309 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7310 tmp)
7311 (error "Invalid key function `%s'" getkey-func)))
7312 (t (error "Invalid sorting type `%c'" sorting-type)))))
7313 (lambda nil
7314 (cond
7315 ((= dcst ?n)
7316 (if (looking-at org-complex-heading-regexp)
7317 (string-to-number (match-string 4))
7318 nil))
7319 ((= dcst ?a)
7320 (if (looking-at org-complex-heading-regexp)
7321 (funcall case-func (match-string 4))
7322 nil))
7323 ((= dcst ?t)
7324 (let ((end (save-excursion (outline-next-heading) (point))))
7325 (if (or (re-search-forward org-ts-regexp end t)
7326 (re-search-forward org-ts-regexp-both end t))
7327 (org-time-string-to-seconds (match-string 0))
7328 (org-float-time now))))
7329 ((= dcst ?c)
7330 (let ((end (save-excursion (outline-next-heading) (point))))
7331 (if (re-search-forward
7332 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7333 end t)
7334 (org-time-string-to-seconds (match-string 0))
7335 (org-float-time now))))
7336 ((= dcst ?s)
7337 (let ((end (save-excursion (outline-next-heading) (point))))
7338 (if (re-search-forward org-scheduled-time-regexp end t)
7339 (org-time-string-to-seconds (match-string 1))
7340 (org-float-time now))))
7341 ((= dcst ?d)
7342 (let ((end (save-excursion (outline-next-heading) (point))))
7343 (if (re-search-forward org-deadline-time-regexp end t)
7344 (org-time-string-to-seconds (match-string 1))
7345 (org-float-time now))))
7346 ((= dcst ?p)
7347 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7348 (string-to-char (match-string 2))
7349 org-default-priority))
7350 ((= dcst ?r)
7351 (or (org-entry-get nil property) ""))
7352 ((= dcst ?o)
7353 (if (looking-at org-complex-heading-regexp)
7354 (- 9999 (length (member (match-string 2)
7355 org-todo-keywords-1)))))
7356 ((= dcst ?f)
7357 (if getkey-func
7358 (progn
7359 (setq tmp (funcall getkey-func))
7360 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7361 tmp)
7362 (error "Invalid key function `%s'" getkey-func)))
7363 (t (error "Invalid sorting type `%c'" sorting-type)))))
7365 (cond
7366 ((= dcst ?a) 'string<)
7367 ((= dcst ?f) compare-func)
7368 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7369 (t nil)))))
7370 (run-hooks 'org-after-sorting-entries-or-items-hook)
7371 (message "Sorting entries...done")))
7373 (defun org-do-sort (table what &optional with-case sorting-type)
7374 "Sort TABLE of WHAT according to SORTING-TYPE.
7375 The user will be prompted for the SORTING-TYPE if the call to this
7376 function does not specify it. WHAT is only for the prompt, to indicate
7377 what is being sorted. The sorting key will be extracted from
7378 the car of the elements of the table.
7379 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7380 (unless sorting-type
7381 (message
7382 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7383 what)
7384 (setq sorting-type (read-char-exclusive)))
7385 (let ((dcst (downcase sorting-type))
7386 extractfun comparefun)
7387 ;; Define the appropriate functions
7388 (cond
7389 ((= dcst ?n)
7390 (setq extractfun 'string-to-number
7391 comparefun (if (= dcst sorting-type) '< '>)))
7392 ((= dcst ?a)
7393 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7394 (lambda(x) (downcase (org-sort-remove-invisible x))))
7395 comparefun (if (= dcst sorting-type)
7396 'string<
7397 (lambda (a b) (and (not (string< a b))
7398 (not (string= a b)))))))
7399 ((= dcst ?t)
7400 (setq extractfun
7401 (lambda (x)
7402 (if (or (string-match org-ts-regexp x)
7403 (string-match org-ts-regexp-both x))
7404 (org-float-time
7405 (org-time-string-to-time (match-string 0 x)))
7407 comparefun (if (= dcst sorting-type) '< '>)))
7408 (t (error "Invalid sorting type `%c'" sorting-type)))
7410 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7411 table)
7412 (lambda (a b) (funcall comparefun (car a) (car b))))))
7415 ;;; The orgstruct minor mode
7417 ;; Define a minor mode which can be used in other modes in order to
7418 ;; integrate the org-mode structure editing commands.
7420 ;; This is really a hack, because the org-mode structure commands use
7421 ;; keys which normally belong to the major mode. Here is how it
7422 ;; works: The minor mode defines all the keys necessary to operate the
7423 ;; structure commands, but wraps the commands into a function which
7424 ;; tests if the cursor is currently at a headline or a plain list
7425 ;; item. If that is the case, the structure command is used,
7426 ;; temporarily setting many Org-mode variables like regular
7427 ;; expressions for filling etc. However, when any of those keys is
7428 ;; used at a different location, function uses `key-binding' to look
7429 ;; up if the key has an associated command in another currently active
7430 ;; keymap (minor modes, major mode, global), and executes that
7431 ;; command. There might be problems if any of the keys is otherwise
7432 ;; used as a prefix key.
7434 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7435 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7436 ;; addresses this by checking explicitly for both bindings.
7438 (defvar orgstruct-mode-map (make-sparse-keymap)
7439 "Keymap for the minor `orgstruct-mode'.")
7441 (defvar org-local-vars nil
7442 "List of local variables, for use by `orgstruct-mode'")
7444 ;;;###autoload
7445 (define-minor-mode orgstruct-mode
7446 "Toggle the minor more `orgstruct-mode'.
7447 This mode is for using Org-mode structure commands in other modes.
7448 The following key behave as if Org-mode was active, if the cursor
7449 is on a headline, or on a plain list item (both in the definition
7450 of Org-mode).
7452 M-up Move entry/item up
7453 M-down Move entry/item down
7454 M-left Promote
7455 M-right Demote
7456 M-S-up Move entry/item up
7457 M-S-down Move entry/item down
7458 M-S-left Promote subtree
7459 M-S-right Demote subtree
7460 M-q Fill paragraph and items like in Org-mode
7461 C-c ^ Sort entries
7462 C-c - Cycle list bullet
7463 TAB Cycle item visibility
7464 M-RET Insert new heading/item
7465 S-M-RET Insert new TODO heading / Checkbox item
7466 C-c C-c Set tags / toggle checkbox"
7467 nil " OrgStruct" nil
7468 (org-load-modules-maybe)
7469 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7471 ;;;###autoload
7472 (defun turn-on-orgstruct ()
7473 "Unconditionally turn on `orgstruct-mode'."
7474 (orgstruct-mode 1))
7476 (defun orgstruct++-mode (&optional arg)
7477 "Toggle `orgstruct-mode', the enhanced version of it.
7478 In addition to setting orgstruct-mode, this also exports all indentation
7479 and autofilling variables from org-mode into the buffer. It will also
7480 recognize item context in multiline items.
7481 Note that turning off orgstruct-mode will *not* remove the
7482 indentation/paragraph settings. This can only be done by refreshing the
7483 major mode, for example with \\[normal-mode]."
7484 (interactive "P")
7485 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7486 (if (< arg 1)
7487 (orgstruct-mode -1)
7488 (orgstruct-mode 1)
7489 (let (var val)
7490 (mapc
7491 (lambda (x)
7492 (when (string-match
7493 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7494 (symbol-name (car x)))
7495 (setq var (car x) val (nth 1 x))
7496 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7497 org-local-vars)
7498 (org-set-local 'orgstruct-is-++ t))))
7500 (defvar orgstruct-is-++ nil
7501 "Is orgstruct-mode in ++ version in the current-buffer?")
7502 (make-variable-buffer-local 'orgstruct-is-++)
7504 ;;;###autoload
7505 (defun turn-on-orgstruct++ ()
7506 "Unconditionally turn on `orgstruct++-mode'."
7507 (orgstruct++-mode 1))
7509 (defun orgstruct-error ()
7510 "Error when there is no default binding for a structure key."
7511 (interactive)
7512 (error "This key has no function outside structure elements"))
7514 (defun orgstruct-setup ()
7515 "Setup orgstruct keymaps."
7516 (let ((nfunc 0)
7517 (bindings
7518 (list
7519 '([(meta up)] org-metaup)
7520 '([(meta down)] org-metadown)
7521 '([(meta left)] org-metaleft)
7522 '([(meta right)] org-metaright)
7523 '([(meta shift up)] org-shiftmetaup)
7524 '([(meta shift down)] org-shiftmetadown)
7525 '([(meta shift left)] org-shiftmetaleft)
7526 '([(meta shift right)] org-shiftmetaright)
7527 '([?\e (up)] org-metaup)
7528 '([?\e (down)] org-metadown)
7529 '([?\e (left)] org-metaleft)
7530 '([?\e (right)] org-metaright)
7531 '([?\e (shift up)] org-shiftmetaup)
7532 '([?\e (shift down)] org-shiftmetadown)
7533 '([?\e (shift left)] org-shiftmetaleft)
7534 '([?\e (shift right)] org-shiftmetaright)
7535 '([(shift up)] org-shiftup)
7536 '([(shift down)] org-shiftdown)
7537 '([(shift left)] org-shiftleft)
7538 '([(shift right)] org-shiftright)
7539 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7540 '("\M-q" fill-paragraph)
7541 '("\C-c^" org-sort)
7542 '("\C-c-" org-cycle-list-bullet)))
7543 elt key fun cmd)
7544 (while (setq elt (pop bindings))
7545 (setq nfunc (1+ nfunc))
7546 (setq key (org-key (car elt))
7547 fun (nth 1 elt)
7548 cmd (orgstruct-make-binding fun nfunc key))
7549 (org-defkey orgstruct-mode-map key cmd))
7551 ;; Special treatment needed for TAB and RET
7552 (org-defkey orgstruct-mode-map [(tab)]
7553 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7554 (org-defkey orgstruct-mode-map "\C-i"
7555 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7557 (org-defkey orgstruct-mode-map "\M-\C-m"
7558 (orgstruct-make-binding 'org-insert-heading 105
7559 "\M-\C-m" [(meta return)]))
7560 (org-defkey orgstruct-mode-map [(meta return)]
7561 (orgstruct-make-binding 'org-insert-heading 106
7562 [(meta return)] "\M-\C-m"))
7564 (org-defkey orgstruct-mode-map [(shift meta return)]
7565 (orgstruct-make-binding 'org-insert-todo-heading 107
7566 [(meta return)] "\M-\C-m"))
7568 (org-defkey orgstruct-mode-map "\e\C-m"
7569 (orgstruct-make-binding 'org-insert-heading 108
7570 "\e\C-m" [?\e (return)]))
7571 (org-defkey orgstruct-mode-map [?\e (return)]
7572 (orgstruct-make-binding 'org-insert-heading 109
7573 [?\e (return)] "\e\C-m"))
7574 (org-defkey orgstruct-mode-map [?\e (shift return)]
7575 (orgstruct-make-binding 'org-insert-todo-heading 110
7576 [?\e (return)] "\e\C-m"))
7578 (unless org-local-vars
7579 (setq org-local-vars (org-get-local-variables)))
7583 (defun orgstruct-make-binding (fun n &rest keys)
7584 "Create a function for binding in the structure minor mode.
7585 FUN is the command to call inside a table. N is used to create a unique
7586 command name. KEYS are keys that should be checked in for a command
7587 to execute outside of tables."
7588 (eval
7589 (list 'defun
7590 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7591 '(arg)
7592 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7593 "Outside of structure, run the binding of `"
7594 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7595 "'.")
7596 '(interactive "p")
7597 (list 'if
7598 `(org-context-p 'headline 'item
7599 (and orgstruct-is-++
7600 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7601 'item-body))
7602 (list 'org-run-like-in-org-mode (list 'quote fun))
7603 (list 'let '(orgstruct-mode)
7604 (list 'call-interactively
7605 (append '(or)
7606 (mapcar (lambda (k)
7607 (list 'key-binding k))
7608 keys)
7609 '('orgstruct-error))))))))
7611 (defun org-context-p (&rest contexts)
7612 "Check if local context is any of CONTEXTS.
7613 Possible values in the list of contexts are `table', `headline', and `item'."
7614 (let ((pos (point)))
7615 (goto-char (point-at-bol))
7616 (prog1 (or (and (memq 'table contexts)
7617 (looking-at "[ \t]*|"))
7618 (and (memq 'headline contexts)
7619 ;;????????? (looking-at "\\*+"))
7620 (looking-at outline-regexp))
7621 (and (memq 'item contexts)
7622 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7623 (and (memq 'item-body contexts)
7624 (org-in-item-p)))
7625 (goto-char pos))))
7627 (defun org-get-local-variables ()
7628 "Return a list of all local variables in an org-mode buffer."
7629 (let (varlist)
7630 (with-current-buffer (get-buffer-create "*Org tmp*")
7631 (erase-buffer)
7632 (org-mode)
7633 (setq varlist (buffer-local-variables)))
7634 (kill-buffer "*Org tmp*")
7635 (delq nil
7636 (mapcar
7637 (lambda (x)
7638 (setq x
7639 (if (symbolp x)
7640 (list x)
7641 (list (car x) (list 'quote (cdr x)))))
7642 (if (string-match
7643 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7644 (symbol-name (car x)))
7645 x nil))
7646 varlist))))
7648 ;;;###autoload
7649 (defun org-run-like-in-org-mode (cmd)
7650 "Run a command, pretending that the current buffer is in Org-mode.
7651 This will temporarily bind local variables that are typically bound in
7652 Org-mode to the values they have in Org-mode, and then interactively
7653 call CMD."
7654 (org-load-modules-maybe)
7655 (unless org-local-vars
7656 (setq org-local-vars (org-get-local-variables)))
7657 (eval (list 'let org-local-vars
7658 (list 'call-interactively (list 'quote cmd)))))
7660 ;;;; Archiving
7662 (defun org-get-category (&optional pos)
7663 "Get the category applying to position POS."
7664 (get-text-property (or pos (point)) 'org-category))
7666 (defun org-refresh-category-properties ()
7667 "Refresh category text properties in the buffer."
7668 (let ((def-cat (cond
7669 ((null org-category)
7670 (if buffer-file-name
7671 (file-name-sans-extension
7672 (file-name-nondirectory buffer-file-name))
7673 "???"))
7674 ((symbolp org-category) (symbol-name org-category))
7675 (t org-category)))
7676 beg end cat pos optionp)
7677 (org-unmodified
7678 (save-excursion
7679 (save-restriction
7680 (widen)
7681 (goto-char (point-min))
7682 (put-text-property (point) (point-max) 'org-category def-cat)
7683 (while (re-search-forward
7684 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7685 (setq pos (match-end 0)
7686 optionp (equal (char-after (match-beginning 0)) ?#)
7687 cat (org-trim (match-string 2)))
7688 (if optionp
7689 (setq beg (point-at-bol) end (point-max))
7690 (org-back-to-heading t)
7691 (setq beg (point) end (org-end-of-subtree t t)))
7692 (put-text-property beg end 'org-category cat)
7693 (goto-char pos)))))))
7696 ;;;; Link Stuff
7698 ;;; Link abbreviations
7700 (defun org-link-expand-abbrev (link)
7701 "Apply replacements as defined in `org-link-abbrev-alist."
7702 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7703 (let* ((key (match-string 1 link))
7704 (as (or (assoc key org-link-abbrev-alist-local)
7705 (assoc key org-link-abbrev-alist)))
7706 (tag (and (match-end 2) (match-string 3 link)))
7707 rpl)
7708 (if (not as)
7709 link
7710 (setq rpl (cdr as))
7711 (cond
7712 ((symbolp rpl) (funcall rpl tag))
7713 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7714 ((string-match "%h" rpl)
7715 (replace-match (url-hexify-string (or tag "")) t t rpl))
7716 (t (concat rpl tag)))))
7717 link))
7719 ;;; Storing and inserting links
7721 (defvar org-insert-link-history nil
7722 "Minibuffer history for links inserted with `org-insert-link'.")
7724 (defvar org-stored-links nil
7725 "Contains the links stored with `org-store-link'.")
7727 (defvar org-store-link-plist nil
7728 "Plist with info about the most recently link created with `org-store-link'.")
7730 (defvar org-link-protocols nil
7731 "Link protocols added to Org-mode using `org-add-link-type'.")
7733 (defvar org-store-link-functions nil
7734 "List of functions that are called to create and store a link.
7735 Each function will be called in turn until one returns a non-nil
7736 value. Each function should check if it is responsible for creating
7737 this link (for example by looking at the major mode).
7738 If not, it must exit and return nil.
7739 If yes, it should return a non-nil value after a calling
7740 `org-store-link-props' with a list of properties and values.
7741 Special properties are:
7743 :type The link prefix. like \"http\". This must be given.
7744 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7745 This is obligatory as well.
7746 :description Optional default description for the second pair
7747 of brackets in an Org-mode link. The user can still change
7748 this when inserting this link into an Org-mode buffer.
7750 In addition to these, any additional properties can be specified
7751 and then used in remember templates.")
7753 (defun org-add-link-type (type &optional follow export)
7754 "Add TYPE to the list of `org-link-types'.
7755 Re-compute all regular expressions depending on `org-link-types'
7757 FOLLOW and EXPORT are two functions.
7759 FOLLOW should take the link path as the single argument and do whatever
7760 is necessary to follow the link, for example find a file or display
7761 a mail message.
7763 EXPORT should format the link path for export to one of the export formats.
7764 It should be a function accepting three arguments:
7766 path the path of the link, the text after the prefix (like \"http:\")
7767 desc the description of the link, if any, nil if there was no description
7768 format the export format, a symbol like `html' or `latex'.
7770 The function may use the FORMAT information to return different values
7771 depending on the format. The return value will be put literally into
7772 the exported file.
7773 Org-mode has a built-in default for exporting links. If you are happy with
7774 this default, there is no need to define an export function for the link
7775 type. For a simple example of an export function, see `org-bbdb.el'."
7776 (add-to-list 'org-link-types type t)
7777 (org-make-link-regexps)
7778 (if (assoc type org-link-protocols)
7779 (setcdr (assoc type org-link-protocols) (list follow export))
7780 (push (list type follow export) org-link-protocols)))
7782 (defvar org-agenda-buffer-name)
7784 ;;;###autoload
7785 (defun org-store-link (arg)
7786 "\\<org-mode-map>Store an org-link to the current location.
7787 This link is added to `org-stored-links' and can later be inserted
7788 into an org-buffer with \\[org-insert-link].
7790 For some link types, a prefix arg is interpreted:
7791 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7792 For file links, arg negates `org-context-in-file-links'."
7793 (interactive "P")
7794 (org-load-modules-maybe)
7795 (setq org-store-link-plist nil) ; reset
7796 (let ((outline-regexp (org-get-limited-outline-regexp))
7797 link cpltxt desc description search txt custom-id)
7798 (cond
7800 ((run-hook-with-args-until-success 'org-store-link-functions)
7801 (setq link (plist-get org-store-link-plist :link)
7802 desc (or (plist-get org-store-link-plist :description) link)))
7804 ((equal (buffer-name) "*Org Edit Src Example*")
7805 (let (label gc)
7806 (while (or (not label)
7807 (save-excursion
7808 (save-restriction
7809 (widen)
7810 (goto-char (point-min))
7811 (re-search-forward
7812 (regexp-quote (format org-coderef-label-format label))
7813 nil t))))
7814 (when label (message "Label exists already") (sit-for 2))
7815 (setq label (read-string "Code line label: " label)))
7816 (end-of-line 1)
7817 (setq link (format org-coderef-label-format label))
7818 (setq gc (- 79 (length link)))
7819 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7820 (insert link)
7821 (setq link (concat "(" label ")") desc nil)))
7823 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7824 ;; We are in the agenda, link to referenced location
7825 (let ((m (or (get-text-property (point) 'org-hd-marker)
7826 (get-text-property (point) 'org-marker))))
7827 (when m
7828 (org-with-point-at m
7829 (call-interactively 'org-store-link)))))
7831 ((eq major-mode 'calendar-mode)
7832 (let ((cd (calendar-cursor-to-date)))
7833 (setq link
7834 (format-time-string
7835 (car org-time-stamp-formats)
7836 (apply 'encode-time
7837 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7838 nil nil nil))))
7839 (org-store-link-props :type "calendar" :date cd)))
7841 ((eq major-mode 'w3-mode)
7842 (setq cpltxt (if (and (buffer-name)
7843 (not (string-match "Untitled" (buffer-name))))
7844 (buffer-name)
7845 (url-view-url t))
7846 link (org-make-link (url-view-url t)))
7847 (org-store-link-props :type "w3" :url (url-view-url t)))
7849 ((eq major-mode 'w3m-mode)
7850 (setq cpltxt (or w3m-current-title w3m-current-url)
7851 link (org-make-link w3m-current-url))
7852 (org-store-link-props :type "w3m" :url (url-view-url t)))
7854 ((setq search (run-hook-with-args-until-success
7855 'org-create-file-search-functions))
7856 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7857 "::" search))
7858 (setq cpltxt (or description link)))
7860 ((eq major-mode 'image-mode)
7861 (setq cpltxt (concat "file:"
7862 (abbreviate-file-name buffer-file-name))
7863 link (org-make-link cpltxt))
7864 (org-store-link-props :type "image" :file buffer-file-name))
7866 ((eq major-mode 'dired-mode)
7867 ;; link to the file in the current line
7868 (let ((file (dired-get-filename nil t)))
7869 (setq file (if file
7870 (abbreviate-file-name
7871 (expand-file-name (dired-get-filename nil t)))
7872 ;; otherwise, no file so use current directory.
7873 default-directory))
7874 (setq cpltxt (concat "file:" file)
7875 link (org-make-link cpltxt))))
7877 ((and buffer-file-name (org-mode-p))
7878 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7879 (cond
7880 ((org-in-regexp "<<\\(.*?\\)>>")
7881 (setq cpltxt
7882 (concat "file:"
7883 (abbreviate-file-name buffer-file-name)
7884 "::" (match-string 1))
7885 link (org-make-link cpltxt)))
7886 ((and (featurep 'org-id)
7887 (or (eq org-link-to-org-use-id t)
7888 (and (eq org-link-to-org-use-id 'create-if-interactive)
7889 (interactive-p))
7890 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7891 (interactive-p)
7892 (not custom-id))
7893 (and org-link-to-org-use-id
7894 (condition-case nil
7895 (org-entry-get nil "ID")
7896 (error nil)))))
7897 ;; We can make a link using the ID.
7898 (setq link (condition-case nil
7899 (prog1 (org-id-store-link)
7900 (setq desc (plist-get org-store-link-plist
7901 :description)))
7902 (error
7903 ;; probably before first headline, link to file only
7904 (concat "file:"
7905 (abbreviate-file-name buffer-file-name))))))
7907 ;; Just link to current headline
7908 (setq cpltxt (concat "file:"
7909 (abbreviate-file-name buffer-file-name)))
7910 ;; Add a context search string
7911 (when (org-xor org-context-in-file-links arg)
7912 (setq txt (cond
7913 ((org-on-heading-p) nil)
7914 ((org-region-active-p)
7915 (buffer-substring (region-beginning) (region-end)))
7916 (t nil)))
7917 (when (or (null txt) (string-match "\\S-" txt))
7918 (setq cpltxt
7919 (concat cpltxt "::"
7920 (condition-case nil
7921 (org-make-org-heading-search-string txt)
7922 (error "")))
7923 desc (or (nth 4 (ignore-errors
7924 (org-heading-components))) "NONE"))))
7925 (if (string-match "::\\'" cpltxt)
7926 (setq cpltxt (substring cpltxt 0 -2)))
7927 (setq link (org-make-link cpltxt)))))
7929 ((buffer-file-name (buffer-base-buffer))
7930 ;; Just link to this file here.
7931 (setq cpltxt (concat "file:"
7932 (abbreviate-file-name
7933 (buffer-file-name (buffer-base-buffer)))))
7934 ;; Add a context string
7935 (when (org-xor org-context-in-file-links arg)
7936 (setq txt (if (org-region-active-p)
7937 (buffer-substring (region-beginning) (region-end))
7938 (buffer-substring (point-at-bol) (point-at-eol))))
7939 ;; Only use search option if there is some text.
7940 (when (string-match "\\S-" txt)
7941 (setq cpltxt
7942 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7943 desc "NONE")))
7944 (setq link (org-make-link cpltxt)))
7946 ((interactive-p)
7947 (error "Cannot link to a buffer which is not visiting a file"))
7949 (t (setq link nil)))
7951 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7952 (setq link (or link cpltxt)
7953 desc (or desc cpltxt))
7954 (if (equal desc "NONE") (setq desc nil))
7956 (if (and (or (interactive-p) executing-kbd-macro) link)
7957 (progn
7958 (setq org-stored-links
7959 (cons (list link desc) org-stored-links))
7960 (message "Stored: %s" (or desc link))
7961 (when custom-id
7962 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7963 "::#" custom-id))
7964 (setq org-stored-links
7965 (cons (list link desc) org-stored-links))))
7966 (and link (org-make-link-string link desc)))))
7968 (defun org-store-link-props (&rest plist)
7969 "Store link properties, extract names and addresses."
7970 (let (x adr)
7971 (when (setq x (plist-get plist :from))
7972 (setq adr (mail-extract-address-components x))
7973 (setq plist (plist-put plist :fromname (car adr)))
7974 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7975 (when (setq x (plist-get plist :to))
7976 (setq adr (mail-extract-address-components x))
7977 (setq plist (plist-put plist :toname (car adr)))
7978 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7979 (let ((from (plist-get plist :from))
7980 (to (plist-get plist :to)))
7981 (when (and from to org-from-is-user-regexp)
7982 (setq plist
7983 (plist-put plist :fromto
7984 (if (string-match org-from-is-user-regexp from)
7985 (concat "to %t")
7986 (concat "from %f"))))))
7987 (setq org-store-link-plist plist))
7989 (defun org-add-link-props (&rest plist)
7990 "Add these properties to the link property list."
7991 (let (key value)
7992 (while plist
7993 (setq key (pop plist) value (pop plist))
7994 (setq org-store-link-plist
7995 (plist-put org-store-link-plist key value)))))
7997 (defun org-email-link-description (&optional fmt)
7998 "Return the description part of an email link.
7999 This takes information from `org-store-link-plist' and formats it
8000 according to FMT (default from `org-email-link-description-format')."
8001 (setq fmt (or fmt org-email-link-description-format))
8002 (let* ((p org-store-link-plist)
8003 (to (plist-get p :toaddress))
8004 (from (plist-get p :fromaddress))
8005 (table
8006 (list
8007 (cons "%c" (plist-get p :fromto))
8008 (cons "%F" (plist-get p :from))
8009 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8010 (cons "%T" (plist-get p :to))
8011 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8012 (cons "%s" (plist-get p :subject))
8013 (cons "%m" (plist-get p :message-id)))))
8014 (when (string-match "%c" fmt)
8015 ;; Check if the user wrote this message
8016 (if (and org-from-is-user-regexp from to
8017 (save-match-data (string-match org-from-is-user-regexp from)))
8018 (setq fmt (replace-match "to %t" t t fmt))
8019 (setq fmt (replace-match "from %f" t t fmt))))
8020 (org-replace-escapes fmt table)))
8022 (defun org-make-org-heading-search-string (&optional string heading)
8023 "Make search string for STRING or current headline."
8024 (interactive)
8025 (let ((s (or string (org-get-heading))))
8026 (unless (and string (not heading))
8027 ;; We are using a headline, clean up garbage in there.
8028 (if (string-match org-todo-regexp s)
8029 (setq s (replace-match "" t t s)))
8030 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
8031 (setq s (replace-match "" t t s)))
8032 (setq s (org-trim s))
8033 (if (string-match (concat "^\\(" org-quote-string "\\|"
8034 org-comment-string "\\)") s)
8035 (setq s (replace-match "" t t s)))
8036 (while (string-match org-ts-regexp s)
8037 (setq s (replace-match "" t t s))))
8038 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8039 (setq s (replace-match " " t t s)))
8040 (or string (setq s (concat "*" s))) ; Add * for headlines
8041 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8043 (defun org-make-link (&rest strings)
8044 "Concatenate STRINGS."
8045 (apply 'concat strings))
8047 (defun org-make-link-string (link &optional description)
8048 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8049 (unless (string-match "\\S-" link)
8050 (error "Empty link"))
8051 (when (and description
8052 (stringp description)
8053 (not (string-match "\\S-" description)))
8054 (setq description nil))
8055 (when (stringp description)
8056 ;; Remove brackets from the description, they are fatal.
8057 (while (string-match "\\[" description)
8058 (setq description (replace-match "{" t t description)))
8059 (while (string-match "\\]" description)
8060 (setq description (replace-match "}" t t description))))
8061 (when (equal (org-link-escape link) description)
8062 ;; No description needed, it is identical
8063 (setq description nil))
8064 (when (and (not description)
8065 (not (equal link (org-link-escape link))))
8066 (setq description (org-extract-attributes link)))
8067 (concat "[[" (org-link-escape link) "]"
8068 (if description (concat "[" description "]") "")
8069 "]"))
8071 (defconst org-link-escape-chars
8072 '((?\ . "%20")
8073 (?\[ . "%5B")
8074 (?\] . "%5D")
8075 (?\340 . "%E0") ; `a
8076 (?\342 . "%E2") ; ^a
8077 (?\347 . "%E7") ; ,c
8078 (?\350 . "%E8") ; `e
8079 (?\351 . "%E9") ; 'e
8080 (?\352 . "%EA") ; ^e
8081 (?\356 . "%EE") ; ^i
8082 (?\364 . "%F4") ; ^o
8083 (?\371 . "%F9") ; `u
8084 (?\373 . "%FB") ; ^u
8085 (?\; . "%3B")
8086 ;; (?? . "%3F")
8087 (?= . "%3D")
8088 (?+ . "%2B")
8090 "Association list of escapes for some characters problematic in links.
8091 This is the list that is used for internal purposes.")
8093 (defvar org-url-encoding-use-url-hexify nil)
8095 (defconst org-link-escape-chars-browser
8096 '((?\ . "%20")) ; 32 for the SPC char
8097 "Association list of escapes for some characters problematic in links.
8098 This is the list that is used before handing over to the browser.")
8100 (defun org-link-escape (text &optional table)
8101 "Escape characters in TEXT that are problematic for links."
8102 (if (and org-url-encoding-use-url-hexify (not table))
8103 (url-hexify-string text)
8104 (setq table (or table org-link-escape-chars))
8105 (when text
8106 (let ((re (mapconcat (lambda (x) (regexp-quote
8107 (char-to-string (car x))))
8108 table "\\|")))
8109 (while (string-match re text)
8110 (setq text
8111 (replace-match
8112 (cdr (assoc (string-to-char (match-string 0 text))
8113 table))
8114 t t text)))
8115 text))))
8117 (defun org-link-unescape (text &optional table)
8118 "Reverse the action of `org-link-escape'."
8119 (if (and org-url-encoding-use-url-hexify (not table))
8120 (url-unhex-string text)
8121 (setq table (or table org-link-escape-chars))
8122 (when text
8123 (let ((case-fold-search t)
8124 (re (mapconcat (lambda (x) (regexp-quote (downcase (cdr x))))
8125 table "\\|")))
8126 (while (string-match re text)
8127 (setq text
8128 (replace-match
8129 (char-to-string (car (rassoc (upcase (match-string 0 text))
8130 table)))
8131 t t text)))
8132 text))))
8134 (defun org-xor (a b)
8135 "Exclusive or."
8136 (if a (not b) b))
8138 (defun org-fixup-message-id-for-http (s)
8139 "Replace special characters in a message id, so it can be used in an http query."
8140 (while (string-match "<" s)
8141 (setq s (replace-match "%3C" t t s)))
8142 (while (string-match ">" s)
8143 (setq s (replace-match "%3E" t t s)))
8144 (while (string-match "@" s)
8145 (setq s (replace-match "%40" t t s)))
8148 ;;;###autoload
8149 (defun org-insert-link-global ()
8150 "Insert a link like Org-mode does.
8151 This command can be called in any mode to insert a link in Org-mode syntax."
8152 (interactive)
8153 (org-load-modules-maybe)
8154 (org-run-like-in-org-mode 'org-insert-link))
8156 (defun org-insert-link (&optional complete-file link-location)
8157 "Insert a link. At the prompt, enter the link.
8159 Completion can be used to insert any of the link protocol prefixes like
8160 http or ftp in use.
8162 The history can be used to select a link previously stored with
8163 `org-store-link'. When the empty string is entered (i.e. if you just
8164 press RET at the prompt), the link defaults to the most recently
8165 stored link. As SPC triggers completion in the minibuffer, you need to
8166 use M-SPC or C-q SPC to force the insertion of a space character.
8168 You will also be prompted for a description, and if one is given, it will
8169 be displayed in the buffer instead of the link.
8171 If there is already a link at point, this command will allow you to edit link
8172 and description parts.
8174 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8175 be selected using completion. The path to the file will be relative to the
8176 current directory if the file is in the current directory or a subdirectory.
8177 Otherwise, the link will be the absolute path as completed in the minibuffer
8178 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8179 option `org-link-file-path-type'.
8181 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8182 the current directory or below.
8184 With three \\[universal-argument] prefixes, negate the meaning of
8185 `org-keep-stored-link-after-insertion'.
8187 If `org-make-link-description-function' is non-nil, this function will be
8188 called with the link target, and the result will be the default
8189 link description.
8191 If the LINK-LOCATION parameter is non-nil, this value will be
8192 used as the link location instead of reading one interactively."
8193 (interactive "P")
8194 (let* ((wcf (current-window-configuration))
8195 (region (if (org-region-active-p)
8196 (buffer-substring (region-beginning) (region-end))))
8197 (remove (and region (list (region-beginning) (region-end))))
8198 (desc region)
8199 tmphist ; byte-compile incorrectly complains about this
8200 (link link-location)
8201 entry file all-prefixes)
8202 (cond
8203 (link-location) ; specified by arg, just use it.
8204 ((org-in-regexp org-bracket-link-regexp 1)
8205 ;; We do have a link at point, and we are going to edit it.
8206 (setq remove (list (match-beginning 0) (match-end 0)))
8207 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8208 (setq link (read-string "Link: "
8209 (org-link-unescape
8210 (org-match-string-no-properties 1)))))
8211 ((or (org-in-regexp org-angle-link-re)
8212 (org-in-regexp org-plain-link-re))
8213 ;; Convert to bracket link
8214 (setq remove (list (match-beginning 0) (match-end 0))
8215 link (read-string "Link: "
8216 (org-remove-angle-brackets (match-string 0)))))
8217 ((member complete-file '((4) (16)))
8218 ;; Completing read for file names.
8219 (setq link (org-file-complete-link complete-file)))
8221 ;; Read link, with completion for stored links.
8222 (with-output-to-temp-buffer "*Org Links*"
8223 (princ "Insert a link.
8224 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8225 (when org-stored-links
8226 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8227 (princ (mapconcat
8228 (lambda (x)
8229 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8230 (reverse org-stored-links) "\n"))))
8231 (let ((cw (selected-window)))
8232 (select-window (get-buffer-window "*Org Links*" 'visible))
8233 (setq truncate-lines t)
8234 (unless (pos-visible-in-window-p (point-max))
8235 (org-fit-window-to-buffer))
8236 (and (window-live-p cw) (select-window cw)))
8237 ;; Fake a link history, containing the stored links.
8238 (setq tmphist (append (mapcar 'car org-stored-links)
8239 org-insert-link-history))
8240 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8241 (mapcar 'car org-link-abbrev-alist)
8242 org-link-types))
8243 (unwind-protect
8244 (progn
8245 (setq link
8246 (let ((org-completion-use-ido nil)
8247 (org-completion-use-iswitchb nil))
8248 (org-completing-read
8249 "Link: "
8250 (append
8251 (mapcar (lambda (x) (list (concat x ":")))
8252 all-prefixes)
8253 (mapcar 'car org-stored-links))
8254 nil nil nil
8255 'tmphist
8256 (car (car org-stored-links)))))
8257 (if (not (string-match "\\S-" link))
8258 (error "No link selected"))
8259 (if (or (member link all-prefixes)
8260 (and (equal ":" (substring link -1))
8261 (member (substring link 0 -1) all-prefixes)
8262 (setq link (substring link 0 -1))))
8263 (setq link (org-link-try-special-completion link))))
8264 (set-window-configuration wcf)
8265 (kill-buffer "*Org Links*"))
8266 (setq entry (assoc link org-stored-links))
8267 (or entry (push link org-insert-link-history))
8268 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8269 (not org-keep-stored-link-after-insertion))
8270 (setq org-stored-links (delq (assoc link org-stored-links)
8271 org-stored-links)))
8272 (setq desc (or desc (nth 1 entry)))))
8274 (if (string-match org-plain-link-re link)
8275 ;; URL-like link, normalize the use of angular brackets.
8276 (setq link (org-make-link (org-remove-angle-brackets link))))
8278 ;; Check if we are linking to the current file with a search option
8279 ;; If yes, simplify the link by using only the search option.
8280 (when (and buffer-file-name
8281 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8282 (let* ((path (match-string 1 link))
8283 (case-fold-search nil)
8284 (search (match-string 2 link)))
8285 (save-match-data
8286 (if (equal (file-truename buffer-file-name) (file-truename path))
8287 ;; We are linking to this same file, with a search option
8288 (setq link search)))))
8290 ;; Check if we can/should use a relative path. If yes, simplify the link
8291 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8292 (let* ((type (match-string 1 link))
8293 (path (match-string 2 link))
8294 (origpath path)
8295 (case-fold-search nil))
8296 (cond
8297 ((or (eq org-link-file-path-type 'absolute)
8298 (equal complete-file '(16)))
8299 (setq path (abbreviate-file-name (expand-file-name path))))
8300 ((eq org-link-file-path-type 'noabbrev)
8301 (setq path (expand-file-name path)))
8302 ((eq org-link-file-path-type 'relative)
8303 (setq path (file-relative-name path)))
8305 (save-match-data
8306 (if (string-match (concat "^" (regexp-quote
8307 (file-name-as-directory
8308 (expand-file-name "."))))
8309 (expand-file-name path))
8310 ;; We are linking a file with relative path name.
8311 (setq path (substring (expand-file-name path)
8312 (match-end 0)))
8313 (setq path (abbreviate-file-name (expand-file-name path)))))))
8314 (setq link (concat type path))
8315 (if (equal desc origpath)
8316 (setq desc path))))
8318 (if org-make-link-description-function
8319 (setq desc (funcall org-make-link-description-function link desc)))
8321 (setq desc (read-string "Description: " desc))
8322 (unless (string-match "\\S-" desc) (setq desc nil))
8323 (if remove (apply 'delete-region remove))
8324 (insert (org-make-link-string link desc))))
8326 (defun org-link-try-special-completion (type)
8327 "If there is completion support for link type TYPE, offer it."
8328 (let ((fun (intern (concat "org-" type "-complete-link"))))
8329 (if (functionp fun)
8330 (funcall fun)
8331 (read-string "Link (no completion support): " (concat type ":")))))
8333 (defun org-file-complete-link (&optional arg)
8334 "Create a file link using completion."
8335 (let (file link)
8336 (setq file (read-file-name "File: "))
8337 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8338 (pwd1 (file-name-as-directory (abbreviate-file-name
8339 (expand-file-name ".")))))
8340 (cond
8341 ((equal arg '(16))
8342 (setq link (org-make-link
8343 "file:"
8344 (abbreviate-file-name (expand-file-name file)))))
8345 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8346 (setq link (org-make-link "file:" (match-string 1 file))))
8347 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8348 (expand-file-name file))
8349 (setq link (org-make-link
8350 "file:" (match-string 1 (expand-file-name file)))))
8351 (t (setq link (org-make-link "file:" file)))))
8352 link))
8354 (defun org-completing-read (&rest args)
8355 "Completing-read with SPACE being a normal character."
8356 (let ((minibuffer-local-completion-map
8357 (copy-keymap minibuffer-local-completion-map)))
8358 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8359 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8360 (apply 'org-icompleting-read args)))
8362 (defun org-completing-read-no-i (&rest args)
8363 (let (org-completion-use-ido org-completion-use-iswitchb)
8364 (apply 'org-completing-read args)))
8366 (defun org-iswitchb-completing-read (prompt choices &rest args)
8367 "Use iswitch as a completing-read replacement to choose from choices.
8368 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8369 from."
8370 (let* ((iswitchb-use-virtual-buffers nil)
8371 (iswitchb-make-buflist-hook
8372 (lambda ()
8373 (setq iswitchb-temp-buflist choices))))
8374 (iswitchb-read-buffer prompt)))
8376 (defun org-icompleting-read (&rest args)
8377 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8378 (org-without-partial-completion
8379 (if (and org-completion-use-ido
8380 (fboundp 'ido-completing-read)
8381 (boundp 'ido-mode) ido-mode
8382 (listp (second args)))
8383 (let ((ido-enter-matching-directory nil))
8384 (apply 'ido-completing-read (concat (car args))
8385 (if (consp (car (nth 1 args)))
8386 (mapcar (lambda (x) (car x)) (nth 1 args))
8387 (nth 1 args))
8388 (cddr args)))
8389 (if (and org-completion-use-iswitchb
8390 (boundp 'iswitchb-mode) iswitchb-mode
8391 (listp (second args)))
8392 (apply 'org-iswitchb-completing-read (concat (car args))
8393 (if (consp (car (nth 1 args)))
8394 (mapcar (lambda (x) (car x)) (nth 1 args))
8395 (nth 1 args))
8396 (cddr args))
8397 (apply 'completing-read args)))))
8399 (defun org-extract-attributes (s)
8400 "Extract the attributes cookie from a string and set as text property."
8401 (let (a attr (start 0) key value)
8402 (save-match-data
8403 (when (string-match "{{\\([^}]+\\)}}$" s)
8404 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8405 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8406 (setq key (match-string 1 a) value (match-string 2 a)
8407 start (match-end 0)
8408 attr (plist-put attr (intern key) value))))
8409 (org-add-props s nil 'org-attr attr))
8412 (defun org-extract-attributes-from-string (tag)
8413 (let (key value attr)
8414 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8415 (setq key (match-string 1 tag) value (match-string 2 tag)
8416 tag (replace-match "" t t tag)
8417 attr (plist-put attr (intern key) value)))
8418 (cons tag attr)))
8420 (defun org-attributes-to-string (plist)
8421 "Format a property list into an HTML attribute list."
8422 (let ((s "") key value)
8423 (while plist
8424 (setq key (pop plist) value (pop plist))
8425 (and value
8426 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8429 ;;; Opening/following a link
8431 (defvar org-link-search-failed nil)
8433 (defvar org-open-link-functions nil
8434 "Hook for functions finding a plain text link.
8435 These functions must take a single argument, the link content.
8436 They will be called for links that look like [[link text][description]]
8437 when LINK TEXT does not have a protocol like \"http:\" and does not look
8438 like a filename (e.g. \"./blue.png\").
8440 These functions will be called *before* Org attempts to resolve the
8441 link by doing text searches in the current buffer - so if you want a
8442 link \"[[target]]\" to still find \"<<target>>\", your function should
8443 handle this as a special case.
8445 When the function does handle the link, it must return a non-nil value.
8446 If it decides that it is not responsible for this link, it must return
8447 nil to indicate that that Org-mode can continue with other options
8448 like exact and fuzzy text search.")
8450 (defun org-next-link ()
8451 "Move forward to the next link.
8452 If the link is in hidden text, expose it."
8453 (interactive)
8454 (when (and org-link-search-failed (eq this-command last-command))
8455 (goto-char (point-min))
8456 (message "Link search wrapped back to beginning of buffer"))
8457 (setq org-link-search-failed nil)
8458 (let* ((pos (point))
8459 (ct (org-context))
8460 (a (assoc :link ct)))
8461 (if a (goto-char (nth 2 a)))
8462 (if (re-search-forward org-any-link-re nil t)
8463 (progn
8464 (goto-char (match-beginning 0))
8465 (if (org-invisible-p) (org-show-context)))
8466 (goto-char pos)
8467 (setq org-link-search-failed t)
8468 (error "No further link found"))))
8470 (defun org-previous-link ()
8471 "Move backward to the previous link.
8472 If the link is in hidden text, expose it."
8473 (interactive)
8474 (when (and org-link-search-failed (eq this-command last-command))
8475 (goto-char (point-max))
8476 (message "Link search wrapped back to end of buffer"))
8477 (setq org-link-search-failed nil)
8478 (let* ((pos (point))
8479 (ct (org-context))
8480 (a (assoc :link ct)))
8481 (if a (goto-char (nth 1 a)))
8482 (if (re-search-backward org-any-link-re nil t)
8483 (progn
8484 (goto-char (match-beginning 0))
8485 (if (org-invisible-p) (org-show-context)))
8486 (goto-char pos)
8487 (setq org-link-search-failed t)
8488 (error "No further link found"))))
8490 (defun org-translate-link (s)
8491 "Translate a link string if a translation function has been defined."
8492 (if (and org-link-translation-function
8493 (fboundp org-link-translation-function)
8494 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8495 (progn
8496 (setq s (funcall org-link-translation-function
8497 (match-string 1) (match-string 2)))
8498 (concat (car s) ":" (cdr s)))
8501 (defun org-translate-link-from-planner (type path)
8502 "Translate a link from Emacs Planner syntax so that Org can follow it.
8503 This is still an experimental function, your mileage may vary."
8504 (cond
8505 ((member type '("http" "https" "news" "ftp"))
8506 ;; standard Internet links are the same.
8507 nil)
8508 ((and (equal type "irc") (string-match "^//" path))
8509 ;; Planner has two / at the beginning of an irc link, we have 1.
8510 ;; We should have zero, actually....
8511 (setq path (substring path 1)))
8512 ((and (equal type "lisp") (string-match "^/" path))
8513 ;; Planner has a slash, we do not.
8514 (setq type "elisp" path (substring path 1)))
8515 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8516 ;; A typical message link. Planner has the id after the final slash,
8517 ;; we separate it with a hash mark
8518 (setq path (concat (match-string 1 path) "#"
8519 (org-remove-angle-brackets (match-string 2 path)))))
8521 (cons type path))
8523 (defun org-find-file-at-mouse (ev)
8524 "Open file link or URL at mouse."
8525 (interactive "e")
8526 (mouse-set-point ev)
8527 (org-open-at-point 'in-emacs))
8529 (defun org-open-at-mouse (ev)
8530 "Open file link or URL at mouse."
8531 (interactive "e")
8532 (mouse-set-point ev)
8533 (if (eq major-mode 'org-agenda-mode)
8534 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8535 (org-open-at-point))
8537 (defvar org-window-config-before-follow-link nil
8538 "The window configuration before following a link.
8539 This is saved in case the need arises to restore it.")
8541 (defvar org-open-link-marker (make-marker)
8542 "Marker pointing to the location where `org-open-at-point; was called.")
8544 ;;;###autoload
8545 (defun org-open-at-point-global ()
8546 "Follow a link like Org-mode does.
8547 This command can be called in any mode to follow a link that has
8548 Org-mode syntax."
8549 (interactive)
8550 (org-run-like-in-org-mode 'org-open-at-point))
8552 ;;;###autoload
8553 (defun org-open-link-from-string (s &optional arg reference-buffer)
8554 "Open a link in the string S, as if it was in Org-mode."
8555 (interactive "sLink: \nP")
8556 (let ((reference-buffer (or reference-buffer (current-buffer))))
8557 (with-temp-buffer
8558 (let ((org-inhibit-startup t))
8559 (org-mode)
8560 (insert s)
8561 (goto-char (point-min))
8562 (when reference-buffer
8563 (setq org-link-abbrev-alist-local
8564 (with-current-buffer reference-buffer
8565 org-link-abbrev-alist-local)))
8566 (org-open-at-point arg reference-buffer)))))
8568 (defun org-open-at-point (&optional in-emacs reference-buffer)
8569 "Open link at or after point.
8570 If there is no link at point, this function will search forward up to
8571 the end of the current line.
8572 Normally, files will be opened by an appropriate application. If the
8573 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8574 With a double prefix argument, try to open outside of Emacs, in the
8575 application the system uses for this file type."
8576 (interactive "P")
8577 (org-load-modules-maybe)
8578 (move-marker org-open-link-marker (point))
8579 (setq org-window-config-before-follow-link (current-window-configuration))
8580 (org-remove-occur-highlights nil nil t)
8581 (cond
8582 ((and (org-on-heading-p)
8583 (not (org-in-regexp
8584 (concat org-plain-link-re "\\|"
8585 org-bracket-link-regexp "\\|"
8586 org-angle-link-re "\\|"
8587 "[ \t]:[^ \t\n]+:[ \t]*$")))
8588 (not (get-text-property (point) 'org-linked-text)))
8589 (or (org-offer-links-in-entry in-emacs)
8590 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8591 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8592 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8593 (org-footnote-action))
8595 (let (type path link line search (pos (point)))
8596 (catch 'match
8597 (save-excursion
8598 (skip-chars-forward "^]\n\r")
8599 (when (org-in-regexp org-bracket-link-regexp 1)
8600 (setq link (org-extract-attributes
8601 (org-link-unescape (org-match-string-no-properties 1))))
8602 (while (string-match " *\n *" link)
8603 (setq link (replace-match " " t t link)))
8604 (setq link (org-link-expand-abbrev link))
8605 (cond
8606 ((or (file-name-absolute-p link)
8607 (string-match "^\\.\\.?/" link))
8608 (setq type "file" path link))
8609 ((string-match org-link-re-with-space3 link)
8610 (setq type (match-string 1 link) path (match-string 2 link)))
8611 (t (setq type "thisfile" path link)))
8612 (throw 'match t)))
8614 (when (get-text-property (point) 'org-linked-text)
8615 (setq type "thisfile"
8616 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8617 (1+ (point)) (point))
8618 path (buffer-substring
8619 (previous-single-property-change pos 'org-linked-text)
8620 (next-single-property-change pos 'org-linked-text)))
8621 (throw 'match t))
8623 (save-excursion
8624 (when (or (org-in-regexp org-angle-link-re)
8625 (org-in-regexp org-plain-link-re))
8626 (setq type (match-string 1) path (match-string 2))
8627 (throw 'match t)))
8628 (save-excursion
8629 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8630 (setq type "tags"
8631 path (match-string 1))
8632 (while (string-match ":" path)
8633 (setq path (replace-match "+" t t path)))
8634 (throw 'match t)))
8635 (when (org-in-regexp "<\\([^><\n]+\\)>")
8636 (setq type "tree-match"
8637 path (match-string 1))
8638 (throw 'match t)))
8639 (unless path
8640 (error "No link found"))
8642 ;; switch back to reference buffer
8643 ;; needed when if called in a temporary buffer through
8644 ;; org-open-link-from-string
8645 (with-current-buffer (or reference-buffer (current-buffer))
8647 ;; Remove any trailing spaces in path
8648 (if (string-match " +\\'" path)
8649 (setq path (replace-match "" t t path)))
8650 (if (and org-link-translation-function
8651 (fboundp org-link-translation-function))
8652 ;; Check if we need to translate the link
8653 (let ((tmp (funcall org-link-translation-function type path)))
8654 (setq type (car tmp) path (cdr tmp))))
8656 (cond
8658 ((assoc type org-link-protocols)
8659 (funcall (nth 1 (assoc type org-link-protocols)) path))
8661 ((equal type "mailto")
8662 (let ((cmd (car org-link-mailto-program))
8663 (args (cdr org-link-mailto-program)) args1
8664 (address path) (subject "") a)
8665 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8666 (setq address (match-string 1 path)
8667 subject (org-link-escape (match-string 2 path))))
8668 (while args
8669 (cond
8670 ((not (stringp (car args))) (push (pop args) args1))
8671 (t (setq a (pop args))
8672 (if (string-match "%a" a)
8673 (setq a (replace-match address t t a)))
8674 (if (string-match "%s" a)
8675 (setq a (replace-match subject t t a)))
8676 (push a args1))))
8677 (apply cmd (nreverse args1))))
8679 ((member type '("http" "https" "ftp" "news"))
8680 (browse-url (concat type ":" (org-link-escape
8681 path org-link-escape-chars-browser))))
8683 ((member type '("message"))
8684 (browse-url (concat type ":" path)))
8686 ((string= type "tags")
8687 (org-tags-view in-emacs path))
8689 ((string= type "tree-match")
8690 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8692 ((string= type "file")
8693 (if (string-match "::\\([0-9]+\\)\\'" path)
8694 (setq line (string-to-number (match-string 1 path))
8695 path (substring path 0 (match-beginning 0)))
8696 (if (string-match "::\\(.+\\)\\'" path)
8697 (setq search (match-string 1 path)
8698 path (substring path 0 (match-beginning 0)))))
8699 (if (string-match "[*?{]" (file-name-nondirectory path))
8700 (dired path)
8701 (org-open-file path in-emacs line search)))
8703 ((string= type "news")
8704 (require 'org-gnus)
8705 (org-gnus-follow-link path))
8707 ((string= type "shell")
8708 (let ((cmd path))
8709 (if (or (not org-confirm-shell-link-function)
8710 (funcall org-confirm-shell-link-function
8711 (format "Execute \"%s\" in shell? "
8712 (org-add-props cmd nil
8713 'face 'org-warning))))
8714 (progn
8715 (message "Executing %s" cmd)
8716 (shell-command cmd))
8717 (error "Abort"))))
8719 ((string= type "elisp")
8720 (let ((cmd path))
8721 (if (or (not org-confirm-elisp-link-function)
8722 (funcall org-confirm-elisp-link-function
8723 (format "Execute \"%s\" as elisp? "
8724 (org-add-props cmd nil
8725 'face 'org-warning))))
8726 (message "%s => %s" cmd
8727 (if (equal (string-to-char cmd) ?\()
8728 (eval (read cmd))
8729 (call-interactively (read cmd))))
8730 (error "Abort"))))
8732 ((and (string= type "thisfile")
8733 (run-hook-with-args-until-success
8734 'org-open-link-functions path)))
8736 ((string= type "thisfile")
8737 (if in-emacs
8738 (switch-to-buffer-other-window
8739 (org-get-buffer-for-internal-link (current-buffer)))
8740 (org-mark-ring-push))
8741 (let ((cmd `(org-link-search
8742 ,path
8743 ,(cond ((equal in-emacs '(4)) 'occur)
8744 ((equal in-emacs '(16)) 'org-occur)
8745 (t nil))
8746 ,pos)))
8747 (condition-case nil (eval cmd)
8748 (error (progn (widen) (eval cmd))))))
8751 (browse-url-at-point)))))))
8752 (move-marker org-open-link-marker nil)
8753 (run-hook-with-args 'org-follow-link-hook))
8755 (defun org-offer-links-in-entry (&optional nth zero)
8756 "Offer links in the current entry and follow the selected link.
8757 If there is only one link, follow it immediately as well.
8758 If NTH is an integer, immediately pick the NTH link found.
8759 If ZERO is a string, check also this string for a link, and if
8760 there is one, offer it as link number zero."
8761 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8762 "\\(" org-angle-link-re "\\)\\|"
8763 "\\(" org-plain-link-re "\\)"))
8764 (cnt ?0)
8765 (in-emacs (if (integerp nth) nil nth))
8766 have-zero end links link c)
8767 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8768 (push (match-string 0 zero) links)
8769 (setq cnt (1- cnt) have-zero t))
8770 (save-excursion
8771 (org-back-to-heading t)
8772 (setq end (save-excursion (outline-next-heading) (point)))
8773 (while (re-search-forward re end t)
8774 (push (match-string 0) links))
8775 (setq links (org-uniquify (reverse links))))
8777 (cond
8778 ((null links)
8779 (message "No links"))
8780 ((equal (length links) 1)
8781 (setq link (list (car links))))
8782 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8783 (setq link (nth (if have-zero nth (1- nth)) links)))
8784 (t ; we have to select a link
8785 (save-excursion
8786 (save-window-excursion
8787 (delete-other-windows)
8788 (with-output-to-temp-buffer "*Select Link*"
8789 (mapc (lambda (l)
8790 (if (not (string-match org-bracket-link-regexp l))
8791 (princ (format "[%c] %s\n" (incf cnt)
8792 (org-remove-angle-brackets l)))
8793 (if (match-end 3)
8794 (princ (format "[%c] %s (%s)\n" (incf cnt)
8795 (match-string 3 l) (match-string 1 l)))
8796 (princ (format "[%c] %s\n" (incf cnt)
8797 (match-string 1 l))))))
8798 links))
8799 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8800 (message "Select link to open, RET to open all:")
8801 (setq c (read-char-exclusive))
8802 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8803 (when (equal c ?q) (error "Abort"))
8804 (if (equal c ?\C-m)
8805 (setq link links)
8806 (setq nth (- c ?0))
8807 (if have-zero (setq nth (1+ nth)))
8808 (unless (and (integerp nth) (>= (length links) nth))
8809 (error "Invalid link selection"))
8810 (setq link (list (nth (1- nth) links))))))
8811 (if link
8812 (let ((buf (current-buffer)))
8813 (dolist (l link)
8814 (org-open-link-from-string l in-emacs buf))
8816 nil)))
8818 ;; Add special file links that specify the way of opening
8820 (org-add-link-type "file+sys" 'org-open-file-with-system)
8821 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
8822 (defun org-open-file-with-system (path)
8823 "Open file at PATH using the system way of opeing it."
8824 (org-open-file path 'system))
8825 (defun org-open-file-with-emacs (path)
8826 "Open file at PATH in emacs."
8827 (org-open-file path 'emacs))
8828 (defun org-remove-file-link-modifiers ()
8829 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
8830 (goto-char (point-min))
8831 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
8832 (org-if-unprotected
8833 (replace-match "file:" t t))))
8834 (eval-after-load "org-exp"
8835 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
8836 'org-remove-file-link-modifiers))
8838 ;;;; Time estimates
8840 (defun org-get-effort (&optional pom)
8841 "Get the effort estimate for the current entry."
8842 (org-entry-get pom org-effort-property))
8844 ;;; File search
8846 (defvar org-create-file-search-functions nil
8847 "List of functions to construct the right search string for a file link.
8848 These functions are called in turn with point at the location to
8849 which the link should point.
8851 A function in the hook should first test if it would like to
8852 handle this file type, for example by checking the major-mode or
8853 the file extension. If it decides not to handle this file, it
8854 should just return nil to give other functions a chance. If it
8855 does handle the file, it must return the search string to be used
8856 when following the link. The search string will be part of the
8857 file link, given after a double colon, and `org-open-at-point'
8858 will automatically search for it. If special measures must be
8859 taken to make the search successful, another function should be
8860 added to the companion hook `org-execute-file-search-functions',
8861 which see.
8863 A function in this hook may also use `setq' to set the variable
8864 `description' to provide a suggestion for the descriptive text to
8865 be used for this link when it gets inserted into an Org-mode
8866 buffer with \\[org-insert-link].")
8868 (defvar org-execute-file-search-functions nil
8869 "List of functions to execute a file search triggered by a link.
8871 Functions added to this hook must accept a single argument, the
8872 search string that was part of the file link, the part after the
8873 double colon. The function must first check if it would like to
8874 handle this search, for example by checking the major-mode or the
8875 file extension. If it decides not to handle this search, it
8876 should just return nil to give other functions a chance. If it
8877 does handle the search, it must return a non-nil value to keep
8878 other functions from trying.
8880 Each function can access the current prefix argument through the
8881 variable `current-prefix-argument'. Note that a single prefix is
8882 used to force opening a link in Emacs, so it may be good to only
8883 use a numeric or double prefix to guide the search function.
8885 In case this is needed, a function in this hook can also restore
8886 the window configuration before `org-open-at-point' was called using:
8888 (set-window-configuration org-window-config-before-follow-link)")
8890 (defun org-link-search (s &optional type avoid-pos)
8891 "Search for a link search option.
8892 If S is surrounded by forward slashes, it is interpreted as a
8893 regular expression. In org-mode files, this will create an `org-occur'
8894 sparse tree. In ordinary files, `occur' will be used to list matches.
8895 If the current buffer is in `dired-mode', grep will be used to search
8896 in all files. If AVOID-POS is given, ignore matches near that position."
8897 (let ((case-fold-search t)
8898 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8899 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8900 (append '(("") (" ") ("\t") ("\n"))
8901 org-emphasis-alist)
8902 "\\|") "\\)"))
8903 (pos (point))
8904 (pre nil) (post nil)
8905 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8906 (cond
8907 ;; First check if there are any special
8908 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8909 ;; Now try the builtin stuff
8910 ((and (equal (string-to-char s0) ?#)
8911 (> (length s0) 1)
8912 (save-excursion
8913 (goto-char (point-min))
8914 (and
8915 (re-search-forward
8916 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8917 (setq type 'dedicated
8918 pos (match-beginning 0))))
8919 ;; There is an exact target for this
8920 (goto-char pos)
8921 (org-back-to-heading t)))
8922 ((save-excursion
8923 (goto-char (point-min))
8924 (and
8925 (re-search-forward
8926 (concat "<<" (regexp-quote s0) ">>") nil t)
8927 (setq type 'dedicated
8928 pos (match-beginning 0))))
8929 ;; There is an exact target for this
8930 (goto-char pos))
8931 ((and (string-match "^(\\(.*\\))$" s0)
8932 (save-excursion
8933 (goto-char (point-min))
8934 (and
8935 (re-search-forward
8936 (concat "[^[]" (regexp-quote
8937 (format org-coderef-label-format
8938 (match-string 1 s0))))
8939 nil t)
8940 (setq type 'dedicated
8941 pos (1+ (match-beginning 0))))))
8942 ;; There is a coderef target for this
8943 (goto-char pos))
8944 ((string-match "^/\\(.*\\)/$" s)
8945 ;; A regular expression
8946 (cond
8947 ((org-mode-p)
8948 (org-occur (match-string 1 s)))
8949 ;;((eq major-mode 'dired-mode)
8950 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8951 (t (org-do-occur (match-string 1 s)))))
8953 ;; A normal search strings
8954 (when (equal (string-to-char s) ?*)
8955 ;; Anchor on headlines, post may include tags.
8956 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8957 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8958 s (substring s 1)))
8959 (remove-text-properties
8960 0 (length s)
8961 '(face nil mouse-face nil keymap nil fontified nil) s)
8962 ;; Make a series of regular expressions to find a match
8963 (setq words (org-split-string s "[ \n\r\t]+")
8965 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8966 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8967 "\\)" markers)
8968 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8969 re2a (concat "[ \t\r\n]" re2a_)
8970 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8971 re4 (concat "[^a-zA-Z_]" re4_)
8973 re1 (concat pre re2 post)
8974 re3 (concat pre (if pre re4_ re4) post)
8975 re5 (concat pre ".*" re4)
8976 re2 (concat pre re2)
8977 re2a (concat pre (if pre re2a_ re2a))
8978 re4 (concat pre (if pre re4_ re4))
8979 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8980 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8981 re5 "\\)"
8983 (cond
8984 ((eq type 'org-occur) (org-occur reall))
8985 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8986 (t (goto-char (point-min))
8987 (setq type 'fuzzy)
8988 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8989 (org-search-not-self 1 re1 nil t)
8990 (org-search-not-self 1 re2 nil t)
8991 (org-search-not-self 1 re2a nil t)
8992 (org-search-not-self 1 re3 nil t)
8993 (org-search-not-self 1 re4 nil t)
8994 (org-search-not-self 1 re5 nil t)
8996 (goto-char (match-beginning 1))
8997 (goto-char pos)
8998 (error "No match")))))
9000 ;; Normal string-search
9001 (goto-char (point-min))
9002 (if (search-forward s nil t)
9003 (goto-char (match-beginning 0))
9004 (error "No match"))))
9005 (and (org-mode-p) (org-show-context 'link-search))
9006 type))
9008 (defun org-search-not-self (group &rest args)
9009 "Execute `re-search-forward', but only accept matches that do not
9010 enclose the position of `org-open-link-marker'."
9011 (let ((m org-open-link-marker))
9012 (catch 'exit
9013 (while (apply 're-search-forward args)
9014 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9015 (goto-char (match-end group))
9016 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9017 (> (match-beginning 0) (marker-position m))
9018 (< (match-end 0) (marker-position m)))
9019 (save-match-data
9020 (or (not (org-in-regexp
9021 org-bracket-link-analytic-regexp 1))
9022 (not (match-end 4)) ; no description
9023 (and (<= (match-beginning 4) (point))
9024 (>= (match-end 4) (point))))))
9025 (throw 'exit (point))))))))
9027 (defun org-get-buffer-for-internal-link (buffer)
9028 "Return a buffer to be used for displaying the link target of internal links."
9029 (cond
9030 ((not org-display-internal-link-with-indirect-buffer)
9031 buffer)
9032 ((string-match "(Clone)$" (buffer-name buffer))
9033 (message "Buffer is already a clone, not making another one")
9034 ;; we also do not modify visibility in this case
9035 buffer)
9036 (t ; make a new indirect buffer for displaying the link
9037 (let* ((bn (buffer-name buffer))
9038 (ibn (concat bn "(Clone)"))
9039 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9040 (with-current-buffer ib (org-overview))
9041 ib))))
9043 (defun org-do-occur (regexp &optional cleanup)
9044 "Call the Emacs command `occur'.
9045 If CLEANUP is non-nil, remove the printout of the regular expression
9046 in the *Occur* buffer. This is useful if the regex is long and not useful
9047 to read."
9048 (occur regexp)
9049 (when cleanup
9050 (let ((cwin (selected-window)) win beg end)
9051 (when (setq win (get-buffer-window "*Occur*"))
9052 (select-window win))
9053 (goto-char (point-min))
9054 (when (re-search-forward "match[a-z]+" nil t)
9055 (setq beg (match-end 0))
9056 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9057 (setq end (1- (match-beginning 0)))))
9058 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9059 (goto-char (point-min))
9060 (select-window cwin))))
9062 ;;; The mark ring for links jumps
9064 (defvar org-mark-ring nil
9065 "Mark ring for positions before jumps in Org-mode.")
9066 (defvar org-mark-ring-last-goto nil
9067 "Last position in the mark ring used to go back.")
9068 ;; Fill and close the ring
9069 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9070 (loop for i from 1 to org-mark-ring-length do
9071 (push (make-marker) org-mark-ring))
9072 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9073 org-mark-ring)
9075 (defun org-mark-ring-push (&optional pos buffer)
9076 "Put the current position or POS into the mark ring and rotate it."
9077 (interactive)
9078 (setq pos (or pos (point)))
9079 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9080 (move-marker (car org-mark-ring)
9081 (or pos (point))
9082 (or buffer (current-buffer)))
9083 (message "%s"
9084 (substitute-command-keys
9085 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9087 (defun org-mark-ring-goto (&optional n)
9088 "Jump to the previous position in the mark ring.
9089 With prefix arg N, jump back that many stored positions. When
9090 called several times in succession, walk through the entire ring.
9091 Org-mode commands jumping to a different position in the current file,
9092 or to another Org-mode file, automatically push the old position
9093 onto the ring."
9094 (interactive "p")
9095 (let (p m)
9096 (if (eq last-command this-command)
9097 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9098 (setq p org-mark-ring))
9099 (setq org-mark-ring-last-goto p)
9100 (setq m (car p))
9101 (switch-to-buffer (marker-buffer m))
9102 (goto-char m)
9103 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9105 (defun org-remove-angle-brackets (s)
9106 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9107 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9109 (defun org-add-angle-brackets (s)
9110 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9111 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9113 (defun org-remove-double-quotes (s)
9114 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9115 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9118 ;;; Following specific links
9120 (defun org-follow-timestamp-link ()
9121 (cond
9122 ((org-at-date-range-p t)
9123 (let ((org-agenda-start-on-weekday)
9124 (t1 (match-string 1))
9125 (t2 (match-string 2)))
9126 (setq t1 (time-to-days (org-time-string-to-time t1))
9127 t2 (time-to-days (org-time-string-to-time t2)))
9128 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9129 ((org-at-timestamp-p t)
9130 (org-agenda-list nil (time-to-days (org-time-string-to-time
9131 (substring (match-string 1) 0 10)))
9133 (t (error "This should not happen"))))
9136 ;;; Following file links
9137 (defvar org-wait nil)
9138 (defun org-open-file (path &optional in-emacs line search)
9139 "Open the file at PATH.
9140 First, this expands any special file name abbreviations. Then the
9141 configuration variable `org-file-apps' is checked if it contains an
9142 entry for this file type, and if yes, the corresponding command is launched.
9144 If no application is found, Emacs simply visits the file.
9146 With optional prefix argument IN-EMACS, Emacs will visit the file.
9147 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
9148 and to use an external application to visit the file.
9150 Optional LINE specifies a line to go to, optional SEARCH a string
9151 to search for. If LINE or SEARCH is given, the file will be
9152 opened in Emacs, unless an entry from org-file-apps that makes
9153 use of groups in a regexp matches.
9154 If the file does not exist, an error is thrown."
9155 (let* ((file (if (equal path "")
9156 buffer-file-name
9157 (substitute-in-file-name (expand-file-name path))))
9158 (file-apps (append org-file-apps (org-default-apps)))
9159 (apps (org-remove-if
9160 'org-file-apps-entry-match-against-dlink-p file-apps))
9161 (apps-dlink (org-remove-if-not
9162 'org-file-apps-entry-match-against-dlink-p file-apps))
9163 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9164 (dirp (if remp nil (file-directory-p file)))
9165 (file (if (and dirp org-open-directory-means-index-dot-org)
9166 (concat (file-name-as-directory file) "index.org")
9167 file))
9168 (a-m-a-p (assq 'auto-mode apps))
9169 (dfile (downcase file))
9170 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9171 (link (cond ((and (eq line nil)
9172 (eq search nil))
9173 file)
9174 (line
9175 (concat file "::" (number-to-string line)))
9176 (search
9177 (concat file "::" search))))
9178 (dlink (downcase link))
9179 (old-buffer (current-buffer))
9180 (old-pos (point))
9181 (old-mode major-mode)
9182 ext cmd link-match-data)
9183 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9184 (setq ext (match-string 1 dfile))
9185 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9186 (setq ext (match-string 1 dfile))))
9187 (cond
9188 ((member in-emacs '((16) system))
9189 (setq cmd (cdr (assoc 'system apps))))
9190 (in-emacs (setq cmd 'emacs))
9192 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9193 (and dirp (cdr (assoc 'directory apps)))
9194 ; first, try matching against apps-dlink
9195 ; if we get a match here, store the match data for later
9196 (let ((match (assoc-default dlink apps-dlink
9197 'string-match)))
9198 (if match
9199 (progn (setq link-match-data (match-data))
9200 match)
9201 (progn (setq in-emacs (or in-emacs line search))
9202 nil))) ; if we have no match in apps-dlink,
9203 ; always open the file in emacs if line or search
9204 ; is given (for backwards compatibility)
9205 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9206 'string-match)
9207 (cdr (assoc ext apps))
9208 (cdr (assoc t apps))))))
9209 (when (eq cmd 'system)
9210 (setq cmd (cdr (assoc 'system apps))))
9211 (when (eq cmd 'default)
9212 (setq cmd (cdr (assoc t apps))))
9213 (when (eq cmd 'mailcap)
9214 (require 'mailcap)
9215 (mailcap-parse-mailcaps)
9216 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9217 (command (mailcap-mime-info mime-type)))
9218 (if (stringp command)
9219 (setq cmd command)
9220 (setq cmd 'emacs))))
9221 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9222 (not (file-exists-p file))
9223 (not org-open-non-existing-files))
9224 (error "No such file: %s" file))
9225 (cond
9226 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9227 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9228 (while (string-match "['\"]%s['\"]" cmd)
9229 (setq cmd (replace-match "%s" t t cmd)))
9230 (while (string-match "%s" cmd)
9231 (setq cmd (replace-match
9232 (save-match-data
9233 (shell-quote-argument
9234 (convert-standard-filename file)))
9235 t t cmd)))
9237 ;; Replace "%1", "%2" etc. in command with group matches from regex
9238 (save-match-data
9239 (let ((match-index 1)
9240 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9241 (set-match-data link-match-data)
9242 (while (<= match-index number-of-groups)
9243 (let ((regex (concat "%" (number-to-string match-index)))
9244 (replace-with (match-string match-index dlink)))
9245 (while (string-match regex cmd)
9246 (setq cmd (replace-match replace-with t t cmd))))
9247 (setq match-index (+ match-index 1)))))
9249 (save-window-excursion
9250 (start-process-shell-command cmd nil cmd)
9251 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9253 ((or (stringp cmd)
9254 (eq cmd 'emacs))
9255 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9256 (widen)
9257 (if line (org-goto-line line)
9258 (if search (org-link-search search))))
9259 ((consp cmd)
9260 (let ((file (convert-standard-filename file)))
9261 (save-match-data
9262 (set-match-data link-match-data)
9263 (eval cmd))))
9264 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9265 (and (org-mode-p) (eq old-mode 'org-mode)
9266 (or (not (equal old-buffer (current-buffer)))
9267 (not (equal old-pos (point))))
9268 (org-mark-ring-push old-pos old-buffer))))
9270 (defun org-file-apps-entry-match-against-dlink-p (entry)
9271 "This function returns non-nil if `entry' uses a regular
9272 expression which should be matched against the whole link by
9273 org-open-file.
9275 It assumes that is the case when the entry uses a regular
9276 expression which has at least one grouping construct and the
9277 action is either a lisp form or a command string containing
9278 '%1', i.e. using at least one subexpression match as a
9279 parameter."
9280 (let ((selector (car entry))
9281 (action (cdr entry)))
9282 (if (stringp selector)
9283 (and (> (regexp-opt-depth selector) 0)
9284 (or (and (stringp action)
9285 (string-match "%[0-9]" action))
9286 (consp action)))
9287 nil)))
9289 (defun org-default-apps ()
9290 "Return the default applications for this operating system."
9291 (cond
9292 ((eq system-type 'darwin)
9293 org-file-apps-defaults-macosx)
9294 ((eq system-type 'windows-nt)
9295 org-file-apps-defaults-windowsnt)
9296 (t org-file-apps-defaults-gnu)))
9298 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9299 "Convert extensions to regular expressions in the cars of LIST.
9300 Also, weed out any non-string entries, because the return value is used
9301 only for regexp matching.
9302 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9303 point to the symbol `emacs', indicating that the file should
9304 be opened in Emacs."
9305 (append
9306 (delq nil
9307 (mapcar (lambda (x)
9308 (if (not (stringp (car x)))
9310 (if (string-match "\\W" (car x))
9312 (cons (concat "\\." (car x) "\\'") (cdr x)))))
9313 list))
9314 (if add-auto-mode
9315 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9317 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9318 (defun org-file-remote-p (file)
9319 "Test whether FILE specifies a location on a remote system.
9320 Return non-nil if the location is indeed remote.
9322 For example, the filename \"/user@host:/foo\" specifies a location
9323 on the system \"/user@host:\"."
9324 (cond ((fboundp 'file-remote-p)
9325 (file-remote-p file))
9326 ((fboundp 'tramp-handle-file-remote-p)
9327 (tramp-handle-file-remote-p file))
9328 ((and (boundp 'ange-ftp-name-format)
9329 (string-match (car ange-ftp-name-format) file))
9331 (t nil)))
9334 ;;;; Refiling
9336 (defun org-get-org-file ()
9337 "Read a filename, with default directory `org-directory'."
9338 (let ((default (or org-default-notes-file remember-data-file)))
9339 (read-file-name (format "File name [%s]: " default)
9340 (file-name-as-directory org-directory)
9341 default)))
9343 (defun org-notes-order-reversed-p ()
9344 "Check if the current file should receive notes in reversed order."
9345 (cond
9346 ((not org-reverse-note-order) nil)
9347 ((eq t org-reverse-note-order) t)
9348 ((not (listp org-reverse-note-order)) nil)
9349 (t (catch 'exit
9350 (let ((all org-reverse-note-order)
9351 entry)
9352 (while (setq entry (pop all))
9353 (if (string-match (car entry) buffer-file-name)
9354 (throw 'exit (cdr entry))))
9355 nil)))))
9357 (defvar org-refile-target-table nil
9358 "The list of refile targets, created by `org-refile'.")
9360 (defvar org-agenda-new-buffers nil
9361 "Buffers created to visit agenda files.")
9363 (defun org-get-refile-targets (&optional default-buffer)
9364 "Produce a table with refile targets."
9365 (let ((case-fold-search nil)
9366 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9367 (entries (or org-refile-targets '((nil . (:level . 1)))))
9368 targets txt re files f desc descre fast-path-p level pos0)
9369 (message "Getting targets...")
9370 (with-current-buffer (or default-buffer (current-buffer))
9371 (while (setq entry (pop entries))
9372 (setq files (car entry) desc (cdr entry))
9373 (setq fast-path-p nil)
9374 (cond
9375 ((null files) (setq files (list (current-buffer))))
9376 ((eq files 'org-agenda-files)
9377 (setq files (org-agenda-files 'unrestricted)))
9378 ((and (symbolp files) (fboundp files))
9379 (setq files (funcall files)))
9380 ((and (symbolp files) (boundp files))
9381 (setq files (symbol-value files))))
9382 (if (stringp files) (setq files (list files)))
9383 (cond
9384 ((eq (car desc) :tag)
9385 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9386 ((eq (car desc) :todo)
9387 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9388 ((eq (car desc) :regexp)
9389 (setq descre (cdr desc)))
9390 ((eq (car desc) :level)
9391 (setq descre (concat "^\\*\\{" (number-to-string
9392 (if org-odd-levels-only
9393 (1- (* 2 (cdr desc)))
9394 (cdr desc)))
9395 "\\}[ \t]")))
9396 ((eq (car desc) :maxlevel)
9397 (setq fast-path-p t)
9398 (setq descre (concat "^\\*\\{1," (number-to-string
9399 (if org-odd-levels-only
9400 (1- (* 2 (cdr desc)))
9401 (cdr desc)))
9402 "\\}[ \t]")))
9403 (t (error "Bad refiling target description %s" desc)))
9404 (while (setq f (pop files))
9405 (with-current-buffer
9406 (if (bufferp f) f (org-get-agenda-file-buffer f))
9407 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
9408 (setq f (and f (expand-file-name f)))
9409 (if (eq org-refile-use-outline-path 'file)
9410 (push (list (file-name-nondirectory f) f nil nil) targets))
9411 (save-excursion
9412 (save-restriction
9413 (widen)
9414 (goto-char (point-min))
9415 (while (re-search-forward descre nil t)
9416 (goto-char (setq pos0 (point-at-bol)))
9417 (catch 'next
9418 (when org-refile-target-verify-function
9419 (save-match-data
9420 (or (funcall org-refile-target-verify-function)
9421 (throw 'next t))))
9422 (when (looking-at org-complex-heading-regexp)
9423 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
9424 txt (org-link-display-format (match-string 4))
9425 re (concat "^" (regexp-quote
9426 (buffer-substring (match-beginning 1)
9427 (match-end 4)))))
9428 (if (match-end 5) (setq re (concat re "[ \t]+"
9429 (regexp-quote
9430 (match-string 5)))))
9431 (setq re (concat re "[ \t]*$"))
9432 (when org-refile-use-outline-path
9433 (setq txt (mapconcat 'org-protect-slash
9434 (append
9435 (if (eq org-refile-use-outline-path 'file)
9436 (list (file-name-nondirectory
9437 (buffer-file-name (buffer-base-buffer))))
9438 (if (eq org-refile-use-outline-path 'full-file-path)
9439 (list (buffer-file-name (buffer-base-buffer)))))
9440 (org-get-outline-path fast-path-p level txt)
9441 (list txt))
9442 "/")))
9443 (push (list txt f re (point)) targets)))
9444 (when (= (point) pos0)
9445 ;; verification function has not moved point
9446 (goto-char (point-at-eol))))))))))
9447 (message "Getting targets...done")
9448 (nreverse targets)))
9450 (defun org-protect-slash (s)
9451 (while (string-match "/" s)
9452 (setq s (replace-match "\\" t t s)))
9455 (defvar org-olpa (make-vector 20 nil))
9457 (defun org-get-outline-path (&optional fastp level heading)
9458 "Return the outline path to the current entry, as a list.
9459 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9460 routine which makes outline path derivations for an entire file,
9461 avoiding backtracing."
9462 (if fastp
9463 (progn
9464 (if (> level 19)
9465 (error "Outline path failure, more than 19 levels."))
9466 (loop for i from level upto 19 do
9467 (aset org-olpa i nil))
9468 (prog1
9469 (delq nil (append org-olpa nil))
9470 (aset org-olpa level heading)))
9471 (let (rtn case-fold-search)
9472 (save-excursion
9473 (save-restriction
9474 (widen)
9475 (while (org-up-heading-safe)
9476 (when (looking-at org-complex-heading-regexp)
9477 (push (org-match-string-no-properties 4) rtn)))
9478 rtn)))))
9480 (defun org-format-outline-path (path &optional width prefix)
9481 "Format the outlie path PATH for display.
9482 Width is the maximum number of characters that is available.
9483 Prefix is a prefix to be included in the returned string,
9484 such as the file name."
9485 (setq width (or width 79))
9486 (if prefix (setq width (- width (length prefix))))
9487 (if (not path)
9488 (or prefix "")
9489 (let* ((nsteps (length path))
9490 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9491 (maxwidth (if (<= total-width width)
9492 10000 ;; everything fits
9493 ;; we need to shorten the level headings
9494 (/ (- width nsteps) nsteps)))
9495 (org-odd-levels-only nil)
9496 (n 0)
9497 (total (1+ (length prefix))))
9498 (setq maxwidth (max maxwidth 10))
9499 (concat prefix
9500 (mapconcat
9501 (lambda (h)
9502 (setq n (1+ n))
9503 (if (and (= n nsteps) (< maxwidth 10000))
9504 (setq maxwidth (- total-width total)))
9505 (if (< (length h) maxwidth)
9506 (progn (setq total (+ total (length h) 1)) h)
9507 (setq h (substring h 0 (- maxwidth 2))
9508 total (+ total maxwidth 1))
9509 (if (string-match "[ \t]+\\'" h)
9510 (setq h (substring h 0 (match-beginning 0))))
9511 (setq h (concat h "..")))
9512 (org-add-props h nil 'face
9513 (nth (% (1- n) org-n-level-faces)
9514 org-level-faces))
9516 path "/")))))
9518 (defun org-display-outline-path (&optional file current)
9519 "Display the current outline path in the echo area."
9520 (interactive "P")
9521 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
9522 (case-fold-search nil)
9523 (path (and (org-mode-p) (org-get-outline-path))))
9524 (if current (setq path (append path
9525 (save-excursion
9526 (org-back-to-heading t)
9527 (if (looking-at org-complex-heading-regexp)
9528 (list (match-string 4)))))))
9529 (message "%s"
9530 (org-format-outline-path
9531 path
9532 (1- (frame-width))
9533 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9535 (defvar org-refile-history nil
9536 "History for refiling operations.")
9538 (defvar org-after-refile-insert-hook nil
9539 "Hook run after `org-refile' has inserted its stuff at the new location.
9540 Note that this is still *before* the stuff will be removed from
9541 the *old* location.")
9543 (defun org-refile (&optional goto default-buffer rfloc)
9544 "Move the entry at point to another heading.
9545 The list of target headings is compiled using the information in
9546 `org-refile-targets', which see. This list is created before each use
9547 and will therefore always be up-to-date.
9549 At the target location, the entry is filed as a subitem of the target heading.
9550 Depending on `org-reverse-note-order', the new subitem will either be the
9551 first or the last subitem.
9553 If there is an active region, all entries in that region will be moved.
9554 However, the region must fulfil the requirement that the first heading
9555 is the first one sets the top-level of the moved text - at most siblings
9556 below it are allowed.
9558 With prefix arg GOTO, the command will only visit the target location,
9559 not actually move anything.
9560 With a double prefix `C-u C-u', go to the location where the last refiling
9561 operation has put the subtree.
9562 With a prefix argument of `2', refile to the running clock.
9564 RFLOC can be a refile location obtained in a different way.
9566 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9567 (interactive "P")
9568 (let* ((cbuf (current-buffer))
9569 (regionp (org-region-active-p))
9570 (region-start (and regionp (region-beginning)))
9571 (region-end (and regionp (region-end)))
9572 (region-length (and regionp (- region-end region-start)))
9573 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9574 pos it nbuf file re level reversed)
9575 (setq last-command nil)
9576 (when regionp
9577 (goto-char region-start)
9578 (or (bolp) (goto-char (point-at-bol)))
9579 (setq region-start (point))
9580 (unless (org-kill-is-subtree-p
9581 (buffer-substring region-start region-end))
9582 (error "The region is not a (sequence of) subtree(s)")))
9583 (if (equal goto '(16))
9584 (org-refile-goto-last-stored)
9585 (when (or
9586 (and (equal goto 2)
9587 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9588 (prog1
9589 (setq it (list (or org-clock-heading "running clock")
9590 (buffer-file-name
9591 (marker-buffer org-clock-hd-marker))
9593 (marker-position org-clock-hd-marker)))
9594 (setq goto nil)))
9595 (setq it (or rfloc
9596 (save-excursion
9597 (org-refile-get-location
9598 (if goto "Goto: " "Refile to: ") default-buffer
9599 org-refile-allow-creating-parent-nodes)))))
9600 (setq file (nth 1 it)
9601 re (nth 2 it)
9602 pos (nth 3 it))
9603 (if (and (not goto)
9605 (equal (buffer-file-name) file)
9606 (if regionp
9607 (and (>= pos region-start)
9608 (<= pos region-end))
9609 (and (>= pos (point))
9610 (< pos (save-excursion
9611 (org-end-of-subtree t t))))))
9612 (error "Cannot refile to position inside the tree or region"))
9614 (setq nbuf (or (find-buffer-visiting file)
9615 (find-file-noselect file)))
9616 (if goto
9617 (progn
9618 (switch-to-buffer nbuf)
9619 (goto-char pos)
9620 (org-show-context 'org-goto))
9621 (if regionp
9622 (progn
9623 (org-kill-new (buffer-substring region-start region-end))
9624 (org-save-markers-in-region region-start region-end))
9625 (org-copy-subtree 1 nil t))
9626 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9627 (find-file-noselect file)))
9628 (setq reversed (org-notes-order-reversed-p))
9629 (save-excursion
9630 (save-restriction
9631 (widen)
9632 (if pos
9633 (progn
9634 (goto-char pos)
9635 (looking-at outline-regexp)
9636 (setq level (org-get-valid-level (funcall outline-level) 1))
9637 (goto-char
9638 (if reversed
9639 (or (outline-next-heading) (point-max))
9640 (or (save-excursion (org-get-next-sibling))
9641 (org-end-of-subtree t t)
9642 (point-max)))))
9643 (setq level 1)
9644 (if (not reversed)
9645 (goto-char (point-max))
9646 (goto-char (point-min))
9647 (or (outline-next-heading) (goto-char (point-max)))))
9648 (if (not (bolp)) (newline))
9649 (org-paste-subtree level)
9650 (when org-log-refile
9651 (org-add-log-setup 'refile nil nil 'findpos
9652 org-log-refile)
9653 (unless (eq org-log-refile 'note)
9654 (save-excursion (org-add-log-note))))
9655 (and org-auto-align-tags (org-set-tags nil t))
9656 (bookmark-set "org-refile-last-stored")
9657 (if (fboundp 'deactivate-mark) (deactivate-mark))
9658 (run-hooks 'org-after-refile-insert-hook))))
9659 (if regionp
9660 (delete-region (point) (+ (point) region-length))
9661 (org-cut-subtree))
9662 (when (featurep 'org-inlinetask)
9663 (org-inlinetask-remove-END-maybe))
9664 (setq org-markers-to-move nil)
9665 (message "Refiled to \"%s\"" (car it)))))))
9667 (defun org-refile-goto-last-stored ()
9668 "Go to the location where the last refile was stored."
9669 (interactive)
9670 (bookmark-jump "org-refile-last-stored")
9671 (message "This is the location of the last refile"))
9673 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9674 "Prompt the user for a refile location, using PROMPT."
9675 (let ((org-refile-targets org-refile-targets)
9676 (org-refile-use-outline-path org-refile-use-outline-path))
9677 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9678 (unless org-refile-target-table
9679 (error "No refile targets"))
9680 (let* ((cbuf (current-buffer))
9681 (partial-completion-mode nil)
9682 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9683 (cfunc (if (and org-refile-use-outline-path
9684 org-outline-path-complete-in-steps)
9685 'org-olpath-completing-read
9686 'org-icompleting-read))
9687 (extra (if org-refile-use-outline-path "/" ""))
9688 (filename (and cfn (expand-file-name cfn)))
9689 (tbl (mapcar
9690 (lambda (x)
9691 (if (and (not (member org-refile-use-outline-path
9692 '(file full-file-path)))
9693 (not (equal filename (nth 1 x))))
9694 (cons (concat (car x) extra " ("
9695 (file-name-nondirectory (nth 1 x)) ")")
9696 (cdr x))
9697 (cons (concat (car x) extra) (cdr x))))
9698 org-refile-target-table))
9699 (completion-ignore-case t)
9700 pa answ parent-target child parent old-hist)
9701 (setq old-hist org-refile-history)
9702 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9703 nil 'org-refile-history))
9704 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9705 (if pa
9706 (progn
9707 (when (or (not org-refile-history)
9708 (not (eq old-hist org-refile-history))
9709 (not (equal (car pa) (car org-refile-history))))
9710 (setq org-refile-history
9711 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9712 org-refile-history
9713 (cdr org-refile-history))))
9714 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9715 (pop org-refile-history)))
9717 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9718 (progn
9719 (setq parent (match-string 1 answ)
9720 child (match-string 2 answ))
9721 (setq parent-target (or (assoc parent tbl)
9722 (assoc (concat parent "/") tbl)))
9723 (when (and parent-target
9724 (or (eq new-nodes t)
9725 (and (eq new-nodes 'confirm)
9726 (y-or-n-p (format "Create new node \"%s\"? "
9727 child)))))
9728 (org-refile-new-child parent-target child)))
9729 (error "Invalid target location")))))
9731 (defun org-refile-new-child (parent-target child)
9732 "Use refile target PARENT-TARGET to add new CHILD below it."
9733 (unless parent-target
9734 (error "Cannot find parent for new node"))
9735 (let ((file (nth 1 parent-target))
9736 (pos (nth 3 parent-target))
9737 level)
9738 (with-current-buffer (or (find-buffer-visiting file)
9739 (find-file-noselect file))
9740 (save-excursion
9741 (save-restriction
9742 (widen)
9743 (if pos
9744 (goto-char pos)
9745 (goto-char (point-max))
9746 (if (not (bolp)) (newline)))
9747 (when (looking-at outline-regexp)
9748 (setq level (funcall outline-level))
9749 (org-end-of-subtree t t))
9750 (org-back-over-empty-lines)
9751 (insert "\n" (make-string
9752 (if pos (org-get-valid-level level 1) 1) ?*)
9753 " " child "\n")
9754 (beginning-of-line 0)
9755 (list (concat (car parent-target) "/" child) file "" (point)))))))
9757 (defun org-olpath-completing-read (prompt collection &rest args)
9758 "Read an outline path like a file name."
9759 (let ((thetable collection)
9760 (org-completion-use-ido nil) ; does not work with ido.
9761 (org-completion-use-iswitchb nil)) ; or iswitchb
9762 (apply
9763 'org-icompleting-read prompt
9764 (lambda (string predicate &optional flag)
9765 (let (rtn r f (l (length string)))
9766 (cond
9767 ((eq flag nil)
9768 ;; try completion
9769 (try-completion string thetable))
9770 ((eq flag t)
9771 ;; all-completions
9772 (setq rtn (all-completions string thetable predicate))
9773 (mapcar
9774 (lambda (x)
9775 (setq r (substring x l))
9776 (if (string-match " ([^)]*)$" x)
9777 (setq f (match-string 0 x))
9778 (setq f ""))
9779 (if (string-match "/" r)
9780 (concat string (substring r 0 (match-end 0)) f)
9782 rtn))
9783 ((eq flag 'lambda)
9784 ;; exact match?
9785 (assoc string thetable)))
9787 args)))
9789 ;;;; Dynamic blocks
9791 (defun org-find-dblock (name)
9792 "Find the first dynamic block with name NAME in the buffer.
9793 If not found, stay at current position and return nil."
9794 (let (pos)
9795 (save-excursion
9796 (goto-char (point-min))
9797 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9798 nil t)
9799 (match-beginning 0))))
9800 (if pos (goto-char pos))
9801 pos))
9803 (defconst org-dblock-start-re
9804 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9805 "Matches the start line of a dynamic block, with parameters.")
9807 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9808 "Matches the end of a dynamic block.")
9810 (defun org-create-dblock (plist)
9811 "Create a dynamic block section, with parameters taken from PLIST.
9812 PLIST must contain a :name entry which is used as name of the block."
9813 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9814 (end-of-line 1)
9815 (newline))
9816 (let ((col (current-column))
9817 (name (plist-get plist :name)))
9818 (insert "#+BEGIN: " name)
9819 (while plist
9820 (if (eq (car plist) :name)
9821 (setq plist (cddr plist))
9822 (insert " " (prin1-to-string (pop plist)))))
9823 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9824 (beginning-of-line -2)))
9826 (defun org-prepare-dblock ()
9827 "Prepare dynamic block for refresh.
9828 This empties the block, puts the cursor at the insert position and returns
9829 the property list including an extra property :name with the block name."
9830 (unless (looking-at org-dblock-start-re)
9831 (error "Not at a dynamic block"))
9832 (let* ((begdel (1+ (match-end 0)))
9833 (name (org-no-properties (match-string 1)))
9834 (params (append (list :name name)
9835 (read (concat "(" (match-string 3) ")")))))
9836 (save-excursion
9837 (beginning-of-line 1)
9838 (skip-chars-forward " \t")
9839 (setq params (plist-put params :indentation-column (current-column))))
9840 (unless (re-search-forward org-dblock-end-re nil t)
9841 (error "Dynamic block not terminated"))
9842 (setq params
9843 (append params
9844 (list :content (buffer-substring
9845 begdel (match-beginning 0)))))
9846 (delete-region begdel (match-beginning 0))
9847 (goto-char begdel)
9848 (open-line 1)
9849 params))
9851 (defun org-map-dblocks (&optional command)
9852 "Apply COMMAND to all dynamic blocks in the current buffer.
9853 If COMMAND is not given, use `org-update-dblock'."
9854 (let ((cmd (or command 'org-update-dblock)))
9855 (save-excursion
9856 (goto-char (point-min))
9857 (while (re-search-forward org-dblock-start-re nil t)
9858 (goto-char (match-beginning 0))
9859 (save-excursion
9860 (condition-case nil
9861 (funcall cmd)
9862 (error (message "Error during update of dynamic block"))))
9863 (unless (re-search-forward org-dblock-end-re nil t)
9864 (error "Dynamic block not terminated"))))))
9866 (defun org-dblock-update (&optional arg)
9867 "User command for updating dynamic blocks.
9868 Update the dynamic block at point. With prefix ARG, update all dynamic
9869 blocks in the buffer."
9870 (interactive "P")
9871 (if arg
9872 (org-update-all-dblocks)
9873 (or (looking-at org-dblock-start-re)
9874 (org-beginning-of-dblock))
9875 (org-update-dblock)))
9877 (defun org-update-dblock ()
9878 "Update the dynamic block at point
9879 This means to empty the block, parse for parameters and then call
9880 the correct writing function."
9881 (save-window-excursion
9882 (let* ((pos (point))
9883 (line (org-current-line))
9884 (params (org-prepare-dblock))
9885 (name (plist-get params :name))
9886 (indent (plist-get params :indentation-column))
9887 (cmd (intern (concat "org-dblock-write:" name))))
9888 (message "Updating dynamic block `%s' at line %d..." name line)
9889 (funcall cmd params)
9890 (message "Updating dynamic block `%s' at line %d...done" name line)
9891 (goto-char pos)
9892 (when (and indent (> indent 0))
9893 (setq indent (make-string indent ?\ ))
9894 (save-excursion
9895 (org-beginning-of-dblock)
9896 (forward-line 1)
9897 (while (not (looking-at org-dblock-end-re))
9898 (insert indent)
9899 (beginning-of-line 2))
9900 (when (looking-at org-dblock-end-re)
9901 (and (looking-at "[ \t]+")
9902 (replace-match ""))
9903 (insert indent)))))))
9905 (defun org-beginning-of-dblock ()
9906 "Find the beginning of the dynamic block at point.
9907 Error if there is no such block at point."
9908 (let ((pos (point))
9909 beg)
9910 (end-of-line 1)
9911 (if (and (re-search-backward org-dblock-start-re nil t)
9912 (setq beg (match-beginning 0))
9913 (re-search-forward org-dblock-end-re nil t)
9914 (> (match-end 0) pos))
9915 (goto-char beg)
9916 (goto-char pos)
9917 (error "Not in a dynamic block"))))
9919 (defun org-update-all-dblocks ()
9920 "Update all dynamic blocks in the buffer.
9921 This function can be used in a hook."
9922 (when (org-mode-p)
9923 (org-map-dblocks 'org-update-dblock)))
9926 ;;;; Completion
9928 (defconst org-additional-option-like-keywords
9929 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9930 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9931 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
9932 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
9933 "BEGIN:" "END:"
9934 "ORGTBL" "TBLFM:" "TBLNAME:"
9935 "BEGIN_EXAMPLE" "END_EXAMPLE"
9936 "BEGIN_QUOTE" "END_QUOTE"
9937 "BEGIN_VERSE" "END_VERSE"
9938 "BEGIN_CENTER" "END_CENTER"
9939 "BEGIN_SRC" "END_SRC"
9940 "CATEGORY" "COLUMNS"
9941 "CAPTION" "LABEL"
9942 "SETUPFILE"
9943 "BIND"
9944 "MACRO"))
9946 (defcustom org-structure-template-alist
9948 ("s" "#+begin_src ?\n\n#+end_src"
9949 "<src lang=\"?\">\n\n</src>")
9950 ("e" "#+begin_example\n?\n#+end_example"
9951 "<example>\n?\n</example>")
9952 ("q" "#+begin_quote\n?\n#+end_quote"
9953 "<quote>\n?\n</quote>")
9954 ("v" "#+begin_verse\n?\n#+end_verse"
9955 "<verse>\n?\n/verse>")
9956 ("c" "#+begin_center\n?\n#+end_center"
9957 "<center>\n?\n/center>")
9958 ("l" "#+begin_latex\n?\n#+end_latex"
9959 "<literal style=\"latex\">\n?\n</literal>")
9960 ("L" "#+latex: "
9961 "<literal style=\"latex\">?</literal>")
9962 ("h" "#+begin_html\n?\n#+end_html"
9963 "<literal style=\"html\">\n?\n</literal>")
9964 ("H" "#+html: "
9965 "<literal style=\"html\">?</literal>")
9966 ("a" "#+begin_ascii\n?\n#+end_ascii")
9967 ("A" "#+ascii: ")
9968 ("i" "#+include %file ?"
9969 "<include file=%file markup=\"?\">")
9971 "Structure completion elements.
9972 This is a list of abbreviation keys and values. The value gets inserted
9973 if you type `<' followed by the key and then press the completion key,
9974 usually `M-TAB'. %file will be replaced by a file name after prompting
9975 for the file using completion.
9976 There are two templates for each key, the first uses the original Org syntax,
9977 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9978 the default when the /org-mtags.el/ module has been loaded. See also the
9979 variable `org-mtags-prefer-muse-templates'.
9980 This is an experimental feature, it is undecided if it is going to stay in."
9981 :group 'org-completion
9982 :type '(repeat
9983 (string :tag "Key")
9984 (string :tag "Template")
9985 (string :tag "Muse Template")))
9987 (defun org-try-structure-completion ()
9988 "Try to complete a structure template before point.
9989 This looks for strings like \"<e\" on an otherwise empty line and
9990 expands them."
9991 (let ((l (buffer-substring (point-at-bol) (point)))
9993 (when (and (looking-at "[ \t]*$")
9994 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9995 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9996 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9997 (match-beginning 1)) a)
9998 t)))
10000 (defun org-complete-expand-structure-template (start cell)
10001 "Expand a structure template."
10002 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10003 (rpl (nth (if musep 2 1) cell))
10004 (ind ""))
10005 (delete-region start (point))
10006 (when (string-match "\\`#\\+" rpl)
10007 (cond
10008 ((bolp))
10009 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10010 (setq ind (buffer-substring (point-at-bol) (point))))
10011 (t (newline))))
10012 (setq start (point))
10013 (if (string-match "%file" rpl)
10014 (setq rpl (replace-match
10015 (concat
10016 "\""
10017 (save-match-data
10018 (abbreviate-file-name (read-file-name "Include file: ")))
10019 "\"")
10020 t t rpl)))
10021 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10022 (concat "\n" ind)))
10023 (insert rpl)
10024 (if (re-search-backward "\\?" start t) (delete-char 1))))
10027 (defun org-complete (&optional arg)
10028 "Perform completion on word at point.
10029 At the beginning of a headline, this completes TODO keywords as given in
10030 `org-todo-keywords'.
10031 If the current word is preceded by a backslash, completes the TeX symbols
10032 that are supported for HTML support.
10033 If the current word is preceded by \"#+\", completes special words for
10034 setting file options.
10035 In the line after \"#+STARTUP:, complete valid keywords.\"
10036 At all other locations, this simply calls the value of
10037 `org-completion-fallback-command'."
10038 (interactive "P")
10039 (org-without-partial-completion
10040 (catch 'exit
10041 (let* ((a nil)
10042 (end (point))
10043 (beg1 (save-excursion
10044 (skip-chars-backward (org-re "[:alnum:]_@"))
10045 (point)))
10046 (beg (save-excursion
10047 (skip-chars-backward "a-zA-Z0-9_:$")
10048 (point)))
10049 (confirm (lambda (x) (stringp (car x))))
10050 (searchhead (equal (char-before beg) ?*))
10051 (struct
10052 (when (and (member (char-before beg1) '(?. ?<))
10053 (setq a (assoc (buffer-substring beg1 (point))
10054 org-structure-template-alist)))
10055 (org-complete-expand-structure-template (1- beg1) a)
10056 (throw 'exit t)))
10057 (tag (and (equal (char-before beg1) ?:)
10058 (equal (char-after (point-at-bol)) ?*)))
10059 (prop (and (equal (char-before beg1) ?:)
10060 (not (equal (char-after (point-at-bol)) ?*))))
10061 (texp (equal (char-before beg) ?\\))
10062 (link (equal (char-before beg) ?\[))
10063 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
10064 beg)
10065 "#+"))
10066 (startup (string-match "^#\\+STARTUP:.*"
10067 (buffer-substring (point-at-bol) (point))))
10068 (completion-ignore-case opt)
10069 (type nil)
10070 (tbl nil)
10071 (table (cond
10072 (opt
10073 (setq type :opt)
10074 (require 'org-exp)
10075 (append
10076 (delq nil
10077 (mapcar
10078 (lambda (x)
10079 (if (string-match
10080 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
10081 (cons (match-string 2 x)
10082 (match-string 1 x))))
10083 (org-split-string (org-get-current-options) "\n")))
10084 (mapcar 'list org-additional-option-like-keywords)))
10085 (startup
10086 (setq type :startup)
10087 org-startup-options)
10088 (link (append org-link-abbrev-alist-local
10089 org-link-abbrev-alist))
10090 (texp
10091 (setq type :tex)
10092 (append org-entities-user org-entities))
10093 ((string-match "\\`\\*+[ \t]+\\'"
10094 (buffer-substring (point-at-bol) beg))
10095 (setq type :todo)
10096 (mapcar 'list org-todo-keywords-1))
10097 (searchhead
10098 (setq type :searchhead)
10099 (save-excursion
10100 (goto-char (point-min))
10101 (while (re-search-forward org-todo-line-regexp nil t)
10102 (push (list
10103 (org-make-org-heading-search-string
10104 (match-string 3) t))
10105 tbl)))
10106 tbl)
10107 (tag (setq type :tag beg beg1)
10108 (or org-tag-alist (org-get-buffer-tags)))
10109 (prop (setq type :prop beg beg1)
10110 (mapcar 'list (org-buffer-property-keys nil t t)))
10111 (t (progn
10112 (call-interactively org-completion-fallback-command)
10113 (throw 'exit nil)))))
10114 (pattern (buffer-substring-no-properties beg end))
10115 (completion (try-completion pattern table confirm)))
10116 (cond ((eq completion t)
10117 (if (not (assoc (upcase pattern) table))
10118 (message "Already complete")
10119 (if (and (equal type :opt)
10120 (not (member (car (assoc (upcase pattern) table))
10121 org-additional-option-like-keywords)))
10122 (insert (substring (cdr (assoc (upcase pattern) table))
10123 (length pattern)))
10124 (if (memq type '(:tag :prop)) (insert ":")))))
10125 ((null completion)
10126 (message "Can't find completion for \"%s\"" pattern)
10127 (ding))
10128 ((not (string= pattern completion))
10129 (delete-region beg end)
10130 (if (string-match " +$" completion)
10131 (setq completion (replace-match "" t t completion)))
10132 (insert completion)
10133 (if (get-buffer-window "*Completions*")
10134 (delete-window (get-buffer-window "*Completions*")))
10135 (if (assoc completion table)
10136 (if (eq type :todo) (insert " ")
10137 (if (memq type '(:tag :prop)) (insert ":"))))
10138 (if (and (equal type :opt) (assoc completion table))
10139 (message "%s" (substitute-command-keys
10140 "Press \\[org-complete] again to insert example settings"))))
10142 (message "Making completion list...")
10143 (let ((list (sort (all-completions pattern table confirm)
10144 'string<)))
10145 (with-output-to-temp-buffer "*Completions*"
10146 (condition-case nil
10147 ;; Protection needed for XEmacs and emacs 21
10148 (display-completion-list list pattern)
10149 (error (display-completion-list list)))))
10150 (message "Making completion list...%s" "done")))))))
10152 ;;;; TODO, DEADLINE, Comments
10154 (defun org-toggle-comment ()
10155 "Change the COMMENT state of an entry."
10156 (interactive)
10157 (save-excursion
10158 (org-back-to-heading)
10159 (let (case-fold-search)
10160 (if (looking-at (concat outline-regexp
10161 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10162 (replace-match "" t t nil 1)
10163 (if (looking-at outline-regexp)
10164 (progn
10165 (goto-char (match-end 0))
10166 (insert org-comment-string " ")))))))
10168 (defvar org-last-todo-state-is-todo nil
10169 "This is non-nil when the last TODO state change led to a TODO state.
10170 If the last change removed the TODO tag or switched to DONE, then
10171 this is nil.")
10173 (defvar org-setting-tags nil) ; dynamically skipped
10175 (defun org-parse-local-options (string var)
10176 "Parse STRING for startup setting relevant for variable VAR."
10177 (let ((rtn (symbol-value var))
10178 e opts)
10179 (save-match-data
10180 (if (or (not string) (not (string-match "\\S-" string)))
10182 (setq opts (delq nil (mapcar (lambda (x)
10183 (setq e (assoc x org-startup-options))
10184 (if (eq (nth 1 e) var) e nil))
10185 (org-split-string string "[ \t]+"))))
10186 (if (not opts)
10188 (setq rtn nil)
10189 (while (setq e (pop opts))
10190 (if (not (nth 3 e))
10191 (setq rtn (nth 2 e))
10192 (if (not (listp rtn)) (setq rtn nil))
10193 (push (nth 2 e) rtn)))
10194 rtn)))))
10196 (defvar org-todo-setup-filter-hook nil
10197 "Hook for functions that pre-filter todo specs.
10199 Each function takes a todo spec and returns either `nil' or the spec
10200 transformed into canonical form." )
10202 (defvar org-todo-get-default-hook nil
10203 "Hook for functions that get a default item for todo.
10205 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10206 `nil' or a string to be used for the todo mark." )
10208 (defvar org-agenda-headline-snapshot-before-repeat)
10210 (defun org-todo (&optional arg)
10211 "Change the TODO state of an item.
10212 The state of an item is given by a keyword at the start of the heading,
10213 like
10214 *** TODO Write paper
10215 *** DONE Call mom
10217 The different keywords are specified in the variable `org-todo-keywords'.
10218 By default the available states are \"TODO\" and \"DONE\".
10219 So for this example: when the item starts with TODO, it is changed to DONE.
10220 When it starts with DONE, the DONE is removed. And when neither TODO nor
10221 DONE are present, add TODO at the beginning of the heading.
10223 With C-u prefix arg, use completion to determine the new state.
10224 With numeric prefix arg, switch to that state.
10225 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
10226 With a triple C-u prefix, circumvent any state blocking.
10228 For calling through lisp, arg is also interpreted in the following way:
10229 'none -> empty state
10230 \"\"(empty string) -> switch to empty state
10231 'done -> switch to DONE
10232 'nextset -> switch to the next set of keywords
10233 'previousset -> switch to the previous set of keywords
10234 \"WAITING\" -> switch to the specified keyword, but only if it
10235 really is a member of `org-todo-keywords'."
10236 (interactive "P")
10237 (if (equal arg '(16)) (setq arg 'nextset))
10238 (let ((org-blocker-hook org-blocker-hook)
10239 (case-fold-search nil))
10240 (when (equal arg '(64))
10241 (setq arg nil org-blocker-hook nil))
10242 (when (and org-blocker-hook
10243 (or org-inhibit-blocking
10244 (org-entry-get nil "NOBLOCKING")))
10245 (setq org-blocker-hook nil))
10246 (save-excursion
10247 (catch 'exit
10248 (org-back-to-heading t)
10249 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10250 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10251 (looking-at " *"))
10252 (let* ((match-data (match-data))
10253 (startpos (point-at-bol))
10254 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
10255 (org-log-done org-log-done)
10256 (org-log-repeat org-log-repeat)
10257 (org-todo-log-states org-todo-log-states)
10258 (this (match-string 1))
10259 (hl-pos (match-beginning 0))
10260 (head (org-get-todo-sequence-head this))
10261 (ass (assoc head org-todo-kwd-alist))
10262 (interpret (nth 1 ass))
10263 (done-word (nth 3 ass))
10264 (final-done-word (nth 4 ass))
10265 (last-state (or this ""))
10266 (completion-ignore-case t)
10267 (member (member this org-todo-keywords-1))
10268 (tail (cdr member))
10269 (state (cond
10270 ((and org-todo-key-trigger
10271 (or (and (equal arg '(4))
10272 (eq org-use-fast-todo-selection 'prefix))
10273 (and (not arg) org-use-fast-todo-selection
10274 (not (eq org-use-fast-todo-selection
10275 'prefix)))))
10276 ;; Use fast selection
10277 (org-fast-todo-selection))
10278 ((and (equal arg '(4))
10279 (or (not org-use-fast-todo-selection)
10280 (not org-todo-key-trigger)))
10281 ;; Read a state with completion
10282 (org-icompleting-read
10283 "State: " (mapcar (lambda(x) (list x))
10284 org-todo-keywords-1)
10285 nil t))
10286 ((eq arg 'right)
10287 (if this
10288 (if tail (car tail) nil)
10289 (car org-todo-keywords-1)))
10290 ((eq arg 'left)
10291 (if (equal member org-todo-keywords-1)
10293 (if this
10294 (nth (- (length org-todo-keywords-1)
10295 (length tail) 2)
10296 org-todo-keywords-1)
10297 (org-last org-todo-keywords-1))))
10298 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10299 (setq arg nil))) ; hack to fall back to cycling
10300 (arg
10301 ;; user or caller requests a specific state
10302 (cond
10303 ((equal arg "") nil)
10304 ((eq arg 'none) nil)
10305 ((eq arg 'done) (or done-word (car org-done-keywords)))
10306 ((eq arg 'nextset)
10307 (or (car (cdr (member head org-todo-heads)))
10308 (car org-todo-heads)))
10309 ((eq arg 'previousset)
10310 (let ((org-todo-heads (reverse org-todo-heads)))
10311 (or (car (cdr (member head org-todo-heads)))
10312 (car org-todo-heads))))
10313 ((car (member arg org-todo-keywords-1)))
10314 ((stringp arg)
10315 (error "State `%s' not valid in this file" arg))
10316 ((nth (1- (prefix-numeric-value arg))
10317 org-todo-keywords-1))))
10318 ((null member) (or head (car org-todo-keywords-1)))
10319 ((equal this final-done-word) nil) ;; -> make empty
10320 ((null tail) nil) ;; -> first entry
10321 ((memq interpret '(type priority))
10322 (if (eq this-command last-command)
10323 (car tail)
10324 (if (> (length tail) 0)
10325 (or done-word (car org-done-keywords))
10326 nil)))
10328 (car tail))))
10329 (state (or
10330 (run-hook-with-args-until-success
10331 'org-todo-get-default-hook state last-state)
10332 state))
10333 (next (if state (concat " " state " ") " "))
10334 (change-plist (list :type 'todo-state-change :from this :to state
10335 :position startpos))
10336 dolog now-done-p)
10337 (when org-blocker-hook
10338 (setq org-last-todo-state-is-todo
10339 (not (member this org-done-keywords)))
10340 (unless (save-excursion
10341 (save-match-data
10342 (run-hook-with-args-until-failure
10343 'org-blocker-hook change-plist)))
10344 (if (interactive-p)
10345 (error "TODO state change from %s to %s blocked" this state)
10346 ;; fail silently
10347 (message "TODO state change from %s to %s blocked" this state)
10348 (throw 'exit nil))))
10349 (store-match-data match-data)
10350 (replace-match next t t)
10351 (unless (pos-visible-in-window-p hl-pos)
10352 (message "TODO state changed to %s" (org-trim next)))
10353 (unless head
10354 (setq head (org-get-todo-sequence-head state)
10355 ass (assoc head org-todo-kwd-alist)
10356 interpret (nth 1 ass)
10357 done-word (nth 3 ass)
10358 final-done-word (nth 4 ass)))
10359 (when (memq arg '(nextset previousset))
10360 (message "Keyword-Set %d/%d: %s"
10361 (- (length org-todo-sets) -1
10362 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10363 (length org-todo-sets)
10364 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10365 (setq org-last-todo-state-is-todo
10366 (not (member state org-done-keywords)))
10367 (setq now-done-p (and (member state org-done-keywords)
10368 (not (member this org-done-keywords))))
10369 (and logging (org-local-logging logging))
10370 (when (and (or org-todo-log-states org-log-done)
10371 (not (eq org-inhibit-logging t))
10372 (not (memq arg '(nextset previousset))))
10373 ;; we need to look at recording a time and note
10374 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10375 (nth 2 (assoc this org-todo-log-states))))
10376 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10377 (setq dolog 'time))
10378 (when (and state
10379 (member state org-not-done-keywords)
10380 (not (member this org-not-done-keywords)))
10381 ;; This is now a todo state and was not one before
10382 ;; If there was a CLOSED time stamp, get rid of it.
10383 (org-add-planning-info nil nil 'closed))
10384 (when (and now-done-p org-log-done)
10385 ;; It is now done, and it was not done before
10386 (org-add-planning-info 'closed (org-current-time))
10387 (if (and (not dolog) (eq 'note org-log-done))
10388 (org-add-log-setup 'done state this 'findpos 'note)))
10389 (when (and state dolog)
10390 ;; This is a non-nil state, and we need to log it
10391 (org-add-log-setup 'state state this 'findpos dolog)))
10392 ;; Fixup tag positioning
10393 (org-todo-trigger-tag-changes state)
10394 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10395 (when org-provide-todo-statistics
10396 (org-update-parent-todo-statistics))
10397 (run-hooks 'org-after-todo-state-change-hook)
10398 (if (and arg (not (member state org-done-keywords)))
10399 (setq head (org-get-todo-sequence-head state)))
10400 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10401 ;; Do we need to trigger a repeat?
10402 (when now-done-p
10403 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10404 ;; This is for the agenda, take a snapshot of the headline.
10405 (save-match-data
10406 (setq org-agenda-headline-snapshot-before-repeat
10407 (org-get-heading))))
10408 (org-auto-repeat-maybe state))
10409 ;; Fixup cursor location if close to the keyword
10410 (if (and (outline-on-heading-p)
10411 (not (bolp))
10412 (save-excursion (beginning-of-line 1)
10413 (looking-at org-todo-line-regexp))
10414 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10415 (progn
10416 (goto-char (or (match-end 2) (match-end 1)))
10417 (and (looking-at " ") (just-one-space))))
10418 (when org-trigger-hook
10419 (save-excursion
10420 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10422 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10423 "Block turning an entry into a TODO, using the hierarchy.
10424 This checks whether the current task should be blocked from state
10425 changes. Such blocking occurs when:
10427 1. The task has children which are not all in a completed state.
10429 2. A task has a parent with the property :ORDERED:, and there
10430 are siblings prior to the current task with incomplete
10431 status.
10433 3. The parent of the task is blocked because it has siblings that should
10434 be done first, or is child of a block grandparent TODO entry."
10436 (if (not org-enforce-todo-dependencies)
10437 t ; if locally turned off don't block
10438 (catch 'dont-block
10439 ;; If this is not a todo state change, or if this entry is already DONE,
10440 ;; do not block
10441 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10442 (member (plist-get change-plist :from)
10443 (cons 'done org-done-keywords))
10444 (member (plist-get change-plist :to)
10445 (cons 'todo org-not-done-keywords))
10446 (not (plist-get change-plist :to)))
10447 (throw 'dont-block t))
10448 ;; If this task has children, and any are undone, it's blocked
10449 (save-excursion
10450 (org-back-to-heading t)
10451 (let ((this-level (funcall outline-level)))
10452 (outline-next-heading)
10453 (let ((child-level (funcall outline-level)))
10454 (while (and (not (eobp))
10455 (> child-level this-level))
10456 ;; this todo has children, check whether they are all
10457 ;; completed
10458 (if (and (not (org-entry-is-done-p))
10459 (org-entry-is-todo-p))
10460 (throw 'dont-block nil))
10461 (outline-next-heading)
10462 (setq child-level (funcall outline-level))))))
10463 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10464 ;; any previous siblings are undone, it's blocked
10465 (save-excursion
10466 (org-back-to-heading t)
10467 (let* ((pos (point))
10468 (parent-pos (and (org-up-heading-safe) (point))))
10469 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10470 (when (and (org-entry-get (point) "ORDERED")
10471 (forward-line 1)
10472 (re-search-forward org-not-done-heading-regexp pos t))
10473 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10474 ;; Search further up the hierarchy, to see if an anchestor is blocked
10475 (while t
10476 (goto-char parent-pos)
10477 (if (not (looking-at org-not-done-heading-regexp))
10478 (throw 'dont-block t)) ; do not block, parent is not a TODO
10479 (setq pos (point))
10480 (setq parent-pos (and (org-up-heading-safe) (point)))
10481 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10482 (when (and (org-entry-get (point) "ORDERED")
10483 (forward-line 1)
10484 (re-search-forward org-not-done-heading-regexp pos t))
10485 (throw 'dont-block nil)))))))) ; block, older sibling not done.
10487 (defcustom org-track-ordered-property-with-tag nil
10488 "Should the ORDERED property also be shown as a tag?
10489 The ORDERED property decides if an entry should require subtasks to be
10490 completed in sequence. Since a property is not very visible, setting
10491 this option means that toggling the ORDERED property with the command
10492 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10493 not relevant for the behavior, but it makes things more visible.
10495 Note that toggling the tag with tags commands will not change the property
10496 and therefore not influence behavior!
10498 This can be t, meaning the tag ORDERED should be used, It can also be a
10499 string to select a different tag for this task."
10500 :group 'org-todo
10501 :type '(choice
10502 (const :tag "No tracking" nil)
10503 (const :tag "Track with ORDERED tag" t)
10504 (string :tag "Use other tag")))
10506 (defun org-toggle-ordered-property ()
10507 "Toggle the ORDERED property of the current entry.
10508 For better visibility, you can track the value of this property with a tag.
10509 See variable `org-track-ordered-property-with-tag'."
10510 (interactive)
10511 (let* ((t1 org-track-ordered-property-with-tag)
10512 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10513 (save-excursion
10514 (org-back-to-heading)
10515 (if (org-entry-get nil "ORDERED")
10516 (progn
10517 (org-delete-property "ORDERED")
10518 (and tag (org-toggle-tag tag 'off))
10519 (message "Subtasks can be completed in arbitrary order"))
10520 (org-entry-put nil "ORDERED" "t")
10521 (and tag (org-toggle-tag tag 'on))
10522 (message "Subtasks must be completed in sequence")))))
10524 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10525 (defun org-block-todo-from-checkboxes (change-plist)
10526 "Block turning an entry into a TODO, using checkboxes.
10527 This checks whether the current task should be blocked from state
10528 changes because there are unchecked boxes in this entry."
10529 (if (not org-enforce-todo-checkbox-dependencies)
10530 t ; if locally turned off don't block
10531 (catch 'dont-block
10532 ;; If this is not a todo state change, or if this entry is already DONE,
10533 ;; do not block
10534 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10535 (member (plist-get change-plist :from)
10536 (cons 'done org-done-keywords))
10537 (member (plist-get change-plist :to)
10538 (cons 'todo org-not-done-keywords))
10539 (not (plist-get change-plist :to)))
10540 (throw 'dont-block t))
10541 ;; If this task has checkboxes that are not checked, it's blocked
10542 (save-excursion
10543 (org-back-to-heading t)
10544 (let ((beg (point)) end)
10545 (outline-next-heading)
10546 (setq end (point))
10547 (goto-char beg)
10548 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10549 end t)
10550 (progn
10551 (if (boundp 'org-blocked-by-checkboxes)
10552 (setq org-blocked-by-checkboxes t))
10553 (throw 'dont-block nil)))))
10554 t))) ; do not block
10556 (defun org-entry-blocked-p ()
10557 "Is the current entry blocked?"
10558 (if (org-entry-get nil "NOBLOCKING")
10559 nil ;; Never block this entry
10560 (not
10561 (run-hook-with-args-until-failure
10562 'org-blocker-hook
10563 (list :type 'todo-state-change
10564 :position (point)
10565 :from 'todo
10566 :to 'done)))))
10568 (defun org-update-statistics-cookies (all)
10569 "Update the statistics cookie, either from TODO or from checkboxes.
10570 This should be called with the cursor in a line with a statistics cookie."
10571 (interactive "P")
10572 (if all
10573 (progn
10574 (org-update-checkbox-count 'all)
10575 (org-map-entries 'org-update-parent-todo-statistics))
10576 (if (not (org-on-heading-p))
10577 (org-update-checkbox-count)
10578 (let ((pos (move-marker (make-marker) (point)))
10579 end l1 l2)
10580 (ignore-errors (org-back-to-heading t))
10581 (if (not (org-on-heading-p))
10582 (org-update-checkbox-count)
10583 (setq l1 (org-outline-level))
10584 (setq end (save-excursion
10585 (outline-next-heading)
10586 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10587 (point)))
10588 (if (and (save-excursion
10589 (re-search-forward
10590 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
10591 (not (save-excursion (re-search-forward
10592 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10593 (org-update-checkbox-count)
10594 (if (and l2 (> l2 l1))
10595 (progn
10596 (goto-char end)
10597 (org-update-parent-todo-statistics))
10598 (goto-char pos)
10599 (beginning-of-line 1)
10600 (while (re-search-forward
10601 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
10602 (point-at-eol) t)
10603 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
10604 (goto-char pos)
10605 (move-marker pos nil)))))
10607 (defvar org-entry-property-inherited-from) ;; defined below
10608 (defun org-update-parent-todo-statistics ()
10609 "Update any statistics cookie in the parent of the current headline.
10610 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10611 the entire subtree and this will travel up the hierarchy and update
10612 statistics everywhere."
10613 (interactive)
10614 (let* ((lim 0) prop
10615 (recursive (or (not org-hierarchical-todo-statistics)
10616 (string-match
10617 "\\<recursive\\>"
10618 (or (setq prop (org-entry-get
10619 nil "COOKIE_DATA" 'inherit)) ""))))
10620 (lim (or (and prop (marker-position
10621 org-entry-property-inherited-from))
10622 lim))
10623 (first t)
10624 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10625 level ltoggle l1 new ndel
10626 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10627 (catch 'exit
10628 (save-excursion
10629 (beginning-of-line 1)
10630 (if (org-at-heading-p)
10631 (setq ltoggle (funcall outline-level))
10632 (error "This should not happen"))
10633 (while (and (setq level (org-up-heading-safe))
10634 (or recursive first)
10635 (>= (point) lim))
10636 (setq first nil cookie-present nil)
10637 (unless (and level
10638 (not (string-match
10639 "\\<checkbox\\>"
10640 (downcase
10641 (or (org-entry-get
10642 nil "COOKIE_DATA")
10643 "")))))
10644 (throw 'exit nil))
10645 (while (re-search-forward box-re (point-at-eol) t)
10646 (setq cnt-all 0 cnt-done 0 cookie-present t)
10647 (setq is-percent (match-end 2))
10648 (save-match-data
10649 (unless (outline-next-heading) (throw 'exit nil))
10650 (while (and (looking-at org-complex-heading-regexp)
10651 (> (setq l1 (length (match-string 1))) level))
10652 (setq kwd (and (or recursive (= l1 ltoggle))
10653 (match-string 2)))
10654 (if (or (eq org-provide-todo-statistics 'all-headlines)
10655 (and (listp org-provide-todo-statistics)
10656 (or (member kwd org-provide-todo-statistics)
10657 (member kwd org-done-keywords))))
10658 (setq cnt-all (1+ cnt-all))
10659 (if (eq org-provide-todo-statistics t)
10660 (and kwd (setq cnt-all (1+ cnt-all)))))
10661 (and (member kwd org-done-keywords)
10662 (setq cnt-done (1+ cnt-done)))
10663 (outline-next-heading)))
10664 (setq new
10665 (if is-percent
10666 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10667 (format "[%d/%d]" cnt-done cnt-all))
10668 ndel (- (match-end 0) (match-beginning 0)))
10669 (goto-char (match-beginning 0))
10670 (insert new)
10671 (delete-region (point) (+ (point) ndel)))
10672 (when cookie-present
10673 (run-hook-with-args 'org-after-todo-statistics-hook
10674 cnt-done (- cnt-all cnt-done))))))
10675 (run-hooks 'org-todo-statistics-hook)))
10677 (defvar org-after-todo-statistics-hook nil
10678 "Hook that is called after a TODO statistics cookie has been updated.
10679 Each function is called with two arguments: the number of not-done entries
10680 and the number of done entries.
10682 For example, the following function, when added to this hook, will switch
10683 an entry to DONE when all children are done, and back to TODO when new
10684 entries are set to a TODO status. Note that this hook is only called
10685 when there is a statistics cookie in the headline!
10687 (defun org-summary-todo (n-done n-not-done)
10688 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10689 (let (org-log-done org-log-states) ; turn off logging
10690 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10693 (defvar org-todo-statistics-hook nil
10694 "Hook that is run whenever Org thinks TODO statistics should be updated.
10695 This hook runs even if there is no statistics cookie present, in which case
10696 `org-after-todo-statistics-hook' would not run.")
10698 (defun org-todo-trigger-tag-changes (state)
10699 "Apply the changes defined in `org-todo-state-tags-triggers'."
10700 (let ((l org-todo-state-tags-triggers)
10701 changes)
10702 (when (or (not state) (equal state ""))
10703 (setq changes (append changes (cdr (assoc "" l)))))
10704 (when (and (stringp state) (> (length state) 0))
10705 (setq changes (append changes (cdr (assoc state l)))))
10706 (when (member state org-not-done-keywords)
10707 (setq changes (append changes (cdr (assoc 'todo l)))))
10708 (when (member state org-done-keywords)
10709 (setq changes (append changes (cdr (assoc 'done l)))))
10710 (dolist (c changes)
10711 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10713 (defun org-local-logging (value)
10714 "Get logging settings from a property VALUE."
10715 (let* (words w a)
10716 ;; directly set the variables, they are already local.
10717 (setq org-log-done nil
10718 org-log-repeat nil
10719 org-todo-log-states nil)
10720 (setq words (org-split-string value))
10721 (while (setq w (pop words))
10722 (cond
10723 ((setq a (assoc w org-startup-options))
10724 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10725 (set (nth 1 a) (nth 2 a))))
10726 ((setq a (org-extract-log-state-settings w))
10727 (and (member (car a) org-todo-keywords-1)
10728 (push a org-todo-log-states)))))))
10730 (defun org-get-todo-sequence-head (kwd)
10731 "Return the head of the TODO sequence to which KWD belongs.
10732 If KWD is not set, check if there is a text property remembering the
10733 right sequence."
10734 (let (p)
10735 (cond
10736 ((not kwd)
10737 (or (get-text-property (point-at-bol) 'org-todo-head)
10738 (progn
10739 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10740 nil (point-at-eol)))
10741 (get-text-property p 'org-todo-head))))
10742 ((not (member kwd org-todo-keywords-1))
10743 (car org-todo-keywords-1))
10744 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10746 (defun org-fast-todo-selection ()
10747 "Fast TODO keyword selection with single keys.
10748 Returns the new TODO keyword, or nil if no state change should occur."
10749 (let* ((fulltable org-todo-key-alist)
10750 (done-keywords org-done-keywords) ;; needed for the faces.
10751 (maxlen (apply 'max (mapcar
10752 (lambda (x)
10753 (if (stringp (car x)) (string-width (car x)) 0))
10754 fulltable)))
10755 (expert nil)
10756 (fwidth (+ maxlen 3 1 3))
10757 (ncol (/ (- (window-width) 4) fwidth))
10758 tg cnt e c tbl
10759 groups ingroup)
10760 (save-excursion
10761 (save-window-excursion
10762 (if expert
10763 (set-buffer (get-buffer-create " *Org todo*"))
10764 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10765 (erase-buffer)
10766 (org-set-local 'org-done-keywords done-keywords)
10767 (setq tbl fulltable cnt 0)
10768 (while (setq e (pop tbl))
10769 (cond
10770 ((equal e '(:startgroup))
10771 (push '() groups) (setq ingroup t)
10772 (when (not (= cnt 0))
10773 (setq cnt 0)
10774 (insert "\n"))
10775 (insert "{ "))
10776 ((equal e '(:endgroup))
10777 (setq ingroup nil cnt 0)
10778 (insert "}\n"))
10779 ((equal e '(:newline))
10780 (when (not (= cnt 0))
10781 (setq cnt 0)
10782 (insert "\n")
10783 (setq e (car tbl))
10784 (while (equal (car tbl) '(:newline))
10785 (insert "\n")
10786 (setq tbl (cdr tbl)))))
10788 (setq tg (car e) c (cdr e))
10789 (if ingroup (push tg (car groups)))
10790 (setq tg (org-add-props tg nil 'face
10791 (org-get-todo-face tg)))
10792 (if (and (= cnt 0) (not ingroup)) (insert " "))
10793 (insert "[" c "] " tg (make-string
10794 (- fwidth 4 (length tg)) ?\ ))
10795 (when (= (setq cnt (1+ cnt)) ncol)
10796 (insert "\n")
10797 (if ingroup (insert " "))
10798 (setq cnt 0)))))
10799 (insert "\n")
10800 (goto-char (point-min))
10801 (if (not expert) (org-fit-window-to-buffer))
10802 (message "[a-z..]:Set [SPC]:clear")
10803 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10804 (cond
10805 ((or (= c ?\C-g)
10806 (and (= c ?q) (not (rassoc c fulltable))))
10807 (setq quit-flag t))
10808 ((= c ?\ ) nil)
10809 ((setq e (rassoc c fulltable) tg (car e))
10811 (t (setq quit-flag t)))))))
10813 (defun org-entry-is-todo-p ()
10814 (member (org-get-todo-state) org-not-done-keywords))
10816 (defun org-entry-is-done-p ()
10817 (member (org-get-todo-state) org-done-keywords))
10819 (defun org-get-todo-state ()
10820 (save-excursion
10821 (org-back-to-heading t)
10822 (and (looking-at org-todo-line-regexp)
10823 (match-end 2)
10824 (match-string 2))))
10826 (defun org-at-date-range-p (&optional inactive-ok)
10827 "Is the cursor inside a date range?"
10828 (interactive)
10829 (save-excursion
10830 (catch 'exit
10831 (let ((pos (point)))
10832 (skip-chars-backward "^[<\r\n")
10833 (skip-chars-backward "<[")
10834 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10835 (>= (match-end 0) pos)
10836 (throw 'exit t))
10837 (skip-chars-backward "^<[\r\n")
10838 (skip-chars-backward "<[")
10839 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10840 (>= (match-end 0) pos)
10841 (throw 'exit t)))
10842 nil)))
10844 (defun org-get-repeat (&optional tagline)
10845 "Check if there is a deadline/schedule with repeater in this entry."
10846 (save-match-data
10847 (save-excursion
10848 (org-back-to-heading t)
10849 (and (re-search-forward (if tagline
10850 (concat tagline "\\s-*" org-repeat-re)
10851 org-repeat-re)
10852 (org-entry-end-position) t)
10853 (match-string-no-properties 1)))))
10855 (defvar org-last-changed-timestamp)
10856 (defvar org-last-inserted-timestamp)
10857 (defvar org-log-post-message)
10858 (defvar org-log-note-purpose)
10859 (defvar org-log-note-how)
10860 (defvar org-log-note-extra)
10861 (defun org-auto-repeat-maybe (done-word)
10862 "Check if the current headline contains a repeated deadline/schedule.
10863 If yes, set TODO state back to what it was and change the base date
10864 of repeating deadline/scheduled time stamps to new date.
10865 This function is run automatically after each state change to a DONE state."
10866 ;; last-state is dynamically scoped into this function
10867 (let* ((repeat (org-get-repeat))
10868 (aa (assoc last-state org-todo-kwd-alist))
10869 (interpret (nth 1 aa))
10870 (head (nth 2 aa))
10871 (whata '(("d" . day) ("m" . month) ("y" . year)))
10872 (msg "Entry repeats: ")
10873 (org-log-done nil)
10874 (org-todo-log-states nil)
10875 (nshiftmax 10) (nshift 0)
10876 re type n what ts time to-state)
10877 (when repeat
10878 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10879 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
10880 org-todo-repeat-to-state))
10881 (unless (and to-state (member to-state org-todo-keywords-1))
10882 (setq to-state (if (eq interpret 'type) last-state head)))
10883 (org-todo to-state)
10884 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
10885 (org-entry-put nil "LAST_REPEAT" (format-time-string
10886 (org-time-stamp-format t t))))
10887 (when org-log-repeat
10888 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10889 (memq 'org-add-log-note post-command-hook))
10890 ;; OK, we are already setup for some record
10891 (if (eq org-log-repeat 'note)
10892 ;; make sure we take a note, not only a time stamp
10893 (setq org-log-note-how 'note))
10894 ;; Set up for taking a record
10895 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10896 last-state
10897 'findpos org-log-repeat)))
10898 (org-back-to-heading t)
10899 (org-add-planning-info nil nil 'closed)
10900 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10901 org-deadline-time-regexp "\\)\\|\\("
10902 org-ts-regexp "\\)"))
10903 (while (re-search-forward
10904 re (save-excursion (outline-next-heading) (point)) t)
10905 (setq type (if (match-end 1) org-scheduled-string
10906 (if (match-end 3) org-deadline-string "Plain:"))
10907 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10908 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10909 (setq n (string-to-number (match-string 2 ts))
10910 what (match-string 3 ts))
10911 (if (equal what "w") (setq n (* n 7) what "d"))
10912 ;; Preparation, see if we need to modify the start date for the change
10913 (when (match-end 1)
10914 (setq time (save-match-data (org-time-string-to-time ts)))
10915 (cond
10916 ((equal (match-string 1 ts) ".")
10917 ;; Shift starting date to today
10918 (org-timestamp-change
10919 (- (time-to-days (current-time)) (time-to-days time))
10920 'day))
10921 ((equal (match-string 1 ts) "+")
10922 (while (or (= nshift 0)
10923 (<= (time-to-days time) (time-to-days (current-time))))
10924 (when (= (incf nshift) nshiftmax)
10925 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10926 (error "Abort")))
10927 (org-timestamp-change n (cdr (assoc what whata)))
10928 (org-at-timestamp-p t)
10929 (setq ts (match-string 1))
10930 (setq time (save-match-data (org-time-string-to-time ts))))
10931 (org-timestamp-change (- n) (cdr (assoc what whata)))
10932 ;; rematch, so that we have everything in place for the real shift
10933 (org-at-timestamp-p t)
10934 (setq ts (match-string 1))
10935 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10936 (org-timestamp-change n (cdr (assoc what whata)))
10937 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10938 (setq org-log-post-message msg)
10939 (message "%s" msg))))
10941 (defun org-show-todo-tree (arg)
10942 "Make a compact tree which shows all headlines marked with TODO.
10943 The tree will show the lines where the regexp matches, and all higher
10944 headlines above the match.
10945 With a \\[universal-argument] prefix, prompt for a regexp to match.
10946 With a numeric prefix N, construct a sparse tree for the Nth element
10947 of `org-todo-keywords-1'."
10948 (interactive "P")
10949 (let ((case-fold-search nil)
10950 (kwd-re
10951 (cond ((null arg) org-not-done-regexp)
10952 ((equal arg '(4))
10953 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10954 (mapcar 'list org-todo-keywords-1))))
10955 (concat "\\("
10956 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10957 "\\)\\>")))
10958 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10959 (regexp-quote (nth (1- (prefix-numeric-value arg))
10960 org-todo-keywords-1)))
10961 (t (error "Invalid prefix argument: %s" arg)))))
10962 (message "%d TODO entries found"
10963 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10965 (defun org-deadline (&optional remove time)
10966 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10967 With argument REMOVE, remove any deadline from the item.
10968 When TIME is set, it should be an internal time specification, and the
10969 scheduling will use the corresponding date."
10970 (interactive "P")
10971 (let* ((old-date (org-entry-get nil "DEADLINE"))
10972 (repeater (and old-date
10973 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
10974 (match-string 1 old-date))))
10975 (if remove
10976 (progn
10977 (when (and old-date org-log-redeadline)
10978 (org-add-log-setup 'deldeadline nil old-date 'findpos
10979 org-log-redeadline))
10980 (org-remove-timestamp-with-keyword org-deadline-string)
10981 (message "Item no longer has a deadline."))
10982 (org-add-planning-info 'deadline time 'closed)
10983 (when (and old-date org-log-redeadline
10984 (not (equal old-date
10985 (substring org-last-inserted-timestamp 1 -1))))
10986 (org-add-log-setup 'redeadline nil old-date 'findpos
10987 org-log-redeadline))
10988 (when repeater
10989 (save-excursion
10990 (org-back-to-heading t)
10991 (when (re-search-forward (concat org-deadline-string " "
10992 org-last-inserted-timestamp)
10993 (save-excursion
10994 (outline-next-heading) (point)) t)
10995 (goto-char (1- (match-end 0)))
10996 (insert " " repeater)
10997 (setq org-last-inserted-timestamp
10998 (concat (substring org-last-inserted-timestamp 0 -1)
10999 " " repeater
11000 (substring org-last-inserted-timestamp -1))))))
11001 (message "Deadline on %s" org-last-inserted-timestamp))))
11003 (defun org-schedule (&optional remove time)
11004 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11005 With argument REMOVE, remove any scheduling date from the item.
11006 When TIME is set, it should be an internal time specification, and the
11007 scheduling will use the corresponding date."
11008 (interactive "P")
11009 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11010 (repeater (and old-date
11011 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11012 (match-string 1 old-date))))
11013 (if remove
11014 (progn
11015 (when (and old-date org-log-reschedule)
11016 (org-add-log-setup 'delschedule nil old-date 'findpos
11017 org-log-reschedule))
11018 (org-remove-timestamp-with-keyword org-scheduled-string)
11019 (message "Item is no longer scheduled."))
11020 (org-add-planning-info 'scheduled time 'closed)
11021 (when (and old-date org-log-reschedule
11022 (not (equal old-date
11023 (substring org-last-inserted-timestamp 1 -1))))
11024 (org-add-log-setup 'reschedule nil old-date 'findpos
11025 org-log-reschedule))
11026 (when repeater
11027 (save-excursion
11028 (org-back-to-heading t)
11029 (when (re-search-forward (concat org-scheduled-string " "
11030 org-last-inserted-timestamp)
11031 (save-excursion
11032 (outline-next-heading) (point)) t)
11033 (goto-char (1- (match-end 0)))
11034 (insert " " repeater)
11035 (setq org-last-inserted-timestamp
11036 (concat (substring org-last-inserted-timestamp 0 -1)
11037 " " repeater
11038 (substring org-last-inserted-timestamp -1))))))
11039 (message "Scheduled to %s" org-last-inserted-timestamp))))
11041 (defun org-get-scheduled-time (pom &optional inherit)
11042 "Get the scheduled time as a time tuple, of a format suitable
11043 for calling org-schedule with, or if there is no scheduling,
11044 returns nil."
11045 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11046 (when time
11047 (apply 'encode-time (org-parse-time-string time)))))
11049 (defun org-get-deadline-time (pom &optional inherit)
11050 "Get the deadine as a time tuple, of a format suitable for
11051 calling org-deadline with, or if there is no scheduling, returns
11052 nil."
11053 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11054 (when time
11055 (apply 'encode-time (org-parse-time-string time)))))
11057 (defun org-remove-timestamp-with-keyword (keyword)
11058 "Remove all time stamps with KEYWORD in the current entry."
11059 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11060 beg)
11061 (save-excursion
11062 (org-back-to-heading t)
11063 (setq beg (point))
11064 (outline-next-heading)
11065 (while (re-search-backward re beg t)
11066 (replace-match "")
11067 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11068 (equal (char-before) ?\ ))
11069 (backward-delete-char 1)
11070 (if (string-match "^[ \t]*$" (buffer-substring
11071 (point-at-bol) (point-at-eol)))
11072 (delete-region (point-at-bol)
11073 (min (point-max) (1+ (point-at-eol))))))))))
11075 (defun org-add-planning-info (what &optional time &rest remove)
11076 "Insert new timestamp with keyword in the line directly after the headline.
11077 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11078 If non is given, the user is prompted for a date.
11079 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11080 be removed."
11081 (interactive)
11082 (let (org-time-was-given org-end-time-was-given ts
11083 end default-time default-input)
11085 (catch 'exit
11086 (when (and (not time) (memq what '(scheduled deadline)))
11087 ;; Try to get a default date/time from existing timestamp
11088 (save-excursion
11089 (org-back-to-heading t)
11090 (setq end (save-excursion (outline-next-heading) (point)))
11091 (when (re-search-forward (if (eq what 'scheduled)
11092 org-scheduled-time-regexp
11093 org-deadline-time-regexp)
11094 end t)
11095 (setq ts (match-string 1)
11096 default-time
11097 (apply 'encode-time (org-parse-time-string ts))
11098 default-input (and ts (org-get-compact-tod ts))))))
11099 (when what
11100 ;; If necessary, get the time from the user
11101 (setq time (or time (org-read-date nil 'to-time nil nil
11102 default-time default-input))))
11104 (when (and org-insert-labeled-timestamps-at-point
11105 (member what '(scheduled deadline)))
11106 (insert
11107 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11108 (org-insert-time-stamp time org-time-was-given
11109 nil nil nil (list org-end-time-was-given))
11110 (setq what nil))
11111 (save-excursion
11112 (save-restriction
11113 (let (col list elt ts buffer-invisibility-spec)
11114 (org-back-to-heading t)
11115 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11116 (goto-char (match-end 1))
11117 (setq col (current-column))
11118 (goto-char (match-end 0))
11119 (if (eobp) (insert "\n") (forward-char 1))
11120 (when (and (not what)
11121 (not (looking-at
11122 (concat "[ \t]*"
11123 org-keyword-time-not-clock-regexp))))
11124 ;; Nothing to add, nothing to remove...... :-)
11125 (throw 'exit nil))
11126 (if (and (not (looking-at outline-regexp))
11127 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11128 "[^\r\n]*"))
11129 (not (equal (match-string 1) org-clock-string)))
11130 (narrow-to-region (match-beginning 0) (match-end 0))
11131 (insert-before-markers "\n")
11132 (backward-char 1)
11133 (narrow-to-region (point) (point))
11134 (and org-adapt-indentation (org-indent-to-column col)))
11135 ;; Check if we have to remove something.
11136 (setq list (cons what remove))
11137 (while list
11138 (setq elt (pop list))
11139 (goto-char (point-min))
11140 (when (or (and (eq elt 'scheduled)
11141 (re-search-forward org-scheduled-time-regexp nil t))
11142 (and (eq elt 'deadline)
11143 (re-search-forward org-deadline-time-regexp nil t))
11144 (and (eq elt 'closed)
11145 (re-search-forward org-closed-time-regexp nil t)))
11146 (replace-match "")
11147 (if (looking-at "--+<[^>]+>") (replace-match ""))
11148 (skip-chars-backward " ")
11149 (if (looking-at " +") (replace-match ""))))
11150 (goto-char (point-max))
11151 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11152 (when what
11153 (insert
11154 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11155 (cond ((eq what 'scheduled) org-scheduled-string)
11156 ((eq what 'deadline) org-deadline-string)
11157 ((eq what 'closed) org-closed-string))
11158 " ")
11159 (setq ts (org-insert-time-stamp
11160 time
11161 (or org-time-was-given
11162 (and (eq what 'closed) org-log-done-with-time))
11163 (eq what 'closed)
11164 nil nil (list org-end-time-was-given)))
11165 (end-of-line 1))
11166 (goto-char (point-min))
11167 (widen)
11168 (if (and (looking-at "[ \t]+\n")
11169 (equal (char-before) ?\n))
11170 (delete-region (1- (point)) (point-at-eol)))
11171 ts))))))
11173 (defvar org-log-note-marker (make-marker))
11174 (defvar org-log-note-purpose nil)
11175 (defvar org-log-note-state nil)
11176 (defvar org-log-note-previous-state nil)
11177 (defvar org-log-note-how nil)
11178 (defvar org-log-note-extra nil)
11179 (defvar org-log-note-window-configuration nil)
11180 (defvar org-log-note-return-to (make-marker))
11181 (defvar org-log-post-message nil
11182 "Message to be displayed after a log note has been stored.
11183 The auto-repeater uses this.")
11185 (defun org-add-note ()
11186 "Add a note to the current entry.
11187 This is done in the same way as adding a state change note."
11188 (interactive)
11189 (org-add-log-setup 'note nil nil 'findpos nil))
11191 (defvar org-property-end-re)
11192 (defun org-add-log-setup (&optional purpose state prev-state
11193 findpos how &optional extra)
11194 "Set up the post command hook to take a note.
11195 If this is about to TODO state change, the new state is expected in STATE.
11196 When FINDPOS is non-nil, find the correct position for the note in
11197 the current entry. If not, assume that it can be inserted at point.
11198 HOW is an indicator what kind of note should be created.
11199 EXTRA is additional text that will be inserted into the notes buffer."
11200 (let* ((org-log-into-drawer (org-log-into-drawer))
11201 (drawer (cond ((stringp org-log-into-drawer)
11202 org-log-into-drawer)
11203 (org-log-into-drawer "LOGBOOK")
11204 (t nil))))
11205 (save-restriction
11206 (save-excursion
11207 (when findpos
11208 (org-back-to-heading t)
11209 (narrow-to-region (point) (save-excursion
11210 (outline-next-heading) (point)))
11211 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11212 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11213 "[^\r\n]*\\)?"))
11214 (goto-char (match-end 0))
11215 (cond
11216 (drawer
11217 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11218 nil t)
11219 (progn
11220 (goto-char (match-end 0))
11221 (or org-log-states-order-reversed
11222 (and (re-search-forward org-property-end-re nil t)
11223 (goto-char (1- (match-beginning 0))))))
11224 (insert "\n:" drawer ":\n:END:")
11225 (beginning-of-line 0)
11226 (org-indent-line-function)
11227 (beginning-of-line 2)
11228 (org-indent-line-function)
11229 (end-of-line 0)))
11230 ((and org-log-state-notes-insert-after-drawers
11231 (save-excursion
11232 (forward-line) (looking-at org-drawer-regexp)))
11233 (forward-line)
11234 (while (looking-at org-drawer-regexp)
11235 (goto-char (match-end 0))
11236 (re-search-forward org-property-end-re (point-max) t)
11237 (forward-line))
11238 (forward-line -1)))
11239 (unless org-log-states-order-reversed
11240 (and (= (char-after) ?\n) (forward-char 1))
11241 (org-skip-over-state-notes)
11242 (skip-chars-backward " \t\n\r")))
11243 (move-marker org-log-note-marker (point))
11244 (setq org-log-note-purpose purpose
11245 org-log-note-state state
11246 org-log-note-previous-state prev-state
11247 org-log-note-how how
11248 org-log-note-extra extra)
11249 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11251 (defun org-skip-over-state-notes ()
11252 "Skip past the list of State notes in an entry."
11253 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11254 (while (looking-at "[ \t]*- State")
11255 (condition-case nil
11256 (org-next-item)
11257 (error (org-end-of-item)))))
11259 (defun org-add-log-note (&optional purpose)
11260 "Pop up a window for taking a note, and add this note later at point."
11261 (remove-hook 'post-command-hook 'org-add-log-note)
11262 (setq org-log-note-window-configuration (current-window-configuration))
11263 (delete-other-windows)
11264 (move-marker org-log-note-return-to (point))
11265 (switch-to-buffer (marker-buffer org-log-note-marker))
11266 (goto-char org-log-note-marker)
11267 (org-switch-to-buffer-other-window "*Org Note*")
11268 (erase-buffer)
11269 (if (memq org-log-note-how '(time state))
11270 (let (current-prefix-arg) (org-store-log-note))
11271 (let ((org-inhibit-startup t)) (org-mode))
11272 (insert (format "# Insert note for %s.
11273 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11274 (cond
11275 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11276 ((eq org-log-note-purpose 'done) "closed todo item")
11277 ((eq org-log-note-purpose 'state)
11278 (format "state change from \"%s\" to \"%s\""
11279 (or org-log-note-previous-state "")
11280 (or org-log-note-state "")))
11281 ((eq org-log-note-purpose 'reschedule)
11282 "rescheduling")
11283 ((eq org-log-note-purpose 'delschedule)
11284 "no longer scheduled")
11285 ((eq org-log-note-purpose 'redeadline)
11286 "changing deadline")
11287 ((eq org-log-note-purpose 'deldeadline)
11288 "removing deadline")
11289 ((eq org-log-note-purpose 'refile)
11290 "refiling")
11291 ((eq org-log-note-purpose 'note)
11292 "this entry")
11293 (t (error "This should not happen")))))
11294 (if org-log-note-extra (insert org-log-note-extra))
11295 (org-set-local 'org-finish-function 'org-store-log-note)))
11297 (defvar org-note-abort nil) ; dynamically scoped
11298 (defun org-store-log-note ()
11299 "Finish taking a log note, and insert it to where it belongs."
11300 (let ((txt (buffer-string))
11301 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11302 lines ind)
11303 (kill-buffer (current-buffer))
11304 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11305 (setq txt (replace-match "" t t txt)))
11306 (if (string-match "\\s-+\\'" txt)
11307 (setq txt (replace-match "" t t txt)))
11308 (setq lines (org-split-string txt "\n"))
11309 (when (and note (string-match "\\S-" note))
11310 (setq note
11311 (org-replace-escapes
11312 note
11313 (list (cons "%u" (user-login-name))
11314 (cons "%U" user-full-name)
11315 (cons "%t" (format-time-string
11316 (org-time-stamp-format 'long 'inactive)
11317 (current-time)))
11318 (cons "%s" (if org-log-note-state
11319 (concat "\"" org-log-note-state "\"")
11320 ""))
11321 (cons "%S" (if org-log-note-previous-state
11322 (concat "\"" org-log-note-previous-state "\"")
11323 "\"\"")))))
11324 (if lines (setq note (concat note " \\\\")))
11325 (push note lines))
11326 (when (or current-prefix-arg org-note-abort)
11327 (when org-log-into-drawer
11328 (org-remove-empty-drawer-at
11329 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11330 org-log-note-marker))
11331 (setq lines nil))
11332 (when lines
11333 (with-current-buffer (marker-buffer org-log-note-marker)
11334 (save-excursion
11335 (goto-char org-log-note-marker)
11336 (move-marker org-log-note-marker nil)
11337 (end-of-line 1)
11338 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11339 (insert "- " (pop lines))
11340 (org-indent-line-function)
11341 (beginning-of-line 1)
11342 (looking-at "[ \t]*")
11343 (setq ind (concat (match-string 0) " "))
11344 (end-of-line 1)
11345 (while lines (insert "\n" ind (pop lines)))
11346 (message "Note stored")
11347 (org-back-to-heading t)
11348 (org-cycle-hide-drawers 'children)))))
11349 (set-window-configuration org-log-note-window-configuration)
11350 (with-current-buffer (marker-buffer org-log-note-return-to)
11351 (goto-char org-log-note-return-to))
11352 (move-marker org-log-note-return-to nil)
11353 (and org-log-post-message (message "%s" org-log-post-message)))
11355 (defun org-remove-empty-drawer-at (drawer pos)
11356 "Remove an empty drawer DRAWER at position POS.
11357 POS may also be a marker."
11358 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11359 (save-excursion
11360 (save-restriction
11361 (widen)
11362 (goto-char pos)
11363 (if (org-in-regexp
11364 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11365 (replace-match ""))))))
11367 (defun org-sparse-tree (&optional arg)
11368 "Create a sparse tree, prompt for the details.
11369 This command can create sparse trees. You first need to select the type
11370 of match used to create the tree:
11372 t Show entries with a specific TODO keyword.
11373 m Show entries selected by a tags/property match.
11374 p Enter a property name and its value (both with completion on existing
11375 names/values) and show entries with that property.
11376 / Show entries matching a regular expression (`r' can be used as well)
11377 d Show deadlines due within `org-deadline-warning-days'.
11378 b Show deadlines and scheduled items before a date.
11379 a Show deadlines and scheduled items after a date."
11380 (interactive "P")
11381 (let (ans kwd value)
11382 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
11383 (setq ans (read-char-exclusive))
11384 (cond
11385 ((equal ans ?d)
11386 (call-interactively 'org-check-deadlines))
11387 ((equal ans ?b)
11388 (call-interactively 'org-check-before-date))
11389 ((equal ans ?a)
11390 (call-interactively 'org-check-after-date))
11391 ((equal ans ?t)
11392 (org-show-todo-tree '(4)))
11393 ((member ans '(?T ?m))
11394 (call-interactively 'org-match-sparse-tree))
11395 ((member ans '(?p ?P))
11396 (setq kwd (org-icompleting-read "Property: "
11397 (mapcar 'list (org-buffer-property-keys))))
11398 (setq value (org-icompleting-read "Value: "
11399 (mapcar 'list (org-property-values kwd))))
11400 (unless (string-match "\\`{.*}\\'" value)
11401 (setq value (concat "\"" value "\"")))
11402 (org-match-sparse-tree arg (concat kwd "=" value)))
11403 ((member ans '(?r ?R ?/))
11404 (call-interactively 'org-occur))
11405 (t (error "No such sparse tree command \"%c\"" ans)))))
11407 (defvar org-occur-highlights nil
11408 "List of overlays used for occur matches.")
11409 (make-variable-buffer-local 'org-occur-highlights)
11410 (defvar org-occur-parameters nil
11411 "Parameters of the active org-occur calls.
11412 This is a list, each call to org-occur pushes as cons cell,
11413 containing the regular expression and the callback, onto the list.
11414 The list can contain several entries if `org-occur' has been called
11415 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11416 will only contain one set of parameters. When the highlights are
11417 removed (for example with `C-c C-c', or with the next edit (depending
11418 on `org-remove-highlights-with-change'), this variable is emptied
11419 as well.")
11420 (make-variable-buffer-local 'org-occur-parameters)
11422 (defun org-occur (regexp &optional keep-previous callback)
11423 "Make a compact tree which shows all matches of REGEXP.
11424 The tree will show the lines where the regexp matches, and all higher
11425 headlines above the match. It will also show the heading after the match,
11426 to make sure editing the matching entry is easy.
11427 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11428 call to `org-occur' will be kept, to allow stacking of calls to this
11429 command.
11430 If CALLBACK is non-nil, it is a function which is called to confirm
11431 that the match should indeed be shown."
11432 (interactive "sRegexp: \nP")
11433 (when (equal regexp "")
11434 (error "Regexp cannot be empty"))
11435 (unless keep-previous
11436 (org-remove-occur-highlights nil nil t))
11437 (push (cons regexp callback) org-occur-parameters)
11438 (let ((cnt 0))
11439 (save-excursion
11440 (goto-char (point-min))
11441 (if (or (not keep-previous) ; do not want to keep
11442 (not org-occur-highlights)) ; no previous matches
11443 ;; hide everything
11444 (org-overview))
11445 (while (re-search-forward regexp nil t)
11446 (when (or (not callback)
11447 (save-match-data (funcall callback)))
11448 (setq cnt (1+ cnt))
11449 (when org-highlight-sparse-tree-matches
11450 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11451 (org-show-context 'occur-tree))))
11452 (when org-remove-highlights-with-change
11453 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11454 nil 'local))
11455 (unless org-sparse-tree-open-archived-trees
11456 (org-hide-archived-subtrees (point-min) (point-max)))
11457 (run-hooks 'org-occur-hook)
11458 (if (interactive-p)
11459 (message "%d match(es) for regexp %s" cnt regexp))
11460 cnt))
11462 (defun org-show-context (&optional key)
11463 "Make sure point and context and visible.
11464 How much context is shown depends upon the variables
11465 `org-show-hierarchy-above', `org-show-following-heading'. and
11466 `org-show-siblings'."
11467 (let ((heading-p (org-on-heading-p t))
11468 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11469 (following-p (org-get-alist-option org-show-following-heading key))
11470 (entry-p (org-get-alist-option org-show-entry-below key))
11471 (siblings-p (org-get-alist-option org-show-siblings key)))
11472 (catch 'exit
11473 ;; Show heading or entry text
11474 (if (and heading-p (not entry-p))
11475 (org-flag-heading nil) ; only show the heading
11476 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11477 (org-show-hidden-entry))) ; show entire entry
11478 (when following-p
11479 ;; Show next sibling, or heading below text
11480 (save-excursion
11481 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11482 (org-flag-heading nil))))
11483 (when siblings-p (org-show-siblings))
11484 (when hierarchy-p
11485 ;; show all higher headings, possibly with siblings
11486 (save-excursion
11487 (while (and (condition-case nil
11488 (progn (org-up-heading-all 1) t)
11489 (error nil))
11490 (not (bobp)))
11491 (org-flag-heading nil)
11492 (when siblings-p (org-show-siblings))))))))
11494 (defvar org-reveal-start-hook nil
11495 "Hook run before revealing a location.")
11497 (defun org-reveal (&optional siblings)
11498 "Show current entry, hierarchy above it, and the following headline.
11499 This can be used to show a consistent set of context around locations
11500 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11501 not t for the search context.
11503 With optional argument SIBLINGS, on each level of the hierarchy all
11504 siblings are shown. This repairs the tree structure to what it would
11505 look like when opened with hierarchical calls to `org-cycle'.
11506 With double optional argument `C-u C-u', go to the parent and show the
11507 entire tree."
11508 (interactive "P")
11509 (run-hooks 'org-reveal-start-hook)
11510 (let ((org-show-hierarchy-above t)
11511 (org-show-following-heading t)
11512 (org-show-siblings (if siblings t org-show-siblings)))
11513 (org-show-context nil))
11514 (when (equal siblings '(16))
11515 (save-excursion
11516 (when (org-up-heading-safe)
11517 (org-show-subtree)
11518 (run-hook-with-args 'org-cycle-hook 'subtree)))))
11520 (defun org-highlight-new-match (beg end)
11521 "Highlight from BEG to END and mark the highlight is an occur headline."
11522 (let ((ov (make-overlay beg end)))
11523 (overlay-put ov 'face 'secondary-selection)
11524 (push ov org-occur-highlights)))
11526 (defun org-remove-occur-highlights (&optional beg end noremove)
11527 "Remove the occur highlights from the buffer.
11528 BEG and END are ignored. If NOREMOVE is nil, remove this function
11529 from the `before-change-functions' in the current buffer."
11530 (interactive)
11531 (unless org-inhibit-highlight-removal
11532 (mapc 'delete-overlay org-occur-highlights)
11533 (setq org-occur-highlights nil)
11534 (setq org-occur-parameters nil)
11535 (unless noremove
11536 (remove-hook 'before-change-functions
11537 'org-remove-occur-highlights 'local))))
11539 ;;;; Priorities
11541 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11542 "Regular expression matching the priority indicator.")
11544 (defvar org-remove-priority-next-time nil)
11546 (defun org-priority-up ()
11547 "Increase the priority of the current item."
11548 (interactive)
11549 (org-priority 'up))
11551 (defun org-priority-down ()
11552 "Decrease the priority of the current item."
11553 (interactive)
11554 (org-priority 'down))
11556 (defun org-priority (&optional action)
11557 "Change the priority of an item by ARG.
11558 ACTION can be `set', `up', `down', or a character."
11559 (interactive)
11560 (unless org-enable-priority-commands
11561 (error "Priority commands are disabled"))
11562 (setq action (or action 'set))
11563 (let (current new news have remove)
11564 (save-excursion
11565 (org-back-to-heading t)
11566 (if (looking-at org-priority-regexp)
11567 (setq current (string-to-char (match-string 2))
11568 have t)
11569 (setq current org-default-priority))
11570 (cond
11571 ((eq action 'remove)
11572 (setq remove t new ?\ ))
11573 ((or (eq action 'set)
11574 (if (featurep 'xemacs) (characterp action) (integerp action)))
11575 (if (not (eq action 'set))
11576 (setq new action)
11577 (message "Priority %c-%c, SPC to remove: "
11578 org-highest-priority org-lowest-priority)
11579 (setq new (read-char-exclusive)))
11580 (if (and (= (upcase org-highest-priority) org-highest-priority)
11581 (= (upcase org-lowest-priority) org-lowest-priority))
11582 (setq new (upcase new)))
11583 (cond ((equal new ?\ ) (setq remove t))
11584 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11585 (error "Priority must be between `%c' and `%c'"
11586 org-highest-priority org-lowest-priority))))
11587 ((eq action 'up)
11588 (if (and (not have) (eq last-command this-command))
11589 (setq new org-lowest-priority)
11590 (setq new (if (and org-priority-start-cycle-with-default (not have))
11591 org-default-priority (1- current)))))
11592 ((eq action 'down)
11593 (if (and (not have) (eq last-command this-command))
11594 (setq new org-highest-priority)
11595 (setq new (if (and org-priority-start-cycle-with-default (not have))
11596 org-default-priority (1+ current)))))
11597 (t (error "Invalid action")))
11598 (if (or (< (upcase new) org-highest-priority)
11599 (> (upcase new) org-lowest-priority))
11600 (setq remove t))
11601 (setq news (format "%c" new))
11602 (if have
11603 (if remove
11604 (replace-match "" t t nil 1)
11605 (replace-match news t t nil 2))
11606 (if remove
11607 (error "No priority cookie found in line")
11608 (let ((case-fold-search nil))
11609 (looking-at org-todo-line-regexp))
11610 (if (match-end 2)
11611 (progn
11612 (goto-char (match-end 2))
11613 (insert " [#" news "]"))
11614 (goto-char (match-beginning 3))
11615 (insert "[#" news "] "))))
11616 (org-preserve-lc (org-set-tags nil 'align)))
11617 (if remove
11618 (message "Priority removed")
11619 (message "Priority of current item set to %s" news))))
11621 (defun org-get-priority (s)
11622 "Find priority cookie and return priority."
11623 (save-match-data
11624 (if (not (string-match org-priority-regexp s))
11625 (* 1000 (- org-lowest-priority org-default-priority))
11626 (* 1000 (- org-lowest-priority
11627 (string-to-char (match-string 2 s)))))))
11629 ;;;; Tags
11631 (defvar org-agenda-archives-mode)
11632 (defvar org-map-continue-from nil
11633 "Position from where mapping should continue.
11634 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11636 (defvar org-scanner-tags nil
11637 "The current tag list while the tags scanner is running.")
11638 (defvar org-trust-scanner-tags nil
11639 "Should `org-get-tags-at' use the tags fro the scanner.
11640 This is for internal dynamical scoping only.
11641 When this is non-nil, the function `org-get-tags-at' will return the value
11642 of `org-scanner-tags' instead of building the list by itself. This
11643 can lead to large speed-ups when the tags scanner is used in a file with
11644 many entries, and when the list of tags is retrieved, for example to
11645 obtain a list of properties. Building the tags list for each entry in such
11646 a file becomes an N^2 operation - but with this variable set, it scales
11647 as N.")
11649 (defun org-scan-tags (action matcher &optional todo-only)
11650 "Scan headline tags with inheritance and produce output ACTION.
11652 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11653 or `agenda' to produce an entry list for an agenda view. It can also be
11654 a Lisp form or a function that should be called at each matched headline, in
11655 this case the return value is a list of all return values from these calls.
11657 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11658 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11659 only lines with a TODO keyword are included in the output."
11660 (require 'org-agenda)
11661 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11662 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11663 (org-re
11664 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11665 (props (list 'face 'default
11666 'done-face 'org-agenda-done
11667 'undone-face 'default
11668 'mouse-face 'highlight
11669 'org-not-done-regexp org-not-done-regexp
11670 'org-todo-regexp org-todo-regexp
11671 'help-echo
11672 (format "mouse-2 or RET jump to org file %s"
11673 (abbreviate-file-name
11674 (or (buffer-file-name (buffer-base-buffer))
11675 (buffer-name (buffer-base-buffer)))))))
11676 (case-fold-search nil)
11677 (org-map-continue-from nil)
11678 lspos tags tags-list
11679 (tags-alist (list (cons 0 org-file-tags)))
11680 (llast 0) rtn rtn1 level category i txt
11681 todo marker entry priority)
11682 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11683 (setq action (list 'lambda nil action)))
11684 (save-excursion
11685 (goto-char (point-min))
11686 (when (eq action 'sparse-tree)
11687 (org-overview)
11688 (org-remove-occur-highlights))
11689 (while (re-search-forward re nil t)
11690 (catch :skip
11691 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11692 tags (if (match-end 4) (org-match-string-no-properties 4)))
11693 (goto-char (setq lspos (match-beginning 0)))
11694 (setq level (org-reduced-level (funcall outline-level))
11695 category (org-get-category))
11696 (setq i llast llast level)
11697 ;; remove tag lists from same and sublevels
11698 (while (>= i level)
11699 (when (setq entry (assoc i tags-alist))
11700 (setq tags-alist (delete entry tags-alist)))
11701 (setq i (1- i)))
11702 ;; add the next tags
11703 (when tags
11704 (setq tags (org-split-string tags ":")
11705 tags-alist
11706 (cons (cons level tags) tags-alist)))
11707 ;; compile tags for current headline
11708 (setq tags-list
11709 (if org-use-tag-inheritance
11710 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11711 tags)
11712 org-scanner-tags tags-list)
11713 (when org-use-tag-inheritance
11714 (setcdr (car tags-alist)
11715 (mapcar (lambda (x)
11716 (setq x (copy-sequence x))
11717 (org-add-prop-inherited x))
11718 (cdar tags-alist))))
11719 (when (and tags org-use-tag-inheritance
11720 (or (not (eq t org-use-tag-inheritance))
11721 org-tags-exclude-from-inheritance))
11722 ;; selective inheritance, remove uninherited ones
11723 (setcdr (car tags-alist)
11724 (org-remove-uniherited-tags (cdar tags-alist))))
11725 (when (and (or (not todo-only)
11726 (and (member todo org-not-done-keywords)
11727 (or (not org-agenda-tags-todo-honor-ignore-options)
11728 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11729 (let ((case-fold-search t)) (eval matcher))
11731 (not (member org-archive-tag tags-list))
11732 ;; we have an archive tag, should we use this anyway?
11733 (or (not org-agenda-skip-archived-trees)
11734 (and (eq action 'agenda) org-agenda-archives-mode))))
11735 (unless (eq action 'sparse-tree) (org-agenda-skip))
11737 ;; select this headline
11739 (cond
11740 ((eq action 'sparse-tree)
11741 (and org-highlight-sparse-tree-matches
11742 (org-get-heading) (match-end 0)
11743 (org-highlight-new-match
11744 (match-beginning 0) (match-beginning 1)))
11745 (org-show-context 'tags-tree))
11746 ((eq action 'agenda)
11747 (setq txt (org-format-agenda-item
11749 (concat
11750 (if (eq org-tags-match-list-sublevels 'indented)
11751 (make-string (1- level) ?.) "")
11752 (org-get-heading))
11753 category
11754 tags-list
11756 priority (org-get-priority txt))
11757 (goto-char lspos)
11758 (setq marker (org-agenda-new-marker))
11759 (org-add-props txt props
11760 'org-marker marker 'org-hd-marker marker 'org-category category
11761 'todo-state todo
11762 'priority priority 'type "tagsmatch")
11763 (push txt rtn))
11764 ((functionp action)
11765 (setq org-map-continue-from nil)
11766 (save-excursion
11767 (setq rtn1 (funcall action))
11768 (push rtn1 rtn)))
11769 (t (error "Invalid action")))
11771 ;; if we are to skip sublevels, jump to end of subtree
11772 (unless org-tags-match-list-sublevels
11773 (org-end-of-subtree t)
11774 (backward-char 1))))
11775 ;; Get the correct position from where to continue
11776 (if org-map-continue-from
11777 (goto-char org-map-continue-from)
11778 (and (= (point) lspos) (end-of-line 1)))))
11779 (when (and (eq action 'sparse-tree)
11780 (not org-sparse-tree-open-archived-trees))
11781 (org-hide-archived-subtrees (point-min) (point-max)))
11782 (nreverse rtn)))
11784 (defun org-remove-uniherited-tags (tags)
11785 "Remove all tags that are not inherited from the list TAGS."
11786 (cond
11787 ((eq org-use-tag-inheritance t)
11788 (if org-tags-exclude-from-inheritance
11789 (org-delete-all org-tags-exclude-from-inheritance tags)
11790 tags))
11791 ((not org-use-tag-inheritance) nil)
11792 ((stringp org-use-tag-inheritance)
11793 (delq nil (mapcar
11794 (lambda (x)
11795 (if (and (string-match org-use-tag-inheritance x)
11796 (not (member x org-tags-exclude-from-inheritance)))
11797 x nil))
11798 tags)))
11799 ((listp org-use-tag-inheritance)
11800 (delq nil (mapcar
11801 (lambda (x)
11802 (if (member x org-use-tag-inheritance) x nil))
11803 tags)))))
11805 (defvar todo-only) ;; dynamically scoped
11807 (defun org-match-sparse-tree (&optional todo-only match)
11808 "Create a sparse tree according to tags string MATCH.
11809 MATCH can contain positive and negative selection of tags, like
11810 \"+WORK+URGENT-WITHBOSS\".
11811 If optional argument TODO-ONLY is non-nil, only select lines that are
11812 also TODO lines."
11813 (interactive "P")
11814 (org-prepare-agenda-buffers (list (current-buffer)))
11815 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11817 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11819 (defvar org-cached-props nil)
11820 (defun org-cached-entry-get (pom property)
11821 (if (or (eq t org-use-property-inheritance)
11822 (and (stringp org-use-property-inheritance)
11823 (string-match org-use-property-inheritance property))
11824 (and (listp org-use-property-inheritance)
11825 (member property org-use-property-inheritance)))
11826 ;; Caching is not possible, check it directly
11827 (org-entry-get pom property 'inherit)
11828 ;; Get all properties, so that we can do complicated checks easily
11829 (cdr (assoc property (or org-cached-props
11830 (setq org-cached-props
11831 (org-entry-properties pom)))))))
11833 (defun org-global-tags-completion-table (&optional files)
11834 "Return the list of all tags in all agenda buffer/files."
11835 (save-excursion
11836 (org-uniquify
11837 (delq nil
11838 (apply 'append
11839 (mapcar
11840 (lambda (file)
11841 (set-buffer (find-file-noselect file))
11842 (append (org-get-buffer-tags)
11843 (mapcar (lambda (x) (if (stringp (car-safe x))
11844 (list (car-safe x)) nil))
11845 org-tag-alist)))
11846 (if (and files (car files))
11847 files
11848 (org-agenda-files))))))))
11850 (defun org-make-tags-matcher (match)
11851 "Create the TAGS//TODO matcher form for the selection string MATCH."
11852 ;; todo-only is scoped dynamically into this function, and the function
11853 ;; may change it if the matcher asks for it.
11854 (unless match
11855 ;; Get a new match request, with completion
11856 (let ((org-last-tags-completion-table
11857 (org-global-tags-completion-table)))
11858 (setq match (org-completing-read-no-i
11859 "Match: " 'org-tags-completion-function nil nil nil
11860 'org-tags-history))))
11862 ;; Parse the string and create a lisp form
11863 (let ((match0 match)
11864 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11865 minus tag mm
11866 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11867 orterms term orlist re-p str-p level-p level-op time-p
11868 prop-p pn pv po cat-p gv rest)
11869 (if (string-match "/+" match)
11870 ;; match contains also a todo-matching request
11871 (progn
11872 (setq tagsmatch (substring match 0 (match-beginning 0))
11873 todomatch (substring match (match-end 0)))
11874 (if (string-match "^!" todomatch)
11875 (setq todo-only t todomatch (substring todomatch 1)))
11876 (if (string-match "^\\s-*$" todomatch)
11877 (setq todomatch nil)))
11878 ;; only matching tags
11879 (setq tagsmatch match todomatch nil))
11881 ;; Make the tags matcher
11882 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11883 (setq tagsmatcher t)
11884 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11885 (while (setq term (pop orterms))
11886 (while (and (equal (substring term -1) "\\") orterms)
11887 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11888 (while (string-match re term)
11889 (setq rest (substring term (match-end 0))
11890 minus (and (match-end 1)
11891 (equal (match-string 1 term) "-"))
11892 tag (match-string 2 term)
11893 re-p (equal (string-to-char tag) ?{)
11894 level-p (match-end 4)
11895 prop-p (match-end 5)
11896 mm (cond
11897 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11898 (level-p
11899 (setq level-op (org-op-to-function (match-string 3 term)))
11900 `(,level-op level ,(string-to-number
11901 (match-string 4 term))))
11902 (prop-p
11903 (setq pn (match-string 5 term)
11904 po (match-string 6 term)
11905 pv (match-string 7 term)
11906 cat-p (equal pn "CATEGORY")
11907 re-p (equal (string-to-char pv) ?{)
11908 str-p (equal (string-to-char pv) ?\")
11909 time-p (save-match-data
11910 (string-match "^\"[[<].*[]>]\"$" pv))
11911 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11912 (if time-p (setq pv (org-matcher-time pv)))
11913 (setq po (org-op-to-function po (if time-p 'time str-p)))
11914 (cond
11915 ((equal pn "CATEGORY")
11916 (setq gv '(get-text-property (point) 'org-category)))
11917 ((equal pn "TODO")
11918 (setq gv 'todo))
11920 (setq gv `(org-cached-entry-get nil ,pn))))
11921 (if re-p
11922 (if (eq po 'org<>)
11923 `(not (string-match ,pv (or ,gv "")))
11924 `(string-match ,pv (or ,gv "")))
11925 (if str-p
11926 `(,po (or ,gv "") ,pv)
11927 `(,po (string-to-number (or ,gv ""))
11928 ,(string-to-number pv) ))))
11929 (t `(member ,tag tags-list)))
11930 mm (if minus (list 'not mm) mm)
11931 term rest)
11932 (push mm tagsmatcher))
11933 (push (if (> (length tagsmatcher) 1)
11934 (cons 'and tagsmatcher)
11935 (car tagsmatcher))
11936 orlist)
11937 (setq tagsmatcher nil))
11938 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11939 (setq tagsmatcher
11940 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11941 ;; Make the todo matcher
11942 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11943 (setq todomatcher t)
11944 (setq orterms (org-split-string todomatch "|") orlist nil)
11945 (while (setq term (pop orterms))
11946 (while (string-match re term)
11947 (setq minus (and (match-end 1)
11948 (equal (match-string 1 term) "-"))
11949 kwd (match-string 2 term)
11950 re-p (equal (string-to-char kwd) ?{)
11951 term (substring term (match-end 0))
11952 mm (if re-p
11953 `(string-match ,(substring kwd 1 -1) todo)
11954 (list 'equal 'todo kwd))
11955 mm (if minus (list 'not mm) mm))
11956 (push mm todomatcher))
11957 (push (if (> (length todomatcher) 1)
11958 (cons 'and todomatcher)
11959 (car todomatcher))
11960 orlist)
11961 (setq todomatcher nil))
11962 (setq todomatcher (if (> (length orlist) 1)
11963 (cons 'or orlist) (car orlist))))
11965 ;; Return the string and lisp forms of the matcher
11966 (setq matcher (if todomatcher
11967 (list 'and tagsmatcher todomatcher)
11968 tagsmatcher))
11969 (cons match0 matcher)))
11971 (defun org-op-to-function (op &optional stringp)
11972 "Turn an operator into the appropriate function."
11973 (setq op
11974 (cond
11975 ((equal op "<" ) '(< string< org-time<))
11976 ((equal op ">" ) '(> org-string> org-time>))
11977 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11978 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11979 ((member op '("=" "==")) '(= string= org-time=))
11980 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11981 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11983 (defun org<> (a b) (not (= a b)))
11984 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11985 (defun org-string>= (a b) (not (string< a b)))
11986 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11987 (defun org-string<> (a b) (not (string= a b)))
11988 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11989 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11990 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11991 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11992 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11993 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11994 (defun org-2ft (s)
11995 "Convert S to a floating point time.
11996 If S is already a number, just return it. If it is a string, parse
11997 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11998 (cond
11999 ((numberp s) s)
12000 ((stringp s)
12001 (condition-case nil
12002 (float-time (apply 'encode-time (org-parse-time-string s)))
12003 (error 0.)))
12004 (t 0.)))
12006 (defun org-time-today ()
12007 "Time in seconds today at 0:00.
12008 Returns the float number of seconds since the beginning of the
12009 epoch to the beginning of today (00:00)."
12010 (float-time (apply 'encode-time
12011 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12013 (defun org-matcher-time (s)
12014 "Interpret a time comparison value."
12015 (save-match-data
12016 (cond
12017 ((string= s "<now>") (float-time))
12018 ((string= s "<today>") (org-time-today))
12019 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12020 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12021 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12022 (+ (org-time-today)
12023 (* (string-to-number (match-string 1 s))
12024 (cdr (assoc (match-string 2 s)
12025 '(("d" . 86400.0) ("w" . 604800.0)
12026 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12027 (t (org-2ft s)))))
12029 (defun org-match-any-p (re list)
12030 "Does re match any element of list?"
12031 (setq list (mapcar (lambda (x) (string-match re x)) list))
12032 (delq nil list))
12034 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12035 (defvar org-tags-overlay (make-overlay 1 1))
12036 (org-detach-overlay org-tags-overlay)
12038 (defun org-get-local-tags-at (&optional pos)
12039 "Get a list of tags defined in the current headline."
12040 (org-get-tags-at pos 'local))
12042 (defun org-get-local-tags ()
12043 "Get a list of tags defined in the current headline."
12044 (org-get-tags-at nil 'local))
12046 (defun org-get-tags-at (&optional pos local)
12047 "Get a list of all headline tags applicable at POS.
12048 POS defaults to point. If tags are inherited, the list contains
12049 the targets in the same sequence as the headlines appear, i.e.
12050 the tags of the current headline come last.
12051 When LOCAL is non-nil, only return tags from the current headline,
12052 ignore inherited ones."
12053 (interactive)
12054 (if (and org-trust-scanner-tags
12055 (or (not pos) (equal pos (point)))
12056 (not local))
12057 org-scanner-tags
12058 (let (tags ltags lastpos parent)
12059 (save-excursion
12060 (save-restriction
12061 (widen)
12062 (goto-char (or pos (point)))
12063 (save-match-data
12064 (catch 'done
12065 (condition-case nil
12066 (progn
12067 (org-back-to-heading t)
12068 (while (not (equal lastpos (point)))
12069 (setq lastpos (point))
12070 (when (looking-at
12071 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
12072 (setq ltags (org-split-string
12073 (org-match-string-no-properties 1) ":"))
12074 (when parent
12075 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12076 (setq tags (append
12077 (if parent
12078 (org-remove-uniherited-tags ltags)
12079 ltags)
12080 tags)))
12081 (or org-use-tag-inheritance (throw 'done t))
12082 (if local (throw 'done t))
12083 (or (org-up-heading-safe) (error nil))
12084 (setq parent t)))
12085 (error nil)))))
12086 (append (org-remove-uniherited-tags org-file-tags) tags)))))
12088 (defun org-add-prop-inherited (s)
12089 (add-text-properties 0 (length s) '(inherited t) s)
12092 (defun org-toggle-tag (tag &optional onoff)
12093 "Toggle the tag TAG for the current line.
12094 If ONOFF is `on' or `off', don't toggle but set to this state."
12095 (let (res current)
12096 (save-excursion
12097 (org-back-to-heading t)
12098 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
12099 (point-at-eol) t)
12100 (progn
12101 (setq current (match-string 1))
12102 (replace-match ""))
12103 (setq current ""))
12104 (setq current (nreverse (org-split-string current ":")))
12105 (cond
12106 ((eq onoff 'on)
12107 (setq res t)
12108 (or (member tag current) (push tag current)))
12109 ((eq onoff 'off)
12110 (or (not (member tag current)) (setq current (delete tag current))))
12111 (t (if (member tag current)
12112 (setq current (delete tag current))
12113 (setq res t)
12114 (push tag current))))
12115 (end-of-line 1)
12116 (if current
12117 (progn
12118 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12119 (org-set-tags nil t))
12120 (delete-horizontal-space))
12121 (run-hooks 'org-after-tags-change-hook))
12122 res))
12124 (defun org-align-tags-here (to-col)
12125 ;; Assumes that this is a headline
12126 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12127 (beginning-of-line 1)
12128 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12129 (< pos (match-beginning 2)))
12130 (progn
12131 (setq tags-l (- (match-end 2) (match-beginning 2)))
12132 (goto-char (match-beginning 1))
12133 (insert " ")
12134 (delete-region (point) (1+ (match-beginning 2)))
12135 (setq ncol (max (1+ (current-column))
12136 (1+ col)
12137 (if (> to-col 0)
12138 to-col
12139 (- (abs to-col) tags-l))))
12140 (setq p (point))
12141 (insert (make-string (- ncol (current-column)) ?\ ))
12142 (setq ncol (current-column))
12143 (when indent-tabs-mode (tabify p (point-at-eol)))
12144 (org-move-to-column (min ncol col) t))
12145 (goto-char pos))))
12147 (defun org-set-tags-command (&optional arg just-align)
12148 "Call the set-tags command for the current entry."
12149 (interactive "P")
12150 (if (org-on-heading-p)
12151 (org-set-tags arg just-align)
12152 (save-excursion
12153 (org-back-to-heading t)
12154 (org-set-tags arg just-align))))
12156 (defun org-set-tags-to (data)
12157 "Set the tags of the current entry to DATA, replacing the current tags.
12158 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12159 If DATA is nil or the empty string, any tags will be removed."
12160 (interactive "sTags: ")
12161 (setq data
12162 (cond
12163 ((eq data nil) "")
12164 ((equal data "") "")
12165 ((stringp data)
12166 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12167 ":"))
12168 ((listp data)
12169 (concat ":" (mapconcat 'identity data ":") ":"))
12170 (t nil)))
12171 (when data
12172 (save-excursion
12173 (org-back-to-heading t)
12174 (when (looking-at org-complex-heading-regexp)
12175 (if (match-end 5)
12176 (progn
12177 (goto-char (match-beginning 5))
12178 (insert data)
12179 (delete-region (point) (point-at-eol))
12180 (org-set-tags nil 'align))
12181 (goto-char (point-at-eol))
12182 (insert " " data)
12183 (org-set-tags nil 'align)))
12184 (beginning-of-line 1)
12185 (if (looking-at ".*?\\([ \t]+\\)$")
12186 (delete-region (match-beginning 1) (match-end 1))))))
12188 (defun org-align-all-tags ()
12189 "Align the tags i all headings."
12190 (interactive)
12191 (save-excursion
12192 (or (ignore-errors (org-back-to-heading t))
12193 (outline-next-heading))
12194 (if (org-on-heading-p)
12195 (org-set-tags t)
12196 (message "No headings"))))
12198 (defun org-set-tags (&optional arg just-align)
12199 "Set the tags for the current headline.
12200 With prefix ARG, realign all tags in headings in the current buffer."
12201 (interactive "P")
12202 (let* ((re (concat "^" outline-regexp))
12203 (current (org-get-tags-string))
12204 (col (current-column))
12205 (org-setting-tags t)
12206 table current-tags inherited-tags ; computed below when needed
12207 tags p0 c0 c1 rpl)
12208 (if arg
12209 (save-excursion
12210 (goto-char (point-min))
12211 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12212 (while (re-search-forward re nil t)
12213 (org-set-tags nil t)
12214 (end-of-line 1)))
12215 (message "All tags realigned to column %d" org-tags-column))
12216 (if just-align
12217 (setq tags current)
12218 ;; Get a new set of tags from the user
12219 (save-excursion
12220 (setq table (append org-tag-persistent-alist
12221 (or org-tag-alist (org-get-buffer-tags))
12222 (and org-complete-tags-always-offer-all-agenda-tags
12223 (org-global-tags-completion-table (org-agenda-files))))
12224 org-last-tags-completion-table table
12225 current-tags (org-split-string current ":")
12226 inherited-tags (nreverse
12227 (nthcdr (length current-tags)
12228 (nreverse (org-get-tags-at))))
12229 tags
12230 (if (or (eq t org-use-fast-tag-selection)
12231 (and org-use-fast-tag-selection
12232 (delq nil (mapcar 'cdr table))))
12233 (org-fast-tag-selection
12234 current-tags inherited-tags table
12235 (if org-fast-tag-selection-include-todo org-todo-key-alist))
12236 (let ((org-add-colon-after-tag-completion t))
12237 (org-trim
12238 (org-without-partial-completion
12239 (org-icompleting-read "Tags: " 'org-tags-completion-function
12240 nil nil current 'org-tags-history)))))))
12241 (while (string-match "[-+&]+" tags)
12242 ;; No boolean logic, just a list
12243 (setq tags (replace-match ":" t t tags))))
12245 (if org-tags-sort-function
12246 (setq tags (mapconcat 'identity
12247 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
12248 org-tags-sort-function) ":")))
12250 (if (string-match "\\`[\t ]*\\'" tags)
12251 (setq tags "")
12252 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12253 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12255 ;; Insert new tags at the correct column
12256 (beginning-of-line 1)
12257 (cond
12258 ((and (equal current "") (equal tags "")))
12259 ((re-search-forward
12260 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12261 (point-at-eol) t)
12262 (if (equal tags "")
12263 (setq rpl "")
12264 (goto-char (match-beginning 0))
12265 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
12266 (1+ (point)) (point))
12267 c1 (max (1+ c0) (if (> org-tags-column 0)
12268 org-tags-column
12269 (- (- org-tags-column) (length tags))))
12270 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12271 (replace-match rpl t t)
12272 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
12273 tags)
12274 (t (error "Tags alignment failed")))
12275 (org-move-to-column col)
12276 (unless just-align
12277 (run-hooks 'org-after-tags-change-hook)))))
12279 (defun org-change-tag-in-region (beg end tag off)
12280 "Add or remove TAG for each entry in the region.
12281 This works in the agenda, and also in an org-mode buffer."
12282 (interactive
12283 (list (region-beginning) (region-end)
12284 (let ((org-last-tags-completion-table
12285 (if (org-mode-p)
12286 (org-get-buffer-tags)
12287 (org-global-tags-completion-table))))
12288 (org-icompleting-read
12289 "Tag: " 'org-tags-completion-function nil nil nil
12290 'org-tags-history))
12291 (progn
12292 (message "[s]et or [r]emove? ")
12293 (equal (read-char-exclusive) ?r))))
12294 (if (fboundp 'deactivate-mark) (deactivate-mark))
12295 (let ((agendap (equal major-mode 'org-agenda-mode))
12296 l1 l2 m buf pos newhead (cnt 0))
12297 (goto-char end)
12298 (setq l2 (1- (org-current-line)))
12299 (goto-char beg)
12300 (setq l1 (org-current-line))
12301 (loop for l from l1 to l2 do
12302 (org-goto-line l)
12303 (setq m (get-text-property (point) 'org-hd-marker))
12304 (when (or (and (org-mode-p) (org-on-heading-p))
12305 (and agendap m))
12306 (setq buf (if agendap (marker-buffer m) (current-buffer))
12307 pos (if agendap m (point)))
12308 (with-current-buffer buf
12309 (save-excursion
12310 (save-restriction
12311 (goto-char pos)
12312 (setq cnt (1+ cnt))
12313 (org-toggle-tag tag (if off 'off 'on))
12314 (setq newhead (org-get-heading)))))
12315 (and agendap (org-agenda-change-all-lines newhead m))))
12316 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12318 (defun org-tags-completion-function (string predicate &optional flag)
12319 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12320 (confirm (lambda (x) (stringp (car x)))))
12321 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12322 (setq s1 (match-string 1 string)
12323 s2 (match-string 2 string))
12324 (setq s1 "" s2 string))
12325 (cond
12326 ((eq flag nil)
12327 ;; try completion
12328 (setq rtn (try-completion s2 ctable confirm))
12329 (if (stringp rtn)
12330 (setq rtn
12331 (concat s1 s2 (substring rtn (length s2))
12332 (if (and org-add-colon-after-tag-completion
12333 (assoc rtn ctable))
12334 ":" ""))))
12335 rtn)
12336 ((eq flag t)
12337 ;; all-completions
12338 (all-completions s2 ctable confirm)
12340 ((eq flag 'lambda)
12341 ;; exact match?
12342 (assoc s2 ctable)))
12345 (defun org-fast-tag-insert (kwd tags face &optional end)
12346 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12347 (insert (format "%-12s" (concat kwd ":"))
12348 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12349 (or end "")))
12351 (defun org-fast-tag-show-exit (flag)
12352 (save-excursion
12353 (org-goto-line 3)
12354 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12355 (replace-match ""))
12356 (when flag
12357 (end-of-line 1)
12358 (org-move-to-column (- (window-width) 19) t)
12359 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12361 (defun org-set-current-tags-overlay (current prefix)
12362 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12363 (if (featurep 'xemacs)
12364 (org-overlay-display org-tags-overlay (concat prefix s)
12365 'secondary-selection)
12366 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12367 (org-overlay-display org-tags-overlay (concat prefix s)))))
12369 (defvar org-last-tag-selection-key nil)
12370 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12371 "Fast tag selection with single keys.
12372 CURRENT is the current list of tags in the headline, INHERITED is the
12373 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12374 possibly with grouping information. TODO-TABLE is a similar table with
12375 TODO keywords, should these have keys assigned to them.
12376 If the keys are nil, a-z are automatically assigned.
12377 Returns the new tags string, or nil to not change the current settings."
12378 (let* ((fulltable (append table todo-table))
12379 (maxlen (apply 'max (mapcar
12380 (lambda (x)
12381 (if (stringp (car x)) (string-width (car x)) 0))
12382 fulltable)))
12383 (buf (current-buffer))
12384 (expert (eq org-fast-tag-selection-single-key 'expert))
12385 (buffer-tags nil)
12386 (fwidth (+ maxlen 3 1 3))
12387 (ncol (/ (- (window-width) 4) fwidth))
12388 (i-face 'org-done)
12389 (c-face 'org-todo)
12390 tg cnt e c char c1 c2 ntable tbl rtn
12391 ov-start ov-end ov-prefix
12392 (exit-after-next org-fast-tag-selection-single-key)
12393 (done-keywords org-done-keywords)
12394 groups ingroup)
12395 (save-excursion
12396 (beginning-of-line 1)
12397 (if (looking-at
12398 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12399 (setq ov-start (match-beginning 1)
12400 ov-end (match-end 1)
12401 ov-prefix "")
12402 (setq ov-start (1- (point-at-eol))
12403 ov-end (1+ ov-start))
12404 (skip-chars-forward "^\n\r")
12405 (setq ov-prefix
12406 (concat
12407 (buffer-substring (1- (point)) (point))
12408 (if (> (current-column) org-tags-column)
12410 (make-string (- org-tags-column (current-column)) ?\ ))))))
12411 (move-overlay org-tags-overlay ov-start ov-end)
12412 (save-window-excursion
12413 (if expert
12414 (set-buffer (get-buffer-create " *Org tags*"))
12415 (delete-other-windows)
12416 (split-window-vertically)
12417 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12418 (erase-buffer)
12419 (org-set-local 'org-done-keywords done-keywords)
12420 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12421 (org-fast-tag-insert "Current" current c-face "\n\n")
12422 (org-fast-tag-show-exit exit-after-next)
12423 (org-set-current-tags-overlay current ov-prefix)
12424 (setq tbl fulltable char ?a cnt 0)
12425 (while (setq e (pop tbl))
12426 (cond
12427 ((equal (car e) :startgroup)
12428 (push '() groups) (setq ingroup t)
12429 (when (not (= cnt 0))
12430 (setq cnt 0)
12431 (insert "\n"))
12432 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12433 ((equal (car e) :endgroup)
12434 (setq ingroup nil cnt 0)
12435 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12436 ((equal e '(:newline))
12437 (when (not (= cnt 0))
12438 (setq cnt 0)
12439 (insert "\n")
12440 (setq e (car tbl))
12441 (while (equal (car tbl) '(:newline))
12442 (insert "\n")
12443 (setq tbl (cdr tbl)))))
12445 (setq tg (copy-sequence (car e)) c2 nil)
12446 (if (cdr e)
12447 (setq c (cdr e))
12448 ;; automatically assign a character.
12449 (setq c1 (string-to-char
12450 (downcase (substring
12451 tg (if (= (string-to-char tg) ?@) 1 0)))))
12452 (if (or (rassoc c1 ntable) (rassoc c1 table))
12453 (while (or (rassoc char ntable) (rassoc char table))
12454 (setq char (1+ char)))
12455 (setq c2 c1))
12456 (setq c (or c2 char)))
12457 (if ingroup (push tg (car groups)))
12458 (setq tg (org-add-props tg nil 'face
12459 (cond
12460 ((not (assoc tg table))
12461 (org-get-todo-face tg))
12462 ((member tg current) c-face)
12463 ((member tg inherited) i-face)
12464 (t nil))))
12465 (if (and (= cnt 0) (not ingroup)) (insert " "))
12466 (insert "[" c "] " tg (make-string
12467 (- fwidth 4 (length tg)) ?\ ))
12468 (push (cons tg c) ntable)
12469 (when (= (setq cnt (1+ cnt)) ncol)
12470 (insert "\n")
12471 (if ingroup (insert " "))
12472 (setq cnt 0)))))
12473 (setq ntable (nreverse ntable))
12474 (insert "\n")
12475 (goto-char (point-min))
12476 (if (not expert) (org-fit-window-to-buffer))
12477 (setq rtn
12478 (catch 'exit
12479 (while t
12480 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12481 (if (not groups) "no " "")
12482 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12483 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12484 (setq org-last-tag-selection-key c)
12485 (cond
12486 ((= c ?\r) (throw 'exit t))
12487 ((= c ?!)
12488 (setq groups (not groups))
12489 (goto-char (point-min))
12490 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12491 ((= c ?\C-c)
12492 (if (not expert)
12493 (org-fast-tag-show-exit
12494 (setq exit-after-next (not exit-after-next)))
12495 (setq expert nil)
12496 (delete-other-windows)
12497 (split-window-vertically)
12498 (org-switch-to-buffer-other-window " *Org tags*")
12499 (org-fit-window-to-buffer)))
12500 ((or (= c ?\C-g)
12501 (and (= c ?q) (not (rassoc c ntable))))
12502 (org-detach-overlay org-tags-overlay)
12503 (setq quit-flag t))
12504 ((= c ?\ )
12505 (setq current nil)
12506 (if exit-after-next (setq exit-after-next 'now)))
12507 ((= c ?\t)
12508 (condition-case nil
12509 (setq tg (org-icompleting-read
12510 "Tag: "
12511 (or buffer-tags
12512 (with-current-buffer buf
12513 (org-get-buffer-tags)))))
12514 (quit (setq tg "")))
12515 (when (string-match "\\S-" tg)
12516 (add-to-list 'buffer-tags (list tg))
12517 (if (member tg current)
12518 (setq current (delete tg current))
12519 (push tg current)))
12520 (if exit-after-next (setq exit-after-next 'now)))
12521 ((setq e (rassoc c todo-table) tg (car e))
12522 (with-current-buffer buf
12523 (save-excursion (org-todo tg)))
12524 (if exit-after-next (setq exit-after-next 'now)))
12525 ((setq e (rassoc c ntable) tg (car e))
12526 (if (member tg current)
12527 (setq current (delete tg current))
12528 (loop for g in groups do
12529 (if (member tg g)
12530 (mapc (lambda (x)
12531 (setq current (delete x current)))
12532 g)))
12533 (push tg current))
12534 (if exit-after-next (setq exit-after-next 'now))))
12536 ;; Create a sorted list
12537 (setq current
12538 (sort current
12539 (lambda (a b)
12540 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12541 (if (eq exit-after-next 'now) (throw 'exit t))
12542 (goto-char (point-min))
12543 (beginning-of-line 2)
12544 (delete-region (point) (point-at-eol))
12545 (org-fast-tag-insert "Current" current c-face)
12546 (org-set-current-tags-overlay current ov-prefix)
12547 (while (re-search-forward
12548 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12549 (setq tg (match-string 1))
12550 (add-text-properties
12551 (match-beginning 1) (match-end 1)
12552 (list 'face
12553 (cond
12554 ((member tg current) c-face)
12555 ((member tg inherited) i-face)
12556 (t (get-text-property (match-beginning 1) 'face))))))
12557 (goto-char (point-min)))))
12558 (org-detach-overlay org-tags-overlay)
12559 (if rtn
12560 (mapconcat 'identity current ":")
12561 nil))))
12563 (defun org-get-tags-string ()
12564 "Get the TAGS string in the current headline."
12565 (unless (org-on-heading-p t)
12566 (error "Not on a heading"))
12567 (save-excursion
12568 (beginning-of-line 1)
12569 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12570 (org-match-string-no-properties 1)
12571 "")))
12573 (defun org-get-tags ()
12574 "Get the list of tags specified in the current headline."
12575 (org-split-string (org-get-tags-string) ":"))
12577 (defun org-get-buffer-tags ()
12578 "Get a table of all tags used in the buffer, for completion."
12579 (let (tags)
12580 (save-excursion
12581 (goto-char (point-min))
12582 (while (re-search-forward
12583 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12584 (when (equal (char-after (point-at-bol 0)) ?*)
12585 (mapc (lambda (x) (add-to-list 'tags x))
12586 (org-split-string (org-match-string-no-properties 1) ":")))))
12587 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12588 (mapcar 'list tags)))
12590 ;;;; The mapping API
12592 ;;;###autoload
12593 (defun org-map-entries (func &optional match scope &rest skip)
12594 "Call FUNC at each headline selected by MATCH in SCOPE.
12596 FUNC is a function or a lisp form. The function will be called without
12597 arguments, with the cursor positioned at the beginning of the headline.
12598 The return values of all calls to the function will be collected and
12599 returned as a list.
12601 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12602 does not need to preserve point. After evaluation, the cursor will be
12603 moved to the end of the line (presumably of the headline of the
12604 processed entry) and search continues from there. Under some
12605 circumstances, this may not produce the wanted results. For example,
12606 if you have removed (e.g. archived) the current (sub)tree it could
12607 mean that the next entry will be skipped entirely. In such cases, you
12608 can specify the position from where search should continue by making
12609 FUNC set the variable `org-map-continue-from' to the desired buffer
12610 position.
12612 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12613 Only headlines that are matched by this query will be considered during
12614 the iteration. When MATCH is nil or t, all headlines will be
12615 visited by the iteration.
12617 SCOPE determines the scope of this command. It can be any of:
12619 nil The current buffer, respecting the restriction if any
12620 tree The subtree started with the entry at point
12621 file The current buffer, without restriction
12622 file-with-archives
12623 The current buffer, and any archives associated with it
12624 agenda All agenda files
12625 agenda-with-archives
12626 All agenda files with any archive files associated with them
12627 \(file1 file2 ...)
12628 If this is a list, all files in the list will be scanned
12630 The remaining args are treated as settings for the skipping facilities of
12631 the scanner. The following items can be given here:
12633 archive skip trees with the archive tag.
12634 comment skip trees with the COMMENT keyword
12635 function or Emacs Lisp form:
12636 will be used as value for `org-agenda-skip-function', so whenever
12637 the function returns t, FUNC will not be called for that
12638 entry and search will continue from the point where the
12639 function leaves it.
12641 If your function needs to retrieve the tags including inherited tags
12642 at the *current* entry, you can use the value of the variable
12643 `org-scanner-tags' which will be much faster than getting the value
12644 with `org-get-tags-at'. If your function gets properties with
12645 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12646 to t around the call to `org-entry-properties' to get the same speedup.
12647 Note that if your function moves around to retrieve tags and properties at
12648 a *different* entry, you cannot use these techniques."
12649 (let* ((org-agenda-archives-mode nil) ; just to make sure
12650 (org-agenda-skip-archived-trees (memq 'archive skip))
12651 (org-agenda-skip-comment-trees (memq 'comment skip))
12652 (org-agenda-skip-function
12653 (car (org-delete-all '(comment archive) skip)))
12654 (org-tags-match-list-sublevels t)
12655 matcher file res
12656 org-todo-keywords-for-agenda
12657 org-done-keywords-for-agenda
12658 org-todo-keyword-alist-for-agenda
12659 org-drawers-for-agenda
12660 org-tag-alist-for-agenda)
12662 (cond
12663 ((eq match t) (setq matcher t))
12664 ((eq match nil) (setq matcher t))
12665 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12667 (save-excursion
12668 (save-restriction
12669 (when (eq scope 'tree)
12670 (org-back-to-heading t)
12671 (org-narrow-to-subtree)
12672 (setq scope nil))
12674 (if (not scope)
12675 (progn
12676 (org-prepare-agenda-buffers
12677 (list (buffer-file-name (current-buffer))))
12678 (setq res (org-scan-tags func matcher)))
12679 ;; Get the right scope
12680 (cond
12681 ((and scope (listp scope) (symbolp (car scope)))
12682 (setq scope (eval scope)))
12683 ((eq scope 'agenda)
12684 (setq scope (org-agenda-files t)))
12685 ((eq scope 'agenda-with-archives)
12686 (setq scope (org-agenda-files t))
12687 (setq scope (org-add-archive-files scope)))
12688 ((eq scope 'file)
12689 (setq scope (list (buffer-file-name))))
12690 ((eq scope 'file-with-archives)
12691 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12692 (org-prepare-agenda-buffers scope)
12693 (while (setq file (pop scope))
12694 (with-current-buffer (org-find-base-buffer-visiting file)
12695 (save-excursion
12696 (save-restriction
12697 (widen)
12698 (goto-char (point-min))
12699 (setq res (append res (org-scan-tags func matcher))))))))))
12700 res))
12702 ;;;; Properties
12704 ;;; Setting and retrieving properties
12706 (defconst org-special-properties
12707 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12708 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
12709 "The special properties valid in Org-mode.
12711 These are properties that are not defined in the property drawer,
12712 but in some other way.")
12714 (defconst org-default-properties
12715 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12716 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12717 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12718 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12719 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
12720 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
12721 "Some properties that are used by Org-mode for various purposes.
12722 Being in this list makes sure that they are offered for completion.")
12724 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12725 "Regular expression matching the first line of a property drawer.")
12727 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12728 "Regular expression matching the last line of a property drawer.")
12730 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12731 "Regular expression matching the first line of a property drawer.")
12733 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12734 "Regular expression matching the first line of a property drawer.")
12736 (defconst org-property-drawer-re
12737 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12738 org-property-end-re "\\)\n?")
12739 "Matches an entire property drawer.")
12741 (defconst org-clock-drawer-re
12742 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12743 org-property-end-re "\\)\n?")
12744 "Matches an entire clock drawer.")
12746 (defun org-property-action ()
12747 "Do an action on properties."
12748 (interactive)
12749 (let (c)
12750 (org-at-property-p)
12751 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12752 (setq c (read-char-exclusive))
12753 (cond
12754 ((equal c ?s)
12755 (call-interactively 'org-set-property))
12756 ((equal c ?d)
12757 (call-interactively 'org-delete-property))
12758 ((equal c ?D)
12759 (call-interactively 'org-delete-property-globally))
12760 ((equal c ?c)
12761 (call-interactively 'org-compute-property-at-point))
12762 (t (error "No such property action %c" c)))))
12764 (defun org-set-effort (&optional value)
12765 "Set the effort property of the current entry.
12766 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12767 allowed value."
12768 (interactive "P")
12769 (if (equal value 0) (setq value 10))
12770 (let* ((completion-ignore-case t)
12771 (prop org-effort-property)
12772 (cur (org-entry-get nil prop))
12773 (allowed (org-property-get-allowed-values nil prop 'table))
12774 (existing (mapcar 'list (org-property-values prop)))
12776 (val (cond
12777 ((stringp value) value)
12778 ((and allowed (integerp value))
12779 (or (car (nth (1- value) allowed))
12780 (car (org-last allowed))))
12781 (allowed
12782 (message "Select 1-9,0, [RET%s]: %s"
12783 (if cur (concat "=" cur) "")
12784 (mapconcat 'car allowed " "))
12785 (setq rpl (read-char-exclusive))
12786 (if (equal rpl ?\r)
12788 (setq rpl (- rpl ?0))
12789 (if (equal rpl 0) (setq rpl 10))
12790 (if (and (> rpl 0) (<= rpl (length allowed)))
12791 (car (nth (1- rpl) allowed))
12792 (org-completing-read "Effort: " allowed nil))))
12794 (let (org-completion-use-ido org-completion-use-iswitchb)
12795 (org-completing-read
12796 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12797 (concat "[" cur "]") "")
12798 ": ")
12799 existing nil nil "" nil cur))))))
12800 (unless (equal (org-entry-get nil prop) val)
12801 (org-entry-put nil prop val))
12802 (message "%s is now %s" prop val)))
12804 (defun org-at-property-p ()
12805 "Is cursor inside a property drawer?"
12806 (save-excursion
12807 (beginning-of-line 1)
12808 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
12809 (let ((match (match-data)) ;; Keep match-data for use by calling
12810 (p (point)) ;; procedures.
12811 (range (unless (org-before-first-heading-p)
12812 (org-get-property-block))))
12813 (prog1 (and range (<= (car range) p) (< p (cdr range)))
12814 (set-match-data match))))))
12816 (defun org-get-property-block (&optional beg end force)
12817 "Return the (beg . end) range of the body of the property drawer.
12818 BEG and END can be beginning and end of subtree, if not given
12819 they will be found.
12820 If the drawer does not exist and FORCE is non-nil, create the drawer."
12821 (catch 'exit
12822 (save-excursion
12823 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12824 (end (or end (progn (outline-next-heading) (point)))))
12825 (goto-char beg)
12826 (if (re-search-forward org-property-start-re end t)
12827 (setq beg (1+ (match-end 0)))
12828 (if force
12829 (save-excursion
12830 (org-insert-property-drawer)
12831 (setq end (progn (outline-next-heading) (point))))
12832 (throw 'exit nil))
12833 (goto-char beg)
12834 (if (re-search-forward org-property-start-re end t)
12835 (setq beg (1+ (match-end 0)))))
12836 (if (re-search-forward org-property-end-re end t)
12837 (setq end (match-beginning 0))
12838 (or force (throw 'exit nil))
12839 (goto-char beg)
12840 (setq end beg)
12841 (org-indent-line-function)
12842 (insert ":END:\n"))
12843 (cons beg end)))))
12845 (defun org-entry-properties (&optional pom which specific)
12846 "Get all properties of the entry at point-or-marker POM.
12847 This includes the TODO keyword, the tags, time strings for deadline,
12848 scheduled, and clocking, and any additional properties defined in the
12849 entry. The return value is an alist, keys may occur multiple times
12850 if the property key was used several times.
12851 POM may also be nil, in which case the current entry is used.
12852 If WHICH is nil or `all', get all properties. If WHICH is
12853 `special' or `standard', only get that subclass. If WHICH
12854 is a string only get exactly this property. Specific can be a string, the
12855 specific property we are interested in. Specifying it can speed
12856 things up because then unnecessary parsing is avoided."
12857 (setq which (or which 'all))
12858 (org-with-point-at pom
12859 (let ((clockstr (substring org-clock-string 0 -1))
12860 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
12861 (case-fold-search nil)
12862 beg end range props sum-props key value string clocksum)
12863 (save-excursion
12864 (when (condition-case nil
12865 (and (org-mode-p) (org-back-to-heading t))
12866 (error nil))
12867 (setq beg (point))
12868 (setq sum-props (get-text-property (point) 'org-summaries))
12869 (setq clocksum (get-text-property (point) :org-clock-minutes))
12870 (outline-next-heading)
12871 (setq end (point))
12872 (when (memq which '(all special))
12873 ;; Get the special properties, like TODO and tags
12874 (goto-char beg)
12875 (when (and (or (not specific) (string= specific "TODO"))
12876 (looking-at org-todo-line-regexp) (match-end 2))
12877 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12878 (when (and (or (not specific) (string= specific "PRIORITY"))
12879 (looking-at org-priority-regexp))
12880 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12881 (when (and (or (not specific) (string= specific "TAGS"))
12882 (setq value (org-get-tags-string))
12883 (string-match "\\S-" value))
12884 (push (cons "TAGS" value) props))
12885 (when (and (or (not specific) (string= specific "ALLTAGS"))
12886 (setq value (org-get-tags-at)))
12887 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
12888 ":"))
12889 props))
12890 (when (or (not specific) (string= specific "BLOCKED"))
12891 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
12892 (when (or (not specific)
12893 (member specific org-all-time-keywords)
12894 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
12895 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12896 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12897 string (if (equal key clockstr)
12898 (org-no-properties
12899 (org-trim
12900 (buffer-substring
12901 (match-beginning 3) (goto-char (point-at-eol)))))
12902 (substring (org-match-string-no-properties 3) 1 -1)))
12903 (unless key
12904 (if (= (char-after (match-beginning 3)) ?\[)
12905 (setq key "TIMESTAMP_IA")
12906 (setq key "TIMESTAMP")))
12907 (when (or (equal key clockstr) (not (assoc key props)))
12908 (push (cons key string) props))))
12912 (when (memq which '(all standard))
12913 ;; Get the standard properties, like :PROP: ...
12914 (setq range (org-get-property-block beg end))
12915 (when range
12916 (goto-char (car range))
12917 (while (re-search-forward
12918 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12919 (cdr range) t)
12920 (setq key (org-match-string-no-properties 1)
12921 value (org-trim (or (org-match-string-no-properties 2) "")))
12922 (unless (member key excluded)
12923 (push (cons key (or value "")) props)))))
12924 (if clocksum
12925 (push (cons "CLOCKSUM"
12926 (org-columns-number-to-string (/ (float clocksum) 60.)
12927 'add_times))
12928 props))
12929 (unless (assoc "CATEGORY" props)
12930 (setq value (or (org-get-category)
12931 (progn (org-refresh-category-properties)
12932 (org-get-category))))
12933 (push (cons "CATEGORY" value) props))
12934 (append sum-props (nreverse props)))))))
12936 (defun org-entry-get (pom property &optional inherit)
12937 "Get value of PROPERTY for entry at point-or-marker POM.
12938 If INHERIT is non-nil and the entry does not have the property,
12939 then also check higher levels of the hierarchy.
12940 If INHERIT is the symbol `selective', use inheritance only if the setting
12941 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12942 If the property is present but empty, the return value is the empty string.
12943 If the property is not present at all, nil is returned."
12944 (org-with-point-at pom
12945 (if (and inherit (if (eq inherit 'selective)
12946 (org-property-inherit-p property)
12948 (org-entry-get-with-inheritance property)
12949 (if (member property org-special-properties)
12950 ;; We need a special property. Use `org-entry-properties' to
12951 ;; retrieve it, but specify the wanted property
12952 (cdr (assoc property (org-entry-properties nil 'special property)))
12953 (let ((range (org-get-property-block)))
12954 (if (and range
12955 (goto-char (car range))
12956 (re-search-forward
12957 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12958 (cdr range) t))
12959 ;; Found the property, return it.
12960 (if (match-end 1)
12961 (org-match-string-no-properties 1)
12962 "")))))))
12964 (defun org-property-or-variable-value (var &optional inherit)
12965 "Check if there is a property fixing the value of VAR.
12966 If yes, return this value. If not, return the current value of the variable."
12967 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12968 (if (and prop (stringp prop) (string-match "\\S-" prop))
12969 (read prop)
12970 (symbol-value var))))
12972 (defun org-entry-delete (pom property)
12973 "Delete the property PROPERTY from entry at point-or-marker POM."
12974 (org-with-point-at pom
12975 (if (member property org-special-properties)
12976 nil ; cannot delete these properties.
12977 (let ((range (org-get-property-block)))
12978 (if (and range
12979 (goto-char (car range))
12980 (re-search-forward
12981 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12982 (cdr range) t))
12983 (progn
12984 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12986 nil)))))
12988 ;; Multi-values properties are properties that contain multiple values
12989 ;; These values are assumed to be single words, separated by whitespace.
12990 (defun org-entry-add-to-multivalued-property (pom property value)
12991 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12992 (let* ((old (org-entry-get pom property))
12993 (values (and old (org-split-string old "[ \t]"))))
12994 (setq value (org-entry-protect-space value))
12995 (unless (member value values)
12996 (setq values (cons value values))
12997 (org-entry-put pom property
12998 (mapconcat 'identity values " ")))))
13000 (defun org-entry-remove-from-multivalued-property (pom property value)
13001 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13002 (let* ((old (org-entry-get pom property))
13003 (values (and old (org-split-string old "[ \t]"))))
13004 (setq value (org-entry-protect-space value))
13005 (when (member value values)
13006 (setq values (delete value values))
13007 (org-entry-put pom property
13008 (mapconcat 'identity values " ")))))
13010 (defun org-entry-member-in-multivalued-property (pom property value)
13011 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13012 (let* ((old (org-entry-get pom property))
13013 (values (and old (org-split-string old "[ \t]"))))
13014 (setq value (org-entry-protect-space value))
13015 (member value values)))
13017 (defun org-entry-get-multivalued-property (pom property)
13018 "Return a list of values in a multivalued property."
13019 (let* ((value (org-entry-get pom property))
13020 (values (and value (org-split-string value "[ \t]"))))
13021 (mapcar 'org-entry-restore-space values)))
13023 (defun org-entry-put-multivalued-property (pom property &rest values)
13024 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13025 VALUES should be a list of strings. Spaces will be protected."
13026 (org-entry-put pom property
13027 (mapconcat 'org-entry-protect-space values " "))
13028 (let* ((value (org-entry-get pom property))
13029 (values (and value (org-split-string value "[ \t]"))))
13030 (mapcar 'org-entry-restore-space values)))
13032 (defun org-entry-protect-space (s)
13033 "Protect spaces and newline in string S."
13034 (while (string-match " " s)
13035 (setq s (replace-match "%20" t t s)))
13036 (while (string-match "\n" s)
13037 (setq s (replace-match "%0A" t t s)))
13040 (defun org-entry-restore-space (s)
13041 "Restore spaces and newline in string S."
13042 (while (string-match "%20" s)
13043 (setq s (replace-match " " t t s)))
13044 (while (string-match "%0A" s)
13045 (setq s (replace-match "\n" t t s)))
13048 (defvar org-entry-property-inherited-from (make-marker)
13049 "Marker pointing to the entry from where a property was inherited.
13050 Each call to `org-entry-get-with-inheritance' will set this marker to the
13051 location of the entry where the inheritance search matched. If there was
13052 no match, the marker will point nowhere.
13053 Note that also `org-entry-get' calls this function, if the INHERIT flag
13054 is set.")
13056 (defun org-entry-get-with-inheritance (property)
13057 "Get entry property, and search higher levels if not present."
13058 (move-marker org-entry-property-inherited-from nil)
13059 (let (tmp)
13060 (save-excursion
13061 (save-restriction
13062 (widen)
13063 (catch 'ex
13064 (while t
13065 (when (setq tmp (org-entry-get nil property))
13066 (org-back-to-heading t)
13067 (move-marker org-entry-property-inherited-from (point))
13068 (throw 'ex tmp))
13069 (or (org-up-heading-safe) (throw 'ex nil)))))
13070 (or tmp
13071 (cdr (assoc property org-file-properties))
13072 (cdr (assoc property org-global-properties))
13073 (cdr (assoc property org-global-properties-fixed))))))
13075 (defvar org-property-changed-functions nil
13076 "Hook called when the value of a property has changed.
13077 Each hook function should accept two arguments, the name of the property
13078 and the new value.")
13080 (defun org-entry-put (pom property value)
13081 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13082 (org-with-point-at pom
13083 (org-back-to-heading t)
13084 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13085 range)
13086 (cond
13087 ((equal property "TODO")
13088 (when (and (stringp value) (string-match "\\S-" value)
13089 (not (member value org-todo-keywords-1)))
13090 (error "\"%s\" is not a valid TODO state" value))
13091 (if (or (not value)
13092 (not (string-match "\\S-" value)))
13093 (setq value 'none))
13094 (org-todo value)
13095 (org-set-tags nil 'align))
13096 ((equal property "PRIORITY")
13097 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13098 (string-to-char value) ?\ ))
13099 (org-set-tags nil 'align))
13100 ((equal property "SCHEDULED")
13101 (if (re-search-forward org-scheduled-time-regexp end t)
13102 (cond
13103 ((eq value 'earlier) (org-timestamp-change -1 'day))
13104 ((eq value 'later) (org-timestamp-change 1 'day))
13105 (t (call-interactively 'org-schedule)))
13106 (call-interactively 'org-schedule)))
13107 ((equal property "DEADLINE")
13108 (if (re-search-forward org-deadline-time-regexp end t)
13109 (cond
13110 ((eq value 'earlier) (org-timestamp-change -1 'day))
13111 ((eq value 'later) (org-timestamp-change 1 'day))
13112 (t (call-interactively 'org-deadline)))
13113 (call-interactively 'org-deadline)))
13114 ((member property org-special-properties)
13115 (error "The %s property can not yet be set with `org-entry-put'"
13116 property))
13117 (t ; a non-special property
13118 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13119 (setq range (org-get-property-block beg end 'force))
13120 (goto-char (car range))
13121 (if (re-search-forward
13122 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13123 (progn
13124 (delete-region (match-beginning 1) (match-end 1))
13125 (goto-char (match-beginning 1)))
13126 (goto-char (cdr range))
13127 (insert "\n")
13128 (backward-char 1)
13129 (org-indent-line-function)
13130 (insert ":" property ":"))
13131 (and value (insert " " value))
13132 (org-indent-line-function)))))
13133 (run-hook-with-args 'org-property-changed-functions property value)))
13135 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13136 "Get all property keys in the current buffer.
13137 With INCLUDE-SPECIALS, also list the special properties that reflect things
13138 like tags and TODO state.
13139 With INCLUDE-DEFAULTS, also include properties that has special meaning
13140 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
13141 With INCLUDE-COLUMNS, also include property names given in COLUMN
13142 formats in the current buffer."
13143 (let (rtn range cfmt s p)
13144 (save-excursion
13145 (save-restriction
13146 (widen)
13147 (goto-char (point-min))
13148 (while (re-search-forward org-property-start-re nil t)
13149 (setq range (org-get-property-block))
13150 (goto-char (car range))
13151 (while (re-search-forward
13152 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13153 (cdr range) t)
13154 (add-to-list 'rtn (org-match-string-no-properties 1)))
13155 (outline-next-heading))))
13157 (when include-specials
13158 (setq rtn (append org-special-properties rtn)))
13160 (when include-defaults
13161 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13162 (add-to-list 'rtn org-effort-property))
13164 (when include-columns
13165 (save-excursion
13166 (save-restriction
13167 (widen)
13168 (goto-char (point-min))
13169 (while (re-search-forward
13170 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13171 nil t)
13172 (setq cfmt (match-string 2) s 0)
13173 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13174 cfmt s)
13175 (setq s (match-end 0)
13176 p (match-string 1 cfmt))
13177 (unless (or (equal p "ITEM")
13178 (member p org-special-properties))
13179 (add-to-list 'rtn (match-string 1 cfmt))))))))
13181 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13183 (defun org-property-values (key)
13184 "Return a list of all values of property KEY."
13185 (save-excursion
13186 (save-restriction
13187 (widen)
13188 (goto-char (point-min))
13189 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
13190 values)
13191 (while (re-search-forward re nil t)
13192 (add-to-list 'values (org-trim (match-string 1))))
13193 (delete "" values)))))
13195 (defun org-insert-property-drawer ()
13196 "Insert a property drawer into the current entry."
13197 (interactive)
13198 (org-back-to-heading t)
13199 (looking-at outline-regexp)
13200 (let ((indent (if org-adapt-indentation
13201 (- (match-end 0)(match-beginning 0))
13203 (beg (point))
13204 (re (concat "^[ \t]*" org-keyword-time-regexp))
13205 end hiddenp)
13206 (outline-next-heading)
13207 (setq end (point))
13208 (goto-char beg)
13209 (while (re-search-forward re end t))
13210 (setq hiddenp (org-invisible-p))
13211 (end-of-line 1)
13212 (and (equal (char-after) ?\n) (forward-char 1))
13213 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
13214 (if (member (match-string 1) '("CLOCK:" ":END:"))
13215 ;; just skip this line
13216 (beginning-of-line 2)
13217 ;; Drawer start, find the end
13218 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
13219 (beginning-of-line 1)))
13220 (org-skip-over-state-notes)
13221 (skip-chars-backward " \t\n\r")
13222 (if (eq (char-before) ?*) (forward-char 1))
13223 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
13224 (beginning-of-line 0)
13225 (org-indent-to-column indent)
13226 (beginning-of-line 2)
13227 (org-indent-to-column indent)
13228 (beginning-of-line 0)
13229 (if hiddenp
13230 (save-excursion
13231 (org-back-to-heading t)
13232 (hide-entry))
13233 (org-flag-drawer t))))
13235 (defun org-set-property (property value)
13236 "In the current entry, set PROPERTY to VALUE.
13237 When called interactively, this will prompt for a property name, offering
13238 completion on existing and default properties. And then it will prompt
13239 for a value, offering completion either on allowed values (via an inherited
13240 xxx_ALL property) or on existing values in other instances of this property
13241 in the current file."
13242 (interactive
13243 (let* ((completion-ignore-case t)
13244 (keys (org-buffer-property-keys nil t t))
13245 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
13246 (prop (if (member prop0 keys)
13247 prop0
13248 (or (cdr (assoc (downcase prop0)
13249 (mapcar (lambda (x) (cons (downcase x) x))
13250 keys)))
13251 prop0)))
13252 (cur (org-entry-get nil prop))
13253 (prompt (concat prop " value"
13254 (if (and cur (string-match "\\S-" cur))
13255 (concat " [" cur "]") "") ": "))
13256 (allowed (org-property-get-allowed-values nil prop 'table))
13257 (existing (mapcar 'list (org-property-values prop)))
13258 (val (if allowed
13259 (org-completing-read prompt allowed nil
13260 (not (get-text-property 0 'org-unrestricted
13261 (caar allowed))))
13262 (let (org-completion-use-ido org-completion-use-iswitchb)
13263 (org-completing-read prompt existing nil nil "" nil cur)))))
13264 (list prop (if (equal val "") cur val))))
13265 (unless (equal (org-entry-get nil property) value)
13266 (org-entry-put nil property value)))
13268 (defun org-delete-property (property)
13269 "In the current entry, delete PROPERTY."
13270 (interactive
13271 (let* ((completion-ignore-case t)
13272 (prop (org-icompleting-read "Property: " (org-entry-properties nil 'standard))))
13273 (list prop)))
13274 (message "Property %s %s" property
13275 (if (org-entry-delete nil property)
13276 "deleted"
13277 "was not present in the entry")))
13279 (defun org-delete-property-globally (property)
13280 "Remove PROPERTY globally, from all entries."
13281 (interactive
13282 (let* ((completion-ignore-case t)
13283 (prop (org-icompleting-read
13284 "Globally remove property: "
13285 (mapcar 'list (org-buffer-property-keys)))))
13286 (list prop)))
13287 (save-excursion
13288 (save-restriction
13289 (widen)
13290 (goto-char (point-min))
13291 (let ((cnt 0))
13292 (while (re-search-forward
13293 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
13294 nil t)
13295 (setq cnt (1+ cnt))
13296 (replace-match ""))
13297 (message "Property \"%s\" removed from %d entries" property cnt)))))
13299 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
13301 (defun org-compute-property-at-point ()
13302 "Compute the property at point.
13303 This looks for an enclosing column format, extracts the operator and
13304 then applies it to the property in the column format's scope."
13305 (interactive)
13306 (unless (org-at-property-p)
13307 (error "Not at a property"))
13308 (let ((prop (org-match-string-no-properties 2)))
13309 (org-columns-get-format-and-top-level)
13310 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
13311 (error "No operator defined for property %s" prop))
13312 (org-columns-compute prop)))
13314 (defvar org-property-allowed-value-functions nil
13315 "Hook for functions supplying allowed values for a specific property.
13316 The functions must take a single argument, the name of the property, and
13317 return a flat list of allowed values. If \":ETC\" is one of
13318 the values, this means that these values are intended as defaults for
13319 completion, but that other values should be allowed too.
13320 The functions must return nil if they are not responsible for this
13321 property.")
13323 (defun org-property-get-allowed-values (pom property &optional table)
13324 "Get allowed values for the property PROPERTY.
13325 When TABLE is non-nil, return an alist that can directly be used for
13326 completion."
13327 (let (vals)
13328 (cond
13329 ((equal property "TODO")
13330 (setq vals (org-with-point-at pom
13331 (append org-todo-keywords-1 '("")))))
13332 ((equal property "PRIORITY")
13333 (let ((n org-lowest-priority))
13334 (while (>= n org-highest-priority)
13335 (push (char-to-string n) vals)
13336 (setq n (1- n)))))
13337 ((member property org-special-properties))
13338 ((setq vals (run-hook-with-args-until-success
13339 'org-property-allowed-value-functions property)))
13341 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13342 (when (and vals (string-match "\\S-" vals))
13343 (setq vals (car (read-from-string (concat "(" vals ")"))))
13344 (setq vals (mapcar (lambda (x)
13345 (cond ((stringp x) x)
13346 ((numberp x) (number-to-string x))
13347 ((symbolp x) (symbol-name x))
13348 (t "???")))
13349 vals)))))
13350 (when (member ":ETC" vals)
13351 (setq vals (remove ":ETC" vals))
13352 (org-add-props (car vals) '(org-unrestricted t)))
13353 (if table (mapcar 'list vals) vals)))
13355 (defun org-property-previous-allowed-value (&optional previous)
13356 "Switch to the next allowed value for this property."
13357 (interactive)
13358 (org-property-next-allowed-value t))
13360 (defun org-property-next-allowed-value (&optional previous)
13361 "Switch to the next allowed value for this property."
13362 (interactive)
13363 (unless (org-at-property-p)
13364 (error "Not at a property"))
13365 (let* ((key (match-string 2))
13366 (value (match-string 3))
13367 (allowed (or (org-property-get-allowed-values (point) key)
13368 (and (member value '("[ ]" "[-]" "[X]"))
13369 '("[ ]" "[X]"))))
13370 nval)
13371 (unless allowed
13372 (error "Allowed values for this property have not been defined"))
13373 (if previous (setq allowed (reverse allowed)))
13374 (if (member value allowed)
13375 (setq nval (car (cdr (member value allowed)))))
13376 (setq nval (or nval (car allowed)))
13377 (if (equal nval value)
13378 (error "Only one allowed value for this property"))
13379 (org-at-property-p)
13380 (replace-match (concat " :" key ": " nval) t t)
13381 (org-indent-line-function)
13382 (beginning-of-line 1)
13383 (skip-chars-forward " \t")
13384 (run-hook-with-args 'org-property-changed-functions key nval)))
13386 (defun org-find-entry-with-id (ident)
13387 "Locate the entry that contains the ID property with exact value IDENT.
13388 IDENT can be a string, a symbol or a number, this function will search for
13389 the string representation of it.
13390 Return the position where this entry starts, or nil if there is no such entry."
13391 (interactive "sID: ")
13392 (let ((id (cond
13393 ((stringp ident) ident)
13394 ((symbol-name ident) (symbol-name ident))
13395 ((numberp ident) (number-to-string ident))
13396 (t (error "IDENT %s must be a string, symbol or number" ident))))
13397 (case-fold-search nil))
13398 (save-excursion
13399 (save-restriction
13400 (widen)
13401 (goto-char (point-min))
13402 (when (re-search-forward
13403 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13404 nil t)
13405 (org-back-to-heading t)
13406 (point))))))
13408 ;;;; Timestamps
13410 (defvar org-last-changed-timestamp nil)
13411 (defvar org-last-inserted-timestamp nil
13412 "The last time stamp inserted with `org-insert-time-stamp'.")
13413 (defvar org-time-was-given) ; dynamically scoped parameter
13414 (defvar org-end-time-was-given) ; dynamically scoped parameter
13415 (defvar org-ts-what) ; dynamically scoped parameter
13417 (defun org-time-stamp (arg &optional inactive)
13418 "Prompt for a date/time and insert a time stamp.
13419 If the user specifies a time like HH:MM, or if this command is called
13420 with a prefix argument, the time stamp will contain date and time.
13421 Otherwise, only the date will be included. All parts of a date not
13422 specified by the user will be filled in from the current date/time.
13423 So if you press just return without typing anything, the time stamp
13424 will represent the current date/time. If there is already a timestamp
13425 at the cursor, it will be modified."
13426 (interactive "P")
13427 (let* ((ts nil)
13428 (default-time
13429 ;; Default time is either today, or, when entering a range,
13430 ;; the range start.
13431 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13432 (save-excursion
13433 (re-search-backward
13434 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13435 (- (point) 20) t)))
13436 (apply 'encode-time (org-parse-time-string (match-string 1)))
13437 (current-time)))
13438 (default-input (and ts (org-get-compact-tod ts)))
13439 org-time-was-given org-end-time-was-given time)
13440 (cond
13441 ((and (org-at-timestamp-p t)
13442 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13443 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13444 (insert "--")
13445 (setq time (let ((this-command this-command))
13446 (org-read-date arg 'totime nil nil
13447 default-time default-input)))
13448 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13449 ((org-at-timestamp-p t)
13450 (setq time (let ((this-command this-command))
13451 (org-read-date arg 'totime nil nil default-time default-input)))
13452 (when (org-at-timestamp-p t) ; just to get the match data
13453 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13454 (replace-match "")
13455 (setq org-last-changed-timestamp
13456 (org-insert-time-stamp
13457 time (or org-time-was-given arg)
13458 inactive nil nil (list org-end-time-was-given))))
13459 (message "Timestamp updated"))
13461 (setq time (let ((this-command this-command))
13462 (org-read-date arg 'totime nil nil default-time default-input)))
13463 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13464 nil nil (list org-end-time-was-given))))))
13466 ;; FIXME: can we use this for something else, like computing time differences?
13467 (defun org-get-compact-tod (s)
13468 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13469 (let* ((t1 (match-string 1 s))
13470 (h1 (string-to-number (match-string 2 s)))
13471 (m1 (string-to-number (match-string 3 s)))
13472 (t2 (and (match-end 4) (match-string 5 s)))
13473 (h2 (and t2 (string-to-number (match-string 6 s))))
13474 (m2 (and t2 (string-to-number (match-string 7 s))))
13475 dh dm)
13476 (if (not t2)
13478 (setq dh (- h2 h1) dm (- m2 m1))
13479 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13480 (concat t1 "+" (number-to-string dh)
13481 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13483 (defun org-time-stamp-inactive (&optional arg)
13484 "Insert an inactive time stamp.
13485 An inactive time stamp is enclosed in square brackets instead of angle
13486 brackets. It is inactive in the sense that it does not trigger agenda entries,
13487 does not link to the calendar and cannot be changed with the S-cursor keys.
13488 So these are more for recording a certain time/date."
13489 (interactive "P")
13490 (org-time-stamp arg 'inactive))
13492 (defvar org-date-ovl (make-overlay 1 1))
13493 (overlay-put org-date-ovl 'face 'org-warning)
13494 (org-detach-overlay org-date-ovl)
13496 (defvar org-ans1) ; dynamically scoped parameter
13497 (defvar org-ans2) ; dynamically scoped parameter
13499 (defvar org-plain-time-of-day-regexp) ; defined below
13501 (defvar org-overriding-default-time nil) ; dynamically scoped
13502 (defvar org-read-date-overlay nil)
13503 (defvar org-dcst nil) ; dynamically scoped
13504 (defvar org-read-date-history nil)
13505 (defvar org-read-date-final-answer nil)
13507 (defun org-read-date (&optional with-time to-time from-string prompt
13508 default-time default-input)
13509 "Read a date, possibly a time, and make things smooth for the user.
13510 The prompt will suggest to enter an ISO date, but you can also enter anything
13511 which will at least partially be understood by `parse-time-string'.
13512 Unrecognized parts of the date will default to the current day, month, year,
13513 hour and minute. If this command is called to replace a timestamp at point,
13514 of to enter the second timestamp of a range, the default time is taken from the
13515 existing stamp. For example,
13516 3-2-5 --> 2003-02-05
13517 feb 15 --> currentyear-02-15
13518 sep 12 9 --> 2009-09-12
13519 12:45 --> today 12:45
13520 22 sept 0:34 --> currentyear-09-22 0:34
13521 12 --> currentyear-currentmonth-12
13522 Fri --> nearest Friday (today or later)
13523 etc.
13525 Furthermore you can specify a relative date by giving, as the *first* thing
13526 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13527 change in days weeks, months, years.
13528 With a single plus or minus, the date is relative to today. With a double
13529 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13530 +4d --> four days from today
13531 +4 --> same as above
13532 +2w --> two weeks from today
13533 ++5 --> five days from default date
13535 The function understands only English month and weekday abbreviations,
13536 but this can be configured with the variables `parse-time-months' and
13537 `parse-time-weekdays'.
13539 While prompting, a calendar is popped up - you can also select the
13540 date with the mouse (button 1). The calendar shows a period of three
13541 months. To scroll it to other months, use the keys `>' and `<'.
13542 If you don't like the calendar, turn it off with
13543 \(setq org-read-date-popup-calendar nil)
13545 With optional argument TO-TIME, the date will immediately be converted
13546 to an internal time.
13547 With an optional argument WITH-TIME, the prompt will suggest to also
13548 insert a time. Note that when WITH-TIME is not set, you can still
13549 enter a time, and this function will inform the calling routine about
13550 this change. The calling routine may then choose to change the format
13551 used to insert the time stamp into the buffer to include the time.
13552 With optional argument FROM-STRING, read from this string instead from
13553 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13554 the time/date that is used for everything that is not specified by the
13555 user."
13556 (require 'parse-time)
13557 (let* ((org-time-stamp-rounding-minutes
13558 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13559 (org-dcst org-display-custom-times)
13560 (ct (org-current-time))
13561 (def (or org-overriding-default-time default-time ct))
13562 (defdecode (decode-time def))
13563 (dummy (progn
13564 (when (< (nth 2 defdecode) org-extend-today-until)
13565 (setcar (nthcdr 2 defdecode) -1)
13566 (setcar (nthcdr 1 defdecode) 59)
13567 (setq def (apply 'encode-time defdecode)
13568 defdecode (decode-time def)))))
13569 (calendar-frame-setup nil)
13570 (calendar-move-hook nil)
13571 (calendar-view-diary-initially-flag nil)
13572 (calendar-view-holidays-initially-flag nil)
13573 (timestr (format-time-string
13574 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
13575 (prompt (concat (if prompt (concat prompt " ") "")
13576 (format "Date+time [%s]: " timestr)))
13577 ans (org-ans0 "") org-ans1 org-ans2 final)
13579 (cond
13580 (from-string (setq ans from-string))
13581 (org-read-date-popup-calendar
13582 (save-excursion
13583 (save-window-excursion
13584 (calendar)
13585 (calendar-forward-day (- (time-to-days def)
13586 (calendar-absolute-from-gregorian
13587 (calendar-current-date))))
13588 (org-eval-in-calendar nil t)
13589 (let* ((old-map (current-local-map))
13590 (map (copy-keymap calendar-mode-map))
13591 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13592 (org-defkey map (kbd "RET") 'org-calendar-select)
13593 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
13594 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
13595 (org-defkey minibuffer-local-map [(meta shift left)]
13596 (lambda () (interactive)
13597 (org-eval-in-calendar '(calendar-backward-month 1))))
13598 (org-defkey minibuffer-local-map [(meta shift right)]
13599 (lambda () (interactive)
13600 (org-eval-in-calendar '(calendar-forward-month 1))))
13601 (org-defkey minibuffer-local-map [(meta shift up)]
13602 (lambda () (interactive)
13603 (org-eval-in-calendar '(calendar-backward-year 1))))
13604 (org-defkey minibuffer-local-map [(meta shift down)]
13605 (lambda () (interactive)
13606 (org-eval-in-calendar '(calendar-forward-year 1))))
13607 (org-defkey minibuffer-local-map [?\e (shift left)]
13608 (lambda () (interactive)
13609 (org-eval-in-calendar '(calendar-backward-month 1))))
13610 (org-defkey minibuffer-local-map [?\e (shift right)]
13611 (lambda () (interactive)
13612 (org-eval-in-calendar '(calendar-forward-month 1))))
13613 (org-defkey minibuffer-local-map [?\e (shift up)]
13614 (lambda () (interactive)
13615 (org-eval-in-calendar '(calendar-backward-year 1))))
13616 (org-defkey minibuffer-local-map [?\e (shift down)]
13617 (lambda () (interactive)
13618 (org-eval-in-calendar '(calendar-forward-year 1))))
13619 (org-defkey minibuffer-local-map [(shift up)]
13620 (lambda () (interactive)
13621 (org-eval-in-calendar '(calendar-backward-week 1))))
13622 (org-defkey minibuffer-local-map [(shift down)]
13623 (lambda () (interactive)
13624 (org-eval-in-calendar '(calendar-forward-week 1))))
13625 (org-defkey minibuffer-local-map [(shift left)]
13626 (lambda () (interactive)
13627 (org-eval-in-calendar '(calendar-backward-day 1))))
13628 (org-defkey minibuffer-local-map [(shift right)]
13629 (lambda () (interactive)
13630 (org-eval-in-calendar '(calendar-forward-day 1))))
13631 (org-defkey minibuffer-local-map ">"
13632 (lambda () (interactive)
13633 (org-eval-in-calendar '(scroll-calendar-left 1))))
13634 (org-defkey minibuffer-local-map "<"
13635 (lambda () (interactive)
13636 (org-eval-in-calendar '(scroll-calendar-right 1))))
13637 (run-hooks 'org-read-date-minibuffer-setup-hook)
13638 (unwind-protect
13639 (progn
13640 (use-local-map map)
13641 (add-hook 'post-command-hook 'org-read-date-display)
13642 (setq org-ans0 (read-string prompt default-input
13643 'org-read-date-history nil))
13644 ;; org-ans0: from prompt
13645 ;; org-ans1: from mouse click
13646 ;; org-ans2: from calendar motion
13647 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13648 (remove-hook 'post-command-hook 'org-read-date-display)
13649 (use-local-map old-map)
13650 (when org-read-date-overlay
13651 (delete-overlay org-read-date-overlay)
13652 (setq org-read-date-overlay nil)))))))
13654 (t ; Naked prompt only
13655 (unwind-protect
13656 (setq ans (read-string prompt default-input
13657 'org-read-date-history timestr))
13658 (when org-read-date-overlay
13659 (delete-overlay org-read-date-overlay)
13660 (setq org-read-date-overlay nil)))))
13662 (setq final (org-read-date-analyze ans def defdecode))
13663 (setq org-read-date-final-answer ans)
13665 (if to-time
13666 (apply 'encode-time final)
13667 (if (and (boundp 'org-time-was-given) org-time-was-given)
13668 (format "%04d-%02d-%02d %02d:%02d"
13669 (nth 5 final) (nth 4 final) (nth 3 final)
13670 (nth 2 final) (nth 1 final))
13671 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13673 (defvar def)
13674 (defvar defdecode)
13675 (defvar with-time)
13676 (defvar org-read-date-analyze-futurep nil)
13677 (defun org-read-date-display ()
13678 "Display the current date prompt interpretation in the minibuffer."
13679 (when org-read-date-display-live
13680 (when org-read-date-overlay
13681 (delete-overlay org-read-date-overlay))
13682 (let ((p (point)))
13683 (end-of-line 1)
13684 (while (not (equal (buffer-substring
13685 (max (point-min) (- (point) 4)) (point))
13686 " "))
13687 (insert " "))
13688 (goto-char p))
13689 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13690 " " (or org-ans1 org-ans2)))
13691 (org-end-time-was-given nil)
13692 (f (org-read-date-analyze ans def defdecode))
13693 (fmts (if org-dcst
13694 org-time-stamp-custom-formats
13695 org-time-stamp-formats))
13696 (fmt (if (or with-time
13697 (and (boundp 'org-time-was-given) org-time-was-given))
13698 (cdr fmts)
13699 (car fmts)))
13700 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13701 (when (and org-end-time-was-given
13702 (string-match org-plain-time-of-day-regexp txt))
13703 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13704 org-end-time-was-given
13705 (substring txt (match-end 0)))))
13706 (when org-read-date-analyze-futurep
13707 (setq txt (concat txt " (=>F)")))
13708 (setq org-read-date-overlay
13709 (make-overlay (1- (point-at-eol)) (point-at-eol)))
13710 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13712 (defun org-read-date-analyze (ans def defdecode)
13713 "Analyse the combined answer of the date prompt."
13714 ;; FIXME: cleanup and comment
13715 (let ((nowdecode (decode-time (current-time)))
13716 delta deltan deltaw deltadef year month day
13717 hour minute second wday pm h2 m2 tl wday1
13718 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
13719 (setq org-read-date-analyze-futurep nil)
13720 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13721 (setq ans "+0"))
13723 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13724 (setq ans (replace-match "" t t ans)
13725 deltan (car delta)
13726 deltaw (nth 1 delta)
13727 deltadef (nth 2 delta)))
13729 ;; Check if there is an iso week date in there
13730 ;; If yes, store the info and postpone interpreting it until the rest
13731 ;; of the parsing is done
13732 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13733 (setq iso-year (if (match-end 1)
13734 (org-small-year-to-year
13735 (string-to-number (match-string 1 ans))))
13736 iso-weekday (if (match-end 3)
13737 (string-to-number (match-string 3 ans)))
13738 iso-week (string-to-number (match-string 2 ans)))
13739 (setq ans (replace-match "" t t ans)))
13741 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
13742 (when (string-match
13743 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13744 (setq year (if (match-end 2)
13745 (string-to-number (match-string 2 ans))
13746 (progn (setq kill-year t)
13747 (string-to-number (format-time-string "%Y"))))
13748 month (string-to-number (match-string 3 ans))
13749 day (string-to-number (match-string 4 ans)))
13750 (if (< year 100) (setq year (+ 2000 year)))
13751 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13752 t nil ans)))
13753 ;; Help matching american dates, like 5/30 or 5/30/7
13754 (when (string-match
13755 "^ *\\([0-3]?[0-9]\\)/\\([0-1]?[0-9]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
13756 (setq year (if (match-end 4)
13757 (string-to-number (match-string 4 ans))
13758 (progn (setq kill-year t)
13759 (string-to-number (format-time-string "%Y"))))
13760 month (string-to-number (match-string 1 ans))
13761 day (string-to-number (match-string 2 ans)))
13762 (if (< year 100) (setq year (+ 2000 year)))
13763 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13764 t nil ans)))
13765 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13766 ;; If there is a time with am/pm, and *no* time without it, we convert
13767 ;; so that matching will be successful.
13768 (loop for i from 1 to 2 do ; twice, for end time as well
13769 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13770 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13771 (setq hour (string-to-number (match-string 1 ans))
13772 minute (if (match-end 3)
13773 (string-to-number (match-string 3 ans))
13775 pm (equal ?p
13776 (string-to-char (downcase (match-string 4 ans)))))
13777 (if (and (= hour 12) (not pm))
13778 (setq hour 0)
13779 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13780 (setq ans (replace-match (format "%02d:%02d" hour minute)
13781 t t ans))))
13783 ;; Check if a time range is given as a duration
13784 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13785 (setq hour (string-to-number (match-string 1 ans))
13786 h2 (+ hour (string-to-number (match-string 3 ans)))
13787 minute (string-to-number (match-string 2 ans))
13788 m2 (+ minute (if (match-end 5) (string-to-number
13789 (match-string 5 ans))0)))
13790 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13791 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13792 t t ans)))
13794 ;; Check if there is a time range
13795 (when (boundp 'org-end-time-was-given)
13796 (setq org-time-was-given nil)
13797 (when (and (string-match org-plain-time-of-day-regexp ans)
13798 (match-end 8))
13799 (setq org-end-time-was-given (match-string 8 ans))
13800 (setq ans (concat (substring ans 0 (match-beginning 7))
13801 (substring ans (match-end 7))))))
13803 (setq tl (parse-time-string ans)
13804 day (or (nth 3 tl) (nth 3 defdecode))
13805 month (or (nth 4 tl)
13806 (if (and org-read-date-prefer-future
13807 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
13808 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
13809 (nth 4 defdecode)))
13810 year (or (and (not kill-year) (nth 5 tl))
13811 (if (and org-read-date-prefer-future
13812 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
13813 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
13814 (nth 5 defdecode)))
13815 hour (or (nth 2 tl) (nth 2 defdecode))
13816 minute (or (nth 1 tl) (nth 1 defdecode))
13817 second (or (nth 0 tl) 0)
13818 wday (nth 6 tl))
13820 (when (and (eq org-read-date-prefer-future 'time)
13821 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13822 (equal day (nth 3 nowdecode))
13823 (equal month (nth 4 nowdecode))
13824 (equal year (nth 5 nowdecode))
13825 (nth 2 tl)
13826 (or (< (nth 2 tl) (nth 2 nowdecode))
13827 (and (= (nth 2 tl) (nth 2 nowdecode))
13828 (nth 1 tl)
13829 (< (nth 1 tl) (nth 1 nowdecode)))))
13830 (setq day (1+ day)
13831 futurep t))
13833 ;; Special date definitions below
13834 (cond
13835 (iso-week
13836 ;; There was an iso week
13837 (require 'cal-iso)
13838 (setq futurep nil)
13839 (setq year (or iso-year year)
13840 day (or iso-weekday wday 1)
13841 wday nil ; to make sure that the trigger below does not match
13842 iso-date (calendar-gregorian-from-absolute
13843 (calendar-absolute-from-iso
13844 (list iso-week day year))))
13845 ; FIXME: Should we also push ISO weeks into the future?
13846 ; (when (and org-read-date-prefer-future
13847 ; (not iso-year)
13848 ; (< (calendar-absolute-from-gregorian iso-date)
13849 ; (time-to-days (current-time))))
13850 ; (setq year (1+ year)
13851 ; iso-date (calendar-gregorian-from-absolute
13852 ; (calendar-absolute-from-iso
13853 ; (list iso-week day year)))))
13854 (setq month (car iso-date)
13855 year (nth 2 iso-date)
13856 day (nth 1 iso-date)))
13857 (deltan
13858 (setq futurep nil)
13859 (unless deltadef
13860 (let ((now (decode-time (current-time))))
13861 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13862 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13863 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13864 ((equal deltaw "m") (setq month (+ month deltan)))
13865 ((equal deltaw "y") (setq year (+ year deltan)))))
13866 ((and wday (not (nth 3 tl)))
13867 (setq futurep nil)
13868 ;; Weekday was given, but no day, so pick that day in the week
13869 ;; on or after the derived date.
13870 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13871 (unless (equal wday wday1)
13872 (setq day (+ day (% (- wday wday1 -7) 7))))))
13873 (if (and (boundp 'org-time-was-given)
13874 (nth 2 tl))
13875 (setq org-time-was-given t))
13876 (if (< year 100) (setq year (+ 2000 year)))
13877 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13878 (setq org-read-date-analyze-futurep futurep)
13879 (list second minute hour day month year)))
13881 (defvar parse-time-weekdays)
13883 (defun org-read-date-get-relative (s today default)
13884 "Check string S for special relative date string.
13885 TODAY and DEFAULT are internal times, for today and for a default.
13886 Return shift list (N what def-flag)
13887 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13888 N is the number of WHATs to shift.
13889 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13890 the DEFAULT date rather than TODAY."
13891 (when (and
13892 (string-match
13893 (concat
13894 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13895 "\\([0-9]+\\)?"
13896 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13897 "\\([ \t]\\|$\\)") s)
13898 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13899 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13900 (string-to-char (substring (match-string 1 s) -1))
13901 ?+))
13902 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13903 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13904 (what (if (match-end 3) (match-string 3 s) "d"))
13905 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13906 (date (if rel default today))
13907 (wday (nth 6 (decode-time date)))
13908 delta)
13909 (if wday1
13910 (progn
13911 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13912 (if (= dir ?-) (setq delta (- delta 7)))
13913 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13914 (list delta "d" rel))
13915 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13917 (defun org-order-calendar-date-args (arg1 arg2 arg3)
13918 "Turn a user-specified date into the internal representation.
13919 The internal representation needed by the calendar is (month day year).
13920 This is a wrapper to handle the brain-dead convention in calendar that
13921 user function argument order change dependent on argument order."
13922 (if (boundp 'calendar-date-style)
13923 (cond
13924 ((eq calendar-date-style 'american)
13925 (list arg1 arg2 arg3))
13926 ((eq calendar-date-style 'european)
13927 (list arg2 arg1 arg3))
13928 ((eq calendar-date-style 'iso)
13929 (list arg2 arg3 arg1)))
13930 (if (org-bound-and-true-p european-calendar-style)
13931 (list arg2 arg1 arg3)
13932 (list arg1 arg2 arg3))))
13934 (defun org-eval-in-calendar (form &optional keepdate)
13935 "Eval FORM in the calendar window and return to current window.
13936 Also, store the cursor date in variable org-ans2."
13937 (let ((sf (selected-frame))
13938 (sw (selected-window)))
13939 (select-window (get-buffer-window "*Calendar*" t))
13940 (eval form)
13941 (when (and (not keepdate) (calendar-cursor-to-date))
13942 (let* ((date (calendar-cursor-to-date))
13943 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13944 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13945 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13946 (select-window sw)
13947 (org-select-frame-set-input-focus sf)))
13949 (defun org-calendar-select ()
13950 "Return to `org-read-date' with the date currently selected.
13951 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13952 (interactive)
13953 (when (calendar-cursor-to-date)
13954 (let* ((date (calendar-cursor-to-date))
13955 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13956 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13957 (if (active-minibuffer-window) (exit-minibuffer))))
13959 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13960 "Insert a date stamp for the date given by the internal TIME.
13961 WITH-HM means use the stamp format that includes the time of the day.
13962 INACTIVE means use square brackets instead of angular ones, so that the
13963 stamp will not contribute to the agenda.
13964 PRE and POST are optional strings to be inserted before and after the
13965 stamp.
13966 The command returns the inserted time stamp."
13967 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13968 stamp)
13969 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13970 (insert-before-markers (or pre ""))
13971 (insert-before-markers (setq stamp (format-time-string fmt time)))
13972 (when (listp extra)
13973 (setq extra (car extra))
13974 (if (and (stringp extra)
13975 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13976 (setq extra (format "-%02d:%02d"
13977 (string-to-number (match-string 1 extra))
13978 (string-to-number (match-string 2 extra))))
13979 (setq extra nil)))
13980 (when extra
13981 (backward-char 1)
13982 (insert-before-markers extra)
13983 (forward-char 1))
13984 (insert-before-markers (or post ""))
13985 (setq org-last-inserted-timestamp stamp)))
13987 (defun org-toggle-time-stamp-overlays ()
13988 "Toggle the use of custom time stamp formats."
13989 (interactive)
13990 (setq org-display-custom-times (not org-display-custom-times))
13991 (unless org-display-custom-times
13992 (let ((p (point-min)) (bmp (buffer-modified-p)))
13993 (while (setq p (next-single-property-change p 'display))
13994 (if (and (get-text-property p 'display)
13995 (eq (get-text-property p 'face) 'org-date))
13996 (remove-text-properties
13997 p (setq p (next-single-property-change p 'display))
13998 '(display t))))
13999 (set-buffer-modified-p bmp)))
14000 (if (featurep 'xemacs)
14001 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
14002 (org-restart-font-lock)
14003 (setq org-table-may-need-update t)
14004 (if org-display-custom-times
14005 (message "Time stamps are overlayed with custom format")
14006 (message "Time stamp overlays removed")))
14008 (defun org-display-custom-time (beg end)
14009 "Overlay modified time stamp format over timestamp between BEG and END."
14010 (let* ((ts (buffer-substring beg end))
14011 t1 w1 with-hm tf time str w2 (off 0))
14012 (save-match-data
14013 (setq t1 (org-parse-time-string ts t))
14014 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
14015 (setq off (- (match-end 0) (match-beginning 0)))))
14016 (setq end (- end off))
14017 (setq w1 (- end beg)
14018 with-hm (and (nth 1 t1) (nth 2 t1))
14019 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
14020 time (org-fix-decoded-time t1)
14021 str (org-add-props
14022 (format-time-string
14023 (substring tf 1 -1) (apply 'encode-time time))
14024 nil 'mouse-face 'highlight)
14025 w2 (length str))
14026 (if (not (= w2 w1))
14027 (add-text-properties (1+ beg) (+ 2 beg)
14028 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
14029 (if (featurep 'xemacs)
14030 (progn
14031 (put-text-property beg end 'invisible t)
14032 (put-text-property beg end 'end-glyph (make-glyph str)))
14033 (put-text-property beg end 'display str))))
14035 (defun org-translate-time (string)
14036 "Translate all timestamps in STRING to custom format.
14037 But do this only if the variable `org-display-custom-times' is set."
14038 (when org-display-custom-times
14039 (save-match-data
14040 (let* ((start 0)
14041 (re org-ts-regexp-both)
14042 t1 with-hm inactive tf time str beg end)
14043 (while (setq start (string-match re string start))
14044 (setq beg (match-beginning 0)
14045 end (match-end 0)
14046 t1 (save-match-data
14047 (org-parse-time-string (substring string beg end) t))
14048 with-hm (and (nth 1 t1) (nth 2 t1))
14049 inactive (equal (substring string beg (1+ beg)) "[")
14050 tf (funcall (if with-hm 'cdr 'car)
14051 org-time-stamp-custom-formats)
14052 time (org-fix-decoded-time t1)
14053 str (format-time-string
14054 (concat
14055 (if inactive "[" "<") (substring tf 1 -1)
14056 (if inactive "]" ">"))
14057 (apply 'encode-time time))
14058 string (replace-match str t t string)
14059 start (+ start (length str)))))))
14060 string)
14062 (defun org-fix-decoded-time (time)
14063 "Set 0 instead of nil for the first 6 elements of time.
14064 Don't touch the rest."
14065 (let ((n 0))
14066 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
14068 (defun org-days-to-time (timestamp-string)
14069 "Difference between TIMESTAMP-STRING and now in days."
14070 (- (time-to-days (org-time-string-to-time timestamp-string))
14071 (time-to-days (current-time))))
14073 (defun org-deadline-close (timestamp-string &optional ndays)
14074 "Is the time in TIMESTAMP-STRING close to the current date?"
14075 (setq ndays (or ndays (org-get-wdays timestamp-string)))
14076 (and (< (org-days-to-time timestamp-string) ndays)
14077 (not (org-entry-is-done-p))))
14079 (defun org-get-wdays (ts)
14080 "Get the deadline lead time appropriate for timestring TS."
14081 (cond
14082 ((<= org-deadline-warning-days 0)
14083 ;; 0 or negative, enforce this value no matter what
14084 (- org-deadline-warning-days))
14085 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
14086 ;; lead time is specified.
14087 (floor (* (string-to-number (match-string 1 ts))
14088 (cdr (assoc (match-string 2 ts)
14089 '(("d" . 1) ("w" . 7)
14090 ("m" . 30.4) ("y" . 365.25)))))))
14091 ;; go for the default.
14092 (t org-deadline-warning-days)))
14094 (defun org-calendar-select-mouse (ev)
14095 "Return to `org-read-date' with the date currently selected.
14096 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14097 (interactive "e")
14098 (mouse-set-point ev)
14099 (when (calendar-cursor-to-date)
14100 (let* ((date (calendar-cursor-to-date))
14101 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14102 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14103 (if (active-minibuffer-window) (exit-minibuffer))))
14105 (defun org-check-deadlines (ndays)
14106 "Check if there are any deadlines due or past due.
14107 A deadline is considered due if it happens within `org-deadline-warning-days'
14108 days from today's date. If the deadline appears in an entry marked DONE,
14109 it is not shown. The prefix arg NDAYS can be used to test that many
14110 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
14111 (interactive "P")
14112 (let* ((org-warn-days
14113 (cond
14114 ((equal ndays '(4)) 100000)
14115 (ndays (prefix-numeric-value ndays))
14116 (t (abs org-deadline-warning-days))))
14117 (case-fold-search nil)
14118 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
14119 (callback
14120 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
14122 (message "%d deadlines past-due or due within %d days"
14123 (org-occur regexp nil callback)
14124 org-warn-days)))
14126 (defun org-check-before-date (date)
14127 "Check if there are deadlines or scheduled entries before DATE."
14128 (interactive (list (org-read-date)))
14129 (let ((case-fold-search nil)
14130 (regexp (concat "\\<\\(" org-deadline-string
14131 "\\|" org-scheduled-string
14132 "\\) *<\\([^>]+\\)>"))
14133 (callback
14134 (lambda () (time-less-p
14135 (org-time-string-to-time (match-string 2))
14136 (org-time-string-to-time date)))))
14137 (message "%d entries before %s"
14138 (org-occur regexp nil callback) date)))
14140 (defun org-check-after-date (date)
14141 "Check if there are deadlines or scheduled entries after DATE."
14142 (interactive (list (org-read-date)))
14143 (let ((case-fold-search nil)
14144 (regexp (concat "\\<\\(" org-deadline-string
14145 "\\|" org-scheduled-string
14146 "\\) *<\\([^>]+\\)>"))
14147 (callback
14148 (lambda () (not
14149 (time-less-p
14150 (org-time-string-to-time (match-string 2))
14151 (org-time-string-to-time date))))))
14152 (message "%d entries after %s"
14153 (org-occur regexp nil callback) date)))
14155 (defun org-evaluate-time-range (&optional to-buffer)
14156 "Evaluate a time range by computing the difference between start and end.
14157 Normally the result is just printed in the echo area, but with prefix arg
14158 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
14159 If the time range is actually in a table, the result is inserted into the
14160 next column.
14161 For time difference computation, a year is assumed to be exactly 365
14162 days in order to avoid rounding problems."
14163 (interactive "P")
14165 (org-clock-update-time-maybe)
14166 (save-excursion
14167 (unless (org-at-date-range-p t)
14168 (goto-char (point-at-bol))
14169 (re-search-forward org-tr-regexp-both (point-at-eol) t))
14170 (if (not (org-at-date-range-p t))
14171 (error "Not at a time-stamp range, and none found in current line")))
14172 (let* ((ts1 (match-string 1))
14173 (ts2 (match-string 2))
14174 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
14175 (match-end (match-end 0))
14176 (time1 (org-time-string-to-time ts1))
14177 (time2 (org-time-string-to-time ts2))
14178 (t1 (org-float-time time1))
14179 (t2 (org-float-time time2))
14180 (diff (abs (- t2 t1)))
14181 (negative (< (- t2 t1) 0))
14182 ;; (ys (floor (* 365 24 60 60)))
14183 (ds (* 24 60 60))
14184 (hs (* 60 60))
14185 (fy "%dy %dd %02d:%02d")
14186 (fy1 "%dy %dd")
14187 (fd "%dd %02d:%02d")
14188 (fd1 "%dd")
14189 (fh "%02d:%02d")
14190 y d h m align)
14191 (if havetime
14192 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14194 d (floor (/ diff ds)) diff (mod diff ds)
14195 h (floor (/ diff hs)) diff (mod diff hs)
14196 m (floor (/ diff 60)))
14197 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14199 d (floor (+ (/ diff ds) 0.5))
14200 h 0 m 0))
14201 (if (not to-buffer)
14202 (message "%s" (org-make-tdiff-string y d h m))
14203 (if (org-at-table-p)
14204 (progn
14205 (goto-char match-end)
14206 (setq align t)
14207 (and (looking-at " *|") (goto-char (match-end 0))))
14208 (goto-char match-end))
14209 (if (looking-at
14210 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
14211 (replace-match ""))
14212 (if negative (insert " -"))
14213 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
14214 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
14215 (insert " " (format fh h m))))
14216 (if align (org-table-align))
14217 (message "Time difference inserted")))))
14219 (defun org-make-tdiff-string (y d h m)
14220 (let ((fmt "")
14221 (l nil))
14222 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
14223 l (push y l)))
14224 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
14225 l (push d l)))
14226 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
14227 l (push h l)))
14228 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
14229 l (push m l)))
14230 (apply 'format fmt (nreverse l))))
14232 (defun org-time-string-to-time (s)
14233 (apply 'encode-time (org-parse-time-string s)))
14234 (defun org-time-string-to-seconds (s)
14235 (org-float-time (org-time-string-to-time s)))
14237 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
14238 "Convert a time stamp to an absolute day number.
14239 If there is a specifyer for a cyclic time stamp, get the closest date to
14240 DAYNR.
14241 PREFER and SHOW-ALL are passed through to `org-closest-date'.
14242 the variable date is bound by the calendar when this is called."
14243 (cond
14244 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
14245 (if (org-diary-sexp-entry (match-string 1 s) "" date)
14246 daynr
14247 (+ daynr 1000)))
14248 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
14249 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
14250 (time-to-days (current-time))) (match-string 0 s)
14251 prefer show-all))
14252 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
14254 (defun org-days-to-iso-week (days)
14255 "Return the iso week number."
14256 (require 'cal-iso)
14257 (car (calendar-iso-from-absolute days)))
14259 (defun org-small-year-to-year (year)
14260 "Convert 2-digit years into 4-digit years.
14261 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
14262 The year 2000 cannot be abbreviated. Any year larger than 99
14263 is returned unchanged."
14264 (if (< year 38)
14265 (setq year (+ 2000 year))
14266 (if (< year 100)
14267 (setq year (+ 1900 year))))
14268 year)
14270 (defun org-time-from-absolute (d)
14271 "Return the time corresponding to date D.
14272 D may be an absolute day number, or a calendar-type list (month day year)."
14273 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
14274 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
14276 (defun org-calendar-holiday ()
14277 "List of holidays, for Diary display in Org-mode."
14278 (require 'holidays)
14279 (let ((hl (funcall
14280 (if (fboundp 'calendar-check-holidays)
14281 'calendar-check-holidays 'check-calendar-holidays) date)))
14282 (if hl (mapconcat 'identity hl "; "))))
14284 (defun org-diary-sexp-entry (sexp entry date)
14285 "Process a SEXP diary ENTRY for DATE."
14286 (require 'diary-lib)
14287 (let ((result (if calendar-debug-sexp
14288 (let ((stack-trace-on-error t))
14289 (eval (car (read-from-string sexp))))
14290 (condition-case nil
14291 (eval (car (read-from-string sexp)))
14292 (error
14293 (beep)
14294 (message "Bad sexp at line %d in %s: %s"
14295 (org-current-line)
14296 (buffer-file-name) sexp)
14297 (sleep-for 2))))))
14298 (cond ((stringp result) result)
14299 ((and (consp result)
14300 (stringp (cdr result))) (cdr result))
14301 (result entry)
14302 (t nil))))
14304 (defun org-diary-to-ical-string (frombuf)
14305 "Get iCalendar entries from diary entries in buffer FROMBUF.
14306 This uses the icalendar.el library."
14307 (let* ((tmpdir (if (featurep 'xemacs)
14308 (temp-directory)
14309 temporary-file-directory))
14310 (tmpfile (make-temp-name
14311 (expand-file-name "orgics" tmpdir)))
14312 buf rtn b e)
14313 (with-current-buffer frombuf
14314 (icalendar-export-region (point-min) (point-max) tmpfile)
14315 (setq buf (find-buffer-visiting tmpfile))
14316 (set-buffer buf)
14317 (goto-char (point-min))
14318 (if (re-search-forward "^BEGIN:VEVENT" nil t)
14319 (setq b (match-beginning 0)))
14320 (goto-char (point-max))
14321 (if (re-search-backward "^END:VEVENT" nil t)
14322 (setq e (match-end 0)))
14323 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
14324 (kill-buffer buf)
14325 (delete-file tmpfile)
14326 rtn))
14328 (defun org-closest-date (start current change prefer show-all)
14329 "Find the date closest to CURRENT that is consistent with START and CHANGE.
14330 When PREFER is `past' return a date that is either CURRENT or past.
14331 When PREFER is `future', return a date that is either CURRENT or future.
14332 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
14333 ;; Make the proper lists from the dates
14334 (catch 'exit
14335 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
14336 dn dw sday cday n1 n2 n0
14337 d m y y1 y2 date1 date2 nmonths nm ny m2)
14339 (setq start (org-date-to-gregorian start)
14340 current (org-date-to-gregorian
14341 (if show-all
14342 current
14343 (time-to-days (current-time))))
14344 sday (calendar-absolute-from-gregorian start)
14345 cday (calendar-absolute-from-gregorian current))
14347 (if (<= cday sday) (throw 'exit sday))
14349 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
14350 (setq dn (string-to-number (match-string 1 change))
14351 dw (cdr (assoc (match-string 2 change) a1)))
14352 (error "Invalid change specifyer: %s" change))
14353 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
14354 (cond
14355 ((eq dw 'day)
14356 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
14357 n2 (+ n1 dn)))
14358 ((eq dw 'year)
14359 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
14360 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
14361 (setq date1 (list m d y1)
14362 n1 (calendar-absolute-from-gregorian date1)
14363 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
14364 n2 (calendar-absolute-from-gregorian date2)))
14365 ((eq dw 'month)
14366 ;; approx number of month between the two dates
14367 (setq nmonths (floor (/ (- cday sday) 30.436875)))
14368 ;; How often does dn fit in there?
14369 (setq d (nth 1 start) m (car start) y (nth 2 start)
14370 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
14371 m (+ m nm)
14372 ny (floor (/ m 12))
14373 y (+ y ny)
14374 m (- m (* ny 12)))
14375 (while (> m 12) (setq m (- m 12) y (1+ y)))
14376 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14377 (setq m2 (+ m dn) y2 y)
14378 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14379 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14380 (while (<= n2 cday)
14381 (setq n1 n2 m m2 y y2)
14382 (setq m2 (+ m dn) y2 y)
14383 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14384 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14385 ;; Make sure n1 is the earlier date
14386 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14387 (if show-all
14388 (cond
14389 ((eq prefer 'past) (if (= cday n2) n2 n1))
14390 ((eq prefer 'future) (if (= cday n1) n1 n2))
14391 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14392 (cond
14393 ((eq prefer 'past) (if (= cday n2) n2 n1))
14394 ((eq prefer 'future) (if (= cday n1) n1 n2))
14395 (t (if (= cday n1) n1 n2)))))))
14397 (defun org-date-to-gregorian (date)
14398 "Turn any specification of DATE into a gregorian date for the calendar."
14399 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14400 ((and (listp date) (= (length date) 3)) date)
14401 ((stringp date)
14402 (setq date (org-parse-time-string date))
14403 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14404 ((listp date)
14405 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14407 (defun org-parse-time-string (s &optional nodefault)
14408 "Parse the standard Org-mode time string.
14409 This should be a lot faster than the normal `parse-time-string'.
14410 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14411 hour and minute fields will be nil if not given."
14412 (if (string-match org-ts-regexp0 s)
14413 (list 0
14414 (if (or (match-beginning 8) (not nodefault))
14415 (string-to-number (or (match-string 8 s) "0")))
14416 (if (or (match-beginning 7) (not nodefault))
14417 (string-to-number (or (match-string 7 s) "0")))
14418 (string-to-number (match-string 4 s))
14419 (string-to-number (match-string 3 s))
14420 (string-to-number (match-string 2 s))
14421 nil nil nil)
14422 (error "Not a standard Org-mode time string: %s" s)))
14424 (defun org-timestamp-up (&optional arg)
14425 "Increase the date item at the cursor by one.
14426 If the cursor is on the year, change the year. If it is on the month or
14427 the day, change that.
14428 With prefix ARG, change by that many units."
14429 (interactive "p")
14430 (org-timestamp-change (prefix-numeric-value arg)))
14432 (defun org-timestamp-down (&optional arg)
14433 "Decrease the date item at the cursor by one.
14434 If the cursor is on the year, change the year. If it is on the month or
14435 the day, change that.
14436 With prefix ARG, change by that many units."
14437 (interactive "p")
14438 (org-timestamp-change (- (prefix-numeric-value arg))))
14440 (defun org-timestamp-up-day (&optional arg)
14441 "Increase 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 'up)
14447 (org-timestamp-change (prefix-numeric-value arg) 'day)))
14449 (defun org-timestamp-down-day (&optional arg)
14450 "Decrease the date in the time stamp by one day.
14451 With prefix ARG, change that many days."
14452 (interactive "p")
14453 (if (and (not (org-at-timestamp-p t))
14454 (org-on-heading-p))
14455 (org-todo 'down)
14456 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
14458 (defun org-at-timestamp-p (&optional inactive-ok)
14459 "Determine if the cursor is in or at a timestamp."
14460 (interactive)
14461 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
14462 (pos (point))
14463 (ans (or (looking-at tsr)
14464 (save-excursion
14465 (skip-chars-backward "^[<\n\r\t")
14466 (if (> (point) (point-min)) (backward-char 1))
14467 (and (looking-at tsr)
14468 (> (- (match-end 0) pos) -1))))))
14469 (and ans
14470 (boundp 'org-ts-what)
14471 (setq org-ts-what
14472 (cond
14473 ((= pos (match-beginning 0)) 'bracket)
14474 ((= pos (1- (match-end 0))) 'bracket)
14475 ((org-pos-in-match-range pos 2) 'year)
14476 ((org-pos-in-match-range pos 3) 'month)
14477 ((org-pos-in-match-range pos 7) 'hour)
14478 ((org-pos-in-match-range pos 8) 'minute)
14479 ((or (org-pos-in-match-range pos 4)
14480 (org-pos-in-match-range pos 5)) 'day)
14481 ((and (> pos (or (match-end 8) (match-end 5)))
14482 (< pos (match-end 0)))
14483 (- pos (or (match-end 8) (match-end 5))))
14484 (t 'day))))
14485 ans))
14487 (defun org-toggle-timestamp-type ()
14488 "Toggle the type (<active> or [inactive]) of a time stamp."
14489 (interactive)
14490 (when (org-at-timestamp-p t)
14491 (let ((beg (match-beginning 0)) (end (match-end 0))
14492 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14493 (save-excursion
14494 (goto-char beg)
14495 (while (re-search-forward "[][<>]" end t)
14496 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14497 t t)))
14498 (message "Timestamp is now %sactive"
14499 (if (equal (char-after beg) ?<) "" "in")))))
14501 (defun org-timestamp-change (n &optional what)
14502 "Change the date in the time stamp at point.
14503 The date will be changed by N times WHAT. WHAT can be `day', `month',
14504 `year', `minute', `second'. If WHAT is not given, the cursor position
14505 in the timestamp determines what will be changed."
14506 (let ((pos (point))
14507 with-hm inactive
14508 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14509 org-ts-what
14510 extra rem
14511 ts time time0)
14512 (if (not (org-at-timestamp-p t))
14513 (error "Not at a timestamp"))
14514 (if (and (not what) (eq org-ts-what 'bracket))
14515 (org-toggle-timestamp-type)
14516 (if (and (not what) (not (eq org-ts-what 'day))
14517 org-display-custom-times
14518 (get-text-property (point) 'display)
14519 (not (get-text-property (1- (point)) 'display)))
14520 (setq org-ts-what 'day))
14521 (setq org-ts-what (or what org-ts-what)
14522 inactive (= (char-after (match-beginning 0)) ?\[)
14523 ts (match-string 0))
14524 (replace-match "")
14525 (if (string-match
14526 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14528 (setq extra (match-string 1 ts)))
14529 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14530 (setq with-hm t))
14531 (setq time0 (org-parse-time-string ts))
14532 (when (and (eq org-ts-what 'minute)
14533 (eq current-prefix-arg nil))
14534 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14535 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14536 (setcar (cdr time0) (+ (nth 1 time0)
14537 (if (> n 0) (- rem) (- dm rem))))))
14538 (setq time
14539 (encode-time (or (car time0) 0)
14540 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14541 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14542 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14543 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14544 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14545 (nthcdr 6 time0)))
14546 (when (and (member org-ts-what '(hour minute))
14547 extra
14548 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14549 (setq extra (org-modify-ts-extra
14550 extra
14551 (if (eq org-ts-what 'hour) 2 5)
14552 n dm)))
14553 (when (integerp org-ts-what)
14554 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14555 (if (eq what 'calendar)
14556 (let ((cal-date (org-get-date-from-calendar)))
14557 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14558 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14559 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14560 (setcar time0 (or (car time0) 0))
14561 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
14562 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
14563 (setq time (apply 'encode-time time0))))
14564 (setq org-last-changed-timestamp
14565 (org-insert-time-stamp time with-hm inactive nil nil extra))
14566 (org-clock-update-time-maybe)
14567 (goto-char pos)
14568 ;; Try to recenter the calendar window, if any
14569 (if (and org-calendar-follow-timestamp-change
14570 (get-buffer-window "*Calendar*" t)
14571 (memq org-ts-what '(day month year)))
14572 (org-recenter-calendar (time-to-days time))))))
14574 (defun org-modify-ts-extra (s pos n dm)
14575 "Change the different parts of the lead-time and repeat fields in timestamp."
14576 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
14577 ng h m new rem)
14578 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
14579 (cond
14580 ((or (org-pos-in-match-range pos 2)
14581 (org-pos-in-match-range pos 3))
14582 (setq m (string-to-number (match-string 3 s))
14583 h (string-to-number (match-string 2 s)))
14584 (if (org-pos-in-match-range pos 2)
14585 (setq h (+ h n))
14586 (setq n (* dm (org-no-warnings (signum n))))
14587 (when (not (= 0 (setq rem (% m dm))))
14588 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
14589 (setq m (+ m n)))
14590 (if (< m 0) (setq m (+ m 60) h (1- h)))
14591 (if (> m 59) (setq m (- m 60) h (1+ h)))
14592 (setq h (min 24 (max 0 h)))
14593 (setq ng 1 new (format "-%02d:%02d" h m)))
14594 ((org-pos-in-match-range pos 6)
14595 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
14596 ((org-pos-in-match-range pos 5)
14597 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
14599 ((org-pos-in-match-range pos 9)
14600 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
14601 ((org-pos-in-match-range pos 8)
14602 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
14604 (when ng
14605 (setq s (concat
14606 (substring s 0 (match-beginning ng))
14608 (substring s (match-end ng))))))
14611 (defun org-recenter-calendar (date)
14612 "If the calendar is visible, recenter it to DATE."
14613 (let* ((win (selected-window))
14614 (cwin (get-buffer-window "*Calendar*" t))
14615 (calendar-move-hook nil))
14616 (when cwin
14617 (select-window cwin)
14618 (calendar-goto-date (if (listp date) date
14619 (calendar-gregorian-from-absolute date)))
14620 (select-window win))))
14622 (defun org-goto-calendar (&optional arg)
14623 "Go to the Emacs calendar at the current date.
14624 If there is a time stamp in the current line, go to that date.
14625 A prefix ARG can be used to force the current date."
14626 (interactive "P")
14627 (let ((tsr org-ts-regexp) diff
14628 (calendar-move-hook nil)
14629 (calendar-view-holidays-initially-flag nil)
14630 (calendar-view-diary-initially-flag nil))
14631 (if (or (org-at-timestamp-p)
14632 (save-excursion
14633 (beginning-of-line 1)
14634 (looking-at (concat ".*" tsr))))
14635 (let ((d1 (time-to-days (current-time)))
14636 (d2 (time-to-days
14637 (org-time-string-to-time (match-string 1)))))
14638 (setq diff (- d2 d1))))
14639 (calendar)
14640 (calendar-goto-today)
14641 (if (and diff (not arg)) (calendar-forward-day diff))))
14643 (defun org-get-date-from-calendar ()
14644 "Return a list (month day year) of date at point in calendar."
14645 (with-current-buffer "*Calendar*"
14646 (save-match-data
14647 (calendar-cursor-to-date))))
14649 (defun org-date-from-calendar ()
14650 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14651 If there is already a time stamp at the cursor position, update it."
14652 (interactive)
14653 (if (org-at-timestamp-p t)
14654 (org-timestamp-change 0 'calendar)
14655 (let ((cal-date (org-get-date-from-calendar)))
14656 (org-insert-time-stamp
14657 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14659 (defun org-minutes-to-hh:mm-string (m)
14660 "Compute H:MM from a number of minutes."
14661 (let ((h (/ m 60)))
14662 (setq m (- m (* 60 h)))
14663 (format org-time-clocksum-format h m)))
14665 (defun org-hh:mm-string-to-minutes (s)
14666 "Convert a string H:MM to a number of minutes.
14667 If the string is just a number, interpret it as minutes.
14668 In fact, the first hh:mm or number in the string will be taken,
14669 there can be extra stuff in the string.
14670 If no number is found, the return value is 0."
14671 (cond
14672 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14673 (+ (* (string-to-number (match-string 1 s)) 60)
14674 (string-to-number (match-string 2 s))))
14675 ((string-match "\\([0-9]+\\)" s)
14676 (string-to-number (match-string 1 s)))
14677 (t 0)))
14679 ;;;; Files
14681 (defun org-save-all-org-buffers ()
14682 "Save all Org-mode buffers without user confirmation."
14683 (interactive)
14684 (message "Saving all Org-mode buffers...")
14685 (save-some-buffers t 'org-mode-p)
14686 (when (featurep 'org-id) (org-id-locations-save))
14687 (message "Saving all Org-mode buffers... done"))
14689 (defun org-revert-all-org-buffers ()
14690 "Revert all Org-mode buffers.
14691 Prompt for confirmation when there are unsaved changes.
14692 Be sure you know what you are doing before letting this function
14693 overwrite your changes.
14695 This function is useful in a setup where one tracks org files
14696 with a version control system, to revert on one machine after pulling
14697 changes from another. I believe the procedure must be like this:
14699 1. M-x org-save-all-org-buffers
14700 2. Pull changes from the other machine, resolve conflicts
14701 3. M-x org-revert-all-org-buffers"
14702 (interactive)
14703 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14704 (error "Abort"))
14705 (save-excursion
14706 (save-window-excursion
14707 (mapc
14708 (lambda (b)
14709 (when (and (with-current-buffer b (org-mode-p))
14710 (with-current-buffer b buffer-file-name))
14711 (switch-to-buffer b)
14712 (revert-buffer t 'no-confirm)))
14713 (buffer-list))
14714 (when (and (featurep 'org-id) org-id-track-globally)
14715 (org-id-locations-load)))))
14717 ;;;; Agenda files
14719 ;;;###autoload
14720 (defun org-iswitchb (&optional arg)
14721 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14722 With a prefix argument, restrict available to files.
14723 With two prefix arguments, restrict available buffers to agenda files."
14724 (interactive "P")
14725 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14726 ((equal arg '(16)) (org-buffer-list 'agenda))
14727 (t (org-buffer-list)))))
14728 (switch-to-buffer
14729 (org-icompleting-read "Org buffer: "
14730 (mapcar 'list (mapcar 'buffer-name blist))
14731 nil t))))
14733 ;;;###autoload
14734 (defalias 'org-ido-switchb 'org-iswitchb)
14736 (defun org-buffer-list (&optional predicate exclude-tmp)
14737 "Return a list of Org buffers.
14738 PREDICATE can be `export', `files' or `agenda'.
14740 export restrict the list to Export buffers.
14741 files restrict the list to buffers visiting Org files.
14742 agenda restrict the list to buffers visiting agenda files.
14744 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14745 (let* ((bfn nil)
14746 (agenda-files (and (eq predicate 'agenda)
14747 (mapcar 'file-truename (org-agenda-files t))))
14748 (filter
14749 (cond
14750 ((eq predicate 'files)
14751 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14752 ((eq predicate 'export)
14753 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14754 ((eq predicate 'agenda)
14755 (lambda (b)
14756 (with-current-buffer b
14757 (and (eq major-mode 'org-mode)
14758 (setq bfn (buffer-file-name b))
14759 (member (file-truename bfn) agenda-files)))))
14760 (t (lambda (b) (with-current-buffer b
14761 (or (eq major-mode 'org-mode)
14762 (string-match "\*Org .*Export"
14763 (buffer-name b)))))))))
14764 (delq nil
14765 (mapcar
14766 (lambda(b)
14767 (if (and (funcall filter b)
14768 (or (not exclude-tmp)
14769 (not (string-match "tmp" (buffer-name b)))))
14771 nil))
14772 (buffer-list)))))
14774 (defun org-agenda-files (&optional unrestricted archives)
14775 "Get the list of agenda files.
14776 Optional UNRESTRICTED means return the full list even if a restriction
14777 is currently in place.
14778 When ARCHIVES is t, include all archive files that are really being
14779 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14780 `org-agenda-archives-mode' is t."
14781 (let ((files
14782 (cond
14783 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14784 ((stringp org-agenda-files) (org-read-agenda-file-list))
14785 ((listp org-agenda-files) org-agenda-files)
14786 (t (error "Invalid value of `org-agenda-files'")))))
14787 (setq files (apply 'append
14788 (mapcar (lambda (f)
14789 (if (file-directory-p f)
14790 (directory-files
14791 f t org-agenda-file-regexp)
14792 (list f)))
14793 files)))
14794 (when org-agenda-skip-unavailable-files
14795 (setq files (delq nil
14796 (mapcar (function
14797 (lambda (file)
14798 (and (file-readable-p file) file)))
14799 files))))
14800 (when (or (eq archives t)
14801 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14802 (setq files (org-add-archive-files files)))
14803 files))
14805 (defun org-edit-agenda-file-list ()
14806 "Edit the list of agenda files.
14807 Depending on setup, this either uses customize to edit the variable
14808 `org-agenda-files', or it visits the file that is holding the list. In the
14809 latter case, the buffer is set up in a way that saving it automatically kills
14810 the buffer and restores the previous window configuration."
14811 (interactive)
14812 (if (stringp org-agenda-files)
14813 (let ((cw (current-window-configuration)))
14814 (find-file org-agenda-files)
14815 (org-set-local 'org-window-configuration cw)
14816 (org-add-hook 'after-save-hook
14817 (lambda ()
14818 (set-window-configuration
14819 (prog1 org-window-configuration
14820 (kill-buffer (current-buffer))))
14821 (org-install-agenda-files-menu)
14822 (message "New agenda file list installed"))
14823 nil 'local)
14824 (message "%s" (substitute-command-keys
14825 "Edit list and finish with \\[save-buffer]")))
14826 (customize-variable 'org-agenda-files)))
14828 (defun org-store-new-agenda-file-list (list)
14829 "Set new value for the agenda file list and save it correctly."
14830 (if (stringp org-agenda-files)
14831 (let ((fe (org-read-agenda-file-list t)) b u)
14832 (while (setq b (find-buffer-visiting org-agenda-files))
14833 (kill-buffer b))
14834 (with-temp-file org-agenda-files
14835 (insert
14836 (mapconcat
14837 (lambda (f) ;; Keep un-expanded entries.
14838 (if (setq u (assoc f fe))
14839 (cdr u)
14841 list "\n")
14842 "\n")))
14843 (let ((org-mode-hook nil) (org-inhibit-startup t)
14844 (org-insert-mode-line-in-empty-file nil))
14845 (setq org-agenda-files list)
14846 (customize-save-variable 'org-agenda-files org-agenda-files))))
14848 (defun org-read-agenda-file-list (&optional pair-with-expansion)
14849 "Read the list of agenda files from a file.
14850 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
14851 filenames, used by `org-store-new-agenda-file-list' to write back
14852 un-expanded file names."
14853 (when (file-directory-p org-agenda-files)
14854 (error "`org-agenda-files' cannot be a single directory"))
14855 (when (stringp org-agenda-files)
14856 (with-temp-buffer
14857 (insert-file-contents org-agenda-files)
14858 (mapcar
14859 (lambda (f)
14860 (let ((e (expand-file-name (substitute-in-file-name f)
14861 org-directory)))
14862 (if pair-with-expansion
14863 (cons e f)
14864 e)))
14865 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
14867 ;;;###autoload
14868 (defun org-cycle-agenda-files ()
14869 "Cycle through the files in `org-agenda-files'.
14870 If the current buffer visits an agenda file, find the next one in the list.
14871 If the current buffer does not, find the first agenda file."
14872 (interactive)
14873 (let* ((fs (org-agenda-files t))
14874 (files (append fs (list (car fs))))
14875 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14876 file)
14877 (unless files (error "No agenda files"))
14878 (catch 'exit
14879 (while (setq file (pop files))
14880 (if (equal (file-truename file) tcf)
14881 (when (car files)
14882 (find-file (car files))
14883 (throw 'exit t))))
14884 (find-file (car fs)))
14885 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14887 (defun org-agenda-file-to-front (&optional to-end)
14888 "Move/add the current file to the top of the agenda file list.
14889 If the file is not present in the list, it is added to the front. If it is
14890 present, it is moved there. With optional argument TO-END, add/move to the
14891 end of the list."
14892 (interactive "P")
14893 (let ((org-agenda-skip-unavailable-files nil)
14894 (file-alist (mapcar (lambda (x)
14895 (cons (file-truename x) x))
14896 (org-agenda-files t)))
14897 (ctf (file-truename buffer-file-name))
14898 x had)
14899 (setq x (assoc ctf file-alist) had x)
14901 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14902 (if to-end
14903 (setq file-alist (append (delq x file-alist) (list x)))
14904 (setq file-alist (cons x (delq x file-alist))))
14905 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14906 (org-install-agenda-files-menu)
14907 (message "File %s to %s of agenda file list"
14908 (if had "moved" "added") (if to-end "end" "front"))))
14910 (defun org-remove-file (&optional file)
14911 "Remove current file from the list of files in variable `org-agenda-files'.
14912 These are the files which are being checked for agenda entries.
14913 Optional argument FILE means use this file instead of the current."
14914 (interactive)
14915 (let* ((org-agenda-skip-unavailable-files nil)
14916 (file (or file buffer-file-name))
14917 (true-file (file-truename file))
14918 (afile (abbreviate-file-name file))
14919 (files (delq nil (mapcar
14920 (lambda (x)
14921 (if (equal true-file
14922 (file-truename x))
14923 nil x))
14924 (org-agenda-files t)))))
14925 (if (not (= (length files) (length (org-agenda-files t))))
14926 (progn
14927 (org-store-new-agenda-file-list files)
14928 (org-install-agenda-files-menu)
14929 (message "Removed file: %s" afile))
14930 (message "File was not in list: %s (not removed)" afile))))
14932 (defun org-file-menu-entry (file)
14933 (vector file (list 'find-file file) t))
14935 (defun org-check-agenda-file (file)
14936 "Make sure FILE exists. If not, ask user what to do."
14937 (when (not (file-exists-p file))
14938 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14939 (abbreviate-file-name file))
14940 (let ((r (downcase (read-char-exclusive))))
14941 (cond
14942 ((equal r ?r)
14943 (org-remove-file file)
14944 (throw 'nextfile t))
14945 (t (error "Abort"))))))
14947 (defun org-get-agenda-file-buffer (file)
14948 "Get a buffer visiting FILE. If the buffer needs to be created, add
14949 it to the list of buffers which might be released later."
14950 (let ((buf (org-find-base-buffer-visiting file)))
14951 (if buf
14952 buf ; just return it
14953 ;; Make a new buffer and remember it
14954 (setq buf (find-file-noselect file))
14955 (if buf (push buf org-agenda-new-buffers))
14956 buf)))
14958 (defun org-release-buffers (blist)
14959 "Release all buffers in list, asking the user for confirmation when needed.
14960 When a buffer is unmodified, it is just killed. When modified, it is saved
14961 \(if the user agrees) and then killed."
14962 (let (buf file)
14963 (while (setq buf (pop blist))
14964 (setq file (buffer-file-name buf))
14965 (when (and (buffer-modified-p buf)
14966 file
14967 (y-or-n-p (format "Save file %s? " file)))
14968 (with-current-buffer buf (save-buffer)))
14969 (kill-buffer buf))))
14971 (defun org-prepare-agenda-buffers (files)
14972 "Create buffers for all agenda files, protect archived trees and comments."
14973 (interactive)
14974 (let ((pa '(:org-archived t))
14975 (pc '(:org-comment t))
14976 (pall '(:org-archived t :org-comment t))
14977 (inhibit-read-only t)
14978 (rea (concat ":" org-archive-tag ":"))
14979 bmp file re)
14980 (save-excursion
14981 (save-restriction
14982 (while (setq file (pop files))
14983 (catch 'nextfile
14984 (if (bufferp file)
14985 (set-buffer file)
14986 (org-check-agenda-file file)
14987 (set-buffer (org-get-agenda-file-buffer file)))
14988 (widen)
14989 (setq bmp (buffer-modified-p))
14990 (org-refresh-category-properties)
14991 (setq org-todo-keywords-for-agenda
14992 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14993 (setq org-done-keywords-for-agenda
14994 (append org-done-keywords-for-agenda org-done-keywords))
14995 (setq org-todo-keyword-alist-for-agenda
14996 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14997 (setq org-drawers-for-agenda
14998 (append org-drawers-for-agenda org-drawers))
14999 (setq org-tag-alist-for-agenda
15000 (append org-tag-alist-for-agenda org-tag-alist))
15002 (save-excursion
15003 (remove-text-properties (point-min) (point-max) pall)
15004 (when org-agenda-skip-archived-trees
15005 (goto-char (point-min))
15006 (while (re-search-forward rea nil t)
15007 (if (org-on-heading-p t)
15008 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
15009 (goto-char (point-min))
15010 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
15011 (while (re-search-forward re nil t)
15012 (add-text-properties
15013 (match-beginning 0) (org-end-of-subtree t) pc)))
15014 (set-buffer-modified-p bmp)))))
15015 (setq org-todo-keywords-for-agenda
15016 (org-uniquify org-todo-keywords-for-agenda))
15017 (setq org-todo-keyword-alist-for-agenda
15018 (org-uniquify org-todo-keyword-alist-for-agenda)
15019 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
15021 ;;;; Embedded LaTeX
15023 (defvar org-cdlatex-mode-map (make-sparse-keymap)
15024 "Keymap for the minor `org-cdlatex-mode'.")
15026 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
15027 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
15028 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
15029 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
15030 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
15032 (defvar org-cdlatex-texmathp-advice-is-done nil
15033 "Flag remembering if we have applied the advice to texmathp already.")
15035 (define-minor-mode org-cdlatex-mode
15036 "Toggle the minor `org-cdlatex-mode'.
15037 This mode supports entering LaTeX environment and math in LaTeX fragments
15038 in Org-mode.
15039 \\{org-cdlatex-mode-map}"
15040 nil " OCDL" nil
15041 (when org-cdlatex-mode (require 'cdlatex))
15042 (unless org-cdlatex-texmathp-advice-is-done
15043 (setq org-cdlatex-texmathp-advice-is-done t)
15044 (defadvice texmathp (around org-math-always-on activate)
15045 "Always return t in org-mode buffers.
15046 This is because we want to insert math symbols without dollars even outside
15047 the LaTeX math segments. If Orgmode thinks that point is actually inside
15048 an embedded LaTeX fragment, let texmathp do its job.
15049 \\[org-cdlatex-mode-map]"
15050 (interactive)
15051 (let (p)
15052 (cond
15053 ((not (org-mode-p)) ad-do-it)
15054 ((eq this-command 'cdlatex-math-symbol)
15055 (setq ad-return-value t
15056 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15058 (let ((p (org-inside-LaTeX-fragment-p)))
15059 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15060 (setq ad-return-value t
15061 texmathp-why '("Org-mode embedded math" . 0))
15062 (if p ad-do-it)))))))))
15064 (defun turn-on-org-cdlatex ()
15065 "Unconditionally turn on `org-cdlatex-mode'."
15066 (org-cdlatex-mode 1))
15068 (defun org-inside-LaTeX-fragment-p ()
15069 "Test if point is inside a LaTeX fragment.
15070 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15071 sequence appearing also before point.
15072 Even though the matchers for math are configurable, this function assumes
15073 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15074 delimiters are skipped when they have been removed by customization.
15075 The return value is nil, or a cons cell with the delimiter and
15076 and the position of this delimiter.
15078 This function does a reasonably good job, but can locally be fooled by
15079 for example currency specifications. For example it will assume being in
15080 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15081 fragments that are properly closed, but during editing, we have to live
15082 with the uncertainty caused by missing closing delimiters. This function
15083 looks only before point, not after."
15084 (catch 'exit
15085 (let ((pos (point))
15086 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15087 (lim (progn
15088 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15089 (point)))
15090 dd-on str (start 0) m re)
15091 (goto-char pos)
15092 (when dodollar
15093 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15094 re (nth 1 (assoc "$" org-latex-regexps)))
15095 (while (string-match re str start)
15096 (cond
15097 ((= (match-end 0) (length str))
15098 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
15099 ((= (match-end 0) (- (length str) 5))
15100 (throw 'exit nil))
15101 (t (setq start (match-end 0))))))
15102 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15103 (goto-char pos)
15104 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15105 (and (match-beginning 2) (throw 'exit nil))
15106 ;; count $$
15107 (while (re-search-backward "\\$\\$" lim t)
15108 (setq dd-on (not dd-on)))
15109 (goto-char pos)
15110 (if dd-on (cons "$$" m))))))
15112 (defun org-inside-latex-macro-p ()
15113 "Is point inside a LaTeX macro or its arguments?"
15114 (save-match-data
15115 (org-in-regexp
15116 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
15118 (defun test ()
15119 (interactive)
15120 (message "%s" (org-inside-latex-macro-p)))
15122 (defun org-try-cdlatex-tab ()
15123 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15124 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15125 - inside a LaTeX fragment, or
15126 - after the first word in a line, where an abbreviation expansion could
15127 insert a LaTeX environment."
15128 (when org-cdlatex-mode
15129 (cond
15130 ((save-excursion
15131 (skip-chars-backward "a-zA-Z0-9*")
15132 (skip-chars-backward " \t")
15133 (bolp))
15134 (cdlatex-tab) t)
15135 ((org-inside-LaTeX-fragment-p)
15136 (cdlatex-tab) t)
15137 (t nil))))
15139 (defun org-cdlatex-underscore-caret (&optional arg)
15140 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15141 Revert to the normal definition outside of these fragments."
15142 (interactive "P")
15143 (if (org-inside-LaTeX-fragment-p)
15144 (call-interactively 'cdlatex-sub-superscript)
15145 (let (org-cdlatex-mode)
15146 (call-interactively (key-binding (vector last-input-event))))))
15148 (defun org-cdlatex-math-modify (&optional arg)
15149 "Execute `cdlatex-math-modify' in LaTeX fragments.
15150 Revert to the normal definition outside of these fragments."
15151 (interactive "P")
15152 (if (org-inside-LaTeX-fragment-p)
15153 (call-interactively 'cdlatex-math-modify)
15154 (let (org-cdlatex-mode)
15155 (call-interactively (key-binding (vector last-input-event))))))
15157 (defvar org-latex-fragment-image-overlays nil
15158 "List of overlays carrying the images of latex fragments.")
15159 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15161 (defun org-remove-latex-fragment-image-overlays ()
15162 "Remove all overlays with LaTeX fragment images in current buffer."
15163 (mapc 'delete-overlay org-latex-fragment-image-overlays)
15164 (setq org-latex-fragment-image-overlays nil))
15166 (defun org-preview-latex-fragment (&optional subtree)
15167 "Preview the LaTeX fragment at point, or all locally or globally.
15168 If the cursor is in a LaTeX fragment, create the image and overlay
15169 it over the source code. If there is no fragment at point, display
15170 all fragments in the current text, from one headline to the next. With
15171 prefix SUBTREE, display all fragments in the current subtree. With a
15172 double prefix `C-u C-u', or when the cursor is before the first headline,
15173 display all fragments in the buffer.
15174 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15175 (interactive "P")
15176 (org-remove-latex-fragment-image-overlays)
15177 (save-excursion
15178 (save-restriction
15179 (let (beg end at msg)
15180 (cond
15181 ((or (equal subtree '(16))
15182 (not (save-excursion
15183 (re-search-backward (concat "^" outline-regexp) nil t))))
15184 (setq beg (point-min) end (point-max)
15185 msg "Creating images for buffer...%s"))
15186 ((equal subtree '(4))
15187 (org-back-to-heading)
15188 (setq beg (point) end (org-end-of-subtree t)
15189 msg "Creating images for subtree...%s"))
15191 (if (setq at (org-inside-LaTeX-fragment-p))
15192 (goto-char (max (point-min) (- (cdr at) 2)))
15193 (org-back-to-heading))
15194 (setq beg (point) end (progn (outline-next-heading) (point))
15195 msg (if at "Creating image...%s"
15196 "Creating images for entry...%s"))))
15197 (message msg "")
15198 (narrow-to-region beg end)
15199 (goto-char beg)
15200 (org-format-latex
15201 (concat "ltxpng/" (file-name-sans-extension
15202 (file-name-nondirectory
15203 buffer-file-name)))
15204 default-directory 'overlays msg at 'forbuffer)
15205 (message msg "done. Use `C-c C-c' to remove images.")))))
15207 (defvar org-latex-regexps
15208 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15209 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15210 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15211 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15212 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15213 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15214 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
15215 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
15216 "Regular expressions for matching embedded LaTeX.")
15218 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
15219 "Replace LaTeX fragments with links to an image, and produce images.
15220 Some of the options can be changed using the variable
15221 `org-format-latex-options'."
15222 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15223 (let* ((prefixnodir (file-name-nondirectory prefix))
15224 (absprefix (expand-file-name prefix dir))
15225 (todir (file-name-directory absprefix))
15226 (opt org-format-latex-options)
15227 (matchers (plist-get opt :matchers))
15228 (re-list org-latex-regexps)
15229 (org-format-latex-header-extra
15230 (plist-get (org-infile-export-plist) :latex-header-extra))
15231 (cnt 0) txt hash link beg end re e checkdir
15232 executables-checked
15233 m n block linkfile movefile ov)
15234 ;; Check the different regular expressions
15235 (while (setq e (pop re-list))
15236 (setq m (car e) re (nth 1 e) n (nth 2 e)
15237 block (if (nth 3 e) "\n\n" ""))
15238 (when (member m matchers)
15239 (goto-char (point-min))
15240 (while (re-search-forward re nil t)
15241 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
15242 (not (get-text-property (match-beginning n)
15243 'org-protected))
15244 (or (not overlays)
15245 (not (eq (get-char-property (match-beginning n)
15246 'org-overlay-type)
15247 'org-latex-overlay))))
15248 (setq txt (match-string n)
15249 beg (match-beginning n) end (match-end n)
15250 cnt (1+ cnt))
15251 (let (print-length print-level) ; make sure full list is printed
15252 (setq hash (sha1 (prin1-to-string
15253 (list org-format-latex-header
15254 org-format-latex-header-extra
15255 org-export-latex-default-packages-alist
15256 org-export-latex-packages-alist
15257 org-format-latex-options
15258 forbuffer txt)))
15259 linkfile (format "%s_%s.png" prefix hash)
15260 movefile (format "%s_%s.png" absprefix hash)))
15261 (setq link (concat block "[[file:" linkfile "]]" block))
15262 (if msg (message msg cnt))
15263 (goto-char beg)
15264 (unless checkdir ; make sure the directory exists
15265 (setq checkdir t)
15266 (or (file-directory-p todir) (make-directory todir)))
15268 (unless executables-checked
15269 (org-check-external-command
15270 "latex" "needed to convert LaTeX fragments to images")
15271 (org-check-external-command
15272 "dvipng" "needed to convert LaTeX fragments to images")
15273 (setq executables-checked t))
15275 (unless (file-exists-p movefile)
15276 (org-create-formula-image
15277 txt movefile opt forbuffer))
15278 (if overlays
15279 (progn
15280 (mapc (lambda (o)
15281 (if (eq (overlay-get o 'org-overlay-type)
15282 'org-latex-overlay)
15283 (delete-overlay o)))
15284 (overlays-in beg end))
15285 (setq ov (make-overlay beg end))
15286 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
15287 (if (featurep 'xemacs)
15288 (progn
15289 (overlay-put ov 'invisible t)
15290 (overlay-put
15291 ov 'end-glyph
15292 (make-glyph (vector 'png :file movefile))))
15293 (overlay-put
15294 ov 'display
15295 (list 'image :type 'png :file movefile :ascent 'center)))
15296 (push ov org-latex-fragment-image-overlays)
15297 (goto-char end))
15298 (delete-region beg end)
15299 (insert (org-add-props link
15300 (list 'org-latex-src
15301 (replace-regexp-in-string "\"" "" txt)))))))))))
15303 ;; This function borrows from Ganesh Swami's latex2png.el
15304 (defun org-create-formula-image (string tofile options buffer)
15305 "This calls dvipng."
15306 (require 'org-latex)
15307 (let* ((tmpdir (if (featurep 'xemacs)
15308 (temp-directory)
15309 temporary-file-directory))
15310 (texfilebase (make-temp-name
15311 (expand-file-name "orgtex" tmpdir)))
15312 (texfile (concat texfilebase ".tex"))
15313 (dvifile (concat texfilebase ".dvi"))
15314 (pngfile (concat texfilebase ".png"))
15315 (fnh (if (featurep 'xemacs)
15316 (font-height (get-face-font 'default))
15317 (face-attribute 'default :height nil)))
15318 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
15319 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
15320 (fg (or (plist-get options (if buffer :foreground :html-foreground))
15321 "Black"))
15322 (bg (or (plist-get options (if buffer :background :html-background))
15323 "Transparent")))
15324 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
15325 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
15326 (with-temp-file texfile
15327 (insert (org-splice-latex-header
15328 org-format-latex-header
15329 org-export-latex-default-packages-alist
15330 org-export-latex-packages-alist
15331 org-format-latex-header-extra))
15332 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
15333 (require 'org-latex)
15334 (org-export-latex-fix-inputenc))
15335 (let ((dir default-directory))
15336 (condition-case nil
15337 (progn
15338 (cd tmpdir)
15339 (call-process "latex" nil nil nil texfile))
15340 (error nil))
15341 (cd dir))
15342 (if (not (file-exists-p dvifile))
15343 (progn (message "Failed to create dvi file from %s" texfile) nil)
15344 (condition-case nil
15345 (call-process "dvipng" nil nil nil
15346 "-fg" fg "-bg" bg
15347 "-D" dpi
15348 ;;"-x" scale "-y" scale
15349 "-T" "tight"
15350 "-o" pngfile
15351 dvifile)
15352 (error nil))
15353 (if (not (file-exists-p pngfile))
15354 (if org-format-latex-signal-error
15355 (error "Failed to create png file from %s" texfile)
15356 (message "Failed to create png file from %s" texfile)
15357 nil)
15358 ;; Use the requested file name and clean up
15359 (copy-file pngfile tofile 'replace)
15360 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15361 (delete-file (concat texfilebase e)))
15362 pngfile))))
15364 (defun org-splice-latex-header (tpl def-pkg pkg &optional extra)
15365 "Fill a LaTeX header template TPL.
15366 In the template, the following place holders will be recognized:
15368 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
15369 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
15370 [PACKAGES] \\usepackage statements for PKG
15371 [NO-PACKAGES] do not include PKG
15372 [EXTRA] the string EXTRA
15373 [NO-EXTRA] do not include EXTRA
15375 For backward compatibility, if both the positive and the negative place
15376 holder is missing, the positive one (without the \"NO-\") will be
15377 assumed to be present at the end of the template.
15378 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
15379 EXTRA is a string."
15380 (let (rpl (end ""))
15381 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
15382 (setq rpl (if (or (match-end 1) (not def-pkg))
15383 "" (org-latex-packages-to-string def-pkg t))
15384 tpl (replace-match rpl t t tpl))
15385 (if def-pkg (setq end (org-latex-packages-to-string def-pkg))))
15387 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
15388 (setq rpl (if (or (match-end 1) (not pkg))
15389 "" (org-latex-packages-to-string pkg t))
15390 tpl (replace-match rpl t t tpl))
15391 (if pkg (setq end (concat end "\n" (org-latex-packages-to-string pkg)))))
15393 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
15394 (setq rpl (if (or (match-end 1) (not extra))
15395 "" (concat extra "\n"))
15396 tpl (replace-match rpl t t tpl))
15397 (if (and extra (string-match "\\S-" extra))
15398 (setq end (concat end "\n" extra))))
15400 (if (string-match "\\S-" end)
15401 (concat tpl "\n" end)
15402 tpl)))
15404 (defun org-latex-packages-to-string (pkg &optional newline)
15405 "Turn an alist of packages into a string with the \\usepackage macros."
15406 (setq pkg (mapconcat (lambda(p)
15407 (cond
15408 ((stringp p) p)
15409 ((equal "" (car p))
15410 (format "\\usepackage{%s}" (cadr p)))
15412 (format "\\usepackage[%s]{%s}"
15413 (car p) (cadr p)))))
15415 "\n"))
15416 (if newline (concat pkg "\n") pkg))
15418 (defun org-dvipng-color (attr)
15419 "Return an rgb color specification for dvipng."
15420 (apply 'format "rgb %s %s %s"
15421 (mapcar 'org-normalize-color
15422 (color-values (face-attribute 'default attr nil)))))
15424 (defun org-normalize-color (value)
15425 "Return string to be used as color value for an RGB component."
15426 (format "%g" (/ value 65535.0)))
15428 ;;;; Key bindings
15430 ;; Make `C-c C-x' a prefix key
15431 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
15433 ;; TAB key with modifiers
15434 (org-defkey org-mode-map "\C-i" 'org-cycle)
15435 (org-defkey org-mode-map [(tab)] 'org-cycle)
15436 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
15437 (org-defkey org-mode-map [(meta tab)] 'org-complete)
15438 (org-defkey org-mode-map "\M-\t" 'org-complete)
15439 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
15440 ;; The following line is necessary under Suse GNU/Linux
15441 (unless (featurep 'xemacs)
15442 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
15443 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
15444 (define-key org-mode-map [backtab] 'org-shifttab)
15446 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
15447 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15448 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
15450 ;; Cursor keys with modifiers
15451 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
15452 (org-defkey org-mode-map [(meta right)] 'org-metaright)
15453 (org-defkey org-mode-map [(meta up)] 'org-metaup)
15454 (org-defkey org-mode-map [(meta down)] 'org-metadown)
15456 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15457 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
15458 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
15459 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
15461 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
15462 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
15463 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
15464 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
15466 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
15467 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
15469 ;;; Extra keys for tty access.
15470 ;; We only set them when really needed because otherwise the
15471 ;; menus don't show the simple keys
15473 (when (or org-use-extra-keys
15474 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
15475 (not window-system))
15476 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
15477 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
15478 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
15479 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
15480 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
15481 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
15482 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
15483 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
15484 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
15485 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
15486 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
15487 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
15488 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
15489 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
15490 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
15491 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
15492 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
15493 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
15494 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
15495 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
15496 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
15497 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
15498 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
15499 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
15500 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
15501 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
15502 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
15503 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
15505 ;; All the other keys
15507 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15508 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
15509 (if (boundp 'narrow-map)
15510 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
15511 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
15512 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
15513 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
15514 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
15515 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
15516 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
15517 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
15518 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
15519 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
15520 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
15521 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
15522 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
15523 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
15524 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
15525 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
15526 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15527 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
15528 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
15529 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
15530 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
15531 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
15532 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
15533 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
15534 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
15535 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
15536 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
15537 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
15538 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
15539 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
15540 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
15541 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
15542 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15543 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15544 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15545 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15546 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
15547 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
15548 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15549 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
15550 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
15551 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
15552 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
15553 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15554 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
15555 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
15556 (org-defkey org-mode-map "\C-c^" 'org-sort)
15557 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15558 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
15559 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
15560 (org-defkey org-mode-map "\C-m" 'org-return)
15561 (org-defkey org-mode-map "\C-j" 'org-return-indent)
15562 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
15563 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
15564 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
15565 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
15566 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
15567 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
15568 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15569 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15570 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
15571 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
15572 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
15573 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
15574 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
15575 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15576 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
15577 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
15578 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
15579 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
15580 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
15581 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
15583 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
15584 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15585 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15586 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15588 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
15589 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15590 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15591 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
15592 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15593 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15594 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15595 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15596 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15597 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15598 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
15599 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
15600 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
15601 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
15602 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
15604 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
15605 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
15606 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
15607 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
15609 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
15611 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
15613 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
15614 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
15616 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
15619 (when (featurep 'xemacs)
15620 (org-defkey org-mode-map 'button3 'popup-mode-menu))
15623 (defconst org-speed-commands-default
15625 ("Outline Navigation")
15626 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
15627 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
15628 ("f" . (org-speed-move-safe 'org-forward-same-level))
15629 ("b" . (org-speed-move-safe 'org-backward-same-level))
15630 ("u" . (org-speed-move-safe 'outline-up-heading))
15631 ("j" . org-goto)
15632 ("g" . (org-refile t))
15633 ("Outline Visibility")
15634 ("c" . org-cycle)
15635 ("C" . org-shifttab)
15636 (" " . org-display-outline-path)
15637 ("Outline Structure Editing")
15638 ("U" . org-shiftmetaup)
15639 ("D" . org-shiftmetadown)
15640 ("r" . org-metaright)
15641 ("l" . org-metaleft)
15642 ("R" . org-shiftmetaright)
15643 ("L" . org-shiftmetaleft)
15644 ("i" . (progn (forward-char 1) (call-interactively
15645 'org-insert-heading-respect-content)))
15646 ("^" . org-sort)
15647 ("w" . org-refile)
15648 ("a" . org-archive-subtree-default-with-confirmation)
15649 ("." . outline-mark-subtree)
15650 ("Clock Commands")
15651 ("I" . org-clock-in)
15652 ("O" . org-clock-out)
15653 ("Meta Data Editing")
15654 ("t" . org-todo)
15655 ("0" . (org-priority ?\ ))
15656 ("1" . (org-priority ?A))
15657 ("2" . (org-priority ?B))
15658 ("3" . (org-priority ?C))
15659 (";" . org-set-tags-command)
15660 ("e" . org-set-effort)
15661 ("Agenda Views etc")
15662 ("v" . org-agenda)
15663 ("/" . org-sparse-tree)
15664 ("Misc")
15665 ("o" . org-open-at-point)
15666 ("?" . org-speed-command-help)
15668 "The default speed commands.")
15670 (defun org-print-speed-command (e)
15671 (if (> (length (car e)) 1)
15672 (progn
15673 (princ "\n")
15674 (princ (car e))
15675 (princ "\n")
15676 (princ (make-string (length (car e)) ?-))
15677 (princ "\n"))
15678 (princ (car e))
15679 (princ " ")
15680 (if (symbolp (cdr e))
15681 (princ (symbol-name (cdr e)))
15682 (prin1 (cdr e)))
15683 (princ "\n")))
15685 (defun org-speed-command-help ()
15686 "Show the available speed commands."
15687 (interactive)
15688 (if (not org-use-speed-commands)
15689 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
15690 (with-output-to-temp-buffer "*Help*"
15691 (princ "User-defined Speed commands\n===========================\n")
15692 (mapc 'org-print-speed-command org-speed-commands-user)
15693 (princ "\n")
15694 (princ "Built-in Speed commands\n=======================\n")
15695 (mapc 'org-print-speed-command org-speed-commands-default))
15696 (with-current-buffer "*Help*"
15697 (setq truncate-lines t))))
15699 (defun org-speed-move-safe (cmd)
15700 "Execute CMD, but make sure that the cursor always ends up in a headline.
15701 If not, return to the original position and throw an error."
15702 (interactive)
15703 (let ((pos (point)))
15704 (call-interactively cmd)
15705 (unless (and (bolp) (org-on-heading-p))
15706 (goto-char pos)
15707 (error "Boundary reached while executing %s" cmd))))
15709 (defvar org-self-insert-command-undo-counter 0)
15711 (defvar org-table-auto-blank-field) ; defined in org-table.el
15712 (defvar org-speed-command nil)
15713 (defun org-self-insert-command (N)
15714 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15715 If the cursor is in a table looking at whitespace, the whitespace is
15716 overwritten, and the table is not marked as requiring realignment."
15717 (interactive "p")
15718 (cond
15719 ((and org-use-speed-commands
15720 (or (and (bolp) (looking-at outline-regexp))
15721 (and (functionp org-use-speed-commands)
15722 (funcall org-use-speed-commands)))
15723 (setq
15724 org-speed-command
15725 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15726 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15727 (cond
15728 ((commandp org-speed-command)
15729 (setq this-command org-speed-command)
15730 (call-interactively org-speed-command))
15731 ((functionp org-speed-command)
15732 (funcall org-speed-command))
15733 ((and org-speed-command (listp org-speed-command))
15734 (eval org-speed-command))
15735 (t (let (org-use-speed-commands)
15736 (call-interactively 'org-self-insert-command)))))
15737 ((and
15738 (org-table-p)
15739 (progn
15740 ;; check if we blank the field, and if that triggers align
15741 (and (featurep 'org-table) org-table-auto-blank-field
15742 (member last-command
15743 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15744 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15745 ;; got extra space, this field does not determine column width
15746 (let (org-table-may-need-update) (org-table-blank-field))
15747 ;; no extra space, this field may determine column width
15748 (org-table-blank-field)))
15750 (eq N 1)
15751 (looking-at "[^|\n]* |"))
15752 (let (org-table-may-need-update)
15753 (goto-char (1- (match-end 0)))
15754 (delete-backward-char 1)
15755 (goto-char (match-beginning 0))
15756 (self-insert-command N)))
15758 (setq org-table-may-need-update t)
15759 (self-insert-command N)
15760 (org-fix-tags-on-the-fly)
15761 (if org-self-insert-cluster-for-undo
15762 (if (not (eq last-command 'org-self-insert-command))
15763 (setq org-self-insert-command-undo-counter 1)
15764 (if (>= org-self-insert-command-undo-counter 20)
15765 (setq org-self-insert-command-undo-counter 1)
15766 (and (> org-self-insert-command-undo-counter 0)
15767 buffer-undo-list
15768 (not (cadr buffer-undo-list)) ; remove nil entry
15769 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15770 (setq org-self-insert-command-undo-counter
15771 (1+ org-self-insert-command-undo-counter))))))))
15773 (defun org-fix-tags-on-the-fly ()
15774 (when (and (equal (char-after (point-at-bol)) ?*)
15775 (org-on-heading-p))
15776 (org-align-tags-here org-tags-column)))
15778 (defun org-delete-backward-char (N)
15779 "Like `delete-backward-char', insert whitespace at field end in tables.
15780 When deleting backwards, in tables this function will insert whitespace in
15781 front of the next \"|\" separator, to keep the table aligned. The table will
15782 still be marked for re-alignment if the field did fill the entire column,
15783 because, in this case the deletion might narrow the column."
15784 (interactive "p")
15785 (if (and (org-table-p)
15786 (eq N 1)
15787 (string-match "|" (buffer-substring (point-at-bol) (point)))
15788 (looking-at ".*?|"))
15789 (let ((pos (point))
15790 (noalign (looking-at "[^|\n\r]* |"))
15791 (c org-table-may-need-update))
15792 (backward-delete-char N)
15793 (skip-chars-forward "^|")
15794 (insert " ")
15795 (goto-char (1- pos))
15796 ;; noalign: if there were two spaces at the end, this field
15797 ;; does not determine the width of the column.
15798 (if noalign (setq org-table-may-need-update c)))
15799 (backward-delete-char N)
15800 (org-fix-tags-on-the-fly)))
15802 (defun org-delete-char (N)
15803 "Like `delete-char', but insert whitespace at field end in tables.
15804 When deleting characters, in tables this function will insert whitespace in
15805 front of the next \"|\" separator, to keep the table aligned. The table will
15806 still be marked for re-alignment if the field did fill the entire column,
15807 because, in this case the deletion might narrow the column."
15808 (interactive "p")
15809 (if (and (org-table-p)
15810 (not (bolp))
15811 (not (= (char-after) ?|))
15812 (eq N 1))
15813 (if (looking-at ".*?|")
15814 (let ((pos (point))
15815 (noalign (looking-at "[^|\n\r]* |"))
15816 (c org-table-may-need-update))
15817 (replace-match (concat
15818 (substring (match-string 0) 1 -1)
15819 " |"))
15820 (goto-char pos)
15821 ;; noalign: if there were two spaces at the end, this field
15822 ;; does not determine the width of the column.
15823 (if noalign (setq org-table-may-need-update c)))
15824 (delete-char N))
15825 (delete-char N)
15826 (org-fix-tags-on-the-fly)))
15828 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15829 (put 'org-self-insert-command 'delete-selection t)
15830 (put 'orgtbl-self-insert-command 'delete-selection t)
15831 (put 'org-delete-char 'delete-selection 'supersede)
15832 (put 'org-delete-backward-char 'delete-selection 'supersede)
15833 (put 'org-yank 'delete-selection 'yank)
15835 ;; Make `flyspell-mode' delay after some commands
15836 (put 'org-self-insert-command 'flyspell-delayed t)
15837 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15838 (put 'org-delete-char 'flyspell-delayed t)
15839 (put 'org-delete-backward-char 'flyspell-delayed t)
15841 ;; Make pabbrev-mode expand after org-mode commands
15842 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15843 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15845 ;; How to do this: Measure non-white length of current string
15846 ;; If equal to column width, we should realign.
15848 (defun org-remap (map &rest commands)
15849 "In MAP, remap the functions given in COMMANDS.
15850 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15851 (let (new old)
15852 (while commands
15853 (setq old (pop commands) new (pop commands))
15854 (if (fboundp 'command-remapping)
15855 (org-defkey map (vector 'remap old) new)
15856 (substitute-key-definition old new map global-map)))))
15858 (when (eq org-enable-table-editor 'optimized)
15859 ;; If the user wants maximum table support, we need to hijack
15860 ;; some standard editing functions
15861 (org-remap org-mode-map
15862 'self-insert-command 'org-self-insert-command
15863 'delete-char 'org-delete-char
15864 'delete-backward-char 'org-delete-backward-char)
15865 (org-defkey org-mode-map "|" 'org-force-self-insert))
15867 (defvar org-ctrl-c-ctrl-c-hook nil
15868 "Hook for functions attaching themselves to `C-c C-c'.
15869 This can be used to add additional functionality to the C-c C-c key which
15870 executes context-dependent commands.
15871 Each function will be called with no arguments. The function must check
15872 if the context is appropriate for it to act. If yes, it should do its
15873 thing and then return a non-nil value. If the context is wrong,
15874 just do nothing and return nil.")
15876 (defvar org-tab-first-hook nil
15877 "Hook for functions to attach themselves to TAB.
15878 See `org-ctrl-c-ctrl-c-hook' for more information.
15879 This hook runs as the first action when TAB is pressed, even before
15880 `org-cycle' messes around with the `outline-regexp' to cater for
15881 inline tasks and plain list item folding.
15882 If any function in this hook returns t, not other actions like table
15883 field motion visibility cycling will be done.")
15885 (defvar org-tab-after-check-for-table-hook nil
15886 "Hook for functions to attach themselves to TAB.
15887 See `org-ctrl-c-ctrl-c-hook' for more information.
15888 This hook runs after it has been established that the cursor is not in a
15889 table, but before checking if the cursor is in a headline or if global cycling
15890 should be done.
15891 If any function in this hook returns t, not other actions like visibility
15892 cycling will be done.")
15894 (defvar org-tab-after-check-for-cycling-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 it has been established that not table field motion and
15898 not visibility should be done because of current context. This is probably
15899 the place where a package like yasnippets can hook in.")
15901 (defvar org-tab-before-tab-emulation-hook nil
15902 "Hook for functions to attach themselves to TAB.
15903 See `org-ctrl-c-ctrl-c-hook' for more information.
15904 This hook runs after every other options for TAB have been exhausted, but
15905 before indentation and \t insertion takes place.")
15907 (defvar org-metaleft-hook nil
15908 "Hook for functions attaching themselves to `M-left'.
15909 See `org-ctrl-c-ctrl-c-hook' for more information.")
15910 (defvar org-metaright-hook nil
15911 "Hook for functions attaching themselves to `M-right'.
15912 See `org-ctrl-c-ctrl-c-hook' for more information.")
15913 (defvar org-metaup-hook nil
15914 "Hook for functions attaching themselves to `M-up'.
15915 See `org-ctrl-c-ctrl-c-hook' for more information.")
15916 (defvar org-metadown-hook nil
15917 "Hook for functions attaching themselves to `M-down'.
15918 See `org-ctrl-c-ctrl-c-hook' for more information.")
15919 (defvar org-shiftmetaleft-hook nil
15920 "Hook for functions attaching themselves to `M-S-left'.
15921 See `org-ctrl-c-ctrl-c-hook' for more information.")
15922 (defvar org-shiftmetaright-hook nil
15923 "Hook for functions attaching themselves to `M-S-right'.
15924 See `org-ctrl-c-ctrl-c-hook' for more information.")
15925 (defvar org-shiftmetaup-hook nil
15926 "Hook for functions attaching themselves to `M-S-up'.
15927 See `org-ctrl-c-ctrl-c-hook' for more information.")
15928 (defvar org-shiftmetadown-hook nil
15929 "Hook for functions attaching themselves to `M-S-down'.
15930 See `org-ctrl-c-ctrl-c-hook' for more information.")
15931 (defvar org-metareturn-hook nil
15932 "Hook for functions attaching themselves to `M-RET'.
15933 See `org-ctrl-c-ctrl-c-hook' for more information.")
15934 (defvar org-shiftup-hook nil
15935 "Hook for functions attaching themselves to `S-up'.
15936 See `org-ctrl-c-ctrl-c-hook' for more information.")
15937 (defvar org-shiftup-final-hook nil
15938 "Hook for functions attaching themselves to `S-up'.
15939 This one runs after all other options except shift-select have been excluded.
15940 See `org-ctrl-c-ctrl-c-hook' for more information.")
15941 (defvar org-shiftdown-hook nil
15942 "Hook for functions attaching themselves to `S-down'.
15943 See `org-ctrl-c-ctrl-c-hook' for more information.")
15944 (defvar org-shiftdown-final-hook nil
15945 "Hook for functions attaching themselves to `S-down'.
15946 This one runs after all other options except shift-select have been excluded.
15947 See `org-ctrl-c-ctrl-c-hook' for more information.")
15948 (defvar org-shiftleft-hook nil
15949 "Hook for functions attaching themselves to `S-left'.
15950 See `org-ctrl-c-ctrl-c-hook' for more information.")
15951 (defvar org-shiftleft-final-hook nil
15952 "Hook for functions attaching themselves to `S-left'.
15953 This one runs after all other options except shift-select have been excluded.
15954 See `org-ctrl-c-ctrl-c-hook' for more information.")
15955 (defvar org-shiftright-hook nil
15956 "Hook for functions attaching themselves to `S-right'.
15957 See `org-ctrl-c-ctrl-c-hook' for more information.")
15958 (defvar org-shiftright-final-hook nil
15959 "Hook for functions attaching themselves to `S-right'.
15960 This one runs after all other options except shift-select have been excluded.
15961 See `org-ctrl-c-ctrl-c-hook' for more information.")
15963 (defun org-modifier-cursor-error ()
15964 "Throw an error, a modified cursor command was applied in wrong context."
15965 (error "This command is active in special context like tables, headlines or items"))
15967 (defun org-shiftselect-error ()
15968 "Throw an error because Shift-Cursor command was applied in wrong context."
15969 (if (and (boundp 'shift-select-mode) shift-select-mode)
15970 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15971 (error "This command works only in special context like headlines or timestamps")))
15973 (defun org-call-for-shift-select (cmd)
15974 (let ((this-command-keys-shift-translated t))
15975 (call-interactively cmd)))
15977 (defun org-shifttab (&optional arg)
15978 "Global visibility cycling or move to previous table field.
15979 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15980 on context.
15981 See the individual commands for more information."
15982 (interactive "P")
15983 (cond
15984 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15985 ((integerp arg)
15986 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15987 (message "Content view to level: %d" arg)
15988 (org-content (prefix-numeric-value arg2))
15989 (setq org-cycle-global-status 'overview)))
15990 (t (call-interactively 'org-global-cycle))))
15992 (defun org-shiftmetaleft ()
15993 "Promote subtree or delete table column.
15994 Calls `org-promote-subtree', `org-outdent-item',
15995 or `org-table-delete-column', depending on context.
15996 See the individual commands for more information."
15997 (interactive)
15998 (cond
15999 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
16000 ((org-at-table-p) (call-interactively 'org-table-delete-column))
16001 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
16002 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
16003 (t (org-modifier-cursor-error))))
16005 (defun org-shiftmetaright ()
16006 "Demote subtree or insert table column.
16007 Calls `org-demote-subtree', `org-indent-item',
16008 or `org-table-insert-column', depending on context.
16009 See the individual commands for more information."
16010 (interactive)
16011 (cond
16012 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
16013 ((org-at-table-p) (call-interactively 'org-table-insert-column))
16014 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
16015 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
16016 (t (org-modifier-cursor-error))))
16018 (defun org-shiftmetaup (&optional arg)
16019 "Move subtree up or kill table row.
16020 Calls `org-move-subtree-up' or `org-table-kill-row' or
16021 `org-move-item-up' depending on context. See the individual commands
16022 for more information."
16023 (interactive "P")
16024 (cond
16025 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
16026 ((org-at-table-p) (call-interactively 'org-table-kill-row))
16027 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16028 ((org-at-item-p) (call-interactively 'org-move-item-up))
16029 (t (org-modifier-cursor-error))))
16031 (defun org-shiftmetadown (&optional arg)
16032 "Move subtree down or insert table row.
16033 Calls `org-move-subtree-down' or `org-table-insert-row' or
16034 `org-move-item-down', depending on context. See the individual
16035 commands for more information."
16036 (interactive "P")
16037 (cond
16038 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
16039 ((org-at-table-p) (call-interactively 'org-table-insert-row))
16040 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16041 ((org-at-item-p) (call-interactively 'org-move-item-down))
16042 (t (org-modifier-cursor-error))))
16044 (defsubst org-hidden-tree-error ()
16045 (error
16046 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
16048 (defun org-metaleft (&optional arg)
16049 "Promote heading or move table column to left.
16050 Calls `org-do-promote' or `org-table-move-column', depending on context.
16051 With no specific context, calls the Emacs default `backward-word'.
16052 See the individual commands for more information."
16053 (interactive "P")
16054 (cond
16055 ((run-hook-with-args-until-success 'org-metaleft-hook))
16056 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
16057 ((or (org-on-heading-p)
16058 (and (org-region-active-p)
16059 (save-excursion
16060 (goto-char (region-beginning))
16061 (org-on-heading-p))))
16062 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
16063 (call-interactively 'org-do-promote))
16064 ((or (org-at-item-p)
16065 (and (org-region-active-p)
16066 (save-excursion
16067 (goto-char (region-beginning))
16068 (org-at-item-p))))
16069 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
16070 (call-interactively 'org-outdent-item))
16071 (t (call-interactively 'backward-word))))
16073 (defun org-metaright (&optional arg)
16074 "Demote subtree or move table column to right.
16075 Calls `org-do-demote' or `org-table-move-column', depending on context.
16076 With no specific context, calls the Emacs default `forward-word'.
16077 See the individual commands for more information."
16078 (interactive "P")
16079 (cond
16080 ((run-hook-with-args-until-success 'org-metaright-hook))
16081 ((org-at-table-p) (call-interactively 'org-table-move-column))
16082 ((or (org-on-heading-p)
16083 (and (org-region-active-p)
16084 (save-excursion
16085 (goto-char (region-beginning))
16086 (org-on-heading-p))))
16087 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
16088 (call-interactively 'org-do-demote))
16089 ((or (org-at-item-p)
16090 (and (org-region-active-p)
16091 (save-excursion
16092 (goto-char (region-beginning))
16093 (org-at-item-p))))
16094 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
16095 (call-interactively 'org-indent-item))
16096 (t (call-interactively 'forward-word))))
16098 (defun org-check-for-hidden (what)
16099 "Check if there are hidden headlines/items in the current visual line.
16100 WHAT can be either `headlines' or `items'. If the current line is
16101 an outline or item heading and it has a folded subtree below it,
16102 this fucntion returns t, nil otherwise."
16103 (let ((re (cond
16104 ((eq what 'headlines) (concat "^" org-outline-regexp))
16105 ((eq what 'items) (concat "^" (org-item-re t)))
16106 (t (error "This should not happen"))))
16107 beg end)
16108 (save-excursion
16109 (catch 'exit
16110 (if (org-region-active-p)
16111 (setq beg (region-beginning) end (region-end))
16112 (setq beg (point-at-bol))
16113 (beginning-of-line 2)
16114 (while (and (not (eobp)) ;; this is like `next-line'
16115 (get-char-property (1- (point)) 'invisible))
16116 (beginning-of-line 2))
16117 (setq end (point)))
16118 (goto-char beg)
16119 (goto-char (point-at-eol))
16120 (setq end (max end (point)))
16121 (while (re-search-forward re end t)
16122 (if (get-char-property (match-beginning 0) 'invisible)
16123 (throw 'exit t)))
16124 nil))))
16126 (defun org-metaup (&optional arg)
16127 "Move subtree up or move table row up.
16128 Calls `org-move-subtree-up' or `org-table-move-row' or
16129 `org-move-item-up', depending on context. See the individual commands
16130 for more information."
16131 (interactive "P")
16132 (cond
16133 ((run-hook-with-args-until-success 'org-metaup-hook))
16134 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
16135 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16136 ((org-at-item-p) (call-interactively 'org-move-item-up))
16137 (t (transpose-lines 1) (beginning-of-line -1))))
16139 (defun org-metadown (&optional arg)
16140 "Move subtree down or move table row down.
16141 Calls `org-move-subtree-down' or `org-table-move-row' or
16142 `org-move-item-down', depending on context. See the individual
16143 commands for more information."
16144 (interactive "P")
16145 (cond
16146 ((run-hook-with-args-until-success 'org-metadown-hook))
16147 ((org-at-table-p) (call-interactively 'org-table-move-row))
16148 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16149 ((org-at-item-p) (call-interactively 'org-move-item-down))
16150 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
16152 (defun org-shiftup (&optional arg)
16153 "Increase item in timestamp or increase priority of current headline.
16154 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
16155 depending on context. See the individual commands for more information."
16156 (interactive "P")
16157 (cond
16158 ((run-hook-with-args-until-success 'org-shiftup-hook))
16159 ((and org-support-shift-select (org-region-active-p))
16160 (org-call-for-shift-select 'previous-line))
16161 ((org-at-timestamp-p t)
16162 (call-interactively (if org-edit-timestamp-down-means-later
16163 'org-timestamp-down 'org-timestamp-up)))
16164 ((and (not (eq org-support-shift-select 'always))
16165 org-enable-priority-commands
16166 (org-on-heading-p))
16167 (call-interactively 'org-priority-up))
16168 ((and (not org-support-shift-select) (org-at-item-p))
16169 (call-interactively 'org-previous-item))
16170 ((org-clocktable-try-shift 'up arg))
16171 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
16172 (org-support-shift-select
16173 (org-call-for-shift-select 'previous-line))
16174 (t (org-shiftselect-error))))
16176 (defun org-shiftdown (&optional arg)
16177 "Decrease item in timestamp or decrease priority of current headline.
16178 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
16179 depending on context. See the individual commands for more information."
16180 (interactive "P")
16181 (cond
16182 ((run-hook-with-args-until-success 'org-shiftdown-hook))
16183 ((and org-support-shift-select (org-region-active-p))
16184 (org-call-for-shift-select 'next-line))
16185 ((org-at-timestamp-p t)
16186 (call-interactively (if org-edit-timestamp-down-means-later
16187 'org-timestamp-up 'org-timestamp-down)))
16188 ((and (not (eq org-support-shift-select 'always))
16189 org-enable-priority-commands
16190 (org-on-heading-p))
16191 (call-interactively 'org-priority-down))
16192 ((and (not org-support-shift-select) (org-at-item-p))
16193 (call-interactively 'org-next-item))
16194 ((org-clocktable-try-shift 'down arg))
16195 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
16196 (org-support-shift-select
16197 (org-call-for-shift-select 'next-line))
16198 (t (org-shiftselect-error))))
16200 (defun org-shiftright (&optional arg)
16201 "Cycle the thing at point or in the current line, depending on context.
16202 Depending on context, this does one of the following:
16204 - switch a timestamp at point one day into the future
16205 - on a headline, switch to the next TODO keyword.
16206 - on an item, switch entire list to the next bullet type
16207 - on a property line, switch to the next allowed value
16208 - on a clocktable definition line, move time block into the future"
16209 (interactive "P")
16210 (cond
16211 ((run-hook-with-args-until-success 'org-shiftright-hook))
16212 ((and org-support-shift-select (org-region-active-p))
16213 (org-call-for-shift-select 'forward-char))
16214 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
16215 ((and (not (eq org-support-shift-select 'always))
16216 (org-on-heading-p))
16217 (let ((org-inhibit-logging
16218 (not org-treat-S-cursor-todo-selection-as-state-change))
16219 (org-inhibit-blocking
16220 (not org-treat-S-cursor-todo-selection-as-state-change)))
16221 (org-call-with-arg 'org-todo 'right)))
16222 ((or (and org-support-shift-select
16223 (not (eq org-support-shift-select 'always))
16224 (org-at-item-bullet-p))
16225 (and (not org-support-shift-select) (org-at-item-p)))
16226 (org-call-with-arg 'org-cycle-list-bullet nil))
16227 ((and (not (eq org-support-shift-select 'always))
16228 (org-at-property-p))
16229 (call-interactively 'org-property-next-allowed-value))
16230 ((org-clocktable-try-shift 'right arg))
16231 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
16232 (org-support-shift-select
16233 (org-call-for-shift-select 'forward-char))
16234 (t (org-shiftselect-error))))
16236 (defun org-shiftleft (&optional arg)
16237 "Cycle the thing at point or in the current line, depending on context.
16238 Depending on context, this does one of the following:
16240 - switch a timestamp at point one day into the past
16241 - on a headline, switch to the previous TODO keyword.
16242 - on an item, switch entire list to the previous bullet type
16243 - on a property line, switch to the previous allowed value
16244 - on a clocktable definition line, move time block into the past"
16245 (interactive "P")
16246 (cond
16247 ((run-hook-with-args-until-success 'org-shiftleft-hook))
16248 ((and org-support-shift-select (org-region-active-p))
16249 (org-call-for-shift-select 'backward-char))
16250 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
16251 ((and (not (eq org-support-shift-select 'always))
16252 (org-on-heading-p))
16253 (let ((org-inhibit-logging
16254 (not org-treat-S-cursor-todo-selection-as-state-change))
16255 (org-inhibit-blocking
16256 (not org-treat-S-cursor-todo-selection-as-state-change)))
16257 (org-call-with-arg 'org-todo 'left)))
16258 ((or (and org-support-shift-select
16259 (not (eq org-support-shift-select 'always))
16260 (org-at-item-bullet-p))
16261 (and (not org-support-shift-select) (org-at-item-p)))
16262 (org-call-with-arg 'org-cycle-list-bullet 'previous))
16263 ((and (not (eq org-support-shift-select 'always))
16264 (org-at-property-p))
16265 (call-interactively 'org-property-previous-allowed-value))
16266 ((org-clocktable-try-shift 'left arg))
16267 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
16268 (org-support-shift-select
16269 (org-call-for-shift-select 'backward-char))
16270 (t (org-shiftselect-error))))
16272 (defun org-shiftcontrolright ()
16273 "Switch to next TODO set."
16274 (interactive)
16275 (cond
16276 ((and org-support-shift-select (org-region-active-p))
16277 (org-call-for-shift-select 'forward-word))
16278 ((and (not (eq org-support-shift-select 'always))
16279 (org-on-heading-p))
16280 (org-call-with-arg 'org-todo 'nextset))
16281 (org-support-shift-select
16282 (org-call-for-shift-select 'forward-word))
16283 (t (org-shiftselect-error))))
16285 (defun org-shiftcontrolleft ()
16286 "Switch to previous TODO set."
16287 (interactive)
16288 (cond
16289 ((and org-support-shift-select (org-region-active-p))
16290 (org-call-for-shift-select 'backward-word))
16291 ((and (not (eq org-support-shift-select 'always))
16292 (org-on-heading-p))
16293 (org-call-with-arg 'org-todo 'previousset))
16294 (org-support-shift-select
16295 (org-call-for-shift-select 'backward-word))
16296 (t (org-shiftselect-error))))
16298 (defun org-ctrl-c-ret ()
16299 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
16300 (interactive)
16301 (cond
16302 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
16303 (t (call-interactively 'org-insert-heading))))
16305 (defun org-copy-special ()
16306 "Copy region in table or copy current subtree.
16307 Calls `org-table-copy' or `org-copy-subtree', depending on context.
16308 See the individual commands for more information."
16309 (interactive)
16310 (call-interactively
16311 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
16313 (defun org-cut-special ()
16314 "Cut region in table or cut current subtree.
16315 Calls `org-table-copy' or `org-cut-subtree', depending on context.
16316 See the individual commands for more information."
16317 (interactive)
16318 (call-interactively
16319 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
16321 (defun org-paste-special (arg)
16322 "Paste rectangular region into table, or past subtree relative to level.
16323 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
16324 See the individual commands for more information."
16325 (interactive "P")
16326 (if (org-at-table-p)
16327 (org-table-paste-rectangle)
16328 (org-paste-subtree arg)))
16330 (defun org-edit-special ()
16331 "Call a special editor for the stuff at point.
16332 When at a table, call the formula editor with `org-table-edit-formulas'.
16333 When at the first line of an src example, call `org-edit-src-code'.
16334 When in an #+include line, visit the include file. Otherwise call
16335 `ffap' to visit the file at point."
16336 (interactive)
16337 (cond
16338 ((org-at-table.el-p)
16339 (org-edit-src-code))
16340 ((org-at-table-p)
16341 (call-interactively 'org-table-edit-formulas))
16342 ((save-excursion
16343 (beginning-of-line 1)
16344 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
16345 (find-file (org-trim (match-string 1))))
16346 ((org-edit-src-code))
16347 ((org-edit-fixed-width-region))
16348 (t (call-interactively 'ffap))))
16351 (defun org-ctrl-c-ctrl-c (&optional arg)
16352 "Set tags in headline, or update according to changed information at point.
16354 This command does many different things, depending on context:
16356 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
16357 this is what we do.
16359 - If the cursor is on a statistics cookie, update it.
16361 - If the cursor is in a headline, prompt for tags and insert them
16362 into the current line, aligned to `org-tags-column'. When called
16363 with prefix arg, realign all tags in the current buffer.
16365 - If the cursor is in one of the special #+KEYWORD lines, this
16366 triggers scanning the buffer for these lines and updating the
16367 information.
16369 - If the cursor is inside a table, realign the table. This command
16370 works even if the automatic table editor has been turned off.
16372 - If the cursor is on a #+TBLFM line, re-apply the formulas to
16373 the entire table.
16375 - If the cursor is at a footnote reference or definition, jump to
16376 the corresponding definition or references, respectively.
16378 - If the cursor is a the beginning of a dynamic block, update it.
16380 - If the current buffer is a remember buffer, close note and file
16381 it. A prefix argument of 1 files to the default location
16382 without further interaction. A prefix argument of 2 files to
16383 the currently clocking task.
16385 - If the cursor is on a <<<target>>>, update radio targets and corresponding
16386 links in this buffer.
16388 - If the cursor is on a numbered item in a plain list, renumber the
16389 ordered list.
16391 - If the cursor is on a checkbox, toggle it."
16392 (interactive "P")
16393 (let ((org-enable-table-editor t))
16394 (cond
16395 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
16396 org-occur-highlights
16397 org-latex-fragment-image-overlays)
16398 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
16399 (org-remove-occur-highlights)
16400 (org-remove-latex-fragment-image-overlays)
16401 (message "Temporary highlights/overlays removed from current buffer"))
16402 ((and (local-variable-p 'org-finish-function (current-buffer))
16403 (fboundp org-finish-function))
16404 (funcall org-finish-function))
16405 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
16406 ((or (looking-at org-property-start-re)
16407 (org-at-property-p))
16408 (call-interactively 'org-property-action))
16409 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
16410 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
16411 (or (org-on-heading-p) (org-at-item-p)))
16412 (call-interactively 'org-update-statistics-cookies))
16413 ((org-on-heading-p) (call-interactively 'org-set-tags))
16414 ((org-at-table.el-p)
16415 (message "Use C-c ' to edit table.el tables"))
16416 ((org-at-table-p)
16417 (org-table-maybe-eval-formula)
16418 (if arg
16419 (call-interactively 'org-table-recalculate)
16420 (org-table-maybe-recalculate-line))
16421 (call-interactively 'org-table-align))
16422 ((or (org-footnote-at-reference-p)
16423 (org-footnote-at-definition-p))
16424 (call-interactively 'org-footnote-action))
16425 ((org-at-item-checkbox-p)
16426 (call-interactively 'org-toggle-checkbox))
16427 ((org-at-item-p)
16428 (if arg
16429 (call-interactively 'org-toggle-checkbox)
16430 (call-interactively 'org-maybe-renumber-ordered-list)))
16431 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
16432 ;; Dynamic block
16433 (beginning-of-line 1)
16434 (save-excursion (org-update-dblock)))
16435 ((save-excursion
16436 (beginning-of-line 1)
16437 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
16438 (cond
16439 ((equal (match-string 1) "TBLFM")
16440 ;; Recalculate the table before this line
16441 (save-excursion
16442 (beginning-of-line 1)
16443 (skip-chars-backward " \r\n\t")
16444 (if (org-at-table-p)
16445 (org-call-with-arg 'org-table-recalculate (or arg t)))))
16447 (let ((org-inhibit-startup-visibility-stuff t)
16448 (org-startup-align-all-tables nil))
16449 (org-save-outline-visibility 'use-markers (org-mode-restart)))
16450 (message "Local setup has been refreshed"))))
16451 ((org-clock-update-time-maybe))
16452 (t (error "C-c C-c can do nothing useful at this location")))))
16454 (defun org-mode-restart ()
16455 "Restart Org-mode, to scan again for special lines.
16456 Also updates the keyword regular expressions."
16457 (interactive)
16458 (org-mode)
16459 (message "Org-mode restarted"))
16461 (defun org-kill-note-or-show-branches ()
16462 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
16463 (interactive)
16464 (if (not org-finish-function)
16465 (call-interactively 'show-branches)
16466 (let ((org-note-abort t))
16467 (funcall org-finish-function))))
16469 (defun org-return (&optional indent)
16470 "Goto next table row or insert a newline.
16471 Calls `org-table-next-row' or `newline', depending on context.
16472 See the individual commands for more information."
16473 (interactive)
16474 (cond
16475 ((bobp) (if indent (newline-and-indent) (newline)))
16476 ((org-at-table-p)
16477 (org-table-justify-field-maybe)
16478 (call-interactively 'org-table-next-row))
16479 ((and org-return-follows-link
16480 (eq (get-text-property (point) 'face) 'org-link))
16481 (call-interactively 'org-open-at-point))
16482 ((and (org-at-heading-p)
16483 (looking-at
16484 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
16485 (org-show-entry)
16486 (end-of-line 1)
16487 (newline))
16488 (t (if indent (newline-and-indent) (newline)))))
16490 (defun org-return-indent ()
16491 "Goto next table row or insert a newline and indent.
16492 Calls `org-table-next-row' or `newline-and-indent', depending on
16493 context. See the individual commands for more information."
16494 (interactive)
16495 (org-return t))
16497 (defun org-ctrl-c-star ()
16498 "Compute table, or change heading status of lines.
16499 Calls `org-table-recalculate' or `org-toggle-heading',
16500 depending on context."
16501 (interactive)
16502 (cond
16503 ((org-at-table-p)
16504 (call-interactively 'org-table-recalculate))
16506 ;; Convert all lines in region to list items
16507 (call-interactively 'org-toggle-heading))))
16509 (defun org-ctrl-c-minus ()
16510 "Insert separator line in table or modify bullet status of line.
16511 Also turns a plain line or a region of lines into list items.
16512 Calls `org-table-insert-hline', `org-toggle-item', or
16513 `org-cycle-list-bullet', depending on context."
16514 (interactive)
16515 (cond
16516 ((org-at-table-p)
16517 (call-interactively 'org-table-insert-hline))
16518 ((org-region-active-p)
16519 (call-interactively 'org-toggle-item))
16520 ((org-in-item-p)
16521 (call-interactively 'org-cycle-list-bullet))
16523 (call-interactively 'org-toggle-item))))
16525 (defun org-toggle-item ()
16526 "Convert headings or normal lines to items, items to normal lines.
16527 If there is no active region, only the current line is considered.
16529 If the first line in the region is a headline, convert all headlines to items.
16531 If the first line in the region is an item, convert all items to normal lines.
16533 If the first line is normal text, add an item bullet to each line."
16534 (interactive)
16535 (let (l2 l beg end)
16536 (if (org-region-active-p)
16537 (setq beg (region-beginning) end (region-end))
16538 (setq beg (point-at-bol)
16539 end (min (1+ (point-at-eol)) (point-max))))
16540 (save-excursion
16541 (goto-char end)
16542 (setq l2 (org-current-line))
16543 (goto-char beg)
16544 (beginning-of-line 1)
16545 (setq l (1- (org-current-line)))
16546 (if (org-at-item-p)
16547 ;; We already have items, de-itemize
16548 (while (< (setq l (1+ l)) l2)
16549 (when (org-at-item-p)
16550 (goto-char (match-beginning 2))
16551 (delete-region (match-beginning 2) (match-end 2))
16552 (and (looking-at "[ \t]+") (replace-match "")))
16553 (beginning-of-line 2))
16554 (if (org-on-heading-p)
16555 ;; Headings, convert to items
16556 (while (< (setq l (1+ l)) l2)
16557 (if (looking-at org-outline-regexp)
16558 (replace-match "- " t t))
16559 (beginning-of-line 2))
16560 ;; normal lines, turn them into items
16561 (while (< (setq l (1+ l)) l2)
16562 (unless (org-at-item-p)
16563 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16564 (replace-match "\\1- \\2")))
16565 (beginning-of-line 2)))))))
16567 (defun org-toggle-heading (&optional nstars)
16568 "Convert headings to normal text, or items or text to headings.
16569 If there is no active region, only the current line is considered.
16571 If the first line is a heading, remove the stars from all headlines
16572 in the region.
16574 If the first line is a plain list item, turn all plain list items
16575 into headings.
16577 If the first line is a normal line, turn each and every line in the
16578 region into a heading.
16580 When converting a line into a heading, the number of stars is chosen
16581 such that the lines become children of the current entry. However,
16582 when a prefix argument is given, its value determines the number of
16583 stars to add."
16584 (interactive "P")
16585 (let (l2 l itemp beg end)
16586 (if (org-region-active-p)
16587 (setq beg (region-beginning) end (region-end))
16588 (setq beg (point-at-bol)
16589 end (min (1+ (point-at-eol)) (point-max))))
16590 (save-excursion
16591 (goto-char end)
16592 (setq l2 (org-current-line))
16593 (goto-char beg)
16594 (beginning-of-line 1)
16595 (setq l (1- (org-current-line)))
16596 (if (org-on-heading-p)
16597 ;; We already have headlines, de-star them
16598 (while (< (setq l (1+ l)) l2)
16599 (when (org-on-heading-p t)
16600 (and (looking-at outline-regexp) (replace-match "")))
16601 (beginning-of-line 2))
16602 (setq itemp (org-at-item-p))
16603 (let* ((stars
16604 (if nstars
16605 (make-string (prefix-numeric-value current-prefix-arg)
16607 (save-excursion
16608 (if (re-search-backward org-complex-heading-regexp nil t)
16609 (match-string 1) ""))))
16610 (add-stars (cond (nstars "")
16611 ((equal stars "") "*")
16612 (org-odd-levels-only "**")
16613 (t "*")))
16614 (rpl (concat stars add-stars " ")))
16615 (while (< (setq l (1+ l)) l2)
16616 (if itemp
16617 (and (org-at-item-p) (replace-match rpl t t))
16618 (unless (org-on-heading-p)
16619 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16620 (replace-match (concat rpl (match-string 2))))))
16621 (beginning-of-line 2)))))))
16623 (defun org-meta-return (&optional arg)
16624 "Insert a new heading or wrap a region in a table.
16625 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16626 See the individual commands for more information."
16627 (interactive "P")
16628 (cond
16629 ((run-hook-with-args-until-success 'org-metareturn-hook))
16630 ((org-at-table-p)
16631 (call-interactively 'org-table-wrap-region))
16632 (t (call-interactively 'org-insert-heading))))
16634 ;;; Menu entries
16636 ;; Define the Org-mode menus
16637 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16638 '("Tbl"
16639 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
16640 ["Next Field" org-cycle (org-at-table-p)]
16641 ["Previous Field" org-shifttab (org-at-table-p)]
16642 ["Next Row" org-return (org-at-table-p)]
16643 "--"
16644 ["Blank Field" org-table-blank-field (org-at-table-p)]
16645 ["Edit Field" org-table-edit-field (org-at-table-p)]
16646 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16647 "--"
16648 ("Column"
16649 ["Move Column Left" org-metaleft (org-at-table-p)]
16650 ["Move Column Right" org-metaright (org-at-table-p)]
16651 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16652 ["Insert Column" org-shiftmetaright (org-at-table-p)])
16653 ("Row"
16654 ["Move Row Up" org-metaup (org-at-table-p)]
16655 ["Move Row Down" org-metadown (org-at-table-p)]
16656 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16657 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16658 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16659 "--"
16660 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
16661 ("Rectangle"
16662 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16663 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16664 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16665 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16666 "--"
16667 ("Calculate"
16668 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16669 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16670 ["Edit Formulas" org-edit-special (org-at-table-p)]
16671 "--"
16672 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16673 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16674 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
16675 "--"
16676 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16677 "--"
16678 ["Sum Column/Rectangle" org-table-sum
16679 (or (org-at-table-p) (org-region-active-p))]
16680 ["Which Column?" org-table-current-column (org-at-table-p)])
16681 ["Debug Formulas"
16682 org-table-toggle-formula-debugger
16683 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
16684 ["Show Col/Row Numbers"
16685 org-table-toggle-coordinate-overlays
16686 :style toggle
16687 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
16688 "--"
16689 ["Create" org-table-create (and (not (org-at-table-p))
16690 org-enable-table-editor)]
16691 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16692 ["Import from File" org-table-import (not (org-at-table-p))]
16693 ["Export to File" org-table-export (org-at-table-p)]
16694 "--"
16695 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16697 (easy-menu-define org-org-menu org-mode-map "Org menu"
16698 '("Org"
16699 ("Show/Hide"
16700 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
16701 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
16702 ["Sparse Tree..." org-sparse-tree t]
16703 ["Reveal Context" org-reveal t]
16704 ["Show All" show-all t]
16705 "--"
16706 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
16707 "--"
16708 ["New Heading" org-insert-heading t]
16709 ("Navigate Headings"
16710 ["Up" outline-up-heading t]
16711 ["Next" outline-next-visible-heading t]
16712 ["Previous" outline-previous-visible-heading t]
16713 ["Next Same Level" outline-forward-same-level t]
16714 ["Previous Same Level" outline-backward-same-level t]
16715 "--"
16716 ["Jump" org-goto t])
16717 ("Edit Structure"
16718 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16719 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16720 "--"
16721 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16722 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16723 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16724 "--"
16725 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
16726 "--"
16727 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16728 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16729 ["Demote Heading" org-metaright (not (org-at-table-p))]
16730 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16731 "--"
16732 ["Sort Region/Children" org-sort (not (org-at-table-p))]
16733 "--"
16734 ["Convert to odd levels" org-convert-to-odd-levels t]
16735 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16736 ("Editing"
16737 ["Emphasis..." org-emphasize t]
16738 ["Edit Source Example" org-edit-special t]
16739 "--"
16740 ["Footnote new/jump" org-footnote-action t]
16741 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
16742 ("Archive"
16743 ["Archive (default method)" org-archive-subtree-default t]
16744 "--"
16745 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
16746 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16747 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
16749 "--"
16750 ("Hyperlinks"
16751 ["Store Link (Global)" org-store-link t]
16752 ["Find existing link to here" org-occur-link-in-agenda-files t]
16753 ["Insert Link" org-insert-link t]
16754 ["Follow Link" org-open-at-point t]
16755 "--"
16756 ["Next link" org-next-link t]
16757 ["Previous link" org-previous-link t]
16758 "--"
16759 ["Descriptive Links"
16760 (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16761 :style radio
16762 :selected (member '(org-link) buffer-invisibility-spec)]
16763 ["Literal Links"
16764 (progn
16765 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16766 :style radio
16767 :selected (not (member '(org-link) buffer-invisibility-spec))])
16768 "--"
16769 ("TODO Lists"
16770 ["TODO/DONE/-" org-todo t]
16771 ("Select keyword"
16772 ["Next keyword" org-shiftright (org-on-heading-p)]
16773 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16774 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
16775 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
16776 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
16777 ["Show TODO Tree" org-show-todo-tree t]
16778 ["Global TODO list" org-todo-list t]
16779 "--"
16780 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
16781 :selected org-enforce-todo-dependencies :style toggle :active t]
16782 "Settings for tree at point"
16783 ["Do Children sequentially" org-toggle-ordered-property :style radio
16784 :selected (ignore-errors (org-entry-get nil "ORDERED"))
16785 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16786 ["Do Children parallel" org-toggle-ordered-property :style radio
16787 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
16788 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16789 "--"
16790 ["Set Priority" org-priority t]
16791 ["Priority Up" org-shiftup t]
16792 ["Priority Down" org-shiftdown t]
16793 "--"
16794 ["Get news from all feeds" org-feed-update-all t]
16795 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16796 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16797 ("TAGS and Properties"
16798 ["Set Tags" org-set-tags-command t]
16799 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16800 "--"
16801 ["Set property" org-set-property t]
16802 ["Column view of properties" org-columns t]
16803 ["Insert Column View DBlock" org-insert-columns-dblock t])
16804 ("Dates and Scheduling"
16805 ["Timestamp" org-time-stamp t]
16806 ["Timestamp (inactive)" org-time-stamp-inactive t]
16807 ("Change Date"
16808 ["1 Day Later" org-shiftright t]
16809 ["1 Day Earlier" org-shiftleft t]
16810 ["1 ... Later" org-shiftup t]
16811 ["1 ... Earlier" org-shiftdown t])
16812 ["Compute Time Range" org-evaluate-time-range t]
16813 ["Schedule Item" org-schedule t]
16814 ["Deadline" org-deadline t]
16815 "--"
16816 ["Custom time format" org-toggle-time-stamp-overlays
16817 :style radio :selected org-display-custom-times]
16818 "--"
16819 ["Goto Calendar" org-goto-calendar t]
16820 ["Date from Calendar" org-date-from-calendar t]
16821 "--"
16822 ["Start/Restart Timer" org-timer-start t]
16823 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16824 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16825 ["Insert Timer String" org-timer t]
16826 ["Insert Timer Item" org-timer-item t])
16827 ("Logging work"
16828 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16829 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16830 ["Clock out" org-clock-out t]
16831 ["Clock cancel" org-clock-cancel t]
16832 "--"
16833 ["Mark as default task" org-clock-mark-default-task t]
16834 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16835 ["Goto running clock" org-clock-goto t]
16836 "--"
16837 ["Display times" org-clock-display t]
16838 ["Create clock table" org-clock-report t]
16839 "--"
16840 ["Record DONE time"
16841 (progn (setq org-log-done (not org-log-done))
16842 (message "Switching to %s will %s record a timestamp"
16843 (car org-done-keywords)
16844 (if org-log-done "automatically" "not")))
16845 :style toggle :selected org-log-done])
16846 "--"
16847 ["Agenda Command..." org-agenda t]
16848 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16849 ("File List for Agenda")
16850 ("Special views current file"
16851 ["TODO Tree" org-show-todo-tree t]
16852 ["Check Deadlines" org-check-deadlines t]
16853 ["Timeline" org-timeline t]
16854 ["Tags/Property tree" org-match-sparse-tree t])
16855 "--"
16856 ["Export/Publish..." org-export t]
16857 ("LaTeX"
16858 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16859 :selected org-cdlatex-mode]
16860 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16861 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16862 ["Modify math symbol" org-cdlatex-math-modify
16863 (org-inside-LaTeX-fragment-p)]
16864 ["Insert citation" org-reftex-citation t]
16865 "--"
16866 ["Export LaTeX fragments as images"
16867 (if (featurep 'org-exp)
16868 (setq org-export-with-LaTeX-fragments
16869 (not org-export-with-LaTeX-fragments))
16870 (require 'org-exp))
16871 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16872 org-export-with-LaTeX-fragments)]
16873 "--"
16874 ["Template for BEAMER" org-beamer-settings-template t])
16875 "--"
16876 ("MobileOrg"
16877 ["Push Files and Views" org-mobile-push t]
16878 ["Get Captured and Flagged" org-mobile-pull t]
16879 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16880 "--"
16881 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16882 "--"
16883 ("Documentation"
16884 ["Show Version" org-version t]
16885 ["Info Documentation" org-info t])
16886 ("Customize"
16887 ["Browse Org Group" org-customize t]
16888 "--"
16889 ["Expand This Menu" org-create-customize-menu
16890 (fboundp 'customize-menu-create)])
16891 ["Send bug report" org-submit-bug-report t]
16892 "--"
16893 ("Refresh/Reload"
16894 ["Refresh setup current buffer" org-mode-restart t]
16895 ["Reload Org (after update)" org-reload t]
16896 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16899 (defun org-info (&optional node)
16900 "Read documentation for Org-mode in the info system.
16901 With optional NODE, go directly to that node."
16902 (interactive)
16903 (info (format "(org)%s" (or node ""))))
16905 ;;;###autoload
16906 (defun org-submit-bug-report ()
16907 "Submit a bug report on Org-mode via mail.
16909 Don't hesitate to report any problems or inaccurate documentation.
16911 If you don't have setup sending mail from (X)Emacs, please copy the
16912 output buffer into your mail program, as it gives us important
16913 information about your Org-mode version and configuration."
16914 (interactive)
16915 (require 'reporter)
16916 (org-load-modules-maybe)
16917 (org-require-autoloaded-modules)
16918 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16919 (reporter-submit-bug-report
16920 "emacs-orgmode@gnu.org"
16921 (org-version)
16922 (let (list)
16923 (save-window-excursion
16924 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16925 (delete-other-windows)
16926 (erase-buffer)
16927 (insert "You are about to submit a bug report to the Org-mode mailing list.
16929 We would like to add your full Org-mode and Outline configuration to the
16930 bug report. This greatly simplifies the work of the maintainer and
16931 other experts on the mailing list.
16933 HOWEVER, some variables you have customized may contain private
16934 information. The names of customers, colleagues, or friends, might
16935 appear in the form of file names, tags, todo states, or search strings.
16936 If you answer yes to the prompt, you might want to check and remove
16937 such private information before sending the email.")
16938 (add-text-properties (point-min) (point-max) '(face org-warning))
16939 (when (yes-or-no-p "Include your Org-mode configuration ")
16940 (mapatoms
16941 (lambda (v)
16942 (and (boundp v)
16943 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16944 (or (and (symbol-value v)
16945 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16946 (and
16947 (get v 'custom-type) (get v 'standard-value)
16948 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16949 (push v list)))))
16950 (kill-buffer (get-buffer "*Warn about privacy*"))
16951 list))
16952 nil nil
16953 "Remember to cover the basics, that is, what you expected to happen and
16954 what in fact did happen. You don't know how to make a good report? See
16956 http://orgmode.org/manual/Feedback.html#Feedback
16958 Your bug report will be posted to the Org-mode mailing list.
16959 ------------------------------------------------------------------------")
16960 (save-excursion
16961 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16962 (replace-match "\\1Bug: \\3 [\\2]")))))
16965 (defun org-install-agenda-files-menu ()
16966 (let ((bl (buffer-list)))
16967 (save-excursion
16968 (while bl
16969 (set-buffer (pop bl))
16970 (if (org-mode-p) (setq bl nil)))
16971 (when (org-mode-p)
16972 (easy-menu-change
16973 '("Org") "File List for Agenda"
16974 (append
16975 (list
16976 ["Edit File List" (org-edit-agenda-file-list) t]
16977 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16978 ["Remove Current File from List" org-remove-file t]
16979 ["Cycle through agenda files" org-cycle-agenda-files t]
16980 ["Occur in all agenda files" org-occur-in-agenda-files t]
16981 "--")
16982 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16984 ;;;; Documentation
16986 ;;;###autoload
16987 (defun org-require-autoloaded-modules ()
16988 (interactive)
16989 (mapc 'require
16990 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16991 org-docbook org-exp org-html org-icalendar
16992 org-id org-latex
16993 org-publish org-remember org-table
16994 org-timer org-xoxo)))
16996 ;;;###autoload
16997 (defun org-reload (&optional uncompiled)
16998 "Reload all org lisp files.
16999 With prefix arg UNCOMPILED, load the uncompiled versions."
17000 (interactive "P")
17001 (require 'find-func)
17002 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
17003 (dir-org (file-name-directory (org-find-library-name "org")))
17004 (dir-org-contrib (ignore-errors
17005 (file-name-directory
17006 (org-find-library-name "org-contribdir"))))
17007 (files
17008 (append (directory-files dir-org t file-re)
17009 (and dir-org-contrib
17010 (directory-files dir-org-contrib t file-re))))
17011 (remove-re (concat (if (featurep 'xemacs)
17012 "org-colview" "org-colview-xemacs")
17013 "\\'")))
17014 (setq files (mapcar 'file-name-sans-extension files))
17015 (setq files (mapcar
17016 (lambda (x) (if (string-match remove-re x) nil x))
17017 files))
17018 (setq files (delq nil files))
17019 (mapc
17020 (lambda (f)
17021 (when (featurep (intern (file-name-nondirectory f)))
17022 (if (and (not uncompiled)
17023 (file-exists-p (concat f ".elc")))
17024 (load (concat f ".elc") nil nil t)
17025 (load (concat f ".el") nil nil t))))
17026 files))
17027 (org-version))
17029 ;;;###autoload
17030 (defun org-customize ()
17031 "Call the customize function with org as argument."
17032 (interactive)
17033 (org-load-modules-maybe)
17034 (org-require-autoloaded-modules)
17035 (customize-browse 'org))
17037 (defun org-create-customize-menu ()
17038 "Create a full customization menu for Org-mode, insert it into the menu."
17039 (interactive)
17040 (org-load-modules-maybe)
17041 (org-require-autoloaded-modules)
17042 (if (fboundp 'customize-menu-create)
17043 (progn
17044 (easy-menu-change
17045 '("Org") "Customize"
17046 `(["Browse Org group" org-customize t]
17047 "--"
17048 ,(customize-menu-create 'org)
17049 ["Set" Custom-set t]
17050 ["Save" Custom-save t]
17051 ["Reset to Current" Custom-reset-current t]
17052 ["Reset to Saved" Custom-reset-saved t]
17053 ["Reset to Standard Settings" Custom-reset-standard t]))
17054 (message "\"Org\"-menu now contains full customization menu"))
17055 (error "Cannot expand menu (outdated version of cus-edit.el)")))
17057 ;;;; Miscellaneous stuff
17059 ;;; Generally useful functions
17061 (defun org-get-at-bol (property)
17062 "Get text property PROPERTY at beginning of line."
17063 (get-text-property (point-at-bol) property))
17065 (defun org-find-text-property-in-string (prop s)
17066 "Return the first non-nil value of property PROP in string S."
17067 (or (get-text-property 0 prop s)
17068 (get-text-property (or (next-single-property-change 0 prop s) 0)
17069 prop s)))
17071 (defun org-display-warning (message) ;; Copied from Emacs-Muse
17072 "Display the given MESSAGE as a warning."
17073 (if (fboundp 'display-warning)
17074 (display-warning 'org message
17075 (if (featurep 'xemacs) 'warning :warning))
17076 (let ((buf (get-buffer-create "*Org warnings*")))
17077 (with-current-buffer buf
17078 (goto-char (point-max))
17079 (insert "Warning (Org): " message)
17080 (unless (bolp)
17081 (newline)))
17082 (display-buffer buf)
17083 (sit-for 0))))
17085 (defun org-in-commented-line ()
17086 "Is point in a line starting with `#'?"
17087 (equal (char-after (point-at-bol)) ?#))
17089 (defun org-in-verbatim-emphasis ()
17090 (save-match-data
17091 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
17093 (defun org-goto-marker-or-bmk (marker &optional bookmark)
17094 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
17095 (if (and marker (marker-buffer marker)
17096 (buffer-live-p (marker-buffer marker)))
17097 (progn
17098 (switch-to-buffer (marker-buffer marker))
17099 (if (or (> marker (point-max)) (< marker (point-min)))
17100 (widen))
17101 (goto-char marker)
17102 (org-show-context 'org-goto))
17103 (if bookmark
17104 (bookmark-jump bookmark)
17105 (error "Cannot find location"))))
17107 (defun org-quote-csv-field (s)
17108 "Quote field for inclusion in CSV material."
17109 (if (string-match "[\",]" s)
17110 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
17113 (defun org-plist-delete (plist property)
17114 "Delete PROPERTY from PLIST.
17115 This is in contrast to merely setting it to 0."
17116 (let (p)
17117 (while plist
17118 (if (not (eq property (car plist)))
17119 (setq p (plist-put p (car plist) (nth 1 plist))))
17120 (setq plist (cddr plist)))
17123 (defun org-force-self-insert (N)
17124 "Needed to enforce self-insert under remapping."
17125 (interactive "p")
17126 (self-insert-command N))
17128 (defun org-string-width (s)
17129 "Compute width of string, ignoring invisible characters.
17130 This ignores character with invisibility property `org-link', and also
17131 characters with property `org-cwidth', because these will become invisible
17132 upon the next fontification round."
17133 (let (b l)
17134 (when (or (eq t buffer-invisibility-spec)
17135 (assq 'org-link buffer-invisibility-spec))
17136 (while (setq b (text-property-any 0 (length s)
17137 'invisible 'org-link s))
17138 (setq s (concat (substring s 0 b)
17139 (substring s (or (next-single-property-change
17140 b 'invisible s) (length s)))))))
17141 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
17142 (setq s (concat (substring s 0 b)
17143 (substring s (or (next-single-property-change
17144 b 'org-cwidth s) (length s))))))
17145 (setq l (string-width s) b -1)
17146 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
17147 (setq l (- l (get-text-property b 'org-dwidth-n s))))
17150 (defun org-get-indentation (&optional line)
17151 "Get the indentation of the current line, interpreting tabs.
17152 When LINE is given, assume it represents a line and compute its indentation."
17153 (if line
17154 (if (string-match "^ *" (org-remove-tabs line))
17155 (match-end 0))
17156 (save-excursion
17157 (beginning-of-line 1)
17158 (skip-chars-forward " \t")
17159 (current-column))))
17161 (defun org-remove-tabs (s &optional width)
17162 "Replace tabulators in S with spaces.
17163 Assumes that s is a single line, starting in column 0."
17164 (setq width (or width tab-width))
17165 (while (string-match "\t" s)
17166 (setq s (replace-match
17167 (make-string
17168 (- (* width (/ (+ (match-beginning 0) width) width))
17169 (match-beginning 0)) ?\ )
17170 t t s)))
17173 (defun org-fix-indentation (line ind)
17174 "Fix indentation in LINE.
17175 IND is a cons cell with target and minimum indentation.
17176 If the current indentation in LINE is smaller than the minimum,
17177 leave it alone. If it is larger than ind, set it to the target."
17178 (let* ((l (org-remove-tabs line))
17179 (i (org-get-indentation l))
17180 (i1 (car ind)) (i2 (cdr ind)))
17181 (if (>= i i2) (setq l (substring line i2)))
17182 (if (> i1 0)
17183 (concat (make-string i1 ?\ ) l)
17184 l)))
17186 (defun org-remove-indentation (code &optional n)
17187 "Remove the maximum common indentation from the lines in CODE.
17188 N may optionally be the number of spaces to remove."
17189 (with-temp-buffer
17190 (insert code)
17191 (org-do-remove-indentation n)
17192 (buffer-string)))
17194 (defun org-do-remove-indentation (&optional n)
17195 "Remove the maximum common indentation from the buffer."
17196 (untabify (point-min) (point-max))
17197 (let ((min 10000) re)
17198 (if n
17199 (setq min n)
17200 (goto-char (point-min))
17201 (while (re-search-forward "^ *[^ \n]" nil t)
17202 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
17203 (unless (or (= min 0) (= min 10000))
17204 (setq re (format "^ \\{%d\\}" min))
17205 (goto-char (point-min))
17206 (while (re-search-forward re nil t)
17207 (replace-match "")
17208 (end-of-line 1))
17209 min)))
17211 (defun org-fill-template (template alist)
17212 "Find each %key of ALIST in TEMPLATE and replace it."
17213 (let ((case-fold-search nil)
17214 entry key value)
17215 (setq alist (sort (copy-sequence alist)
17216 (lambda (a b) (< (length (car a)) (length (car b))))))
17217 (while (setq entry (pop alist))
17218 (setq template
17219 (replace-regexp-in-string
17220 (concat "%" (regexp-quote (car entry)))
17221 (cdr entry) template t t)))
17222 template))
17224 (defun org-base-buffer (buffer)
17225 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
17226 (if (not buffer)
17227 buffer
17228 (or (buffer-base-buffer buffer)
17229 buffer)))
17231 (defun org-trim (s)
17232 "Remove whitespace at beginning and end of string."
17233 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
17234 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
17237 (defun org-wrap (string &optional width lines)
17238 "Wrap string to either a number of lines, or a width in characters.
17239 If WIDTH is non-nil, the string is wrapped to that width, however many lines
17240 that costs. If there is a word longer than WIDTH, the text is actually
17241 wrapped to the length of that word.
17242 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
17243 many lines, whatever width that takes.
17244 The return value is a list of lines, without newlines at the end."
17245 (let* ((words (org-split-string string "[ \t\n]+"))
17246 (maxword (apply 'max (mapcar 'org-string-width words)))
17247 w ll)
17248 (cond (width
17249 (org-do-wrap words (max maxword width)))
17250 (lines
17251 (setq w maxword)
17252 (setq ll (org-do-wrap words maxword))
17253 (if (<= (length ll) lines)
17255 (setq ll words)
17256 (while (> (length ll) lines)
17257 (setq w (1+ w))
17258 (setq ll (org-do-wrap words w)))
17259 ll))
17260 (t (error "Cannot wrap this")))))
17262 (defun org-do-wrap (words width)
17263 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
17264 (let (lines line)
17265 (while words
17266 (setq line (pop words))
17267 (while (and words (< (+ (length line) (length (car words))) width))
17268 (setq line (concat line " " (pop words))))
17269 (setq lines (push line lines)))
17270 (nreverse lines)))
17272 (defun org-split-string (string &optional separators)
17273 "Splits STRING into substrings at SEPARATORS.
17274 No empty strings are returned if there are matches at the beginning
17275 and end of string."
17276 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
17277 (start 0)
17278 notfirst
17279 (list nil))
17280 (while (and (string-match rexp string
17281 (if (and notfirst
17282 (= start (match-beginning 0))
17283 (< start (length string)))
17284 (1+ start) start))
17285 (< (match-beginning 0) (length string)))
17286 (setq notfirst t)
17287 (or (eq (match-beginning 0) 0)
17288 (and (eq (match-beginning 0) (match-end 0))
17289 (eq (match-beginning 0) start))
17290 (setq list
17291 (cons (substring string start (match-beginning 0))
17292 list)))
17293 (setq start (match-end 0)))
17294 (or (eq start (length string))
17295 (setq list
17296 (cons (substring string start)
17297 list)))
17298 (nreverse list)))
17300 (defun org-quote-vert (s)
17301 "Replace \"|\" with \"\\vert\"."
17302 (while (string-match "|" s)
17303 (setq s (replace-match "\\vert" t t s)))
17306 (defun org-uuidgen-p (s)
17307 "Is S an ID created by UUIDGEN?"
17308 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
17310 (defun org-context ()
17311 "Return a list of contexts of the current cursor position.
17312 If several contexts apply, all are returned.
17313 Each context entry is a list with a symbol naming the context, and
17314 two positions indicating start and end of the context. Possible
17315 contexts are:
17317 :headline anywhere in a headline
17318 :headline-stars on the leading stars in a headline
17319 :todo-keyword on a TODO keyword (including DONE) in a headline
17320 :tags on the TAGS in a headline
17321 :priority on the priority cookie in a headline
17322 :item on the first line of a plain list item
17323 :item-bullet on the bullet/number of a plain list item
17324 :checkbox on the checkbox in a plain list item
17325 :table in an org-mode table
17326 :table-special on a special filed in a table
17327 :table-table in a table.el table
17328 :link on a hyperlink
17329 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
17330 :target on a <<target>>
17331 :radio-target on a <<<radio-target>>>
17332 :latex-fragment on a LaTeX fragment
17333 :latex-preview on a LaTeX fragment with overlayed preview image
17335 This function expects the position to be visible because it uses font-lock
17336 faces as a help to recognize the following contexts: :table-special, :link,
17337 and :keyword."
17338 (let* ((f (get-text-property (point) 'face))
17339 (faces (if (listp f) f (list f)))
17340 (p (point)) clist o)
17341 ;; First the large context
17342 (cond
17343 ((org-on-heading-p t)
17344 (push (list :headline (point-at-bol) (point-at-eol)) clist)
17345 (when (progn
17346 (beginning-of-line 1)
17347 (looking-at org-todo-line-tags-regexp))
17348 (push (org-point-in-group p 1 :headline-stars) clist)
17349 (push (org-point-in-group p 2 :todo-keyword) clist)
17350 (push (org-point-in-group p 4 :tags) clist))
17351 (goto-char p)
17352 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
17353 (if (looking-at "\\[#[A-Z0-9]\\]")
17354 (push (org-point-in-group p 0 :priority) clist)))
17356 ((org-at-item-p)
17357 (push (org-point-in-group p 2 :item-bullet) clist)
17358 (push (list :item (point-at-bol)
17359 (save-excursion (org-end-of-item) (point)))
17360 clist)
17361 (and (org-at-item-checkbox-p)
17362 (push (org-point-in-group p 0 :checkbox) clist)))
17364 ((org-at-table-p)
17365 (push (list :table (org-table-begin) (org-table-end)) clist)
17366 (if (memq 'org-formula faces)
17367 (push (list :table-special
17368 (previous-single-property-change p 'face)
17369 (next-single-property-change p 'face)) clist)))
17370 ((org-at-table-p 'any)
17371 (push (list :table-table) clist)))
17372 (goto-char p)
17374 ;; Now the small context
17375 (cond
17376 ((org-at-timestamp-p)
17377 (push (org-point-in-group p 0 :timestamp) clist))
17378 ((memq 'org-link faces)
17379 (push (list :link
17380 (previous-single-property-change p 'face)
17381 (next-single-property-change p 'face)) clist))
17382 ((memq 'org-special-keyword faces)
17383 (push (list :keyword
17384 (previous-single-property-change p 'face)
17385 (next-single-property-change p 'face)) clist))
17386 ((org-on-target-p)
17387 (push (org-point-in-group p 0 :target) clist)
17388 (goto-char (1- (match-beginning 0)))
17389 (if (looking-at org-radio-target-regexp)
17390 (push (org-point-in-group p 0 :radio-target) clist))
17391 (goto-char p))
17392 ((setq o (car (delq nil
17393 (mapcar
17394 (lambda (x)
17395 (if (memq x org-latex-fragment-image-overlays) x))
17396 (overlays-at (point))))))
17397 (push (list :latex-fragment
17398 (overlay-start o) (overlay-end o)) clist)
17399 (push (list :latex-preview
17400 (overlay-start o) (overlay-end o)) clist))
17401 ((org-inside-LaTeX-fragment-p)
17402 ;; FIXME: positions wrong.
17403 (push (list :latex-fragment (point) (point)) clist)))
17405 (setq clist (nreverse (delq nil clist)))
17406 clist))
17408 ;; FIXME: Compare with at-regexp-p Do we need both?
17409 (defun org-in-regexp (re &optional nlines visually)
17410 "Check if point is inside a match of regexp.
17411 Normally only the current line is checked, but you can include NLINES extra
17412 lines both before and after point into the search.
17413 If VISUALLY is set, require that the cursor is not after the match but
17414 really on, so that the block visually is on the match."
17415 (catch 'exit
17416 (let ((pos (point))
17417 (eol (point-at-eol (+ 1 (or nlines 0))))
17418 (inc (if visually 1 0)))
17419 (save-excursion
17420 (beginning-of-line (- 1 (or nlines 0)))
17421 (while (re-search-forward re eol t)
17422 (if (and (<= (match-beginning 0) pos)
17423 (>= (+ inc (match-end 0)) pos))
17424 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
17426 (defun org-at-regexp-p (regexp)
17427 "Is point inside a match of REGEXP in the current line?"
17428 (catch 'exit
17429 (save-excursion
17430 (let ((pos (point)) (end (point-at-eol)))
17431 (beginning-of-line 1)
17432 (while (re-search-forward regexp end t)
17433 (if (and (<= (match-beginning 0) pos)
17434 (>= (match-end 0) pos))
17435 (throw 'exit t)))
17436 nil))))
17438 (defun org-in-regexps-block-p (start-re end-re)
17439 "Returns t if the current point is between matches of START-RE and END-RE.
17440 This will also return to if point is on one of the two matches."
17441 (interactive)
17442 (let ((p (point)))
17443 (save-excursion
17444 (and (or (org-at-regexp-p start-re)
17445 (re-search-backward start-re nil t))
17446 (re-search-forward end-re nil t)
17447 (>= (point) p)))))
17449 (defun org-occur-in-agenda-files (regexp &optional nlines)
17450 "Call `multi-occur' with buffers for all agenda files."
17451 (interactive "sOrg-files matching: \np")
17452 (let* ((files (org-agenda-files))
17453 (tnames (mapcar 'file-truename files))
17454 (extra org-agenda-text-search-extra-files)
17456 (when (eq (car extra) 'agenda-archives)
17457 (setq extra (cdr extra))
17458 (setq files (org-add-archive-files files)))
17459 (while (setq f (pop extra))
17460 (unless (member (file-truename f) tnames)
17461 (add-to-list 'files f 'append)
17462 (add-to-list 'tnames (file-truename f) 'append)))
17463 (multi-occur
17464 (mapcar (lambda (x)
17465 (with-current-buffer
17466 (or (get-file-buffer x) (find-file-noselect x))
17467 (widen)
17468 (current-buffer)))
17469 files)
17470 regexp)))
17472 (if (boundp 'occur-mode-find-occurrence-hook)
17473 ;; Emacs 23
17474 (add-hook 'occur-mode-find-occurrence-hook
17475 (lambda ()
17476 (when (org-mode-p)
17477 (org-reveal))))
17478 ;; Emacs 22
17479 (defadvice occur-mode-goto-occurrence
17480 (after org-occur-reveal activate)
17481 (and (org-mode-p) (org-reveal)))
17482 (defadvice occur-mode-goto-occurrence-other-window
17483 (after org-occur-reveal activate)
17484 (and (org-mode-p) (org-reveal)))
17485 (defadvice occur-mode-display-occurrence
17486 (after org-occur-reveal activate)
17487 (when (org-mode-p)
17488 (let ((pos (occur-mode-find-occurrence)))
17489 (with-current-buffer (marker-buffer pos)
17490 (save-excursion
17491 (goto-char pos)
17492 (org-reveal)))))))
17494 (defun org-occur-link-in-agenda-files ()
17495 "Create a link and search for it in the agendas.
17496 The link is not stored in `org-stored-links', it is just created
17497 for the search purpose."
17498 (interactive)
17499 (let ((link (condition-case nil
17500 (org-store-link nil)
17501 (error "Unable to create a link to here"))))
17502 (org-occur-in-agenda-files (regexp-quote link))))
17504 (defun org-uniquify (list)
17505 "Remove duplicate elements from LIST."
17506 (let (res)
17507 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
17508 res))
17510 (defun org-delete-all (elts list)
17511 "Remove all elements in ELTS from LIST."
17512 (while elts
17513 (setq list (delete (pop elts) list)))
17514 list)
17516 (defun org-remove-if (predicate seq)
17517 "Remove everything from SEQ that fulfills PREDICATE."
17518 (let (res e)
17519 (while seq
17520 (setq e (pop seq))
17521 (if (not (funcall predicate e)) (push e res)))
17522 (nreverse res)))
17524 (defun org-remove-if-not (predicate seq)
17525 "Remove everything from SEQ that does not fulfill PREDICATE."
17526 (let (res e)
17527 (while seq
17528 (setq e (pop seq))
17529 (if (funcall predicate e) (push e res)))
17530 (nreverse res)))
17532 (defun org-back-over-empty-lines ()
17533 "Move backwards over whitespace, to the beginning of the first empty line.
17534 Returns the number of empty lines passed."
17535 (let ((pos (point)))
17536 (skip-chars-backward " \t\n\r")
17537 (beginning-of-line 2)
17538 (goto-char (min (point) pos))
17539 (count-lines (point) pos)))
17541 (defun org-skip-whitespace ()
17542 (skip-chars-forward " \t\n\r"))
17544 (defun org-point-in-group (point group &optional context)
17545 "Check if POINT is in match-group GROUP.
17546 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
17547 match. If the match group does ot exist or point is not inside it,
17548 return nil."
17549 (and (match-beginning group)
17550 (>= point (match-beginning group))
17551 (<= point (match-end group))
17552 (if context
17553 (list context (match-beginning group) (match-end group))
17554 t)))
17556 (defun org-switch-to-buffer-other-window (&rest args)
17557 "Switch to buffer in a second window on the current frame.
17558 In particular, do not allow pop-up frames."
17559 (let (pop-up-frames special-display-buffer-names special-display-regexps
17560 special-display-function)
17561 (apply 'switch-to-buffer-other-window args)))
17563 (defun org-combine-plists (&rest plists)
17564 "Create a single property list from all plists in PLISTS.
17565 The process starts by copying the first list, and then setting properties
17566 from the other lists. Settings in the last list are the most significant
17567 ones and overrule settings in the other lists."
17568 (let ((rtn (copy-sequence (pop plists)))
17569 p v ls)
17570 (while plists
17571 (setq ls (pop plists))
17572 (while ls
17573 (setq p (pop ls) v (pop ls))
17574 (setq rtn (plist-put rtn p v))))
17575 rtn))
17577 (defun org-move-line-down (arg)
17578 "Move the current line down. With prefix argument, move it past ARG lines."
17579 (interactive "p")
17580 (let ((col (current-column))
17581 beg end pos)
17582 (beginning-of-line 1) (setq beg (point))
17583 (beginning-of-line 2) (setq end (point))
17584 (beginning-of-line (+ 1 arg))
17585 (setq pos (move-marker (make-marker) (point)))
17586 (insert (delete-and-extract-region beg end))
17587 (goto-char pos)
17588 (org-move-to-column col)))
17590 (defun org-move-line-up (arg)
17591 "Move the current line up. With prefix argument, move it past ARG lines."
17592 (interactive "p")
17593 (let ((col (current-column))
17594 beg end pos)
17595 (beginning-of-line 1) (setq beg (point))
17596 (beginning-of-line 2) (setq end (point))
17597 (beginning-of-line (- arg))
17598 (setq pos (move-marker (make-marker) (point)))
17599 (insert (delete-and-extract-region beg end))
17600 (goto-char pos)
17601 (org-move-to-column col)))
17603 (defun org-replace-escapes (string table)
17604 "Replace %-escapes in STRING with values in TABLE.
17605 TABLE is an association list with keys like \"%a\" and string values.
17606 The sequences in STRING may contain normal field width and padding information,
17607 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
17608 so values can contain further %-escapes if they are define later in TABLE."
17609 (let ((case-fold-search nil)
17610 e re rpl)
17611 (while (setq e (pop table))
17612 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
17613 (while (string-match re string)
17614 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
17615 (cdr e)))
17616 (setq string (replace-match rpl t t string))))
17617 string))
17620 (defun org-sublist (list start end)
17621 "Return a section of LIST, from START to END.
17622 Counting starts at 1."
17623 (let (rtn (c start))
17624 (setq list (nthcdr (1- start) list))
17625 (while (and list (<= c end))
17626 (push (pop list) rtn)
17627 (setq c (1+ c)))
17628 (nreverse rtn)))
17630 (defun org-find-base-buffer-visiting (file)
17631 "Like `find-buffer-visiting' but always return the base buffer and
17632 not an indirect buffer."
17633 (let ((buf (or (get-file-buffer file)
17634 (find-buffer-visiting file))))
17635 (if buf
17636 (or (buffer-base-buffer buf) buf)
17637 nil)))
17639 (defun org-image-file-name-regexp (&optional extensions)
17640 "Return regexp matching the file names of images.
17641 If EXTENSIONS is given, only match these."
17642 (if (and (not extensions) (fboundp 'image-file-name-regexp))
17643 (image-file-name-regexp)
17644 (let ((image-file-name-extensions
17645 (or extensions
17646 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
17647 "xbm" "xpm" "pbm" "pgm" "ppm"))))
17648 (concat "\\."
17649 (regexp-opt (nconc (mapcar 'upcase
17650 image-file-name-extensions)
17651 image-file-name-extensions)
17653 "\\'"))))
17655 (defun org-file-image-p (file &optional extensions)
17656 "Return non-nil if FILE is an image."
17657 (save-match-data
17658 (string-match (org-image-file-name-regexp extensions) file)))
17660 (defun org-get-cursor-date ()
17661 "Return the date at cursor in as a time.
17662 This works in the calendar and in the agenda, anywhere else it just
17663 returns the current time."
17664 (let (date day defd)
17665 (cond
17666 ((eq major-mode 'calendar-mode)
17667 (setq date (calendar-cursor-to-date)
17668 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17669 ((eq major-mode 'org-agenda-mode)
17670 (setq day (get-text-property (point) 'day))
17671 (if day
17672 (setq date (calendar-gregorian-from-absolute day)
17673 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
17674 (nth 2 date))))))
17675 (or defd (current-time))))
17677 (defvar org-agenda-action-marker (make-marker)
17678 "Marker pointing to the entry for the next agenda action.")
17680 (defun org-mark-entry-for-agenda-action ()
17681 "Mark the current entry as target of an agenda action.
17682 Agenda actions are actions executed from the agenda with the key `k',
17683 which make use of the date at the cursor."
17684 (interactive)
17685 (move-marker org-agenda-action-marker
17686 (save-excursion (org-back-to-heading t) (point))
17687 (current-buffer))
17688 (message
17689 "Entry marked for action; press `k' at desired date in agenda or calendar"))
17691 ;;; Paragraph filling stuff.
17692 ;; We want this to be just right, so use the full arsenal.
17694 (defun org-indent-line-function ()
17695 "Indent line like previous, but further if previous was headline or item."
17696 (interactive)
17697 (let* ((pos (point))
17698 (itemp (org-at-item-p))
17699 (case-fold-search t)
17700 (org-drawer-regexp (or org-drawer-regexp "\000"))
17701 column bpos bcol tpos tcol bullet btype bullet-type)
17702 ;; Find the previous relevant line
17703 (beginning-of-line 1)
17704 (cond
17705 ((looking-at "#") (setq column 0))
17706 ((looking-at "\\*+ ") (setq column 0))
17707 ((and (looking-at "[ \t]*:END:")
17708 (save-excursion (re-search-backward org-drawer-regexp nil t)))
17709 (save-excursion
17710 (goto-char (1- (match-beginning 1)))
17711 (setq column (current-column))))
17712 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
17713 (save-excursion
17714 (re-search-backward
17715 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
17716 (setq column (org-get-indentation (match-string 0))))
17718 (beginning-of-line 0)
17719 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
17720 (not (looking-at "[ \t]*:END:"))
17721 (not (looking-at org-drawer-regexp)))
17722 (beginning-of-line 0))
17723 (cond
17724 ((looking-at "\\*+[ \t]+")
17725 (if (not org-adapt-indentation)
17726 (setq column 0)
17727 (goto-char (match-end 0))
17728 (setq column (current-column))))
17729 ((looking-at org-drawer-regexp)
17730 (goto-char (1- (match-beginning 1)))
17731 (setq column (current-column)))
17732 ((looking-at "\\([ \t]*\\):END:")
17733 (goto-char (match-end 1))
17734 (setq column (current-column)))
17735 ((org-in-item-p)
17736 (org-beginning-of-item)
17737 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
17738 (setq bpos (match-beginning 1) tpos (match-end 0)
17739 bcol (progn (goto-char bpos) (current-column))
17740 tcol (progn (goto-char tpos) (current-column))
17741 bullet (match-string 1)
17742 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
17743 (if (> tcol (+ bcol org-description-max-indent))
17744 (setq tcol (+ bcol 5)))
17745 (if (not itemp)
17746 (setq column tcol)
17747 (goto-char pos)
17748 (beginning-of-line 1)
17749 (if (looking-at "\\S-")
17750 (progn
17751 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
17752 (setq bullet (match-string 1)
17753 btype (if (string-match "[0-9]" bullet) "n" bullet))
17754 (setq column (if (equal btype bullet-type) bcol tcol)))
17755 (setq column (org-get-indentation)))))
17756 (t (setq column (org-get-indentation))))))
17757 (goto-char pos)
17758 (if (<= (current-column) (current-indentation))
17759 (org-indent-line-to column)
17760 (save-excursion (org-indent-line-to column)))
17761 (setq column (current-column))
17762 (beginning-of-line 1)
17763 (if (looking-at
17764 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
17765 (replace-match (concat (match-string 1)
17766 (format org-property-format
17767 (match-string 2) (match-string 3)))
17768 t t))
17769 (org-move-to-column column)))
17771 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
17772 "Variable to store copy of `adaptive-fill-regexp'.
17773 Since `adaptive-fill-regexp' is set to never match, we need to
17774 store a backup of its value before entering `org-mode' so that
17775 the functionality can be provided as a fall-back.")
17777 (defun org-set-autofill-regexps ()
17778 (interactive)
17779 ;; In the paragraph separator we include headlines, because filling
17780 ;; text in a line directly attached to a headline would otherwise
17781 ;; fill the headline as well.
17782 (org-set-local 'comment-start-skip "^#+[ \t]*")
17783 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
17784 ;; The paragraph starter includes hand-formatted lists.
17785 (org-set-local
17786 'paragraph-start
17787 (concat
17788 "\f" "\\|"
17789 "[ ]*$" "\\|"
17790 "\\*+ " "\\|"
17791 "[ \t]*#" "\\|"
17792 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
17793 "[ \t]*[:|]" "\\|"
17794 "\\$\\$" "\\|"
17795 "\\\\\\(begin\\|end\\|[][]\\)"))
17796 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17797 ;; But only if the user has not turned off tables or fixed-width regions
17798 (org-set-local
17799 'auto-fill-inhibit-regexp
17800 (concat "\\*+ \\|#\\+"
17801 "\\|[ \t]*" org-keyword-time-regexp
17802 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17803 (concat
17804 "\\|[ \t]*["
17805 (if org-enable-table-editor "|" "")
17806 (if org-enable-fixed-width-editor ":" "")
17807 "]"))))
17808 ;; We use our own fill-paragraph function, to make sure that tables
17809 ;; and fixed-width regions are not wrapped. That function will pass
17810 ;; through to `fill-paragraph' when appropriate.
17811 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17812 ;; Adaptive filling: To get full control, first make sure that
17813 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17814 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
17815 (org-set-local 'org-adaptive-fill-regexp-backup
17816 adaptive-fill-regexp))
17817 (org-set-local 'adaptive-fill-regexp "\000")
17818 (org-set-local 'adaptive-fill-function
17819 'org-adaptive-fill-function)
17820 (org-set-local
17821 'align-mode-rules-list
17822 '((org-in-buffer-settings
17823 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
17824 (modes . '(org-mode))))))
17826 (defun org-fill-paragraph (&optional justify)
17827 "Re-align a table, pass through to fill-paragraph if no table."
17828 (let ((table-p (org-at-table-p))
17829 (table.el-p (org-at-table.el-p)))
17830 (cond ((and (equal (char-after (point-at-bol)) ?*)
17831 (save-excursion (goto-char (point-at-bol))
17832 (looking-at outline-regexp)))
17833 t) ; skip headlines
17834 (table.el-p t) ; skip table.el tables
17835 (table-p (org-table-align) t) ; align org-mode tables
17836 (t nil)))) ; call paragraph-fill
17838 ;; For reference, this is the default value of adaptive-fill-regexp
17839 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17841 (defun org-adaptive-fill-function ()
17842 "Return a fill prefix for org-mode files.
17843 In particular, this makes sure hanging paragraphs for hand-formatted lists
17844 work correctly."
17845 (cond
17846 ;; Comment line
17847 ((looking-at "#[ \t]+")
17848 (match-string-no-properties 0))
17849 ;; Description list
17850 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17851 (save-excursion
17852 (if (> (match-end 1) (+ (match-beginning 1)
17853 org-description-max-indent))
17854 (goto-char (+ (match-beginning 1) 5))
17855 (goto-char (match-end 0)))
17856 (make-string (current-column) ?\ )))
17857 ;; Ordered or unordered list
17858 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)")
17859 (save-excursion
17860 (goto-char (match-end 0))
17861 (make-string (current-column) ?\ )))
17862 ;; Other text
17863 ((looking-at org-adaptive-fill-regexp-backup)
17864 (match-string-no-properties 0))))
17866 ;;; Other stuff.
17868 (defun org-toggle-fixed-width-section (arg)
17869 "Toggle the fixed-width export.
17870 If there is no active region, the QUOTE keyword at the current headline is
17871 inserted or removed. When present, it causes the text between this headline
17872 and the next to be exported as fixed-width text, and unmodified.
17873 If there is an active region, this command adds or removes a colon as the
17874 first character of this line. If the first character of a line is a colon,
17875 this line is also exported in fixed-width font."
17876 (interactive "P")
17877 (let* ((cc 0)
17878 (regionp (org-region-active-p))
17879 (beg (if regionp (region-beginning) (point)))
17880 (end (if regionp (region-end)))
17881 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17882 (case-fold-search nil)
17883 (re "[ \t]*\\(: \\)")
17884 off)
17885 (if regionp
17886 (save-excursion
17887 (goto-char beg)
17888 (setq cc (current-column))
17889 (beginning-of-line 1)
17890 (setq off (looking-at re))
17891 (while (> nlines 0)
17892 (setq nlines (1- nlines))
17893 (beginning-of-line 1)
17894 (cond
17895 (arg
17896 (org-move-to-column cc t)
17897 (insert ": \n")
17898 (forward-line -1))
17899 ((and off (looking-at re))
17900 (replace-match "" t t nil 1))
17901 ((not off) (org-move-to-column cc t) (insert ": ")))
17902 (forward-line 1)))
17903 (save-excursion
17904 (org-back-to-heading)
17905 (if (looking-at (concat outline-regexp
17906 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17907 (replace-match "" t t nil 1)
17908 (if (looking-at outline-regexp)
17909 (progn
17910 (goto-char (match-end 0))
17911 (insert org-quote-string " "))))))))
17913 (defun org-reftex-citation ()
17914 "Use reftex-citation to insert a citation into the buffer.
17915 This looks for a line like
17917 #+BIBLIOGRAPHY: foo plain option:-d
17919 and derives from it that foo.bib is the bibliography file relevant
17920 for this document. It then installs the necessary environment for RefTeX
17921 to work in this buffer and calls `reftex-citation' to insert a citation
17922 into the buffer.
17924 Export of such citations to both LaTeX and HTML is handled by the contributed
17925 package org-exp-bibtex by Taru Karttunen."
17926 (interactive)
17927 (let ((reftex-docstruct-symbol 'rds)
17928 (reftex-cite-format "\\cite{%l}")
17929 rds bib)
17930 (save-excursion
17931 (save-restriction
17932 (widen)
17933 (let ((case-fold-search t)
17934 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17935 (if (not (save-excursion
17936 (or (re-search-forward re nil t)
17937 (re-search-backward re nil t))))
17938 (error "No bibliography defined in file")
17939 (setq bib (concat (match-string 1) ".bib")
17940 rds (list (list 'bib bib)))))))
17941 (call-interactively 'reftex-citation)))
17943 ;;;; Functions extending outline functionality
17945 (defun org-beginning-of-line (&optional arg)
17946 "Go to the beginning of the current line. If that is invisible, continue
17947 to a visible line beginning. This makes the function of C-a more intuitive.
17948 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17949 first attempt, and only move to after the tags when the cursor is already
17950 beyond the end of the headline."
17951 (interactive "P")
17952 (let ((pos (point))
17953 (special (if (consp org-special-ctrl-a/e)
17954 (car org-special-ctrl-a/e)
17955 org-special-ctrl-a/e))
17956 refpos)
17957 (if (org-bound-and-true-p line-move-visual)
17958 (beginning-of-visual-line 1)
17959 (beginning-of-line 1))
17960 (if (and arg (fboundp 'move-beginning-of-line))
17961 (call-interactively 'move-beginning-of-line)
17962 (if (bobp)
17964 (backward-char 1)
17965 (if (org-invisible-p)
17966 (while (and (not (bobp)) (org-invisible-p))
17967 (backward-char 1)
17968 (beginning-of-line 1))
17969 (forward-char 1))))
17970 (when special
17971 (cond
17972 ((and (looking-at org-complex-heading-regexp)
17973 (= (char-after (match-end 1)) ?\ ))
17974 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17975 (point-at-eol)))
17976 (goto-char
17977 (if (eq special t)
17978 (cond ((> pos refpos) refpos)
17979 ((= pos (point)) refpos)
17980 (t (point)))
17981 (cond ((> pos (point)) (point))
17982 ((not (eq last-command this-command)) (point))
17983 (t refpos)))))
17984 ((org-at-item-p)
17985 (goto-char
17986 (if (eq special t)
17987 (cond ((> pos (match-end 4)) (match-end 4))
17988 ((= pos (point)) (match-end 4))
17989 (t (point)))
17990 (cond ((> pos (point)) (point))
17991 ((not (eq last-command this-command)) (point))
17992 (t (match-end 4))))))))
17993 (org-no-warnings
17994 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17996 (defun org-end-of-line (&optional arg)
17997 "Go to the end of the line.
17998 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17999 first attempt, and only move to after the tags when the cursor is already
18000 beyond the end of the headline."
18001 (interactive "P")
18002 (let ((special (if (consp org-special-ctrl-a/e)
18003 (cdr org-special-ctrl-a/e)
18004 org-special-ctrl-a/e)))
18005 (if (or (not special)
18006 (not (org-on-heading-p))
18007 arg)
18008 (call-interactively
18009 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
18010 ((fboundp 'move-end-of-line) 'move-end-of-line)
18011 (t 'end-of-line)))
18012 (let ((pos (point)))
18013 (beginning-of-line 1)
18014 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
18015 (if (eq special t)
18016 (if (or (< pos (match-beginning 1))
18017 (= pos (match-end 0)))
18018 (goto-char (match-beginning 1))
18019 (goto-char (match-end 0)))
18020 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
18021 (goto-char (match-end 0))
18022 (goto-char (match-beginning 1))))
18023 (call-interactively (if (fboundp 'move-end-of-line)
18024 'move-end-of-line
18025 'end-of-line)))))
18026 (org-no-warnings
18027 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
18029 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
18030 (define-key org-mode-map "\C-e" 'org-end-of-line)
18031 (define-key org-mode-map [home] 'org-beginning-of-line)
18032 (define-key org-mode-map [end] 'org-end-of-line)
18034 (defun org-backward-sentence (&optional arg)
18035 "Go to beginning of sentence, or beginning of table field.
18036 This will call `backward-sentence' or `org-table-beginning-of-field',
18037 depending on context."
18038 (interactive "P")
18039 (cond
18040 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
18041 (t (call-interactively 'backward-sentence))))
18043 (defun org-forward-sentence (&optional arg)
18044 "Go to end of sentence, or end of table field.
18045 This will call `forward-sentence' or `org-table-end-of-field',
18046 depending on context."
18047 (interactive "P")
18048 (cond
18049 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
18050 (t (call-interactively 'forward-sentence))))
18052 (define-key org-mode-map "\M-a" 'org-backward-sentence)
18053 (define-key org-mode-map "\M-e" 'org-forward-sentence)
18055 (defun org-kill-line (&optional arg)
18056 "Kill line, to tags or end of line."
18057 (interactive "P")
18058 (cond
18059 ((or (not org-special-ctrl-k)
18060 (bolp)
18061 (not (org-on-heading-p)))
18062 (call-interactively 'kill-line))
18063 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
18064 (kill-region (point) (match-beginning 1))
18065 (org-set-tags nil t))
18066 (t (kill-region (point) (point-at-eol)))))
18068 (define-key org-mode-map "\C-k" 'org-kill-line)
18070 (defun org-yank (&optional arg)
18071 "Yank. If the kill is a subtree, treat it specially.
18072 This command will look at the current kill and check if is a single
18073 subtree, or a series of subtrees[1]. If it passes the test, and if the
18074 cursor is at the beginning of a line or after the stars of a currently
18075 empty headline, then the yank is handled specially. How exactly depends
18076 on the value of the following variables, both set by default.
18078 org-yank-folded-subtrees
18079 When set, the subtree(s) will be folded after insertion, but only
18080 if doing so would now swallow text after the yanked text.
18082 org-yank-adjusted-subtrees
18083 When set, the subtree will be promoted or demoted in order to
18084 fit into the local outline tree structure, which means that the level
18085 will be adjusted so that it becomes the smaller one of the two
18086 *visible* surrounding headings.
18088 Any prefix to this command will cause `yank' to be called directly with
18089 no special treatment. In particular, a simple `C-u' prefix will just
18090 plainly yank the text as it is.
18092 \[1] The test checks if the first non-white line is a heading
18093 and if there are no other headings with fewer stars."
18094 (interactive "P")
18095 (org-yank-generic 'yank arg))
18097 (defun org-yank-generic (command arg)
18098 "Perform some yank-like command.
18100 This function implements the behavior described in the `org-yank'
18101 documentation. However, it has been generalized to work for any
18102 interactive command with similar behavior."
18104 ;; pretend to be command COMMAND
18105 (setq this-command command)
18107 (if arg
18108 (call-interactively command)
18110 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
18111 (and (org-kill-is-subtree-p)
18112 (or (bolp)
18113 (and (looking-at "[ \t]*$")
18114 (string-match
18115 "\\`\\*+\\'"
18116 (buffer-substring (point-at-bol) (point)))))))
18117 swallowp)
18118 (cond
18119 ((and subtreep org-yank-folded-subtrees)
18120 (let ((beg (point))
18121 end)
18122 (if (and subtreep org-yank-adjusted-subtrees)
18123 (org-paste-subtree nil nil 'for-yank)
18124 (call-interactively command))
18126 (setq end (point))
18127 (goto-char beg)
18128 (when (and (bolp) subtreep
18129 (not (setq swallowp
18130 (org-yank-folding-would-swallow-text beg end))))
18131 (or (looking-at outline-regexp)
18132 (re-search-forward (concat "^" outline-regexp) end t))
18133 (while (and (< (point) end) (looking-at outline-regexp))
18134 (hide-subtree)
18135 (org-cycle-show-empty-lines 'folded)
18136 (condition-case nil
18137 (outline-forward-same-level 1)
18138 (error (goto-char end)))))
18139 (when swallowp
18140 (message
18141 "Inserted text not folded because that would swallow text"))
18143 (goto-char end)
18144 (skip-chars-forward " \t\n\r")
18145 (beginning-of-line 1)
18146 (push-mark beg 'nomsg)))
18147 ((and subtreep org-yank-adjusted-subtrees)
18148 (let ((beg (point-at-bol)))
18149 (org-paste-subtree nil nil 'for-yank)
18150 (push-mark beg 'nomsg)))
18152 (call-interactively command))))))
18154 (defun org-yank-folding-would-swallow-text (beg end)
18155 "Would hide-subtree at BEG swallow any text after END?"
18156 (let (level)
18157 (save-excursion
18158 (goto-char beg)
18159 (when (or (looking-at outline-regexp)
18160 (re-search-forward (concat "^" outline-regexp) end t))
18161 (setq level (org-outline-level)))
18162 (goto-char end)
18163 (skip-chars-forward " \t\r\n\v\f")
18164 (if (or (eobp)
18165 (and (bolp) (looking-at org-outline-regexp)
18166 (<= (org-outline-level) level)))
18167 nil ; Nothing would be swallowed
18168 t)))) ; something would swallow
18170 (define-key org-mode-map "\C-y" 'org-yank)
18172 (defun org-invisible-p ()
18173 "Check if point is at a character currently not visible."
18174 ;; Early versions of noutline don't have `outline-invisible-p'.
18175 (if (fboundp 'outline-invisible-p)
18176 (outline-invisible-p)
18177 (get-char-property (point) 'invisible)))
18179 (defun org-invisible-p2 ()
18180 "Check if point is at a character currently not visible."
18181 (save-excursion
18182 (if (and (eolp) (not (bobp))) (backward-char 1))
18183 ;; Early versions of noutline don't have `outline-invisible-p'.
18184 (if (fboundp 'outline-invisible-p)
18185 (outline-invisible-p)
18186 (get-char-property (point) 'invisible))))
18188 (defun org-back-to-heading (&optional invisible-ok)
18189 "Call `outline-back-to-heading', but provide a better error message."
18190 (condition-case nil
18191 (outline-back-to-heading invisible-ok)
18192 (error (error "Before first headline at position %d in buffer %s"
18193 (point) (current-buffer)))))
18195 (defun org-before-first-heading-p ()
18196 "Before first heading?"
18197 (save-excursion
18198 (null (re-search-backward "^\\*+ " nil t))))
18200 (defun org-on-heading-p (&optional ignored)
18201 (outline-on-heading-p t))
18202 (defun org-at-heading-p (&optional ignored)
18203 (outline-on-heading-p t))
18205 (defun org-point-at-end-of-empty-headline ()
18206 "If point is at the end of an empty headline, return t, else nil.
18207 If the heading only contains a TODO keyword, it is still still considered
18208 empty."
18209 (and (looking-at "[ \t]*$")
18210 (save-excursion
18211 (beginning-of-line 1)
18212 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
18213 "\\)?[ \t]*$")))))
18214 (defun org-at-heading-or-item-p ()
18215 (or (org-on-heading-p) (org-at-item-p)))
18217 (defun org-on-target-p ()
18218 (or (org-in-regexp org-radio-target-regexp)
18219 (org-in-regexp org-target-regexp)))
18221 (defun org-up-heading-all (arg)
18222 "Move to the heading line of which the present line is a subheading.
18223 This function considers both visible and invisible heading lines.
18224 With argument, move up ARG levels."
18225 (if (fboundp 'outline-up-heading-all)
18226 (outline-up-heading-all arg) ; emacs 21 version of outline.el
18227 (outline-up-heading arg t))) ; emacs 22 version of outline.el
18229 (defun org-up-heading-safe ()
18230 "Move to the heading line of which the present line is a subheading.
18231 This version will not throw an error. It will return the level of the
18232 headline found, or nil if no higher level is found.
18234 Also, this function will be a lot faster than `outline-up-heading',
18235 because it relies on stars being the outline starters. This can really
18236 make a significant difference in outlines with very many siblings."
18237 (let (start-level re)
18238 (org-back-to-heading t)
18239 (setq start-level (funcall outline-level))
18240 (if (equal start-level 1)
18242 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
18243 (if (re-search-backward re nil t)
18244 (funcall outline-level)))))
18246 (defun org-first-sibling-p ()
18247 "Is this heading the first child of its parents?"
18248 (interactive)
18249 (let ((re (concat "^" outline-regexp))
18250 level l)
18251 (unless (org-at-heading-p t)
18252 (error "Not at a heading"))
18253 (setq level (funcall outline-level))
18254 (save-excursion
18255 (if (not (re-search-backward re nil t))
18257 (setq l (funcall outline-level))
18258 (< l level)))))
18260 (defun org-goto-sibling (&optional previous)
18261 "Goto the next sibling, even if it is invisible.
18262 When PREVIOUS is set, go to the previous sibling instead. Returns t
18263 when a sibling was found. When none is found, return nil and don't
18264 move point."
18265 (let ((fun (if previous 're-search-backward 're-search-forward))
18266 (pos (point))
18267 (re (concat "^" outline-regexp))
18268 level l)
18269 (when (condition-case nil (org-back-to-heading t) (error nil))
18270 (setq level (funcall outline-level))
18271 (catch 'exit
18272 (or previous (forward-char 1))
18273 (while (funcall fun re nil t)
18274 (setq l (funcall outline-level))
18275 (when (< l level) (goto-char pos) (throw 'exit nil))
18276 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
18277 (goto-char pos)
18278 nil))))
18280 (defun org-show-siblings ()
18281 "Show all siblings of the current headline."
18282 (save-excursion
18283 (while (org-goto-sibling) (org-flag-heading nil)))
18284 (save-excursion
18285 (while (org-goto-sibling 'previous)
18286 (org-flag-heading nil))))
18288 (defun org-show-hidden-entry ()
18289 "Show an entry where even the heading is hidden."
18290 (save-excursion
18291 (org-show-entry)))
18293 (defun org-flag-heading (flag &optional entry)
18294 "Flag the current heading. FLAG non-nil means make invisible.
18295 When ENTRY is non-nil, show the entire entry."
18296 (save-excursion
18297 (org-back-to-heading t)
18298 ;; Check if we should show the entire entry
18299 (if entry
18300 (progn
18301 (org-show-entry)
18302 (save-excursion
18303 (and (outline-next-heading)
18304 (org-flag-heading nil))))
18305 (outline-flag-region (max (point-min) (1- (point)))
18306 (save-excursion (outline-end-of-heading) (point))
18307 flag))))
18309 (defun org-get-next-sibling ()
18310 "Move to next heading of the same level, and return point.
18311 If there is no such heading, return nil.
18312 This is like outline-next-sibling, but invisible headings are ok."
18313 (let ((level (funcall outline-level)))
18314 (outline-next-heading)
18315 (while (and (not (eobp)) (> (funcall outline-level) level))
18316 (outline-next-heading))
18317 (if (or (eobp) (< (funcall outline-level) level))
18319 (point))))
18321 (defun org-get-last-sibling ()
18322 "Move to previous heading of the same level, and return point.
18323 If there is no such heading, return nil."
18324 (let ((opoint (point))
18325 (level (funcall outline-level)))
18326 (outline-previous-heading)
18327 (when (and (/= (point) opoint) (outline-on-heading-p t))
18328 (while (and (> (funcall outline-level) level)
18329 (not (bobp)))
18330 (outline-previous-heading))
18331 (if (< (funcall outline-level) level)
18333 (point)))))
18335 (defun org-end-of-subtree (&optional invisible-OK to-heading)
18336 ;; This contains an exact copy of the original function, but it uses
18337 ;; `org-back-to-heading', to make it work also in invisible
18338 ;; trees. And is uses an invisible-OK argument.
18339 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
18340 ;; Furthermore, when used inside Org, finding the end of a large subtree
18341 ;; with many children and grandchildren etc, this can be much faster
18342 ;; than the outline version.
18343 (org-back-to-heading invisible-OK)
18344 (let ((first t)
18345 (level (funcall outline-level)))
18346 (if (and (org-mode-p) (< level 1000))
18347 ;; A true heading (not a plain list item), in Org-mode
18348 ;; This means we can easily find the end by looking
18349 ;; only for the right number of stars. Using a regexp to do
18350 ;; this is so much faster than using a Lisp loop.
18351 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
18352 (forward-char 1)
18353 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
18354 ;; something else, do it the slow way
18355 (while (and (not (eobp))
18356 (or first (> (funcall outline-level) level)))
18357 (setq first nil)
18358 (outline-next-heading)))
18359 (unless to-heading
18360 (if (memq (preceding-char) '(?\n ?\^M))
18361 (progn
18362 ;; Go to end of line before heading
18363 (forward-char -1)
18364 (if (memq (preceding-char) '(?\n ?\^M))
18365 ;; leave blank line before heading
18366 (forward-char -1))))))
18367 (point))
18369 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
18370 "Use Org version in org-mode, for dramatic speed-up."
18371 (if (eq major-mode 'org-mode)
18372 (progn
18373 (org-end-of-subtree nil t)
18374 (unless (eobp) (backward-char 1)))
18375 ad-do-it))
18377 (defun org-forward-same-level (arg &optional invisible-ok)
18378 "Move forward to the arg'th subheading at same level as this one.
18379 Stop at the first and last subheadings of a superior heading."
18380 (interactive "p")
18381 (org-back-to-heading invisible-ok)
18382 (org-on-heading-p)
18383 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18384 (re (format "^\\*\\{1,%d\\} " level))
18386 (forward-char 1)
18387 (while (> arg 0)
18388 (while (and (re-search-forward re nil 'move)
18389 (setq l (- (match-end 0) (match-beginning 0) 1))
18390 (= l level)
18391 (not invisible-ok)
18392 (progn (backward-char 1) (org-invisible-p)))
18393 (if (< l level) (setq arg 1)))
18394 (setq arg (1- arg)))
18395 (beginning-of-line 1)))
18397 (defun org-backward-same-level (arg &optional invisible-ok)
18398 "Move backward to the arg'th subheading at same level as this one.
18399 Stop at the first and last subheadings of a superior heading."
18400 (interactive "p")
18401 (org-back-to-heading)
18402 (org-on-heading-p)
18403 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18404 (re (format "^\\*\\{1,%d\\} " level))
18406 (while (> arg 0)
18407 (while (and (re-search-backward re nil 'move)
18408 (setq l (- (match-end 0) (match-beginning 0) 1))
18409 (= l level)
18410 (not invisible-ok)
18411 (org-invisible-p))
18412 (if (< l level) (setq arg 1)))
18413 (setq arg (1- arg)))))
18415 (defun org-show-subtree ()
18416 "Show everything after this heading at deeper levels."
18417 (outline-flag-region
18418 (point)
18419 (save-excursion
18420 (org-end-of-subtree t t))
18421 nil))
18423 (defun org-show-entry ()
18424 "Show the body directly following this heading.
18425 Show the heading too, if it is currently invisible."
18426 (interactive)
18427 (save-excursion
18428 (condition-case nil
18429 (progn
18430 (org-back-to-heading t)
18431 (outline-flag-region
18432 (max (point-min) (1- (point)))
18433 (save-excursion
18434 (if (re-search-forward
18435 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
18436 (match-beginning 1)
18437 (point-max)))
18438 nil)
18439 (org-cycle-hide-drawers 'children))
18440 (error nil))))
18442 (defun org-make-options-regexp (kwds &optional extra)
18443 "Make a regular expression for keyword lines."
18444 (concat
18446 "#?[ \t]*\\+\\("
18447 (mapconcat 'regexp-quote kwds "\\|")
18448 (if extra (concat "\\|" extra))
18449 "\\):[ \t]*"
18450 "\\(.*\\)"))
18452 ;; Make isearch reveal the necessary context
18453 (defun org-isearch-end ()
18454 "Reveal context after isearch exits."
18455 (when isearch-success ; only if search was successful
18456 (if (featurep 'xemacs)
18457 ;; Under XEmacs, the hook is run in the correct place,
18458 ;; we directly show the context.
18459 (org-show-context 'isearch)
18460 ;; In Emacs the hook runs *before* restoring the overlays.
18461 ;; So we have to use a one-time post-command-hook to do this.
18462 ;; (Emacs 22 has a special variable, see function `org-mode')
18463 (unless (and (boundp 'isearch-mode-end-hook-quit)
18464 isearch-mode-end-hook-quit)
18465 ;; Only when the isearch was not quitted.
18466 (org-add-hook 'post-command-hook 'org-isearch-post-command
18467 'append 'local)))))
18469 (defun org-isearch-post-command ()
18470 "Remove self from hook, and show context."
18471 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
18472 (org-show-context 'isearch))
18475 ;;;; Integration with and fixes for other packages
18477 ;;; Imenu support
18479 (defvar org-imenu-markers nil
18480 "All markers currently used by Imenu.")
18481 (make-variable-buffer-local 'org-imenu-markers)
18483 (defun org-imenu-new-marker (&optional pos)
18484 "Return a new marker for use by Imenu, and remember the marker."
18485 (let ((m (make-marker)))
18486 (move-marker m (or pos (point)))
18487 (push m org-imenu-markers)
18490 (defun org-imenu-get-tree ()
18491 "Produce the index for Imenu."
18492 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
18493 (setq org-imenu-markers nil)
18494 (let* ((n org-imenu-depth)
18495 (re (concat "^" outline-regexp))
18496 (subs (make-vector (1+ n) nil))
18497 (last-level 0)
18498 m level head)
18499 (save-excursion
18500 (save-restriction
18501 (widen)
18502 (goto-char (point-max))
18503 (while (re-search-backward re nil t)
18504 (setq level (org-reduced-level (funcall outline-level)))
18505 (when (<= level n)
18506 (looking-at org-complex-heading-regexp)
18507 (setq head (org-link-display-format
18508 (org-match-string-no-properties 4))
18509 m (org-imenu-new-marker))
18510 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
18511 (if (>= level last-level)
18512 (push (cons head m) (aref subs level))
18513 (push (cons head (aref subs (1+ level))) (aref subs level))
18514 (loop for i from (1+ level) to n do (aset subs i nil)))
18515 (setq last-level level)))))
18516 (aref subs 1)))
18518 (eval-after-load "imenu"
18519 '(progn
18520 (add-hook 'imenu-after-jump-hook
18521 (lambda ()
18522 (if (eq major-mode 'org-mode)
18523 (org-show-context 'org-goto))))))
18525 (defun org-link-display-format (link)
18526 "Replace a link with either the description, or the link target
18527 if no description is present"
18528 (save-match-data
18529 (if (string-match org-bracket-link-analytic-regexp link)
18530 (replace-match (if (match-end 5)
18531 (match-string 5 link)
18532 (concat (match-string 1 link)
18533 (match-string 3 link)))
18534 nil t link)
18535 link)))
18537 ;; Speedbar support
18539 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
18540 "Overlay marking the agenda restriction line in speedbar.")
18541 (overlay-put org-speedbar-restriction-lock-overlay
18542 'face 'org-agenda-restriction-lock)
18543 (overlay-put org-speedbar-restriction-lock-overlay
18544 'help-echo "Agendas are currently limited to this item.")
18545 (org-detach-overlay org-speedbar-restriction-lock-overlay)
18547 (defun org-speedbar-set-agenda-restriction ()
18548 "Restrict future agenda commands to the location at point in speedbar.
18549 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
18550 (interactive)
18551 (require 'org-agenda)
18552 (let (p m tp np dir txt)
18553 (cond
18554 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18555 'org-imenu t))
18556 (setq m (get-text-property p 'org-imenu-marker))
18557 (with-current-buffer (marker-buffer m)
18558 (goto-char m)
18559 (org-agenda-set-restriction-lock 'subtree)))
18560 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18561 'speedbar-function 'speedbar-find-file))
18562 (setq tp (previous-single-property-change
18563 (1+ p) 'speedbar-function)
18564 np (next-single-property-change
18565 tp 'speedbar-function)
18566 dir (speedbar-line-directory)
18567 txt (buffer-substring-no-properties (or tp (point-min))
18568 (or np (point-max))))
18569 (with-current-buffer (find-file-noselect
18570 (let ((default-directory dir))
18571 (expand-file-name txt)))
18572 (unless (org-mode-p)
18573 (error "Cannot restrict to non-Org-mode file"))
18574 (org-agenda-set-restriction-lock 'file)))
18575 (t (error "Don't know how to restrict Org-mode's agenda")))
18576 (move-overlay org-speedbar-restriction-lock-overlay
18577 (point-at-bol) (point-at-eol))
18578 (setq current-prefix-arg nil)
18579 (org-agenda-maybe-redo)))
18581 (eval-after-load "speedbar"
18582 '(progn
18583 (speedbar-add-supported-extension ".org")
18584 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
18585 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
18586 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
18587 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18588 (add-hook 'speedbar-visiting-tag-hook
18589 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
18592 ;;; Fixes and Hacks for problems with other packages
18594 ;; Make flyspell not check words in links, to not mess up our keymap
18595 (defun org-mode-flyspell-verify ()
18596 "Don't let flyspell put overlays at active buttons."
18597 (and (not (get-text-property (point) 'keymap))
18598 (not (get-text-property (point) 'org-no-flyspell))))
18600 (defun org-remove-flyspell-overlays-in (beg end)
18601 "Remove flyspell overlays in region."
18602 (and (org-bound-and-true-p flyspell-mode)
18603 (fboundp 'flyspell-delete-region-overlays)
18604 (flyspell-delete-region-overlays beg end))
18605 (add-text-properties beg end '(org-no-flyspell t)))
18607 ;; Make `bookmark-jump' shows the jump location if it was hidden.
18608 (eval-after-load "bookmark"
18609 '(if (boundp 'bookmark-after-jump-hook)
18610 ;; We can use the hook
18611 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
18612 ;; Hook not available, use advice
18613 (defadvice bookmark-jump (after org-make-visible activate)
18614 "Make the position visible."
18615 (org-bookmark-jump-unhide))))
18617 ;; Make sure saveplace shows the location if it was hidden
18618 (eval-after-load "saveplace"
18619 '(defadvice save-place-find-file-hook (after org-make-visible activate)
18620 "Make the position visible."
18621 (org-bookmark-jump-unhide)))
18623 ;; Make sure ecb shows the location if it was hidden
18624 (eval-after-load "ecb"
18625 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
18626 "Make hierarchy visible when jumping into location from ECB tree buffer."
18627 (if (eq major-mode 'org-mode)
18628 (org-show-context))))
18630 (defun org-bookmark-jump-unhide ()
18631 "Unhide the current position, to show the bookmark location."
18632 (and (org-mode-p)
18633 (or (org-invisible-p)
18634 (save-excursion (goto-char (max (point-min) (1- (point))))
18635 (org-invisible-p)))
18636 (org-show-context 'bookmark-jump)))
18638 ;; Make session.el ignore our circular variable
18639 (eval-after-load "session"
18640 '(add-to-list 'session-globals-exclude 'org-mark-ring))
18642 ;;;; Experimental code
18644 (defun org-closed-in-range ()
18645 "Sparse tree of items closed in a certain time range.
18646 Still experimental, may disappear in the future."
18647 (interactive)
18648 ;; Get the time interval from the user.
18649 (let* ((time1 (org-float-time
18650 (org-read-date nil 'to-time nil "Starting date: ")))
18651 (time2 (org-float-time
18652 (org-read-date nil 'to-time nil "End date:")))
18653 ;; callback function
18654 (callback (lambda ()
18655 (let ((time
18656 (org-float-time
18657 (apply 'encode-time
18658 (org-parse-time-string
18659 (match-string 1))))))
18660 ;; check if time in interval
18661 (and (>= time time1) (<= time time2))))))
18662 ;; make tree, check each match with the callback
18663 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
18665 ;;;; Finish up
18667 (provide 'org)
18669 (run-hooks 'org-load-hook)
18671 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
18673 ;;; org.el ends here