Implement new and better support for entities
[org-mode.git] / lisp / org.el
blob988dab116d6f877217e4202cf3e46f9dcaa8a0a6
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.34trans
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum)
76 (require 'calendar))
77 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
78 ;; the file noutline.el being loaded.
79 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
80 ;; We require noutline, which might be provided in outline.el
81 (require 'outline) (require 'noutline)
82 ;; Other stuff we need.
83 (require 'time-date)
84 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
85 (require 'easymenu)
87 (require 'org-macs)
88 (require 'org-entities)
89 (require 'org-compat)
90 (require 'org-faces)
91 (require 'org-list)
92 (require 'org-src)
93 (require 'org-footnote)
95 ;;;; Customization variables
97 ;;; Version
99 (defconst org-version "6.34trans"
100 "The version number of the file org.el.")
102 (defun org-version (&optional here)
103 "Show the org-mode version in the echo area.
104 With prefix arg HERE, insert it at point."
105 (interactive "P")
106 (let* ((origin default-directory)
107 (version org-version)
108 (git-version)
109 (dir (concat (file-name-directory (locate-library "org")) "../" )))
110 (when (and (file-exists-p (expand-file-name ".git" dir))
111 (executable-find "git"))
112 (unwind-protect
113 (progn
114 (cd dir)
115 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
116 (with-current-buffer "*Shell Command Output*"
117 (goto-char (point-min))
118 (setq git-version (buffer-substring (point) (point-at-eol))))
119 (subst-char-in-string ?- ?. git-version t)
120 (when (string-match "\\S-"
121 (shell-command-to-string
122 "git diff-index --name-only HEAD --"))
123 (setq git-version (concat git-version ".dirty")))
124 (setq version (concat version " (" git-version ")"))))
125 (cd origin)))
126 (setq version (format "Org-mode version %s" version))
127 (if here (insert version))
128 (message version)))
130 ;;; Compatibility constants
132 ;;; The custom variables
134 (defgroup org nil
135 "Outline-based notes management and organizer."
136 :tag "Org"
137 :group 'outlines
138 :group 'calendar)
140 (defcustom org-mode-hook nil
141 "Mode hook for Org-mode, run after the mode was turned on."
142 :group 'org
143 :type 'hook)
145 (defcustom org-load-hook nil
146 "Hook that is run after org.el has been loaded."
147 :group 'org
148 :type 'hook)
150 (defvar org-modules) ; defined below
151 (defvar org-modules-loaded nil
152 "Have the modules been loaded already?")
154 (defun org-load-modules-maybe (&optional force)
155 "Load all extensions listed in `org-modules'."
156 (when (or force (not org-modules-loaded))
157 (mapc (lambda (ext)
158 (condition-case nil (require ext)
159 (error (message "Problems while trying to load feature `%s'" ext))))
160 org-modules)
161 (setq org-modules-loaded t)))
163 (defun org-set-modules (var value)
164 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
165 (set var value)
166 (when (featurep 'org)
167 (org-load-modules-maybe 'force)))
169 (when (org-bound-and-true-p org-modules)
170 (let ((a (member 'org-infojs org-modules)))
171 (and a (setcar a 'org-jsinfo))))
173 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
174 "Modules that should always be loaded together with org.el.
175 If a description starts with <C>, the file is not part of Emacs
176 and loading it will require that you have downloaded and properly installed
177 the org-mode distribution.
179 You can also use this system to load external packages (i.e. neither Org
180 core modules, nor modules from the CONTRIB directory). Just add symbols
181 to the end of the list. If the package is called org-xyz.el, then you need
182 to add the symbol `xyz', and the package must have a call to
184 (provide 'org-xyz)"
185 :group 'org
186 :set 'org-set-modules
187 :type
188 '(set :greedy t
189 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
190 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
191 (const :tag " crypt: Encryption of subtrees" org-crypt)
192 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
193 (const :tag " docview: Links to doc-view buffers" org-docview)
194 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
195 (const :tag " id: Global IDs for identifying entries" org-id)
196 (const :tag " info: Links to Info nodes" org-info)
197 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
198 (const :tag " habit: Track your consistency with habits" org-habit)
199 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
200 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
201 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
202 (const :tag " mew Links to Mew folders/messages" org-mew)
203 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
204 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
205 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
206 (const :tag " vm: Links to VM folders/messages" org-vm)
207 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
208 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
209 (const :tag " mouse: Additional mouse support" org-mouse)
211 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
212 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
213 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
214 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
215 (const :tag "C collector: Collect properties into tables" org-collector)
216 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
217 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
218 (const :tag "C eval: Include command output as text" org-eval)
219 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
220 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
221 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
222 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
223 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
225 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
227 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
228 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
229 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
230 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
231 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
232 (const :tag "C mtags: Support for muse-like tags" org-mtags)
233 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
234 (const :tag "C registry: A registry for Org-mode links" org-registry)
235 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
236 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
237 (const :tag "C secretary: Team management with org-mode" org-secretary)
238 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
239 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
240 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
241 (const :tag "C track: Keep up with Org-mode development" org-track)
242 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
244 (defcustom org-support-shift-select nil
245 "Non-nil means make shift-cursor commands select text when possible.
247 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
248 selecting a region, or enlarge thusly regions started in this way.
249 In Org-mode, in special contexts, these same keys are used for other
250 purposes, important enough to compete with shift selection. Org tries
251 to balance these needs by supporting `shift-select-mode' outside these
252 special contexts, under control of this variable.
254 The default of this variable is nil, to avoid confusing behavior. Shifted
255 cursor keys will then execute Org commands in the following contexts:
256 - on a headline, changing TODO state (left/right) and priority (up/down)
257 - on a time stamp, changing the time
258 - in a plain list item, changing the bullet type
259 - in a property definition line, switching between allowed values
260 - in the BEGIN line of a clock table (changing the time block).
261 Outside these contexts, the commands will throw an error.
263 When this variable is t and the cursor is not in a special context,
264 Org-mode will support shift-selection for making and enlarging regions.
265 To make this more effective, the bullet cycling will no longer happen
266 anywhere in an item line, but only if the cursor is exactly on the bullet.
268 If you set this variable to the symbol `always', then the keys
269 will not be special in headlines, property lines, and item lines, to make
270 shift selection work there as well. If this is what you want, you can
271 use the following alternative commands: `C-c C-t' and `C-c ,' to
272 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
273 TODO sets, `C-c -' to cycle item bullet types, and properties can be
274 edited by hand or in column view.
276 However, when the cursor is on a timestamp, shift-cursor commands
277 will still edit the time stamp - this is just too good to give up.
279 XEmacs user should have this variable set to nil, because shift-select-mode
280 is Emacs 23 only."
281 :group 'org
282 :type '(choice
283 (const :tag "Never" nil)
284 (const :tag "When outside special context" t)
285 (const :tag "Everywhere except timestamps" always)))
287 (defgroup org-startup nil
288 "Options concerning startup of Org-mode."
289 :tag "Org Startup"
290 :group 'org)
292 (defcustom org-startup-folded t
293 "Non-nil means entering Org-mode will switch to OVERVIEW.
294 This can also be configured on a per-file basis by adding one of
295 the following lines anywhere in the buffer:
297 #+STARTUP: fold (or `overview', this is equivalent)
298 #+STARTUP: nofold (or `showall', this is equivalent)
299 #+STARTUP: content
300 #+STARTUP: showeverything"
301 :group 'org-startup
302 :type '(choice
303 (const :tag "nofold: show all" nil)
304 (const :tag "fold: overview" t)
305 (const :tag "content: all headlines" content)
306 (const :tag "show everything, even drawers" showeverything)))
308 (defcustom org-startup-truncated t
309 "Non-nil means entering Org-mode will set `truncate-lines'.
310 This is useful since some lines containing links can be very long and
311 uninteresting. Also tables look terrible when wrapped."
312 :group 'org-startup
313 :type 'boolean)
315 (defcustom org-startup-indented nil
316 "Non-nil means turn on `org-indent-mode' on startup.
317 This can also be configured on a per-file basis by adding one of
318 the following lines anywhere in the buffer:
320 #+STARTUP: indent
321 #+STARTUP: noindent"
322 :group 'org-structure
323 :type '(choice
324 (const :tag "Not" nil)
325 (const :tag "Globally (slow on startup in large files)" t)))
327 (defcustom org-startup-with-beamer-mode nil
328 "Non-nil means turn on `org-beamer-mode' on startup.
329 This can also be configured on a per-file basis by adding one of
330 the following lines anywhere in the buffer:
332 #+STARTUP: beamer"
333 :group 'org-startup
334 :type 'boolean)
336 (defcustom org-startup-align-all-tables nil
337 "Non-nil means align all tables when visiting a file.
338 This is useful when the column width in tables is forced with <N> cookies
339 in table fields. Such tables will look correct only after the first re-align.
340 This can also be configured on a per-file basis by adding one of
341 the following lines anywhere in the buffer:
342 #+STARTUP: align
343 #+STARTUP: noalign"
344 :group 'org-startup
345 :type 'boolean)
347 (defcustom org-insert-mode-line-in-empty-file nil
348 "Non-nil means insert the first line setting Org-mode in empty files.
349 When the function `org-mode' is called interactively in an empty file, this
350 normally means that the file name does not automatically trigger Org-mode.
351 To ensure that the file will always be in Org-mode in the future, a
352 line enforcing Org-mode will be inserted into the buffer, if this option
353 has been set."
354 :group 'org-startup
355 :type 'boolean)
357 (defcustom org-replace-disputed-keys nil
358 "Non-nil means use alternative key bindings for some keys.
359 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
360 These keys are also used by other packages like shift-selection-mode'
361 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
362 If you want to use Org-mode together with one of these other modes,
363 or more generally if you would like to move some Org-mode commands to
364 other keys, set this variable and configure the keys with the variable
365 `org-disputed-keys'.
367 This option is only relevant at load-time of Org-mode, and must be set
368 *before* org.el is loaded. Changing it requires a restart of Emacs to
369 become effective."
370 :group 'org-startup
371 :type 'boolean)
373 (defcustom org-use-extra-keys nil
374 "Non-nil means use extra key sequence definitions for certain
375 commands. This happens automatically if you run XEmacs or if
376 window-system is nil. This variable lets you do the same
377 manually. You must set it before loading org.
379 Example: on Carbon Emacs 22 running graphically, with an external
380 keyboard on a Powerbook, the default way of setting M-left might
381 not work for either Alt or ESC. Setting this variable will make
382 it work for ESC."
383 :group 'org-startup
384 :type 'boolean)
386 (if (fboundp 'defvaralias)
387 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
389 (defcustom org-disputed-keys
390 '(([(shift up)] . [(meta p)])
391 ([(shift down)] . [(meta n)])
392 ([(shift left)] . [(meta -)])
393 ([(shift right)] . [(meta +)])
394 ([(control shift right)] . [(meta shift +)])
395 ([(control shift left)] . [(meta shift -)]))
396 "Keys for which Org-mode and other modes compete.
397 This is an alist, cars are the default keys, second element specifies
398 the alternative to use when `org-replace-disputed-keys' is t.
400 Keys can be specified in any syntax supported by `define-key'.
401 The value of this option takes effect only at Org-mode's startup,
402 therefore you'll have to restart Emacs to apply it after changing."
403 :group 'org-startup
404 :type 'alist)
406 (defun org-key (key)
407 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
408 Or return the original if not disputed."
409 (if org-replace-disputed-keys
410 (let* ((nkey (key-description key))
411 (x (org-find-if (lambda (x)
412 (equal (key-description (car x)) nkey))
413 org-disputed-keys)))
414 (if x (cdr x) key))
415 key))
417 (defun org-find-if (predicate seq)
418 (catch 'exit
419 (while seq
420 (if (funcall predicate (car seq))
421 (throw 'exit (car seq))
422 (pop seq)))))
424 (defun org-defkey (keymap key def)
425 "Define a key, possibly translated, as returned by `org-key'."
426 (define-key keymap (org-key key) def))
428 (defcustom org-ellipsis nil
429 "The ellipsis to use in the Org-mode outline.
430 When nil, just use the standard three dots. When a string, use that instead,
431 When a face, use the standard 3 dots, but with the specified face.
432 The change affects only Org-mode (which will then use its own display table).
433 Changing this requires executing `M-x org-mode' in a buffer to become
434 effective."
435 :group 'org-startup
436 :type '(choice (const :tag "Default" nil)
437 (face :tag "Face" :value org-warning)
438 (string :tag "String" :value "...#")))
440 (defvar org-display-table nil
441 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
443 (defgroup org-keywords nil
444 "Keywords in Org-mode."
445 :tag "Org Keywords"
446 :group 'org)
448 (defcustom org-deadline-string "DEADLINE:"
449 "String to mark deadline entries.
450 A deadline is this string, followed by a time stamp. Should be a word,
451 terminated by a colon. You can insert a schedule keyword and
452 a timestamp with \\[org-deadline].
453 Changes become only effective after restarting Emacs."
454 :group 'org-keywords
455 :type 'string)
457 (defcustom org-scheduled-string "SCHEDULED:"
458 "String to mark scheduled TODO entries.
459 A schedule is this string, followed by a time stamp. Should be a word,
460 terminated by a colon. You can insert a schedule keyword and
461 a timestamp with \\[org-schedule].
462 Changes become only effective after restarting Emacs."
463 :group 'org-keywords
464 :type 'string)
466 (defcustom org-closed-string "CLOSED:"
467 "String used as the prefix for timestamps logging closing a TODO entry."
468 :group 'org-keywords
469 :type 'string)
471 (defcustom org-clock-string "CLOCK:"
472 "String used as prefix for timestamps clocking work hours on an item."
473 :group 'org-keywords
474 :type 'string)
476 (defcustom org-comment-string "COMMENT"
477 "Entries starting with this keyword will never be exported.
478 An entry can be toggled between COMMENT and normal with
479 \\[org-toggle-comment].
480 Changes become only effective after restarting Emacs."
481 :group 'org-keywords
482 :type 'string)
484 (defcustom org-quote-string "QUOTE"
485 "Entries starting with this keyword will be exported in fixed-width font.
486 Quoting applies only to the text in the entry following the headline, and does
487 not extend beyond the next headline, even if that is lower level.
488 An entry can be toggled between QUOTE and normal with
489 \\[org-toggle-fixed-width-section]."
490 :group 'org-keywords
491 :type 'string)
493 (defconst org-repeat-re
494 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
495 "Regular expression for specifying repeated events.
496 After a match, group 1 contains the repeat expression.")
498 (defgroup org-structure nil
499 "Options concerning the general structure of Org-mode files."
500 :tag "Org Structure"
501 :group 'org)
503 (defgroup org-reveal-location nil
504 "Options about how to make context of a location visible."
505 :tag "Org Reveal Location"
506 :group 'org-structure)
508 (defconst org-context-choice
509 '(choice
510 (const :tag "Always" t)
511 (const :tag "Never" nil)
512 (repeat :greedy t :tag "Individual contexts"
513 (cons
514 (choice :tag "Context"
515 (const agenda)
516 (const org-goto)
517 (const occur-tree)
518 (const tags-tree)
519 (const link-search)
520 (const mark-goto)
521 (const bookmark-jump)
522 (const isearch)
523 (const default))
524 (boolean))))
525 "Contexts for the reveal options.")
527 (defcustom org-show-hierarchy-above '((default . t))
528 "Non-nil means show full hierarchy when revealing a location.
529 Org-mode often shows locations in an org-mode file which might have
530 been invisible before. When this is set, the hierarchy of headings
531 above the exposed location is shown.
532 Turning this off for example for sparse trees makes them very compact.
533 Instead of t, this can also be an alist specifying this option for different
534 contexts. Valid contexts are
535 agenda when exposing an entry from the agenda
536 org-goto when using the command `org-goto' on key C-c C-j
537 occur-tree when using the command `org-occur' on key C-c /
538 tags-tree when constructing a sparse tree based on tags matches
539 link-search when exposing search matches associated with a link
540 mark-goto when exposing the jump goal of a mark
541 bookmark-jump when exposing a bookmark location
542 isearch when exiting from an incremental search
543 default default for all contexts not set explicitly"
544 :group 'org-reveal-location
545 :type org-context-choice)
547 (defcustom org-show-following-heading '((default . nil))
548 "Non-nil means show following heading when revealing a location.
549 Org-mode often shows locations in an org-mode file which might have
550 been invisible before. When this is set, the heading following the
551 match is shown.
552 Turning this off for example for sparse trees makes them very compact,
553 but makes it harder to edit the location of the match. In such a case,
554 use the command \\[org-reveal] to show more context.
555 Instead of t, this can also be an alist specifying this option for different
556 contexts. See `org-show-hierarchy-above' for valid contexts."
557 :group 'org-reveal-location
558 :type org-context-choice)
560 (defcustom org-show-siblings '((default . nil) (isearch t))
561 "Non-nil means show all sibling heading when revealing a location.
562 Org-mode often shows locations in an org-mode file which might have
563 been invisible before. When this is set, the sibling of the current entry
564 heading are all made visible. If `org-show-hierarchy-above' is t,
565 the same happens on each level of the hierarchy above the current entry.
567 By default this is on for the isearch context, off for all other contexts.
568 Turning this off for example for sparse trees makes them very compact,
569 but makes it harder to edit the location of the match. In such a case,
570 use the command \\[org-reveal] to show more context.
571 Instead of t, this can also be an alist specifying this option for different
572 contexts. See `org-show-hierarchy-above' for valid contexts."
573 :group 'org-reveal-location
574 :type org-context-choice)
576 (defcustom org-show-entry-below '((default . nil))
577 "Non-nil means show the entry below a headline when revealing a location.
578 Org-mode often shows locations in an org-mode file which might have
579 been invisible before. When this is set, the text below the headline that is
580 exposed is also shown.
582 By default this is off for all contexts.
583 Instead of t, this can also be an alist specifying this option for different
584 contexts. See `org-show-hierarchy-above' for valid contexts."
585 :group 'org-reveal-location
586 :type org-context-choice)
588 (defcustom org-indirect-buffer-display 'other-window
589 "How should indirect tree buffers be displayed?
590 This applies to indirect buffers created with the commands
591 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
592 Valid values are:
593 current-window Display in the current window
594 other-window Just display in another window.
595 dedicated-frame Create one new frame, and re-use it each time.
596 new-frame Make a new frame each time. Note that in this case
597 previously-made indirect buffers are kept, and you need to
598 kill these buffers yourself."
599 :group 'org-structure
600 :group 'org-agenda-windows
601 :type '(choice
602 (const :tag "In current window" current-window)
603 (const :tag "In current frame, other window" other-window)
604 (const :tag "Each time a new frame" new-frame)
605 (const :tag "One dedicated frame" dedicated-frame)))
607 (defcustom org-use-speed-commands nil
608 "Non-nil means activate single letter commands at beginning of a headline.
609 This may also be a function to test for appropriate locations where speed
610 commands should be active."
611 :group 'org-structure
612 :type '(choice
613 (const :tag "Never" nil)
614 (const :tag "At beginning of headline stars" t)
615 (function)))
617 (defcustom org-speed-commands-user nil
618 "Alist of additional speed commands.
619 This list will be checked before `org-speed-commands-default'
620 when the variable `org-use-speed-commands' is non-nil
621 and when the cursor is at the beginning of a headline.
622 The car if each entry is a string with a single letter, which must
623 be assigned to `self-insert-command' in the global map.
624 The cdr is either a command to be called interactively, a function
625 to be called, or a form to be evaluated.
626 An entry that is just a list with a single string will be interpreted
627 as a descriptive headline that will be added when listing the speed
628 copmmands in the Help buffer using the `?' speed command."
629 :group 'org-structure
630 :type '(repeat :value ("k" . ignore)
631 (choice :value ("k" . ignore)
632 (list :tag "Descriptive Headline" (string :tag "Headline"))
633 (cons :tag "Letter and Command"
634 (string :tag "Command letter")
635 (choice
636 (function)
637 (sexp))))))
639 (defgroup org-cycle nil
640 "Options concerning visibility cycling in Org-mode."
641 :tag "Org Cycle"
642 :group 'org-structure)
644 (defcustom org-cycle-skip-children-state-if-no-children t
645 "Non-nil means skip CHILDREN state in entries that don't have any."
646 :group 'org-cycle
647 :type 'boolean)
649 (defcustom org-cycle-max-level nil
650 "Maximum level which should still be subject to visibility cycling.
651 Levels higher than this will, for cycling, be treated as text, not a headline.
652 When `org-odd-levels-only' is set, a value of N in this variable actually
653 means 2N-1 stars as the limiting headline.
654 When nil, cycle all levels.
655 Note that the limiting level of cycling is also influenced by
656 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
657 `org-inlinetask-min-level' is, cycling will be limited to levels one less
658 than its value."
659 :group 'org-cycle
660 :type '(choice
661 (const :tag "No limit" nil)
662 (integer :tag "Maximum level")))
664 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
665 "Names of drawers. Drawers are not opened by cycling on the headline above.
666 Drawers only open with a TAB on the drawer line itself. A drawer looks like
667 this:
668 :DRAWERNAME:
669 .....
670 :END:
671 The drawer \"PROPERTIES\" is special for capturing properties through
672 the property API.
674 Drawers can be defined on the per-file basis with a line like:
676 #+DRAWERS: HIDDEN STATE PROPERTIES"
677 :group 'org-structure
678 :group 'org-cycle
679 :type '(repeat (string :tag "Drawer Name")))
681 (defcustom org-hide-block-startup nil
682 "Non-nil means entering Org-mode will fold all blocks.
683 This can also be set in on a per-file basis with
685 #+STARTUP: hideblocks
686 #+STARTUP: showblocks"
687 :group 'org-startup
688 :group 'org-cycle
689 :type 'boolean)
691 (defcustom org-cycle-global-at-bob nil
692 "Cycle globally if cursor is at beginning of buffer and not at a headline.
693 This makes it possible to do global cycling without having to use S-TAB or
694 C-u TAB. For this special case to work, the first line of the buffer
695 must not be a headline - it may be empty or some other text. When used in
696 this way, `org-cycle-hook' is disables temporarily, to make sure the
697 cursor stays at the beginning of the buffer.
698 When this option is nil, don't do anything special at the beginning
699 of the buffer."
700 :group 'org-cycle
701 :type 'boolean)
703 (defcustom org-cycle-level-after-item/entry-creation t
704 "Non-nil means cycle entry level or item indentation in new empty entries.
706 When the cursor is at the end of an empty headline, i.e with only stars
707 and maybe a TODO keyword, TAB will then switch the entry to become a child,
708 and then all possible anchestor states, before returning to the original state.
709 This makes data entry extremely fast: M-RET to create a new headline,
710 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
712 When the cursor is at the end of an empty plain list item, one TAB will
713 make it a subitem, two or more tabs will back up to make this an item
714 higher up in the item hierarchy."
715 :group 'org-cycle
716 :type 'boolean)
718 (defcustom org-cycle-emulate-tab t
719 "Where should `org-cycle' emulate TAB.
720 nil Never
721 white Only in completely white lines
722 whitestart Only at the beginning of lines, before the first non-white char
723 t Everywhere except in headlines
724 exc-hl-bol Everywhere except at the start of a headline
725 If TAB is used in a place where it does not emulate TAB, the current subtree
726 visibility is cycled."
727 :group 'org-cycle
728 :type '(choice (const :tag "Never" nil)
729 (const :tag "Only in completely white lines" white)
730 (const :tag "Before first char in a line" whitestart)
731 (const :tag "Everywhere except in headlines" t)
732 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
735 (defcustom org-cycle-separator-lines 2
736 "Number of empty lines needed to keep an empty line between collapsed trees.
737 If you leave an empty line between the end of a subtree and the following
738 headline, this empty line is hidden when the subtree is folded.
739 Org-mode will leave (exactly) one empty line visible if the number of
740 empty lines is equal or larger to the number given in this variable.
741 So the default 2 means at least 2 empty lines after the end of a subtree
742 are needed to produce free space between a collapsed subtree and the
743 following headline.
745 If the number is negative, and the number of empty lines is at least -N,
746 all empty lines are shown.
748 Special case: when 0, never leave empty lines in collapsed view."
749 :group 'org-cycle
750 :type 'integer)
751 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
753 (defcustom org-pre-cycle-hook nil
754 "Hook that is run before visibility cycling is happening.
755 The function(s) in this hook must accept a single argument which indicates
756 the new state that will be set right after running this hook. The
757 argument is a symbol. Before a global state change, it can have the values
758 `overview', `content', or `all'. Before a local state change, it can have
759 the values `folded', `children', or `subtree'."
760 :group 'org-cycle
761 :type 'hook)
763 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
764 org-cycle-hide-drawers
765 org-cycle-show-empty-lines
766 org-optimize-window-after-visibility-change)
767 "Hook that is run after `org-cycle' has changed the buffer visibility.
768 The function(s) in this hook must accept a single argument which indicates
769 the new state that was set by the most recent `org-cycle' command. The
770 argument is a symbol. After a global state change, it can have the values
771 `overview', `content', or `all'. After a local state change, it can have
772 the values `folded', `children', or `subtree'."
773 :group 'org-cycle
774 :type 'hook)
776 (defgroup org-edit-structure nil
777 "Options concerning structure editing in Org-mode."
778 :tag "Org Edit Structure"
779 :group 'org-structure)
781 (defcustom org-odd-levels-only nil
782 "Non-nil means skip even levels and only use odd levels for the outline.
783 This has the effect that two stars are being added/taken away in
784 promotion/demotion commands. It also influences how levels are
785 handled by the exporters.
786 Changing it requires restart of `font-lock-mode' to become effective
787 for fontification also in regions already fontified.
788 You may also set this on a per-file basis by adding one of the following
789 lines to the buffer:
791 #+STARTUP: odd
792 #+STARTUP: oddeven"
793 :group 'org-edit-structure
794 :group 'org-appearance
795 :type 'boolean)
797 (defcustom org-adapt-indentation t
798 "Non-nil means adapt indentation to outline node level.
800 When this variable is set, Org assumes that you write outlines by
801 indenting text in each node to align with the headline (after the stars).
802 The following issues are influenced by this variable:
804 - When this is set and the *entire* text in an entry is indented, the
805 indentation is increased by one space in a demotion command, and
806 decreased by one in a promotion command. If any line in the entry
807 body starts with text at column 0, indentation is not changed at all.
809 - Property drawers and planning information is inserted indented when
810 this variable s set. When nil, they will not be indented.
812 - TAB indents a line relative to context. The lines below a headline
813 will be indented when this variable is set.
815 Note that this is all about true indentation, by adding and removing
816 space characters. See also `org-indent.el' which does level-dependent
817 indentation in a virtual way, i.e. at display time in Emacs."
818 :group 'org-edit-structure
819 :type 'boolean)
821 (defcustom org-special-ctrl-a/e nil
822 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
824 When t, `C-a' will bring back the cursor to the beginning of the
825 headline text, i.e. after the stars and after a possible TODO keyword.
826 In an item, this will be the position after the bullet.
827 When the cursor is already at that position, another `C-a' will bring
828 it to the beginning of the line.
830 `C-e' will jump to the end of the headline, ignoring the presence of tags
831 in the headline. A second `C-e' will then jump to the true end of the
832 line, after any tags. This also means that, when this variable is
833 non-nil, `C-e' also will never jump beyond the end of the heading of a
834 folded section, i.e. not after the ellipses.
836 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
837 going to the true line boundary first. Only a directly following, identical
838 keypress will bring the cursor to the special positions.
840 This may also be a cons cell where the behavior for `C-a' and `C-e' is
841 set separately."
842 :group 'org-edit-structure
843 :type '(choice
844 (const :tag "off" nil)
845 (const :tag "on: after stars/bullet and before tags first" t)
846 (const :tag "reversed: true line boundary first" reversed)
847 (cons :tag "Set C-a and C-e separately"
848 (choice :tag "Special C-a"
849 (const :tag "off" nil)
850 (const :tag "on: after stars/bullet first" t)
851 (const :tag "reversed: before stars/bullet first" reversed))
852 (choice :tag "Special C-e"
853 (const :tag "off" nil)
854 (const :tag "on: before tags first" t)
855 (const :tag "reversed: after tags first" reversed)))))
856 (if (fboundp 'defvaralias)
857 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
859 (defcustom org-special-ctrl-k nil
860 "Non-nil means `C-k' will behave specially in headlines.
861 When nil, `C-k' will call the default `kill-line' command.
862 When t, the following will happen while the cursor is in the headline:
864 - When the cursor is at the beginning of a headline, kill the entire
865 line and possible the folded subtree below the line.
866 - When in the middle of the headline text, kill the headline up to the tags.
867 - When after the headline text, kill the tags."
868 :group 'org-edit-structure
869 :type 'boolean)
871 (defcustom org-yank-folded-subtrees t
872 "Non-nil means when yanking subtrees, fold them.
873 If the kill is a single subtree, or a sequence of subtrees, i.e. if
874 it starts with a heading and all other headings in it are either children
875 or siblings, then fold all the subtrees. However, do this only if no
876 text after the yank would be swallowed into a folded tree by this action."
877 :group 'org-edit-structure
878 :type 'boolean)
880 (defcustom org-yank-adjusted-subtrees nil
881 "Non-nil means when yanking subtrees, adjust the level.
882 With this setting, `org-paste-subtree' is used to insert the subtree, see
883 this function for details."
884 :group 'org-edit-structure
885 :type 'boolean)
887 (defcustom org-M-RET-may-split-line '((default . t))
888 "Non-nil means M-RET will split the line at the cursor position.
889 When nil, it will go to the end of the line before making a
890 new line.
891 You may also set this option in a different way for different
892 contexts. Valid contexts are:
894 headline when creating a new headline
895 item when creating a new item
896 table in a table field
897 default the value to be used for all contexts not explicitly
898 customized"
899 :group 'org-structure
900 :group 'org-table
901 :type '(choice
902 (const :tag "Always" t)
903 (const :tag "Never" nil)
904 (repeat :greedy t :tag "Individual contexts"
905 (cons
906 (choice :tag "Context"
907 (const headline)
908 (const item)
909 (const table)
910 (const default))
911 (boolean)))))
914 (defcustom org-insert-heading-respect-content nil
915 "Non-nil means insert new headings after the current subtree.
916 When nil, the new heading is created directly after the current line.
917 The commands \\[org-insert-heading-respect-content] and
918 \\[org-insert-todo-heading-respect-content] turn this variable on
919 for the duration of the command."
920 :group 'org-structure
921 :type 'boolean)
923 (defcustom org-blank-before-new-entry '((heading . auto)
924 (plain-list-item . auto))
925 "Should `org-insert-heading' leave a blank line before new heading/item?
926 The value is an alist, with `heading' and `plain-list-item' as car,
927 and a boolean flag as cdr. For plain lists, if the variable
928 `org-empty-line-terminates-plain-lists' is set, the setting here
929 is ignored and no empty line is inserted, to keep the list in tact."
930 :group 'org-edit-structure
931 :type '(list
932 (cons (const heading)
933 (choice (const :tag "Never" nil)
934 (const :tag "Always" t)
935 (const :tag "Auto" auto)))
936 (cons (const plain-list-item)
937 (choice (const :tag "Never" nil)
938 (const :tag "Always" t)
939 (const :tag "Auto" auto)))))
941 (defcustom org-insert-heading-hook nil
942 "Hook being run after inserting a new heading."
943 :group 'org-edit-structure
944 :type 'hook)
946 (defcustom org-enable-fixed-width-editor t
947 "Non-nil means lines starting with \":\" are treated as fixed-width.
948 This currently only means they are never auto-wrapped.
949 When nil, such lines will be treated like ordinary lines.
950 See also the QUOTE keyword."
951 :group 'org-edit-structure
952 :type 'boolean)
955 (defcustom org-goto-auto-isearch t
956 "Non-nil means typing characters in org-goto starts incremental search."
957 :group 'org-edit-structure
958 :type 'boolean)
960 (defgroup org-sparse-trees nil
961 "Options concerning sparse trees in Org-mode."
962 :tag "Org Sparse Trees"
963 :group 'org-structure)
965 (defcustom org-highlight-sparse-tree-matches t
966 "Non-nil means highlight all matches that define a sparse tree.
967 The highlights will automatically disappear the next time the buffer is
968 changed by an edit command."
969 :group 'org-sparse-trees
970 :type 'boolean)
972 (defcustom org-remove-highlights-with-change t
973 "Non-nil means any change to the buffer will remove temporary highlights.
974 Such highlights are created by `org-occur' and `org-clock-display'.
975 When nil, `C-c C-c needs to be used to get rid of the highlights.
976 The highlights created by `org-preview-latex-fragment' always need
977 `C-c C-c' to be removed."
978 :group 'org-sparse-trees
979 :group 'org-time
980 :type 'boolean)
983 (defcustom org-occur-hook '(org-first-headline-recenter)
984 "Hook that is run after `org-occur' has constructed a sparse tree.
985 This can be used to recenter the window to show as much of the structure
986 as possible."
987 :group 'org-sparse-trees
988 :type 'hook)
990 (defgroup org-imenu-and-speedbar nil
991 "Options concerning imenu and speedbar in Org-mode."
992 :tag "Org Imenu and Speedbar"
993 :group 'org-structure)
995 (defcustom org-imenu-depth 2
996 "The maximum level for Imenu access to Org-mode headlines.
997 This also applied for speedbar access."
998 :group 'org-imenu-and-speedbar
999 :type 'integer)
1001 (defgroup org-table nil
1002 "Options concerning tables in Org-mode."
1003 :tag "Org Table"
1004 :group 'org)
1006 (defcustom org-enable-table-editor 'optimized
1007 "Non-nil means lines starting with \"|\" are handled by the table editor.
1008 When nil, such lines will be treated like ordinary lines.
1010 When equal to the symbol `optimized', the table editor will be optimized to
1011 do the following:
1012 - Automatic overwrite mode in front of whitespace in table fields.
1013 This makes the structure of the table stay in tact as long as the edited
1014 field does not exceed the column width.
1015 - Minimize the number of realigns. Normally, the table is aligned each time
1016 TAB or RET are pressed to move to another field. With optimization this
1017 happens only if changes to a field might have changed the column width.
1018 Optimization requires replacing the functions `self-insert-command',
1019 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1020 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1021 very good at guessing when a re-align will be necessary, but you can always
1022 force one with \\[org-ctrl-c-ctrl-c].
1024 If you would like to use the optimized version in Org-mode, but the
1025 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1027 This variable can be used to turn on and off the table editor during a session,
1028 but in order to toggle optimization, a restart is required.
1030 See also the variable `org-table-auto-blank-field'."
1031 :group 'org-table
1032 :type '(choice
1033 (const :tag "off" nil)
1034 (const :tag "on" t)
1035 (const :tag "on, optimized" optimized)))
1037 (defcustom org-self-insert-cluster-for-undo t
1038 "Non-nil means cluster self-insert commands for undo when possible.
1039 If this is set, then, like in the Emacs command loop, 20 consecutive
1040 characters will be undone together.
1041 This is configurable, because there is some impact on typing performance."
1042 :group 'org-table
1043 :type 'boolean)
1045 (defcustom org-table-tab-recognizes-table.el t
1046 "Non-nil means TAB will automatically notice a table.el table.
1047 When it sees such a table, it moves point into it and - if necessary -
1048 calls `table-recognize-table'."
1049 :group 'org-table-editing
1050 :type 'boolean)
1052 (defgroup org-link nil
1053 "Options concerning links in Org-mode."
1054 :tag "Org Link"
1055 :group 'org)
1057 (defvar org-link-abbrev-alist-local nil
1058 "Buffer-local version of `org-link-abbrev-alist', which see.
1059 The value of this is taken from the #+LINK lines.")
1060 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1062 (defcustom org-link-abbrev-alist nil
1063 "Alist of link abbreviations.
1064 The car of each element is a string, to be replaced at the start of a link.
1065 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1066 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1068 [[linkkey:tag][description]]
1070 The 'linkkey' must be a word word, starting with a letter, followed
1071 by letters, numbers, '-' or '_'.
1073 If REPLACE is a string, the tag will simply be appended to create the link.
1074 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1075 the placeholder \"%h\" will cause a url-encoded version of the tag to
1076 be inserted at that point (see the function `url-hexify-string').
1078 REPLACE may also be a function that will be called with the tag as the
1079 only argument to create the link, which should be returned as a string.
1081 See the manual for examples."
1082 :group 'org-link
1083 :type '(repeat
1084 (cons
1085 (string :tag "Protocol")
1086 (choice
1087 (string :tag "Format")
1088 (function)))))
1090 (defcustom org-descriptive-links t
1091 "Non-nil means hide link part and only show description of bracket links.
1092 Bracket links are like [[link][description]]. This variable sets the initial
1093 state in new org-mode buffers. The setting can then be toggled on a
1094 per-buffer basis from the Org->Hyperlinks menu."
1095 :group 'org-link
1096 :type 'boolean)
1098 (defcustom org-link-file-path-type 'adaptive
1099 "How the path name in file links should be stored.
1100 Valid values are:
1102 relative Relative to the current directory, i.e. the directory of the file
1103 into which the link is being inserted.
1104 absolute Absolute path, if possible with ~ for home directory.
1105 noabbrev Absolute path, no abbreviation of home directory.
1106 adaptive Use relative path for files in the current directory and sub-
1107 directories of it. For other files, use an absolute path."
1108 :group 'org-link
1109 :type '(choice
1110 (const relative)
1111 (const absolute)
1112 (const noabbrev)
1113 (const adaptive)))
1115 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1116 "Types of links that should be activated in Org-mode files.
1117 This is a list of symbols, each leading to the activation of a certain link
1118 type. In principle, it does not hurt to turn on most link types - there may
1119 be a small gain when turning off unused link types. The types are:
1121 bracket The recommended [[link][description]] or [[link]] links with hiding.
1122 angular Links in angular brackets that may contain whitespace like
1123 <bbdb:Carsten Dominik>.
1124 plain Plain links in normal text, no whitespace, like http://google.com.
1125 radio Text that is matched by a radio target, see manual for details.
1126 tag Tag settings in a headline (link to tag search).
1127 date Time stamps (link to calendar).
1128 footnote Footnote labels.
1130 Changing this variable requires a restart of Emacs to become effective."
1131 :group 'org-link
1132 :type '(set :greedy t
1133 (const :tag "Double bracket links (new style)" bracket)
1134 (const :tag "Angular bracket links (old style)" angular)
1135 (const :tag "Plain text links" plain)
1136 (const :tag "Radio target matches" radio)
1137 (const :tag "Tags" tag)
1138 (const :tag "Timestamps" date)
1139 (const :tag "Footnotes" footnote)))
1141 (defcustom org-make-link-description-function nil
1142 "Function to use to generate link descriptions from links. If
1143 nil the link location will be used. This function must take two
1144 parameters; the first is the link and the second the description
1145 org-insert-link has generated, and should return the description
1146 to use."
1147 :group 'org-link
1148 :type 'function)
1150 (defgroup org-link-store nil
1151 "Options concerning storing links in Org-mode."
1152 :tag "Org Store Link"
1153 :group 'org-link)
1155 (defcustom org-email-link-description-format "Email %c: %.30s"
1156 "Format of the description part of a link to an email or usenet message.
1157 The following %-escapes will be replaced by corresponding information:
1159 %F full \"From\" field
1160 %f name, taken from \"From\" field, address if no name
1161 %T full \"To\" field
1162 %t first name in \"To\" field, address if no name
1163 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1164 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1165 %s subject
1166 %m message-id.
1168 You may use normal field width specification between the % and the letter.
1169 This is for example useful to limit the length of the subject.
1171 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1172 :group 'org-link-store
1173 :type 'string)
1175 (defcustom org-from-is-user-regexp
1176 (let (r1 r2)
1177 (when (and user-mail-address (not (string= user-mail-address "")))
1178 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1179 (when (and user-full-name (not (string= user-full-name "")))
1180 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1181 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1182 "Regexp matched against the \"From:\" header of an email or usenet message.
1183 It should match if the message is from the user him/herself."
1184 :group 'org-link-store
1185 :type 'regexp)
1187 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1188 "Non-nil means storing a link to an Org file will use entry IDs.
1190 Note that before this variable is even considered, org-id must be loaded,
1191 so please customize `org-modules' and turn it on.
1193 The variable can have the following values:
1195 t Create an ID if needed to make a link to the current entry.
1197 create-if-interactive
1198 If `org-store-link' is called directly (interactively, as a user
1199 command), do create an ID to support the link. But when doing the
1200 job for remember, only use the ID if it already exists. The
1201 purpose of this setting is to avoid proliferation of unwanted
1202 IDs, just because you happen to be in an Org file when you
1203 call `org-remember' that automatically and preemptively
1204 creates a link. If you do want to get an ID link in a remember
1205 template to an entry not having an ID, create it first by
1206 explicitly creating a link to it, using `C-c C-l' first.
1208 create-if-interactive-and-no-custom-id
1209 Like create-if-interactive, but do not create an ID if there is
1210 a CUSTOM_ID property defined in the entry. This is the default.
1212 use-existing
1213 Use existing ID, do not create one.
1215 nil Never use an ID to make a link, instead link using a text search for
1216 the headline text."
1217 :group 'org-link-store
1218 :type '(choice
1219 (const :tag "Create ID to make link" t)
1220 (const :tag "Create if storing link interactively"
1221 create-if-interactive)
1222 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1223 create-if-interactive-and-no-custom-id)
1224 (const :tag "Only use existing" use-existing)
1225 (const :tag "Do not use ID to create link" nil)))
1227 (defcustom org-context-in-file-links t
1228 "Non-nil means file links from `org-store-link' contain context.
1229 A search string will be added to the file name with :: as separator and
1230 used to find the context when the link is activated by the command
1231 `org-open-at-point'.
1232 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1233 negates this setting for the duration of the command."
1234 :group 'org-link-store
1235 :type 'boolean)
1237 (defcustom org-keep-stored-link-after-insertion nil
1238 "Non-nil means keep link in list for entire session.
1240 The command `org-store-link' adds a link pointing to the current
1241 location to an internal list. These links accumulate during a session.
1242 The command `org-insert-link' can be used to insert links into any
1243 Org-mode file (offering completion for all stored links). When this
1244 option is nil, every link which has been inserted once using \\[org-insert-link]
1245 will be removed from the list, to make completing the unused links
1246 more efficient."
1247 :group 'org-link-store
1248 :type 'boolean)
1250 (defgroup org-link-follow nil
1251 "Options concerning following links in Org-mode."
1252 :tag "Org Follow Link"
1253 :group 'org-link)
1255 (defcustom org-link-translation-function nil
1256 "Function to translate links with different syntax to Org syntax.
1257 This can be used to translate links created for example by the Planner
1258 or emacs-wiki packages to Org syntax.
1259 The function must accept two parameters, a TYPE containing the link
1260 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1261 which is everything after the link protocol. It should return a cons
1262 with possibly modified values of type and path.
1263 Org contains a function for this, so if you set this variable to
1264 `org-translate-link-from-planner', you should be able follow many
1265 links created by planner."
1266 :group 'org-link-follow
1267 :type 'function)
1269 (defcustom org-follow-link-hook nil
1270 "Hook that is run after a link has been followed."
1271 :group 'org-link-follow
1272 :type 'hook)
1274 (defcustom org-tab-follows-link nil
1275 "Non-nil means on links TAB will follow the link.
1276 Needs to be set before org.el is loaded.
1277 This really should not be used, it does not make sense, and the
1278 implementation is bad."
1279 :group 'org-link-follow
1280 :type 'boolean)
1282 (defcustom org-return-follows-link nil
1283 "Non-nil means on links RET will follow the link.
1284 Needs to be set before org.el is loaded."
1285 :group 'org-link-follow
1286 :type 'boolean)
1288 (defcustom org-mouse-1-follows-link
1289 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1290 "Non-nil means mouse-1 on a link will follow the link.
1291 A longer mouse click will still set point. Does not work on XEmacs.
1292 Needs to be set before org.el is loaded."
1293 :group 'org-link-follow
1294 :type 'boolean)
1296 (defcustom org-mark-ring-length 4
1297 "Number of different positions to be recorded in the ring
1298 Changing this requires a restart of Emacs to work correctly."
1299 :group 'org-link-follow
1300 :type 'integer)
1302 (defcustom org-link-frame-setup
1303 '((vm . vm-visit-folder-other-frame)
1304 (gnus . gnus-other-frame)
1305 (file . find-file-other-window))
1306 "Setup the frame configuration for following links.
1307 When following a link with Emacs, it may often be useful to display
1308 this link in another window or frame. This variable can be used to
1309 set this up for the different types of links.
1310 For VM, use any of
1311 `vm-visit-folder'
1312 `vm-visit-folder-other-frame'
1313 For Gnus, use any of
1314 `gnus'
1315 `gnus-other-frame'
1316 `org-gnus-no-new-news'
1317 For FILE, use any of
1318 `find-file'
1319 `find-file-other-window'
1320 `find-file-other-frame'
1321 For the calendar, use the variable `calendar-setup'.
1322 For BBDB, it is currently only possible to display the matches in
1323 another window."
1324 :group 'org-link-follow
1325 :type '(list
1326 (cons (const vm)
1327 (choice
1328 (const vm-visit-folder)
1329 (const vm-visit-folder-other-window)
1330 (const vm-visit-folder-other-frame)))
1331 (cons (const gnus)
1332 (choice
1333 (const gnus)
1334 (const gnus-other-frame)
1335 (const org-gnus-no-new-news)))
1336 (cons (const file)
1337 (choice
1338 (const find-file)
1339 (const find-file-other-window)
1340 (const find-file-other-frame)))))
1342 (defcustom org-display-internal-link-with-indirect-buffer nil
1343 "Non-nil means use indirect buffer to display infile links.
1344 Activating internal links (from one location in a file to another location
1345 in the same file) normally just jumps to the location. When the link is
1346 activated with a C-u prefix (or with mouse-3), the link is displayed in
1347 another window. When this option is set, the other window actually displays
1348 an indirect buffer clone of the current buffer, to avoid any visibility
1349 changes to the current buffer."
1350 :group 'org-link-follow
1351 :type 'boolean)
1353 (defcustom org-open-non-existing-files nil
1354 "Non-nil means `org-open-file' will open non-existing files.
1355 When nil, an error will be generated.
1356 This variable applies only to external applications because they
1357 might choke on non-existing files. If the link is to a file that
1358 will be opened in Emacs, the variable is ignored."
1359 :group 'org-link-follow
1360 :type 'boolean)
1362 (defcustom org-open-directory-means-index-dot-org nil
1363 "Non-nil means a link to a directory really means to index.org.
1364 When nil, following a directory link will run dired or open a finder/explorer
1365 window on that directory."
1366 :group 'org-link-follow
1367 :type 'boolean)
1369 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1370 "Function and arguments to call for following mailto links.
1371 This is a list with the first element being a lisp function, and the
1372 remaining elements being arguments to the function. In string arguments,
1373 %a will be replaced by the address, and %s will be replaced by the subject
1374 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1375 :group 'org-link-follow
1376 :type '(choice
1377 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1378 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1379 (const :tag "message-mail" (message-mail "%a" "%s"))
1380 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1382 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1383 "Non-nil means ask for confirmation before executing shell links.
1384 Shell links can be dangerous: just think about a link
1386 [[shell:rm -rf ~/*][Google Search]]
1388 This link would show up in your Org-mode document as \"Google Search\",
1389 but really it would remove your entire home directory.
1390 Therefore we advise against setting this variable to nil.
1391 Just change it to `y-or-n-p' if you want to confirm with a
1392 single keystroke rather than having to type \"yes\"."
1393 :group 'org-link-follow
1394 :type '(choice
1395 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1396 (const :tag "with y-or-n (faster)" y-or-n-p)
1397 (const :tag "no confirmation (dangerous)" nil)))
1399 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1400 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1401 Elisp links can be dangerous: just think about a link
1403 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1405 This link would show up in your Org-mode document as \"Google Search\",
1406 but really it would remove your entire home directory.
1407 Therefore we advise against setting this variable to nil.
1408 Just change it to `y-or-n-p' if you want to confirm with a
1409 single keystroke rather than having to type \"yes\"."
1410 :group 'org-link-follow
1411 :type '(choice
1412 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1413 (const :tag "with y-or-n (faster)" y-or-n-p)
1414 (const :tag "no confirmation (dangerous)" nil)))
1416 (defconst org-file-apps-defaults-gnu
1417 '((remote . emacs)
1418 (system . mailcap)
1419 (t . mailcap))
1420 "Default file applications on a UNIX or GNU/Linux system.
1421 See `org-file-apps'.")
1423 (defconst org-file-apps-defaults-macosx
1424 '((remote . emacs)
1425 (t . "open %s")
1426 (system . "open %s")
1427 ("ps.gz" . "gv %s")
1428 ("eps.gz" . "gv %s")
1429 ("dvi" . "xdvi %s")
1430 ("fig" . "xfig %s"))
1431 "Default file applications on a MacOS X system.
1432 The system \"open\" is known as a default, but we use X11 applications
1433 for some files for which the OS does not have a good default.
1434 See `org-file-apps'.")
1436 (defconst org-file-apps-defaults-windowsnt
1437 (list
1438 '(remote . emacs)
1439 (cons t
1440 (list (if (featurep 'xemacs)
1441 'mswindows-shell-execute
1442 'w32-shell-execute)
1443 "open" 'file))
1444 (cons 'system
1445 (list (if (featurep 'xemacs)
1446 'mswindows-shell-execute
1447 'w32-shell-execute)
1448 "open" 'file)))
1449 "Default file applications on a Windows NT system.
1450 The system \"open\" is used for most files.
1451 See `org-file-apps'.")
1453 (defcustom org-file-apps
1455 (auto-mode . emacs)
1456 ("\\.mm\\'" . default)
1457 ("\\.x?html?\\'" . default)
1458 ("\\.pdf\\'" . default)
1460 "External applications for opening `file:path' items in a document.
1461 Org-mode uses system defaults for different file types, but
1462 you can use this variable to set the application for a given file
1463 extension. The entries in this list are cons cells where the car identifies
1464 files and the cdr the corresponding command. Possible values for the
1465 file identifier are
1466 \"regex\" Regular expression matched against the file: link. For
1467 backward compatibility, this can also be a string with only
1468 alphanumeric characters, which is then interpreted as an
1469 extension.
1470 `directory' Matches a directory
1471 `remote' Matches a remote file, accessible through tramp or efs.
1472 Remote files most likely should be visited through Emacs
1473 because external applications cannot handle such paths.
1474 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1475 so all files Emacs knows how to handle. Using this with
1476 command `emacs' will open most files in Emacs. Beware that this
1477 will also open html files inside Emacs, unless you add
1478 (\"html\" . default) to the list as well.
1479 t Default for files not matched by any of the other options.
1480 `system' The system command to open files, like `open' on Windows
1481 and Mac OS X, and mailcap under GNU/Linux. This is the command
1482 that will be selected if you call `C-c C-o' with a double
1483 `C-u C-u' prefix.
1485 Possible values for the command are:
1486 `emacs' The file will be visited by the current Emacs process.
1487 `default' Use the default application for this file type, which is the
1488 association for t in the list, most likely in the system-specific
1489 part.
1490 This can be used to overrule an unwanted setting in the
1491 system-specific variable.
1492 `system' Use the system command for opening files, like \"open\".
1493 This command is specified by the entry whose car is `system'.
1494 Most likely, the system-specific version of this variable
1495 does define this command, but you can overrule/replace it
1496 here.
1497 string A command to be executed by a shell; %s will be replaced
1498 by the path to the file. If the file identifier is a regex,
1499 %n will be replaced by the match of the nth match group.
1500 sexp A Lisp form which will be evaluated. The file path will
1501 be available in the Lisp variable `file', the link itself
1502 in the Lisp variable `link'. If the file identifier is a regex,
1503 the original match data will be restored, so subexpression
1504 matches are accessible using (match-string n link).
1505 For more examples, see the system specific constants
1506 `org-file-apps-defaults-macosx'
1507 `org-file-apps-defaults-windowsnt'
1508 `org-file-apps-defaults-gnu'."
1509 :group 'org-link-follow
1510 :type '(repeat
1511 (cons (choice :value ""
1512 (string :tag "Extension")
1513 (const :tag "System command to open files" system)
1514 (const :tag "Default for unrecognized files" t)
1515 (const :tag "Remote file" remote)
1516 (const :tag "Links to a directory" directory)
1517 (const :tag "Any files that have Emacs modes"
1518 auto-mode))
1519 (choice :value ""
1520 (const :tag "Visit with Emacs" emacs)
1521 (const :tag "Use default" default)
1522 (const :tag "Use the system command" system)
1523 (string :tag "Command")
1524 (sexp :tag "Lisp form")))))
1526 (defgroup org-refile nil
1527 "Options concerning refiling entries in Org-mode."
1528 :tag "Org Refile"
1529 :group 'org)
1531 (defcustom org-directory "~/org"
1532 "Directory with org files.
1533 This is just a default location to look for Org files. There is no need
1534 at all to put your files into this directory. It is only used in the
1535 following situations:
1537 1. When a remember template specifies a target file that is not an
1538 absolute path. The path will then be interpreted relative to
1539 `org-directory'
1540 2. When a remember note is filed away in an interactive way (when exiting the
1541 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1542 with `org-directory' as the default path."
1543 :group 'org-refile
1544 :group 'org-remember
1545 :type 'directory)
1547 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1548 "Default target for storing notes.
1549 Used by the hooks for remember.el. This can be a string, or nil to mean
1550 the value of `remember-data-file'.
1551 You can set this on a per-template basis with the variable
1552 `org-remember-templates'."
1553 :group 'org-refile
1554 :group 'org-remember
1555 :type '(choice
1556 (const :tag "Default from remember-data-file" nil)
1557 file))
1559 (defcustom org-goto-interface 'outline
1560 "The default interface to be used for `org-goto'.
1561 Allowed values are:
1562 outline The interface shows an outline of the relevant file
1563 and the correct heading is found by moving through
1564 the outline or by searching with incremental search.
1565 outline-path-completion Headlines in the current buffer are offered via
1566 completion. This is the interface also used by
1567 the refile command."
1568 :group 'org-refile
1569 :type '(choice
1570 (const :tag "Outline" outline)
1571 (const :tag "Outline-path-completion" outline-path-completion)))
1573 (defcustom org-goto-max-level 5
1574 "Maximum level to be considered when running org-goto with refile interface."
1575 :group 'org-refile
1576 :type 'integer)
1578 (defcustom org-reverse-note-order nil
1579 "Non-nil means store new notes at the beginning of a file or entry.
1580 When nil, new notes will be filed to the end of a file or entry.
1581 This can also be a list with cons cells of regular expressions that
1582 are matched against file names, and values."
1583 :group 'org-remember
1584 :group 'org-refile
1585 :type '(choice
1586 (const :tag "Reverse always" t)
1587 (const :tag "Reverse never" nil)
1588 (repeat :tag "By file name regexp"
1589 (cons regexp boolean))))
1591 (defcustom org-log-refile nil
1592 "Information to record when a task is refiled.
1594 Possible values are:
1596 nil Don't add anything
1597 time Add a time stamp to the task
1598 note Prompt for a note and add it with template `org-log-note-headings'
1600 This option can also be set with on a per-file-basis with
1602 #+STARTUP: nologrefile
1603 #+STARTUP: logrefile
1604 #+STARTUP: lognoterefile
1606 You can have local logging settings for a subtree by setting the LOGGING
1607 property to one or more of these keywords.
1609 When bulk-refiling from the agenda, the value `note' is forbidden and
1610 will temporarily be changed to `time'."
1611 :group 'org-refile
1612 :group 'org-progress
1613 :type '(choice
1614 (const :tag "No logging" nil)
1615 (const :tag "Record timestamp" time)
1616 (const :tag "Record timestamp with note." note)))
1618 (defcustom org-refile-targets nil
1619 "Targets for refiling entries with \\[org-refile].
1620 This is list of cons cells. Each cell contains:
1621 - a specification of the files to be considered, either a list of files,
1622 or a symbol whose function or variable value will be used to retrieve
1623 a file name or a list of file names. If you use `org-agenda-files' for
1624 that, all agenda files will be scanned for targets. Nil means consider
1625 headings in the current buffer.
1626 - A specification of how to find candidate refile targets. This may be
1627 any of:
1628 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1629 This tag has to be present in all target headlines, inheritance will
1630 not be considered.
1631 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1632 todo keyword.
1633 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1634 headlines that are refiling targets.
1635 - a cons cell (:level . N). Any headline of level N is considered a target.
1636 Note that, when `org-odd-levels-only' is set, level corresponds to
1637 order in hierarchy, not to the number of stars.
1638 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1639 Note that, when `org-odd-levels-only' is set, level corresponds to
1640 order in hierarchy, not to the number of stars.
1642 You can set the variable `org-refile-target-verify-function' to a function
1643 to verify each headline found by the simple critery above.
1645 When this variable is nil, all top-level headlines in the current buffer
1646 are used, equivalent to the value `((nil . (:level . 1))'."
1647 :group 'org-refile
1648 :type '(repeat
1649 (cons
1650 (choice :value org-agenda-files
1651 (const :tag "All agenda files" org-agenda-files)
1652 (const :tag "Current buffer" nil)
1653 (function) (variable) (file))
1654 (choice :tag "Identify target headline by"
1655 (cons :tag "Specific tag" (const :value :tag) (string))
1656 (cons :tag "TODO keyword" (const :value :todo) (string))
1657 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1658 (cons :tag "Level number" (const :value :level) (integer))
1659 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1661 (defcustom org-refile-target-verify-function nil
1662 "Function to verify if the headline at point should be a refile target.
1663 The function will be called without arguments, with point at the
1664 beginning of the headline. It should return t and leave point
1665 where it is if the headline is a valid target for refiling.
1667 If the target should not be selected, the function must return nil.
1668 In addition to this, it may move point to a place from where the search
1669 should be continued. For example, the function may decide that the entire
1670 subtree of the current entry should be excluded and move point to the end
1671 of the subtree."
1672 :group 'org-refile
1673 :type 'function)
1675 (defcustom org-refile-use-outline-path nil
1676 "Non-nil means provide refile targets as paths.
1677 So a level 3 headline will be available as level1/level2/level3.
1679 When the value is `file', also include the file name (without directory)
1680 into the path. In this case, you can also stop the completion after
1681 the file name, to get entries inserted as top level in the file.
1683 When `full-file-path', include the full file path."
1684 :group 'org-refile
1685 :type '(choice
1686 (const :tag "Not" nil)
1687 (const :tag "Yes" t)
1688 (const :tag "Start with file name" file)
1689 (const :tag "Start with full file path" full-file-path)))
1691 (defcustom org-outline-path-complete-in-steps t
1692 "Non-nil means complete the outline path in hierarchical steps.
1693 When Org-mode uses the refile interface to select an outline path
1694 \(see variable `org-refile-use-outline-path'), the completion of
1695 the path can be done is a single go, or if can be done in steps down
1696 the headline hierarchy. Going in steps is probably the best if you
1697 do not use a special completion package like `ido' or `icicles'.
1698 However, when using these packages, going in one step can be very
1699 fast, while still showing the whole path to the entry."
1700 :group 'org-refile
1701 :type 'boolean)
1703 (defcustom org-refile-allow-creating-parent-nodes nil
1704 "Non-nil means allow to create new nodes as refile targets.
1705 New nodes are then created by adding \"/new node name\" to the completion
1706 of an existing node. When the value of this variable is `confirm',
1707 new node creation must be confirmed by the user (recommended)
1708 When nil, the completion must match an existing entry.
1710 Note that, if the new heading is not seen by the criteria
1711 listed in `org-refile-targets', multiple instances of the same
1712 heading would be created by trying again to file under the new
1713 heading."
1714 :group 'org-refile
1715 :type '(choice
1716 (const :tag "Never" nil)
1717 (const :tag "Always" t)
1718 (const :tag "Prompt for confirmation" confirm)))
1720 (defgroup org-todo nil
1721 "Options concerning TODO items in Org-mode."
1722 :tag "Org TODO"
1723 :group 'org)
1725 (defgroup org-progress nil
1726 "Options concerning Progress logging in Org-mode."
1727 :tag "Org Progress"
1728 :group 'org-time)
1730 (defvar org-todo-interpretation-widgets
1732 (:tag "Sequence (cycling hits every state)" sequence)
1733 (:tag "Type (cycling directly to DONE)" type))
1734 "The available interpretation symbols for customizing
1735 `org-todo-keywords'.
1736 Interested libraries should add to this list.")
1738 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1739 "List of TODO entry keyword sequences and their interpretation.
1740 \\<org-mode-map>This is a list of sequences.
1742 Each sequence starts with a symbol, either `sequence' or `type',
1743 indicating if the keywords should be interpreted as a sequence of
1744 action steps, or as different types of TODO items. The first
1745 keywords are states requiring action - these states will select a headline
1746 for inclusion into the global TODO list Org-mode produces. If one of
1747 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1748 signify that no further action is necessary. If \"|\" is not found,
1749 the last keyword is treated as the only DONE state of the sequence.
1751 The command \\[org-todo] cycles an entry through these states, and one
1752 additional state where no keyword is present. For details about this
1753 cycling, see the manual.
1755 TODO keywords and interpretation can also be set on a per-file basis with
1756 the special #+SEQ_TODO and #+TYP_TODO lines.
1758 Each keyword can optionally specify a character for fast state selection
1759 \(in combination with the variable `org-use-fast-todo-selection')
1760 and specifiers for state change logging, using the same syntax
1761 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1762 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1763 indicates to record a time stamp each time this state is selected.
1765 Each keyword may also specify if a timestamp or a note should be
1766 recorded when entering or leaving the state, by adding additional
1767 characters in the parenthesis after the keyword. This looks like this:
1768 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1769 record only the time of the state change. With X and Y being either
1770 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1771 Y when leaving the state if and only if the *target* state does not
1772 define X. You may omit any of the fast-selection key or X or /Y,
1773 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1775 For backward compatibility, this variable may also be just a list
1776 of keywords - in this case the interpretation (sequence or type) will be
1777 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1778 :group 'org-todo
1779 :group 'org-keywords
1780 :type '(choice
1781 (repeat :tag "Old syntax, just keywords"
1782 (string :tag "Keyword"))
1783 (repeat :tag "New syntax"
1784 (cons
1785 (choice
1786 :tag "Interpretation"
1787 ;;Quick and dirty way to see
1788 ;;`org-todo-interpretations'. This takes the
1789 ;;place of item arguments
1790 :convert-widget
1791 (lambda (widget)
1792 (widget-put widget
1793 :args (mapcar
1794 #'(lambda (x)
1795 (widget-convert
1796 (cons 'const x)))
1797 org-todo-interpretation-widgets))
1798 widget))
1799 (repeat
1800 (string :tag "Keyword"))))))
1802 (defvar org-todo-keywords-1 nil
1803 "All TODO and DONE keywords active in a buffer.")
1804 (make-variable-buffer-local 'org-todo-keywords-1)
1805 (defvar org-todo-keywords-for-agenda nil)
1806 (defvar org-done-keywords-for-agenda nil)
1807 (defvar org-drawers-for-agenda nil)
1808 (defvar org-todo-keyword-alist-for-agenda nil)
1809 (defvar org-tag-alist-for-agenda nil)
1810 (defvar org-agenda-contributing-files nil)
1811 (defvar org-not-done-keywords nil)
1812 (make-variable-buffer-local 'org-not-done-keywords)
1813 (defvar org-done-keywords nil)
1814 (make-variable-buffer-local 'org-done-keywords)
1815 (defvar org-todo-heads nil)
1816 (make-variable-buffer-local 'org-todo-heads)
1817 (defvar org-todo-sets nil)
1818 (make-variable-buffer-local 'org-todo-sets)
1819 (defvar org-todo-log-states nil)
1820 (make-variable-buffer-local 'org-todo-log-states)
1821 (defvar org-todo-kwd-alist nil)
1822 (make-variable-buffer-local 'org-todo-kwd-alist)
1823 (defvar org-todo-key-alist nil)
1824 (make-variable-buffer-local 'org-todo-key-alist)
1825 (defvar org-todo-key-trigger nil)
1826 (make-variable-buffer-local 'org-todo-key-trigger)
1828 (defcustom org-todo-interpretation 'sequence
1829 "Controls how TODO keywords are interpreted.
1830 This variable is in principle obsolete and is only used for
1831 backward compatibility, if the interpretation of todo keywords is
1832 not given already in `org-todo-keywords'. See that variable for
1833 more information."
1834 :group 'org-todo
1835 :group 'org-keywords
1836 :type '(choice (const sequence)
1837 (const type)))
1839 (defcustom org-use-fast-todo-selection t
1840 "Non-nil means use the fast todo selection scheme with C-c C-t.
1841 This variable describes if and under what circumstances the cycling
1842 mechanism for TODO keywords will be replaced by a single-key, direct
1843 selection scheme.
1845 When nil, fast selection is never used.
1847 When the symbol `prefix', it will be used when `org-todo' is called with
1848 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1849 in an agenda buffer.
1851 When t, fast selection is used by default. In this case, the prefix
1852 argument forces cycling instead.
1854 In all cases, the special interface is only used if access keys have actually
1855 been assigned by the user, i.e. if keywords in the configuration are followed
1856 by a letter in parenthesis, like TODO(t)."
1857 :group 'org-todo
1858 :type '(choice
1859 (const :tag "Never" nil)
1860 (const :tag "By default" t)
1861 (const :tag "Only with C-u C-c C-t" prefix)))
1863 (defcustom org-provide-todo-statistics t
1864 "Non-nil means update todo statistics after insert and toggle.
1865 ALL-HEADLINES means update todo statistics by including headlines
1866 with no TODO keyword as well, counting them as not done.
1867 A list of TODO keywords means the same, but skip keywords that are
1868 not in this list.
1870 When this is set, todo statistics is updated in the parent of the
1871 current entry each time a todo state is changed."
1872 :group 'org-todo
1873 :type '(choice
1874 (const :tag "Yes, only for TODO entries" t)
1875 (const :tag "Yes, including all entries" 'all-headlines)
1876 (repeat :tag "Yes, for TODOs in this list"
1877 (string :tag "TODO keyword"))
1878 (other :tag "No TODO statistics" nil)))
1880 (defcustom org-hierarchical-todo-statistics t
1881 "Non-nil means TODO statistics covers just direct children.
1882 When nil, all entries in the subtree are considered.
1883 This has only an effect if `org-provide-todo-statistics' is set.
1884 To set this to nil for only a single subtree, use a COOKIE_DATA
1885 property and include the word \"recursive\" into the value."
1886 :group 'org-todo
1887 :type 'boolean)
1889 (defcustom org-after-todo-state-change-hook nil
1890 "Hook which is run after the state of a TODO item was changed.
1891 The new state (a string with a TODO keyword, or nil) is available in the
1892 Lisp variable `state'."
1893 :group 'org-todo
1894 :type 'hook)
1896 (defvar org-blocker-hook nil
1897 "Hook for functions that are allowed to block a state change.
1899 Each function gets as its single argument a property list, see
1900 `org-trigger-hook' for more information about this list.
1902 If any of the functions in this hook returns nil, the state change
1903 is blocked.")
1905 (defvar org-trigger-hook nil
1906 "Hook for functions that are triggered by a state change.
1908 Each function gets as its single argument a property list with at least
1909 the following elements:
1911 (:type type-of-change :position pos-at-entry-start
1912 :from old-state :to new-state)
1914 Depending on the type, more properties may be present.
1916 This mechanism is currently implemented for:
1918 TODO state changes
1919 ------------------
1920 :type todo-state-change
1921 :from previous state (keyword as a string), or nil, or a symbol
1922 'todo' or 'done', to indicate the general type of state.
1923 :to new state, like in :from")
1925 (defcustom org-enforce-todo-dependencies nil
1926 "Non-nil means undone TODO entries will block switching the parent to DONE.
1927 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1928 be blocked if any prior sibling is not yet done.
1929 Finally, if the parent is blocked because of ordered siblings of its own,
1930 the child will also be blocked.
1931 This variable needs to be set before org.el is loaded, and you need to
1932 restart Emacs after a change to make the change effective. The only way
1933 to change is while Emacs is running is through the customize interface."
1934 :set (lambda (var val)
1935 (set var val)
1936 (if val
1937 (add-hook 'org-blocker-hook
1938 'org-block-todo-from-children-or-siblings-or-parent)
1939 (remove-hook 'org-blocker-hook
1940 'org-block-todo-from-children-or-siblings-or-parent)))
1941 :group 'org-todo
1942 :type 'boolean)
1944 (defcustom org-enforce-todo-checkbox-dependencies nil
1945 "Non-nil means unchecked boxes will block switching the parent to DONE.
1946 When this is nil, checkboxes have no influence on switching TODO states.
1947 When non-nil, you first need to check off all check boxes before the TODO
1948 entry can be switched to DONE.
1949 This variable needs to be set before org.el is loaded, and you need to
1950 restart Emacs after a change to make the change effective. The only way
1951 to change is while Emacs is running is through the customize interface."
1952 :set (lambda (var val)
1953 (set var val)
1954 (if val
1955 (add-hook 'org-blocker-hook
1956 'org-block-todo-from-checkboxes)
1957 (remove-hook 'org-blocker-hook
1958 'org-block-todo-from-checkboxes)))
1959 :group 'org-todo
1960 :type 'boolean)
1962 (defcustom org-treat-insert-todo-heading-as-state-change nil
1963 "Non-nil means inserting a TODO heading is treated as state change.
1964 So when the command \\[org-insert-todo-heading] is used, state change
1965 logging will apply if appropriate. When nil, the new TODO item will
1966 be inserted directly, and no logging will take place."
1967 :group 'org-todo
1968 :type 'boolean)
1970 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1971 "Non-nil means switching TODO states with S-cursor counts as state change.
1972 This is the default behavior. However, setting this to nil allows a
1973 convenient way to select a TODO state and bypass any logging associated
1974 with that."
1975 :group 'org-todo
1976 :type 'boolean)
1978 (defcustom org-todo-state-tags-triggers nil
1979 "Tag changes that should be triggered by TODO state changes.
1980 This is a list. Each entry is
1982 (state-change (tag . flag) .......)
1984 State-change can be a string with a state, and empty string to indicate the
1985 state that has no TODO keyword, or it can be one of the symbols `todo'
1986 or `done', meaning any not-done or done state, respectively."
1987 :group 'org-todo
1988 :group 'org-tags
1989 :type '(repeat
1990 (cons (choice :tag "When changing to"
1991 (const :tag "Not-done state" todo)
1992 (const :tag "Done state" done)
1993 (string :tag "State"))
1994 (repeat
1995 (cons :tag "Tag action"
1996 (string :tag "Tag")
1997 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1999 (defcustom org-log-done nil
2000 "Information to record when a task moves to the DONE state.
2002 Possible values are:
2004 nil Don't add anything, just change the keyword
2005 time Add a time stamp to the task
2006 note Prompt for a note and add it with template `org-log-note-headings'
2008 This option can also be set with on a per-file-basis with
2010 #+STARTUP: nologdone
2011 #+STARTUP: logdone
2012 #+STARTUP: lognotedone
2014 You can have local logging settings for a subtree by setting the LOGGING
2015 property to one or more of these keywords."
2016 :group 'org-todo
2017 :group 'org-progress
2018 :type '(choice
2019 (const :tag "No logging" nil)
2020 (const :tag "Record CLOSED timestamp" time)
2021 (const :tag "Record CLOSED timestamp with note." note)))
2023 ;; Normalize old uses of org-log-done.
2024 (cond
2025 ((eq org-log-done t) (setq org-log-done 'time))
2026 ((and (listp org-log-done) (memq 'done org-log-done))
2027 (setq org-log-done 'note)))
2029 (defcustom org-log-reschedule nil
2030 "Information to record when the scheduling date of a tasks is modified.
2032 Possible values are:
2034 nil Don't add anything, just change the date
2035 time Add a time stamp to the task
2036 note Prompt for a note and add it with template `org-log-note-headings'
2038 This option can also be set with on a per-file-basis with
2040 #+STARTUP: nologreschedule
2041 #+STARTUP: logreschedule
2042 #+STARTUP: lognotereschedule"
2043 :group 'org-todo
2044 :group 'org-progress
2045 :type '(choice
2046 (const :tag "No logging" nil)
2047 (const :tag "Record timestamp" time)
2048 (const :tag "Record timestamp with note." note)))
2050 (defcustom org-log-redeadline nil
2051 "Information to record when the deadline date of a tasks is modified.
2053 Possible values are:
2055 nil Don't add anything, just change the date
2056 time Add a time stamp to the task
2057 note Prompt for a note and add it with template `org-log-note-headings'
2059 This option can also be set with on a per-file-basis with
2061 #+STARTUP: nologredeadline
2062 #+STARTUP: logredeadline
2063 #+STARTUP: lognoteredeadline
2065 You can have local logging settings for a subtree by setting the LOGGING
2066 property to one or more of these keywords."
2067 :group 'org-todo
2068 :group 'org-progress
2069 :type '(choice
2070 (const :tag "No logging" nil)
2071 (const :tag "Record timestamp" time)
2072 (const :tag "Record timestamp with note." note)))
2074 (defcustom org-log-note-clock-out nil
2075 "Non-nil means record a note when clocking out of an item.
2076 This can also be configured on a per-file basis by adding one of
2077 the following lines anywhere in the buffer:
2079 #+STARTUP: lognoteclock-out
2080 #+STARTUP: nolognoteclock-out"
2081 :group 'org-todo
2082 :group 'org-progress
2083 :type 'boolean)
2085 (defcustom org-log-done-with-time t
2086 "Non-nil means the CLOSED time stamp will contain date and time.
2087 When nil, only the date will be recorded."
2088 :group 'org-progress
2089 :type 'boolean)
2091 (defcustom org-log-note-headings
2092 '((done . "CLOSING NOTE %t")
2093 (state . "State %-12s from %-12S %t")
2094 (note . "Note taken on %t")
2095 (reschedule . "Rescheduled from %S on %t")
2096 (delschedule . "Not scheduled, was %S on %t")
2097 (redeadline . "New deadline from %S on %t")
2098 (deldeadline . "Removed deadline, was %S on %t")
2099 (refile . "Refiled on %t")
2100 (clock-out . ""))
2101 "Headings for notes added to entries.
2102 The value is an alist, with the car being a symbol indicating the note
2103 context, and the cdr is the heading to be used. The heading may also be the
2104 empty string.
2105 %t in the heading will be replaced by a time stamp.
2106 %s will be replaced by the new TODO state, in double quotes.
2107 %S will be replaced by the old TODO state, in double quotes.
2108 %u will be replaced by the user name.
2109 %U will be replaced by the full user name.
2111 In fact, it is not a good idea to change the `state' entry, because
2112 agenda log mode depends on the format of these entries."
2113 :group 'org-todo
2114 :group 'org-progress
2115 :type '(list :greedy t
2116 (cons (const :tag "Heading when closing an item" done) string)
2117 (cons (const :tag
2118 "Heading when changing todo state (todo sequence only)"
2119 state) string)
2120 (cons (const :tag "Heading when just taking a note" note) string)
2121 (cons (const :tag "Heading when clocking out" clock-out) string)
2122 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2123 (cons (const :tag "Heading when rescheduling" reschedule) string)
2124 (cons (const :tag "Heading when changing deadline" redeadline) string)
2125 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2126 (cons (const :tag "Heading when refiling" refile) string)))
2128 (unless (assq 'note org-log-note-headings)
2129 (push '(note . "%t") org-log-note-headings))
2131 (defcustom org-log-into-drawer nil
2132 "Non-nil means insert state change notes and time stamps into a drawer.
2133 When nil, state changes notes will be inserted after the headline and
2134 any scheduling and clock lines, but not inside a drawer.
2136 The value of this variable should be the name of the drawer to use.
2137 LOGBOOK is proposed at the default drawer for this purpose, you can
2138 also set this to a string to define the drawer of your choice.
2140 A value of t is also allowed, representing \"LOGBOOK\".
2142 If this variable is set, `org-log-state-notes-insert-after-drawers'
2143 will be ignored.
2145 You can set the property LOG_INTO_DRAWER to overrule this setting for
2146 a subtree."
2147 :group 'org-todo
2148 :group 'org-progress
2149 :type '(choice
2150 (const :tag "Not into a drawer" nil)
2151 (const :tag "LOGBOOK" t)
2152 (string :tag "Other")))
2154 (if (fboundp 'defvaralias)
2155 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2157 (defun org-log-into-drawer ()
2158 "Return the value of `org-log-into-drawer', but let properties overrule.
2159 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2160 used instead of the default value."
2161 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2162 (cond
2163 ((or (not p) (equal p "nil")) org-log-into-drawer)
2164 ((equal p "t") "LOGBOOK")
2165 (t p))))
2167 (defcustom org-log-state-notes-insert-after-drawers nil
2168 "Non-nil means insert state change notes after any drawers in entry.
2169 Only the drawers that *immediately* follow the headline and the
2170 deadline/scheduled line are skipped.
2171 When nil, insert notes right after the heading and perhaps the line
2172 with deadline/scheduling if present.
2174 This variable will have no effect if `org-log-into-drawer' is
2175 set."
2176 :group 'org-todo
2177 :group 'org-progress
2178 :type 'boolean)
2180 (defcustom org-log-states-order-reversed t
2181 "Non-nil means the latest state note will be directly after heading.
2182 When nil, the state change notes will be ordered according to time."
2183 :group 'org-todo
2184 :group 'org-progress
2185 :type 'boolean)
2187 (defcustom org-log-repeat 'time
2188 "Non-nil means record moving through the DONE state when triggering repeat.
2189 An auto-repeating task is immediately switched back to TODO when
2190 marked DONE. If you are not logging state changes (by adding \"@\"
2191 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2192 record a closing note, there will be no record of the task moving
2193 through DONE. This variable forces taking a note anyway.
2195 nil Don't force a record
2196 time Record a time stamp
2197 note Record a note
2199 This option can also be set with on a per-file-basis with
2201 #+STARTUP: logrepeat
2202 #+STARTUP: lognoterepeat
2203 #+STARTUP: nologrepeat
2205 You can have local logging settings for a subtree by setting the LOGGING
2206 property to one or more of these keywords."
2207 :group 'org-todo
2208 :group 'org-progress
2209 :type '(choice
2210 (const :tag "Don't force a record" nil)
2211 (const :tag "Force recording the DONE state" time)
2212 (const :tag "Force recording a note with the DONE state" note)))
2215 (defgroup org-priorities nil
2216 "Priorities in Org-mode."
2217 :tag "Org Priorities"
2218 :group 'org-todo)
2220 (defcustom org-enable-priority-commands t
2221 "Non-nil means priority commands are active.
2222 When nil, these commands will be disabled, so that you never accidentally
2223 set a priority."
2224 :group 'org-priorities
2225 :type 'boolean)
2227 (defcustom org-highest-priority ?A
2228 "The highest priority of TODO items. A character like ?A, ?B etc.
2229 Must have a smaller ASCII number than `org-lowest-priority'."
2230 :group 'org-priorities
2231 :type 'character)
2233 (defcustom org-lowest-priority ?C
2234 "The lowest priority of TODO items. A character like ?A, ?B etc.
2235 Must have a larger ASCII number than `org-highest-priority'."
2236 :group 'org-priorities
2237 :type 'character)
2239 (defcustom org-default-priority ?B
2240 "The default priority of TODO items.
2241 This is the priority an item get if no explicit priority is given."
2242 :group 'org-priorities
2243 :type 'character)
2245 (defcustom org-priority-start-cycle-with-default t
2246 "Non-nil means start with default priority when starting to cycle.
2247 When this is nil, the first step in the cycle will be (depending on the
2248 command used) one higher or lower that the default priority."
2249 :group 'org-priorities
2250 :type 'boolean)
2252 (defgroup org-time nil
2253 "Options concerning time stamps and deadlines in Org-mode."
2254 :tag "Org Time"
2255 :group 'org)
2257 (defcustom org-insert-labeled-timestamps-at-point nil
2258 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2259 When nil, these labeled time stamps are forces into the second line of an
2260 entry, just after the headline. When scheduling from the global TODO list,
2261 the time stamp will always be forced into the second line."
2262 :group 'org-time
2263 :type 'boolean)
2265 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2266 "Formats for `format-time-string' which are used for time stamps.
2267 It is not recommended to change this constant.")
2269 (defcustom org-time-stamp-rounding-minutes '(0 5)
2270 "Number of minutes to round time stamps to.
2271 These are two values, the first applies when first creating a time stamp.
2272 The second applies when changing it with the commands `S-up' and `S-down'.
2273 When changing the time stamp, this means that it will change in steps
2274 of N minutes, as given by the second value.
2276 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2277 numbers should be factors of 60, so for example 5, 10, 15.
2279 When this is larger than 1, you can still force an exact time-stamp by using
2280 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2281 and by using a prefix arg to `S-up/down' to specify the exact number
2282 of minutes to shift."
2283 :group 'org-time
2284 :get '(lambda (var) ; Make sure all entries have 5 elements
2285 (if (integerp (default-value var))
2286 (list (default-value var) 5)
2287 (default-value var)))
2288 :type '(list
2289 (integer :tag "when inserting times")
2290 (integer :tag "when modifying times")))
2292 ;; Normalize old customizations of this variable.
2293 (when (integerp org-time-stamp-rounding-minutes)
2294 (setq org-time-stamp-rounding-minutes
2295 (list org-time-stamp-rounding-minutes
2296 org-time-stamp-rounding-minutes)))
2298 (defcustom org-display-custom-times nil
2299 "Non-nil means overlay custom formats over all time stamps.
2300 The formats are defined through the variable `org-time-stamp-custom-formats'.
2301 To turn this on on a per-file basis, insert anywhere in the file:
2302 #+STARTUP: customtime"
2303 :group 'org-time
2304 :set 'set-default
2305 :type 'sexp)
2306 (make-variable-buffer-local 'org-display-custom-times)
2308 (defcustom org-time-stamp-custom-formats
2309 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2310 "Custom formats for time stamps. See `format-time-string' for the syntax.
2311 These are overlayed over the default ISO format if the variable
2312 `org-display-custom-times' is set. Time like %H:%M should be at the
2313 end of the second format. The custom formats are also honored by export
2314 commands, if custom time display is turned on at the time of export."
2315 :group 'org-time
2316 :type 'sexp)
2318 (defun org-time-stamp-format (&optional long inactive)
2319 "Get the right format for a time string."
2320 (let ((f (if long (cdr org-time-stamp-formats)
2321 (car org-time-stamp-formats))))
2322 (if inactive
2323 (concat "[" (substring f 1 -1) "]")
2324 f)))
2326 (defcustom org-time-clocksum-format "%d:%02d"
2327 "The format string used when creating CLOCKSUM lines, or when
2328 org-mode generates a time duration."
2329 :group 'org-time
2330 :type 'string)
2332 (defcustom org-time-clocksum-use-fractional nil
2333 "If non-nil, \\[org-clock-display] uses fractional times.
2334 org-mode generates a time duration."
2335 :group 'org-time
2336 :type 'boolean)
2338 (defcustom org-time-clocksum-fractional-format "%.2f"
2339 "The format string used when creating CLOCKSUM lines, or when
2340 org-mode generates a time duration."
2341 :group 'org-time
2342 :type 'string)
2344 (defcustom org-deadline-warning-days 14
2345 "No. of days before expiration during which a deadline becomes active.
2346 This variable governs the display in sparse trees and in the agenda.
2347 When 0 or negative, it means use this number (the absolute value of it)
2348 even if a deadline has a different individual lead time specified.
2350 Custom commands can set this variable in the options section."
2351 :group 'org-time
2352 :group 'org-agenda-daily/weekly
2353 :type 'integer)
2355 (defcustom org-read-date-prefer-future t
2356 "Non-nil means assume future for incomplete date input from user.
2357 This affects the following situations:
2358 1. The user gives a month but not a year.
2359 For example, if it is april and you enter \"feb 2\", this will be read
2360 as feb 2, *next* year. \"May 5\", however, will be this year.
2361 2. The user gives a day, but no month.
2362 For example, if today is the 15th, and you enter \"3\", Org-mode will
2363 read this as the third of *next* month. However, if you enter \"17\",
2364 it will be considered as *this* month.
2366 If you set this variable to the symbol `time', then also the following
2367 will work:
2369 3. If the user gives a time, but no day. If the time is before now,
2370 to will be interpreted as tomorrow.
2372 Currently none of this works for ISO week specifications.
2374 When this option is nil, the current day, month and year will always be
2375 used as defaults."
2376 :group 'org-time
2377 :type '(choice
2378 (const :tag "Never" nil)
2379 (const :tag "Check month and day" t)
2380 (const :tag "Check month, day, and time" time)))
2382 (defcustom org-read-date-display-live t
2383 "Non-nil means display current interpretation of date prompt live.
2384 This display will be in an overlay, in the minibuffer."
2385 :group 'org-time
2386 :type 'boolean)
2388 (defcustom org-read-date-popup-calendar t
2389 "Non-nil means pop up a calendar when prompting for a date.
2390 In the calendar, the date can be selected with mouse-1. However, the
2391 minibuffer will also be active, and you can simply enter the date as well.
2392 When nil, only the minibuffer will be available."
2393 :group 'org-time
2394 :type 'boolean)
2395 (if (fboundp 'defvaralias)
2396 (defvaralias 'org-popup-calendar-for-date-prompt
2397 'org-read-date-popup-calendar))
2399 (defcustom org-read-date-minibuffer-setup-hook nil
2400 "Hook to be used to set up keys for the date/time interface.
2401 Add key definitions to `minibuffer-local-map', which will be a temporary
2402 copy."
2403 :group 'org-time
2404 :type 'hook)
2406 (defcustom org-extend-today-until 0
2407 "The hour when your day really ends. Must be an integer.
2408 This has influence for the following applications:
2409 - When switching the agenda to \"today\". It it is still earlier than
2410 the time given here, the day recognized as TODAY is actually yesterday.
2411 - When a date is read from the user and it is still before the time given
2412 here, the current date and time will be assumed to be yesterday, 23:59.
2413 Also, timestamps inserted in remember templates follow this rule.
2415 IMPORTANT: This is a feature whose implementation is and likely will
2416 remain incomplete. Really, it is only here because past midnight seems to
2417 be the favorite working time of John Wiegley :-)"
2418 :group 'org-time
2419 :type 'integer)
2421 (defcustom org-edit-timestamp-down-means-later nil
2422 "Non-nil means S-down will increase the time in a time stamp.
2423 When nil, S-up will increase."
2424 :group 'org-time
2425 :type 'boolean)
2427 (defcustom org-calendar-follow-timestamp-change t
2428 "Non-nil means make the calendar window follow timestamp changes.
2429 When a timestamp is modified and the calendar window is visible, it will be
2430 moved to the new date."
2431 :group 'org-time
2432 :type 'boolean)
2434 (defgroup org-tags nil
2435 "Options concerning tags in Org-mode."
2436 :tag "Org Tags"
2437 :group 'org)
2439 (defcustom org-tag-alist nil
2440 "List of tags allowed in Org-mode files.
2441 When this list is nil, Org-mode will base TAG input on what is already in the
2442 buffer.
2443 The value of this variable is an alist, the car of each entry must be a
2444 keyword as a string, the cdr may be a character that is used to select
2445 that tag through the fast-tag-selection interface.
2446 See the manual for details."
2447 :group 'org-tags
2448 :type '(repeat
2449 (choice
2450 (cons (string :tag "Tag name")
2451 (character :tag "Access char"))
2452 (list :tag "Start radio group"
2453 (const :startgroup)
2454 (option (string :tag "Group description")))
2455 (list :tag "End radio group"
2456 (const :endgroup)
2457 (option (string :tag "Group description")))
2458 (const :tag "New line" (:newline)))))
2460 (defcustom org-tag-persistent-alist nil
2461 "List of tags that will always appear in all Org-mode files.
2462 This is in addition to any in buffer settings or customizations
2463 of `org-tag-alist'.
2464 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2465 The value of this variable is an alist, the car of each entry must be a
2466 keyword as a string, the cdr may be a character that is used to select
2467 that tag through the fast-tag-selection interface.
2468 See the manual for details.
2469 To disable these tags on a per-file basis, insert anywhere in the file:
2470 #+STARTUP: noptag"
2471 :group 'org-tags
2472 :type '(repeat
2473 (choice
2474 (cons (string :tag "Tag name")
2475 (character :tag "Access char"))
2476 (const :tag "Start radio group" (:startgroup))
2477 (const :tag "End radio group" (:endgroup))
2478 (const :tag "New line" (:newline)))))
2480 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2481 "If non-nil, always offer completion for all tags of all agenda files.
2482 Instead of customizing this variable directly, you might want to
2483 set it locally for remember buffers, because there no list of
2484 tags in that file can be created dynamically (there are none).
2486 (add-hook 'org-remember-mode-hook
2487 (lambda ()
2488 (set (make-local-variable
2489 'org-complete-tags-always-offer-all-agenda-tags)
2490 t)))"
2491 :group 'org-tags
2492 :type 'boolean)
2494 (defvar org-file-tags nil
2495 "List of tags that can be inherited by all entries in the file.
2496 The tags will be inherited if the variable `org-use-tag-inheritance'
2497 says they should be.
2498 This variable is populated from #+FILETAGS lines.")
2500 (defcustom org-use-fast-tag-selection 'auto
2501 "Non-nil means use fast tag selection scheme.
2502 This is a special interface to select and deselect tags with single keys.
2503 When nil, fast selection is never used.
2504 When the symbol `auto', fast selection is used if and only if selection
2505 characters for tags have been configured, either through the variable
2506 `org-tag-alist' or through a #+TAGS line in the buffer.
2507 When t, fast selection is always used and selection keys are assigned
2508 automatically if necessary."
2509 :group 'org-tags
2510 :type '(choice
2511 (const :tag "Always" t)
2512 (const :tag "Never" nil)
2513 (const :tag "When selection characters are configured" 'auto)))
2515 (defcustom org-fast-tag-selection-single-key nil
2516 "Non-nil means fast tag selection exits after first change.
2517 When nil, you have to press RET to exit it.
2518 During fast tag selection, you can toggle this flag with `C-c'.
2519 This variable can also have the value `expert'. In this case, the window
2520 displaying the tags menu is not even shown, until you press C-c again."
2521 :group 'org-tags
2522 :type '(choice
2523 (const :tag "No" nil)
2524 (const :tag "Yes" t)
2525 (const :tag "Expert" expert)))
2527 (defvar org-fast-tag-selection-include-todo nil
2528 "Non-nil means fast tags selection interface will also offer TODO states.
2529 This is an undocumented feature, you should not rely on it.")
2531 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2532 "The column to which tags should be indented in a headline.
2533 If this number is positive, it specifies the column. If it is negative,
2534 it means that the tags should be flushright to that column. For example,
2535 -80 works well for a normal 80 character screen."
2536 :group 'org-tags
2537 :type 'integer)
2539 (defcustom org-auto-align-tags t
2540 "Non-nil means realign tags after pro/demotion of TODO state change.
2541 These operations change the length of a headline and therefore shift
2542 the tags around. With this options turned on, after each such operation
2543 the tags are again aligned to `org-tags-column'."
2544 :group 'org-tags
2545 :type 'boolean)
2547 (defcustom org-use-tag-inheritance t
2548 "Non-nil means tags in levels apply also for sublevels.
2549 When nil, only the tags directly given in a specific line apply there.
2550 This may also be a list of tags that should be inherited, or a regexp that
2551 matches tags that should be inherited. Additional control is possible
2552 with the variable `org-tags-exclude-from-inheritance' which gives an
2553 explicit list of tags to be excluded from inheritance., even if the value of
2554 `org-use-tag-inheritance' would select it for inheritance.
2556 If this option is t, a match early-on in a tree can lead to a large
2557 number of matches in the subtree when constructing the agenda or creating
2558 a sparse tree. If you only want to see the first match in a tree during
2559 a search, check out the variable `org-tags-match-list-sublevels'."
2560 :group 'org-tags
2561 :type '(choice
2562 (const :tag "Not" nil)
2563 (const :tag "Always" t)
2564 (repeat :tag "Specific tags" (string :tag "Tag"))
2565 (regexp :tag "Tags matched by regexp")))
2567 (defcustom org-tags-exclude-from-inheritance nil
2568 "List of tags that should never be inherited.
2569 This is a way to exclude a few tags from inheritance. For way to do
2570 the opposite, to actively allow inheritance for selected tags,
2571 see the variable `org-use-tag-inheritance'."
2572 :group 'org-tags
2573 :type '(repeat (string :tag "Tag")))
2575 (defun org-tag-inherit-p (tag)
2576 "Check if TAG is one that should be inherited."
2577 (cond
2578 ((member tag org-tags-exclude-from-inheritance) nil)
2579 ((eq org-use-tag-inheritance t) t)
2580 ((not org-use-tag-inheritance) nil)
2581 ((stringp org-use-tag-inheritance)
2582 (string-match org-use-tag-inheritance tag))
2583 ((listp org-use-tag-inheritance)
2584 (member tag org-use-tag-inheritance))
2585 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2587 (defcustom org-tags-match-list-sublevels t
2588 "Non-nil means list also sublevels of headlines matching a search.
2589 This variable applies to tags/property searches, and also to stuck
2590 projects because this search is based on a tags match as well.
2592 When set to the symbol `indented', sublevels are indented with
2593 leading dots.
2595 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2596 the sublevels of a headline matching a tag search often also match
2597 the same search. Listing all of them can create very long lists.
2598 Setting this variable to nil causes subtrees of a match to be skipped.
2600 This variable is semi-obsolete and probably should always be true. It
2601 is better to limit inheritance to certain tags using the variables
2602 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2603 :group 'org-tags
2604 :type '(choice
2605 (const :tag "No, don't list them" nil)
2606 (const :tag "Yes, do list them" t)
2607 (const :tag "List them, indented with leading dots" indented)))
2609 (defcustom org-tags-sort-function nil
2610 "When set, tags are sorted using this function as a comparator"
2611 :group 'org-tags
2612 :type '(choice
2613 (const :tag "No sorting" nil)
2614 (const :tag "Alphabetical" string<)
2615 (const :tag "Reverse alphabetical" string>)
2616 (function :tag "Custom function" nil)))
2618 (defvar org-tags-history nil
2619 "History of minibuffer reads for tags.")
2620 (defvar org-last-tags-completion-table nil
2621 "The last used completion table for tags.")
2622 (defvar org-after-tags-change-hook nil
2623 "Hook that is run after the tags in a line have changed.")
2625 (defgroup org-properties nil
2626 "Options concerning properties in Org-mode."
2627 :tag "Org Properties"
2628 :group 'org)
2630 (defcustom org-property-format "%-10s %s"
2631 "How property key/value pairs should be formatted by `indent-line'.
2632 When `indent-line' hits a property definition, it will format the line
2633 according to this format, mainly to make sure that the values are
2634 lined-up with respect to each other."
2635 :group 'org-properties
2636 :type 'string)
2638 (defcustom org-use-property-inheritance nil
2639 "Non-nil means properties apply also for sublevels.
2641 This setting is chiefly used during property searches. Turning it on can
2642 cause significant overhead when doing a search, which is why it is not
2643 on by default.
2645 When nil, only the properties directly given in the current entry count.
2646 When t, every property is inherited. The value may also be a list of
2647 properties that should have inheritance, or a regular expression matching
2648 properties that should be inherited.
2650 However, note that some special properties use inheritance under special
2651 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2652 and the properties ending in \"_ALL\" when they are used as descriptor
2653 for valid values of a property.
2655 Note for programmers:
2656 When querying an entry with `org-entry-get', you can control if inheritance
2657 should be used. By default, `org-entry-get' looks only at the local
2658 properties. You can request inheritance by setting the inherit argument
2659 to t (to force inheritance) or to `selective' (to respect the setting
2660 in this variable)."
2661 :group 'org-properties
2662 :type '(choice
2663 (const :tag "Not" nil)
2664 (const :tag "Always" t)
2665 (repeat :tag "Specific properties" (string :tag "Property"))
2666 (regexp :tag "Properties matched by regexp")))
2668 (defun org-property-inherit-p (property)
2669 "Check if PROPERTY is one that should be inherited."
2670 (cond
2671 ((eq org-use-property-inheritance t) t)
2672 ((not org-use-property-inheritance) nil)
2673 ((stringp org-use-property-inheritance)
2674 (string-match org-use-property-inheritance property))
2675 ((listp org-use-property-inheritance)
2676 (member property org-use-property-inheritance))
2677 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2679 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2680 "The default column format, if no other format has been defined.
2681 This variable can be set on the per-file basis by inserting a line
2683 #+COLUMNS: %25ITEM ....."
2684 :group 'org-properties
2685 :type 'string)
2687 (defcustom org-columns-ellipses ".."
2688 "The ellipses to be used when a field in column view is truncated.
2689 When this is the empty string, as many characters as possible are shown,
2690 but then there will be no visual indication that the field has been truncated.
2691 When this is a string of length N, the last N characters of a truncated
2692 field are replaced by this string. If the column is narrower than the
2693 ellipses string, only part of the ellipses string will be shown."
2694 :group 'org-properties
2695 :type 'string)
2697 (defcustom org-columns-modify-value-for-display-function nil
2698 "Function that modifies values for display in column view.
2699 For example, it can be used to cut out a certain part from a time stamp.
2700 The function must take 2 arguments:
2702 column-title The title of the column (*not* the property name)
2703 value The value that should be modified.
2705 The function should return the value that should be displayed,
2706 or nil if the normal value should be used."
2707 :group 'org-properties
2708 :type 'function)
2710 (defcustom org-effort-property "Effort"
2711 "The property that is being used to keep track of effort estimates.
2712 Effort estimates given in this property need to have the format H:MM."
2713 :group 'org-properties
2714 :group 'org-progress
2715 :type '(string :tag "Property"))
2717 (defconst org-global-properties-fixed
2718 '(("VISIBILITY_ALL" . "folded children content all")
2719 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2720 "List of property/value pairs that can be inherited by any entry.
2722 These are fixed values, for the preset properties. The user variable
2723 that can be used to add to this list is `org-global-properties'.
2725 The entries in this list are cons cells where the car is a property
2726 name and cdr is a string with the value. If the value represents
2727 multiple items like an \"_ALL\" property, separate the items by
2728 spaces.")
2730 (defcustom org-global-properties nil
2731 "List of property/value pairs that can be inherited by any entry.
2733 This list will be combined with the constant `org-global-properties-fixed'.
2735 The entries in this list are cons cells where the car is a property
2736 name and cdr is a string with the value.
2738 You can set buffer-local values for the same purpose in the variable
2739 `org-file-properties' this by adding lines like
2741 #+PROPERTY: NAME VALUE"
2742 :group 'org-properties
2743 :type '(repeat
2744 (cons (string :tag "Property")
2745 (string :tag "Value"))))
2747 (defvar org-file-properties nil
2748 "List of property/value pairs that can be inherited by any entry.
2749 Valid for the current buffer.
2750 This variable is populated from #+PROPERTY lines.")
2751 (make-variable-buffer-local 'org-file-properties)
2753 (defgroup org-agenda nil
2754 "Options concerning agenda views in Org-mode."
2755 :tag "Org Agenda"
2756 :group 'org)
2758 (defvar org-category nil
2759 "Variable used by org files to set a category for agenda display.
2760 Such files should use a file variable to set it, for example
2762 # -*- mode: org; org-category: \"ELisp\"
2764 or contain a special line
2766 #+CATEGORY: ELisp
2768 If the file does not specify a category, then file's base name
2769 is used instead.")
2770 (make-variable-buffer-local 'org-category)
2771 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2773 (defcustom org-agenda-files nil
2774 "The files to be used for agenda display.
2775 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2776 \\[org-remove-file]. You can also use customize to edit the list.
2778 If an entry is a directory, all files in that directory that are matched by
2779 `org-agenda-file-regexp' will be part of the file list.
2781 If the value of the variable is not a list but a single file name, then
2782 the list of agenda files is actually stored and maintained in that file, one
2783 agenda file per line. In this file paths can be given relative to
2784 `org-directory'. Tilde expansion and environment variable substitution
2785 are also made."
2786 :group 'org-agenda
2787 :type '(choice
2788 (repeat :tag "List of files and directories" file)
2789 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2791 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2792 "Regular expression to match files for `org-agenda-files'.
2793 If any element in the list in that variable contains a directory instead
2794 of a normal file, all files in that directory that are matched by this
2795 regular expression will be included."
2796 :group 'org-agenda
2797 :type 'regexp)
2799 (defcustom org-agenda-text-search-extra-files nil
2800 "List of extra files to be searched by text search commands.
2801 These files will be search in addition to the agenda files by the
2802 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2803 Note that these files will only be searched for text search commands,
2804 not for the other agenda views like todo lists, tag searches or the weekly
2805 agenda. This variable is intended to list notes and possibly archive files
2806 that should also be searched by these two commands.
2807 In fact, if the first element in the list is the symbol `agenda-archives',
2808 than all archive files of all agenda files will be added to the search
2809 scope."
2810 :group 'org-agenda
2811 :type '(set :greedy t
2812 (const :tag "Agenda Archives" agenda-archives)
2813 (repeat :inline t (file))))
2815 (if (fboundp 'defvaralias)
2816 (defvaralias 'org-agenda-multi-occur-extra-files
2817 'org-agenda-text-search-extra-files))
2819 (defcustom org-agenda-skip-unavailable-files nil
2820 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2821 A nil value means to remove them, after a query, from the list."
2822 :group 'org-agenda
2823 :type 'boolean)
2825 (defcustom org-calendar-to-agenda-key [?c]
2826 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2827 The command `org-calendar-goto-agenda' will be bound to this key. The
2828 default is the character `c' because then `c' can be used to switch back and
2829 forth between agenda and calendar."
2830 :group 'org-agenda
2831 :type 'sexp)
2833 (defcustom org-calendar-agenda-action-key [?k]
2834 "The key to be installed in `calendar-mode-map' for agenda-action.
2835 The command `org-agenda-action' will be bound to this key. The
2836 default is the character `k' because we use the same key in the agenda."
2837 :group 'org-agenda
2838 :type 'sexp)
2840 (defcustom org-calendar-insert-diary-entry-key [?i]
2841 "The key to be installed in `calendar-mode-map' for adding diary entries.
2842 This option is irrelevant until `org-agenda-diary-file' has been configured
2843 to point to an Org-mode file. When that is the case, the command
2844 `org-agenda-diary-entry' will be bound to the key given here, by default
2845 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2846 if you want to continue doing this, you need to change this to a different
2847 key."
2848 :group 'org-agenda
2849 :type 'sexp)
2851 (defcustom org-agenda-diary-file 'diary-file
2852 "File to which to add new entries with the `i' key in agenda and calendar.
2853 When this is the symbol `diary-file', the functionality in the Emacs
2854 calendar will be used to add entries to the `diary-file'. But when this
2855 points to a file, `org-agenda-diary-entry' will be used instead."
2856 :group 'org-agenda
2857 :type '(choice
2858 (const :tag "The standard Emacs diary file" diary-file)
2859 (file :tag "Special Org file diary entries")))
2861 (eval-after-load "calendar"
2862 '(progn
2863 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2864 'org-calendar-goto-agenda)
2865 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2866 'org-agenda-action)
2867 (add-hook 'calendar-mode-hook
2868 (lambda ()
2869 (unless (eq org-agenda-diary-file 'diary-file)
2870 (define-key calendar-mode-map
2871 org-calendar-insert-diary-entry-key
2872 'org-agenda-diary-entry))))))
2874 (defgroup org-latex nil
2875 "Options for embedding LaTeX code into Org-mode."
2876 :tag "Org LaTeX"
2877 :group 'org)
2879 (defcustom org-format-latex-options
2880 '(:foreground default :background default :scale 1.0
2881 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2882 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2883 "Options for creating images from LaTeX fragments.
2884 This is a property list with the following properties:
2885 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2886 `default' means use the foreground of the default face.
2887 :background the background color, or \"Transparent\".
2888 `default' means use the background of the default face.
2889 :scale a scaling factor for the size of the images.
2890 :html-foreground, :html-background, :html-scale
2891 the same numbers for HTML export.
2892 :matchers a list indicating which matchers should be used to
2893 find LaTeX fragments. Valid members of this list are:
2894 \"begin\" find environments
2895 \"$1\" find single characters surrounded by $.$
2896 \"$\" find math expressions surrounded by $...$
2897 \"$$\" find math expressions surrounded by $$....$$
2898 \"\\(\" find math expressions surrounded by \\(...\\)
2899 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2900 :group 'org-latex
2901 :type 'plist)
2903 (defcustom org-format-latex-signal-error t
2904 "Non-nil means signal an error when image creation of LaTeX snippets fails.
2905 When nil, just push out a message."
2906 :group 'org-latex
2907 :type 'boolean)
2909 (defcustom org-format-latex-header "\\documentclass{article}
2910 \\usepackage{amssymb}
2911 \\usepackage[usenames]{color}
2912 \\usepackage{amsmath}
2913 \\usepackage{latexsym}
2914 \\usepackage[mathscr]{eucal}
2915 \\pagestyle{empty} % do not remove
2916 % The settings below are copied from fullpage.sty
2917 \\setlength{\\textwidth}{\\paperwidth}
2918 \\addtolength{\\textwidth}{-3cm}
2919 \\setlength{\\oddsidemargin}{1.5cm}
2920 \\addtolength{\\oddsidemargin}{-2.54cm}
2921 \\setlength{\\evensidemargin}{\\oddsidemargin}
2922 \\setlength{\\textheight}{\\paperheight}
2923 \\addtolength{\\textheight}{-\\headheight}
2924 \\addtolength{\\textheight}{-\\headsep}
2925 \\addtolength{\\textheight}{-\\footskip}
2926 \\addtolength{\\textheight}{-3cm}
2927 \\setlength{\\topmargin}{1.5cm}
2928 \\addtolength{\\topmargin}{-2.54cm}"
2929 "The document header used for processing LaTeX fragments.
2930 It is imperative that this header make sure that no page number
2931 appears on the page."
2932 :group 'org-latex
2933 :type 'string)
2935 (defvar org-format-latex-header-extra nil)
2937 ;; The following variable is defined here because is it also used
2938 ;; when formatting latex fragments. Originally it was part of the
2939 ;; LaTeX exporter, which is why the name includes "export".
2940 (defcustom org-export-latex-packages-alist nil
2941 "Alist of packages to be inserted in the header.
2942 Each cell is of the format \( \"option\" . \"package\" \)."
2943 :group 'org-export-latex
2944 :type '(repeat
2945 (list
2946 (string :tag "option")
2947 (string :tag "package"))))
2949 (defgroup org-appearance nil
2950 "Settings for Org-mode appearance."
2951 :tag "Org Appearance"
2952 :group 'org)
2954 (defcustom org-level-color-stars-only nil
2955 "Non-nil means fontify only the stars in each headline.
2956 When nil, the entire headline is fontified.
2957 Changing it requires restart of `font-lock-mode' to become effective
2958 also in regions already fontified."
2959 :group 'org-appearance
2960 :type 'boolean)
2962 (defcustom org-hide-leading-stars nil
2963 "Non-nil means hide the first N-1 stars in a headline.
2964 This works by using the face `org-hide' for these stars. This
2965 face is white for a light background, and black for a dark
2966 background. You may have to customize the face `org-hide' to
2967 make this work.
2968 Changing it requires restart of `font-lock-mode' to become effective
2969 also in regions already fontified.
2970 You may also set this on a per-file basis by adding one of the following
2971 lines to the buffer:
2973 #+STARTUP: hidestars
2974 #+STARTUP: showstars"
2975 :group 'org-appearance
2976 :type 'boolean)
2978 (defcustom org-hidden-keywords nil
2979 "List of keywords that should be hidden when typed in the org buffer.
2980 For example, add #+TITLE to this list in order to make the
2981 document title appear in the buffer without the initial #+TITLE:
2982 keyword."
2983 :group 'org-appearance
2984 :type '(set (const :tag "#+AUTHOR" author)
2985 (const :tag "#+DATE" date)
2986 (const :tag "#+EMAIL" email)
2987 (const :tag "#+TITLE" title)))
2989 (defcustom org-fontify-done-headline nil
2990 "Non-nil means change the face of a headline if it is marked DONE.
2991 Normally, only the TODO/DONE keyword indicates the state of a headline.
2992 When this is non-nil, the headline after the keyword is set to the
2993 `org-headline-done' as an additional indication."
2994 :group 'org-appearance
2995 :type 'boolean)
2997 (defcustom org-fontify-emphasized-text t
2998 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2999 Changing this variable requires a restart of Emacs to take effect."
3000 :group 'org-appearance
3001 :type 'boolean)
3003 (defcustom org-fontify-whole-heading-line nil
3004 "Non-nil means fontify the whole line for headings.
3005 This is useful when setting a background color for the
3006 org-level-* faces."
3007 :group 'org-appearance
3008 :type 'boolean)
3010 (defcustom org-highlight-latex-fragments-and-specials nil
3011 "Non-nil means fontify what is treated specially by the exporters."
3012 :group 'org-appearance
3013 :type 'boolean)
3015 (defcustom org-hide-emphasis-markers nil
3016 "Non-nil mean font-lock should hide the emphasis marker characters."
3017 :group 'org-appearance
3018 :type 'boolean)
3020 (defvar org-emph-re nil
3021 "Regular expression for matching emphasis.")
3022 (defvar org-verbatim-re nil
3023 "Regular expression for matching verbatim text.")
3024 (defvar org-emphasis-regexp-components) ; defined just below
3025 (defvar org-emphasis-alist) ; defined just below
3026 (defun org-set-emph-re (var val)
3027 "Set variable and compute the emphasis regular expression."
3028 (set var val)
3029 (when (and (boundp 'org-emphasis-alist)
3030 (boundp 'org-emphasis-regexp-components)
3031 org-emphasis-alist org-emphasis-regexp-components)
3032 (let* ((e org-emphasis-regexp-components)
3033 (pre (car e))
3034 (post (nth 1 e))
3035 (border (nth 2 e))
3036 (body (nth 3 e))
3037 (nl (nth 4 e))
3038 (body1 (concat body "*?"))
3039 (markers (mapconcat 'car org-emphasis-alist ""))
3040 (vmarkers (mapconcat
3041 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3042 org-emphasis-alist "")))
3043 ;; make sure special characters appear at the right position in the class
3044 (if (string-match "\\^" markers)
3045 (setq markers (concat (replace-match "" t t markers) "^")))
3046 (if (string-match "-" markers)
3047 (setq markers (concat (replace-match "" t t markers) "-")))
3048 (if (string-match "\\^" vmarkers)
3049 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3050 (if (string-match "-" vmarkers)
3051 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3052 (if (> nl 0)
3053 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3054 (int-to-string nl) "\\}")))
3055 ;; Make the regexp
3056 (setq org-emph-re
3057 (concat "\\([" pre "]\\|^\\)"
3058 "\\("
3059 "\\([" markers "]\\)"
3060 "\\("
3061 "[^" border "]\\|"
3062 "[^" border "]"
3063 body1
3064 "[^" border "]"
3065 "\\)"
3066 "\\3\\)"
3067 "\\([" post "]\\|$\\)"))
3068 (setq org-verbatim-re
3069 (concat "\\([" pre "]\\|^\\)"
3070 "\\("
3071 "\\([" vmarkers "]\\)"
3072 "\\("
3073 "[^" border "]\\|"
3074 "[^" border "]"
3075 body1
3076 "[^" border "]"
3077 "\\)"
3078 "\\3\\)"
3079 "\\([" post "]\\|$\\)")))))
3081 (defcustom org-emphasis-regexp-components
3082 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3083 "Components used to build the regular expression for emphasis.
3084 This is a list with 6 entries. Terminology: In an emphasis string
3085 like \" *strong word* \", we call the initial space PREMATCH, the final
3086 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3087 and \"trong wor\" is the body. The different components in this variable
3088 specify what is allowed/forbidden in each part:
3090 pre Chars allowed as prematch. Beginning of line will be allowed too.
3091 post Chars allowed as postmatch. End of line will be allowed too.
3092 border The chars *forbidden* as border characters.
3093 body-regexp A regexp like \".\" to match a body character. Don't use
3094 non-shy groups here, and don't allow newline here.
3095 newline The maximum number of newlines allowed in an emphasis exp.
3097 Use customize to modify this, or restart Emacs after changing it."
3098 :group 'org-appearance
3099 :set 'org-set-emph-re
3100 :type '(list
3101 (sexp :tag "Allowed chars in pre ")
3102 (sexp :tag "Allowed chars in post ")
3103 (sexp :tag "Forbidden chars in border ")
3104 (sexp :tag "Regexp for body ")
3105 (integer :tag "number of newlines allowed")
3106 (option (boolean :tag "Please ignore this button"))))
3108 (defcustom org-emphasis-alist
3109 `(("*" bold "<b>" "</b>")
3110 ("/" italic "<i>" "</i>")
3111 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3112 ("=" org-code "<code>" "</code>" verbatim)
3113 ("~" org-verbatim "<code>" "</code>" verbatim)
3114 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3115 "<del>" "</del>")
3117 "Special syntax for emphasized text.
3118 Text starting and ending with a special character will be emphasized, for
3119 example *bold*, _underlined_ and /italic/. This variable sets the marker
3120 characters, the face to be used by font-lock for highlighting in Org-mode
3121 Emacs buffers, and the HTML tags to be used for this.
3122 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3123 Use customize to modify this, or restart Emacs after changing it."
3124 :group 'org-appearance
3125 :set 'org-set-emph-re
3126 :type '(repeat
3127 (list
3128 (string :tag "Marker character")
3129 (choice
3130 (face :tag "Font-lock-face")
3131 (plist :tag "Face property list"))
3132 (string :tag "HTML start tag")
3133 (string :tag "HTML end tag")
3134 (option (const verbatim)))))
3136 (defvar org-protecting-blocks
3137 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3138 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3139 This is needed for font-lock setup.")
3141 ;;; Miscellaneous options
3143 (defgroup org-completion nil
3144 "Completion in Org-mode."
3145 :tag "Org Completion"
3146 :group 'org)
3148 (defcustom org-completion-use-ido nil
3149 "Non-nil means use ido completion wherever possible.
3150 Note that `ido-mode' must be active for this variable to be relevant.
3151 If you decide to turn this variable on, you might well want to turn off
3152 `org-outline-path-complete-in-steps'.
3153 See also `org-completion-use-iswitchb'."
3154 :group 'org-completion
3155 :type 'boolean)
3157 (defcustom org-completion-use-iswitchb nil
3158 "Non-nil means use iswitchb completion wherever possible.
3159 Note that `iswitchb-mode' must be active for this variable to be relevant.
3160 If you decide to turn this variable on, you might well want to turn off
3161 `org-outline-path-complete-in-steps'.
3162 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3163 :group 'org-completion
3164 :type 'boolean)
3166 (defcustom org-completion-fallback-command 'hippie-expand
3167 "The expansion command called by \\[org-complete] in normal context.
3168 Normal means no org-mode-specific context."
3169 :group 'org-completion
3170 :type 'function)
3172 ;;; Functions and variables from their packages
3173 ;; Declared here to avoid compiler warnings
3175 ;; XEmacs only
3176 (defvar outline-mode-menu-heading)
3177 (defvar outline-mode-menu-show)
3178 (defvar outline-mode-menu-hide)
3179 (defvar zmacs-regions) ; XEmacs regions
3181 ;; Emacs only
3182 (defvar mark-active)
3184 ;; Various packages
3185 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3186 (declare-function calendar-forward-day "cal-move" (arg))
3187 (declare-function calendar-goto-date "cal-move" (date))
3188 (declare-function calendar-goto-today "cal-move" ())
3189 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3190 (defvar calc-embedded-close-formula)
3191 (defvar calc-embedded-open-formula)
3192 (declare-function cdlatex-tab "ext:cdlatex" ())
3193 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3194 (defvar font-lock-unfontify-region-function)
3195 (declare-function iswitchb-read-buffer "iswitchb"
3196 (prompt &optional default require-match start matches-set))
3197 (defvar iswitchb-temp-buflist)
3198 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3199 (defvar org-agenda-tags-todo-honor-ignore-options)
3200 (declare-function org-agenda-skip "org-agenda" ())
3201 (declare-function
3202 org-format-agenda-item "org-agenda"
3203 (extra txt &optional category tags dotime noprefix remove-re habitp))
3204 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3205 (declare-function org-agenda-change-all-lines "org-agenda"
3206 (newhead hdmarker &optional fixface just-this))
3207 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3208 (declare-function org-agenda-maybe-redo "org-agenda" ())
3209 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3210 (beg end))
3211 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3212 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3213 "org-agenda" (&optional end))
3214 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3215 (declare-function org-indent-mode "org-indent" (&optional arg))
3216 (declare-function parse-time-string "parse-time" (string))
3217 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3218 (defvar remember-data-file)
3219 (defvar texmathp-why)
3220 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3221 (declare-function table--at-cell-p "table" (position &optional object at-column))
3223 (defvar w3m-current-url)
3224 (defvar w3m-current-title)
3226 (defvar org-latex-regexps)
3228 ;;; Autoload and prepare some org modules
3230 ;; Some table stuff that needs to be defined here, because it is used
3231 ;; by the functions setting up org-mode or checking for table context.
3233 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3234 "Detects an org-type or table-type table.")
3235 (defconst org-table-line-regexp "^[ \t]*|"
3236 "Detects an org-type table line.")
3237 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3238 "Detects an org-type table line.")
3239 (defconst org-table-hline-regexp "^[ \t]*|-"
3240 "Detects an org-type table hline.")
3241 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3242 "Detects a table-type table hline.")
3243 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3244 "Searching from within a table (any type) this finds the first line
3245 outside the table.")
3247 ;; Autoload the functions in org-table.el that are needed by functions here.
3249 (eval-and-compile
3250 (org-autoload "org-table"
3251 '(org-table-align org-table-begin org-table-blank-field
3252 org-table-convert org-table-convert-region org-table-copy-down
3253 org-table-copy-region org-table-create
3254 org-table-create-or-convert-from-region
3255 org-table-create-with-table.el org-table-current-dline
3256 org-table-cut-region org-table-delete-column org-table-edit-field
3257 org-table-edit-formulas org-table-end org-table-eval-formula
3258 org-table-export org-table-field-info
3259 org-table-get-stored-formulas org-table-goto-column
3260 org-table-hline-and-move org-table-import org-table-insert-column
3261 org-table-insert-hline org-table-insert-row org-table-iterate
3262 org-table-justify-field-maybe org-table-kill-row
3263 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3264 org-table-move-column org-table-move-column-left
3265 org-table-move-column-right org-table-move-row
3266 org-table-move-row-down org-table-move-row-up
3267 org-table-next-field org-table-next-row org-table-paste-rectangle
3268 org-table-previous-field org-table-recalculate
3269 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3270 org-table-toggle-coordinate-overlays
3271 org-table-toggle-formula-debugger org-table-wrap-region
3272 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3274 (defun org-at-table-p (&optional table-type)
3275 "Return t if the cursor is inside an org-type table.
3276 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3277 (if org-enable-table-editor
3278 (save-excursion
3279 (beginning-of-line 1)
3280 (looking-at (if table-type org-table-any-line-regexp
3281 org-table-line-regexp)))
3282 nil))
3283 (defsubst org-table-p () (org-at-table-p))
3285 (defun org-at-table.el-p ()
3286 "Return t if and only if we are at a table.el table."
3287 (and (org-at-table-p 'any)
3288 (save-excursion
3289 (goto-char (org-table-begin 'any))
3290 (looking-at org-table1-hline-regexp))))
3291 (defun org-table-recognize-table.el ()
3292 "If there is a table.el table nearby, recognize it and move into it."
3293 (if org-table-tab-recognizes-table.el
3294 (if (org-at-table.el-p)
3295 (progn
3296 (beginning-of-line 1)
3297 (if (looking-at org-table-dataline-regexp)
3299 (if (looking-at org-table1-hline-regexp)
3300 (progn
3301 (beginning-of-line 2)
3302 (if (looking-at org-table-any-border-regexp)
3303 (beginning-of-line -1)))))
3304 (if (re-search-forward "|" (org-table-end t) t)
3305 (progn
3306 (require 'table)
3307 (if (table--at-cell-p (point))
3309 (message "recognizing table.el table...")
3310 (table-recognize-table)
3311 (message "recognizing table.el table...done")))
3312 (error "This should not happen..."))
3314 nil)
3315 nil))
3317 (defun org-at-table-hline-p ()
3318 "Return t if the cursor is inside a hline in a table."
3319 (if org-enable-table-editor
3320 (save-excursion
3321 (beginning-of-line 1)
3322 (looking-at org-table-hline-regexp))
3323 nil))
3325 (defvar org-table-clean-did-remove-column nil)
3327 (defun org-table-map-tables (function)
3328 "Apply FUNCTION to the start of all tables in the buffer."
3329 (save-excursion
3330 (save-restriction
3331 (widen)
3332 (goto-char (point-min))
3333 (while (re-search-forward org-table-any-line-regexp nil t)
3334 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3335 (beginning-of-line 1)
3336 (when (looking-at org-table-line-regexp)
3337 (save-excursion (funcall function))
3338 (or (looking-at org-table-line-regexp)
3339 (forward-char 1)))
3340 (re-search-forward org-table-any-border-regexp nil 1))))
3341 (message "Mapping tables: done"))
3343 ;; Declare and autoload functions from org-exp.el & Co
3345 (declare-function org-default-export-plist "org-exp")
3346 (declare-function org-infile-export-plist "org-exp")
3347 (declare-function org-get-current-options "org-exp")
3348 (eval-and-compile
3349 (org-autoload "org-exp"
3350 '(org-export org-export-visible
3351 org-insert-export-options-template
3352 org-table-clean-before-export))
3353 (org-autoload "org-ascii"
3354 '(org-export-as-ascii org-export-ascii-preprocess
3355 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3356 org-export-region-as-ascii))
3357 (org-autoload "org-latex"
3358 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3359 org-replace-region-by-latex org-export-region-as-latex
3360 org-export-as-latex org-export-as-pdf
3361 org-export-as-pdf-and-open))
3362 (org-autoload "org-html"
3363 '(org-export-as-html-and-open
3364 org-export-as-html-batch org-export-as-html-to-buffer
3365 org-replace-region-by-html org-export-region-as-html
3366 org-export-as-html))
3367 (org-autoload "org-docbook"
3368 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3369 org-replace-region-by-docbook org-export-region-as-docbook
3370 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3371 org-export-as-docbook))
3372 (org-autoload "org-icalendar"
3373 '(org-export-icalendar-this-file
3374 org-export-icalendar-all-agenda-files
3375 org-export-icalendar-combine-agenda-files))
3376 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3377 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3379 ;; Declare and autoload functions from org-agenda.el
3381 (eval-and-compile
3382 (org-autoload "org-agenda"
3383 '(org-agenda org-agenda-list org-search-view
3384 org-todo-list org-tags-view org-agenda-list-stuck-projects
3385 org-diary org-agenda-to-appt
3386 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3388 ;; Autoload org-remember
3390 (eval-and-compile
3391 (org-autoload "org-remember"
3392 '(org-remember-insinuate org-remember-annotation
3393 org-remember-apply-template org-remember org-remember-handler)))
3395 ;; Autoload org-clock.el
3398 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3399 (beg end))
3400 (declare-function org-clock-update-mode-line "org-clock" ())
3401 (declare-function org-resolve-clocks "org-clock"
3402 (&optional also-non-dangling-p prompt last-valid))
3403 (defvar org-clock-start-time)
3404 (defvar org-clock-marker (make-marker)
3405 "Marker recording the last clock-in.")
3406 (defvar org-clock-hd-marker (make-marker)
3407 "Marker recording the last clock-in, but the headline position.")
3408 (defvar org-clock-heading ""
3409 "The heading of the current clock entry.")
3410 (defun org-clock-is-active ()
3411 "Return non-nil if clock is currently running.
3412 The return value is actually the clock marker."
3413 (marker-buffer org-clock-marker))
3415 (eval-and-compile
3416 (org-autoload
3417 "org-clock"
3418 '(org-clock-in org-clock-out org-clock-cancel
3419 org-clock-goto org-clock-sum org-clock-display
3420 org-clock-remove-overlays org-clock-report
3421 org-clocktable-shift org-dblock-write:clocktable
3422 org-get-clocktable org-resolve-clocks)))
3424 (defun org-clock-update-time-maybe ()
3425 "If this is a CLOCK line, update it and return t.
3426 Otherwise, return nil."
3427 (interactive)
3428 (save-excursion
3429 (beginning-of-line 1)
3430 (skip-chars-forward " \t")
3431 (when (looking-at org-clock-string)
3432 (let ((re (concat "[ \t]*" org-clock-string
3433 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3434 "\\([ \t]*=>.*\\)?\\)?"))
3435 ts te h m s neg)
3436 (cond
3437 ((not (looking-at re))
3438 nil)
3439 ((not (match-end 2))
3440 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3441 (> org-clock-marker (point))
3442 (<= org-clock-marker (point-at-eol)))
3443 ;; The clock is running here
3444 (setq org-clock-start-time
3445 (apply 'encode-time
3446 (org-parse-time-string (match-string 1))))
3447 (org-clock-update-mode-line)))
3449 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3450 (end-of-line 1)
3451 (setq ts (match-string 1)
3452 te (match-string 3))
3453 (setq s (- (org-float-time
3454 (apply 'encode-time (org-parse-time-string te)))
3455 (org-float-time
3456 (apply 'encode-time (org-parse-time-string ts))))
3457 neg (< s 0)
3458 s (abs s)
3459 h (floor (/ s 3600))
3460 s (- s (* 3600 h))
3461 m (floor (/ s 60))
3462 s (- s (* 60 s)))
3463 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3464 t))))))
3466 (defun org-check-running-clock ()
3467 "Check if the current buffer contains the running clock.
3468 If yes, offer to stop it and to save the buffer with the changes."
3469 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3470 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3471 (buffer-name))))
3472 (org-clock-out)
3473 (when (y-or-n-p "Save changed buffer?")
3474 (save-buffer))))
3476 (defun org-clocktable-try-shift (dir n)
3477 "Check if this line starts a clock table, if yes, shift the time block."
3478 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3479 (org-clocktable-shift dir n)))
3481 ;; Autoload org-timer.el
3483 (eval-and-compile
3484 (org-autoload
3485 "org-timer"
3486 '(org-timer-start org-timer org-timer-item
3487 org-timer-change-times-in-region
3488 org-timer-set-timer
3489 org-timer-reset-timers
3490 org-timer-show-remaining-time)))
3492 ;; Autoload org-feed.el
3494 (eval-and-compile
3495 (org-autoload
3496 "org-feed"
3497 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3500 ;; Autoload org-indent.el
3502 ;; Define the variable already here, to make sure we have it.
3503 (defvar org-indent-mode nil
3504 "Non-nil if Org-Indent mode is enabled.
3505 Use the command `org-indent-mode' to change this variable.")
3507 (eval-and-compile
3508 (org-autoload
3509 "org-indent"
3510 '(org-indent-mode)))
3512 ;; Autoload org-mobile.el
3514 (eval-and-compile
3515 (org-autoload
3516 "org-mobile"
3517 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3519 ;; Autoload archiving code
3520 ;; The stuff that is needed for cycling and tags has to be defined here.
3522 (defgroup org-archive nil
3523 "Options concerning archiving in Org-mode."
3524 :tag "Org Archive"
3525 :group 'org-structure)
3527 (defcustom org-archive-location "%s_archive::"
3528 "The location where subtrees should be archived.
3530 The value of this variable is a string, consisting of two parts,
3531 separated by a double-colon. The first part is a filename and
3532 the second part is a headline.
3534 When the filename is omitted, archiving happens in the same file.
3535 %s in the filename will be replaced by the current file
3536 name (without the directory part). Archiving to a different file
3537 is useful to keep archived entries from contributing to the
3538 Org-mode Agenda.
3540 The archived entries will be filed as subtrees of the specified
3541 headline. When the headline is omitted, the subtrees are simply
3542 filed away at the end of the file, as top-level entries. Also in
3543 the heading you can use %s to represent the file name, this can be
3544 useful when using the same archive for a number of different files.
3546 Here are a few examples:
3547 \"%s_archive::\"
3548 If the current file is Projects.org, archive in file
3549 Projects.org_archive, as top-level trees. This is the default.
3551 \"::* Archived Tasks\"
3552 Archive in the current file, under the top-level headline
3553 \"* Archived Tasks\".
3555 \"~/org/archive.org::\"
3556 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3558 \"~/org/archive.org::From %s\"
3559 Archive in file ~/org/archive.org (absolute path), under headlines
3560 \"From FILENAME\" where file name is the current file name.
3562 \"basement::** Finished Tasks\"
3563 Archive in file ./basement (relative path), as level 3 trees
3564 below the level 2 heading \"** Finished Tasks\".
3566 You may set this option on a per-file basis by adding to the buffer a
3567 line like
3569 #+ARCHIVE: basement::** Finished Tasks
3571 You may also define it locally for a subtree by setting an ARCHIVE property
3572 in the entry. If such a property is found in an entry, or anywhere up
3573 the hierarchy, it will be used."
3574 :group 'org-archive
3575 :type 'string)
3577 (defcustom org-archive-tag "ARCHIVE"
3578 "The tag that marks a subtree as archived.
3579 An archived subtree does not open during visibility cycling, and does
3580 not contribute to the agenda listings.
3581 After changing this, font-lock must be restarted in the relevant buffers to
3582 get the proper fontification."
3583 :group 'org-archive
3584 :group 'org-keywords
3585 :type 'string)
3587 (defcustom org-agenda-skip-archived-trees t
3588 "Non-nil means the agenda will skip any items located in archived trees.
3589 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3590 variable is no longer recommended, you should leave it at the value t.
3591 Instead, use the key `v' to cycle the archives-mode in the agenda."
3592 :group 'org-archive
3593 :group 'org-agenda-skip
3594 :type 'boolean)
3596 (defcustom org-columns-skip-archived-trees t
3597 "Non-nil means ignore archived trees when creating column view."
3598 :group 'org-archive
3599 :group 'org-properties
3600 :type 'boolean)
3602 (defcustom org-cycle-open-archived-trees nil
3603 "Non-nil means `org-cycle' will open archived trees.
3604 An archived tree is a tree marked with the tag ARCHIVE.
3605 When nil, archived trees will stay folded. You can still open them with
3606 normal outline commands like `show-all', but not with the cycling commands."
3607 :group 'org-archive
3608 :group 'org-cycle
3609 :type 'boolean)
3611 (defcustom org-sparse-tree-open-archived-trees nil
3612 "Non-nil means sparse tree construction shows matches in archived trees.
3613 When nil, matches in these trees are highlighted, but the trees are kept in
3614 collapsed state."
3615 :group 'org-archive
3616 :group 'org-sparse-trees
3617 :type 'boolean)
3619 (defun org-cycle-hide-archived-subtrees (state)
3620 "Re-hide all archived subtrees after a visibility state change."
3621 (when (and (not org-cycle-open-archived-trees)
3622 (not (memq state '(overview folded))))
3623 (save-excursion
3624 (let* ((globalp (memq state '(contents all)))
3625 (beg (if globalp (point-min) (point)))
3626 (end (if globalp (point-max) (org-end-of-subtree t))))
3627 (org-hide-archived-subtrees beg end)
3628 (goto-char beg)
3629 (if (looking-at (concat ".*:" org-archive-tag ":"))
3630 (message "%s" (substitute-command-keys
3631 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3633 (defun org-force-cycle-archived ()
3634 "Cycle subtree even if it is archived."
3635 (interactive)
3636 (setq this-command 'org-cycle)
3637 (let ((org-cycle-open-archived-trees t))
3638 (call-interactively 'org-cycle)))
3640 (defun org-hide-archived-subtrees (beg end)
3641 "Re-hide all archived subtrees after a visibility state change."
3642 (save-excursion
3643 (let* ((re (concat ":" org-archive-tag ":")))
3644 (goto-char beg)
3645 (while (re-search-forward re end t)
3646 (when (org-on-heading-p)
3647 (org-flag-subtree t)
3648 (org-end-of-subtree t))))))
3650 (defun org-flag-subtree (flag)
3651 (save-excursion
3652 (org-back-to-heading t)
3653 (outline-end-of-heading)
3654 (outline-flag-region (point)
3655 (progn (org-end-of-subtree t) (point))
3656 flag)))
3658 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3660 (eval-and-compile
3661 (org-autoload "org-archive"
3662 '(org-add-archive-files org-archive-subtree
3663 org-archive-to-archive-sibling org-toggle-archive-tag
3664 org-archive-subtree-default
3665 org-archive-subtree-default-with-confirmation)))
3667 ;; Autoload Column View Code
3669 (declare-function org-columns-number-to-string "org-colview")
3670 (declare-function org-columns-get-format-and-top-level "org-colview")
3671 (declare-function org-columns-compute "org-colview")
3673 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3674 '(org-columns-number-to-string org-columns-get-format-and-top-level
3675 org-columns-compute org-agenda-columns org-columns-remove-overlays
3676 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3678 ;; Autoload ID code
3680 (declare-function org-id-store-link "org-id")
3681 (declare-function org-id-locations-load "org-id")
3682 (declare-function org-id-locations-save "org-id")
3683 (defvar org-id-track-globally)
3684 (org-autoload "org-id"
3685 '(org-id-get-create org-id-new org-id-copy org-id-get
3686 org-id-get-with-outline-path-completion
3687 org-id-get-with-outline-drilling
3688 org-id-goto org-id-find org-id-store-link))
3690 ;; Autoload Plotting Code
3692 (org-autoload "org-plot"
3693 '(org-plot/gnuplot))
3695 ;;; Variables for pre-computed regular expressions, all buffer local
3697 (defvar org-drawer-regexp nil
3698 "Matches first line of a hidden block.")
3699 (make-variable-buffer-local 'org-drawer-regexp)
3700 (defvar org-todo-regexp nil
3701 "Matches any of the TODO state keywords.")
3702 (make-variable-buffer-local 'org-todo-regexp)
3703 (defvar org-not-done-regexp nil
3704 "Matches any of the TODO state keywords except the last one.")
3705 (make-variable-buffer-local 'org-not-done-regexp)
3706 (defvar org-not-done-heading-regexp nil
3707 "Matches a TODO headline that is not done.")
3708 (make-variable-buffer-local 'org-not-done-regexp)
3709 (defvar org-todo-line-regexp nil
3710 "Matches a headline and puts TODO state into group 2 if present.")
3711 (make-variable-buffer-local 'org-todo-line-regexp)
3712 (defvar org-complex-heading-regexp nil
3713 "Matches a headline and puts everything into groups:
3714 group 1: the stars
3715 group 2: The todo keyword, maybe
3716 group 3: Priority cookie
3717 group 4: True headline
3718 group 5: Tags")
3719 (make-variable-buffer-local 'org-complex-heading-regexp)
3720 (defvar org-complex-heading-regexp-format nil)
3721 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3722 (defvar org-todo-line-tags-regexp nil
3723 "Matches a headline and puts TODO state into group 2 if present.
3724 Also put tags into group 4 if tags are present.")
3725 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3726 (defvar org-nl-done-regexp nil
3727 "Matches newline followed by a headline with the DONE keyword.")
3728 (make-variable-buffer-local 'org-nl-done-regexp)
3729 (defvar org-looking-at-done-regexp nil
3730 "Matches the DONE keyword a point.")
3731 (make-variable-buffer-local 'org-looking-at-done-regexp)
3732 (defvar org-ds-keyword-length 12
3733 "Maximum length of the Deadline and SCHEDULED keywords.")
3734 (make-variable-buffer-local 'org-ds-keyword-length)
3735 (defvar org-deadline-regexp nil
3736 "Matches the DEADLINE keyword.")
3737 (make-variable-buffer-local 'org-deadline-regexp)
3738 (defvar org-deadline-time-regexp nil
3739 "Matches the DEADLINE keyword together with a time stamp.")
3740 (make-variable-buffer-local 'org-deadline-time-regexp)
3741 (defvar org-deadline-line-regexp nil
3742 "Matches the DEADLINE keyword and the rest of the line.")
3743 (make-variable-buffer-local 'org-deadline-line-regexp)
3744 (defvar org-scheduled-regexp nil
3745 "Matches the SCHEDULED keyword.")
3746 (make-variable-buffer-local 'org-scheduled-regexp)
3747 (defvar org-scheduled-time-regexp nil
3748 "Matches the SCHEDULED keyword together with a time stamp.")
3749 (make-variable-buffer-local 'org-scheduled-time-regexp)
3750 (defvar org-closed-time-regexp nil
3751 "Matches the CLOSED keyword together with a time stamp.")
3752 (make-variable-buffer-local 'org-closed-time-regexp)
3754 (defvar org-keyword-time-regexp nil
3755 "Matches any of the 4 keywords, together with the time stamp.")
3756 (make-variable-buffer-local 'org-keyword-time-regexp)
3757 (defvar org-keyword-time-not-clock-regexp nil
3758 "Matches any of the 3 keywords, together with the time stamp.")
3759 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3760 (defvar org-maybe-keyword-time-regexp nil
3761 "Matches a timestamp, possibly preceeded by a keyword.")
3762 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3763 (defvar org-planning-or-clock-line-re nil
3764 "Matches a line with planning or clock info.")
3765 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3766 (defvar org-all-time-keywords nil
3767 "List of time keywords.")
3768 (make-variable-buffer-local 'org-all-time-keywords)
3770 (defconst org-plain-time-of-day-regexp
3771 (concat
3772 "\\(\\<[012]?[0-9]"
3773 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3774 "\\(--?"
3775 "\\(\\<[012]?[0-9]"
3776 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3777 "\\)?")
3778 "Regular expression to match a plain time or time range.
3779 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3780 groups carry important information:
3781 0 the full match
3782 1 the first time, range or not
3783 8 the second time, if it is a range.")
3785 (defconst org-plain-time-extension-regexp
3786 (concat
3787 "\\(\\<[012]?[0-9]"
3788 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3789 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3790 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3791 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3792 groups carry important information:
3793 0 the full match
3794 7 hours of duration
3795 9 minutes of duration")
3797 (defconst org-stamp-time-of-day-regexp
3798 (concat
3799 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3800 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3801 "\\(--?"
3802 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3803 "Regular expression to match a timestamp time or time range.
3804 After a match, the following groups carry important information:
3805 0 the full match
3806 1 date plus weekday, for back referencing to make sure both times are on the same day
3807 2 the first time, range or not
3808 4 the second time, if it is a range.")
3810 (defconst org-startup-options
3811 '(("fold" org-startup-folded t)
3812 ("overview" org-startup-folded t)
3813 ("nofold" org-startup-folded nil)
3814 ("showall" org-startup-folded nil)
3815 ("showeverything" org-startup-folded showeverything)
3816 ("content" org-startup-folded content)
3817 ("indent" org-startup-indented t)
3818 ("noindent" org-startup-indented nil)
3819 ("hidestars" org-hide-leading-stars t)
3820 ("showstars" org-hide-leading-stars nil)
3821 ("odd" org-odd-levels-only t)
3822 ("oddeven" org-odd-levels-only nil)
3823 ("align" org-startup-align-all-tables t)
3824 ("noalign" org-startup-align-all-tables nil)
3825 ("customtime" org-display-custom-times t)
3826 ("logdone" org-log-done time)
3827 ("lognotedone" org-log-done note)
3828 ("nologdone" org-log-done nil)
3829 ("lognoteclock-out" org-log-note-clock-out t)
3830 ("nolognoteclock-out" org-log-note-clock-out nil)
3831 ("logrepeat" org-log-repeat state)
3832 ("lognoterepeat" org-log-repeat note)
3833 ("nologrepeat" org-log-repeat nil)
3834 ("logreschedule" org-log-reschedule time)
3835 ("lognotereschedule" org-log-reschedule note)
3836 ("nologreschedule" org-log-reschedule nil)
3837 ("logredeadline" org-log-redeadline time)
3838 ("lognoteredeadline" org-log-redeadline note)
3839 ("nologredeadline" org-log-redeadline nil)
3840 ("logrefile" org-log-refile time)
3841 ("lognoterefile" org-log-refile note)
3842 ("nologrefile" org-log-refile nil)
3843 ("fninline" org-footnote-define-inline t)
3844 ("nofninline" org-footnote-define-inline nil)
3845 ("fnlocal" org-footnote-section nil)
3846 ("fnauto" org-footnote-auto-label t)
3847 ("fnprompt" org-footnote-auto-label nil)
3848 ("fnconfirm" org-footnote-auto-label confirm)
3849 ("fnplain" org-footnote-auto-label plain)
3850 ("fnadjust" org-footnote-auto-adjust t)
3851 ("nofnadjust" org-footnote-auto-adjust nil)
3852 ("constcgs" constants-unit-system cgs)
3853 ("constSI" constants-unit-system SI)
3854 ("noptag" org-tag-persistent-alist nil)
3855 ("hideblocks" org-hide-block-startup t)
3856 ("nohideblocks" org-hide-block-startup nil)
3857 ("beamer" org-startup-with-beamer-mode t))
3858 "Variable associated with STARTUP options for org-mode.
3859 Each element is a list of three items: The startup options as written
3860 in the #+STARTUP line, the corresponding variable, and the value to
3861 set this variable to if the option is found. An optional forth element PUSH
3862 means to push this value onto the list in the variable.")
3864 (defun org-set-regexps-and-options ()
3865 "Precompute regular expressions for current buffer."
3866 (when (org-mode-p)
3867 (org-set-local 'org-todo-kwd-alist nil)
3868 (org-set-local 'org-todo-key-alist nil)
3869 (org-set-local 'org-todo-key-trigger nil)
3870 (org-set-local 'org-todo-keywords-1 nil)
3871 (org-set-local 'org-done-keywords nil)
3872 (org-set-local 'org-todo-heads nil)
3873 (org-set-local 'org-todo-sets nil)
3874 (org-set-local 'org-todo-log-states nil)
3875 (org-set-local 'org-file-properties nil)
3876 (org-set-local 'org-file-tags nil)
3877 (let ((re (org-make-options-regexp
3878 '("CATEGORY" "TODO" "COLUMNS"
3879 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3880 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS")
3881 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3882 (splitre "[ \t]+")
3883 kwds kws0 kwsa key log value cat arch tags const links hw dws
3884 tail sep kws1 prio props ftags drawers beamer-p
3885 ext-setup-or-nil setup-contents (start 0))
3886 (save-excursion
3887 (save-restriction
3888 (widen)
3889 (goto-char (point-min))
3890 (while (or (and ext-setup-or-nil
3891 (string-match re ext-setup-or-nil start)
3892 (setq start (match-end 0)))
3893 (and (setq ext-setup-or-nil nil start 0)
3894 (re-search-forward re nil t)))
3895 (setq key (upcase (match-string 1 ext-setup-or-nil))
3896 value (org-match-string-no-properties 2 ext-setup-or-nil))
3897 (cond
3898 ((equal key "CATEGORY")
3899 (if (string-match "[ \t]+$" value)
3900 (setq value (replace-match "" t t value)))
3901 (setq cat value))
3902 ((member key '("SEQ_TODO" "TODO"))
3903 (push (cons 'sequence (org-split-string value splitre)) kwds))
3904 ((equal key "TYP_TODO")
3905 (push (cons 'type (org-split-string value splitre)) kwds))
3906 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3907 ;; general TODO-like setup
3908 (push (cons (intern (downcase (match-string 1 key)))
3909 (org-split-string value splitre)) kwds))
3910 ((equal key "TAGS")
3911 (setq tags (append tags (if tags '("\\n") nil)
3912 (org-split-string value splitre))))
3913 ((equal key "COLUMNS")
3914 (org-set-local 'org-columns-default-format value))
3915 ((equal key "LINK")
3916 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3917 (push (cons (match-string 1 value)
3918 (org-trim (match-string 2 value)))
3919 links)))
3920 ((equal key "PRIORITIES")
3921 (setq prio (org-split-string value " +")))
3922 ((equal key "PROPERTY")
3923 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3924 (push (cons (match-string 1 value) (match-string 2 value))
3925 props)))
3926 ((equal key "FILETAGS")
3927 (when (string-match "\\S-" value)
3928 (setq ftags
3929 (append
3930 ftags
3931 (apply 'append
3932 (mapcar (lambda (x) (org-split-string x ":"))
3933 (org-split-string value)))))))
3934 ((equal key "DRAWERS")
3935 (setq drawers (org-split-string value splitre)))
3936 ((equal key "CONSTANTS")
3937 (setq const (append const (org-split-string value splitre))))
3938 ((equal key "STARTUP")
3939 (let ((opts (org-split-string value splitre))
3940 l var val)
3941 (while (setq l (pop opts))
3942 (when (setq l (assoc l org-startup-options))
3943 (setq var (nth 1 l) val (nth 2 l))
3944 (if (not (nth 3 l))
3945 (set (make-local-variable var) val)
3946 (if (not (listp (symbol-value var)))
3947 (set (make-local-variable var) nil))
3948 (set (make-local-variable var) (symbol-value var))
3949 (add-to-list var val))))))
3950 ((equal key "ARCHIVE")
3951 (string-match " *$" value)
3952 (setq arch (replace-match "" t t value))
3953 (remove-text-properties 0 (length arch)
3954 '(face t fontified t) arch))
3955 ((equal key "LATEX_CLASS")
3956 (setq beamer-p (equal value "beamer")))
3957 ((equal key "SETUPFILE")
3958 (setq setup-contents (org-file-contents
3959 (expand-file-name
3960 (org-remove-double-quotes value))
3961 'noerror))
3962 (if (not ext-setup-or-nil)
3963 (setq ext-setup-or-nil setup-contents start 0)
3964 (setq ext-setup-or-nil
3965 (concat (substring ext-setup-or-nil 0 start)
3966 "\n" setup-contents "\n"
3967 (substring ext-setup-or-nil start)))))
3968 ))))
3969 (when cat
3970 (org-set-local 'org-category (intern cat))
3971 (push (cons "CATEGORY" cat) props))
3972 (when prio
3973 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3974 (setq prio (mapcar 'string-to-char prio))
3975 (org-set-local 'org-highest-priority (nth 0 prio))
3976 (org-set-local 'org-lowest-priority (nth 1 prio))
3977 (org-set-local 'org-default-priority (nth 2 prio)))
3978 (and props (org-set-local 'org-file-properties (nreverse props)))
3979 (and ftags (org-set-local 'org-file-tags
3980 (mapcar 'org-add-prop-inherited ftags)))
3981 (and drawers (org-set-local 'org-drawers drawers))
3982 (and arch (org-set-local 'org-archive-location arch))
3983 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3984 ;; Process the TODO keywords
3985 (unless kwds
3986 ;; Use the global values as if they had been given locally.
3987 (setq kwds (default-value 'org-todo-keywords))
3988 (if (stringp (car kwds))
3989 (setq kwds (list (cons org-todo-interpretation
3990 (default-value 'org-todo-keywords)))))
3991 (setq kwds (reverse kwds)))
3992 (setq kwds (nreverse kwds))
3993 (let (inter kws kw)
3994 (while (setq kws (pop kwds))
3995 (let ((kws (or
3996 (run-hook-with-args-until-success
3997 'org-todo-setup-filter-hook kws)
3998 kws)))
3999 (setq inter (pop kws) sep (member "|" kws)
4000 kws0 (delete "|" (copy-sequence kws))
4001 kwsa nil
4002 kws1 (mapcar
4003 (lambda (x)
4004 ;; 1 2
4005 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4006 (progn
4007 (setq kw (match-string 1 x)
4008 key (and (match-end 2) (match-string 2 x))
4009 log (org-extract-log-state-settings x))
4010 (push (cons kw (and key (string-to-char key))) kwsa)
4011 (and log (push log org-todo-log-states))
4013 (error "Invalid TODO keyword %s" x)))
4014 kws0)
4015 kwsa (if kwsa (append '((:startgroup))
4016 (nreverse kwsa)
4017 '((:endgroup))))
4018 hw (car kws1)
4019 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4020 tail (list inter hw (car dws) (org-last dws))))
4021 (add-to-list 'org-todo-heads hw 'append)
4022 (push kws1 org-todo-sets)
4023 (setq org-done-keywords (append org-done-keywords dws nil))
4024 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4025 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4026 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4027 (setq org-todo-sets (nreverse org-todo-sets)
4028 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4029 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4030 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4031 ;; Process the constants
4032 (when const
4033 (let (e cst)
4034 (while (setq e (pop const))
4035 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4036 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4037 (setq org-table-formula-constants-local cst)))
4039 ;; Process the tags.
4040 (when tags
4041 (let (e tgs)
4042 (while (setq e (pop tags))
4043 (cond
4044 ((equal e "{") (push '(:startgroup) tgs))
4045 ((equal e "}") (push '(:endgroup) tgs))
4046 ((equal e "\\n") (push '(:newline) tgs))
4047 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4048 (push (cons (match-string 1 e)
4049 (string-to-char (match-string 2 e)))
4050 tgs))
4051 (t (push (list e) tgs))))
4052 (org-set-local 'org-tag-alist nil)
4053 (while (setq e (pop tgs))
4054 (or (and (stringp (car e))
4055 (assoc (car e) org-tag-alist))
4056 (push e org-tag-alist)))))
4058 ;; Compute the regular expressions and other local variables
4059 (if (not org-done-keywords)
4060 (setq org-done-keywords (and org-todo-keywords-1
4061 (list (org-last org-todo-keywords-1)))))
4062 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4063 (length org-scheduled-string)
4064 (length org-clock-string)
4065 (length org-closed-string)))
4066 org-drawer-regexp
4067 (concat "^[ \t]*:\\("
4068 (mapconcat 'regexp-quote org-drawers "\\|")
4069 "\\):[ \t]*$")
4070 org-not-done-keywords
4071 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4072 org-todo-regexp
4073 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4074 "\\|") "\\)\\>")
4075 org-not-done-regexp
4076 (concat "\\<\\("
4077 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4078 "\\)\\>")
4079 org-not-done-heading-regexp
4080 (concat "^\\(\\*+\\)[ \t]+\\("
4081 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4082 "\\)\\>")
4083 org-todo-line-regexp
4084 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4085 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4086 "\\)\\>\\)?[ \t]*\\(.*\\)")
4087 org-complex-heading-regexp
4088 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4089 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4090 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4091 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4092 org-complex-heading-regexp-format
4093 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4094 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4095 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
4096 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4097 org-nl-done-regexp
4098 (concat "\n\\*+[ \t]+"
4099 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4100 "\\)" "\\>")
4101 org-todo-line-tags-regexp
4102 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4103 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4104 (org-re
4105 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4106 org-looking-at-done-regexp
4107 (concat "^" "\\(?:"
4108 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4109 "\\>")
4110 org-deadline-regexp (concat "\\<" org-deadline-string)
4111 org-deadline-time-regexp
4112 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4113 org-deadline-line-regexp
4114 (concat "\\<\\(" org-deadline-string "\\).*")
4115 org-scheduled-regexp
4116 (concat "\\<" org-scheduled-string)
4117 org-scheduled-time-regexp
4118 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4119 org-closed-time-regexp
4120 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4121 org-keyword-time-regexp
4122 (concat "\\<\\(" org-scheduled-string
4123 "\\|" org-deadline-string
4124 "\\|" org-closed-string
4125 "\\|" org-clock-string "\\)"
4126 " *[[<]\\([^]>]+\\)[]>]")
4127 org-keyword-time-not-clock-regexp
4128 (concat "\\<\\(" org-scheduled-string
4129 "\\|" org-deadline-string
4130 "\\|" org-closed-string
4131 "\\)"
4132 " *[[<]\\([^]>]+\\)[]>]")
4133 org-maybe-keyword-time-regexp
4134 (concat "\\(\\<\\(" org-scheduled-string
4135 "\\|" org-deadline-string
4136 "\\|" org-closed-string
4137 "\\|" org-clock-string "\\)\\)?"
4138 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4139 org-planning-or-clock-line-re
4140 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4141 "\\|" org-deadline-string
4142 "\\|" org-closed-string "\\|" org-clock-string
4143 "\\)\\>\\)")
4144 org-all-time-keywords
4145 (mapcar (lambda (w) (substring w 0 -1))
4146 (list org-scheduled-string org-deadline-string
4147 org-clock-string org-closed-string))
4149 (org-compute-latex-and-specials-regexp)
4150 (org-set-font-lock-defaults))))
4152 (defun org-file-contents (file &optional noerror)
4153 "Return the contents of FILE, as a string."
4154 (if (or (not file)
4155 (not (file-readable-p file)))
4156 (if noerror
4157 (progn
4158 (message "Cannot read file %s" file)
4159 (ding) (sit-for 2)
4161 (error "Cannot read file %s" file))
4162 (with-temp-buffer
4163 (insert-file-contents file)
4164 (buffer-string))))
4166 (defun org-extract-log-state-settings (x)
4167 "Extract the log state setting from a TODO keyword string.
4168 This will extract info from a string like \"WAIT(w@/!)\"."
4169 (let (kw key log1 log2)
4170 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4171 (setq kw (match-string 1 x)
4172 key (and (match-end 2) (match-string 2 x))
4173 log1 (and (match-end 3) (match-string 3 x))
4174 log2 (and (match-end 4) (match-string 4 x)))
4175 (and (or log1 log2)
4176 (list kw
4177 (and log1 (if (equal log1 "!") 'time 'note))
4178 (and log2 (if (equal log2 "!") 'time 'note)))))))
4180 (defun org-remove-keyword-keys (list)
4181 "Remove a pair of parenthesis at the end of each string in LIST."
4182 (mapcar (lambda (x)
4183 (if (string-match "(.*)$" x)
4184 (substring x 0 (match-beginning 0))
4186 list))
4188 (defun org-assign-fast-keys (alist)
4189 "Assign fast keys to a keyword-key alist.
4190 Respect keys that are already there."
4191 (let (new e (alt ?0))
4192 (while (setq e (pop alist))
4193 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4194 (cdr e)) ;; Key already assigned.
4195 (push e new)
4196 (let ((clist (string-to-list (downcase (car e))))
4197 (used (append new alist)))
4198 (when (= (car clist) ?@)
4199 (pop clist))
4200 (while (and clist (rassoc (car clist) used))
4201 (pop clist))
4202 (unless clist
4203 (while (rassoc alt used)
4204 (incf alt)))
4205 (push (cons (car e) (or (car clist) alt)) new))))
4206 (nreverse new)))
4208 ;;; Some variables used in various places
4210 (defvar org-window-configuration nil
4211 "Used in various places to store a window configuration.")
4212 (defvar org-selected-window nil
4213 "Used in various places to store a window configuration.")
4214 (defvar org-finish-function nil
4215 "Function to be called when `C-c C-c' is used.
4216 This is for getting out of special buffers like remember.")
4219 ;; FIXME: Occasionally check by commenting these, to make sure
4220 ;; no other functions uses these, forgetting to let-bind them.
4221 (defvar entry)
4222 (defvar last-state)
4223 (defvar date)
4225 ;; Defined somewhere in this file, but used before definition.
4226 (defvar org-entities) ;; defined in org-entities.el
4227 (defvar org-struct-menu)
4228 (defvar org-org-menu)
4229 (defvar org-tbl-menu)
4231 ;;;; Define the Org-mode
4233 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4234 (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."))
4237 ;; We use a before-change function to check if a table might need
4238 ;; an update.
4239 (defvar org-table-may-need-update t
4240 "Indicates that a table might need an update.
4241 This variable is set by `org-before-change-function'.
4242 `org-table-align' sets it back to nil.")
4243 (defun org-before-change-function (beg end)
4244 "Every change indicates that a table might need an update."
4245 (setq org-table-may-need-update t))
4246 (defvar org-mode-map)
4247 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4248 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4249 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4250 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4251 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4252 (defvar org-table-buffer-is-an nil)
4253 (defconst org-outline-regexp "\\*+ ")
4255 ;;;###autoload
4256 (define-derived-mode org-mode outline-mode "Org"
4257 "Outline-based notes management and organizer, alias
4258 \"Carsten's outline-mode for keeping track of everything.\"
4260 Org-mode develops organizational tasks around a NOTES file which
4261 contains information about projects as plain text. Org-mode is
4262 implemented on top of outline-mode, which is ideal to keep the content
4263 of large files well structured. It supports ToDo items, deadlines and
4264 time stamps, which magically appear in the diary listing of the Emacs
4265 calendar. Tables are easily created with a built-in table editor.
4266 Plain text URL-like links connect to websites, emails (VM), Usenet
4267 messages (Gnus), BBDB entries, and any files related to the project.
4268 For printing and sharing of notes, an Org-mode file (or a part of it)
4269 can be exported as a structured ASCII or HTML file.
4271 The following commands are available:
4273 \\{org-mode-map}"
4275 ;; Get rid of Outline menus, they are not needed
4276 ;; Need to do this here because define-derived-mode sets up
4277 ;; the keymap so late. Still, it is a waste to call this each time
4278 ;; we switch another buffer into org-mode.
4279 (if (featurep 'xemacs)
4280 (when (boundp 'outline-mode-menu-heading)
4281 ;; Assume this is Greg's port, it used easymenu
4282 (easy-menu-remove outline-mode-menu-heading)
4283 (easy-menu-remove outline-mode-menu-show)
4284 (easy-menu-remove outline-mode-menu-hide))
4285 (define-key org-mode-map [menu-bar headings] 'undefined)
4286 (define-key org-mode-map [menu-bar hide] 'undefined)
4287 (define-key org-mode-map [menu-bar show] 'undefined))
4289 (org-load-modules-maybe)
4290 (easy-menu-add org-org-menu)
4291 (easy-menu-add org-tbl-menu)
4292 (org-install-agenda-files-menu)
4293 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4294 (org-add-to-invisibility-spec '(org-cwidth))
4295 (org-add-to-invisibility-spec '(org-hide-block . t))
4296 (when (featurep 'xemacs)
4297 (org-set-local 'line-move-ignore-invisible t))
4298 (org-set-local 'outline-regexp org-outline-regexp)
4299 (org-set-local 'outline-level 'org-outline-level)
4300 (when (and org-ellipsis
4301 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4302 (fboundp 'make-glyph-code))
4303 (unless org-display-table
4304 (setq org-display-table (make-display-table)))
4305 (set-display-table-slot
4306 org-display-table 4
4307 (vconcat (mapcar
4308 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4309 org-ellipsis)))
4310 (if (stringp org-ellipsis) org-ellipsis "..."))))
4311 (setq buffer-display-table org-display-table))
4312 (org-set-regexps-and-options)
4313 (when (and org-tag-faces (not org-tags-special-faces-re))
4314 ;; tag faces set outside customize.... force initialization.
4315 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4316 ;; Calc embedded
4317 (org-set-local 'calc-embedded-open-mode "# ")
4318 (modify-syntax-entry ?# "<")
4319 (modify-syntax-entry ?@ "w")
4320 (if org-startup-truncated (setq truncate-lines t))
4321 (org-set-local 'font-lock-unfontify-region-function
4322 'org-unfontify-region)
4323 ;; Activate before-change-function
4324 (org-set-local 'org-table-may-need-update t)
4325 (org-add-hook 'before-change-functions 'org-before-change-function nil
4326 'local)
4327 ;; Check for running clock before killing a buffer
4328 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4329 ;; Paragraphs and auto-filling
4330 (org-set-autofill-regexps)
4331 (setq indent-line-function 'org-indent-line-function)
4332 (org-update-radio-target-regexp)
4333 ;; Make sure dependence stuff works reliably, even for users who set it
4334 ;; too late :-(
4335 (if org-enforce-todo-dependencies
4336 (add-hook 'org-blocker-hook
4337 'org-block-todo-from-children-or-siblings-or-parent)
4338 (remove-hook 'org-blocker-hook
4339 'org-block-todo-from-children-or-siblings-or-parent))
4340 (if org-enforce-todo-checkbox-dependencies
4341 (add-hook 'org-blocker-hook
4342 'org-block-todo-from-checkboxes)
4343 (remove-hook 'org-blocker-hook
4344 'org-block-todo-from-checkboxes))
4346 ;; Comment characters
4347 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4348 (org-set-local 'comment-padding " ")
4350 ;; Align options lines
4351 (org-set-local
4352 'align-mode-rules-list
4353 '((org-in-buffer-settings
4354 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4355 (modes . '(org-mode)))))
4357 ;; Imenu
4358 (org-set-local 'imenu-create-index-function
4359 'org-imenu-get-tree)
4361 ;; Make isearch reveal context
4362 (if (or (featurep 'xemacs)
4363 (not (boundp 'outline-isearch-open-invisible-function)))
4364 ;; Emacs 21 and XEmacs make use of the hook
4365 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4366 ;; Emacs 22 deals with this through a special variable
4367 (org-set-local 'outline-isearch-open-invisible-function
4368 (lambda (&rest ignore) (org-show-context 'isearch))))
4370 ;; Turn on org-beamer-mode?
4371 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4373 ;; If empty file that did not turn on org-mode automatically, make it to.
4374 (if (and org-insert-mode-line-in-empty-file
4375 (interactive-p)
4376 (= (point-min) (point-max)))
4377 (insert "# -*- mode: org -*-\n\n"))
4378 (unless org-inhibit-startup
4379 (when org-startup-align-all-tables
4380 (let ((bmp (buffer-modified-p)))
4381 (org-table-map-tables 'org-table-align)
4382 (set-buffer-modified-p bmp)))
4383 (when org-startup-indented
4384 (require 'org-indent)
4385 (org-indent-mode 1))
4386 (unless org-inhibit-startup-visibility-stuff
4387 (org-set-startup-visibility))))
4389 (when (fboundp 'abbrev-table-put)
4390 (abbrev-table-put org-mode-abbrev-table
4391 :parents (list text-mode-abbrev-table)))
4393 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4395 (defun org-current-time ()
4396 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4397 (if (> (car org-time-stamp-rounding-minutes) 1)
4398 (let ((r (car org-time-stamp-rounding-minutes))
4399 (time (decode-time)))
4400 (apply 'encode-time
4401 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4402 (nthcdr 2 time))))
4403 (current-time)))
4405 ;;;; Font-Lock stuff, including the activators
4407 (defvar org-mouse-map (make-sparse-keymap))
4408 (org-defkey org-mouse-map
4409 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4410 (org-defkey org-mouse-map
4411 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4412 (when org-mouse-1-follows-link
4413 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4414 (when org-tab-follows-link
4415 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4416 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4418 (require 'font-lock)
4420 (defconst org-non-link-chars "]\t\n\r<>")
4421 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4422 "shell" "elisp"))
4423 (defvar org-link-types-re nil
4424 "Matches a link that has a url-like prefix like \"http:\"")
4425 (defvar org-link-re-with-space nil
4426 "Matches a link with spaces, optional angular brackets around it.")
4427 (defvar org-link-re-with-space2 nil
4428 "Matches a link with spaces, optional angular brackets around it.")
4429 (defvar org-link-re-with-space3 nil
4430 "Matches a link with spaces, only for internal part in bracket links.")
4431 (defvar org-angle-link-re nil
4432 "Matches link with angular brackets, spaces are allowed.")
4433 (defvar org-plain-link-re nil
4434 "Matches plain link, without spaces.")
4435 (defvar org-bracket-link-regexp nil
4436 "Matches a link in double brackets.")
4437 (defvar org-bracket-link-analytic-regexp nil
4438 "Regular expression used to analyze links.
4439 Here is what the match groups contain after a match:
4440 1: http:
4441 2: http
4442 3: path
4443 4: [desc]
4444 5: desc")
4445 (defvar org-bracket-link-analytic-regexp++ nil
4446 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4447 (defvar org-any-link-re nil
4448 "Regular expression matching any link.")
4450 (defun org-make-link-regexps ()
4451 "Update the link regular expressions.
4452 This should be called after the variable `org-link-types' has changed."
4453 (setq org-link-types-re
4454 (concat
4455 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4456 org-link-re-with-space
4457 (concat
4458 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4459 "\\([^" org-non-link-chars " ]"
4460 "[^" org-non-link-chars "]*"
4461 "[^" org-non-link-chars " ]\\)>?")
4462 org-link-re-with-space2
4463 (concat
4464 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4465 "\\([^" org-non-link-chars " ]"
4466 "[^\t\n\r]*"
4467 "[^" org-non-link-chars " ]\\)>?")
4468 org-link-re-with-space3
4469 (concat
4470 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4471 "\\([^" org-non-link-chars " ]"
4472 "[^\t\n\r]*\\)")
4473 org-angle-link-re
4474 (concat
4475 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4476 "\\([^" org-non-link-chars " ]"
4477 "[^" org-non-link-chars "]*"
4478 "\\)>")
4479 org-plain-link-re
4480 (concat
4481 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4482 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4483 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4484 org-bracket-link-regexp
4485 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4486 org-bracket-link-analytic-regexp
4487 (concat
4488 "\\[\\["
4489 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4490 "\\([^]]+\\)"
4491 "\\]"
4492 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4493 "\\]")
4494 org-bracket-link-analytic-regexp++
4495 (concat
4496 "\\[\\["
4497 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4498 "\\([^]]+\\)"
4499 "\\]"
4500 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4501 "\\]")
4502 org-any-link-re
4503 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4504 org-angle-link-re "\\)\\|\\("
4505 org-plain-link-re "\\)")))
4507 (org-make-link-regexps)
4509 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4510 "Regular expression for fast time stamp matching.")
4511 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4512 "Regular expression for fast time stamp matching.")
4513 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4514 "Regular expression matching time strings for analysis.
4515 This one does not require the space after the date, so it can be used
4516 on a string that terminates immediately after the date.")
4517 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4518 "Regular expression matching time strings for analysis.")
4519 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4520 "Regular expression matching time stamps, with groups.")
4521 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4522 "Regular expression matching time stamps (also [..]), with groups.")
4523 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4524 "Regular expression matching a time stamp range.")
4525 (defconst org-tr-regexp-both
4526 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4527 "Regular expression matching a time stamp range.")
4528 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4529 org-ts-regexp "\\)?")
4530 "Regular expression matching a time stamp or time stamp range.")
4531 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4532 org-ts-regexp-both "\\)?")
4533 "Regular expression matching a time stamp or time stamp range.
4534 The time stamps may be either active or inactive.")
4536 (defvar org-emph-face nil)
4538 (defun org-do-emphasis-faces (limit)
4539 "Run through the buffer and add overlays to links."
4540 (let (rtn a)
4541 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4542 (if (not (= (char-after (match-beginning 3))
4543 (char-after (match-beginning 4))))
4544 (progn
4545 (setq rtn t)
4546 (setq a (assoc (match-string 3) org-emphasis-alist))
4547 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4548 'face
4549 (nth 1 a))
4550 (and (nth 4 a)
4551 (org-remove-flyspell-overlays-in
4552 (match-beginning 0) (match-end 0)))
4553 (add-text-properties (match-beginning 2) (match-end 2)
4554 '(font-lock-multiline t))
4555 (when org-hide-emphasis-markers
4556 (add-text-properties (match-end 4) (match-beginning 5)
4557 '(invisible org-link))
4558 (add-text-properties (match-beginning 3) (match-end 3)
4559 '(invisible org-link)))))
4560 (backward-char 1))
4561 rtn))
4563 (defun org-emphasize (&optional char)
4564 "Insert or change an emphasis, i.e. a font like bold or italic.
4565 If there is an active region, change that region to a new emphasis.
4566 If there is no region, just insert the marker characters and position
4567 the cursor between them.
4568 CHAR should be either the marker character, or the first character of the
4569 HTML tag associated with that emphasis. If CHAR is a space, the means
4570 to remove the emphasis of the selected region.
4571 If char is not given (for example in an interactive call) it
4572 will be prompted for."
4573 (interactive)
4574 (let ((eal org-emphasis-alist) e det
4575 (erc org-emphasis-regexp-components)
4576 (prompt "")
4577 (string "") beg end move tag c s)
4578 (if (org-region-active-p)
4579 (setq beg (region-beginning) end (region-end)
4580 string (buffer-substring beg end))
4581 (setq move t))
4583 (while (setq e (pop eal))
4584 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4585 c (aref tag 0))
4586 (push (cons c (string-to-char (car e))) det)
4587 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4588 (substring tag 1)))))
4589 (setq det (nreverse det))
4590 (unless char
4591 (message "%s" (concat "Emphasis marker or tag:" prompt))
4592 (setq char (read-char-exclusive)))
4593 (setq char (or (cdr (assoc char det)) char))
4594 (if (equal char ?\ )
4595 (setq s "" move nil)
4596 (unless (assoc (char-to-string char) org-emphasis-alist)
4597 (error "No such emphasis marker: \"%c\"" char))
4598 (setq s (char-to-string char)))
4599 (while (and (> (length string) 1)
4600 (equal (substring string 0 1) (substring string -1))
4601 (assoc (substring string 0 1) org-emphasis-alist))
4602 (setq string (substring string 1 -1)))
4603 (setq string (concat s string s))
4604 (if beg (delete-region beg end))
4605 (unless (or (bolp)
4606 (string-match (concat "[" (nth 0 erc) "\n]")
4607 (char-to-string (char-before (point)))))
4608 (insert " "))
4609 (unless (or (eobp)
4610 (string-match (concat "[" (nth 1 erc) "\n]")
4611 (char-to-string (char-after (point)))))
4612 (insert " ") (backward-char 1))
4613 (insert string)
4614 (and move (backward-char 1))))
4616 (defconst org-nonsticky-props
4617 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4619 (defsubst org-rear-nonsticky-at (pos)
4620 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4622 (defun org-activate-plain-links (limit)
4623 "Run through the buffer and add overlays to links."
4624 (catch 'exit
4625 (let (f)
4626 (if (re-search-forward org-plain-link-re limit t)
4627 (progn
4628 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4629 (setq f (get-text-property (match-beginning 0) 'face))
4630 (if (or (eq f 'org-tag)
4631 (and (listp f) (memq 'org-tag f)))
4633 (add-text-properties (match-beginning 0) (match-end 0)
4634 (list 'mouse-face 'highlight
4635 'face 'org-link
4636 'keymap org-mouse-map))
4637 (org-rear-nonsticky-at (match-end 0)))
4638 t)))))
4640 (defun org-activate-code (limit)
4641 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4642 (progn
4643 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4644 (remove-text-properties (match-beginning 0) (match-end 0)
4645 '(display t invisible t intangible t))
4646 t)))
4648 (defun org-fontify-meta-lines-and-blocks (limit)
4649 "Fontify #+ lines and blocks, in the correct ways."
4650 (let ((case-fold-search t))
4651 (if (re-search-forward
4652 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4653 limit t)
4654 (let ((beg (match-beginning 0))
4655 (beg1 (line-beginning-position 2))
4656 (dc1 (downcase (match-string 2)))
4657 (dc3 (downcase (match-string 3)))
4658 end end1 quoting block-type)
4659 (cond
4660 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4661 ;; a single line of backend-specific content
4662 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4663 (remove-text-properties (match-beginning 0) (match-end 0)
4664 '(display t invisible t intangible t))
4665 (add-text-properties (match-beginning 1) (match-end 3)
4666 '(font-lock-fontified t face org-meta-line))
4667 (add-text-properties (match-beginning 6) (match-end 6)
4668 '(font-lock-fontified t face org-block))
4670 ((and (match-end 4) (equal dc3 "begin"))
4671 ;; Truely a block
4672 (setq block-type (downcase (match-string 5))
4673 quoting (member block-type org-protecting-blocks))
4674 (when (re-search-forward
4675 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4676 nil t) ;; on purpose, we look further than LIMIT
4677 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4678 (when quoting
4679 (remove-text-properties beg end
4680 '(display t invisible t intangible t)))
4681 (add-text-properties
4682 beg end
4683 '(font-lock-fontified t font-lock-multiline t))
4684 (add-text-properties beg beg1 '(face org-meta-line))
4685 (add-text-properties end1 end '(face org-meta-line))
4686 (cond
4687 (quoting
4688 (add-text-properties beg1 end1 '(face org-block)))
4689 ((not org-fontify-quote-and-verse-blocks))
4690 ((string= block-type "quote")
4691 (add-text-properties beg1 end1 '(face org-quote)))
4692 ((string= block-type "verse")
4693 (add-text-properties beg1 end1 '(face org-verse))))
4695 ((member dc1 '("title:" "author:" "email:" "date:"))
4696 (add-text-properties
4697 beg (match-end 3)
4698 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
4699 '(font-lock-fontified t invisible t)
4700 '(font-lock-fontified t face org-document-info-keyword)))
4701 (add-text-properties
4702 (match-beginning 6) (match-end 6)
4703 (if (string-equal dc1 "title:")
4704 '(font-lock-fontified t face org-document-title)
4705 '(font-lock-fontified t face org-document-info))))
4706 ((not (member (char-after beg) '(?\ ?\t)))
4707 ;; just any other in-buffer setting, but not indented
4708 (add-text-properties
4709 beg (match-end 0)
4710 '(font-lock-fontified t face org-meta-line))
4712 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4713 "orgtbl:" "tblfm:" "tblname:"))
4714 (and (match-end 4) (equal dc3 "attr")))
4715 (add-text-properties
4716 beg (match-end 0)
4717 '(font-lock-fontified t face org-meta-line))
4719 ((member dc3 '(" " ""))
4720 (add-text-properties
4721 beg (match-end 0)
4722 '(font-lock-fontified t face font-lock-comment-face)))
4723 (t nil))))))
4725 (defun org-activate-angle-links (limit)
4726 "Run through the buffer and add overlays to links."
4727 (if (re-search-forward org-angle-link-re limit t)
4728 (progn
4729 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4730 (add-text-properties (match-beginning 0) (match-end 0)
4731 (list 'mouse-face 'highlight
4732 'keymap org-mouse-map))
4733 (org-rear-nonsticky-at (match-end 0))
4734 t)))
4736 (defun org-activate-footnote-links (limit)
4737 "Run through the buffer and add overlays to links."
4738 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4739 limit t)
4740 (progn
4741 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4742 (add-text-properties (match-beginning 2) (match-end 2)
4743 (list 'mouse-face 'highlight
4744 'keymap org-mouse-map
4745 'help-echo
4746 (if (= (point-at-bol) (match-beginning 2))
4747 "Footnote definition"
4748 "Footnote reference")
4750 (org-rear-nonsticky-at (match-end 2))
4751 t)))
4753 (defun org-activate-bracket-links (limit)
4754 "Run through the buffer and add overlays to bracketed links."
4755 (if (re-search-forward org-bracket-link-regexp limit t)
4756 (let* ((help (concat "LINK: "
4757 (org-match-string-no-properties 1)))
4758 ;; FIXME: above we should remove the escapes.
4759 ;; but that requires another match, protecting match data,
4760 ;; a lot of overhead for font-lock.
4761 (ip (org-maybe-intangible
4762 (list 'invisible 'org-link
4763 'keymap org-mouse-map 'mouse-face 'highlight
4764 'font-lock-multiline t 'help-echo help)))
4765 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4766 'font-lock-multiline t 'help-echo help)))
4767 ;; We need to remove the invisible property here. Table narrowing
4768 ;; may have made some of this invisible.
4769 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4770 (remove-text-properties (match-beginning 0) (match-end 0)
4771 '(invisible nil))
4772 (if (match-end 3)
4773 (progn
4774 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4775 (org-rear-nonsticky-at (match-beginning 3))
4776 (add-text-properties (match-beginning 3) (match-end 3) vp)
4777 (org-rear-nonsticky-at (match-end 3))
4778 (add-text-properties (match-end 3) (match-end 0) ip)
4779 (org-rear-nonsticky-at (match-end 0)))
4780 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4781 (org-rear-nonsticky-at (match-beginning 1))
4782 (add-text-properties (match-beginning 1) (match-end 1) vp)
4783 (org-rear-nonsticky-at (match-end 1))
4784 (add-text-properties (match-end 1) (match-end 0) ip)
4785 (org-rear-nonsticky-at (match-end 0)))
4786 t)))
4788 (defun org-activate-dates (limit)
4789 "Run through the buffer and add overlays to dates."
4790 (if (re-search-forward org-tsr-regexp-both limit t)
4791 (progn
4792 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4793 (add-text-properties (match-beginning 0) (match-end 0)
4794 (list 'mouse-face 'highlight
4795 'keymap org-mouse-map))
4796 (org-rear-nonsticky-at (match-end 0))
4797 (when org-display-custom-times
4798 (if (match-end 3)
4799 (org-display-custom-time (match-beginning 3) (match-end 3)))
4800 (org-display-custom-time (match-beginning 1) (match-end 1)))
4801 t)))
4803 (defvar org-target-link-regexp nil
4804 "Regular expression matching radio targets in plain text.")
4805 (make-variable-buffer-local 'org-target-link-regexp)
4806 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4807 "Regular expression matching a link target.")
4808 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4809 "Regular expression matching a radio target.")
4810 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4811 "Regular expression matching any target.")
4813 (defun org-activate-target-links (limit)
4814 "Run through the buffer and add overlays to target matches."
4815 (when org-target-link-regexp
4816 (let ((case-fold-search t))
4817 (if (re-search-forward org-target-link-regexp limit t)
4818 (progn
4819 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4820 (add-text-properties (match-beginning 0) (match-end 0)
4821 (list 'mouse-face 'highlight
4822 'keymap org-mouse-map
4823 'help-echo "Radio target link"
4824 'org-linked-text t))
4825 (org-rear-nonsticky-at (match-end 0))
4826 t)))))
4828 (defun org-update-radio-target-regexp ()
4829 "Find all radio targets in this file and update the regular expression."
4830 (interactive)
4831 (when (memq 'radio org-activate-links)
4832 (setq org-target-link-regexp
4833 (org-make-target-link-regexp (org-all-targets 'radio)))
4834 (org-restart-font-lock)))
4836 (defun org-hide-wide-columns (limit)
4837 (let (s e)
4838 (setq s (text-property-any (point) (or limit (point-max))
4839 'org-cwidth t))
4840 (when s
4841 (setq e (next-single-property-change s 'org-cwidth))
4842 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4843 (goto-char e)
4844 t)))
4846 (defvar org-latex-and-specials-regexp nil
4847 "Regular expression for highlighting export special stuff.")
4848 (defvar org-match-substring-regexp)
4849 (defvar org-match-substring-with-braces-regexp)
4851 ;; This should be with the exporter code, but we also use if for font-locking
4852 (defconst org-export-html-special-string-regexps
4853 '(("\\\\-" . "&shy;")
4854 ("---\\([^-]\\)" . "&mdash;\\1")
4855 ("--\\([^-]\\)" . "&ndash;\\1")
4856 ("\\.\\.\\." . "&hellip;"))
4857 "Regular expressions for special string conversion.")
4860 (defun org-compute-latex-and-specials-regexp ()
4861 "Compute regular expression for stuff treated specially by exporters."
4862 (if (not org-highlight-latex-fragments-and-specials)
4863 (org-set-local 'org-latex-and-specials-regexp nil)
4864 (require 'org-exp)
4865 (let*
4866 ((matchers (plist-get org-format-latex-options :matchers))
4867 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4868 org-latex-regexps)))
4869 (org-export-allow-BIND nil)
4870 (options (org-combine-plists (org-default-export-plist)
4871 (org-infile-export-plist)))
4872 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4873 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4874 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4875 (org-export-html-expand (plist-get options :expand-quoted-html))
4876 (org-export-with-special-strings (plist-get options :special-strings))
4877 (re-sub
4878 (cond
4879 ((equal org-export-with-sub-superscripts '{})
4880 (list org-match-substring-with-braces-regexp))
4881 (org-export-with-sub-superscripts
4882 (list org-match-substring-regexp))
4883 (t nil)))
4884 (re-latex
4885 (if org-export-with-LaTeX-fragments
4886 (mapcar (lambda (x) (nth 1 x)) latexs)))
4887 (re-macros
4888 (if org-export-with-TeX-macros
4889 (list (concat "\\\\"
4890 (regexp-opt
4891 (append (mapcar 'car (append org-entities-user
4892 org-entities))
4893 (if (boundp 'org-latex-entities)
4894 (mapcar (lambda (x)
4895 (or (car-safe x) x))
4896 org-latex-entities)
4897 nil))
4898 'words))) ; FIXME
4900 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4901 (re-special (if org-export-with-special-strings
4902 (mapcar (lambda (x) (car x))
4903 org-export-html-special-string-regexps)))
4904 (re-rest
4905 (delq nil
4906 (list
4907 (if org-export-html-expand "@<[^>\n]+>")
4908 ))))
4909 (org-set-local
4910 'org-latex-and-specials-regexp
4911 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4912 re-rest) "\\|")))))
4914 (defun org-do-latex-and-special-faces (limit)
4915 "Run through the buffer and add overlays to links."
4916 (when org-latex-and-specials-regexp
4917 (let (rtn d)
4918 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4919 limit t))
4920 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4921 'face))
4922 '(org-code org-verbatim underline)))
4923 (progn
4924 (setq rtn t
4925 d (cond ((member (char-after (1+ (match-beginning 0)))
4926 '(?_ ?^)) 1)
4927 (t 0)))
4928 (font-lock-prepend-text-property
4929 (+ d (match-beginning 0)) (match-end 0)
4930 'face 'org-latex-and-export-specials)
4931 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4932 '(font-lock-multiline t)))))
4933 rtn)))
4935 (defun org-restart-font-lock ()
4936 "Restart font-lock-mode, to force refontification."
4937 (when (and (boundp 'font-lock-mode) font-lock-mode)
4938 (font-lock-mode -1)
4939 (font-lock-mode 1)))
4941 (defun org-all-targets (&optional radio)
4942 "Return a list of all targets in this file.
4943 With optional argument RADIO, only find radio targets."
4944 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4945 rtn)
4946 (save-excursion
4947 (goto-char (point-min))
4948 (while (re-search-forward re nil t)
4949 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4950 rtn)))
4952 (defun org-make-target-link-regexp (targets)
4953 "Make regular expression matching all strings in TARGETS.
4954 The regular expression finds the targets also if there is a line break
4955 between words."
4956 (and targets
4957 (concat
4958 "\\<\\("
4959 (mapconcat
4960 (lambda (x)
4961 (while (string-match " +" x)
4962 (setq x (replace-match "\\s-+" t t x)))
4964 targets
4965 "\\|")
4966 "\\)\\>")))
4968 (defun org-activate-tags (limit)
4969 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4970 (progn
4971 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
4972 (add-text-properties (match-beginning 1) (match-end 1)
4973 (list 'mouse-face 'highlight
4974 'keymap org-mouse-map))
4975 (org-rear-nonsticky-at (match-end 1))
4976 t)))
4978 (defun org-outline-level ()
4979 "Compute the outline level of the heading at point.
4980 This function assumes that the cursor is at the beginning of a line matched
4981 by outline-regexp. Otherwise it returns garbage.
4982 If this is called at a normal headline, the level is the number of stars.
4983 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4984 For plain list items, if they are matched by `outline-regexp', this returns
4985 1000 plus the line indentation."
4986 (save-excursion
4987 (looking-at outline-regexp)
4988 (if (match-beginning 1)
4989 (+ (org-get-string-indentation (match-string 1)) 1000)
4990 (1- (- (match-end 0) (match-beginning 0))))))
4992 (defvar org-font-lock-keywords nil)
4994 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4995 "Regular expression matching a property line.")
4997 (defvar org-font-lock-hook nil
4998 "Functions to be called for special font lock stuff.")
5000 (defun org-font-lock-hook (limit)
5001 (run-hook-with-args 'org-font-lock-hook limit))
5003 (defun org-set-font-lock-defaults ()
5004 (let* ((em org-fontify-emphasized-text)
5005 (lk org-activate-links)
5006 (org-font-lock-extra-keywords
5007 (list
5008 ;; Call the hook
5009 '(org-font-lock-hook)
5010 ;; Headlines
5011 `(,(if org-fontify-whole-heading-line
5012 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5013 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5014 (1 (org-get-level-face 1))
5015 (2 (org-get-level-face 2))
5016 (3 (org-get-level-face 3)))
5017 ;; Table lines
5018 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5019 (1 'org-table t))
5020 ;; Table internals
5021 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5022 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5023 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5024 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
5025 ;; Drawers
5026 (list org-drawer-regexp '(0 'org-special-keyword t))
5027 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5028 ;; Properties
5029 (list org-property-re
5030 '(1 'org-special-keyword t)
5031 '(3 'org-property-value t))
5032 ;; Links
5033 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5034 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5035 (if (memq 'plain lk) '(org-activate-plain-links))
5036 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5037 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5038 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5039 (if (memq 'footnote lk) '(org-activate-footnote-links
5040 (2 'org-footnote t)))
5041 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5042 '(org-hide-wide-columns (0 nil append))
5043 ;; TODO lines
5044 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5045 '(1 (org-get-todo-face 1) t))
5046 ;; DONE
5047 (if org-fontify-done-headline
5048 (list (concat "^[*]+ +\\<\\("
5049 (mapconcat 'regexp-quote org-done-keywords "\\|")
5050 "\\)\\(.*\\)")
5051 '(2 'org-headline-done t))
5052 nil)
5053 ;; Priorities
5054 '(org-font-lock-add-priority-faces)
5055 ;; Tags
5056 '(org-font-lock-add-tag-faces)
5057 ;; Special keywords
5058 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5059 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5060 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5061 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5062 ;; Emphasis
5063 (if em
5064 (if (featurep 'xemacs)
5065 '(org-do-emphasis-faces (0 nil append))
5066 '(org-do-emphasis-faces)))
5067 ;; Checkboxes
5068 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5069 2 'org-checkbox prepend)
5070 (if org-provide-checkbox-statistics
5071 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5072 (0 (org-get-checkbox-statistics-face) t)))
5073 ;; Description list items
5074 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5075 2 'bold prepend)
5076 ;; ARCHIVEd headings
5077 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5078 '(1 'org-archived prepend))
5079 ;; Specials
5080 '(org-do-latex-and-special-faces)
5081 ;; Code
5082 '(org-activate-code (1 'org-code t))
5083 ;; COMMENT
5084 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5085 "\\|" org-quote-string "\\)\\>")
5086 '(1 'org-special-keyword t))
5087 '("^#.*" (0 'font-lock-comment-face t))
5088 ;; Blocks and meta lines
5089 '(org-fontify-meta-lines-and-blocks)
5091 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5092 ;; Now set the full font-lock-keywords
5093 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5094 (org-set-local 'font-lock-defaults
5095 '(org-font-lock-keywords t nil nil backward-paragraph))
5096 (kill-local-variable 'font-lock-keywords) nil))
5098 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5099 "Fontify string S like in Org-mode"
5100 (with-temp-buffer
5101 (insert s)
5102 (let ((org-odd-levels-only odd-levels))
5103 (org-mode)
5104 (font-lock-fontify-buffer)
5105 (buffer-string))))
5107 (defvar org-m nil)
5108 (defvar org-l nil)
5109 (defvar org-f nil)
5110 (defun org-get-level-face (n)
5111 "Get the right face for match N in font-lock matching of headlines."
5112 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5113 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5114 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5115 (cond
5116 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5117 ((eq n 2) org-f)
5118 (t (if org-level-color-stars-only nil org-f))))
5120 (defun org-get-todo-face (kwd)
5121 "Get the right face for a TODO keyword KWD.
5122 If KWD is a number, get the corresponding match group."
5123 (if (numberp kwd) (setq kwd (match-string kwd)))
5124 (or (org-face-from-face-or-color
5125 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5126 (and (member kwd org-done-keywords) 'org-done)
5127 'org-todo))
5129 (defun org-face-from-face-or-color (context inherit face-or-color)
5130 "Create a face list that inherits INHERIT, but sets the foreground color.
5131 When FACE-OR-COLOR is not a string, just return it."
5132 (if (stringp face-or-color)
5133 (list :inherit inherit
5134 (cdr (assoc context org-faces-easy-properties))
5135 face-or-color)
5136 face-or-color))
5138 (defun org-font-lock-add-tag-faces (limit)
5139 "Add the special tag faces."
5140 (when (and org-tag-faces org-tags-special-faces-re)
5141 (while (re-search-forward org-tags-special-faces-re limit t)
5142 (add-text-properties (match-beginning 1) (match-end 1)
5143 (list 'face (org-get-tag-face 1)
5144 'font-lock-fontified t))
5145 (backward-char 1))))
5147 (defun org-font-lock-add-priority-faces (limit)
5148 "Add the special priority faces."
5149 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5150 (add-text-properties
5151 (match-beginning 0) (match-end 0)
5152 (list 'face (or (org-face-from-face-or-color
5153 'priority 'org-special-keyword
5154 (cdr (assoc (char-after (match-beginning 1))
5155 org-priority-faces)))
5156 'org-special-keyword)
5157 'font-lock-fontified t))))
5159 (defun org-get-tag-face (kwd)
5160 "Get the right face for a TODO keyword KWD.
5161 If KWD is a number, get the corresponding match group."
5162 (if (numberp kwd) (setq kwd (match-string kwd)))
5163 (or (org-face-from-face-or-color
5164 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5165 'org-tag))
5167 (defun org-unfontify-region (beg end &optional maybe_loudly)
5168 "Remove fontification and activation overlays from links."
5169 (font-lock-default-unfontify-region beg end)
5170 (let* ((buffer-undo-list t)
5171 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5172 (inhibit-modification-hooks t)
5173 deactivate-mark buffer-file-name buffer-file-truename)
5174 (remove-text-properties
5175 beg end
5176 (if org-indent-mode
5177 ;; also remove line-prefix and wrap-prefix properties
5178 '(mouse-face t keymap t org-linked-text t
5179 invisible t intangible t
5180 line-prefix t wrap-prefix t
5181 org-no-flyspell t)
5182 '(mouse-face t keymap t org-linked-text t
5183 invisible t intangible t
5184 org-no-flyspell t)))))
5186 ;;;; Visibility cycling, including org-goto and indirect buffer
5188 ;;; Cycling
5190 (defvar org-cycle-global-status nil)
5191 (make-variable-buffer-local 'org-cycle-global-status)
5192 (defvar org-cycle-subtree-status nil)
5193 (make-variable-buffer-local 'org-cycle-subtree-status)
5195 ;;;###autoload
5197 (defvar org-inlinetask-min-level)
5199 (defun org-cycle (&optional arg)
5200 "TAB-action and visibility cycling for Org-mode.
5202 This is the command invoked in Org-mode by the TAB key. Its main purpose
5203 is outline visibility cycling, but it also invokes other actions
5204 in special contexts.
5206 - When this function is called with a prefix argument, rotate the entire
5207 buffer through 3 states (global cycling)
5208 1. OVERVIEW: Show only top-level headlines.
5209 2. CONTENTS: Show all headlines of all levels, but no body text.
5210 3. SHOW ALL: Show everything.
5211 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5212 determined by the variable `org-startup-folded', and by any VISIBILITY
5213 properties in the buffer.
5214 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5215 including any drawers.
5217 - When inside a table, re-align the table and move to the next field.
5219 - When point is at the beginning of a headline, rotate the subtree started
5220 by this line through 3 different states (local cycling)
5221 1. FOLDED: Only the main headline is shown.
5222 2. CHILDREN: The main headline and the direct children are shown.
5223 From this state, you can move to one of the children
5224 and zoom in further.
5225 3. SUBTREE: Show the entire subtree, including body text.
5226 If there is no subtree, switch directly from CHILDREN to FOLDED.
5228 - When point is at the beginning of an empty headline and the variable
5229 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5230 of the headline by demoting and promoting it to likely levels. This
5231 speeds up creation document structure by presing TAB once or several
5232 times right after creating a new headline.
5234 - When there is a numeric prefix, go up to a heading with level ARG, do
5235 a `show-subtree' and return to the previous cursor position. If ARG
5236 is negative, go up that many levels.
5238 - When point is not at the beginning of a headline, execute the global
5239 binding for TAB, which is re-indenting the line. See the option
5240 `org-cycle-emulate-tab' for details.
5242 - Special case: if point is at the beginning of the buffer and there is
5243 no headline in line 1, this function will act as if called with prefix arg.
5244 But only if also the variable `org-cycle-global-at-bob' is t."
5245 (interactive "P")
5246 (org-load-modules-maybe)
5247 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5248 (and org-cycle-level-after-item/entry-creation
5249 (or (org-cycle-level)
5250 (org-cycle-item-indentation))))
5251 (let* ((limit-level
5252 (or org-cycle-max-level
5253 (and (boundp 'org-inlinetask-min-level)
5254 org-inlinetask-min-level
5255 (1- org-inlinetask-min-level))))
5256 (nstars (and limit-level
5257 (if org-odd-levels-only
5258 (and limit-level (1- (* limit-level 2)))
5259 limit-level)))
5260 (outline-regexp
5261 (cond
5262 ((not (org-mode-p)) outline-regexp)
5263 ((or (eq org-cycle-include-plain-lists 'integrate)
5264 (and org-cycle-include-plain-lists (org-at-item-p)))
5265 (concat "\\(?:\\*"
5266 (if nstars (format "\\{1,%d\\}" nstars) "+")
5267 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5268 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5269 (bob-special (and org-cycle-global-at-bob (bobp)
5270 (not (looking-at outline-regexp))))
5271 (org-cycle-hook
5272 (if bob-special
5273 (delq 'org-optimize-window-after-visibility-change
5274 (copy-sequence org-cycle-hook))
5275 org-cycle-hook))
5276 (pos (point)))
5278 (if (or bob-special (equal arg '(4)))
5279 ;; special case: use global cycling
5280 (setq arg t))
5282 (cond
5284 ((equal arg '(16))
5285 (org-set-startup-visibility)
5286 (message "Startup visibility, plus VISIBILITY properties"))
5288 ((equal arg '(64))
5289 (show-all)
5290 (message "Entire buffer visible, including drawers"))
5292 ((org-at-table-p 'any)
5293 ;; Enter the table or move to the next field in the table
5294 (if (org-at-table.el-p)
5295 (message "Use C-c ' to edit table.el tables")
5296 (if arg (org-table-edit-field t)
5297 (org-table-justify-field-maybe)
5298 (call-interactively 'org-table-next-field))))
5300 ((run-hook-with-args-until-success
5301 'org-tab-after-check-for-table-hook))
5303 ((eq arg t) ;; Global cycling
5304 (org-cycle-internal-global))
5306 ((and org-drawers org-drawer-regexp
5307 (save-excursion
5308 (beginning-of-line 1)
5309 (looking-at org-drawer-regexp)))
5310 ;; Toggle block visibility
5311 (org-flag-drawer
5312 (not (get-char-property (match-end 0) 'invisible))))
5314 ((integerp arg)
5315 ;; Show-subtree, ARG levels up from here.
5316 (save-excursion
5317 (org-back-to-heading)
5318 (outline-up-heading (if (< arg 0) (- arg)
5319 (- (funcall outline-level) arg)))
5320 (org-show-subtree)))
5322 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5323 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5325 (org-cycle-internal-local))
5327 ;; TAB emulation and template completion
5328 (buffer-read-only (org-back-to-heading))
5330 ((run-hook-with-args-until-success
5331 'org-tab-after-check-for-cycling-hook))
5333 ((org-try-structure-completion))
5335 ((org-try-cdlatex-tab))
5337 ((run-hook-with-args-until-success
5338 'org-tab-before-tab-emulation-hook))
5340 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5341 (or (not (bolp))
5342 (not (looking-at outline-regexp))))
5343 (call-interactively (global-key-binding "\t")))
5345 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5346 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5347 (or (and (eq org-cycle-emulate-tab 'white)
5348 (= (match-end 0) (point-at-eol)))
5349 (and (eq org-cycle-emulate-tab 'whitestart)
5350 (>= (match-end 0) pos))))
5352 (eq org-cycle-emulate-tab t))
5353 (call-interactively (global-key-binding "\t")))
5355 (t (save-excursion
5356 (org-back-to-heading)
5357 (org-cycle)))))))
5359 (defun org-cycle-internal-global ()
5360 "Do the global cycling action."
5361 (cond
5362 ((and (eq last-command this-command)
5363 (eq org-cycle-global-status 'overview))
5364 ;; We just created the overview - now do table of contents
5365 ;; This can be slow in very large buffers, so indicate action
5366 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5367 (message "CONTENTS...")
5368 (org-content)
5369 (message "CONTENTS...done")
5370 (setq org-cycle-global-status 'contents)
5371 (run-hook-with-args 'org-cycle-hook 'contents))
5373 ((and (eq last-command this-command)
5374 (eq org-cycle-global-status 'contents))
5375 ;; We just showed the table of contents - now show everything
5376 (run-hook-with-args 'org-pre-cycle-hook 'all)
5377 (show-all)
5378 (message "SHOW ALL")
5379 (setq org-cycle-global-status 'all)
5380 (run-hook-with-args 'org-cycle-hook 'all))
5383 ;; Default action: go to overview
5384 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5385 (org-overview)
5386 (message "OVERVIEW")
5387 (setq org-cycle-global-status 'overview)
5388 (run-hook-with-args 'org-cycle-hook 'overview))))
5390 (defun org-cycle-internal-local ()
5391 "Do the local cycling action."
5392 (org-back-to-heading)
5393 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5394 ;; First, some boundaries
5395 (save-excursion
5396 (org-back-to-heading)
5397 (setq level (funcall outline-level))
5398 (save-excursion
5399 (beginning-of-line 2)
5400 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5401 ; XEmacs does not have `next-single-char-property-change'
5402 ; I'm not sure about Emacs 21.
5403 (while (and (not (eobp)) ;; this is like `next-line'
5404 (get-char-property (1- (point)) 'invisible))
5405 (beginning-of-line 2))
5406 (while (and (not (eobp)) ;; this is like `next-line'
5407 (get-char-property (1- (point)) 'invisible))
5408 (goto-char (next-single-char-property-change (point) 'invisible))
5409 ;;;??? (or (bolp) (beginning-of-line 2))))
5410 (and (eolp) (beginning-of-line 2))))
5411 (setq eol (point)))
5412 (outline-end-of-heading) (setq eoh (point))
5413 (save-excursion
5414 (outline-next-heading)
5415 (setq has-children (and (org-at-heading-p t)
5416 (> (funcall outline-level) level))))
5417 (org-end-of-subtree t)
5418 (unless (eobp)
5419 (skip-chars-forward " \t\n")
5420 (beginning-of-line 1) ; in case this is an item
5422 (setq eos (if (eobp) (point) (1- (point)))))
5423 ;; Find out what to do next and set `this-command'
5424 (cond
5425 ((= eos eoh)
5426 ;; Nothing is hidden behind this heading
5427 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5428 (message "EMPTY ENTRY")
5429 (setq org-cycle-subtree-status nil)
5430 (save-excursion
5431 (goto-char eos)
5432 (outline-next-heading)
5433 (if (org-invisible-p) (org-flag-heading nil))))
5434 ((and (or (>= eol eos)
5435 (not (string-match "\\S-" (buffer-substring eol eos))))
5436 (or has-children
5437 (not (setq children-skipped
5438 org-cycle-skip-children-state-if-no-children))))
5439 ;; Entire subtree is hidden in one line: children view
5440 (run-hook-with-args 'org-pre-cycle-hook 'children)
5441 (org-show-entry)
5442 (show-children)
5443 (message "CHILDREN")
5444 (save-excursion
5445 (goto-char eos)
5446 (outline-next-heading)
5447 (if (org-invisible-p) (org-flag-heading nil)))
5448 (setq org-cycle-subtree-status 'children)
5449 (run-hook-with-args 'org-cycle-hook 'children))
5450 ((or children-skipped
5451 (and (eq last-command this-command)
5452 (eq org-cycle-subtree-status 'children)))
5453 ;; We just showed the children, or no children are there,
5454 ;; now show everything.
5455 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5456 (org-show-subtree)
5457 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5458 (setq org-cycle-subtree-status 'subtree)
5459 (run-hook-with-args 'org-cycle-hook 'subtree))
5461 ;; Default action: hide the subtree.
5462 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5463 (hide-subtree)
5464 (message "FOLDED")
5465 (setq org-cycle-subtree-status 'folded)
5466 (run-hook-with-args 'org-cycle-hook 'folded)))))
5468 ;;;###autoload
5469 (defun org-global-cycle (&optional arg)
5470 "Cycle the global visibility. For details see `org-cycle'.
5471 With C-u prefix arg, switch to startup visibility.
5472 With a numeric prefix, show all headlines up to that level."
5473 (interactive "P")
5474 (let ((org-cycle-include-plain-lists
5475 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5476 (cond
5477 ((integerp arg)
5478 (show-all)
5479 (hide-sublevels arg)
5480 (setq org-cycle-global-status 'contents))
5481 ((equal arg '(4))
5482 (org-set-startup-visibility)
5483 (message "Startup visibility, plus VISIBILITY properties."))
5485 (org-cycle '(4))))))
5487 (defun org-set-startup-visibility ()
5488 "Set the visibility required by startup options and properties."
5489 (cond
5490 ((eq org-startup-folded t)
5491 (org-cycle '(4)))
5492 ((eq org-startup-folded 'content)
5493 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5494 (org-cycle '(4)) (org-cycle '(4)))))
5495 (unless (eq org-startup-folded 'showeverything)
5496 (if org-hide-block-startup (org-hide-block-all))
5497 (org-set-visibility-according-to-property 'no-cleanup)
5498 (org-cycle-hide-archived-subtrees 'all)
5499 (org-cycle-hide-drawers 'all)
5500 (org-cycle-show-empty-lines 'all)))
5502 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5503 "Switch subtree visibilities according to :VISIBILITY: property."
5504 (interactive)
5505 (let (org-show-entry-below state)
5506 (save-excursion
5507 (goto-char (point-min))
5508 (while (re-search-forward
5509 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5510 nil t)
5511 (setq state (match-string 1))
5512 (save-excursion
5513 (org-back-to-heading t)
5514 (hide-subtree)
5515 (org-reveal)
5516 (cond
5517 ((equal state '("fold" "folded"))
5518 (hide-subtree))
5519 ((equal state "children")
5520 (org-show-hidden-entry)
5521 (show-children))
5522 ((equal state "content")
5523 (save-excursion
5524 (save-restriction
5525 (org-narrow-to-subtree)
5526 (org-content))))
5527 ((member state '("all" "showall"))
5528 (show-subtree)))))
5529 (unless no-cleanup
5530 (org-cycle-hide-archived-subtrees 'all)
5531 (org-cycle-hide-drawers 'all)
5532 (org-cycle-show-empty-lines 'all)))))
5534 (defun org-overview ()
5535 "Switch to overview mode, showing only top-level headlines.
5536 Really, this shows all headlines with level equal or greater than the level
5537 of the first headline in the buffer. This is important, because if the
5538 first headline is not level one, then (hide-sublevels 1) gives confusing
5539 results."
5540 (interactive)
5541 (let ((level (save-excursion
5542 (goto-char (point-min))
5543 (if (re-search-forward (concat "^" outline-regexp) nil t)
5544 (progn
5545 (goto-char (match-beginning 0))
5546 (funcall outline-level))))))
5547 (and level (hide-sublevels level))))
5549 (defun org-content (&optional arg)
5550 "Show all headlines in the buffer, like a table of contents.
5551 With numerical argument N, show content up to level N."
5552 (interactive "P")
5553 (save-excursion
5554 ;; Visit all headings and show their offspring
5555 (and (integerp arg) (org-overview))
5556 (goto-char (point-max))
5557 (catch 'exit
5558 (while (and (progn (condition-case nil
5559 (outline-previous-visible-heading 1)
5560 (error (goto-char (point-min))))
5562 (looking-at outline-regexp))
5563 (if (integerp arg)
5564 (show-children (1- arg))
5565 (show-branches))
5566 (if (bobp) (throw 'exit nil))))))
5569 (defun org-optimize-window-after-visibility-change (state)
5570 "Adjust the window after a change in outline visibility.
5571 This function is the default value of the hook `org-cycle-hook'."
5572 (when (get-buffer-window (current-buffer))
5573 (cond
5574 ((eq state 'content) nil)
5575 ((eq state 'all) nil)
5576 ((eq state 'folded) nil)
5577 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5578 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5580 (defun org-remove-empty-overlays-at (pos)
5581 "Remove outline overlays that do not contain non-white stuff."
5582 (mapc
5583 (lambda (o)
5584 (and (eq 'outline (org-overlay-get o 'invisible))
5585 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5586 (org-overlay-end o))))
5587 (org-delete-overlay o)))
5588 (org-overlays-at pos)))
5590 (defun org-clean-visibility-after-subtree-move ()
5591 "Fix visibility issues after moving a subtree."
5592 ;; First, find a reasonable region to look at:
5593 ;; Start two siblings above, end three below
5594 (let* ((beg (save-excursion
5595 (and (org-get-last-sibling)
5596 (org-get-last-sibling))
5597 (point)))
5598 (end (save-excursion
5599 (and (org-get-next-sibling)
5600 (org-get-next-sibling)
5601 (org-get-next-sibling))
5602 (if (org-at-heading-p)
5603 (point-at-eol)
5604 (point))))
5605 (level (looking-at "\\*+"))
5606 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5607 (save-excursion
5608 (save-restriction
5609 (narrow-to-region beg end)
5610 (when re
5611 ;; Properly fold already folded siblings
5612 (goto-char (point-min))
5613 (while (re-search-forward re nil t)
5614 (if (and (not (org-invisible-p))
5615 (save-excursion
5616 (goto-char (point-at-eol)) (org-invisible-p)))
5617 (hide-entry))))
5618 (org-cycle-show-empty-lines 'overview)
5619 (org-cycle-hide-drawers 'overview)))))
5621 (defun org-cycle-show-empty-lines (state)
5622 "Show empty lines above all visible headlines.
5623 The region to be covered depends on STATE when called through
5624 `org-cycle-hook'. Lisp program can use t for STATE to get the
5625 entire buffer covered. Note that an empty line is only shown if there
5626 are at least `org-cycle-separator-lines' empty lines before the headline."
5627 (when (not (= org-cycle-separator-lines 0))
5628 (save-excursion
5629 (let* ((n (abs org-cycle-separator-lines))
5630 (re (cond
5631 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5632 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5633 (t (let ((ns (number-to-string (- n 2))))
5634 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5635 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5636 beg end b e)
5637 (cond
5638 ((memq state '(overview contents t))
5639 (setq beg (point-min) end (point-max)))
5640 ((memq state '(children folded))
5641 (setq beg (point) end (progn (org-end-of-subtree t t)
5642 (beginning-of-line 2)
5643 (point)))))
5644 (when beg
5645 (goto-char beg)
5646 (while (re-search-forward re end t)
5647 (unless (get-char-property (match-end 1) 'invisible)
5648 (setq e (match-end 1))
5649 (if (< org-cycle-separator-lines 0)
5650 (setq b (save-excursion
5651 (goto-char (match-beginning 0))
5652 (org-back-over-empty-lines)
5653 (if (save-excursion
5654 (goto-char (max (point-min) (1- (point))))
5655 (org-on-heading-p))
5656 (1- (point))
5657 (point))))
5658 (setq b (match-beginning 1)))
5659 (outline-flag-region b e nil)))))))
5660 ;; Never hide empty lines at the end of the file.
5661 (save-excursion
5662 (goto-char (point-max))
5663 (outline-previous-heading)
5664 (outline-end-of-heading)
5665 (if (and (looking-at "[ \t\n]+")
5666 (= (match-end 0) (point-max)))
5667 (outline-flag-region (point) (match-end 0) nil))))
5669 (defun org-show-empty-lines-in-parent ()
5670 "Move to the parent and re-show empty lines before visible headlines."
5671 (save-excursion
5672 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5673 (org-cycle-show-empty-lines context))))
5675 (defun org-files-list ()
5676 "Return `org-agenda-files' list, plus all open org-mode files.
5677 This is useful for operations that need to scan all of a user's
5678 open and agenda-wise Org files."
5679 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5680 (dolist (buf (buffer-list))
5681 (with-current-buffer buf
5682 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5683 (let ((file (expand-file-name (buffer-file-name))))
5684 (unless (member file files)
5685 (push file files))))))
5686 files))
5688 (defsubst org-entry-beginning-position ()
5689 "Return the beginning position of the current entry."
5690 (save-excursion (outline-back-to-heading t) (point)))
5692 (defsubst org-entry-end-position ()
5693 "Return the end position of the current entry."
5694 (save-excursion (outline-next-heading) (point)))
5696 (defun org-cycle-hide-drawers (state)
5697 "Re-hide all drawers after a visibility state change."
5698 (when (and (org-mode-p)
5699 (not (memq state '(overview folded contents))))
5700 (save-excursion
5701 (let* ((globalp (memq state '(contents all)))
5702 (beg (if globalp (point-min) (point)))
5703 (end (if globalp (point-max)
5704 (if (eq state 'children)
5705 (save-excursion (outline-next-heading) (point))
5706 (org-end-of-subtree t)))))
5707 (goto-char beg)
5708 (while (re-search-forward org-drawer-regexp end t)
5709 (org-flag-drawer t))))))
5711 (defun org-flag-drawer (flag)
5712 (save-excursion
5713 (beginning-of-line 1)
5714 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5715 (let ((b (match-end 0))
5716 (outline-regexp org-outline-regexp))
5717 (if (re-search-forward
5718 "^[ \t]*:END:"
5719 (save-excursion (outline-next-heading) (point)) t)
5720 (outline-flag-region b (point-at-eol) flag)
5721 (error ":END: line missing at position %s" b))))))
5723 (defun org-subtree-end-visible-p ()
5724 "Is the end of the current subtree visible?"
5725 (pos-visible-in-window-p
5726 (save-excursion (org-end-of-subtree t) (point))))
5728 (defun org-first-headline-recenter (&optional N)
5729 "Move cursor to the first headline and recenter the headline.
5730 Optional argument N means put the headline into the Nth line of the window."
5731 (goto-char (point-min))
5732 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5733 (beginning-of-line)
5734 (recenter (prefix-numeric-value N))))
5736 ;;; Saving and restoring visibility
5738 (defun org-outline-overlay-data (&optional use-markers)
5739 "Return a list of the locations of all outline overlays.
5740 The are overlays with the `invisible' property value `outline'.
5741 The return valus is a list of cons cells, with start and stop
5742 positions for each overlay.
5743 If USE-MARKERS is set, return the positions as markers."
5744 (let (beg end)
5745 (save-excursion
5746 (save-restriction
5747 (widen)
5748 (delq nil
5749 (mapcar (lambda (o)
5750 (when (eq (org-overlay-get o 'invisible) 'outline)
5751 (setq beg (org-overlay-start o)
5752 end (org-overlay-end o))
5753 (and beg end (> end beg)
5754 (if use-markers
5755 (cons (move-marker (make-marker) beg)
5756 (move-marker (make-marker) end))
5757 (cons beg end)))))
5758 (org-overlays-in (point-min) (point-max))))))))
5760 (defun org-set-outline-overlay-data (data)
5761 "Create visibility overlays for all positions in DATA.
5762 DATA should have been made by `org-outline-overlay-data'."
5763 (let (o)
5764 (save-excursion
5765 (save-restriction
5766 (widen)
5767 (show-all)
5768 (mapc (lambda (c)
5769 (setq o (org-make-overlay (car c) (cdr c)))
5770 (org-overlay-put o 'invisible 'outline))
5771 data)))))
5773 (defmacro org-save-outline-visibility (use-markers &rest body)
5774 "Save and restore outline visibility around BODY.
5775 If USE-MARKERS is non-nil, use markers for the positions.
5776 This means that the buffer may change while running BODY,
5777 but it also means that the buffer should stay alive
5778 during the operation, because otherwise all these markers will
5779 point nowhere."
5780 `(let ((data (org-outline-overlay-data ,use-markers)))
5781 (unwind-protect
5782 (progn
5783 ,@body
5784 (org-set-outline-overlay-data data))
5785 (when ,use-markers
5786 (mapc (lambda (c)
5787 (and (markerp (car c)) (move-marker (car c) nil))
5788 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
5789 data)))))
5792 ;;; Folding of blocks
5794 (defconst org-block-regexp
5796 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5797 "Regular expression for hiding blocks.")
5799 (defvar org-hide-block-overlays nil
5800 "Overlays hiding blocks.")
5801 (make-variable-buffer-local 'org-hide-block-overlays)
5803 (defun org-block-map (function &optional start end)
5804 "Call func at the head of all source blocks in the current
5805 buffer. Optional arguments START and END can be used to limit
5806 the range."
5807 (let ((start (or start (point-min)))
5808 (end (or end (point-max))))
5809 (save-excursion
5810 (goto-char start)
5811 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5812 (save-excursion
5813 (save-match-data
5814 (goto-char (match-beginning 0))
5815 (funcall function)))))))
5817 (defun org-hide-block-toggle-all ()
5818 "Toggle the visibility of all blocks in the current buffer."
5819 (org-block-map #'org-hide-block-toggle))
5821 (defun org-hide-block-all ()
5822 "Fold all blocks in the current buffer."
5823 (interactive)
5824 (org-show-block-all)
5825 (org-block-map #'org-hide-block-toggle-maybe))
5827 (defun org-show-block-all ()
5828 "Unfold all blocks in the current buffer."
5829 (mapc 'org-delete-overlay org-hide-block-overlays)
5830 (setq org-hide-block-overlays nil))
5832 (defun org-hide-block-toggle-maybe ()
5833 "Toggle visibility of block at point."
5834 (interactive)
5835 (let ((case-fold-search t))
5836 (if (save-excursion
5837 (beginning-of-line 1)
5838 (looking-at org-block-regexp))
5839 (progn (org-hide-block-toggle)
5840 t) ;; to signal that we took action
5841 nil))) ;; to signal that we did not
5843 (defun org-hide-block-toggle (&optional force)
5844 "Toggle the visibility of the current block."
5845 (interactive)
5846 (save-excursion
5847 (beginning-of-line)
5848 (if (re-search-forward org-block-regexp nil t)
5849 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5850 (end (match-end 0)) ;; end of entire body
5852 (if (memq t (mapcar (lambda (overlay)
5853 (eq (org-overlay-get overlay 'invisible)
5854 'org-hide-block))
5855 (org-overlays-at start)))
5856 (if (or (not force) (eq force 'off))
5857 (mapc (lambda (ov)
5858 (when (member ov org-hide-block-overlays)
5859 (setq org-hide-block-overlays
5860 (delq ov org-hide-block-overlays)))
5861 (when (eq (org-overlay-get ov 'invisible)
5862 'org-hide-block)
5863 (org-delete-overlay ov)))
5864 (org-overlays-at start)))
5865 (setq ov (org-make-overlay start end))
5866 (org-overlay-put ov 'invisible 'org-hide-block)
5867 ;; make the block accessible to isearch
5868 (org-overlay-put
5869 ov 'isearch-open-invisible
5870 (lambda (ov)
5871 (when (member ov org-hide-block-overlays)
5872 (setq org-hide-block-overlays
5873 (delq ov org-hide-block-overlays)))
5874 (when (eq (org-overlay-get ov 'invisible)
5875 'org-hide-block)
5876 (org-delete-overlay ov))))
5877 (push ov org-hide-block-overlays)))
5878 (error "Not looking at a source block"))))
5880 ;; org-tab-after-check-for-cycling-hook
5881 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5882 ;; Remove overlays when changing major mode
5883 (add-hook 'org-mode-hook
5884 (lambda () (org-add-hook 'change-major-mode-hook
5885 'org-show-block-all 'append 'local)))
5887 ;;; Org-goto
5889 (defvar org-goto-window-configuration nil)
5890 (defvar org-goto-marker nil)
5891 (defvar org-goto-map
5892 (let ((map (make-sparse-keymap)))
5893 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5894 (while (setq cmd (pop cmds))
5895 (substitute-key-definition cmd cmd map global-map)))
5896 (suppress-keymap map)
5897 (org-defkey map "\C-m" 'org-goto-ret)
5898 (org-defkey map [(return)] 'org-goto-ret)
5899 (org-defkey map [(left)] 'org-goto-left)
5900 (org-defkey map [(right)] 'org-goto-right)
5901 (org-defkey map [(control ?g)] 'org-goto-quit)
5902 (org-defkey map "\C-i" 'org-cycle)
5903 (org-defkey map [(tab)] 'org-cycle)
5904 (org-defkey map [(down)] 'outline-next-visible-heading)
5905 (org-defkey map [(up)] 'outline-previous-visible-heading)
5906 (if org-goto-auto-isearch
5907 (if (fboundp 'define-key-after)
5908 (define-key-after map [t] 'org-goto-local-auto-isearch)
5909 nil)
5910 (org-defkey map "q" 'org-goto-quit)
5911 (org-defkey map "n" 'outline-next-visible-heading)
5912 (org-defkey map "p" 'outline-previous-visible-heading)
5913 (org-defkey map "f" 'outline-forward-same-level)
5914 (org-defkey map "b" 'outline-backward-same-level)
5915 (org-defkey map "u" 'outline-up-heading))
5916 (org-defkey map "/" 'org-occur)
5917 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5918 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5919 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5920 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5921 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5922 map))
5924 (defconst org-goto-help
5925 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5926 RET=jump to location [Q]uit and return to previous location
5927 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5929 (defvar org-goto-start-pos) ; dynamically scoped parameter
5931 ;; FIXME: Docstring does not mention both interfaces
5932 (defun org-goto (&optional alternative-interface)
5933 "Look up a different location in the current file, keeping current visibility.
5935 When you want look-up or go to a different location in a document, the
5936 fastest way is often to fold the entire buffer and then dive into the tree.
5937 This method has the disadvantage, that the previous location will be folded,
5938 which may not be what you want.
5940 This command works around this by showing a copy of the current buffer
5941 in an indirect buffer, in overview mode. You can dive into the tree in
5942 that copy, use org-occur and incremental search to find a location.
5943 When pressing RET or `Q', the command returns to the original buffer in
5944 which the visibility is still unchanged. After RET is will also jump to
5945 the location selected in the indirect buffer and expose the
5946 the headline hierarchy above."
5947 (interactive "P")
5948 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5949 (org-refile-use-outline-path t)
5950 (org-refile-target-verify-function nil)
5951 (interface
5952 (if (not alternative-interface)
5953 org-goto-interface
5954 (if (eq org-goto-interface 'outline)
5955 'outline-path-completion
5956 'outline)))
5957 (org-goto-start-pos (point))
5958 (selected-point
5959 (if (eq interface 'outline)
5960 (car (org-get-location (current-buffer) org-goto-help))
5961 (nth 3 (org-refile-get-location "Goto: ")))))
5962 (if selected-point
5963 (progn
5964 (org-mark-ring-push org-goto-start-pos)
5965 (goto-char selected-point)
5966 (if (or (org-invisible-p) (org-invisible-p2))
5967 (org-show-context 'org-goto)))
5968 (message "Quit"))))
5970 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5971 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5972 (defvar org-goto-local-auto-isearch-map) ; defined below
5974 (defun org-get-location (buf help)
5975 "Let the user select a location in the Org-mode buffer BUF.
5976 This function uses a recursive edit. It returns the selected position
5977 or nil."
5978 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5979 (isearch-hide-immediately nil)
5980 (isearch-search-fun-function
5981 (lambda () 'org-goto-local-search-headings))
5982 (org-goto-selected-point org-goto-exit-command)
5983 (pop-up-frames nil)
5984 (special-display-buffer-names nil)
5985 (special-display-regexps nil)
5986 (special-display-function nil))
5987 (save-excursion
5988 (save-window-excursion
5989 (delete-other-windows)
5990 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5991 (switch-to-buffer
5992 (condition-case nil
5993 (make-indirect-buffer (current-buffer) "*org-goto*")
5994 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5995 (with-output-to-temp-buffer "*Help*"
5996 (princ help))
5997 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5998 (setq buffer-read-only nil)
5999 (let ((org-startup-truncated t)
6000 (org-startup-folded nil)
6001 (org-startup-align-all-tables nil))
6002 (org-mode)
6003 (org-overview))
6004 (setq buffer-read-only t)
6005 (if (and (boundp 'org-goto-start-pos)
6006 (integer-or-marker-p org-goto-start-pos))
6007 (let ((org-show-hierarchy-above t)
6008 (org-show-siblings t)
6009 (org-show-following-heading t))
6010 (goto-char org-goto-start-pos)
6011 (and (org-invisible-p) (org-show-context)))
6012 (goto-char (point-min)))
6013 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6014 (message "Select location and press RET")
6015 (use-local-map org-goto-map)
6016 (recursive-edit)
6018 (kill-buffer "*org-goto*")
6019 (cons org-goto-selected-point org-goto-exit-command)))
6021 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6022 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6023 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6024 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6026 (defun org-goto-local-search-headings (string bound noerror)
6027 "Search and make sure that any matches are in headlines."
6028 (catch 'return
6029 (while (if isearch-forward
6030 (search-forward string bound noerror)
6031 (search-backward string bound noerror))
6032 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6033 (and (member :headline context)
6034 (not (member :tags context))))
6035 (throw 'return (point))))))
6037 (defun org-goto-local-auto-isearch ()
6038 "Start isearch."
6039 (interactive)
6040 (goto-char (point-min))
6041 (let ((keys (this-command-keys)))
6042 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6043 (isearch-mode t)
6044 (isearch-process-search-char (string-to-char keys)))))
6046 (defun org-goto-ret (&optional arg)
6047 "Finish `org-goto' by going to the new location."
6048 (interactive "P")
6049 (setq org-goto-selected-point (point)
6050 org-goto-exit-command 'return)
6051 (throw 'exit nil))
6053 (defun org-goto-left ()
6054 "Finish `org-goto' by going to the new location."
6055 (interactive)
6056 (if (org-on-heading-p)
6057 (progn
6058 (beginning-of-line 1)
6059 (setq org-goto-selected-point (point)
6060 org-goto-exit-command 'left)
6061 (throw 'exit nil))
6062 (error "Not on a heading")))
6064 (defun org-goto-right ()
6065 "Finish `org-goto' by going to the new location."
6066 (interactive)
6067 (if (org-on-heading-p)
6068 (progn
6069 (setq org-goto-selected-point (point)
6070 org-goto-exit-command 'right)
6071 (throw 'exit nil))
6072 (error "Not on a heading")))
6074 (defun org-goto-quit ()
6075 "Finish `org-goto' without cursor motion."
6076 (interactive)
6077 (setq org-goto-selected-point nil)
6078 (setq org-goto-exit-command 'quit)
6079 (throw 'exit nil))
6081 ;;; Indirect buffer display of subtrees
6083 (defvar org-indirect-dedicated-frame nil
6084 "This is the frame being used for indirect tree display.")
6085 (defvar org-last-indirect-buffer nil)
6087 (defun org-tree-to-indirect-buffer (&optional arg)
6088 "Create indirect buffer and narrow it to current subtree.
6089 With numerical prefix ARG, go up to this level and then take that tree.
6090 If ARG is negative, go up that many levels.
6091 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6092 indirect buffer previously made with this command, to avoid proliferation of
6093 indirect buffers. However, when you call the command with a `C-u' prefix, or
6094 when `org-indirect-buffer-display' is `new-frame', the last buffer
6095 is kept so that you can work with several indirect buffers at the same time.
6096 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6097 requests that a new frame be made for the new buffer, so that the dedicated
6098 frame is not changed."
6099 (interactive "P")
6100 (let ((cbuf (current-buffer))
6101 (cwin (selected-window))
6102 (pos (point))
6103 beg end level heading ibuf)
6104 (save-excursion
6105 (org-back-to-heading t)
6106 (when (numberp arg)
6107 (setq level (org-outline-level))
6108 (if (< arg 0) (setq arg (+ level arg)))
6109 (while (> (setq level (org-outline-level)) arg)
6110 (outline-up-heading 1 t)))
6111 (setq beg (point)
6112 heading (org-get-heading))
6113 (org-end-of-subtree t t)
6114 (if (org-on-heading-p) (backward-char 1))
6115 (setq end (point)))
6116 (if (and (buffer-live-p org-last-indirect-buffer)
6117 (not (eq org-indirect-buffer-display 'new-frame))
6118 (not arg))
6119 (kill-buffer org-last-indirect-buffer))
6120 (setq ibuf (org-get-indirect-buffer cbuf)
6121 org-last-indirect-buffer ibuf)
6122 (cond
6123 ((or (eq org-indirect-buffer-display 'new-frame)
6124 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6125 (select-frame (make-frame))
6126 (delete-other-windows)
6127 (switch-to-buffer ibuf)
6128 (org-set-frame-title heading))
6129 ((eq org-indirect-buffer-display 'dedicated-frame)
6130 (raise-frame
6131 (select-frame (or (and org-indirect-dedicated-frame
6132 (frame-live-p org-indirect-dedicated-frame)
6133 org-indirect-dedicated-frame)
6134 (setq org-indirect-dedicated-frame (make-frame)))))
6135 (delete-other-windows)
6136 (switch-to-buffer ibuf)
6137 (org-set-frame-title (concat "Indirect: " heading)))
6138 ((eq org-indirect-buffer-display 'current-window)
6139 (switch-to-buffer ibuf))
6140 ((eq org-indirect-buffer-display 'other-window)
6141 (pop-to-buffer ibuf))
6142 (t (error "Invalid value")))
6143 (if (featurep 'xemacs)
6144 (save-excursion (org-mode) (turn-on-font-lock)))
6145 (narrow-to-region beg end)
6146 (show-all)
6147 (goto-char pos)
6148 (and (window-live-p cwin) (select-window cwin))))
6150 (defun org-get-indirect-buffer (&optional buffer)
6151 (setq buffer (or buffer (current-buffer)))
6152 (let ((n 1) (base (buffer-name buffer)) bname)
6153 (while (buffer-live-p
6154 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6155 (setq n (1+ n)))
6156 (condition-case nil
6157 (make-indirect-buffer buffer bname 'clone)
6158 (error (make-indirect-buffer buffer bname)))))
6160 (defun org-set-frame-title (title)
6161 "Set the title of the current frame to the string TITLE."
6162 ;; FIXME: how to name a single frame in XEmacs???
6163 (unless (featurep 'xemacs)
6164 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6166 ;;;; Structure editing
6168 ;;; Inserting headlines
6170 (defun org-previous-line-empty-p ()
6171 (save-excursion
6172 (and (not (bobp))
6173 (or (beginning-of-line 0) t)
6174 (save-match-data
6175 (looking-at "[ \t]*$")))))
6177 (defun org-insert-heading (&optional force-heading invisible-ok)
6178 "Insert a new heading or item with same depth at point.
6179 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6180 If point is at the beginning of a headline, insert a sibling before the
6181 current headline. If point is not at the beginning, do not split the line,
6182 but create the new headline after the current line.
6183 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6184 This is important for non-interactive uses of the command."
6185 (interactive "P")
6186 (if (or (= (buffer-size) 0)
6187 (and (not (save-excursion (and (ignore-errors (org-back-to-heading invisible-ok))
6188 (org-on-heading-p))))
6189 (not (org-in-item-p))))
6190 (insert "\n* ")
6191 (when (or force-heading (not (org-insert-item)))
6192 (let* ((empty-line-p nil)
6193 (head (save-excursion
6194 (condition-case nil
6195 (progn
6196 (org-back-to-heading invisible-ok)
6197 (setq empty-line-p (org-previous-line-empty-p))
6198 (match-string 0))
6199 (error "*"))))
6200 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6201 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6202 pos hide-previous previous-pos)
6203 (cond
6204 ((and (org-on-heading-p) (bolp)
6205 (or (bobp)
6206 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6207 ;; insert before the current line
6208 (open-line (if blank 2 1)))
6209 ((and (bolp)
6210 (not org-insert-heading-respect-content)
6211 (or (bobp)
6212 (save-excursion
6213 (backward-char 1) (not (org-invisible-p)))))
6214 ;; insert right here
6215 nil)
6217 ;; somewhere in the line
6218 (save-excursion
6219 (setq previous-pos (point-at-bol))
6220 (end-of-line)
6221 (setq hide-previous (org-invisible-p)))
6222 (and org-insert-heading-respect-content (org-show-subtree))
6223 (let ((split
6224 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6225 (save-excursion
6226 (let ((p (point)))
6227 (goto-char (point-at-bol))
6228 (and (looking-at org-complex-heading-regexp)
6229 (> p (match-beginning 4)))))))
6230 tags pos)
6231 (cond
6232 (org-insert-heading-respect-content
6233 (org-end-of-subtree nil t)
6234 (or (bolp) (newline))
6235 (or (org-previous-line-empty-p)
6236 (and blank (newline)))
6237 (open-line 1))
6238 ((org-on-heading-p)
6239 (when hide-previous
6240 (show-children)
6241 (org-show-entry))
6242 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6243 (setq tags (and (match-end 2) (match-string 2)))
6244 (and (match-end 1)
6245 (delete-region (match-beginning 1) (match-end 1)))
6246 (setq pos (point-at-bol))
6247 (or split (end-of-line 1))
6248 (delete-horizontal-space)
6249 (if (string-match "\\`\\*+\\'"
6250 (buffer-substring (point-at-bol) (point)))
6251 (insert " "))
6252 (newline (if blank 2 1))
6253 (when tags
6254 (save-excursion
6255 (goto-char pos)
6256 (end-of-line 1)
6257 (insert " " tags)
6258 (org-set-tags nil 'align))))
6260 (or split (end-of-line 1))
6261 (newline (if blank 2 1)))))))
6262 (insert head) (just-one-space)
6263 (setq pos (point))
6264 (end-of-line 1)
6265 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6266 (when (and org-insert-heading-respect-content hide-previous)
6267 (save-excursion
6268 (goto-char previous-pos)
6269 (hide-subtree)))
6270 (run-hooks 'org-insert-heading-hook)))))
6272 (defun org-get-heading (&optional no-tags)
6273 "Return the heading of the current entry, without the stars."
6274 (save-excursion
6275 (org-back-to-heading t)
6276 (if (looking-at
6277 (if no-tags
6278 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6279 "\\*+[ \t]+\\([^\r\n]*\\)"))
6280 (match-string 1) "")))
6282 (defun org-heading-components ()
6283 "Return the components of the current heading.
6284 This is a list with the following elements:
6285 - the level as an integer
6286 - the reduced level, different if `org-odd-levels-only' is set.
6287 - the TODO keyword, or nil
6288 - the priority character, like ?A, or nil if no priority is given
6289 - the headline text itself, or the tags string if no headline text
6290 - the tags string, or nil."
6291 (save-excursion
6292 (org-back-to-heading t)
6293 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6294 (list (length (match-string 1))
6295 (org-reduced-level (length (match-string 1)))
6296 (org-match-string-no-properties 2)
6297 (and (match-end 3) (aref (match-string 3) 2))
6298 (org-match-string-no-properties 4)
6299 (org-match-string-no-properties 5)))))
6301 (defun org-get-entry ()
6302 "Get the entry text, after heading, entire subtree."
6303 (save-excursion
6304 (org-back-to-heading t)
6305 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6307 (defun org-insert-heading-after-current ()
6308 "Insert a new heading with same level as current, after current subtree."
6309 (interactive)
6310 (org-back-to-heading)
6311 (org-insert-heading)
6312 (org-move-subtree-down)
6313 (end-of-line 1))
6315 (defun org-insert-heading-respect-content ()
6316 (interactive)
6317 (let ((org-insert-heading-respect-content t))
6318 (org-insert-heading t)))
6320 (defun org-insert-todo-heading-respect-content (&optional force-state)
6321 (interactive "P")
6322 (let ((org-insert-heading-respect-content t))
6323 (org-insert-todo-heading force-state t)))
6325 (defun org-insert-todo-heading (arg &optional force-heading)
6326 "Insert a new heading with the same level and TODO state as current heading.
6327 If the heading has no TODO state, or if the state is DONE, use the first
6328 state (TODO by default). Also with prefix arg, force first state."
6329 (interactive "P")
6330 (when (or force-heading (not (org-insert-item 'checkbox)))
6331 (org-insert-heading force-heading)
6332 (save-excursion
6333 (org-back-to-heading)
6334 (outline-previous-heading)
6335 (looking-at org-todo-line-regexp))
6336 (let*
6337 ((new-mark-x
6338 (if (or arg
6339 (not (match-beginning 2))
6340 (member (match-string 2) org-done-keywords))
6341 (car org-todo-keywords-1)
6342 (match-string 2)))
6343 (new-mark
6345 (run-hook-with-args-until-success
6346 'org-todo-get-default-hook new-mark-x nil)
6347 new-mark-x)))
6348 (beginning-of-line 1)
6349 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6350 (if org-treat-insert-todo-heading-as-state-change
6351 (org-todo new-mark)
6352 (insert new-mark " "))))
6353 (when org-provide-todo-statistics
6354 (org-update-parent-todo-statistics))))
6356 (defun org-insert-subheading (arg)
6357 "Insert a new subheading and demote it.
6358 Works for outline headings and for plain lists alike."
6359 (interactive "P")
6360 (org-insert-heading arg)
6361 (cond
6362 ((org-on-heading-p) (org-do-demote))
6363 ((org-at-item-p) (org-indent-item 1))))
6365 (defun org-insert-todo-subheading (arg)
6366 "Insert a new subheading with TODO keyword or checkbox and demote it.
6367 Works for outline headings and for plain lists alike."
6368 (interactive "P")
6369 (org-insert-todo-heading arg)
6370 (cond
6371 ((org-on-heading-p) (org-do-demote))
6372 ((org-at-item-p) (org-indent-item 1))))
6374 ;;; Promotion and Demotion
6376 (defvar org-after-demote-entry-hook nil
6377 "Hook run after an entry has been demoted.
6378 The cursor will be at the beginning of the entry.
6379 When a subtree is being demoted, the hook will be called for each node.")
6381 (defvar org-after-promote-entry-hook nil
6382 "Hook run after an entry has been promoted.
6383 The cursor will be at the beginning of the entry.
6384 When a subtree is being promoted, the hook will be called for each node.")
6386 (defun org-promote-subtree ()
6387 "Promote the entire subtree.
6388 See also `org-promote'."
6389 (interactive)
6390 (save-excursion
6391 (org-map-tree 'org-promote))
6392 (org-fix-position-after-promote))
6394 (defun org-demote-subtree ()
6395 "Demote the entire subtree. See `org-demote'.
6396 See also `org-promote'."
6397 (interactive)
6398 (save-excursion
6399 (org-map-tree 'org-demote))
6400 (org-fix-position-after-promote))
6403 (defun org-do-promote ()
6404 "Promote the current heading higher up the tree.
6405 If the region is active in `transient-mark-mode', promote all headings
6406 in the region."
6407 (interactive)
6408 (save-excursion
6409 (if (org-region-active-p)
6410 (org-map-region 'org-promote (region-beginning) (region-end))
6411 (org-promote)))
6412 (org-fix-position-after-promote))
6414 (defun org-do-demote ()
6415 "Demote the current heading lower down the tree.
6416 If the region is active in `transient-mark-mode', demote all headings
6417 in the region."
6418 (interactive)
6419 (save-excursion
6420 (if (org-region-active-p)
6421 (org-map-region 'org-demote (region-beginning) (region-end))
6422 (org-demote)))
6423 (org-fix-position-after-promote))
6425 (defun org-fix-position-after-promote ()
6426 "Make sure that after pro/demotion cursor position is right."
6427 (let ((pos (point)))
6428 (when (save-excursion
6429 (beginning-of-line 1)
6430 (looking-at org-todo-line-regexp)
6431 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6432 (cond ((eobp) (insert " "))
6433 ((eolp) (insert " "))
6434 ((equal (char-after) ?\ ) (forward-char 1))))))
6436 (defun org-current-level ()
6437 "Return the level of the current entry, or nil if before the first headline.
6438 The level is the number of stars at the beginning of the headline."
6439 (save-excursion
6440 (condition-case nil
6441 (progn
6442 (org-back-to-heading t)
6443 (funcall outline-level))
6444 (error nil))))
6446 (defun org-get-previous-line-level ()
6447 "Return the outline depth of the last headline before the current line.
6448 Returns 0 for the first headline in the buffer, and nil if before the
6449 first headline."
6450 (let ((current-level (org-current-level))
6451 (prev-level (when (> (line-number-at-pos) 1)
6452 (save-excursion
6453 (beginning-of-line 0)
6454 (org-current-level)))))
6455 (cond ((null current-level) nil) ; Before first headline
6456 ((null prev-level) 0) ; At first headline
6457 (prev-level))))
6459 (defun org-reduced-level (l)
6460 "Compute the effective level of a heading.
6461 This takes into account the setting of `org-odd-levels-only'."
6462 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6464 (defun org-level-increment ()
6465 "Return the number of stars that will be added or removed at a
6466 time to headlines when structure editing, based on the value of
6467 `org-odd-levels-only'."
6468 (if org-odd-levels-only 2 1))
6470 (defun org-get-valid-level (level &optional change)
6471 "Rectify a level change under the influence of `org-odd-levels-only'
6472 LEVEL is a current level, CHANGE is by how much the level should be
6473 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6474 even level numbers will become the next higher odd number."
6475 (if org-odd-levels-only
6476 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6477 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6478 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6479 (max 1 (+ level (or change 0)))))
6481 (if (boundp 'define-obsolete-function-alias)
6482 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6483 (define-obsolete-function-alias 'org-get-legal-level
6484 'org-get-valid-level)
6485 (define-obsolete-function-alias 'org-get-legal-level
6486 'org-get-valid-level "23.1")))
6488 (defun org-promote ()
6489 "Promote the current heading higher up the tree.
6490 If the region is active in `transient-mark-mode', promote all headings
6491 in the region."
6492 (org-back-to-heading t)
6493 (let* ((level (save-match-data (funcall outline-level)))
6494 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6495 (diff (abs (- level (length up-head) -1))))
6496 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6497 (replace-match up-head nil t)
6498 ;; Fixup tag positioning
6499 (and org-auto-align-tags (org-set-tags nil t))
6500 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6501 (run-hooks 'org-after-promote-entry-hook)))
6503 (defun org-demote ()
6504 "Demote the current heading lower down the tree.
6505 If the region is active in `transient-mark-mode', demote all headings
6506 in the region."
6507 (org-back-to-heading t)
6508 (let* ((level (save-match-data (funcall outline-level)))
6509 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6510 (diff (abs (- level (length down-head) -1))))
6511 (replace-match down-head nil t)
6512 ;; Fixup tag positioning
6513 (and org-auto-align-tags (org-set-tags nil t))
6514 (if org-adapt-indentation (org-fixup-indentation diff))
6515 (run-hooks 'org-after-demote-entry-hook)))
6517 (defun org-cycle-level ()
6518 "Cycle the level of an empty headline through possible states.
6519 This goes first to child, then to parent, level, then up the hierarchy.
6520 After top level, it switches back to sibling level."
6521 (interactive)
6522 (let ((org-adapt-indentation nil))
6523 (when (org-point-at-end-of-empty-headline)
6524 (setq this-command 'org-cycle-level) ; Only needed for caching
6525 (let ((cur-level (org-current-level))
6526 (prev-level (org-get-previous-line-level)))
6527 (cond
6528 ;; If first headline in file, promote to top-level.
6529 ((= prev-level 0)
6530 (loop repeat (/ (- cur-level 1) (org-level-increment))
6531 do (org-do-promote)))
6532 ;; If same level as prev, demote one.
6533 ((= prev-level cur-level)
6534 (org-do-demote))
6535 ;; If parent is top-level, promote to top level if not already.
6536 ((= prev-level 1)
6537 (loop repeat (/ (- cur-level 1) (org-level-increment))
6538 do (org-do-promote)))
6539 ;; If top-level, return to prev-level.
6540 ((= cur-level 1)
6541 (loop repeat (/ (- prev-level 1) (org-level-increment))
6542 do (org-do-demote)))
6543 ;; If less than prev-level, promote one.
6544 ((< cur-level prev-level)
6545 (org-do-promote))
6546 ;; If deeper than prev-level, promote until higher than
6547 ;; prev-level.
6548 ((> cur-level prev-level)
6549 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
6550 do (org-do-promote))))
6551 t))))
6553 (defun org-map-tree (fun)
6554 "Call FUN for every heading underneath the current one."
6555 (org-back-to-heading)
6556 (let ((level (funcall outline-level)))
6557 (save-excursion
6558 (funcall fun)
6559 (while (and (progn
6560 (outline-next-heading)
6561 (> (funcall outline-level) level))
6562 (not (eobp)))
6563 (funcall fun)))))
6565 (defun org-map-region (fun beg end)
6566 "Call FUN for every heading between BEG and END."
6567 (let ((org-ignore-region t))
6568 (save-excursion
6569 (setq end (copy-marker end))
6570 (goto-char beg)
6571 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6572 (< (point) end))
6573 (funcall fun))
6574 (while (and (progn
6575 (outline-next-heading)
6576 (< (point) end))
6577 (not (eobp)))
6578 (funcall fun)))))
6580 (defun org-fixup-indentation (diff)
6581 "Change the indentation in the current entry by DIFF
6582 However, if any line in the current entry has no indentation, or if it
6583 would end up with no indentation after the change, nothing at all is done."
6584 (save-excursion
6585 (let ((end (save-excursion (outline-next-heading)
6586 (point-marker)))
6587 (prohibit (if (> diff 0)
6588 "^\\S-"
6589 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6590 col)
6591 (unless (save-excursion (end-of-line 1)
6592 (re-search-forward prohibit end t))
6593 (while (and (< (point) end)
6594 (re-search-forward "^[ \t]+" end t))
6595 (goto-char (match-end 0))
6596 (setq col (current-column))
6597 (if (< diff 0) (replace-match ""))
6598 (org-indent-to-column (+ diff col))))
6599 (move-marker end nil))))
6601 (defun org-convert-to-odd-levels ()
6602 "Convert an org-mode file with all levels allowed to one with odd levels.
6603 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6604 level 5 etc."
6605 (interactive)
6606 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6607 (let ((outline-regexp org-outline-regexp)
6608 (outline-level 'org-outline-level)
6609 (org-odd-levels-only nil) n)
6610 (save-excursion
6611 (goto-char (point-min))
6612 (while (re-search-forward "^\\*\\*+ " nil t)
6613 (setq n (- (length (match-string 0)) 2))
6614 (while (>= (setq n (1- n)) 0)
6615 (org-demote))
6616 (end-of-line 1))))))
6618 (defun org-convert-to-oddeven-levels ()
6619 "Convert an org-mode file with only odd levels to one with odd and even levels.
6620 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6621 section with an even level, conversion would destroy the structure of the file. An error
6622 is signaled in this case."
6623 (interactive)
6624 (goto-char (point-min))
6625 ;; First check if there are no even levels
6626 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6627 (org-show-context t)
6628 (error "Not all levels are odd in this file. Conversion not possible"))
6629 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6630 (let ((outline-regexp org-outline-regexp)
6631 (outline-level 'org-outline-level)
6632 (org-odd-levels-only nil) n)
6633 (save-excursion
6634 (goto-char (point-min))
6635 (while (re-search-forward "^\\*\\*+ " nil t)
6636 (setq n (/ (1- (length (match-string 0))) 2))
6637 (while (>= (setq n (1- n)) 0)
6638 (org-promote))
6639 (end-of-line 1))))))
6641 (defun org-tr-level (n)
6642 "Make N odd if required."
6643 (if org-odd-levels-only (1+ (/ n 2)) n))
6645 ;;; Vertical tree motion, cutting and pasting of subtrees
6647 (defun org-move-subtree-up (&optional arg)
6648 "Move the current subtree up past ARG headlines of the same level."
6649 (interactive "p")
6650 (org-move-subtree-down (- (prefix-numeric-value arg))))
6652 (defun org-move-subtree-down (&optional arg)
6653 "Move the current subtree down past ARG headlines of the same level."
6654 (interactive "p")
6655 (setq arg (prefix-numeric-value arg))
6656 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6657 'org-get-last-sibling))
6658 (ins-point (make-marker))
6659 (cnt (abs arg))
6660 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6661 ;; Select the tree
6662 (org-back-to-heading)
6663 (setq beg0 (point))
6664 (save-excursion
6665 (setq ne-beg (org-back-over-empty-lines))
6666 (setq beg (point)))
6667 (save-match-data
6668 (save-excursion (outline-end-of-heading)
6669 (setq folded (org-invisible-p)))
6670 (outline-end-of-subtree))
6671 (outline-next-heading)
6672 (setq ne-end (org-back-over-empty-lines))
6673 (setq end (point))
6674 (goto-char beg0)
6675 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6676 ;; include less whitespace
6677 (save-excursion
6678 (goto-char beg)
6679 (forward-line (- ne-beg ne-end))
6680 (setq beg (point))))
6681 ;; Find insertion point, with error handling
6682 (while (> cnt 0)
6683 (or (and (funcall movfunc) (looking-at outline-regexp))
6684 (progn (goto-char beg0)
6685 (error "Cannot move past superior level or buffer limit")))
6686 (setq cnt (1- cnt)))
6687 (if (> arg 0)
6688 ;; Moving forward - still need to move over subtree
6689 (progn (org-end-of-subtree t t)
6690 (save-excursion
6691 (org-back-over-empty-lines)
6692 (or (bolp) (newline)))))
6693 (setq ne-ins (org-back-over-empty-lines))
6694 (move-marker ins-point (point))
6695 (setq txt (buffer-substring beg end))
6696 (org-save-markers-in-region beg end)
6697 (delete-region beg end)
6698 (org-remove-empty-overlays-at beg)
6699 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6700 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6701 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6702 (let ((bbb (point)))
6703 (insert-before-markers txt)
6704 (org-reinstall-markers-in-region bbb)
6705 (move-marker ins-point bbb))
6706 (or (bolp) (insert "\n"))
6707 (setq ins-end (point))
6708 (goto-char ins-point)
6709 (org-skip-whitespace)
6710 (when (and (< arg 0)
6711 (org-first-sibling-p)
6712 (> ne-ins ne-beg))
6713 ;; Move whitespace back to beginning
6714 (save-excursion
6715 (goto-char ins-end)
6716 (let ((kill-whole-line t))
6717 (kill-line (- ne-ins ne-beg)) (point)))
6718 (insert (make-string (- ne-ins ne-beg) ?\n)))
6719 (move-marker ins-point nil)
6720 (if folded
6721 (hide-subtree)
6722 (org-show-entry)
6723 (show-children)
6724 (org-cycle-hide-drawers 'children))
6725 (org-clean-visibility-after-subtree-move)))
6727 (defvar org-subtree-clip ""
6728 "Clipboard for cut and paste of subtrees.
6729 This is actually only a copy of the kill, because we use the normal kill
6730 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6732 (defvar org-subtree-clip-folded nil
6733 "Was the last copied subtree folded?
6734 This is used to fold the tree back after pasting.")
6736 (defun org-cut-subtree (&optional n)
6737 "Cut the current subtree into the clipboard.
6738 With prefix arg N, cut this many sequential subtrees.
6739 This is a short-hand for marking the subtree and then cutting it."
6740 (interactive "p")
6741 (org-copy-subtree n 'cut))
6743 (defun org-copy-subtree (&optional n cut force-store-markers)
6744 "Cut the current subtree into the clipboard.
6745 With prefix arg N, cut this many sequential subtrees.
6746 This is a short-hand for marking the subtree and then copying it.
6747 If CUT is non-nil, actually cut the subtree.
6748 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6749 of some markers in the region, even if CUT is non-nil. This is
6750 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6751 (interactive "p")
6752 (let (beg end folded (beg0 (point)))
6753 (if (interactive-p)
6754 (org-back-to-heading nil) ; take what looks like a subtree
6755 (org-back-to-heading t)) ; take what is really there
6756 (org-back-over-empty-lines)
6757 (setq beg (point))
6758 (skip-chars-forward " \t\r\n")
6759 (save-match-data
6760 (save-excursion (outline-end-of-heading)
6761 (setq folded (org-invisible-p)))
6762 (condition-case nil
6763 (org-forward-same-level (1- n) t)
6764 (error nil))
6765 (org-end-of-subtree t t))
6766 (org-back-over-empty-lines)
6767 (setq end (point))
6768 (goto-char beg0)
6769 (when (> end beg)
6770 (setq org-subtree-clip-folded folded)
6771 (when (or cut force-store-markers)
6772 (org-save-markers-in-region beg end))
6773 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6774 (setq org-subtree-clip (current-kill 0))
6775 (message "%s: Subtree(s) with %d characters"
6776 (if cut "Cut" "Copied")
6777 (length org-subtree-clip)))))
6779 (defun org-paste-subtree (&optional level tree for-yank)
6780 "Paste the clipboard as a subtree, with modification of headline level.
6781 The entire subtree is promoted or demoted in order to match a new headline
6782 level.
6784 If the cursor is at the beginning of a headline, the same level as
6785 that headline is used to paste the tree
6787 If not, the new level is derived from the *visible* headings
6788 before and after the insertion point, and taken to be the inferior headline
6789 level of the two. So if the previous visible heading is level 3 and the
6790 next is level 4 (or vice versa), level 4 will be used for insertion.
6791 This makes sure that the subtree remains an independent subtree and does
6792 not swallow low level entries.
6794 You can also force a different level, either by using a numeric prefix
6795 argument, or by inserting the heading marker by hand. For example, if the
6796 cursor is after \"*****\", then the tree will be shifted to level 5.
6798 If optional TREE is given, use this text instead of the kill ring.
6800 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6801 move back over whitespace before inserting, and move point to the end of
6802 the inserted text when done."
6803 (interactive "P")
6804 (setq tree (or tree (and kill-ring (current-kill 0))))
6805 (unless (org-kill-is-subtree-p tree)
6806 (error "%s"
6807 (substitute-command-keys
6808 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6809 (let* ((visp (not (org-invisible-p)))
6810 (txt tree)
6811 (^re (concat "^\\(" outline-regexp "\\)"))
6812 (re (concat "\\(" outline-regexp "\\)"))
6813 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6815 (old-level (if (string-match ^re txt)
6816 (- (match-end 0) (match-beginning 0) 1)
6817 -1))
6818 (force-level (cond (level (prefix-numeric-value level))
6819 ((and (looking-at "[ \t]*$")
6820 (string-match
6821 ^re_ (buffer-substring
6822 (point-at-bol) (point))))
6823 (- (match-end 1) (match-beginning 1)))
6824 ((and (bolp)
6825 (looking-at org-outline-regexp))
6826 (- (match-end 0) (point) 1))
6827 (t nil)))
6828 (previous-level (save-excursion
6829 (condition-case nil
6830 (progn
6831 (outline-previous-visible-heading 1)
6832 (if (looking-at re)
6833 (- (match-end 0) (match-beginning 0) 1)
6835 (error 1))))
6836 (next-level (save-excursion
6837 (condition-case nil
6838 (progn
6839 (or (looking-at outline-regexp)
6840 (outline-next-visible-heading 1))
6841 (if (looking-at re)
6842 (- (match-end 0) (match-beginning 0) 1)
6844 (error 1))))
6845 (new-level (or force-level (max previous-level next-level)))
6846 (shift (if (or (= old-level -1)
6847 (= new-level -1)
6848 (= old-level new-level))
6850 (- new-level old-level)))
6851 (delta (if (> shift 0) -1 1))
6852 (func (if (> shift 0) 'org-demote 'org-promote))
6853 (org-odd-levels-only nil)
6854 beg end newend)
6855 ;; Remove the forced level indicator
6856 (if force-level
6857 (delete-region (point-at-bol) (point)))
6858 ;; Paste
6859 (beginning-of-line 1)
6860 (unless for-yank (org-back-over-empty-lines))
6861 (setq beg (point))
6862 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6863 (insert-before-markers txt)
6864 (unless (string-match "\n\\'" txt) (insert "\n"))
6865 (setq newend (point))
6866 (org-reinstall-markers-in-region beg)
6867 (setq end (point))
6868 (goto-char beg)
6869 (skip-chars-forward " \t\n\r")
6870 (setq beg (point))
6871 (if (and (org-invisible-p) visp)
6872 (save-excursion (outline-show-heading)))
6873 ;; Shift if necessary
6874 (unless (= shift 0)
6875 (save-restriction
6876 (narrow-to-region beg end)
6877 (while (not (= shift 0))
6878 (org-map-region func (point-min) (point-max))
6879 (setq shift (+ delta shift)))
6880 (goto-char (point-min))
6881 (setq newend (point-max))))
6882 (when (or (interactive-p) for-yank)
6883 (message "Clipboard pasted as level %d subtree" new-level))
6884 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6885 kill-ring
6886 (eq org-subtree-clip (current-kill 0))
6887 org-subtree-clip-folded)
6888 ;; The tree was folded before it was killed/copied
6889 (hide-subtree))
6890 (and for-yank (goto-char newend))))
6892 (defun org-kill-is-subtree-p (&optional txt)
6893 "Check if the current kill is an outline subtree, or a set of trees.
6894 Returns nil if kill does not start with a headline, or if the first
6895 headline level is not the largest headline level in the tree.
6896 So this will actually accept several entries of equal levels as well,
6897 which is OK for `org-paste-subtree'.
6898 If optional TXT is given, check this string instead of the current kill."
6899 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6900 (start-level (and kill
6901 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6902 org-outline-regexp "\\)")
6903 kill)
6904 (- (match-end 2) (match-beginning 2) 1)))
6905 (re (concat "^" org-outline-regexp))
6906 (start (1+ (or (match-beginning 2) -1))))
6907 (if (not start-level)
6908 (progn
6909 nil) ;; does not even start with a heading
6910 (catch 'exit
6911 (while (setq start (string-match re kill (1+ start)))
6912 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6913 (throw 'exit nil)))
6914 t))))
6916 (defvar org-markers-to-move nil
6917 "Markers that should be moved with a cut-and-paste operation.
6918 Those markers are stored together with their positions relative to
6919 the start of the region.")
6921 (defun org-save-markers-in-region (beg end)
6922 "Check markers in region.
6923 If these markers are between BEG and END, record their position relative
6924 to BEG, so that after moving the block of text, we can put the markers back
6925 into place.
6926 This function gets called just before an entry or tree gets cut from the
6927 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6928 called immediately, to move the markers with the entries."
6929 (setq org-markers-to-move nil)
6930 (when (featurep 'org-clock)
6931 (org-clock-save-markers-for-cut-and-paste beg end))
6932 (when (featurep 'org-agenda)
6933 (org-agenda-save-markers-for-cut-and-paste beg end)))
6935 (defun org-check-and-save-marker (marker beg end)
6936 "Check if MARKER is between BEG and END.
6937 If yes, remember the marker and the distance to BEG."
6938 (when (and (marker-buffer marker)
6939 (equal (marker-buffer marker) (current-buffer)))
6940 (if (and (>= marker beg) (< marker end))
6941 (push (cons marker (- marker beg)) org-markers-to-move))))
6943 (defun org-reinstall-markers-in-region (beg)
6944 "Move all remembered markers to their position relative to BEG."
6945 (mapc (lambda (x)
6946 (move-marker (car x) (+ beg (cdr x))))
6947 org-markers-to-move)
6948 (setq org-markers-to-move nil))
6950 (defun org-narrow-to-subtree ()
6951 "Narrow buffer to the current subtree."
6952 (interactive)
6953 (save-excursion
6954 (save-match-data
6955 (narrow-to-region
6956 (progn (org-back-to-heading t) (point))
6957 (progn (org-end-of-subtree t t)
6958 (if (org-on-heading-p) (backward-char 1))
6959 (point))))))
6961 (defun org-clone-subtree-with-time-shift (n &optional shift)
6962 "Clone the task (subtree) at point N times.
6963 The clones will be inserted as siblings.
6965 In interactive use, the user will be prompted for the number of clones
6966 to be produced, and for a time SHIFT, which may be a repeater as used
6967 in time stamps, for example `+3d'.
6969 When a valid repeater is given and the entry contains any time stamps,
6970 the clones will become a sequence in time, with time stamps in the
6971 subtree shifted for each clone produced. If SHIFT is nil or the
6972 empty string, time stamps will be left alone.
6974 If the original subtree did contain time stamps with a repeater,
6975 the following will happen:
6976 - the repeater will be removed in each clone
6977 - an additional clone will be produced, with the current, unshifted
6978 date(s) in the entry.
6979 - the original entry will be placed *after* all the clones, with
6980 repeater intact.
6981 - the start days in the repeater in the original entry will be shifted
6982 to past the last clone.
6983 I this way you can spell out a number of instances of a repeating task,
6984 and still retain the repeater to cover future instances of the task."
6985 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6986 (let (beg end template task
6987 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6988 (if (not (and (integerp n) (> n 0)))
6989 (error "Invalid number of replications %s" n))
6990 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6991 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6992 shift)))
6993 (error "Invalid shift specification %s" shift))
6994 (when doshift
6995 (setq shift-n (string-to-number (match-string 1 shift))
6996 shift-what (cdr (assoc (match-string 2 shift)
6997 '(("d" . day) ("w" . week)
6998 ("m" . month) ("y" . year))))))
6999 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7000 (setq nmin 1 nmax n)
7001 (org-back-to-heading t)
7002 (setq beg (point))
7003 (org-end-of-subtree t t)
7004 (or (bolp) (insert "\n"))
7005 (setq end (point))
7006 (setq template (buffer-substring beg end))
7007 (when (and doshift
7008 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7009 (delete-region beg end)
7010 (setq end beg)
7011 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7012 (goto-char end)
7013 (loop for n from nmin to nmax do
7014 (if (not doshift)
7015 (setq task template)
7016 (with-temp-buffer
7017 (insert template)
7018 (org-mode)
7019 (goto-char (point-min))
7020 (while (re-search-forward org-ts-regexp-both nil t)
7021 (org-timestamp-change (* n shift-n) shift-what))
7022 (unless (= n n-no-remove)
7023 (goto-char (point-min))
7024 (while (re-search-forward org-ts-regexp nil t)
7025 (save-excursion
7026 (goto-char (match-beginning 0))
7027 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7028 (delete-region (match-beginning 1) (match-end 1))))))
7029 (setq task (buffer-string))))
7030 (insert task))
7031 (goto-char beg)))
7033 ;;; Outline Sorting
7035 (defun org-sort (with-case)
7036 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
7037 Optional argument WITH-CASE means sort case-sensitively.
7038 With a double prefix argument, also remove duplicate entries."
7039 (interactive "P")
7040 (if (org-at-table-p)
7041 (org-call-with-arg 'org-table-sort-lines with-case)
7042 (org-call-with-arg 'org-sort-entries-or-items with-case)))
7044 (defun org-sort-remove-invisible (s)
7045 (remove-text-properties 0 (length s) org-rm-props s)
7046 (while (string-match org-bracket-link-regexp s)
7047 (setq s (replace-match (if (match-end 2)
7048 (match-string 3 s)
7049 (match-string 1 s)) t t s)))
7052 (defvar org-priority-regexp) ; defined later in the file
7054 (defvar org-after-sorting-entries-or-items-hook nil
7055 "Hook that is run after a bunch of entries or items have been sorted.
7056 When children are sorted, the cursor is in the parent line when this
7057 hook gets called. When a region or a plain list is sorted, the cursor
7058 will be in the first entry of the sorted region/list.")
7060 (defun org-sort-entries-or-items
7061 (&optional with-case sorting-type getkey-func compare-func property)
7062 "Sort entries on a certain level of an outline tree, or plain list items.
7063 If there is an active region, the entries in the region are sorted.
7064 Else, if the cursor is before the first entry, sort the top-level items.
7065 Else, the children of the entry at point are sorted.
7066 If the cursor is at the first item in a plain list, the list items will be
7067 sorted.
7069 Sorting can be alphabetically, numerically, by date/time as given by
7070 a time stamp, by a property or by priority.
7072 The command prompts for the sorting type unless it has been given to the
7073 function through the SORTING-TYPE argument, which needs to a character,
7074 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7075 precise meaning of each character:
7077 n Numerically, by converting the beginning of the entry/item to a number.
7078 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7079 t By date/time, either the first active time stamp in the entry, or, if
7080 none exist, by the first inactive one.
7081 In items, only the first line will be checked.
7082 s By the scheduled date/time.
7083 d By deadline date/time.
7084 c By creation time, which is assumed to be the first inactive time stamp
7085 at the beginning of a line.
7086 p By priority according to the cookie.
7087 r By the value of a property.
7089 Capital letters will reverse the sort order.
7091 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7092 called with point at the beginning of the record. It must return either
7093 a string or a number that should serve as the sorting key for that record.
7095 Comparing entries ignores case by default. However, with an optional argument
7096 WITH-CASE, the sorting considers case as well."
7097 (interactive "P")
7098 (let ((case-func (if with-case 'identity 'downcase))
7099 start beg end stars re re2
7100 txt what tmp plain-list-p)
7101 ;; Find beginning and end of region to sort
7102 (cond
7103 ((org-region-active-p)
7104 ;; we will sort the region
7105 (setq end (region-end)
7106 what "region")
7107 (goto-char (region-beginning))
7108 (if (not (org-on-heading-p)) (outline-next-heading))
7109 (setq start (point)))
7110 ((org-at-item-p)
7111 ;; we will sort this plain list
7112 (org-beginning-of-item-list) (setq start (point))
7113 (org-end-of-item-list)
7114 (or (bolp) (insert "\n"))
7115 (setq end (point))
7116 (goto-char start)
7117 (setq plain-list-p t
7118 what "plain list"))
7119 ((or (org-on-heading-p)
7120 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7121 ;; we will sort the children of the current headline
7122 (org-back-to-heading)
7123 (setq start (point)
7124 end (progn (org-end-of-subtree t t)
7125 (or (bolp) (insert "\n"))
7126 (org-back-over-empty-lines)
7127 (point))
7128 what "children")
7129 (goto-char start)
7130 (show-subtree)
7131 (outline-next-heading))
7133 ;; we will sort the top-level entries in this file
7134 (goto-char (point-min))
7135 (or (org-on-heading-p) (outline-next-heading))
7136 (setq start (point))
7137 (goto-char (point-max))
7138 (beginning-of-line 1)
7139 (when (looking-at ".*?\\S-")
7140 ;; File ends in a non-white line
7141 (end-of-line 1)
7142 (insert "\n"))
7143 (setq end (point-max))
7144 (setq what "top-level")
7145 (goto-char start)
7146 (show-all)))
7148 (setq beg (point))
7149 (if (>= beg end) (error "Nothing to sort"))
7151 (unless plain-list-p
7152 (looking-at "\\(\\*+\\)")
7153 (setq stars (match-string 1)
7154 re (concat "^" (regexp-quote stars) " +")
7155 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7156 txt (buffer-substring beg end))
7157 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7158 (if (and (not (equal stars "*")) (string-match re2 txt))
7159 (error "Region to sort contains a level above the first entry")))
7161 (unless sorting-type
7162 (message
7163 (if plain-list-p
7164 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7165 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7166 [t]ime [s]cheduled [d]eadline [c]reated
7167 A/N/T/S/D/C/P/O/F means reversed:")
7168 what)
7169 (setq sorting-type (read-char-exclusive))
7171 (and (= (downcase sorting-type) ?f)
7172 (setq getkey-func
7173 (org-icompleting-read "Sort using function: "
7174 obarray 'fboundp t nil nil))
7175 (setq getkey-func (intern getkey-func)))
7177 (and (= (downcase sorting-type) ?r)
7178 (setq property
7179 (org-icompleting-read "Property: "
7180 (mapcar 'list (org-buffer-property-keys t))
7181 nil t))))
7183 (message "Sorting entries...")
7185 (save-restriction
7186 (narrow-to-region start end)
7188 (let ((dcst (downcase sorting-type))
7189 (case-fold-search nil)
7190 (now (current-time)))
7191 (sort-subr
7192 (/= dcst sorting-type)
7193 ;; This function moves to the beginning character of the "record" to
7194 ;; be sorted.
7195 (if plain-list-p
7196 (lambda nil
7197 (if (org-at-item-p) t (goto-char (point-max))))
7198 (lambda nil
7199 (if (re-search-forward re nil t)
7200 (goto-char (match-beginning 0))
7201 (goto-char (point-max)))))
7202 ;; This function moves to the last character of the "record" being
7203 ;; sorted.
7204 (if plain-list-p
7205 'org-end-of-item
7206 (lambda nil
7207 (save-match-data
7208 (condition-case nil
7209 (outline-forward-same-level 1)
7210 (error
7211 (goto-char (point-max)))))))
7213 ;; This function returns the value that gets sorted against.
7214 (if plain-list-p
7215 (lambda nil
7216 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7217 (cond
7218 ((= dcst ?n)
7219 (string-to-number (buffer-substring (match-end 0)
7220 (point-at-eol))))
7221 ((= dcst ?a)
7222 (buffer-substring (match-end 0) (point-at-eol)))
7223 ((= dcst ?t)
7224 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7225 (re-search-forward org-ts-regexp-both
7226 (point-at-eol) t))
7227 (org-time-string-to-seconds (match-string 0))
7228 (org-float-time now)))
7229 ((= dcst ?f)
7230 (if getkey-func
7231 (progn
7232 (setq tmp (funcall getkey-func))
7233 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7234 tmp)
7235 (error "Invalid key function `%s'" getkey-func)))
7236 (t (error "Invalid sorting type `%c'" sorting-type)))))
7237 (lambda nil
7238 (cond
7239 ((= dcst ?n)
7240 (if (looking-at org-complex-heading-regexp)
7241 (string-to-number (match-string 4))
7242 nil))
7243 ((= dcst ?a)
7244 (if (looking-at org-complex-heading-regexp)
7245 (funcall case-func (match-string 4))
7246 nil))
7247 ((= dcst ?t)
7248 (let ((end (save-excursion (outline-next-heading) (point))))
7249 (if (or (re-search-forward org-ts-regexp end t)
7250 (re-search-forward org-ts-regexp-both end t))
7251 (org-time-string-to-seconds (match-string 0))
7252 (org-float-time now))))
7253 ((= dcst ?c)
7254 (let ((end (save-excursion (outline-next-heading) (point))))
7255 (if (re-search-forward
7256 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7257 end t)
7258 (org-time-string-to-seconds (match-string 0))
7259 (org-float-time now))))
7260 ((= dcst ?s)
7261 (let ((end (save-excursion (outline-next-heading) (point))))
7262 (if (re-search-forward org-scheduled-time-regexp end t)
7263 (org-time-string-to-seconds (match-string 1))
7264 (org-float-time now))))
7265 ((= dcst ?d)
7266 (let ((end (save-excursion (outline-next-heading) (point))))
7267 (if (re-search-forward org-deadline-time-regexp end t)
7268 (org-time-string-to-seconds (match-string 1))
7269 (org-float-time now))))
7270 ((= dcst ?p)
7271 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7272 (string-to-char (match-string 2))
7273 org-default-priority))
7274 ((= dcst ?r)
7275 (or (org-entry-get nil property) ""))
7276 ((= dcst ?o)
7277 (if (looking-at org-complex-heading-regexp)
7278 (- 9999 (length (member (match-string 2)
7279 org-todo-keywords-1)))))
7280 ((= dcst ?f)
7281 (if getkey-func
7282 (progn
7283 (setq tmp (funcall getkey-func))
7284 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7285 tmp)
7286 (error "Invalid key function `%s'" getkey-func)))
7287 (t (error "Invalid sorting type `%c'" sorting-type)))))
7289 (cond
7290 ((= dcst ?a) 'string<)
7291 ((= dcst ?f) compare-func)
7292 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7293 (t nil)))))
7294 (run-hooks 'org-after-sorting-entries-or-items-hook)
7295 (message "Sorting entries...done")))
7297 (defun org-do-sort (table what &optional with-case sorting-type)
7298 "Sort TABLE of WHAT according to SORTING-TYPE.
7299 The user will be prompted for the SORTING-TYPE if the call to this
7300 function does not specify it. WHAT is only for the prompt, to indicate
7301 what is being sorted. The sorting key will be extracted from
7302 the car of the elements of the table.
7303 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7304 (unless sorting-type
7305 (message
7306 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7307 what)
7308 (setq sorting-type (read-char-exclusive)))
7309 (let ((dcst (downcase sorting-type))
7310 extractfun comparefun)
7311 ;; Define the appropriate functions
7312 (cond
7313 ((= dcst ?n)
7314 (setq extractfun 'string-to-number
7315 comparefun (if (= dcst sorting-type) '< '>)))
7316 ((= dcst ?a)
7317 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7318 (lambda(x) (downcase (org-sort-remove-invisible x))))
7319 comparefun (if (= dcst sorting-type)
7320 'string<
7321 (lambda (a b) (and (not (string< a b))
7322 (not (string= a b)))))))
7323 ((= dcst ?t)
7324 (setq extractfun
7325 (lambda (x)
7326 (if (or (string-match org-ts-regexp x)
7327 (string-match org-ts-regexp-both x))
7328 (org-float-time
7329 (org-time-string-to-time (match-string 0 x)))
7331 comparefun (if (= dcst sorting-type) '< '>)))
7332 (t (error "Invalid sorting type `%c'" sorting-type)))
7334 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7335 table)
7336 (lambda (a b) (funcall comparefun (car a) (car b))))))
7339 ;;; The orgstruct minor mode
7341 ;; Define a minor mode which can be used in other modes in order to
7342 ;; integrate the org-mode structure editing commands.
7344 ;; This is really a hack, because the org-mode structure commands use
7345 ;; keys which normally belong to the major mode. Here is how it
7346 ;; works: The minor mode defines all the keys necessary to operate the
7347 ;; structure commands, but wraps the commands into a function which
7348 ;; tests if the cursor is currently at a headline or a plain list
7349 ;; item. If that is the case, the structure command is used,
7350 ;; temporarily setting many Org-mode variables like regular
7351 ;; expressions for filling etc. However, when any of those keys is
7352 ;; used at a different location, function uses `key-binding' to look
7353 ;; up if the key has an associated command in another currently active
7354 ;; keymap (minor modes, major mode, global), and executes that
7355 ;; command. There might be problems if any of the keys is otherwise
7356 ;; used as a prefix key.
7358 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7359 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7360 ;; addresses this by checking explicitly for both bindings.
7362 (defvar orgstruct-mode-map (make-sparse-keymap)
7363 "Keymap for the minor `orgstruct-mode'.")
7365 (defvar org-local-vars nil
7366 "List of local variables, for use by `orgstruct-mode'")
7368 ;;;###autoload
7369 (define-minor-mode orgstruct-mode
7370 "Toggle the minor more `orgstruct-mode'.
7371 This mode is for using Org-mode structure commands in other modes.
7372 The following key behave as if Org-mode was active, if the cursor
7373 is on a headline, or on a plain list item (both in the definition
7374 of Org-mode).
7376 M-up Move entry/item up
7377 M-down Move entry/item down
7378 M-left Promote
7379 M-right Demote
7380 M-S-up Move entry/item up
7381 M-S-down Move entry/item down
7382 M-S-left Promote subtree
7383 M-S-right Demote subtree
7384 M-q Fill paragraph and items like in Org-mode
7385 C-c ^ Sort entries
7386 C-c - Cycle list bullet
7387 TAB Cycle item visibility
7388 M-RET Insert new heading/item
7389 S-M-RET Insert new TODO heading / Checkbox item
7390 C-c C-c Set tags / toggle checkbox"
7391 nil " OrgStruct" nil
7392 (org-load-modules-maybe)
7393 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7395 ;;;###autoload
7396 (defun turn-on-orgstruct ()
7397 "Unconditionally turn on `orgstruct-mode'."
7398 (orgstruct-mode 1))
7400 (defun orgstruct++-mode (&optional arg)
7401 "Toggle `orgstruct-mode', the enhanced version of it.
7402 In addition to setting orgstruct-mode, this also exports all indentation
7403 and autofilling variables from org-mode into the buffer. It will also
7404 recognize item context in multiline items.
7405 Note that turning off orgstruct-mode will *not* remove the
7406 indentation/paragraph settings. This can only be done by refreshing the
7407 major mode, for example with \\[normal-mode]."
7408 (interactive "P")
7409 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7410 (if (< arg 1)
7411 (orgstruct-mode -1)
7412 (orgstruct-mode 1)
7413 (let (var val)
7414 (mapc
7415 (lambda (x)
7416 (when (string-match
7417 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7418 (symbol-name (car x)))
7419 (setq var (car x) val (nth 1 x))
7420 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7421 org-local-vars)
7422 (org-set-local 'orgstruct-is-++ t))))
7424 (defvar orgstruct-is-++ nil
7425 "Is orgstruct-mode in ++ version in the current-buffer?")
7426 (make-variable-buffer-local 'orgstruct-is-++)
7428 ;;;###autoload
7429 (defun turn-on-orgstruct++ ()
7430 "Unconditionally turn on `orgstruct++-mode'."
7431 (orgstruct++-mode 1))
7433 (defun orgstruct-error ()
7434 "Error when there is no default binding for a structure key."
7435 (interactive)
7436 (error "This key has no function outside structure elements"))
7438 (defun orgstruct-setup ()
7439 "Setup orgstruct keymaps."
7440 (let ((nfunc 0)
7441 (bindings
7442 (list
7443 '([(meta up)] org-metaup)
7444 '([(meta down)] org-metadown)
7445 '([(meta left)] org-metaleft)
7446 '([(meta right)] org-metaright)
7447 '([(meta shift up)] org-shiftmetaup)
7448 '([(meta shift down)] org-shiftmetadown)
7449 '([(meta shift left)] org-shiftmetaleft)
7450 '([(meta shift right)] org-shiftmetaright)
7451 '([?\e (up)] org-metaup)
7452 '([?\e (down)] org-metadown)
7453 '([?\e (left)] org-metaleft)
7454 '([?\e (right)] org-metaright)
7455 '([?\e (shift up)] org-shiftmetaup)
7456 '([?\e (shift down)] org-shiftmetadown)
7457 '([?\e (shift left)] org-shiftmetaleft)
7458 '([?\e (shift right)] org-shiftmetaright)
7459 '([(shift up)] org-shiftup)
7460 '([(shift down)] org-shiftdown)
7461 '([(shift left)] org-shiftleft)
7462 '([(shift right)] org-shiftright)
7463 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7464 '("\M-q" fill-paragraph)
7465 '("\C-c^" org-sort)
7466 '("\C-c-" org-cycle-list-bullet)))
7467 elt key fun cmd)
7468 (while (setq elt (pop bindings))
7469 (setq nfunc (1+ nfunc))
7470 (setq key (org-key (car elt))
7471 fun (nth 1 elt)
7472 cmd (orgstruct-make-binding fun nfunc key))
7473 (org-defkey orgstruct-mode-map key cmd))
7475 ;; Special treatment needed for TAB and RET
7476 (org-defkey orgstruct-mode-map [(tab)]
7477 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7478 (org-defkey orgstruct-mode-map "\C-i"
7479 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7481 (org-defkey orgstruct-mode-map "\M-\C-m"
7482 (orgstruct-make-binding 'org-insert-heading 105
7483 "\M-\C-m" [(meta return)]))
7484 (org-defkey orgstruct-mode-map [(meta return)]
7485 (orgstruct-make-binding 'org-insert-heading 106
7486 [(meta return)] "\M-\C-m"))
7488 (org-defkey orgstruct-mode-map [(shift meta return)]
7489 (orgstruct-make-binding 'org-insert-todo-heading 107
7490 [(meta return)] "\M-\C-m"))
7492 (org-defkey orgstruct-mode-map "\e\C-m"
7493 (orgstruct-make-binding 'org-insert-heading 108
7494 "\e\C-m" [?\e (return)]))
7495 (org-defkey orgstruct-mode-map [?\e (return)]
7496 (orgstruct-make-binding 'org-insert-heading 109
7497 [?\e (return)] "\e\C-m"))
7498 (org-defkey orgstruct-mode-map [?\e (shift return)]
7499 (orgstruct-make-binding 'org-insert-todo-heading 110
7500 [?\e (return)] "\e\C-m"))
7502 (unless org-local-vars
7503 (setq org-local-vars (org-get-local-variables)))
7507 (defun orgstruct-make-binding (fun n &rest keys)
7508 "Create a function for binding in the structure minor mode.
7509 FUN is the command to call inside a table. N is used to create a unique
7510 command name. KEYS are keys that should be checked in for a command
7511 to execute outside of tables."
7512 (eval
7513 (list 'defun
7514 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7515 '(arg)
7516 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7517 "Outside of structure, run the binding of `"
7518 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7519 "'.")
7520 '(interactive "p")
7521 (list 'if
7522 `(org-context-p 'headline 'item
7523 (and orgstruct-is-++
7524 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7525 'item-body))
7526 (list 'org-run-like-in-org-mode (list 'quote fun))
7527 (list 'let '(orgstruct-mode)
7528 (list 'call-interactively
7529 (append '(or)
7530 (mapcar (lambda (k)
7531 (list 'key-binding k))
7532 keys)
7533 '('orgstruct-error))))))))
7535 (defun org-context-p (&rest contexts)
7536 "Check if local context is any of CONTEXTS.
7537 Possible values in the list of contexts are `table', `headline', and `item'."
7538 (let ((pos (point)))
7539 (goto-char (point-at-bol))
7540 (prog1 (or (and (memq 'table contexts)
7541 (looking-at "[ \t]*|"))
7542 (and (memq 'headline contexts)
7543 ;;????????? (looking-at "\\*+"))
7544 (looking-at outline-regexp))
7545 (and (memq 'item contexts)
7546 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7547 (and (memq 'item-body contexts)
7548 (org-in-item-p)))
7549 (goto-char pos))))
7551 (defun org-get-local-variables ()
7552 "Return a list of all local variables in an org-mode buffer."
7553 (let (varlist)
7554 (with-current-buffer (get-buffer-create "*Org tmp*")
7555 (erase-buffer)
7556 (org-mode)
7557 (setq varlist (buffer-local-variables)))
7558 (kill-buffer "*Org tmp*")
7559 (delq nil
7560 (mapcar
7561 (lambda (x)
7562 (setq x
7563 (if (symbolp x)
7564 (list x)
7565 (list (car x) (list 'quote (cdr x)))))
7566 (if (string-match
7567 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7568 (symbol-name (car x)))
7569 x nil))
7570 varlist))))
7572 ;;;###autoload
7573 (defun org-run-like-in-org-mode (cmd)
7574 "Run a command, pretending that the current buffer is in Org-mode.
7575 This will temporarily bind local variables that are typically bound in
7576 Org-mode to the values they have in Org-mode, and then interactively
7577 call CMD."
7578 (org-load-modules-maybe)
7579 (unless org-local-vars
7580 (setq org-local-vars (org-get-local-variables)))
7581 (eval (list 'let org-local-vars
7582 (list 'call-interactively (list 'quote cmd)))))
7584 ;;;; Archiving
7586 (defun org-get-category (&optional pos)
7587 "Get the category applying to position POS."
7588 (get-text-property (or pos (point)) 'org-category))
7590 (defun org-refresh-category-properties ()
7591 "Refresh category text properties in the buffer."
7592 (let ((def-cat (cond
7593 ((null org-category)
7594 (if buffer-file-name
7595 (file-name-sans-extension
7596 (file-name-nondirectory buffer-file-name))
7597 "???"))
7598 ((symbolp org-category) (symbol-name org-category))
7599 (t org-category)))
7600 beg end cat pos optionp)
7601 (org-unmodified
7602 (save-excursion
7603 (save-restriction
7604 (widen)
7605 (goto-char (point-min))
7606 (put-text-property (point) (point-max) 'org-category def-cat)
7607 (while (re-search-forward
7608 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7609 (setq pos (match-end 0)
7610 optionp (equal (char-after (match-beginning 0)) ?#)
7611 cat (org-trim (match-string 2)))
7612 (if optionp
7613 (setq beg (point-at-bol) end (point-max))
7614 (org-back-to-heading t)
7615 (setq beg (point) end (org-end-of-subtree t t)))
7616 (put-text-property beg end 'org-category cat)
7617 (goto-char pos)))))))
7620 ;;;; Link Stuff
7622 ;;; Link abbreviations
7624 (defun org-link-expand-abbrev (link)
7625 "Apply replacements as defined in `org-link-abbrev-alist."
7626 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7627 (let* ((key (match-string 1 link))
7628 (as (or (assoc key org-link-abbrev-alist-local)
7629 (assoc key org-link-abbrev-alist)))
7630 (tag (and (match-end 2) (match-string 3 link)))
7631 rpl)
7632 (if (not as)
7633 link
7634 (setq rpl (cdr as))
7635 (cond
7636 ((symbolp rpl) (funcall rpl tag))
7637 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7638 ((string-match "%h" rpl)
7639 (replace-match (url-hexify-string (or tag "")) t t rpl))
7640 (t (concat rpl tag)))))
7641 link))
7643 ;;; Storing and inserting links
7645 (defvar org-insert-link-history nil
7646 "Minibuffer history for links inserted with `org-insert-link'.")
7648 (defvar org-stored-links nil
7649 "Contains the links stored with `org-store-link'.")
7651 (defvar org-store-link-plist nil
7652 "Plist with info about the most recently link created with `org-store-link'.")
7654 (defvar org-link-protocols nil
7655 "Link protocols added to Org-mode using `org-add-link-type'.")
7657 (defvar org-store-link-functions nil
7658 "List of functions that are called to create and store a link.
7659 Each function will be called in turn until one returns a non-nil
7660 value. Each function should check if it is responsible for creating
7661 this link (for example by looking at the major mode).
7662 If not, it must exit and return nil.
7663 If yes, it should return a non-nil value after a calling
7664 `org-store-link-props' with a list of properties and values.
7665 Special properties are:
7667 :type The link prefix. like \"http\". This must be given.
7668 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7669 This is obligatory as well.
7670 :description Optional default description for the second pair
7671 of brackets in an Org-mode link. The user can still change
7672 this when inserting this link into an Org-mode buffer.
7674 In addition to these, any additional properties can be specified
7675 and then used in remember templates.")
7677 (defun org-add-link-type (type &optional follow export)
7678 "Add TYPE to the list of `org-link-types'.
7679 Re-compute all regular expressions depending on `org-link-types'
7681 FOLLOW and EXPORT are two functions.
7683 FOLLOW should take the link path as the single argument and do whatever
7684 is necessary to follow the link, for example find a file or display
7685 a mail message.
7687 EXPORT should format the link path for export to one of the export formats.
7688 It should be a function accepting three arguments:
7690 path the path of the link, the text after the prefix (like \"http:\")
7691 desc the description of the link, if any, nil if there was no description
7692 format the export format, a symbol like `html' or `latex'.
7694 The function may use the FORMAT information to return different values
7695 depending on the format. The return value will be put literally into
7696 the exported file.
7697 Org-mode has a built-in default for exporting links. If you are happy with
7698 this default, there is no need to define an export function for the link
7699 type. For a simple example of an export function, see `org-bbdb.el'."
7700 (add-to-list 'org-link-types type t)
7701 (org-make-link-regexps)
7702 (if (assoc type org-link-protocols)
7703 (setcdr (assoc type org-link-protocols) (list follow export))
7704 (push (list type follow export) org-link-protocols)))
7706 (defvar org-agenda-buffer-name)
7708 ;;;###autoload
7709 (defun org-store-link (arg)
7710 "\\<org-mode-map>Store an org-link to the current location.
7711 This link is added to `org-stored-links' and can later be inserted
7712 into an org-buffer with \\[org-insert-link].
7714 For some link types, a prefix arg is interpreted:
7715 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7716 For file links, arg negates `org-context-in-file-links'."
7717 (interactive "P")
7718 (org-load-modules-maybe)
7719 (setq org-store-link-plist nil) ; reset
7720 (let ((outline-regexp (org-get-limited-outline-regexp))
7721 link cpltxt desc description search txt custom-id)
7722 (cond
7724 ((run-hook-with-args-until-success 'org-store-link-functions)
7725 (setq link (plist-get org-store-link-plist :link)
7726 desc (or (plist-get org-store-link-plist :description) link)))
7728 ((equal (buffer-name) "*Org Edit Src Example*")
7729 (let (label gc)
7730 (while (or (not label)
7731 (save-excursion
7732 (save-restriction
7733 (widen)
7734 (goto-char (point-min))
7735 (re-search-forward
7736 (regexp-quote (format org-coderef-label-format label))
7737 nil t))))
7738 (when label (message "Label exists already") (sit-for 2))
7739 (setq label (read-string "Code line label: " label)))
7740 (end-of-line 1)
7741 (setq link (format org-coderef-label-format label))
7742 (setq gc (- 79 (length link)))
7743 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7744 (insert link)
7745 (setq link (concat "(" label ")") desc nil)))
7747 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7748 ;; We are in the agenda, link to referenced location
7749 (let ((m (or (get-text-property (point) 'org-hd-marker)
7750 (get-text-property (point) 'org-marker))))
7751 (when m
7752 (org-with-point-at m
7753 (call-interactively 'org-store-link)))))
7755 ((eq major-mode 'calendar-mode)
7756 (let ((cd (calendar-cursor-to-date)))
7757 (setq link
7758 (format-time-string
7759 (car org-time-stamp-formats)
7760 (apply 'encode-time
7761 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7762 nil nil nil))))
7763 (org-store-link-props :type "calendar" :date cd)))
7765 ((eq major-mode 'w3-mode)
7766 (setq cpltxt (if (and (buffer-name)
7767 (not (string-match "Untitled" (buffer-name))))
7768 (buffer-name)
7769 (url-view-url t))
7770 link (org-make-link (url-view-url t)))
7771 (org-store-link-props :type "w3" :url (url-view-url t)))
7773 ((eq major-mode 'w3m-mode)
7774 (setq cpltxt (or w3m-current-title w3m-current-url)
7775 link (org-make-link w3m-current-url))
7776 (org-store-link-props :type "w3m" :url (url-view-url t)))
7778 ((setq search (run-hook-with-args-until-success
7779 'org-create-file-search-functions))
7780 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7781 "::" search))
7782 (setq cpltxt (or description link)))
7784 ((eq major-mode 'image-mode)
7785 (setq cpltxt (concat "file:"
7786 (abbreviate-file-name buffer-file-name))
7787 link (org-make-link cpltxt))
7788 (org-store-link-props :type "image" :file buffer-file-name))
7790 ((eq major-mode 'dired-mode)
7791 ;; link to the file in the current line
7792 (let ((file (dired-get-filename nil t)))
7793 (setq file (if file
7794 (abbreviate-file-name
7795 (expand-file-name (dired-get-filename nil t)))
7796 ;; otherwise, no file so use current directory.
7797 default-directory))
7798 (setq cpltxt (concat "file:" file)
7799 link (org-make-link cpltxt))))
7801 ((and buffer-file-name (org-mode-p))
7802 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7803 (cond
7804 ((org-in-regexp "<<\\(.*?\\)>>")
7805 (setq cpltxt
7806 (concat "file:"
7807 (abbreviate-file-name buffer-file-name)
7808 "::" (match-string 1))
7809 link (org-make-link cpltxt)))
7810 ((and (featurep 'org-id)
7811 (or (eq org-link-to-org-use-id t)
7812 (and (eq org-link-to-org-use-id 'create-if-interactive)
7813 (interactive-p))
7814 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7815 (interactive-p)
7816 (not custom-id))
7817 (and org-link-to-org-use-id
7818 (condition-case nil
7819 (org-entry-get nil "ID")
7820 (error nil)))))
7821 ;; We can make a link using the ID.
7822 (setq link (condition-case nil
7823 (prog1 (org-id-store-link)
7824 (setq desc (plist-get org-store-link-plist
7825 :description)))
7826 (error
7827 ;; probably before first headline, link to file only
7828 (concat "file:"
7829 (abbreviate-file-name buffer-file-name))))))
7831 ;; Just link to current headline
7832 (setq cpltxt (concat "file:"
7833 (abbreviate-file-name buffer-file-name)))
7834 ;; Add a context search string
7835 (when (org-xor org-context-in-file-links arg)
7836 (setq txt (cond
7837 ((org-on-heading-p) nil)
7838 ((org-region-active-p)
7839 (buffer-substring (region-beginning) (region-end)))
7840 (t nil)))
7841 (when (or (null txt) (string-match "\\S-" txt))
7842 (setq cpltxt
7843 (concat cpltxt "::"
7844 (condition-case nil
7845 (org-make-org-heading-search-string txt)
7846 (error "")))
7847 desc (or (nth 4 (ignore-errors
7848 (org-heading-components))) "NONE"))))
7849 (if (string-match "::\\'" cpltxt)
7850 (setq cpltxt (substring cpltxt 0 -2)))
7851 (setq link (org-make-link cpltxt)))))
7853 ((buffer-file-name (buffer-base-buffer))
7854 ;; Just link to this file here.
7855 (setq cpltxt (concat "file:"
7856 (abbreviate-file-name
7857 (buffer-file-name (buffer-base-buffer)))))
7858 ;; Add a context string
7859 (when (org-xor org-context-in-file-links arg)
7860 (setq txt (if (org-region-active-p)
7861 (buffer-substring (region-beginning) (region-end))
7862 (buffer-substring (point-at-bol) (point-at-eol))))
7863 ;; Only use search option if there is some text.
7864 (when (string-match "\\S-" txt)
7865 (setq cpltxt
7866 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7867 desc "NONE")))
7868 (setq link (org-make-link cpltxt)))
7870 ((interactive-p)
7871 (error "Cannot link to a buffer which is not visiting a file"))
7873 (t (setq link nil)))
7875 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7876 (setq link (or link cpltxt)
7877 desc (or desc cpltxt))
7878 (if (equal desc "NONE") (setq desc nil))
7880 (if (and (or (interactive-p) executing-kbd-macro) link)
7881 (progn
7882 (setq org-stored-links
7883 (cons (list link desc) org-stored-links))
7884 (message "Stored: %s" (or desc link))
7885 (when custom-id
7886 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7887 "::#" custom-id))
7888 (setq org-stored-links
7889 (cons (list link desc) org-stored-links))))
7890 (and link (org-make-link-string link desc)))))
7892 (defun org-store-link-props (&rest plist)
7893 "Store link properties, extract names and addresses."
7894 (let (x adr)
7895 (when (setq x (plist-get plist :from))
7896 (setq adr (mail-extract-address-components x))
7897 (setq plist (plist-put plist :fromname (car adr)))
7898 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7899 (when (setq x (plist-get plist :to))
7900 (setq adr (mail-extract-address-components x))
7901 (setq plist (plist-put plist :toname (car adr)))
7902 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7903 (let ((from (plist-get plist :from))
7904 (to (plist-get plist :to)))
7905 (when (and from to org-from-is-user-regexp)
7906 (setq plist
7907 (plist-put plist :fromto
7908 (if (string-match org-from-is-user-regexp from)
7909 (concat "to %t")
7910 (concat "from %f"))))))
7911 (setq org-store-link-plist plist))
7913 (defun org-add-link-props (&rest plist)
7914 "Add these properties to the link property list."
7915 (let (key value)
7916 (while plist
7917 (setq key (pop plist) value (pop plist))
7918 (setq org-store-link-plist
7919 (plist-put org-store-link-plist key value)))))
7921 (defun org-email-link-description (&optional fmt)
7922 "Return the description part of an email link.
7923 This takes information from `org-store-link-plist' and formats it
7924 according to FMT (default from `org-email-link-description-format')."
7925 (setq fmt (or fmt org-email-link-description-format))
7926 (let* ((p org-store-link-plist)
7927 (to (plist-get p :toaddress))
7928 (from (plist-get p :fromaddress))
7929 (table
7930 (list
7931 (cons "%c" (plist-get p :fromto))
7932 (cons "%F" (plist-get p :from))
7933 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7934 (cons "%T" (plist-get p :to))
7935 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7936 (cons "%s" (plist-get p :subject))
7937 (cons "%m" (plist-get p :message-id)))))
7938 (when (string-match "%c" fmt)
7939 ;; Check if the user wrote this message
7940 (if (and org-from-is-user-regexp from to
7941 (save-match-data (string-match org-from-is-user-regexp from)))
7942 (setq fmt (replace-match "to %t" t t fmt))
7943 (setq fmt (replace-match "from %f" t t fmt))))
7944 (org-replace-escapes fmt table)))
7946 (defun org-make-org-heading-search-string (&optional string heading)
7947 "Make search string for STRING or current headline."
7948 (interactive)
7949 (let ((s (or string (org-get-heading))))
7950 (unless (and string (not heading))
7951 ;; We are using a headline, clean up garbage in there.
7952 (if (string-match org-todo-regexp s)
7953 (setq s (replace-match "" t t s)))
7954 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7955 (setq s (replace-match "" t t s)))
7956 (setq s (org-trim s))
7957 (if (string-match (concat "^\\(" org-quote-string "\\|"
7958 org-comment-string "\\)") s)
7959 (setq s (replace-match "" t t s)))
7960 (while (string-match org-ts-regexp s)
7961 (setq s (replace-match "" t t s))))
7962 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7963 (setq s (replace-match " " t t s)))
7964 (or string (setq s (concat "*" s))) ; Add * for headlines
7965 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7967 (defun org-make-link (&rest strings)
7968 "Concatenate STRINGS."
7969 (apply 'concat strings))
7971 (defun org-make-link-string (link &optional description)
7972 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7973 (unless (string-match "\\S-" link)
7974 (error "Empty link"))
7975 (when (and description
7976 (stringp description)
7977 (not (string-match "\\S-" description)))
7978 (setq description nil))
7979 (when (stringp description)
7980 ;; Remove brackets from the description, they are fatal.
7981 (while (string-match "\\[" description)
7982 (setq description (replace-match "{" t t description)))
7983 (while (string-match "\\]" description)
7984 (setq description (replace-match "}" t t description))))
7985 (when (equal (org-link-escape link) description)
7986 ;; No description needed, it is identical
7987 (setq description nil))
7988 (when (and (not description)
7989 (not (equal link (org-link-escape link))))
7990 (setq description (org-extract-attributes link)))
7991 (concat "[[" (org-link-escape link) "]"
7992 (if description (concat "[" description "]") "")
7993 "]"))
7995 (defconst org-link-escape-chars
7996 '((?\ . "%20")
7997 (?\[ . "%5B")
7998 (?\] . "%5D")
7999 (?\340 . "%E0") ; `a
8000 (?\342 . "%E2") ; ^a
8001 (?\347 . "%E7") ; ,c
8002 (?\350 . "%E8") ; `e
8003 (?\351 . "%E9") ; 'e
8004 (?\352 . "%EA") ; ^e
8005 (?\356 . "%EE") ; ^i
8006 (?\364 . "%F4") ; ^o
8007 (?\371 . "%F9") ; `u
8008 (?\373 . "%FB") ; ^u
8009 (?\; . "%3B")
8010 ;; (?? . "%3F")
8011 (?= . "%3D")
8012 (?+ . "%2B")
8014 "Association list of escapes for some characters problematic in links.
8015 This is the list that is used for internal purposes.")
8017 (defvar org-url-encoding-use-url-hexify nil)
8019 (defconst org-link-escape-chars-browser
8020 '((?\ . "%20")) ; 32 for the SPC char
8021 "Association list of escapes for some characters problematic in links.
8022 This is the list that is used before handing over to the browser.")
8024 (defun org-link-escape (text &optional table)
8025 "Escape characters in TEXT that are problematic for links."
8026 (if (and org-url-encoding-use-url-hexify (not table))
8027 (url-hexify-string text)
8028 (setq table (or table org-link-escape-chars))
8029 (when text
8030 (let ((re (mapconcat (lambda (x) (regexp-quote
8031 (char-to-string (car x))))
8032 table "\\|")))
8033 (while (string-match re text)
8034 (setq text
8035 (replace-match
8036 (cdr (assoc (string-to-char (match-string 0 text))
8037 table))
8038 t t text)))
8039 text))))
8041 (defun org-link-unescape (text &optional table)
8042 "Reverse the action of `org-link-escape'."
8043 (if (and org-url-encoding-use-url-hexify (not table))
8044 (url-unhex-string text)
8045 (setq table (or table org-link-escape-chars))
8046 (when text
8047 (let ((case-fold-search t)
8048 (re (mapconcat (lambda (x) (regexp-quote (downcase (cdr x))))
8049 table "\\|")))
8050 (while (string-match re text)
8051 (setq text
8052 (replace-match
8053 (char-to-string (car (rassoc (upcase (match-string 0 text))
8054 table)))
8055 t t text)))
8056 text))))
8058 (defun org-xor (a b)
8059 "Exclusive or."
8060 (if a (not b) b))
8062 (defun org-fixup-message-id-for-http (s)
8063 "Replace special characters in a message id, so it can be used in an http query."
8064 (while (string-match "<" s)
8065 (setq s (replace-match "%3C" t t s)))
8066 (while (string-match ">" s)
8067 (setq s (replace-match "%3E" t t s)))
8068 (while (string-match "@" s)
8069 (setq s (replace-match "%40" t t s)))
8072 ;;;###autoload
8073 (defun org-insert-link-global ()
8074 "Insert a link like Org-mode does.
8075 This command can be called in any mode to insert a link in Org-mode syntax."
8076 (interactive)
8077 (org-load-modules-maybe)
8078 (org-run-like-in-org-mode 'org-insert-link))
8080 (defun org-insert-link (&optional complete-file link-location)
8081 "Insert a link. At the prompt, enter the link.
8083 Completion can be used to insert any of the link protocol prefixes like
8084 http or ftp in use.
8086 The history can be used to select a link previously stored with
8087 `org-store-link'. When the empty string is entered (i.e. if you just
8088 press RET at the prompt), the link defaults to the most recently
8089 stored link. As SPC triggers completion in the minibuffer, you need to
8090 use M-SPC or C-q SPC to force the insertion of a space character.
8092 You will also be prompted for a description, and if one is given, it will
8093 be displayed in the buffer instead of the link.
8095 If there is already a link at point, this command will allow you to edit link
8096 and description parts.
8098 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8099 be selected using completion. The path to the file will be relative to the
8100 current directory if the file is in the current directory or a subdirectory.
8101 Otherwise, the link will be the absolute path as completed in the minibuffer
8102 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8103 option `org-link-file-path-type'.
8105 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8106 the current directory or below.
8108 With three \\[universal-argument] prefixes, negate the meaning of
8109 `org-keep-stored-link-after-insertion'.
8111 If `org-make-link-description-function' is non-nil, this function will be
8112 called with the link target, and the result will be the default
8113 link description.
8115 If the LINK-LOCATION parameter is non-nil, this value will be
8116 used as the link location instead of reading one interactively."
8117 (interactive "P")
8118 (let* ((wcf (current-window-configuration))
8119 (region (if (org-region-active-p)
8120 (buffer-substring (region-beginning) (region-end))))
8121 (remove (and region (list (region-beginning) (region-end))))
8122 (desc region)
8123 tmphist ; byte-compile incorrectly complains about this
8124 (link link-location)
8125 entry file all-prefixes)
8126 (cond
8127 (link-location) ; specified by arg, just use it.
8128 ((org-in-regexp org-bracket-link-regexp 1)
8129 ;; We do have a link at point, and we are going to edit it.
8130 (setq remove (list (match-beginning 0) (match-end 0)))
8131 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8132 (setq link (read-string "Link: "
8133 (org-link-unescape
8134 (org-match-string-no-properties 1)))))
8135 ((or (org-in-regexp org-angle-link-re)
8136 (org-in-regexp org-plain-link-re))
8137 ;; Convert to bracket link
8138 (setq remove (list (match-beginning 0) (match-end 0))
8139 link (read-string "Link: "
8140 (org-remove-angle-brackets (match-string 0)))))
8141 ((member complete-file '((4) (16)))
8142 ;; Completing read for file names.
8143 (setq link (org-file-complete-link complete-file)))
8145 ;; Read link, with completion for stored links.
8146 (with-output-to-temp-buffer "*Org Links*"
8147 (princ "Insert a link.
8148 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8149 (when org-stored-links
8150 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8151 (princ (mapconcat
8152 (lambda (x)
8153 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8154 (reverse org-stored-links) "\n"))))
8155 (let ((cw (selected-window)))
8156 (select-window (get-buffer-window "*Org Links*"))
8157 (setq truncate-lines t)
8158 (unless (pos-visible-in-window-p (point-max))
8159 (org-fit-window-to-buffer))
8160 (and (window-live-p cw) (select-window cw)))
8161 ;; Fake a link history, containing the stored links.
8162 (setq tmphist (append (mapcar 'car org-stored-links)
8163 org-insert-link-history))
8164 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8165 (mapcar 'car org-link-abbrev-alist)
8166 org-link-types))
8167 (unwind-protect
8168 (progn
8169 (setq link
8170 (let ((org-completion-use-ido nil)
8171 (org-completion-use-iswitchb nil))
8172 (org-completing-read
8173 "Link: "
8174 (append
8175 (mapcar (lambda (x) (list (concat x ":")))
8176 all-prefixes)
8177 (mapcar 'car org-stored-links))
8178 nil nil nil
8179 'tmphist
8180 (car (car org-stored-links)))))
8181 (if (not (string-match "\\S-" link))
8182 (error "No link selected"))
8183 (if (or (member link all-prefixes)
8184 (and (equal ":" (substring link -1))
8185 (member (substring link 0 -1) all-prefixes)
8186 (setq link (substring link 0 -1))))
8187 (setq link (org-link-try-special-completion link))))
8188 (set-window-configuration wcf)
8189 (kill-buffer "*Org Links*"))
8190 (setq entry (assoc link org-stored-links))
8191 (or entry (push link org-insert-link-history))
8192 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8193 (not org-keep-stored-link-after-insertion))
8194 (setq org-stored-links (delq (assoc link org-stored-links)
8195 org-stored-links)))
8196 (setq desc (or desc (nth 1 entry)))))
8198 (if (string-match org-plain-link-re link)
8199 ;; URL-like link, normalize the use of angular brackets.
8200 (setq link (org-make-link (org-remove-angle-brackets link))))
8202 ;; Check if we are linking to the current file with a search option
8203 ;; If yes, simplify the link by using only the search option.
8204 (when (and buffer-file-name
8205 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8206 (let* ((path (match-string 1 link))
8207 (case-fold-search nil)
8208 (search (match-string 2 link)))
8209 (save-match-data
8210 (if (equal (file-truename buffer-file-name) (file-truename path))
8211 ;; We are linking to this same file, with a search option
8212 (setq link search)))))
8214 ;; Check if we can/should use a relative path. If yes, simplify the link
8215 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8216 (let* ((type (match-string 1 link))
8217 (path (match-string 2 link))
8218 (origpath path)
8219 (case-fold-search nil))
8220 (cond
8221 ((or (eq org-link-file-path-type 'absolute)
8222 (equal complete-file '(16)))
8223 (setq path (abbreviate-file-name (expand-file-name path))))
8224 ((eq org-link-file-path-type 'noabbrev)
8225 (setq path (expand-file-name path)))
8226 ((eq org-link-file-path-type 'relative)
8227 (setq path (file-relative-name path)))
8229 (save-match-data
8230 (if (string-match (concat "^" (regexp-quote
8231 (file-name-as-directory
8232 (expand-file-name "."))))
8233 (expand-file-name path))
8234 ;; We are linking a file with relative path name.
8235 (setq path (substring (expand-file-name path)
8236 (match-end 0)))
8237 (setq path (abbreviate-file-name (expand-file-name path)))))))
8238 (setq link (concat type path))
8239 (if (equal desc origpath)
8240 (setq desc path))))
8242 (if org-make-link-description-function
8243 (setq desc (funcall org-make-link-description-function link desc)))
8245 (setq desc (read-string "Description: " desc))
8246 (unless (string-match "\\S-" desc) (setq desc nil))
8247 (if remove (apply 'delete-region remove))
8248 (insert (org-make-link-string link desc))))
8250 (defun org-link-try-special-completion (type)
8251 "If there is completion support for link type TYPE, offer it."
8252 (let ((fun (intern (concat "org-" type "-complete-link"))))
8253 (if (functionp fun)
8254 (funcall fun)
8255 (read-string "Link (no completion support): " (concat type ":")))))
8257 (defun org-file-complete-link (&optional arg)
8258 "Create a file link using completion."
8259 (let (file link)
8260 (setq file (read-file-name "File: "))
8261 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8262 (pwd1 (file-name-as-directory (abbreviate-file-name
8263 (expand-file-name ".")))))
8264 (cond
8265 ((equal arg '(16))
8266 (setq link (org-make-link
8267 "file:"
8268 (abbreviate-file-name (expand-file-name file)))))
8269 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8270 (setq link (org-make-link "file:" (match-string 1 file))))
8271 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8272 (expand-file-name file))
8273 (setq link (org-make-link
8274 "file:" (match-string 1 (expand-file-name file)))))
8275 (t (setq link (org-make-link "file:" file)))))
8276 link))
8278 (defun org-completing-read (&rest args)
8279 "Completing-read with SPACE being a normal character."
8280 (let ((minibuffer-local-completion-map
8281 (copy-keymap minibuffer-local-completion-map)))
8282 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8283 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8284 (apply 'org-icompleting-read args)))
8286 (defun org-completing-read-no-i (&rest args)
8287 (let (org-completion-use-ido org-completion-use-iswitchb)
8288 (apply 'org-completing-read args)))
8290 (defun org-iswitchb-completing-read (prompt choices &rest args)
8291 "Use iswitch as a completing-read replacement to choose from choices.
8292 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8293 from."
8294 (let* ((iswitchb-use-virtual-buffers nil)
8295 (iswitchb-make-buflist-hook
8296 (lambda ()
8297 (setq iswitchb-temp-buflist choices))))
8298 (iswitchb-read-buffer prompt)))
8300 (defun org-icompleting-read (&rest args)
8301 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8302 (org-without-partial-completion
8303 (if (and org-completion-use-ido
8304 (fboundp 'ido-completing-read)
8305 (boundp 'ido-mode) ido-mode
8306 (listp (second args)))
8307 (let ((ido-enter-matching-directory nil))
8308 (apply 'ido-completing-read (concat (car args))
8309 (if (consp (car (nth 1 args)))
8310 (mapcar (lambda (x) (car x)) (nth 1 args))
8311 (nth 1 args))
8312 (cddr args)))
8313 (if (and org-completion-use-iswitchb
8314 (boundp 'iswitchb-mode) iswitchb-mode
8315 (listp (second args)))
8316 (apply 'org-iswitchb-completing-read (concat (car args))
8317 (if (consp (car (nth 1 args)))
8318 (mapcar (lambda (x) (car x)) (nth 1 args))
8319 (nth 1 args))
8320 (cddr args))
8321 (apply 'completing-read args)))))
8323 (defun org-extract-attributes (s)
8324 "Extract the attributes cookie from a string and set as text property."
8325 (let (a attr (start 0) key value)
8326 (save-match-data
8327 (when (string-match "{{\\([^}]+\\)}}$" s)
8328 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8329 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8330 (setq key (match-string 1 a) value (match-string 2 a)
8331 start (match-end 0)
8332 attr (plist-put attr (intern key) value))))
8333 (org-add-props s nil 'org-attr attr))
8336 (defun org-extract-attributes-from-string (tag)
8337 (let (key value attr)
8338 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8339 (setq key (match-string 1 tag) value (match-string 2 tag)
8340 tag (replace-match "" t t tag)
8341 attr (plist-put attr (intern key) value)))
8342 (cons tag attr)))
8344 (defun org-attributes-to-string (plist)
8345 "Format a property list into an HTML attribute list."
8346 (let ((s "") key value)
8347 (while plist
8348 (setq key (pop plist) value (pop plist))
8349 (and value
8350 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8353 ;;; Opening/following a link
8355 (defvar org-link-search-failed nil)
8357 (defvar org-open-link-functions nil
8358 "Hook for functions finding a plain text link.
8359 These functions must take a single argument, the link content.
8360 They will be called for links that look like [[link text][description]]
8361 when LINK TEXT does not have a protocol like \"http:\" and does not look
8362 like a filename (e.g. \"./blue.png\").
8364 These functions will be called *before* Org attempts to resolve the
8365 link by doing text searches in the current buffer - so if you want a
8366 link \"[[target]]\" to still find \"<<target>>\", your function should
8367 handle this as a special case.
8369 When the function does handle the link, it must return a non-nil value.
8370 If it decides that it is not responsible for this link, it must return
8371 nil to indicate that that Org-mode can continue with other options
8372 like exact and fuzzy text search.")
8374 (defun org-next-link ()
8375 "Move forward to the next link.
8376 If the link is in hidden text, expose it."
8377 (interactive)
8378 (when (and org-link-search-failed (eq this-command last-command))
8379 (goto-char (point-min))
8380 (message "Link search wrapped back to beginning of buffer"))
8381 (setq org-link-search-failed nil)
8382 (let* ((pos (point))
8383 (ct (org-context))
8384 (a (assoc :link ct)))
8385 (if a (goto-char (nth 2 a)))
8386 (if (re-search-forward org-any-link-re nil t)
8387 (progn
8388 (goto-char (match-beginning 0))
8389 (if (org-invisible-p) (org-show-context)))
8390 (goto-char pos)
8391 (setq org-link-search-failed t)
8392 (error "No further link found"))))
8394 (defun org-previous-link ()
8395 "Move backward to the previous link.
8396 If the link is in hidden text, expose it."
8397 (interactive)
8398 (when (and org-link-search-failed (eq this-command last-command))
8399 (goto-char (point-max))
8400 (message "Link search wrapped back to end of buffer"))
8401 (setq org-link-search-failed nil)
8402 (let* ((pos (point))
8403 (ct (org-context))
8404 (a (assoc :link ct)))
8405 (if a (goto-char (nth 1 a)))
8406 (if (re-search-backward org-any-link-re nil t)
8407 (progn
8408 (goto-char (match-beginning 0))
8409 (if (org-invisible-p) (org-show-context)))
8410 (goto-char pos)
8411 (setq org-link-search-failed t)
8412 (error "No further link found"))))
8414 (defun org-translate-link (s)
8415 "Translate a link string if a translation function has been defined."
8416 (if (and org-link-translation-function
8417 (fboundp org-link-translation-function)
8418 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8419 (progn
8420 (setq s (funcall org-link-translation-function
8421 (match-string 1) (match-string 2)))
8422 (concat (car s) ":" (cdr s)))
8425 (defun org-translate-link-from-planner (type path)
8426 "Translate a link from Emacs Planner syntax so that Org can follow it.
8427 This is still an experimental function, your mileage may vary."
8428 (cond
8429 ((member type '("http" "https" "news" "ftp"))
8430 ;; standard Internet links are the same.
8431 nil)
8432 ((and (equal type "irc") (string-match "^//" path))
8433 ;; Planner has two / at the beginning of an irc link, we have 1.
8434 ;; We should have zero, actually....
8435 (setq path (substring path 1)))
8436 ((and (equal type "lisp") (string-match "^/" path))
8437 ;; Planner has a slash, we do not.
8438 (setq type "elisp" path (substring path 1)))
8439 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8440 ;; A typical message link. Planner has the id after the final slash,
8441 ;; we separate it with a hash mark
8442 (setq path (concat (match-string 1 path) "#"
8443 (org-remove-angle-brackets (match-string 2 path)))))
8445 (cons type path))
8447 (defun org-find-file-at-mouse (ev)
8448 "Open file link or URL at mouse."
8449 (interactive "e")
8450 (mouse-set-point ev)
8451 (org-open-at-point 'in-emacs))
8453 (defun org-open-at-mouse (ev)
8454 "Open file link or URL at mouse."
8455 (interactive "e")
8456 (mouse-set-point ev)
8457 (if (eq major-mode 'org-agenda-mode)
8458 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8459 (org-open-at-point))
8461 (defvar org-window-config-before-follow-link nil
8462 "The window configuration before following a link.
8463 This is saved in case the need arises to restore it.")
8465 (defvar org-open-link-marker (make-marker)
8466 "Marker pointing to the location where `org-open-at-point; was called.")
8468 ;;;###autoload
8469 (defun org-open-at-point-global ()
8470 "Follow a link like Org-mode does.
8471 This command can be called in any mode to follow a link that has
8472 Org-mode syntax."
8473 (interactive)
8474 (org-run-like-in-org-mode 'org-open-at-point))
8476 ;;;###autoload
8477 (defun org-open-link-from-string (s &optional arg reference-buffer)
8478 "Open a link in the string S, as if it was in Org-mode."
8479 (interactive "sLink: \nP")
8480 (let ((reference-buffer (or reference-buffer (current-buffer))))
8481 (with-temp-buffer
8482 (let ((org-inhibit-startup t))
8483 (org-mode)
8484 (insert s)
8485 (goto-char (point-min))
8486 (when reference-buffer
8487 (setq org-link-abbrev-alist-local
8488 (with-current-buffer reference-buffer
8489 org-link-abbrev-alist-local)))
8490 (org-open-at-point arg reference-buffer)))))
8492 (defun org-open-at-point (&optional in-emacs reference-buffer)
8493 "Open link at or after point.
8494 If there is no link at point, this function will search forward up to
8495 the end of the current line.
8496 Normally, files will be opened by an appropriate application. If the
8497 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8498 With a double prefix argument, try to open outside of Emacs, in the
8499 application the system uses for this file type."
8500 (interactive "P")
8501 (org-load-modules-maybe)
8502 (move-marker org-open-link-marker (point))
8503 (setq org-window-config-before-follow-link (current-window-configuration))
8504 (org-remove-occur-highlights nil nil t)
8505 (cond
8506 ((and (org-on-heading-p)
8507 (not (org-in-regexp
8508 (concat org-plain-link-re "\\|"
8509 org-bracket-link-regexp "\\|"
8510 org-angle-link-re "\\|"
8511 "[ \t]:[^ \t\n]+:[ \t]*$")))
8512 (not (get-text-property (point) 'org-linked-text)))
8513 (or (org-offer-links-in-entry in-emacs)
8514 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8515 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8516 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8517 (org-footnote-action))
8519 (let (type path link line search (pos (point)))
8520 (catch 'match
8521 (save-excursion
8522 (skip-chars-forward "^]\n\r")
8523 (when (org-in-regexp org-bracket-link-regexp 1)
8524 (setq link (org-extract-attributes
8525 (org-link-unescape (org-match-string-no-properties 1))))
8526 (while (string-match " *\n *" link)
8527 (setq link (replace-match " " t t link)))
8528 (setq link (org-link-expand-abbrev link))
8529 (cond
8530 ((or (file-name-absolute-p link)
8531 (string-match "^\\.\\.?/" link))
8532 (setq type "file" path link))
8533 ((string-match org-link-re-with-space3 link)
8534 (setq type (match-string 1 link) path (match-string 2 link)))
8535 (t (setq type "thisfile" path link)))
8536 (throw 'match t)))
8538 (when (get-text-property (point) 'org-linked-text)
8539 (setq type "thisfile"
8540 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8541 (1+ (point)) (point))
8542 path (buffer-substring
8543 (previous-single-property-change pos 'org-linked-text)
8544 (next-single-property-change pos 'org-linked-text)))
8545 (throw 'match t))
8547 (save-excursion
8548 (when (or (org-in-regexp org-angle-link-re)
8549 (org-in-regexp org-plain-link-re))
8550 (setq type (match-string 1) path (match-string 2))
8551 (throw 'match t)))
8552 (save-excursion
8553 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8554 (setq type "tags"
8555 path (match-string 1))
8556 (while (string-match ":" path)
8557 (setq path (replace-match "+" t t path)))
8558 (throw 'match t)))
8559 (when (org-in-regexp "<\\([^><\n]+\\)>")
8560 (setq type "tree-match"
8561 path (match-string 1))
8562 (throw 'match t)))
8563 (unless path
8564 (error "No link found"))
8566 ;; switch back to reference buffer
8567 ;; needed when if called in a temporary buffer through
8568 ;; org-open-link-from-string
8569 (with-current-buffer (or reference-buffer (current-buffer))
8571 ;; Remove any trailing spaces in path
8572 (if (string-match " +\\'" path)
8573 (setq path (replace-match "" t t path)))
8574 (if (and org-link-translation-function
8575 (fboundp org-link-translation-function))
8576 ;; Check if we need to translate the link
8577 (let ((tmp (funcall org-link-translation-function type path)))
8578 (setq type (car tmp) path (cdr tmp))))
8580 (cond
8582 ((assoc type org-link-protocols)
8583 (funcall (nth 1 (assoc type org-link-protocols)) path))
8585 ((equal type "mailto")
8586 (let ((cmd (car org-link-mailto-program))
8587 (args (cdr org-link-mailto-program)) args1
8588 (address path) (subject "") a)
8589 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8590 (setq address (match-string 1 path)
8591 subject (org-link-escape (match-string 2 path))))
8592 (while args
8593 (cond
8594 ((not (stringp (car args))) (push (pop args) args1))
8595 (t (setq a (pop args))
8596 (if (string-match "%a" a)
8597 (setq a (replace-match address t t a)))
8598 (if (string-match "%s" a)
8599 (setq a (replace-match subject t t a)))
8600 (push a args1))))
8601 (apply cmd (nreverse args1))))
8603 ((member type '("http" "https" "ftp" "news"))
8604 (browse-url (concat type ":" (org-link-escape
8605 path org-link-escape-chars-browser))))
8607 ((member type '("message"))
8608 (browse-url (concat type ":" path)))
8610 ((string= type "tags")
8611 (org-tags-view in-emacs path))
8613 ((string= type "tree-match")
8614 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8616 ((string= type "file")
8617 (if (string-match "::\\([0-9]+\\)\\'" path)
8618 (setq line (string-to-number (match-string 1 path))
8619 path (substring path 0 (match-beginning 0)))
8620 (if (string-match "::\\(.+\\)\\'" path)
8621 (setq search (match-string 1 path)
8622 path (substring path 0 (match-beginning 0)))))
8623 (if (string-match "[*?{]" (file-name-nondirectory path))
8624 (dired path)
8625 (org-open-file path in-emacs line search)))
8627 ((string= type "news")
8628 (require 'org-gnus)
8629 (org-gnus-follow-link path))
8631 ((string= type "shell")
8632 (let ((cmd path))
8633 (if (or (not org-confirm-shell-link-function)
8634 (funcall org-confirm-shell-link-function
8635 (format "Execute \"%s\" in shell? "
8636 (org-add-props cmd nil
8637 'face 'org-warning))))
8638 (progn
8639 (message "Executing %s" cmd)
8640 (shell-command cmd))
8641 (error "Abort"))))
8643 ((string= type "elisp")
8644 (let ((cmd path))
8645 (if (or (not org-confirm-elisp-link-function)
8646 (funcall org-confirm-elisp-link-function
8647 (format "Execute \"%s\" as elisp? "
8648 (org-add-props cmd nil
8649 'face 'org-warning))))
8650 (message "%s => %s" cmd
8651 (if (equal (string-to-char cmd) ?\()
8652 (eval (read cmd))
8653 (call-interactively (read cmd))))
8654 (error "Abort"))))
8656 ((and (string= type "thisfile")
8657 (run-hook-with-args-until-success
8658 'org-open-link-functions path)))
8660 ((string= type "thisfile")
8661 (if in-emacs
8662 (switch-to-buffer-other-window
8663 (org-get-buffer-for-internal-link (current-buffer)))
8664 (org-mark-ring-push))
8665 (let ((cmd `(org-link-search
8666 ,path
8667 ,(cond ((equal in-emacs '(4)) 'occur)
8668 ((equal in-emacs '(16)) 'org-occur)
8669 (t nil))
8670 ,pos)))
8671 (condition-case nil (eval cmd)
8672 (error (progn (widen) (eval cmd))))))
8675 (browse-url-at-point)))))))
8676 (move-marker org-open-link-marker nil)
8677 (run-hook-with-args 'org-follow-link-hook))
8679 (defun org-offer-links-in-entry (&optional nth zero)
8680 "Offer links in the current entry and follow the selected link.
8681 If there is only one link, follow it immediately as well.
8682 If NTH is an integer, immediately pick the NTH link found.
8683 If ZERO is a string, check also this string for a link, and if
8684 there is one, offer it as link number zero."
8685 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8686 "\\(" org-angle-link-re "\\)\\|"
8687 "\\(" org-plain-link-re "\\)"))
8688 (cnt ?0)
8689 (in-emacs (if (integerp nth) nil nth))
8690 have-zero end links link c)
8691 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8692 (push (match-string 0 zero) links)
8693 (setq cnt (1- cnt) have-zero t))
8694 (save-excursion
8695 (org-back-to-heading t)
8696 (setq end (save-excursion (outline-next-heading) (point)))
8697 (while (re-search-forward re end t)
8698 (push (match-string 0) links))
8699 (setq links (org-uniquify (reverse links))))
8701 (cond
8702 ((null links)
8703 (message "No links"))
8704 ((equal (length links) 1)
8705 (setq link (list (car links))))
8706 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8707 (setq link (nth (if have-zero nth (1- nth)) links)))
8708 (t ; we have to select a link
8709 (save-excursion
8710 (save-window-excursion
8711 (delete-other-windows)
8712 (with-output-to-temp-buffer "*Select Link*"
8713 (mapc (lambda (l)
8714 (if (not (string-match org-bracket-link-regexp l))
8715 (princ (format "[%c] %s\n" (incf cnt)
8716 (org-remove-angle-brackets l)))
8717 (if (match-end 3)
8718 (princ (format "[%c] %s (%s)\n" (incf cnt)
8719 (match-string 3 l) (match-string 1 l)))
8720 (princ (format "[%c] %s\n" (incf cnt)
8721 (match-string 1 l))))))
8722 links))
8723 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8724 (message "Select link to open, RET to open all:")
8725 (setq c (read-char-exclusive))
8726 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8727 (when (equal c ?q) (error "Abort"))
8728 (if (equal c ?\C-m)
8729 (setq link links)
8730 (setq nth (- c ?0))
8731 (if have-zero (setq nth (1+ nth)))
8732 (unless (and (integerp nth) (>= (length links) nth))
8733 (error "Invalid link selection"))
8734 (setq link (list (nth (1- nth) links))))))
8735 (if link
8736 (let ((buf (current-buffer)))
8737 (dolist (l link)
8738 (org-open-link-from-string l in-emacs buf))
8740 nil)))
8742 ;; Add special file links that specify the way of opening
8744 (org-add-link-type "file+sys" 'org-open-file-with-system)
8745 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
8746 (defun org-open-file-with-system (path)
8747 "Open file at PATH using the system way of opeing it."
8748 (org-open-file path 'system))
8749 (defun org-open-file-with-emacs (path)
8750 "Open file at PATH in emacs."
8751 (org-open-file path 'emacs))
8752 (defun org-remove-file-link-modifiers ()
8753 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
8754 (goto-char (point-min))
8755 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
8756 (org-if-unprotected
8757 (replace-match "file:" t t))))
8758 (eval-after-load "org-exp"
8759 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
8760 'org-remove-file-link-modifiers))
8762 ;;;; Time estimates
8764 (defun org-get-effort (&optional pom)
8765 "Get the effort estimate for the current entry."
8766 (org-entry-get pom org-effort-property))
8768 ;;; File search
8770 (defvar org-create-file-search-functions nil
8771 "List of functions to construct the right search string for a file link.
8772 These functions are called in turn with point at the location to
8773 which the link should point.
8775 A function in the hook should first test if it would like to
8776 handle this file type, for example by checking the major-mode or
8777 the file extension. If it decides not to handle this file, it
8778 should just return nil to give other functions a chance. If it
8779 does handle the file, it must return the search string to be used
8780 when following the link. The search string will be part of the
8781 file link, given after a double colon, and `org-open-at-point'
8782 will automatically search for it. If special measures must be
8783 taken to make the search successful, another function should be
8784 added to the companion hook `org-execute-file-search-functions',
8785 which see.
8787 A function in this hook may also use `setq' to set the variable
8788 `description' to provide a suggestion for the descriptive text to
8789 be used for this link when it gets inserted into an Org-mode
8790 buffer with \\[org-insert-link].")
8792 (defvar org-execute-file-search-functions nil
8793 "List of functions to execute a file search triggered by a link.
8795 Functions added to this hook must accept a single argument, the
8796 search string that was part of the file link, the part after the
8797 double colon. The function must first check if it would like to
8798 handle this search, for example by checking the major-mode or the
8799 file extension. If it decides not to handle this search, it
8800 should just return nil to give other functions a chance. If it
8801 does handle the search, it must return a non-nil value to keep
8802 other functions from trying.
8804 Each function can access the current prefix argument through the
8805 variable `current-prefix-argument'. Note that a single prefix is
8806 used to force opening a link in Emacs, so it may be good to only
8807 use a numeric or double prefix to guide the search function.
8809 In case this is needed, a function in this hook can also restore
8810 the window configuration before `org-open-at-point' was called using:
8812 (set-window-configuration org-window-config-before-follow-link)")
8814 (defun org-link-search (s &optional type avoid-pos)
8815 "Search for a link search option.
8816 If S is surrounded by forward slashes, it is interpreted as a
8817 regular expression. In org-mode files, this will create an `org-occur'
8818 sparse tree. In ordinary files, `occur' will be used to list matches.
8819 If the current buffer is in `dired-mode', grep will be used to search
8820 in all files. If AVOID-POS is given, ignore matches near that position."
8821 (let ((case-fold-search t)
8822 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8823 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8824 (append '(("") (" ") ("\t") ("\n"))
8825 org-emphasis-alist)
8826 "\\|") "\\)"))
8827 (pos (point))
8828 (pre nil) (post nil)
8829 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8830 (cond
8831 ;; First check if there are any special
8832 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8833 ;; Now try the builtin stuff
8834 ((and (equal (string-to-char s0) ?#)
8835 (> (length s0) 1)
8836 (save-excursion
8837 (goto-char (point-min))
8838 (and
8839 (re-search-forward
8840 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8841 (setq type 'dedicated
8842 pos (match-beginning 0))))
8843 ;; There is an exact target for this
8844 (goto-char pos)
8845 (org-back-to-heading t)))
8846 ((save-excursion
8847 (goto-char (point-min))
8848 (and
8849 (re-search-forward
8850 (concat "<<" (regexp-quote s0) ">>") nil t)
8851 (setq type 'dedicated
8852 pos (match-beginning 0))))
8853 ;; There is an exact target for this
8854 (goto-char pos))
8855 ((and (string-match "^(\\(.*\\))$" s0)
8856 (save-excursion
8857 (goto-char (point-min))
8858 (and
8859 (re-search-forward
8860 (concat "[^[]" (regexp-quote
8861 (format org-coderef-label-format
8862 (match-string 1 s0))))
8863 nil t)
8864 (setq type 'dedicated
8865 pos (1+ (match-beginning 0))))))
8866 ;; There is a coderef target for this
8867 (goto-char pos))
8868 ((string-match "^/\\(.*\\)/$" s)
8869 ;; A regular expression
8870 (cond
8871 ((org-mode-p)
8872 (org-occur (match-string 1 s)))
8873 ;;((eq major-mode 'dired-mode)
8874 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8875 (t (org-do-occur (match-string 1 s)))))
8877 ;; A normal search strings
8878 (when (equal (string-to-char s) ?*)
8879 ;; Anchor on headlines, post may include tags.
8880 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8881 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8882 s (substring s 1)))
8883 (remove-text-properties
8884 0 (length s)
8885 '(face nil mouse-face nil keymap nil fontified nil) s)
8886 ;; Make a series of regular expressions to find a match
8887 (setq words (org-split-string s "[ \n\r\t]+")
8889 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8890 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8891 "\\)" markers)
8892 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8893 re2a (concat "[ \t\r\n]" re2a_)
8894 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8895 re4 (concat "[^a-zA-Z_]" re4_)
8897 re1 (concat pre re2 post)
8898 re3 (concat pre (if pre re4_ re4) post)
8899 re5 (concat pre ".*" re4)
8900 re2 (concat pre re2)
8901 re2a (concat pre (if pre re2a_ re2a))
8902 re4 (concat pre (if pre re4_ re4))
8903 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8904 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8905 re5 "\\)"
8907 (cond
8908 ((eq type 'org-occur) (org-occur reall))
8909 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8910 (t (goto-char (point-min))
8911 (setq type 'fuzzy)
8912 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8913 (org-search-not-self 1 re1 nil t)
8914 (org-search-not-self 1 re2 nil t)
8915 (org-search-not-self 1 re2a nil t)
8916 (org-search-not-self 1 re3 nil t)
8917 (org-search-not-self 1 re4 nil t)
8918 (org-search-not-self 1 re5 nil t)
8920 (goto-char (match-beginning 1))
8921 (goto-char pos)
8922 (error "No match")))))
8924 ;; Normal string-search
8925 (goto-char (point-min))
8926 (if (search-forward s nil t)
8927 (goto-char (match-beginning 0))
8928 (error "No match"))))
8929 (and (org-mode-p) (org-show-context 'link-search))
8930 type))
8932 (defun org-search-not-self (group &rest args)
8933 "Execute `re-search-forward', but only accept matches that do not
8934 enclose the position of `org-open-link-marker'."
8935 (let ((m org-open-link-marker))
8936 (catch 'exit
8937 (while (apply 're-search-forward args)
8938 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8939 (goto-char (match-end group))
8940 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8941 (> (match-beginning 0) (marker-position m))
8942 (< (match-end 0) (marker-position m)))
8943 (save-match-data
8944 (or (not (org-in-regexp
8945 org-bracket-link-analytic-regexp 1))
8946 (not (match-end 4)) ; no description
8947 (and (<= (match-beginning 4) (point))
8948 (>= (match-end 4) (point))))))
8949 (throw 'exit (point))))))))
8951 (defun org-get-buffer-for-internal-link (buffer)
8952 "Return a buffer to be used for displaying the link target of internal links."
8953 (cond
8954 ((not org-display-internal-link-with-indirect-buffer)
8955 buffer)
8956 ((string-match "(Clone)$" (buffer-name buffer))
8957 (message "Buffer is already a clone, not making another one")
8958 ;; we also do not modify visibility in this case
8959 buffer)
8960 (t ; make a new indirect buffer for displaying the link
8961 (let* ((bn (buffer-name buffer))
8962 (ibn (concat bn "(Clone)"))
8963 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8964 (with-current-buffer ib (org-overview))
8965 ib))))
8967 (defun org-do-occur (regexp &optional cleanup)
8968 "Call the Emacs command `occur'.
8969 If CLEANUP is non-nil, remove the printout of the regular expression
8970 in the *Occur* buffer. This is useful if the regex is long and not useful
8971 to read."
8972 (occur regexp)
8973 (when cleanup
8974 (let ((cwin (selected-window)) win beg end)
8975 (when (setq win (get-buffer-window "*Occur*"))
8976 (select-window win))
8977 (goto-char (point-min))
8978 (when (re-search-forward "match[a-z]+" nil t)
8979 (setq beg (match-end 0))
8980 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8981 (setq end (1- (match-beginning 0)))))
8982 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8983 (goto-char (point-min))
8984 (select-window cwin))))
8986 ;;; The mark ring for links jumps
8988 (defvar org-mark-ring nil
8989 "Mark ring for positions before jumps in Org-mode.")
8990 (defvar org-mark-ring-last-goto nil
8991 "Last position in the mark ring used to go back.")
8992 ;; Fill and close the ring
8993 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8994 (loop for i from 1 to org-mark-ring-length do
8995 (push (make-marker) org-mark-ring))
8996 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8997 org-mark-ring)
8999 (defun org-mark-ring-push (&optional pos buffer)
9000 "Put the current position or POS into the mark ring and rotate it."
9001 (interactive)
9002 (setq pos (or pos (point)))
9003 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9004 (move-marker (car org-mark-ring)
9005 (or pos (point))
9006 (or buffer (current-buffer)))
9007 (message "%s"
9008 (substitute-command-keys
9009 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9011 (defun org-mark-ring-goto (&optional n)
9012 "Jump to the previous position in the mark ring.
9013 With prefix arg N, jump back that many stored positions. When
9014 called several times in succession, walk through the entire ring.
9015 Org-mode commands jumping to a different position in the current file,
9016 or to another Org-mode file, automatically push the old position
9017 onto the ring."
9018 (interactive "p")
9019 (let (p m)
9020 (if (eq last-command this-command)
9021 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9022 (setq p org-mark-ring))
9023 (setq org-mark-ring-last-goto p)
9024 (setq m (car p))
9025 (switch-to-buffer (marker-buffer m))
9026 (goto-char m)
9027 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9029 (defun org-remove-angle-brackets (s)
9030 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9031 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9033 (defun org-add-angle-brackets (s)
9034 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9035 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9037 (defun org-remove-double-quotes (s)
9038 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9039 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9042 ;;; Following specific links
9044 (defun org-follow-timestamp-link ()
9045 (cond
9046 ((org-at-date-range-p t)
9047 (let ((org-agenda-start-on-weekday)
9048 (t1 (match-string 1))
9049 (t2 (match-string 2)))
9050 (setq t1 (time-to-days (org-time-string-to-time t1))
9051 t2 (time-to-days (org-time-string-to-time t2)))
9052 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9053 ((org-at-timestamp-p t)
9054 (org-agenda-list nil (time-to-days (org-time-string-to-time
9055 (substring (match-string 1) 0 10)))
9057 (t (error "This should not happen"))))
9060 ;;; Following file links
9061 (defvar org-wait nil)
9062 (defun org-open-file (path &optional in-emacs line search)
9063 "Open the file at PATH.
9064 First, this expands any special file name abbreviations. Then the
9065 configuration variable `org-file-apps' is checked if it contains an
9066 entry for this file type, and if yes, the corresponding command is launched.
9068 If no application is found, Emacs simply visits the file.
9070 With optional prefix argument IN-EMACS, Emacs will visit the file.
9071 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
9072 and to use an external application to visit the file.
9074 Optional LINE specifies a line to go to, optional SEARCH a string to
9075 search for. If LINE or SEARCH is given, but IN-EMACS is nil, it will
9076 be assumed that org-open-file was called to open a file: link, and the
9077 original link to match against org-file-apps will be reconstructed
9078 from PATH and whichever of LINE or SEARCH is given.
9080 If the file does not exist, an error is thrown."
9081 (let* ((file (if (equal path "")
9082 buffer-file-name
9083 (substitute-in-file-name (expand-file-name path))))
9084 (apps (append org-file-apps (org-default-apps)))
9085 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9086 (dirp (if remp nil (file-directory-p file)))
9087 (file (if (and dirp org-open-directory-means-index-dot-org)
9088 (concat (file-name-as-directory file) "index.org")
9089 file))
9090 (a-m-a-p (assq 'auto-mode apps))
9091 (dfile (downcase file))
9092 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9093 (link (cond ((and (eq line nil)
9094 (eq search nil))
9095 file)
9096 (line
9097 (concat file "::" (number-to-string line)))
9098 (search
9099 (concat file "::" search))))
9100 (dlink (downcase link))
9101 (old-buffer (current-buffer))
9102 (old-pos (point))
9103 (old-mode major-mode)
9104 ext cmd link-match-data)
9105 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9106 (setq ext (match-string 1 dfile))
9107 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9108 (setq ext (match-string 1 dfile))))
9109 (cond
9110 ((member in-emacs '((16) system))
9111 (setq cmd (cdr (assoc 'system apps))))
9112 (in-emacs (setq cmd 'emacs))
9114 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9115 (and dirp (cdr (assoc 'directory apps)))
9116 ;; if we find a match in org-file-apps, store the match
9117 ;; data for later
9118 (let ((match (assoc-default dlink (org-apps-regexp-alist
9119 apps a-m-a-p)
9120 'string-match)))
9121 (if match
9122 (progn (setq link-match-data (match-data))
9123 match)
9124 nil))
9125 (cdr (assoc ext apps))
9126 (cdr (assoc t apps))))))
9127 (when (eq cmd 'system)
9128 (setq cmd (cdr (assoc 'system apps))))
9129 (when (eq cmd 'default)
9130 (setq cmd (cdr (assoc t apps))))
9131 (when (eq cmd 'mailcap)
9132 (require 'mailcap)
9133 (mailcap-parse-mailcaps)
9134 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9135 (command (mailcap-mime-info mime-type)))
9136 (if (stringp command)
9137 (setq cmd command)
9138 (setq cmd 'emacs))))
9139 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9140 (not (file-exists-p file))
9141 (not org-open-non-existing-files))
9142 (error "No such file: %s" file))
9143 (cond
9144 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9145 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9146 (while (string-match "['\"]%s['\"]" cmd)
9147 (setq cmd (replace-match "%s" t t cmd)))
9148 (while (string-match "%s" cmd)
9149 (setq cmd (replace-match
9150 (save-match-data
9151 (shell-quote-argument
9152 (convert-standard-filename file)))
9153 t t cmd)))
9154 ;; Replace "%1", "%2" etc. in command with group matches from regex
9155 (save-match-data
9156 (let ((match-index 1)
9157 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9158 (set-match-data link-match-data)
9159 (while (<= match-index number-of-groups)
9160 (let ((regex (concat "%" (number-to-string match-index)))
9161 (replace-with (match-string match-index dlink)))
9162 (while (string-match regex cmd)
9163 (setq cmd (replace-match replace-with t t cmd))))
9164 (setq match-index (+ match-index 1)))))
9166 (save-window-excursion
9167 (start-process-shell-command cmd nil cmd)
9168 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9170 ((or (stringp cmd)
9171 (eq cmd 'emacs))
9172 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9173 (widen)
9174 (if line (org-goto-line line)
9175 (if search (org-link-search search))))
9176 ((consp cmd)
9177 (let ((file (convert-standard-filename file)))
9178 (save-match-data
9179 (set-match-data link-match-data)
9180 (eval cmd))))
9181 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9182 (and (org-mode-p) (eq old-mode 'org-mode)
9183 (or (not (equal old-buffer (current-buffer)))
9184 (not (equal old-pos (point))))
9185 (org-mark-ring-push old-pos old-buffer))))
9187 (defun org-default-apps ()
9188 "Return the default applications for this operating system."
9189 (cond
9190 ((eq system-type 'darwin)
9191 org-file-apps-defaults-macosx)
9192 ((eq system-type 'windows-nt)
9193 org-file-apps-defaults-windowsnt)
9194 (t org-file-apps-defaults-gnu)))
9196 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9197 "Convert extensions to regular expressions in the cars of LIST.
9198 Also, weed out any non-string entries, because the return value is used
9199 only for regexp matching.
9200 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9201 point to the symbol `emacs', indicating that the file should
9202 be opened in Emacs."
9203 (append
9204 (delq nil
9205 (mapcar (lambda (x)
9206 (if (not (stringp (car x)))
9208 (if (string-match "\\W" (car x))
9210 (cons (concat "\\." (car x) "\\(::.*\\)?\\'")
9211 (cdr x)))))
9212 list))
9213 (if add-auto-mode
9214 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9216 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9217 (defun org-file-remote-p (file)
9218 "Test whether FILE specifies a location on a remote system.
9219 Return non-nil if the location is indeed remote.
9221 For example, the filename \"/user@host:/foo\" specifies a location
9222 on the system \"/user@host:\"."
9223 (cond ((fboundp 'file-remote-p)
9224 (file-remote-p file))
9225 ((fboundp 'tramp-handle-file-remote-p)
9226 (tramp-handle-file-remote-p file))
9227 ((and (boundp 'ange-ftp-name-format)
9228 (string-match (car ange-ftp-name-format) file))
9230 (t nil)))
9233 ;;;; Refiling
9235 (defun org-get-org-file ()
9236 "Read a filename, with default directory `org-directory'."
9237 (let ((default (or org-default-notes-file remember-data-file)))
9238 (read-file-name (format "File name [%s]: " default)
9239 (file-name-as-directory org-directory)
9240 default)))
9242 (defun org-notes-order-reversed-p ()
9243 "Check if the current file should receive notes in reversed order."
9244 (cond
9245 ((not org-reverse-note-order) nil)
9246 ((eq t org-reverse-note-order) t)
9247 ((not (listp org-reverse-note-order)) nil)
9248 (t (catch 'exit
9249 (let ((all org-reverse-note-order)
9250 entry)
9251 (while (setq entry (pop all))
9252 (if (string-match (car entry) buffer-file-name)
9253 (throw 'exit (cdr entry))))
9254 nil)))))
9256 (defvar org-refile-target-table nil
9257 "The list of refile targets, created by `org-refile'.")
9259 (defvar org-agenda-new-buffers nil
9260 "Buffers created to visit agenda files.")
9262 (defun org-get-refile-targets (&optional default-buffer)
9263 "Produce a table with refile targets."
9264 (let ((case-fold-search nil)
9265 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9266 (entries (or org-refile-targets '((nil . (:level . 1)))))
9267 targets txt re files f desc descre fast-path-p level pos0)
9268 (message "Getting targets...")
9269 (with-current-buffer (or default-buffer (current-buffer))
9270 (while (setq entry (pop entries))
9271 (setq files (car entry) desc (cdr entry))
9272 (setq fast-path-p nil)
9273 (cond
9274 ((null files) (setq files (list (current-buffer))))
9275 ((eq files 'org-agenda-files)
9276 (setq files (org-agenda-files 'unrestricted)))
9277 ((and (symbolp files) (fboundp files))
9278 (setq files (funcall files)))
9279 ((and (symbolp files) (boundp files))
9280 (setq files (symbol-value files))))
9281 (if (stringp files) (setq files (list files)))
9282 (cond
9283 ((eq (car desc) :tag)
9284 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9285 ((eq (car desc) :todo)
9286 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9287 ((eq (car desc) :regexp)
9288 (setq descre (cdr desc)))
9289 ((eq (car desc) :level)
9290 (setq descre (concat "^\\*\\{" (number-to-string
9291 (if org-odd-levels-only
9292 (1- (* 2 (cdr desc)))
9293 (cdr desc)))
9294 "\\}[ \t]")))
9295 ((eq (car desc) :maxlevel)
9296 (setq fast-path-p t)
9297 (setq descre (concat "^\\*\\{1," (number-to-string
9298 (if org-odd-levels-only
9299 (1- (* 2 (cdr desc)))
9300 (cdr desc)))
9301 "\\}[ \t]")))
9302 (t (error "Bad refiling target description %s" desc)))
9303 (while (setq f (pop files))
9304 (with-current-buffer
9305 (if (bufferp f) f (org-get-agenda-file-buffer f))
9306 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
9307 (setq f (and f (expand-file-name f)))
9308 (if (eq org-refile-use-outline-path 'file)
9309 (push (list (file-name-nondirectory f) f nil nil) targets))
9310 (save-excursion
9311 (save-restriction
9312 (widen)
9313 (goto-char (point-min))
9314 (while (re-search-forward descre nil t)
9315 (goto-char (setq pos0 (point-at-bol)))
9316 (catch 'next
9317 (when org-refile-target-verify-function
9318 (save-match-data
9319 (or (funcall org-refile-target-verify-function)
9320 (throw 'next t))))
9321 (when (looking-at org-complex-heading-regexp)
9322 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
9323 txt (org-link-display-format (match-string 4))
9324 re (concat "^" (regexp-quote
9325 (buffer-substring (match-beginning 1)
9326 (match-end 4)))))
9327 (if (match-end 5) (setq re (concat re "[ \t]+"
9328 (regexp-quote
9329 (match-string 5)))))
9330 (setq re (concat re "[ \t]*$"))
9331 (when org-refile-use-outline-path
9332 (setq txt (mapconcat 'org-protect-slash
9333 (append
9334 (if (eq org-refile-use-outline-path 'file)
9335 (list (file-name-nondirectory
9336 (buffer-file-name (buffer-base-buffer))))
9337 (if (eq org-refile-use-outline-path 'full-file-path)
9338 (list (buffer-file-name (buffer-base-buffer)))))
9339 (org-get-outline-path fast-path-p level txt)
9340 (list txt))
9341 "/")))
9342 (push (list txt f re (point)) targets)))
9343 (when (= (point) pos0)
9344 ;; verification function has not moved point
9345 (goto-char (point-at-eol))))))))))
9346 (message "Getting targets...done")
9347 (nreverse targets)))
9349 (defun org-protect-slash (s)
9350 (while (string-match "/" s)
9351 (setq s (replace-match "\\" t t s)))
9354 (defvar org-olpa (make-vector 20 nil))
9356 (defun org-get-outline-path (&optional fastp level heading)
9357 "Return the outline path to the current entry, as a list.
9358 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9359 routine which makes outline path derivations for an entire file,
9360 avoiding backtracing."
9361 (if fastp
9362 (progn
9363 (if (> level 19)
9364 (error "Outline path failure, more than 19 levels."))
9365 (loop for i from level upto 19 do
9366 (aset org-olpa i nil))
9367 (prog1
9368 (delq nil (append org-olpa nil))
9369 (aset org-olpa level heading)))
9370 (let (rtn case-fold-search)
9371 (save-excursion
9372 (save-restriction
9373 (widen)
9374 (while (org-up-heading-safe)
9375 (when (looking-at org-complex-heading-regexp)
9376 (push (org-match-string-no-properties 4) rtn)))
9377 rtn)))))
9379 (defun org-format-outline-path (path &optional width prefix)
9380 "Format the outlie path PATH for display.
9381 Width is the maximum number of characters that is available.
9382 Prefix is a prefix to be included in the returned string,
9383 such as the file name."
9384 (setq width (or width 79))
9385 (if prefix (setq width (- width (length prefix))))
9386 (if (not path)
9387 (or prefix "")
9388 (let* ((nsteps (length path))
9389 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9390 (maxwidth (if (<= total-width width)
9391 10000 ;; everything fits
9392 ;; we need to shorten the level headings
9393 (/ (- width nsteps) nsteps)))
9394 (org-odd-levels-only nil)
9395 (n 0)
9396 (total (1+ (length prefix))))
9397 (setq maxwidth (max maxwidth 10))
9398 (concat prefix
9399 (mapconcat
9400 (lambda (h)
9401 (setq n (1+ n))
9402 (if (and (= n nsteps) (< maxwidth 10000))
9403 (setq maxwidth (- total-width total)))
9404 (if (< (length h) maxwidth)
9405 (progn (setq total (+ total (length h) 1)) h)
9406 (setq h (substring h 0 (- maxwidth 2))
9407 total (+ total maxwidth 1))
9408 (if (string-match "[ \t]+\\'" h)
9409 (setq h (substring h 0 (match-beginning 0))))
9410 (setq h (concat h "..")))
9411 (org-add-props h nil 'face
9412 (nth (% (1- n) org-n-level-faces)
9413 org-level-faces))
9415 path "/")))))
9417 (defun org-display-outline-path (&optional file current)
9418 "Display the current outline path in the echo area."
9419 (interactive "P")
9420 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
9421 (case-fold-search nil)
9422 (path (and (org-mode-p) (org-get-outline-path))))
9423 (if current (setq path (append path
9424 (save-excursion
9425 (org-back-to-heading t)
9426 (if (looking-at org-complex-heading-regexp)
9427 (list (match-string 4)))))))
9428 (message "%s"
9429 (org-format-outline-path
9430 path
9431 (1- (frame-width))
9432 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9434 (defvar org-refile-history nil
9435 "History for refiling operations.")
9437 (defvar org-after-refile-insert-hook nil
9438 "Hook run after `org-refile' has inserted its stuff at the new location.
9439 Note that this is still *before* the stuff will be removed from
9440 the *old* location.")
9442 (defun org-refile (&optional goto default-buffer rfloc)
9443 "Move the entry at point to another heading.
9444 The list of target headings is compiled using the information in
9445 `org-refile-targets', which see. This list is created before each use
9446 and will therefore always be up-to-date.
9448 At the target location, the entry is filed as a subitem of the target heading.
9449 Depending on `org-reverse-note-order', the new subitem will either be the
9450 first or the last subitem.
9452 If there is an active region, all entries in that region will be moved.
9453 However, the region must fulfil the requirement that the first heading
9454 is the first one sets the top-level of the moved text - at most siblings
9455 below it are allowed.
9457 With prefix arg GOTO, the command will only visit the target location,
9458 not actually move anything.
9459 With a double prefix `C-u C-u', go to the location where the last refiling
9460 operation has put the subtree.
9461 With a prefix argument of `2', refile to the running clock.
9463 RFLOC can be a refile location obtained in a different way.
9465 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9466 (interactive "P")
9467 (let* ((cbuf (current-buffer))
9468 (regionp (org-region-active-p))
9469 (region-start (and regionp (region-beginning)))
9470 (region-end (and regionp (region-end)))
9471 (region-length (and regionp (- region-end region-start)))
9472 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9473 pos it nbuf file re level reversed)
9474 (setq last-command nil)
9475 (when regionp
9476 (goto-char region-start)
9477 (or (bolp) (goto-char (point-at-bol)))
9478 (setq region-start (point))
9479 (unless (org-kill-is-subtree-p
9480 (buffer-substring region-start region-end))
9481 (error "The region is not a (sequence of) subtree(s)")))
9482 (if (equal goto '(16))
9483 (org-refile-goto-last-stored)
9484 (when (or
9485 (and (equal goto 2)
9486 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9487 (prog1
9488 (setq it (list (or org-clock-heading "running clock")
9489 (buffer-file-name
9490 (marker-buffer org-clock-hd-marker))
9492 (marker-position org-clock-hd-marker)))
9493 (setq goto nil)))
9494 (setq it (or rfloc
9495 (save-excursion
9496 (org-refile-get-location
9497 (if goto "Goto: " "Refile to: ") default-buffer
9498 org-refile-allow-creating-parent-nodes)))))
9499 (setq file (nth 1 it)
9500 re (nth 2 it)
9501 pos (nth 3 it))
9502 (if (and (not goto)
9504 (equal (buffer-file-name) file)
9505 (if regionp
9506 (and (>= pos region-start)
9507 (<= pos region-end))
9508 (and (>= pos (point))
9509 (< pos (save-excursion
9510 (org-end-of-subtree t t))))))
9511 (error "Cannot refile to position inside the tree or region"))
9513 (setq nbuf (or (find-buffer-visiting file)
9514 (find-file-noselect file)))
9515 (if goto
9516 (progn
9517 (switch-to-buffer nbuf)
9518 (goto-char pos)
9519 (org-show-context 'org-goto))
9520 (if regionp
9521 (progn
9522 (org-kill-new (buffer-substring region-start region-end))
9523 (org-save-markers-in-region region-start region-end))
9524 (org-copy-subtree 1 nil t))
9525 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9526 (find-file-noselect file)))
9527 (setq reversed (org-notes-order-reversed-p))
9528 (save-excursion
9529 (save-restriction
9530 (widen)
9531 (if pos
9532 (progn
9533 (goto-char pos)
9534 (looking-at outline-regexp)
9535 (setq level (org-get-valid-level (funcall outline-level) 1))
9536 (goto-char
9537 (if reversed
9538 (or (outline-next-heading) (point-max))
9539 (or (save-excursion (org-get-next-sibling))
9540 (org-end-of-subtree t t)
9541 (point-max)))))
9542 (setq level 1)
9543 (if (not reversed)
9544 (goto-char (point-max))
9545 (goto-char (point-min))
9546 (or (outline-next-heading) (goto-char (point-max)))))
9547 (if (not (bolp)) (newline))
9548 (org-paste-subtree level)
9549 (when org-log-refile
9550 (org-add-log-setup 'refile nil nil 'findpos
9551 org-log-refile)
9552 (unless (eq org-log-refile 'note)
9553 (save-excursion (org-add-log-note))))
9554 (and org-auto-align-tags (org-set-tags nil t))
9555 (bookmark-set "org-refile-last-stored")
9556 (if (fboundp 'deactivate-mark) (deactivate-mark))
9557 (run-hooks 'org-after-refile-insert-hook))))
9558 (if regionp
9559 (delete-region (point) (+ (point) region-length))
9560 (org-cut-subtree))
9561 (when (featurep 'org-inlinetask)
9562 (org-inlinetask-remove-END-maybe))
9563 (setq org-markers-to-move nil)
9564 (message "Refiled to \"%s\"" (car it))))))
9565 (org-reveal))
9567 (defun org-refile-goto-last-stored ()
9568 "Go to the location where the last refile was stored."
9569 (interactive)
9570 (bookmark-jump "org-refile-last-stored")
9571 (message "This is the location of the last refile"))
9573 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9574 "Prompt the user for a refile location, using PROMPT."
9575 (let ((org-refile-targets org-refile-targets)
9576 (org-refile-use-outline-path org-refile-use-outline-path))
9577 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9578 (unless org-refile-target-table
9579 (error "No refile targets"))
9580 (let* ((cbuf (current-buffer))
9581 (partial-completion-mode nil)
9582 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9583 (cfunc (if (and org-refile-use-outline-path
9584 org-outline-path-complete-in-steps)
9585 'org-olpath-completing-read
9586 'org-icompleting-read))
9587 (extra (if org-refile-use-outline-path "/" ""))
9588 (filename (and cfn (expand-file-name cfn)))
9589 (tbl (mapcar
9590 (lambda (x)
9591 (if (and (not (member org-refile-use-outline-path
9592 '(file full-file-path)))
9593 (not (equal filename (nth 1 x))))
9594 (cons (concat (car x) extra " ("
9595 (file-name-nondirectory (nth 1 x)) ")")
9596 (cdr x))
9597 (cons (concat (car x) extra) (cdr x))))
9598 org-refile-target-table))
9599 (completion-ignore-case t)
9600 pa answ parent-target child parent old-hist)
9601 (setq old-hist org-refile-history)
9602 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9603 nil 'org-refile-history))
9604 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9605 (if pa
9606 (progn
9607 (when (or (not org-refile-history)
9608 (not (eq old-hist org-refile-history))
9609 (not (equal (car pa) (car org-refile-history))))
9610 (setq org-refile-history
9611 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9612 org-refile-history
9613 (cdr org-refile-history))))
9614 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9615 (pop org-refile-history)))
9617 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9618 (progn
9619 (setq parent (match-string 1 answ)
9620 child (match-string 2 answ))
9621 (setq parent-target (or (assoc parent tbl)
9622 (assoc (concat parent "/") tbl)))
9623 (when (and parent-target
9624 (or (eq new-nodes t)
9625 (and (eq new-nodes 'confirm)
9626 (y-or-n-p (format "Create new node \"%s\"? "
9627 child)))))
9628 (org-refile-new-child parent-target child)))
9629 (error "Invalid target location")))))
9631 (defun org-refile-new-child (parent-target child)
9632 "Use refile target PARENT-TARGET to add new CHILD below it."
9633 (unless parent-target
9634 (error "Cannot find parent for new node"))
9635 (let ((file (nth 1 parent-target))
9636 (pos (nth 3 parent-target))
9637 level)
9638 (with-current-buffer (or (find-buffer-visiting file)
9639 (find-file-noselect file))
9640 (save-excursion
9641 (save-restriction
9642 (widen)
9643 (if pos
9644 (goto-char pos)
9645 (goto-char (point-max))
9646 (if (not (bolp)) (newline)))
9647 (when (looking-at outline-regexp)
9648 (setq level (funcall outline-level))
9649 (org-end-of-subtree t t))
9650 (org-back-over-empty-lines)
9651 (insert "\n" (make-string
9652 (if pos (org-get-valid-level level 1) 1) ?*)
9653 " " child "\n")
9654 (beginning-of-line 0)
9655 (list (concat (car parent-target) "/" child) file "" (point)))))))
9657 (defun org-olpath-completing-read (prompt collection &rest args)
9658 "Read an outline path like a file name."
9659 (let ((thetable collection)
9660 (org-completion-use-ido nil) ; does not work with ido.
9661 (org-completion-use-iswitchb nil)) ; or iswitchb
9662 (apply
9663 'org-icompleting-read prompt
9664 (lambda (string predicate &optional flag)
9665 (let (rtn r f (l (length string)))
9666 (cond
9667 ((eq flag nil)
9668 ;; try completion
9669 (try-completion string thetable))
9670 ((eq flag t)
9671 ;; all-completions
9672 (setq rtn (all-completions string thetable predicate))
9673 (mapcar
9674 (lambda (x)
9675 (setq r (substring x l))
9676 (if (string-match " ([^)]*)$" x)
9677 (setq f (match-string 0 x))
9678 (setq f ""))
9679 (if (string-match "/" r)
9680 (concat string (substring r 0 (match-end 0)) f)
9682 rtn))
9683 ((eq flag 'lambda)
9684 ;; exact match?
9685 (assoc string thetable)))
9687 args)))
9689 ;;;; Dynamic blocks
9691 (defun org-find-dblock (name)
9692 "Find the first dynamic block with name NAME in the buffer.
9693 If not found, stay at current position and return nil."
9694 (let (pos)
9695 (save-excursion
9696 (goto-char (point-min))
9697 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9698 nil t)
9699 (match-beginning 0))))
9700 (if pos (goto-char pos))
9701 pos))
9703 (defconst org-dblock-start-re
9704 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9705 "Matches the start line of a dynamic block, with parameters.")
9707 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9708 "Matches the end of a dynamic block.")
9710 (defun org-create-dblock (plist)
9711 "Create a dynamic block section, with parameters taken from PLIST.
9712 PLIST must contain a :name entry which is used as name of the block."
9713 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9714 (end-of-line 1)
9715 (newline))
9716 (let ((col (current-column))
9717 (name (plist-get plist :name)))
9718 (insert "#+BEGIN: " name)
9719 (while plist
9720 (if (eq (car plist) :name)
9721 (setq plist (cddr plist))
9722 (insert " " (prin1-to-string (pop plist)))))
9723 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9724 (beginning-of-line -2)))
9726 (defun org-prepare-dblock ()
9727 "Prepare dynamic block for refresh.
9728 This empties the block, puts the cursor at the insert position and returns
9729 the property list including an extra property :name with the block name."
9730 (unless (looking-at org-dblock-start-re)
9731 (error "Not at a dynamic block"))
9732 (let* ((begdel (1+ (match-end 0)))
9733 (name (org-no-properties (match-string 1)))
9734 (params (append (list :name name)
9735 (read (concat "(" (match-string 3) ")")))))
9736 (save-excursion
9737 (beginning-of-line 1)
9738 (skip-chars-forward " \t")
9739 (setq params (plist-put params :indentation-column (current-column))))
9740 (unless (re-search-forward org-dblock-end-re nil t)
9741 (error "Dynamic block not terminated"))
9742 (setq params
9743 (append params
9744 (list :content (buffer-substring
9745 begdel (match-beginning 0)))))
9746 (delete-region begdel (match-beginning 0))
9747 (goto-char begdel)
9748 (open-line 1)
9749 params))
9751 (defun org-map-dblocks (&optional command)
9752 "Apply COMMAND to all dynamic blocks in the current buffer.
9753 If COMMAND is not given, use `org-update-dblock'."
9754 (let ((cmd (or command 'org-update-dblock)))
9755 (save-excursion
9756 (goto-char (point-min))
9757 (while (re-search-forward org-dblock-start-re nil t)
9758 (goto-char (match-beginning 0))
9759 (save-excursion
9760 (condition-case nil
9761 (funcall cmd)
9762 (error (message "Error during update of dynamic block"))))
9763 (unless (re-search-forward org-dblock-end-re nil t)
9764 (error "Dynamic block not terminated"))))))
9766 (defun org-dblock-update (&optional arg)
9767 "User command for updating dynamic blocks.
9768 Update the dynamic block at point. With prefix ARG, update all dynamic
9769 blocks in the buffer."
9770 (interactive "P")
9771 (if arg
9772 (org-update-all-dblocks)
9773 (or (looking-at org-dblock-start-re)
9774 (org-beginning-of-dblock))
9775 (org-update-dblock)))
9777 (defun org-update-dblock ()
9778 "Update the dynamic block at point
9779 This means to empty the block, parse for parameters and then call
9780 the correct writing function."
9781 (save-window-excursion
9782 (let* ((pos (point))
9783 (line (org-current-line))
9784 (params (org-prepare-dblock))
9785 (name (plist-get params :name))
9786 (indent (plist-get params :indentation-column))
9787 (cmd (intern (concat "org-dblock-write:" name))))
9788 (message "Updating dynamic block `%s' at line %d..." name line)
9789 (funcall cmd params)
9790 (message "Updating dynamic block `%s' at line %d...done" name line)
9791 (goto-char pos)
9792 (when (and indent (> indent 0))
9793 (setq indent (make-string indent ?\ ))
9794 (save-excursion
9795 (org-beginning-of-dblock)
9796 (forward-line 1)
9797 (while (not (looking-at org-dblock-end-re))
9798 (insert indent)
9799 (beginning-of-line 2))
9800 (when (looking-at org-dblock-end-re)
9801 (and (looking-at "[ \t]+")
9802 (replace-match ""))
9803 (insert indent)))))))
9805 (defun org-beginning-of-dblock ()
9806 "Find the beginning of the dynamic block at point.
9807 Error if there is no such block at point."
9808 (let ((pos (point))
9809 beg)
9810 (end-of-line 1)
9811 (if (and (re-search-backward org-dblock-start-re nil t)
9812 (setq beg (match-beginning 0))
9813 (re-search-forward org-dblock-end-re nil t)
9814 (> (match-end 0) pos))
9815 (goto-char beg)
9816 (goto-char pos)
9817 (error "Not in a dynamic block"))))
9819 (defun org-update-all-dblocks ()
9820 "Update all dynamic blocks in the buffer.
9821 This function can be used in a hook."
9822 (when (org-mode-p)
9823 (org-map-dblocks 'org-update-dblock)))
9826 ;;;; Completion
9828 (defconst org-additional-option-like-keywords
9829 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9830 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9831 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
9832 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
9833 "BEGIN:" "END:"
9834 "ORGTBL" "TBLFM:" "TBLNAME:"
9835 "BEGIN_EXAMPLE" "END_EXAMPLE"
9836 "BEGIN_QUOTE" "END_QUOTE"
9837 "BEGIN_VERSE" "END_VERSE"
9838 "BEGIN_CENTER" "END_CENTER"
9839 "BEGIN_SRC" "END_SRC"
9840 "CATEGORY" "COLUMNS"
9841 "CAPTION" "LABEL"
9842 "SETUPFILE"
9843 "BIND"
9844 "MACRO"))
9846 (defcustom org-structure-template-alist
9848 ("s" "#+begin_src ?\n\n#+end_src"
9849 "<src lang=\"?\">\n\n</src>")
9850 ("e" "#+begin_example\n?\n#+end_example"
9851 "<example>\n?\n</example>")
9852 ("q" "#+begin_quote\n?\n#+end_quote"
9853 "<quote>\n?\n</quote>")
9854 ("v" "#+begin_verse\n?\n#+end_verse"
9855 "<verse>\n?\n/verse>")
9856 ("c" "#+begin_center\n?\n#+end_center"
9857 "<center>\n?\n/center>")
9858 ("l" "#+begin_latex\n?\n#+end_latex"
9859 "<literal style=\"latex\">\n?\n</literal>")
9860 ("L" "#+latex: "
9861 "<literal style=\"latex\">?</literal>")
9862 ("h" "#+begin_html\n?\n#+end_html"
9863 "<literal style=\"html\">\n?\n</literal>")
9864 ("H" "#+html: "
9865 "<literal style=\"html\">?</literal>")
9866 ("a" "#+begin_ascii\n?\n#+end_ascii")
9867 ("A" "#+ascii: ")
9868 ("i" "#+include %file ?"
9869 "<include file=%file markup=\"?\">")
9871 "Structure completion elements.
9872 This is a list of abbreviation keys and values. The value gets inserted
9873 it you type @samp{.} followed by the key and then the completion key,
9874 usually `M-TAB'. %file will be replaced by a file name after prompting
9875 for the file using completion.
9876 There are two templates for each key, the first uses the original Org syntax,
9877 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9878 the default when the /org-mtags.el/ module has been loaded. See also the
9879 variable `org-mtags-prefer-muse-templates'.
9880 This is an experimental feature, it is undecided if it is going to stay in."
9881 :group 'org-completion
9882 :type '(repeat
9883 (string :tag "Key")
9884 (string :tag "Template")
9885 (string :tag "Muse Template")))
9887 (defun org-try-structure-completion ()
9888 "Try to complete a structure template before point.
9889 This looks for strings like \"<e\" on an otherwise empty line and
9890 expands them."
9891 (let ((l (buffer-substring (point-at-bol) (point)))
9893 (when (and (looking-at "[ \t]*$")
9894 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9895 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9896 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9897 (match-beginning 1)) a)
9898 t)))
9900 (defun org-complete-expand-structure-template (start cell)
9901 "Expand a structure template."
9902 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9903 (rpl (nth (if musep 2 1) cell))
9904 (ind ""))
9905 (delete-region start (point))
9906 (when (string-match "\\`#\\+" rpl)
9907 (cond
9908 ((bolp))
9909 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9910 (setq ind (buffer-substring (point-at-bol) (point))))
9911 (t (newline))))
9912 (setq start (point))
9913 (if (string-match "%file" rpl)
9914 (setq rpl (replace-match
9915 (concat
9916 "\""
9917 (save-match-data
9918 (abbreviate-file-name (read-file-name "Include file: ")))
9919 "\"")
9920 t t rpl)))
9921 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9922 (concat "\n" ind)))
9923 (insert rpl)
9924 (if (re-search-backward "\\?" start t) (delete-char 1))))
9927 (defun org-complete (&optional arg)
9928 "Perform completion on word at point.
9929 At the beginning of a headline, this completes TODO keywords as given in
9930 `org-todo-keywords'.
9931 If the current word is preceded by a backslash, completes the TeX symbols
9932 that are supported for HTML support.
9933 If the current word is preceded by \"#+\", completes special words for
9934 setting file options.
9935 In the line after \"#+STARTUP:, complete valid keywords.\"
9936 At all other locations, this simply calls the value of
9937 `org-completion-fallback-command'."
9938 (interactive "P")
9939 (org-without-partial-completion
9940 (catch 'exit
9941 (let* ((a nil)
9942 (end (point))
9943 (beg1 (save-excursion
9944 (skip-chars-backward (org-re "[:alnum:]_@"))
9945 (point)))
9946 (beg (save-excursion
9947 (skip-chars-backward "a-zA-Z0-9_:$")
9948 (point)))
9949 (confirm (lambda (x) (stringp (car x))))
9950 (searchhead (equal (char-before beg) ?*))
9951 (struct
9952 (when (and (member (char-before beg1) '(?. ?<))
9953 (setq a (assoc (buffer-substring beg1 (point))
9954 org-structure-template-alist)))
9955 (org-complete-expand-structure-template (1- beg1) a)
9956 (throw 'exit t)))
9957 (tag (and (equal (char-before beg1) ?:)
9958 (equal (char-after (point-at-bol)) ?*)))
9959 (prop (and (equal (char-before beg1) ?:)
9960 (not (equal (char-after (point-at-bol)) ?*))))
9961 (texp (equal (char-before beg) ?\\))
9962 (link (equal (char-before beg) ?\[))
9963 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9964 beg)
9965 "#+"))
9966 (startup (string-match "^#\\+STARTUP:.*"
9967 (buffer-substring (point-at-bol) (point))))
9968 (completion-ignore-case opt)
9969 (type nil)
9970 (tbl nil)
9971 (table (cond
9972 (opt
9973 (setq type :opt)
9974 (require 'org-exp)
9975 (append
9976 (delq nil
9977 (mapcar
9978 (lambda (x)
9979 (if (string-match
9980 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9981 (cons (match-string 2 x)
9982 (match-string 1 x))))
9983 (org-split-string (org-get-current-options) "\n")))
9984 (mapcar 'list org-additional-option-like-keywords)))
9985 (startup
9986 (setq type :startup)
9987 org-startup-options)
9988 (link (append org-link-abbrev-alist-local
9989 org-link-abbrev-alist))
9990 (texp
9991 (setq type :tex)
9992 (append org-entities-user org-entities))
9993 ((string-match "\\`\\*+[ \t]+\\'"
9994 (buffer-substring (point-at-bol) beg))
9995 (setq type :todo)
9996 (mapcar 'list org-todo-keywords-1))
9997 (searchhead
9998 (setq type :searchhead)
9999 (save-excursion
10000 (goto-char (point-min))
10001 (while (re-search-forward org-todo-line-regexp nil t)
10002 (push (list
10003 (org-make-org-heading-search-string
10004 (match-string 3) t))
10005 tbl)))
10006 tbl)
10007 (tag (setq type :tag beg beg1)
10008 (or org-tag-alist (org-get-buffer-tags)))
10009 (prop (setq type :prop beg beg1)
10010 (mapcar 'list (org-buffer-property-keys nil t t)))
10011 (t (progn
10012 (call-interactively org-completion-fallback-command)
10013 (throw 'exit nil)))))
10014 (pattern (buffer-substring-no-properties beg end))
10015 (completion (try-completion pattern table confirm)))
10016 (cond ((eq completion t)
10017 (if (not (assoc (upcase pattern) table))
10018 (message "Already complete")
10019 (if (and (equal type :opt)
10020 (not (member (car (assoc (upcase pattern) table))
10021 org-additional-option-like-keywords)))
10022 (insert (substring (cdr (assoc (upcase pattern) table))
10023 (length pattern)))
10024 (if (memq type '(:tag :prop)) (insert ":")))))
10025 ((null completion)
10026 (message "Can't find completion for \"%s\"" pattern)
10027 (ding))
10028 ((not (string= pattern completion))
10029 (delete-region beg end)
10030 (if (string-match " +$" completion)
10031 (setq completion (replace-match "" t t completion)))
10032 (insert completion)
10033 (if (get-buffer-window "*Completions*")
10034 (delete-window (get-buffer-window "*Completions*")))
10035 (if (assoc completion table)
10036 (if (eq type :todo) (insert " ")
10037 (if (memq type '(:tag :prop)) (insert ":"))))
10038 (if (and (equal type :opt) (assoc completion table))
10039 (message "%s" (substitute-command-keys
10040 "Press \\[org-complete] again to insert example settings"))))
10042 (message "Making completion list...")
10043 (let ((list (sort (all-completions pattern table confirm)
10044 'string<)))
10045 (with-output-to-temp-buffer "*Completions*"
10046 (condition-case nil
10047 ;; Protection needed for XEmacs and emacs 21
10048 (display-completion-list list pattern)
10049 (error (display-completion-list list)))))
10050 (message "Making completion list...%s" "done")))))))
10052 ;;;; TODO, DEADLINE, Comments
10054 (defun org-toggle-comment ()
10055 "Change the COMMENT state of an entry."
10056 (interactive)
10057 (save-excursion
10058 (org-back-to-heading)
10059 (let (case-fold-search)
10060 (if (looking-at (concat outline-regexp
10061 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10062 (replace-match "" t t nil 1)
10063 (if (looking-at outline-regexp)
10064 (progn
10065 (goto-char (match-end 0))
10066 (insert org-comment-string " ")))))))
10068 (defvar org-last-todo-state-is-todo nil
10069 "This is non-nil when the last TODO state change led to a TODO state.
10070 If the last change removed the TODO tag or switched to DONE, then
10071 this is nil.")
10073 (defvar org-setting-tags nil) ; dynamically skipped
10075 (defun org-parse-local-options (string var)
10076 "Parse STRING for startup setting relevant for variable VAR."
10077 (let ((rtn (symbol-value var))
10078 e opts)
10079 (save-match-data
10080 (if (or (not string) (not (string-match "\\S-" string)))
10082 (setq opts (delq nil (mapcar (lambda (x)
10083 (setq e (assoc x org-startup-options))
10084 (if (eq (nth 1 e) var) e nil))
10085 (org-split-string string "[ \t]+"))))
10086 (if (not opts)
10088 (setq rtn nil)
10089 (while (setq e (pop opts))
10090 (if (not (nth 3 e))
10091 (setq rtn (nth 2 e))
10092 (if (not (listp rtn)) (setq rtn nil))
10093 (push (nth 2 e) rtn)))
10094 rtn)))))
10096 (defvar org-todo-setup-filter-hook nil
10097 "Hook for functions that pre-filter todo specs.
10099 Each function takes a todo spec and returns either `nil' or the spec
10100 transformed into canonical form." )
10102 (defvar org-todo-get-default-hook nil
10103 "Hook for functions that get a default item for todo.
10105 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10106 `nil' or a string to be used for the todo mark." )
10108 (defvar org-agenda-headline-snapshot-before-repeat)
10110 (defun org-todo (&optional arg)
10111 "Change the TODO state of an item.
10112 The state of an item is given by a keyword at the start of the heading,
10113 like
10114 *** TODO Write paper
10115 *** DONE Call mom
10117 The different keywords are specified in the variable `org-todo-keywords'.
10118 By default the available states are \"TODO\" and \"DONE\".
10119 So for this example: when the item starts with TODO, it is changed to DONE.
10120 When it starts with DONE, the DONE is removed. And when neither TODO nor
10121 DONE are present, add TODO at the beginning of the heading.
10123 With C-u prefix arg, use completion to determine the new state.
10124 With numeric prefix arg, switch to that state.
10125 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
10126 With a triple C-u prefix, circumvent any state blocking.
10128 For calling through lisp, arg is also interpreted in the following way:
10129 'none -> empty state
10130 \"\"(empty string) -> switch to empty state
10131 'done -> switch to DONE
10132 'nextset -> switch to the next set of keywords
10133 'previousset -> switch to the previous set of keywords
10134 \"WAITING\" -> switch to the specified keyword, but only if it
10135 really is a member of `org-todo-keywords'."
10136 (interactive "P")
10137 (if (equal arg '(16)) (setq arg 'nextset))
10138 (let ((org-blocker-hook org-blocker-hook)
10139 (case-fold-search nil))
10140 (when (equal arg '(64))
10141 (setq arg nil org-blocker-hook nil))
10142 (when (and org-blocker-hook
10143 (or org-inhibit-blocking
10144 (org-entry-get nil "NOBLOCKING")))
10145 (setq org-blocker-hook nil))
10146 (save-excursion
10147 (catch 'exit
10148 (org-back-to-heading t)
10149 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10150 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10151 (looking-at " *"))
10152 (let* ((match-data (match-data))
10153 (startpos (point-at-bol))
10154 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
10155 (org-log-done org-log-done)
10156 (org-log-repeat org-log-repeat)
10157 (org-todo-log-states org-todo-log-states)
10158 (this (match-string 1))
10159 (hl-pos (match-beginning 0))
10160 (head (org-get-todo-sequence-head this))
10161 (ass (assoc head org-todo-kwd-alist))
10162 (interpret (nth 1 ass))
10163 (done-word (nth 3 ass))
10164 (final-done-word (nth 4 ass))
10165 (last-state (or this ""))
10166 (completion-ignore-case t)
10167 (member (member this org-todo-keywords-1))
10168 (tail (cdr member))
10169 (state (cond
10170 ((and org-todo-key-trigger
10171 (or (and (equal arg '(4))
10172 (eq org-use-fast-todo-selection 'prefix))
10173 (and (not arg) org-use-fast-todo-selection
10174 (not (eq org-use-fast-todo-selection
10175 'prefix)))))
10176 ;; Use fast selection
10177 (org-fast-todo-selection))
10178 ((and (equal arg '(4))
10179 (or (not org-use-fast-todo-selection)
10180 (not org-todo-key-trigger)))
10181 ;; Read a state with completion
10182 (org-icompleting-read
10183 "State: " (mapcar (lambda(x) (list x))
10184 org-todo-keywords-1)
10185 nil t))
10186 ((eq arg 'right)
10187 (if this
10188 (if tail (car tail) nil)
10189 (car org-todo-keywords-1)))
10190 ((eq arg 'left)
10191 (if (equal member org-todo-keywords-1)
10193 (if this
10194 (nth (- (length org-todo-keywords-1)
10195 (length tail) 2)
10196 org-todo-keywords-1)
10197 (org-last org-todo-keywords-1))))
10198 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10199 (setq arg nil))) ; hack to fall back to cycling
10200 (arg
10201 ;; user or caller requests a specific state
10202 (cond
10203 ((equal arg "") nil)
10204 ((eq arg 'none) nil)
10205 ((eq arg 'done) (or done-word (car org-done-keywords)))
10206 ((eq arg 'nextset)
10207 (or (car (cdr (member head org-todo-heads)))
10208 (car org-todo-heads)))
10209 ((eq arg 'previousset)
10210 (let ((org-todo-heads (reverse org-todo-heads)))
10211 (or (car (cdr (member head org-todo-heads)))
10212 (car org-todo-heads))))
10213 ((car (member arg org-todo-keywords-1)))
10214 ((stringp arg)
10215 (error "State `%s' not valid in this file" arg))
10216 ((nth (1- (prefix-numeric-value arg))
10217 org-todo-keywords-1))))
10218 ((null member) (or head (car org-todo-keywords-1)))
10219 ((equal this final-done-word) nil) ;; -> make empty
10220 ((null tail) nil) ;; -> first entry
10221 ((memq interpret '(type priority))
10222 (if (eq this-command last-command)
10223 (car tail)
10224 (if (> (length tail) 0)
10225 (or done-word (car org-done-keywords))
10226 nil)))
10228 (car tail))))
10229 (state (or
10230 (run-hook-with-args-until-success
10231 'org-todo-get-default-hook state last-state)
10232 state))
10233 (next (if state (concat " " state " ") " "))
10234 (change-plist (list :type 'todo-state-change :from this :to state
10235 :position startpos))
10236 dolog now-done-p)
10237 (when org-blocker-hook
10238 (setq org-last-todo-state-is-todo
10239 (not (member this org-done-keywords)))
10240 (unless (save-excursion
10241 (save-match-data
10242 (run-hook-with-args-until-failure
10243 'org-blocker-hook change-plist)))
10244 (if (interactive-p)
10245 (error "TODO state change from %s to %s blocked" this state)
10246 ;; fail silently
10247 (message "TODO state change from %s to %s blocked" this state)
10248 (throw 'exit nil))))
10249 (store-match-data match-data)
10250 (replace-match next t t)
10251 (unless (pos-visible-in-window-p hl-pos)
10252 (message "TODO state changed to %s" (org-trim next)))
10253 (unless head
10254 (setq head (org-get-todo-sequence-head state)
10255 ass (assoc head org-todo-kwd-alist)
10256 interpret (nth 1 ass)
10257 done-word (nth 3 ass)
10258 final-done-word (nth 4 ass)))
10259 (when (memq arg '(nextset previousset))
10260 (message "Keyword-Set %d/%d: %s"
10261 (- (length org-todo-sets) -1
10262 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10263 (length org-todo-sets)
10264 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10265 (setq org-last-todo-state-is-todo
10266 (not (member state org-done-keywords)))
10267 (setq now-done-p (and (member state org-done-keywords)
10268 (not (member this org-done-keywords))))
10269 (and logging (org-local-logging logging))
10270 (when (and (or org-todo-log-states org-log-done)
10271 (not (eq org-inhibit-logging t))
10272 (not (memq arg '(nextset previousset))))
10273 ;; we need to look at recording a time and note
10274 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10275 (nth 2 (assoc this org-todo-log-states))))
10276 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10277 (setq dolog 'time))
10278 (when (and state
10279 (member state org-not-done-keywords)
10280 (not (member this org-not-done-keywords)))
10281 ;; This is now a todo state and was not one before
10282 ;; If there was a CLOSED time stamp, get rid of it.
10283 (org-add-planning-info nil nil 'closed))
10284 (when (and now-done-p org-log-done)
10285 ;; It is now done, and it was not done before
10286 (org-add-planning-info 'closed (org-current-time))
10287 (if (and (not dolog) (eq 'note org-log-done))
10288 (org-add-log-setup 'done state this 'findpos 'note)))
10289 (when (and state dolog)
10290 ;; This is a non-nil state, and we need to log it
10291 (org-add-log-setup 'state state this 'findpos dolog)))
10292 ;; Fixup tag positioning
10293 (org-todo-trigger-tag-changes state)
10294 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10295 (when org-provide-todo-statistics
10296 (org-update-parent-todo-statistics))
10297 (run-hooks 'org-after-todo-state-change-hook)
10298 (if (and arg (not (member state org-done-keywords)))
10299 (setq head (org-get-todo-sequence-head state)))
10300 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10301 ;; Do we need to trigger a repeat?
10302 (when now-done-p
10303 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10304 ;; This is for the agenda, take a snapshot of the headline.
10305 (save-match-data
10306 (setq org-agenda-headline-snapshot-before-repeat
10307 (org-get-heading))))
10308 (org-auto-repeat-maybe state))
10309 ;; Fixup cursor location if close to the keyword
10310 (if (and (outline-on-heading-p)
10311 (not (bolp))
10312 (save-excursion (beginning-of-line 1)
10313 (looking-at org-todo-line-regexp))
10314 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10315 (progn
10316 (goto-char (or (match-end 2) (match-end 1)))
10317 (and (looking-at " ") (just-one-space))))
10318 (when org-trigger-hook
10319 (save-excursion
10320 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10322 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10323 "Block turning an entry into a TODO, using the hierarchy.
10324 This checks whether the current task should be blocked from state
10325 changes. Such blocking occurs when:
10327 1. The task has children which are not all in a completed state.
10329 2. A task has a parent with the property :ORDERED:, and there
10330 are siblings prior to the current task with incomplete
10331 status.
10333 3. The parent of the task is blocked because it has siblings that should
10334 be done first, or is child of a block grandparent TODO entry."
10336 (if (not org-enforce-todo-dependencies)
10337 t ; if locally turned off don't block
10338 (catch 'dont-block
10339 ;; If this is not a todo state change, or if this entry is already DONE,
10340 ;; do not block
10341 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10342 (member (plist-get change-plist :from)
10343 (cons 'done org-done-keywords))
10344 (member (plist-get change-plist :to)
10345 (cons 'todo org-not-done-keywords))
10346 (not (plist-get change-plist :to)))
10347 (throw 'dont-block t))
10348 ;; If this task has children, and any are undone, it's blocked
10349 (save-excursion
10350 (org-back-to-heading t)
10351 (let ((this-level (funcall outline-level)))
10352 (outline-next-heading)
10353 (let ((child-level (funcall outline-level)))
10354 (while (and (not (eobp))
10355 (> child-level this-level))
10356 ;; this todo has children, check whether they are all
10357 ;; completed
10358 (if (and (not (org-entry-is-done-p))
10359 (org-entry-is-todo-p))
10360 (throw 'dont-block nil))
10361 (outline-next-heading)
10362 (setq child-level (funcall outline-level))))))
10363 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10364 ;; any previous siblings are undone, it's blocked
10365 (save-excursion
10366 (org-back-to-heading t)
10367 (let* ((pos (point))
10368 (parent-pos (and (org-up-heading-safe) (point))))
10369 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10370 (when (and (org-entry-get (point) "ORDERED")
10371 (forward-line 1)
10372 (re-search-forward org-not-done-heading-regexp pos t))
10373 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10374 ;; Search further up the hierarchy, to see if an anchestor is blocked
10375 (while t
10376 (goto-char parent-pos)
10377 (if (not (looking-at org-not-done-heading-regexp))
10378 (throw 'dont-block t)) ; do not block, parent is not a TODO
10379 (setq pos (point))
10380 (setq parent-pos (and (org-up-heading-safe) (point)))
10381 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10382 (when (and (org-entry-get (point) "ORDERED")
10383 (forward-line 1)
10384 (re-search-forward org-not-done-heading-regexp pos t))
10385 (throw 'dont-block nil)))))))) ; block, older sibling not done.
10387 (defcustom org-track-ordered-property-with-tag nil
10388 "Should the ORDERED property also be shown as a tag?
10389 The ORDERED property decides if an entry should require subtasks to be
10390 completed in sequence. Since a property is not very visible, setting
10391 this option means that toggling the ORDERED property with the command
10392 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10393 not relevant for the behavior, but it makes things more visible.
10395 Note that toggling the tag with tags commands will not change the property
10396 and therefore not influence behavior!
10398 This can be t, meaning the tag ORDERED should be used, It can also be a
10399 string to select a different tag for this task."
10400 :group 'org-todo
10401 :type '(choice
10402 (const :tag "No tracking" nil)
10403 (const :tag "Track with ORDERED tag" t)
10404 (string :tag "Use other tag")))
10406 (defun org-toggle-ordered-property ()
10407 "Toggle the ORDERED property of the current entry.
10408 For better visibility, you can track the value of this property with a tag.
10409 See variable `org-track-ordered-property-with-tag'."
10410 (interactive)
10411 (let* ((t1 org-track-ordered-property-with-tag)
10412 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10413 (save-excursion
10414 (org-back-to-heading)
10415 (if (org-entry-get nil "ORDERED")
10416 (progn
10417 (org-delete-property "ORDERED")
10418 (and tag (org-toggle-tag tag 'off))
10419 (message "Subtasks can be completed in arbitrary order"))
10420 (org-entry-put nil "ORDERED" "t")
10421 (and tag (org-toggle-tag tag 'on))
10422 (message "Subtasks must be completed in sequence")))))
10424 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10425 (defun org-block-todo-from-checkboxes (change-plist)
10426 "Block turning an entry into a TODO, using checkboxes.
10427 This checks whether the current task should be blocked from state
10428 changes because there are unchecked boxes in this entry."
10429 (if (not org-enforce-todo-checkbox-dependencies)
10430 t ; if locally turned off don't block
10431 (catch 'dont-block
10432 ;; If this is not a todo state change, or if this entry is already DONE,
10433 ;; do not block
10434 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10435 (member (plist-get change-plist :from)
10436 (cons 'done org-done-keywords))
10437 (member (plist-get change-plist :to)
10438 (cons 'todo org-not-done-keywords))
10439 (not (plist-get change-plist :to)))
10440 (throw 'dont-block t))
10441 ;; If this task has checkboxes that are not checked, it's blocked
10442 (save-excursion
10443 (org-back-to-heading t)
10444 (let ((beg (point)) end)
10445 (outline-next-heading)
10446 (setq end (point))
10447 (goto-char beg)
10448 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10449 end t)
10450 (progn
10451 (if (boundp 'org-blocked-by-checkboxes)
10452 (setq org-blocked-by-checkboxes t))
10453 (throw 'dont-block nil)))))
10454 t))) ; do not block
10456 (defun org-entry-blocked-p ()
10457 "Is the current entry blocked?"
10458 (if (org-entry-get nil "NOBLOCKING")
10459 nil ;; Never block this entry
10460 (not
10461 (run-hook-with-args-until-failure
10462 'org-blocker-hook
10463 (list :type 'todo-state-change
10464 :position (point)
10465 :from 'todo
10466 :to 'done)))))
10468 (defun org-update-statistics-cookies (all)
10469 "Update the statistics cookie, either from TODO or from checkboxes.
10470 This should be called with the cursor in a line with a statistics cookie."
10471 (interactive "P")
10472 (if all
10473 (progn
10474 (org-update-checkbox-count 'all)
10475 (org-map-entries 'org-update-parent-todo-statistics))
10476 (if (not (org-on-heading-p))
10477 (org-update-checkbox-count)
10478 (let ((pos (move-marker (make-marker) (point)))
10479 end l1 l2)
10480 (ignore-errors (org-back-to-heading t))
10481 (if (not (org-on-heading-p))
10482 (org-update-checkbox-count)
10483 (setq l1 (org-outline-level))
10484 (setq end (save-excursion
10485 (outline-next-heading)
10486 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10487 (point)))
10488 (if (and (save-excursion
10489 (re-search-forward
10490 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
10491 (not (save-excursion (re-search-forward
10492 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10493 (org-update-checkbox-count)
10494 (if (and l2 (> l2 l1))
10495 (progn
10496 (goto-char end)
10497 (org-update-parent-todo-statistics))
10498 (goto-char pos)
10499 (beginning-of-line 1)
10500 (while (re-search-forward
10501 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
10502 (point-at-eol) t)
10503 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
10504 (goto-char pos)
10505 (move-marker pos nil)))))
10507 (defvar org-entry-property-inherited-from) ;; defined below
10508 (defun org-update-parent-todo-statistics ()
10509 "Update any statistics cookie in the parent of the current headline.
10510 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10511 the entire subtree and this will travel up the hierarchy and update
10512 statistics everywhere."
10513 (interactive)
10514 (let* ((lim 0) prop
10515 (recursive (or (not org-hierarchical-todo-statistics)
10516 (string-match
10517 "\\<recursive\\>"
10518 (or (setq prop (org-entry-get
10519 nil "COOKIE_DATA" 'inherit)) ""))))
10520 (lim (or (and prop (marker-position
10521 org-entry-property-inherited-from))
10522 lim))
10523 (first t)
10524 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10525 level ltoggle l1 new ndel
10526 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10527 (catch 'exit
10528 (save-excursion
10529 (beginning-of-line 1)
10530 (if (org-at-heading-p)
10531 (setq ltoggle (funcall outline-level))
10532 (error "This should not happen"))
10533 (while (and (setq level (org-up-heading-safe))
10534 (or recursive first)
10535 (>= (point) lim))
10536 (setq first nil cookie-present nil)
10537 (unless (and level
10538 (not (string-match
10539 "\\<checkbox\\>"
10540 (downcase
10541 (or (org-entry-get
10542 nil "COOKIE_DATA")
10543 "")))))
10544 (throw 'exit nil))
10545 (while (re-search-forward box-re (point-at-eol) t)
10546 (setq cnt-all 0 cnt-done 0 cookie-present t)
10547 (setq is-percent (match-end 2))
10548 (save-match-data
10549 (unless (outline-next-heading) (throw 'exit nil))
10550 (while (and (looking-at org-complex-heading-regexp)
10551 (> (setq l1 (length (match-string 1))) level))
10552 (setq kwd (and (or recursive (= l1 ltoggle))
10553 (match-string 2)))
10554 (if (or (eq org-provide-todo-statistics 'all-headlines)
10555 (and (listp org-provide-todo-statistics)
10556 (or (member kwd org-provide-todo-statistics)
10557 (member kwd org-done-keywords))))
10558 (setq cnt-all (1+ cnt-all))
10559 (if (eq org-provide-todo-statistics t)
10560 (and kwd (setq cnt-all (1+ cnt-all)))))
10561 (and (member kwd org-done-keywords)
10562 (setq cnt-done (1+ cnt-done)))
10563 (outline-next-heading)))
10564 (setq new
10565 (if is-percent
10566 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10567 (format "[%d/%d]" cnt-done cnt-all))
10568 ndel (- (match-end 0) (match-beginning 0)))
10569 (goto-char (match-beginning 0))
10570 (insert new)
10571 (delete-region (point) (+ (point) ndel)))
10572 (when cookie-present
10573 (run-hook-with-args 'org-after-todo-statistics-hook
10574 cnt-done (- cnt-all cnt-done))))))
10575 (run-hooks 'org-todo-statistics-hook)))
10577 (defvar org-after-todo-statistics-hook nil
10578 "Hook that is called after a TODO statistics cookie has been updated.
10579 Each function is called with two arguments: the number of not-done entries
10580 and the number of done entries.
10582 For example, the following function, when added to this hook, will switch
10583 an entry to DONE when all children are done, and back to TODO when new
10584 entries are set to a TODO status. Note that this hook is only called
10585 when there is a statistics cookie in the headline!
10587 (defun org-summary-todo (n-done n-not-done)
10588 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10589 (let (org-log-done org-log-states) ; turn off logging
10590 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10593 (defvar org-todo-statistics-hook nil
10594 "Hook that is run whenever Org thinks TODO statistics should be updated.
10595 This hook runs even if there is no statistics cookie present, in which case
10596 `org-after-todo-statistics-hook' would not run.")
10598 (defun org-todo-trigger-tag-changes (state)
10599 "Apply the changes defined in `org-todo-state-tags-triggers'."
10600 (let ((l org-todo-state-tags-triggers)
10601 changes)
10602 (when (or (not state) (equal state ""))
10603 (setq changes (append changes (cdr (assoc "" l)))))
10604 (when (and (stringp state) (> (length state) 0))
10605 (setq changes (append changes (cdr (assoc state l)))))
10606 (when (member state org-not-done-keywords)
10607 (setq changes (append changes (cdr (assoc 'todo l)))))
10608 (when (member state org-done-keywords)
10609 (setq changes (append changes (cdr (assoc 'done l)))))
10610 (dolist (c changes)
10611 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10613 (defun org-local-logging (value)
10614 "Get logging settings from a property VALUE."
10615 (let* (words w a)
10616 ;; directly set the variables, they are already local.
10617 (setq org-log-done nil
10618 org-log-repeat nil
10619 org-todo-log-states nil)
10620 (setq words (org-split-string value))
10621 (while (setq w (pop words))
10622 (cond
10623 ((setq a (assoc w org-startup-options))
10624 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10625 (set (nth 1 a) (nth 2 a))))
10626 ((setq a (org-extract-log-state-settings w))
10627 (and (member (car a) org-todo-keywords-1)
10628 (push a org-todo-log-states)))))))
10630 (defun org-get-todo-sequence-head (kwd)
10631 "Return the head of the TODO sequence to which KWD belongs.
10632 If KWD is not set, check if there is a text property remembering the
10633 right sequence."
10634 (let (p)
10635 (cond
10636 ((not kwd)
10637 (or (get-text-property (point-at-bol) 'org-todo-head)
10638 (progn
10639 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10640 nil (point-at-eol)))
10641 (get-text-property p 'org-todo-head))))
10642 ((not (member kwd org-todo-keywords-1))
10643 (car org-todo-keywords-1))
10644 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10646 (defun org-fast-todo-selection ()
10647 "Fast TODO keyword selection with single keys.
10648 Returns the new TODO keyword, or nil if no state change should occur."
10649 (let* ((fulltable org-todo-key-alist)
10650 (done-keywords org-done-keywords) ;; needed for the faces.
10651 (maxlen (apply 'max (mapcar
10652 (lambda (x)
10653 (if (stringp (car x)) (string-width (car x)) 0))
10654 fulltable)))
10655 (expert nil)
10656 (fwidth (+ maxlen 3 1 3))
10657 (ncol (/ (- (window-width) 4) fwidth))
10658 tg cnt e c tbl
10659 groups ingroup)
10660 (save-excursion
10661 (save-window-excursion
10662 (if expert
10663 (set-buffer (get-buffer-create " *Org todo*"))
10664 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10665 (erase-buffer)
10666 (org-set-local 'org-done-keywords done-keywords)
10667 (setq tbl fulltable cnt 0)
10668 (while (setq e (pop tbl))
10669 (cond
10670 ((equal e '(:startgroup))
10671 (push '() groups) (setq ingroup t)
10672 (when (not (= cnt 0))
10673 (setq cnt 0)
10674 (insert "\n"))
10675 (insert "{ "))
10676 ((equal e '(:endgroup))
10677 (setq ingroup nil cnt 0)
10678 (insert "}\n"))
10679 ((equal e '(:newline))
10680 (when (not (= cnt 0))
10681 (setq cnt 0)
10682 (insert "\n")
10683 (setq e (car tbl))
10684 (while (equal (car tbl) '(:newline))
10685 (insert "\n")
10686 (setq tbl (cdr tbl)))))
10688 (setq tg (car e) c (cdr e))
10689 (if ingroup (push tg (car groups)))
10690 (setq tg (org-add-props tg nil 'face
10691 (org-get-todo-face tg)))
10692 (if (and (= cnt 0) (not ingroup)) (insert " "))
10693 (insert "[" c "] " tg (make-string
10694 (- fwidth 4 (length tg)) ?\ ))
10695 (when (= (setq cnt (1+ cnt)) ncol)
10696 (insert "\n")
10697 (if ingroup (insert " "))
10698 (setq cnt 0)))))
10699 (insert "\n")
10700 (goto-char (point-min))
10701 (if (not expert) (org-fit-window-to-buffer))
10702 (message "[a-z..]:Set [SPC]:clear")
10703 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10704 (cond
10705 ((or (= c ?\C-g)
10706 (and (= c ?q) (not (rassoc c fulltable))))
10707 (setq quit-flag t))
10708 ((= c ?\ ) nil)
10709 ((setq e (rassoc c fulltable) tg (car e))
10711 (t (setq quit-flag t)))))))
10713 (defun org-entry-is-todo-p ()
10714 (member (org-get-todo-state) org-not-done-keywords))
10716 (defun org-entry-is-done-p ()
10717 (member (org-get-todo-state) org-done-keywords))
10719 (defun org-get-todo-state ()
10720 (save-excursion
10721 (org-back-to-heading t)
10722 (and (looking-at org-todo-line-regexp)
10723 (match-end 2)
10724 (match-string 2))))
10726 (defun org-at-date-range-p (&optional inactive-ok)
10727 "Is the cursor inside a date range?"
10728 (interactive)
10729 (save-excursion
10730 (catch 'exit
10731 (let ((pos (point)))
10732 (skip-chars-backward "^[<\r\n")
10733 (skip-chars-backward "<[")
10734 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10735 (>= (match-end 0) pos)
10736 (throw 'exit t))
10737 (skip-chars-backward "^<[\r\n")
10738 (skip-chars-backward "<[")
10739 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10740 (>= (match-end 0) pos)
10741 (throw 'exit t)))
10742 nil)))
10744 (defun org-get-repeat (&optional tagline)
10745 "Check if there is a deadline/schedule with repeater in this entry."
10746 (save-match-data
10747 (save-excursion
10748 (org-back-to-heading t)
10749 (and (re-search-forward (if tagline
10750 (concat tagline "\\s-*" org-repeat-re)
10751 org-repeat-re)
10752 (org-entry-end-position) t)
10753 (match-string-no-properties 1)))))
10755 (defvar org-last-changed-timestamp)
10756 (defvar org-last-inserted-timestamp)
10757 (defvar org-log-post-message)
10758 (defvar org-log-note-purpose)
10759 (defvar org-log-note-how)
10760 (defvar org-log-note-extra)
10761 (defun org-auto-repeat-maybe (done-word)
10762 "Check if the current headline contains a repeated deadline/schedule.
10763 If yes, set TODO state back to what it was and change the base date
10764 of repeating deadline/scheduled time stamps to new date.
10765 This function is run automatically after each state change to a DONE state."
10766 ;; last-state is dynamically scoped into this function
10767 (let* ((repeat (org-get-repeat))
10768 (aa (assoc last-state org-todo-kwd-alist))
10769 (interpret (nth 1 aa))
10770 (head (nth 2 aa))
10771 (whata '(("d" . day) ("m" . month) ("y" . year)))
10772 (msg "Entry repeats: ")
10773 (org-log-done nil)
10774 (org-todo-log-states nil)
10775 (nshiftmax 10) (nshift 0)
10776 re type n what ts time)
10777 (when repeat
10778 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10779 (org-todo (if (eq interpret 'type) last-state head))
10780 (org-entry-put nil "LAST_REPEAT" (format-time-string
10781 (org-time-stamp-format t t)))
10782 (when org-log-repeat
10783 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10784 (memq 'org-add-log-note post-command-hook))
10785 ;; OK, we are already setup for some record
10786 (if (eq org-log-repeat 'note)
10787 ;; make sure we take a note, not only a time stamp
10788 (setq org-log-note-how 'note))
10789 ;; Set up for taking a record
10790 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10791 last-state
10792 'findpos org-log-repeat)))
10793 (org-back-to-heading t)
10794 (org-add-planning-info nil nil 'closed)
10795 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10796 org-deadline-time-regexp "\\)\\|\\("
10797 org-ts-regexp "\\)"))
10798 (while (re-search-forward
10799 re (save-excursion (outline-next-heading) (point)) t)
10800 (setq type (if (match-end 1) org-scheduled-string
10801 (if (match-end 3) org-deadline-string "Plain:"))
10802 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10803 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10804 (setq n (string-to-number (match-string 2 ts))
10805 what (match-string 3 ts))
10806 (if (equal what "w") (setq n (* n 7) what "d"))
10807 ;; Preparation, see if we need to modify the start date for the change
10808 (when (match-end 1)
10809 (setq time (save-match-data (org-time-string-to-time ts)))
10810 (cond
10811 ((equal (match-string 1 ts) ".")
10812 ;; Shift starting date to today
10813 (org-timestamp-change
10814 (- (time-to-days (current-time)) (time-to-days time))
10815 'day))
10816 ((equal (match-string 1 ts) "+")
10817 (while (or (= nshift 0)
10818 (<= (time-to-days time) (time-to-days (current-time))))
10819 (when (= (incf nshift) nshiftmax)
10820 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10821 (error "Abort")))
10822 (org-timestamp-change n (cdr (assoc what whata)))
10823 (org-at-timestamp-p t)
10824 (setq ts (match-string 1))
10825 (setq time (save-match-data (org-time-string-to-time ts))))
10826 (org-timestamp-change (- n) (cdr (assoc what whata)))
10827 ;; rematch, so that we have everything in place for the real shift
10828 (org-at-timestamp-p t)
10829 (setq ts (match-string 1))
10830 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10831 (org-timestamp-change n (cdr (assoc what whata)))
10832 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10833 (setq org-log-post-message msg)
10834 (message "%s" msg))))
10836 (defun org-show-todo-tree (arg)
10837 "Make a compact tree which shows all headlines marked with TODO.
10838 The tree will show the lines where the regexp matches, and all higher
10839 headlines above the match.
10840 With a \\[universal-argument] prefix, prompt for a regexp to match.
10841 With a numeric prefix N, construct a sparse tree for the Nth element
10842 of `org-todo-keywords-1'."
10843 (interactive "P")
10844 (let ((case-fold-search nil)
10845 (kwd-re
10846 (cond ((null arg) org-not-done-regexp)
10847 ((equal arg '(4))
10848 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10849 (mapcar 'list org-todo-keywords-1))))
10850 (concat "\\("
10851 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10852 "\\)\\>")))
10853 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10854 (regexp-quote (nth (1- (prefix-numeric-value arg))
10855 org-todo-keywords-1)))
10856 (t (error "Invalid prefix argument: %s" arg)))))
10857 (message "%d TODO entries found"
10858 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10860 (defun org-deadline (&optional remove time)
10861 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10862 With argument REMOVE, remove any deadline from the item.
10863 When TIME is set, it should be an internal time specification, and the
10864 scheduling will use the corresponding date."
10865 (interactive "P")
10866 (let* ((old-date (org-entry-get nil "DEADLINE"))
10867 (repeater (and old-date
10868 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
10869 (match-string 1 old-date))))
10870 (if remove
10871 (progn
10872 (when (and old-date org-log-redeadline)
10873 (org-add-log-setup 'deldeadline nil old-date 'findpos
10874 org-log-redeadline))
10875 (org-remove-timestamp-with-keyword org-deadline-string)
10876 (message "Item no longer has a deadline."))
10877 (org-add-planning-info 'deadline time 'closed)
10878 (when (and old-date org-log-redeadline
10879 (not (equal old-date
10880 (substring org-last-inserted-timestamp 1 -1))))
10881 (org-add-log-setup 'redeadline nil old-date 'findpos
10882 org-log-redeadline))
10883 (when repeater
10884 (save-excursion
10885 (org-back-to-heading t)
10886 (when (re-search-forward (concat org-deadline-string " "
10887 org-last-inserted-timestamp)
10888 (save-excursion
10889 (outline-next-heading) (point)) t)
10890 (goto-char (1- (match-end 0)))
10891 (insert " " repeater)
10892 (setq org-last-inserted-timestamp
10893 (concat (substring org-last-inserted-timestamp 0 -1)
10894 " " repeater
10895 (substring org-last-inserted-timestamp -1))))))
10896 (message "Deadline on %s" org-last-inserted-timestamp))))
10898 (defun org-schedule (&optional remove time)
10899 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10900 With argument REMOVE, remove any scheduling date from the item.
10901 When TIME is set, it should be an internal time specification, and the
10902 scheduling will use the corresponding date."
10903 (interactive "P")
10904 (let* ((old-date (org-entry-get nil "SCHEDULED"))
10905 (repeater (and old-date
10906 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
10907 (match-string 1 old-date))))
10908 (if remove
10909 (progn
10910 (when (and old-date org-log-reschedule)
10911 (org-add-log-setup 'delschedule nil old-date 'findpos
10912 org-log-reschedule))
10913 (org-remove-timestamp-with-keyword org-scheduled-string)
10914 (message "Item is no longer scheduled."))
10915 (org-add-planning-info 'scheduled time 'closed)
10916 (when (and old-date org-log-reschedule
10917 (not (equal old-date
10918 (substring org-last-inserted-timestamp 1 -1))))
10919 (org-add-log-setup 'reschedule nil old-date 'findpos
10920 org-log-reschedule))
10921 (when repeater
10922 (save-excursion
10923 (org-back-to-heading t)
10924 (when (re-search-forward (concat org-scheduled-string " "
10925 org-last-inserted-timestamp)
10926 (save-excursion
10927 (outline-next-heading) (point)) t)
10928 (goto-char (1- (match-end 0)))
10929 (insert " " repeater)
10930 (setq org-last-inserted-timestamp
10931 (concat (substring org-last-inserted-timestamp 0 -1)
10932 " " repeater
10933 (substring org-last-inserted-timestamp -1))))))
10934 (message "Scheduled to %s" org-last-inserted-timestamp))))
10936 (defun org-get-scheduled-time (pom &optional inherit)
10937 "Get the scheduled time as a time tuple, of a format suitable
10938 for calling org-schedule with, or if there is no scheduling,
10939 returns nil."
10940 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10941 (when time
10942 (apply 'encode-time (org-parse-time-string time)))))
10944 (defun org-get-deadline-time (pom &optional inherit)
10945 "Get the deadine as a time tuple, of a format suitable for
10946 calling org-deadline with, or if there is no scheduling, returns
10947 nil."
10948 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10949 (when time
10950 (apply 'encode-time (org-parse-time-string time)))))
10952 (defun org-remove-timestamp-with-keyword (keyword)
10953 "Remove all time stamps with KEYWORD in the current entry."
10954 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10955 beg)
10956 (save-excursion
10957 (org-back-to-heading t)
10958 (setq beg (point))
10959 (outline-next-heading)
10960 (while (re-search-backward re beg t)
10961 (replace-match "")
10962 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10963 (equal (char-before) ?\ ))
10964 (backward-delete-char 1)
10965 (if (string-match "^[ \t]*$" (buffer-substring
10966 (point-at-bol) (point-at-eol)))
10967 (delete-region (point-at-bol)
10968 (min (point-max) (1+ (point-at-eol))))))))))
10970 (defun org-add-planning-info (what &optional time &rest remove)
10971 "Insert new timestamp with keyword in the line directly after the headline.
10972 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10973 If non is given, the user is prompted for a date.
10974 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10975 be removed."
10976 (interactive)
10977 (let (org-time-was-given org-end-time-was-given ts
10978 end default-time default-input)
10980 (catch 'exit
10981 (when (and (not time) (memq what '(scheduled deadline)))
10982 ;; Try to get a default date/time from existing timestamp
10983 (save-excursion
10984 (org-back-to-heading t)
10985 (setq end (save-excursion (outline-next-heading) (point)))
10986 (when (re-search-forward (if (eq what 'scheduled)
10987 org-scheduled-time-regexp
10988 org-deadline-time-regexp)
10989 end t)
10990 (setq ts (match-string 1)
10991 default-time
10992 (apply 'encode-time (org-parse-time-string ts))
10993 default-input (and ts (org-get-compact-tod ts))))))
10994 (when what
10995 ;; If necessary, get the time from the user
10996 (setq time (or time (org-read-date nil 'to-time nil nil
10997 default-time default-input))))
10999 (when (and org-insert-labeled-timestamps-at-point
11000 (member what '(scheduled deadline)))
11001 (insert
11002 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11003 (org-insert-time-stamp time org-time-was-given
11004 nil nil nil (list org-end-time-was-given))
11005 (setq what nil))
11006 (save-excursion
11007 (save-restriction
11008 (let (col list elt ts buffer-invisibility-spec)
11009 (org-back-to-heading t)
11010 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11011 (goto-char (match-end 1))
11012 (setq col (current-column))
11013 (goto-char (match-end 0))
11014 (if (eobp) (insert "\n") (forward-char 1))
11015 (when (and (not what)
11016 (not (looking-at
11017 (concat "[ \t]*"
11018 org-keyword-time-not-clock-regexp))))
11019 ;; Nothing to add, nothing to remove...... :-)
11020 (throw 'exit nil))
11021 (if (and (not (looking-at outline-regexp))
11022 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11023 "[^\r\n]*"))
11024 (not (equal (match-string 1) org-clock-string)))
11025 (narrow-to-region (match-beginning 0) (match-end 0))
11026 (insert-before-markers "\n")
11027 (backward-char 1)
11028 (narrow-to-region (point) (point))
11029 (and org-adapt-indentation (org-indent-to-column col)))
11030 ;; Check if we have to remove something.
11031 (setq list (cons what remove))
11032 (while list
11033 (setq elt (pop list))
11034 (goto-char (point-min))
11035 (when (or (and (eq elt 'scheduled)
11036 (re-search-forward org-scheduled-time-regexp nil t))
11037 (and (eq elt 'deadline)
11038 (re-search-forward org-deadline-time-regexp nil t))
11039 (and (eq elt 'closed)
11040 (re-search-forward org-closed-time-regexp nil t)))
11041 (replace-match "")
11042 (if (looking-at "--+<[^>]+>") (replace-match ""))
11043 (skip-chars-backward " ")
11044 (if (looking-at " +") (replace-match ""))))
11045 (goto-char (point-max))
11046 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11047 (when what
11048 (insert
11049 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11050 (cond ((eq what 'scheduled) org-scheduled-string)
11051 ((eq what 'deadline) org-deadline-string)
11052 ((eq what 'closed) org-closed-string))
11053 " ")
11054 (setq ts (org-insert-time-stamp
11055 time
11056 (or org-time-was-given
11057 (and (eq what 'closed) org-log-done-with-time))
11058 (eq what 'closed)
11059 nil nil (list org-end-time-was-given)))
11060 (end-of-line 1))
11061 (goto-char (point-min))
11062 (widen)
11063 (if (and (looking-at "[ \t]+\n")
11064 (equal (char-before) ?\n))
11065 (delete-region (1- (point)) (point-at-eol)))
11066 ts))))))
11068 (defvar org-log-note-marker (make-marker))
11069 (defvar org-log-note-purpose nil)
11070 (defvar org-log-note-state nil)
11071 (defvar org-log-note-previous-state nil)
11072 (defvar org-log-note-how nil)
11073 (defvar org-log-note-extra nil)
11074 (defvar org-log-note-window-configuration nil)
11075 (defvar org-log-note-return-to (make-marker))
11076 (defvar org-log-post-message nil
11077 "Message to be displayed after a log note has been stored.
11078 The auto-repeater uses this.")
11080 (defun org-add-note ()
11081 "Add a note to the current entry.
11082 This is done in the same way as adding a state change note."
11083 (interactive)
11084 (org-add-log-setup 'note nil nil 'findpos nil))
11086 (defvar org-property-end-re)
11087 (defun org-add-log-setup (&optional purpose state prev-state
11088 findpos how &optional extra)
11089 "Set up the post command hook to take a note.
11090 If this is about to TODO state change, the new state is expected in STATE.
11091 When FINDPOS is non-nil, find the correct position for the note in
11092 the current entry. If not, assume that it can be inserted at point.
11093 HOW is an indicator what kind of note should be created.
11094 EXTRA is additional text that will be inserted into the notes buffer."
11095 (let* ((org-log-into-drawer (org-log-into-drawer))
11096 (drawer (cond ((stringp org-log-into-drawer)
11097 org-log-into-drawer)
11098 (org-log-into-drawer "LOGBOOK")
11099 (t nil))))
11100 (save-restriction
11101 (save-excursion
11102 (when findpos
11103 (org-back-to-heading t)
11104 (narrow-to-region (point) (save-excursion
11105 (outline-next-heading) (point)))
11106 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11107 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11108 "[^\r\n]*\\)?"))
11109 (goto-char (match-end 0))
11110 (cond
11111 (drawer
11112 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11113 nil t)
11114 (progn
11115 (goto-char (match-end 0))
11116 (or org-log-states-order-reversed
11117 (and (re-search-forward org-property-end-re nil t)
11118 (goto-char (1- (match-beginning 0))))))
11119 (insert "\n:" drawer ":\n:END:")
11120 (beginning-of-line 0)
11121 (org-indent-line-function)
11122 (beginning-of-line 2)
11123 (org-indent-line-function)
11124 (end-of-line 0)))
11125 ((and org-log-state-notes-insert-after-drawers
11126 (save-excursion
11127 (forward-line) (looking-at org-drawer-regexp)))
11128 (forward-line)
11129 (while (looking-at org-drawer-regexp)
11130 (goto-char (match-end 0))
11131 (re-search-forward org-property-end-re (point-max) t)
11132 (forward-line))
11133 (forward-line -1)))
11134 (unless org-log-states-order-reversed
11135 (and (= (char-after) ?\n) (forward-char 1))
11136 (org-skip-over-state-notes)
11137 (skip-chars-backward " \t\n\r")))
11138 (move-marker org-log-note-marker (point))
11139 (setq org-log-note-purpose purpose
11140 org-log-note-state state
11141 org-log-note-previous-state prev-state
11142 org-log-note-how how
11143 org-log-note-extra extra)
11144 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11146 (defun org-skip-over-state-notes ()
11147 "Skip past the list of State notes in an entry."
11148 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11149 (while (looking-at "[ \t]*- State")
11150 (condition-case nil
11151 (org-next-item)
11152 (error (org-end-of-item)))))
11154 (defun org-add-log-note (&optional purpose)
11155 "Pop up a window for taking a note, and add this note later at point."
11156 (remove-hook 'post-command-hook 'org-add-log-note)
11157 (setq org-log-note-window-configuration (current-window-configuration))
11158 (delete-other-windows)
11159 (move-marker org-log-note-return-to (point))
11160 (switch-to-buffer (marker-buffer org-log-note-marker))
11161 (goto-char org-log-note-marker)
11162 (org-switch-to-buffer-other-window "*Org Note*")
11163 (erase-buffer)
11164 (if (memq org-log-note-how '(time state))
11165 (let (current-prefix-arg) (org-store-log-note))
11166 (let ((org-inhibit-startup t)) (org-mode))
11167 (insert (format "# Insert note for %s.
11168 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11169 (cond
11170 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11171 ((eq org-log-note-purpose 'done) "closed todo item")
11172 ((eq org-log-note-purpose 'state)
11173 (format "state change from \"%s\" to \"%s\""
11174 (or org-log-note-previous-state "")
11175 (or org-log-note-state "")))
11176 ((eq org-log-note-purpose 'reschedule)
11177 "rescheduling")
11178 ((eq org-log-note-purpose 'delschedule)
11179 "no longer scheduled")
11180 ((eq org-log-note-purpose 'redeadline)
11181 "changing deadline")
11182 ((eq org-log-note-purpose 'deldeadline)
11183 "removing deadline")
11184 ((eq org-log-note-purpose 'refile)
11185 "refiling")
11186 ((eq org-log-note-purpose 'note)
11187 "this entry")
11188 (t (error "This should not happen")))))
11189 (if org-log-note-extra (insert org-log-note-extra))
11190 (org-set-local 'org-finish-function 'org-store-log-note)))
11192 (defvar org-note-abort nil) ; dynamically scoped
11193 (defun org-store-log-note ()
11194 "Finish taking a log note, and insert it to where it belongs."
11195 (let ((txt (buffer-string))
11196 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11197 lines ind)
11198 (kill-buffer (current-buffer))
11199 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11200 (setq txt (replace-match "" t t txt)))
11201 (if (string-match "\\s-+\\'" txt)
11202 (setq txt (replace-match "" t t txt)))
11203 (setq lines (org-split-string txt "\n"))
11204 (when (and note (string-match "\\S-" note))
11205 (setq note
11206 (org-replace-escapes
11207 note
11208 (list (cons "%u" (user-login-name))
11209 (cons "%U" user-full-name)
11210 (cons "%t" (format-time-string
11211 (org-time-stamp-format 'long 'inactive)
11212 (current-time)))
11213 (cons "%s" (if org-log-note-state
11214 (concat "\"" org-log-note-state "\"")
11215 ""))
11216 (cons "%S" (if org-log-note-previous-state
11217 (concat "\"" org-log-note-previous-state "\"")
11218 "\"\"")))))
11219 (if lines (setq note (concat note " \\\\")))
11220 (push note lines))
11221 (when (or current-prefix-arg org-note-abort)
11222 (when org-log-into-drawer
11223 (org-remove-empty-drawer-at
11224 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11225 org-log-note-marker))
11226 (setq lines nil))
11227 (when lines
11228 (with-current-buffer (marker-buffer org-log-note-marker)
11229 (save-excursion
11230 (goto-char org-log-note-marker)
11231 (move-marker org-log-note-marker nil)
11232 (end-of-line 1)
11233 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11234 (insert "- " (pop lines))
11235 (org-indent-line-function)
11236 (beginning-of-line 1)
11237 (looking-at "[ \t]*")
11238 (setq ind (concat (match-string 0) " "))
11239 (end-of-line 1)
11240 (while lines (insert "\n" ind (pop lines)))
11241 (message "Note stored")
11242 (org-back-to-heading t)
11243 (org-cycle-hide-drawers 'children)))))
11244 (set-window-configuration org-log-note-window-configuration)
11245 (with-current-buffer (marker-buffer org-log-note-return-to)
11246 (goto-char org-log-note-return-to))
11247 (move-marker org-log-note-return-to nil)
11248 (and org-log-post-message (message "%s" org-log-post-message)))
11250 (defun org-remove-empty-drawer-at (drawer pos)
11251 "Remove an empty drawer DRAWER at position POS.
11252 POS may also be a marker."
11253 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11254 (save-excursion
11255 (save-restriction
11256 (widen)
11257 (goto-char pos)
11258 (if (org-in-regexp
11259 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11260 (replace-match ""))))))
11262 (defun org-sparse-tree (&optional arg)
11263 "Create a sparse tree, prompt for the details.
11264 This command can create sparse trees. You first need to select the type
11265 of match used to create the tree:
11267 t Show entries with a specific TODO keyword.
11268 m Show entries selected by a tags/property match.
11269 p Enter a property name and its value (both with completion on existing
11270 names/values) and show entries with that property.
11271 / Show entries matching a regular expression (`r' can be used as well)
11272 d Show deadlines due within `org-deadline-warning-days'.
11273 b Show deadlines and scheduled items before a date.
11274 a Show deadlines and scheduled items after a date."
11275 (interactive "P")
11276 (let (ans kwd value)
11277 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
11278 (setq ans (read-char-exclusive))
11279 (cond
11280 ((equal ans ?d)
11281 (call-interactively 'org-check-deadlines))
11282 ((equal ans ?b)
11283 (call-interactively 'org-check-before-date))
11284 ((equal ans ?a)
11285 (call-interactively 'org-check-after-date))
11286 ((equal ans ?t)
11287 (org-show-todo-tree '(4)))
11288 ((member ans '(?T ?m))
11289 (call-interactively 'org-match-sparse-tree))
11290 ((member ans '(?p ?P))
11291 (setq kwd (org-icompleting-read "Property: "
11292 (mapcar 'list (org-buffer-property-keys))))
11293 (setq value (org-icompleting-read "Value: "
11294 (mapcar 'list (org-property-values kwd))))
11295 (unless (string-match "\\`{.*}\\'" value)
11296 (setq value (concat "\"" value "\"")))
11297 (org-match-sparse-tree arg (concat kwd "=" value)))
11298 ((member ans '(?r ?R ?/))
11299 (call-interactively 'org-occur))
11300 (t (error "No such sparse tree command \"%c\"" ans)))))
11302 (defvar org-occur-highlights nil
11303 "List of overlays used for occur matches.")
11304 (make-variable-buffer-local 'org-occur-highlights)
11305 (defvar org-occur-parameters nil
11306 "Parameters of the active org-occur calls.
11307 This is a list, each call to org-occur pushes as cons cell,
11308 containing the regular expression and the callback, onto the list.
11309 The list can contain several entries if `org-occur' has been called
11310 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11311 will only contain one set of parameters. When the highlights are
11312 removed (for example with `C-c C-c', or with the next edit (depending
11313 on `org-remove-highlights-with-change'), this variable is emptied
11314 as well.")
11315 (make-variable-buffer-local 'org-occur-parameters)
11317 (defun org-occur (regexp &optional keep-previous callback)
11318 "Make a compact tree which shows all matches of REGEXP.
11319 The tree will show the lines where the regexp matches, and all higher
11320 headlines above the match. It will also show the heading after the match,
11321 to make sure editing the matching entry is easy.
11322 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11323 call to `org-occur' will be kept, to allow stacking of calls to this
11324 command.
11325 If CALLBACK is non-nil, it is a function which is called to confirm
11326 that the match should indeed be shown."
11327 (interactive "sRegexp: \nP")
11328 (when (equal regexp "")
11329 (error "Regexp cannot be empty"))
11330 (unless keep-previous
11331 (org-remove-occur-highlights nil nil t))
11332 (push (cons regexp callback) org-occur-parameters)
11333 (let ((cnt 0))
11334 (save-excursion
11335 (goto-char (point-min))
11336 (if (or (not keep-previous) ; do not want to keep
11337 (not org-occur-highlights)) ; no previous matches
11338 ;; hide everything
11339 (org-overview))
11340 (while (re-search-forward regexp nil t)
11341 (when (or (not callback)
11342 (save-match-data (funcall callback)))
11343 (setq cnt (1+ cnt))
11344 (when org-highlight-sparse-tree-matches
11345 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11346 (org-show-context 'occur-tree))))
11347 (when org-remove-highlights-with-change
11348 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11349 nil 'local))
11350 (unless org-sparse-tree-open-archived-trees
11351 (org-hide-archived-subtrees (point-min) (point-max)))
11352 (run-hooks 'org-occur-hook)
11353 (if (interactive-p)
11354 (message "%d match(es) for regexp %s" cnt regexp))
11355 cnt))
11357 (defun org-show-context (&optional key)
11358 "Make sure point and context and visible.
11359 How much context is shown depends upon the variables
11360 `org-show-hierarchy-above', `org-show-following-heading'. and
11361 `org-show-siblings'."
11362 (let ((heading-p (org-on-heading-p t))
11363 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11364 (following-p (org-get-alist-option org-show-following-heading key))
11365 (entry-p (org-get-alist-option org-show-entry-below key))
11366 (siblings-p (org-get-alist-option org-show-siblings key)))
11367 (catch 'exit
11368 ;; Show heading or entry text
11369 (if (and heading-p (not entry-p))
11370 (org-flag-heading nil) ; only show the heading
11371 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11372 (org-show-hidden-entry))) ; show entire entry
11373 (when following-p
11374 ;; Show next sibling, or heading below text
11375 (save-excursion
11376 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11377 (org-flag-heading nil))))
11378 (when siblings-p (org-show-siblings))
11379 (when hierarchy-p
11380 ;; show all higher headings, possibly with siblings
11381 (save-excursion
11382 (while (and (condition-case nil
11383 (progn (org-up-heading-all 1) t)
11384 (error nil))
11385 (not (bobp)))
11386 (org-flag-heading nil)
11387 (when siblings-p (org-show-siblings))))))))
11389 (defvar org-reveal-start-hook nil
11390 "Hook run before revealing a location.")
11392 (defun org-reveal (&optional siblings)
11393 "Show current entry, hierarchy above it, and the following headline.
11394 This can be used to show a consistent set of context around locations
11395 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11396 not t for the search context.
11398 With optional argument SIBLINGS, on each level of the hierarchy all
11399 siblings are shown. This repairs the tree structure to what it would
11400 look like when opened with hierarchical calls to `org-cycle'.
11401 With double optional argument `C-u C-u', go to the parent and show the
11402 entire tree."
11403 (interactive "P")
11404 (run-hooks 'org-reveal-start-hook)
11405 (let ((org-show-hierarchy-above t)
11406 (org-show-following-heading t)
11407 (org-show-siblings (if siblings t org-show-siblings)))
11408 (org-show-context nil))
11409 (when (equal siblings '(16))
11410 (save-excursion
11411 (when (org-up-heading-safe)
11412 (org-show-subtree)
11413 (run-hook-with-args 'org-cycle-hook 'subtree)))))
11415 (defun org-highlight-new-match (beg end)
11416 "Highlight from BEG to END and mark the highlight is an occur headline."
11417 (let ((ov (org-make-overlay beg end)))
11418 (org-overlay-put ov 'face 'secondary-selection)
11419 (push ov org-occur-highlights)))
11421 (defun org-remove-occur-highlights (&optional beg end noremove)
11422 "Remove the occur highlights from the buffer.
11423 BEG and END are ignored. If NOREMOVE is nil, remove this function
11424 from the `before-change-functions' in the current buffer."
11425 (interactive)
11426 (unless org-inhibit-highlight-removal
11427 (mapc 'org-delete-overlay org-occur-highlights)
11428 (setq org-occur-highlights nil)
11429 (setq org-occur-parameters nil)
11430 (unless noremove
11431 (remove-hook 'before-change-functions
11432 'org-remove-occur-highlights 'local))))
11434 ;;;; Priorities
11436 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11437 "Regular expression matching the priority indicator.")
11439 (defvar org-remove-priority-next-time nil)
11441 (defun org-priority-up ()
11442 "Increase the priority of the current item."
11443 (interactive)
11444 (org-priority 'up))
11446 (defun org-priority-down ()
11447 "Decrease the priority of the current item."
11448 (interactive)
11449 (org-priority 'down))
11451 (defun org-priority (&optional action)
11452 "Change the priority of an item by ARG.
11453 ACTION can be `set', `up', `down', or a character."
11454 (interactive)
11455 (unless org-enable-priority-commands
11456 (error "Priority commands are disabled"))
11457 (setq action (or action 'set))
11458 (let (current new news have remove)
11459 (save-excursion
11460 (org-back-to-heading t)
11461 (if (looking-at org-priority-regexp)
11462 (setq current (string-to-char (match-string 2))
11463 have t)
11464 (setq current org-default-priority))
11465 (cond
11466 ((eq action 'remove)
11467 (setq remove t new ?\ ))
11468 ((or (eq action 'set)
11469 (if (featurep 'xemacs) (characterp action) (integerp action)))
11470 (if (not (eq action 'set))
11471 (setq new action)
11472 (message "Priority %c-%c, SPC to remove: "
11473 org-highest-priority org-lowest-priority)
11474 (setq new (read-char-exclusive)))
11475 (if (and (= (upcase org-highest-priority) org-highest-priority)
11476 (= (upcase org-lowest-priority) org-lowest-priority))
11477 (setq new (upcase new)))
11478 (cond ((equal new ?\ ) (setq remove t))
11479 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11480 (error "Priority must be between `%c' and `%c'"
11481 org-highest-priority org-lowest-priority))))
11482 ((eq action 'up)
11483 (if (and (not have) (eq last-command this-command))
11484 (setq new org-lowest-priority)
11485 (setq new (if (and org-priority-start-cycle-with-default (not have))
11486 org-default-priority (1- current)))))
11487 ((eq action 'down)
11488 (if (and (not have) (eq last-command this-command))
11489 (setq new org-highest-priority)
11490 (setq new (if (and org-priority-start-cycle-with-default (not have))
11491 org-default-priority (1+ current)))))
11492 (t (error "Invalid action")))
11493 (if (or (< (upcase new) org-highest-priority)
11494 (> (upcase new) org-lowest-priority))
11495 (setq remove t))
11496 (setq news (format "%c" new))
11497 (if have
11498 (if remove
11499 (replace-match "" t t nil 1)
11500 (replace-match news t t nil 2))
11501 (if remove
11502 (error "No priority cookie found in line")
11503 (let ((case-fold-search nil))
11504 (looking-at org-todo-line-regexp))
11505 (if (match-end 2)
11506 (progn
11507 (goto-char (match-end 2))
11508 (insert " [#" news "]"))
11509 (goto-char (match-beginning 3))
11510 (insert "[#" news "] "))))
11511 (org-preserve-lc (org-set-tags nil 'align)))
11512 (if remove
11513 (message "Priority removed")
11514 (message "Priority of current item set to %s" news))))
11516 (defun org-get-priority (s)
11517 "Find priority cookie and return priority."
11518 (save-match-data
11519 (if (not (string-match org-priority-regexp s))
11520 (* 1000 (- org-lowest-priority org-default-priority))
11521 (* 1000 (- org-lowest-priority
11522 (string-to-char (match-string 2 s)))))))
11524 ;;;; Tags
11526 (defvar org-agenda-archives-mode)
11527 (defvar org-map-continue-from nil
11528 "Position from where mapping should continue.
11529 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11531 (defvar org-scanner-tags nil
11532 "The current tag list while the tags scanner is running.")
11533 (defvar org-trust-scanner-tags nil
11534 "Should `org-get-tags-at' use the tags fro the scanner.
11535 This is for internal dynamical scoping only.
11536 When this is non-nil, the function `org-get-tags-at' will return the value
11537 of `org-scanner-tags' instead of building the list by itself. This
11538 can lead to large speed-ups when the tags scanner is used in a file with
11539 many entries, and when the list of tags is retrieved, for example to
11540 obtain a list of properties. Building the tags list for each entry in such
11541 a file becomes an N^2 operation - but with this variable set, it scales
11542 as N.")
11544 (defun org-scan-tags (action matcher &optional todo-only)
11545 "Scan headline tags with inheritance and produce output ACTION.
11547 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11548 or `agenda' to produce an entry list for an agenda view. It can also be
11549 a Lisp form or a function that should be called at each matched headline, in
11550 this case the return value is a list of all return values from these calls.
11552 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11553 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11554 only lines with a TODO keyword are included in the output."
11555 (require 'org-agenda)
11556 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11557 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11558 (org-re
11559 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11560 (props (list 'face 'default
11561 'done-face 'org-agenda-done
11562 'undone-face 'default
11563 'mouse-face 'highlight
11564 'org-not-done-regexp org-not-done-regexp
11565 'org-todo-regexp org-todo-regexp
11566 'help-echo
11567 (format "mouse-2 or RET jump to org file %s"
11568 (abbreviate-file-name
11569 (or (buffer-file-name (buffer-base-buffer))
11570 (buffer-name (buffer-base-buffer)))))))
11571 (case-fold-search nil)
11572 (org-map-continue-from nil)
11573 lspos tags tags-list
11574 (tags-alist (list (cons 0 org-file-tags)))
11575 (llast 0) rtn rtn1 level category i txt
11576 todo marker entry priority)
11577 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11578 (setq action (list 'lambda nil action)))
11579 (save-excursion
11580 (goto-char (point-min))
11581 (when (eq action 'sparse-tree)
11582 (org-overview)
11583 (org-remove-occur-highlights))
11584 (while (re-search-forward re nil t)
11585 (catch :skip
11586 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11587 tags (if (match-end 4) (org-match-string-no-properties 4)))
11588 (goto-char (setq lspos (match-beginning 0)))
11589 (setq level (org-reduced-level (funcall outline-level))
11590 category (org-get-category))
11591 (setq i llast llast level)
11592 ;; remove tag lists from same and sublevels
11593 (while (>= i level)
11594 (when (setq entry (assoc i tags-alist))
11595 (setq tags-alist (delete entry tags-alist)))
11596 (setq i (1- i)))
11597 ;; add the next tags
11598 (when tags
11599 (setq tags (org-split-string tags ":")
11600 tags-alist
11601 (cons (cons level tags) tags-alist)))
11602 ;; compile tags for current headline
11603 (setq tags-list
11604 (if org-use-tag-inheritance
11605 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11606 tags)
11607 org-scanner-tags tags-list)
11608 (when org-use-tag-inheritance
11609 (setcdr (car tags-alist)
11610 (mapcar (lambda (x)
11611 (setq x (copy-sequence x))
11612 (org-add-prop-inherited x))
11613 (cdar tags-alist))))
11614 (when (and tags org-use-tag-inheritance
11615 (or (not (eq t org-use-tag-inheritance))
11616 org-tags-exclude-from-inheritance))
11617 ;; selective inheritance, remove uninherited ones
11618 (setcdr (car tags-alist)
11619 (org-remove-uniherited-tags (cdar tags-alist))))
11620 (when (and (or (not todo-only)
11621 (and (member todo org-not-done-keywords)
11622 (or (not org-agenda-tags-todo-honor-ignore-options)
11623 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11624 (let ((case-fold-search t)) (eval matcher))
11626 (not (member org-archive-tag tags-list))
11627 ;; we have an archive tag, should we use this anyway?
11628 (or (not org-agenda-skip-archived-trees)
11629 (and (eq action 'agenda) org-agenda-archives-mode))))
11630 (unless (eq action 'sparse-tree) (org-agenda-skip))
11632 ;; select this headline
11634 (cond
11635 ((eq action 'sparse-tree)
11636 (and org-highlight-sparse-tree-matches
11637 (org-get-heading) (match-end 0)
11638 (org-highlight-new-match
11639 (match-beginning 0) (match-beginning 1)))
11640 (org-show-context 'tags-tree))
11641 ((eq action 'agenda)
11642 (setq txt (org-format-agenda-item
11644 (concat
11645 (if (eq org-tags-match-list-sublevels 'indented)
11646 (make-string (1- level) ?.) "")
11647 (org-get-heading))
11648 category
11649 tags-list
11651 priority (org-get-priority txt))
11652 (goto-char lspos)
11653 (setq marker (org-agenda-new-marker))
11654 (org-add-props txt props
11655 'org-marker marker 'org-hd-marker marker 'org-category category
11656 'todo-state todo
11657 'priority priority 'type "tagsmatch")
11658 (push txt rtn))
11659 ((functionp action)
11660 (setq org-map-continue-from nil)
11661 (save-excursion
11662 (setq rtn1 (funcall action))
11663 (push rtn1 rtn)))
11664 (t (error "Invalid action")))
11666 ;; if we are to skip sublevels, jump to end of subtree
11667 (unless org-tags-match-list-sublevels
11668 (org-end-of-subtree t)
11669 (backward-char 1))))
11670 ;; Get the correct position from where to continue
11671 (if org-map-continue-from
11672 (goto-char org-map-continue-from)
11673 (and (= (point) lspos) (end-of-line 1)))))
11674 (when (and (eq action 'sparse-tree)
11675 (not org-sparse-tree-open-archived-trees))
11676 (org-hide-archived-subtrees (point-min) (point-max)))
11677 (nreverse rtn)))
11679 (defun org-remove-uniherited-tags (tags)
11680 "Remove all tags that are not inherited from the list TAGS."
11681 (cond
11682 ((eq org-use-tag-inheritance t)
11683 (if org-tags-exclude-from-inheritance
11684 (org-delete-all org-tags-exclude-from-inheritance tags)
11685 tags))
11686 ((not org-use-tag-inheritance) nil)
11687 ((stringp org-use-tag-inheritance)
11688 (delq nil (mapcar
11689 (lambda (x)
11690 (if (and (string-match org-use-tag-inheritance x)
11691 (not (member x org-tags-exclude-from-inheritance)))
11692 x nil))
11693 tags)))
11694 ((listp org-use-tag-inheritance)
11695 (delq nil (mapcar
11696 (lambda (x)
11697 (if (member x org-use-tag-inheritance) x nil))
11698 tags)))))
11700 (defvar todo-only) ;; dynamically scoped
11702 (defun org-match-sparse-tree (&optional todo-only match)
11703 "Create a sparse tree according to tags string MATCH.
11704 MATCH can contain positive and negative selection of tags, like
11705 \"+WORK+URGENT-WITHBOSS\".
11706 If optional argument TODO-ONLY is non-nil, only select lines that are
11707 also TODO lines."
11708 (interactive "P")
11709 (org-prepare-agenda-buffers (list (current-buffer)))
11710 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11712 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11714 (defvar org-cached-props nil)
11715 (defun org-cached-entry-get (pom property)
11716 (if (or (eq t org-use-property-inheritance)
11717 (and (stringp org-use-property-inheritance)
11718 (string-match org-use-property-inheritance property))
11719 (and (listp org-use-property-inheritance)
11720 (member property org-use-property-inheritance)))
11721 ;; Caching is not possible, check it directly
11722 (org-entry-get pom property 'inherit)
11723 ;; Get all properties, so that we can do complicated checks easily
11724 (cdr (assoc property (or org-cached-props
11725 (setq org-cached-props
11726 (org-entry-properties pom)))))))
11728 (defun org-global-tags-completion-table (&optional files)
11729 "Return the list of all tags in all agenda buffer/files."
11730 (save-excursion
11731 (org-uniquify
11732 (delq nil
11733 (apply 'append
11734 (mapcar
11735 (lambda (file)
11736 (set-buffer (find-file-noselect file))
11737 (append (org-get-buffer-tags)
11738 (mapcar (lambda (x) (if (stringp (car-safe x))
11739 (list (car-safe x)) nil))
11740 org-tag-alist)))
11741 (if (and files (car files))
11742 files
11743 (org-agenda-files))))))))
11745 (defun org-make-tags-matcher (match)
11746 "Create the TAGS//TODO matcher form for the selection string MATCH."
11747 ;; todo-only is scoped dynamically into this function, and the function
11748 ;; may change it if the matcher asks for it.
11749 (unless match
11750 ;; Get a new match request, with completion
11751 (let ((org-last-tags-completion-table
11752 (org-global-tags-completion-table)))
11753 (setq match (org-completing-read-no-i
11754 "Match: " 'org-tags-completion-function nil nil nil
11755 'org-tags-history))))
11757 ;; Parse the string and create a lisp form
11758 (let ((match0 match)
11759 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11760 minus tag mm
11761 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11762 orterms term orlist re-p str-p level-p level-op time-p
11763 prop-p pn pv po cat-p gv rest)
11764 (if (string-match "/+" match)
11765 ;; match contains also a todo-matching request
11766 (progn
11767 (setq tagsmatch (substring match 0 (match-beginning 0))
11768 todomatch (substring match (match-end 0)))
11769 (if (string-match "^!" todomatch)
11770 (setq todo-only t todomatch (substring todomatch 1)))
11771 (if (string-match "^\\s-*$" todomatch)
11772 (setq todomatch nil)))
11773 ;; only matching tags
11774 (setq tagsmatch match todomatch nil))
11776 ;; Make the tags matcher
11777 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11778 (setq tagsmatcher t)
11779 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11780 (while (setq term (pop orterms))
11781 (while (and (equal (substring term -1) "\\") orterms)
11782 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11783 (while (string-match re term)
11784 (setq rest (substring term (match-end 0))
11785 minus (and (match-end 1)
11786 (equal (match-string 1 term) "-"))
11787 tag (match-string 2 term)
11788 re-p (equal (string-to-char tag) ?{)
11789 level-p (match-end 4)
11790 prop-p (match-end 5)
11791 mm (cond
11792 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11793 (level-p
11794 (setq level-op (org-op-to-function (match-string 3 term)))
11795 `(,level-op level ,(string-to-number
11796 (match-string 4 term))))
11797 (prop-p
11798 (setq pn (match-string 5 term)
11799 po (match-string 6 term)
11800 pv (match-string 7 term)
11801 cat-p (equal pn "CATEGORY")
11802 re-p (equal (string-to-char pv) ?{)
11803 str-p (equal (string-to-char pv) ?\")
11804 time-p (save-match-data
11805 (string-match "^\"[[<].*[]>]\"$" pv))
11806 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11807 (if time-p (setq pv (org-matcher-time pv)))
11808 (setq po (org-op-to-function po (if time-p 'time str-p)))
11809 (cond
11810 ((equal pn "CATEGORY")
11811 (setq gv '(get-text-property (point) 'org-category)))
11812 ((equal pn "TODO")
11813 (setq gv 'todo))
11815 (setq gv `(org-cached-entry-get nil ,pn))))
11816 (if re-p
11817 (if (eq po 'org<>)
11818 `(not (string-match ,pv (or ,gv "")))
11819 `(string-match ,pv (or ,gv "")))
11820 (if str-p
11821 `(,po (or ,gv "") ,pv)
11822 `(,po (string-to-number (or ,gv ""))
11823 ,(string-to-number pv) ))))
11824 (t `(member ,tag tags-list)))
11825 mm (if minus (list 'not mm) mm)
11826 term rest)
11827 (push mm tagsmatcher))
11828 (push (if (> (length tagsmatcher) 1)
11829 (cons 'and tagsmatcher)
11830 (car tagsmatcher))
11831 orlist)
11832 (setq tagsmatcher nil))
11833 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11834 (setq tagsmatcher
11835 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11836 ;; Make the todo matcher
11837 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11838 (setq todomatcher t)
11839 (setq orterms (org-split-string todomatch "|") orlist nil)
11840 (while (setq term (pop orterms))
11841 (while (string-match re term)
11842 (setq minus (and (match-end 1)
11843 (equal (match-string 1 term) "-"))
11844 kwd (match-string 2 term)
11845 re-p (equal (string-to-char kwd) ?{)
11846 term (substring term (match-end 0))
11847 mm (if re-p
11848 `(string-match ,(substring kwd 1 -1) todo)
11849 (list 'equal 'todo kwd))
11850 mm (if minus (list 'not mm) mm))
11851 (push mm todomatcher))
11852 (push (if (> (length todomatcher) 1)
11853 (cons 'and todomatcher)
11854 (car todomatcher))
11855 orlist)
11856 (setq todomatcher nil))
11857 (setq todomatcher (if (> (length orlist) 1)
11858 (cons 'or orlist) (car orlist))))
11860 ;; Return the string and lisp forms of the matcher
11861 (setq matcher (if todomatcher
11862 (list 'and tagsmatcher todomatcher)
11863 tagsmatcher))
11864 (cons match0 matcher)))
11866 (defun org-op-to-function (op &optional stringp)
11867 "Turn an operator into the appropriate function."
11868 (setq op
11869 (cond
11870 ((equal op "<" ) '(< string< org-time<))
11871 ((equal op ">" ) '(> org-string> org-time>))
11872 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11873 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11874 ((member op '("=" "==")) '(= string= org-time=))
11875 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11876 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11878 (defun org<> (a b) (not (= a b)))
11879 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11880 (defun org-string>= (a b) (not (string< a b)))
11881 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11882 (defun org-string<> (a b) (not (string= a b)))
11883 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11884 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11885 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11886 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11887 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11888 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11889 (defun org-2ft (s)
11890 "Convert S to a floating point time.
11891 If S is already a number, just return it. If it is a string, parse
11892 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11893 (cond
11894 ((numberp s) s)
11895 ((stringp s)
11896 (condition-case nil
11897 (float-time (apply 'encode-time (org-parse-time-string s)))
11898 (error 0.)))
11899 (t 0.)))
11901 (defun org-time-today ()
11902 "Time in seconds today at 0:00.
11903 Returns the float number of seconds since the beginning of the
11904 epoch to the beginning of today (00:00)."
11905 (float-time (apply 'encode-time
11906 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11908 (defun org-matcher-time (s)
11909 "Interpret a time comparison value."
11910 (save-match-data
11911 (cond
11912 ((string= s "<now>") (float-time))
11913 ((string= s "<today>") (org-time-today))
11914 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11915 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11916 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11917 (+ (org-time-today)
11918 (* (string-to-number (match-string 1 s))
11919 (cdr (assoc (match-string 2 s)
11920 '(("d" . 86400.0) ("w" . 604800.0)
11921 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11922 (t (org-2ft s)))))
11924 (defun org-match-any-p (re list)
11925 "Does re match any element of list?"
11926 (setq list (mapcar (lambda (x) (string-match re x)) list))
11927 (delq nil list))
11929 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11930 (defvar org-tags-overlay (org-make-overlay 1 1))
11931 (org-detach-overlay org-tags-overlay)
11933 (defun org-get-local-tags-at (&optional pos)
11934 "Get a list of tags defined in the current headline."
11935 (org-get-tags-at pos 'local))
11937 (defun org-get-local-tags ()
11938 "Get a list of tags defined in the current headline."
11939 (org-get-tags-at nil 'local))
11941 (defun org-get-tags-at (&optional pos local)
11942 "Get a list of all headline tags applicable at POS.
11943 POS defaults to point. If tags are inherited, the list contains
11944 the targets in the same sequence as the headlines appear, i.e.
11945 the tags of the current headline come last.
11946 When LOCAL is non-nil, only return tags from the current headline,
11947 ignore inherited ones."
11948 (interactive)
11949 (if (and org-trust-scanner-tags
11950 (or (not pos) (equal pos (point)))
11951 (not local))
11952 org-scanner-tags
11953 (let (tags ltags lastpos parent)
11954 (save-excursion
11955 (save-restriction
11956 (widen)
11957 (goto-char (or pos (point)))
11958 (save-match-data
11959 (catch 'done
11960 (condition-case nil
11961 (progn
11962 (org-back-to-heading t)
11963 (while (not (equal lastpos (point)))
11964 (setq lastpos (point))
11965 (when (looking-at
11966 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11967 (setq ltags (org-split-string
11968 (org-match-string-no-properties 1) ":"))
11969 (when parent
11970 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11971 (setq tags (append
11972 (if parent
11973 (org-remove-uniherited-tags ltags)
11974 ltags)
11975 tags)))
11976 (or org-use-tag-inheritance (throw 'done t))
11977 (if local (throw 'done t))
11978 (or (org-up-heading-safe) (error nil))
11979 (setq parent t)))
11980 (error nil)))))
11981 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11983 (defun org-add-prop-inherited (s)
11984 (add-text-properties 0 (length s) '(inherited t) s)
11987 (defun org-toggle-tag (tag &optional onoff)
11988 "Toggle the tag TAG for the current line.
11989 If ONOFF is `on' or `off', don't toggle but set to this state."
11990 (let (res current)
11991 (save-excursion
11992 (org-back-to-heading t)
11993 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11994 (point-at-eol) t)
11995 (progn
11996 (setq current (match-string 1))
11997 (replace-match ""))
11998 (setq current ""))
11999 (setq current (nreverse (org-split-string current ":")))
12000 (cond
12001 ((eq onoff 'on)
12002 (setq res t)
12003 (or (member tag current) (push tag current)))
12004 ((eq onoff 'off)
12005 (or (not (member tag current)) (setq current (delete tag current))))
12006 (t (if (member tag current)
12007 (setq current (delete tag current))
12008 (setq res t)
12009 (push tag current))))
12010 (end-of-line 1)
12011 (if current
12012 (progn
12013 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12014 (org-set-tags nil t))
12015 (delete-horizontal-space))
12016 (run-hooks 'org-after-tags-change-hook))
12017 res))
12019 (defun org-align-tags-here (to-col)
12020 ;; Assumes that this is a headline
12021 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12022 (beginning-of-line 1)
12023 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12024 (< pos (match-beginning 2)))
12025 (progn
12026 (setq tags-l (- (match-end 2) (match-beginning 2)))
12027 (goto-char (match-beginning 1))
12028 (insert " ")
12029 (delete-region (point) (1+ (match-beginning 2)))
12030 (setq ncol (max (1+ (current-column))
12031 (1+ col)
12032 (if (> to-col 0)
12033 to-col
12034 (- (abs to-col) tags-l))))
12035 (setq p (point))
12036 (insert (make-string (- ncol (current-column)) ?\ ))
12037 (setq ncol (current-column))
12038 (when indent-tabs-mode (tabify p (point-at-eol)))
12039 (org-move-to-column (min ncol col) t))
12040 (goto-char pos))))
12042 (defun org-set-tags-command (&optional arg just-align)
12043 "Call the set-tags command for the current entry."
12044 (interactive "P")
12045 (if (org-on-heading-p)
12046 (org-set-tags arg just-align)
12047 (save-excursion
12048 (org-back-to-heading t)
12049 (org-set-tags arg just-align))))
12051 (defun org-set-tags-to (data)
12052 "Set the tags of the current entry to DATA, replacing the current tags.
12053 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12054 If DATA is nil or the empty string, any tags will be removed."
12055 (interactive "sTags: ")
12056 (setq data
12057 (cond
12058 ((eq data nil) "")
12059 ((equal data "") "")
12060 ((stringp data)
12061 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12062 ":"))
12063 ((listp data)
12064 (concat ":" (mapconcat 'identity data ":") ":"))
12065 (t nil)))
12066 (when data
12067 (save-excursion
12068 (org-back-to-heading t)
12069 (when (looking-at org-complex-heading-regexp)
12070 (if (match-end 5)
12071 (progn
12072 (goto-char (match-beginning 5))
12073 (insert data)
12074 (delete-region (point) (point-at-eol))
12075 (org-set-tags nil 'align))
12076 (goto-char (point-at-eol))
12077 (insert " " data)
12078 (org-set-tags nil 'align)))
12079 (beginning-of-line 1)
12080 (if (looking-at ".*?\\([ \t]+\\)$")
12081 (delete-region (match-beginning 1) (match-end 1))))))
12083 (defun org-set-tags (&optional arg just-align)
12084 "Set the tags for the current headline.
12085 With prefix ARG, realign all tags in headings in the current buffer."
12086 (interactive "P")
12087 (let* ((re (concat "^" outline-regexp))
12088 (current (org-get-tags-string))
12089 (col (current-column))
12090 (org-setting-tags t)
12091 table current-tags inherited-tags ; computed below when needed
12092 tags p0 c0 c1 rpl)
12093 (if arg
12094 (save-excursion
12095 (goto-char (point-min))
12096 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12097 (while (re-search-forward re nil t)
12098 (org-set-tags nil t)
12099 (end-of-line 1)))
12100 (message "All tags realigned to column %d" org-tags-column))
12101 (if just-align
12102 (setq tags current)
12103 ;; Get a new set of tags from the user
12104 (save-excursion
12105 (setq table (append org-tag-persistent-alist
12106 (or org-tag-alist (org-get-buffer-tags))
12107 (and org-complete-tags-always-offer-all-agenda-tags
12108 (org-global-tags-completion-table (org-agenda-files))))
12109 org-last-tags-completion-table table
12110 current-tags (org-split-string current ":")
12111 inherited-tags (nreverse
12112 (nthcdr (length current-tags)
12113 (nreverse (org-get-tags-at))))
12114 tags
12115 (if (or (eq t org-use-fast-tag-selection)
12116 (and org-use-fast-tag-selection
12117 (delq nil (mapcar 'cdr table))))
12118 (org-fast-tag-selection
12119 current-tags inherited-tags table
12120 (if org-fast-tag-selection-include-todo org-todo-key-alist))
12121 (let ((org-add-colon-after-tag-completion t))
12122 (org-trim
12123 (org-without-partial-completion
12124 (org-icompleting-read "Tags: " 'org-tags-completion-function
12125 nil nil current 'org-tags-history)))))))
12126 (while (string-match "[-+&]+" tags)
12127 ;; No boolean logic, just a list
12128 (setq tags (replace-match ":" t t tags))))
12130 (if org-tags-sort-function
12131 (setq tags (mapconcat 'identity
12132 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
12133 org-tags-sort-function) ":")))
12135 (if (string-match "\\`[\t ]*\\'" tags)
12136 (setq tags "")
12137 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12138 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12140 ;; Insert new tags at the correct column
12141 (beginning-of-line 1)
12142 (cond
12143 ((and (equal current "") (equal tags "")))
12144 ((re-search-forward
12145 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12146 (point-at-eol) t)
12147 (if (equal tags "")
12148 (setq rpl "")
12149 (goto-char (match-beginning 0))
12150 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
12151 (1+ (point)) (point))
12152 c1 (max (1+ c0) (if (> org-tags-column 0)
12153 org-tags-column
12154 (- (- org-tags-column) (length tags))))
12155 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12156 (replace-match rpl t t)
12157 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
12158 tags)
12159 (t (error "Tags alignment failed")))
12160 (org-move-to-column col)
12161 (unless just-align
12162 (run-hooks 'org-after-tags-change-hook)))))
12164 (defun org-change-tag-in-region (beg end tag off)
12165 "Add or remove TAG for each entry in the region.
12166 This works in the agenda, and also in an org-mode buffer."
12167 (interactive
12168 (list (region-beginning) (region-end)
12169 (let ((org-last-tags-completion-table
12170 (if (org-mode-p)
12171 (org-get-buffer-tags)
12172 (org-global-tags-completion-table))))
12173 (org-icompleting-read
12174 "Tag: " 'org-tags-completion-function nil nil nil
12175 'org-tags-history))
12176 (progn
12177 (message "[s]et or [r]emove? ")
12178 (equal (read-char-exclusive) ?r))))
12179 (if (fboundp 'deactivate-mark) (deactivate-mark))
12180 (let ((agendap (equal major-mode 'org-agenda-mode))
12181 l1 l2 m buf pos newhead (cnt 0))
12182 (goto-char end)
12183 (setq l2 (1- (org-current-line)))
12184 (goto-char beg)
12185 (setq l1 (org-current-line))
12186 (loop for l from l1 to l2 do
12187 (org-goto-line l)
12188 (setq m (get-text-property (point) 'org-hd-marker))
12189 (when (or (and (org-mode-p) (org-on-heading-p))
12190 (and agendap m))
12191 (setq buf (if agendap (marker-buffer m) (current-buffer))
12192 pos (if agendap m (point)))
12193 (with-current-buffer buf
12194 (save-excursion
12195 (save-restriction
12196 (goto-char pos)
12197 (setq cnt (1+ cnt))
12198 (org-toggle-tag tag (if off 'off 'on))
12199 (setq newhead (org-get-heading)))))
12200 (and agendap (org-agenda-change-all-lines newhead m))))
12201 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12203 (defun org-tags-completion-function (string predicate &optional flag)
12204 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12205 (confirm (lambda (x) (stringp (car x)))))
12206 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12207 (setq s1 (match-string 1 string)
12208 s2 (match-string 2 string))
12209 (setq s1 "" s2 string))
12210 (cond
12211 ((eq flag nil)
12212 ;; try completion
12213 (setq rtn (try-completion s2 ctable confirm))
12214 (if (stringp rtn)
12215 (setq rtn
12216 (concat s1 s2 (substring rtn (length s2))
12217 (if (and org-add-colon-after-tag-completion
12218 (assoc rtn ctable))
12219 ":" ""))))
12220 rtn)
12221 ((eq flag t)
12222 ;; all-completions
12223 (all-completions s2 ctable confirm)
12225 ((eq flag 'lambda)
12226 ;; exact match?
12227 (assoc s2 ctable)))
12230 (defun org-fast-tag-insert (kwd tags face &optional end)
12231 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12232 (insert (format "%-12s" (concat kwd ":"))
12233 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12234 (or end "")))
12236 (defun org-fast-tag-show-exit (flag)
12237 (save-excursion
12238 (org-goto-line 3)
12239 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12240 (replace-match ""))
12241 (when flag
12242 (end-of-line 1)
12243 (org-move-to-column (- (window-width) 19) t)
12244 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12246 (defun org-set-current-tags-overlay (current prefix)
12247 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12248 (if (featurep 'xemacs)
12249 (org-overlay-display org-tags-overlay (concat prefix s)
12250 'secondary-selection)
12251 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12252 (org-overlay-display org-tags-overlay (concat prefix s)))))
12254 (defvar org-last-tag-selection-key nil)
12255 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12256 "Fast tag selection with single keys.
12257 CURRENT is the current list of tags in the headline, INHERITED is the
12258 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12259 possibly with grouping information. TODO-TABLE is a similar table with
12260 TODO keywords, should these have keys assigned to them.
12261 If the keys are nil, a-z are automatically assigned.
12262 Returns the new tags string, or nil to not change the current settings."
12263 (let* ((fulltable (append table todo-table))
12264 (maxlen (apply 'max (mapcar
12265 (lambda (x)
12266 (if (stringp (car x)) (string-width (car x)) 0))
12267 fulltable)))
12268 (buf (current-buffer))
12269 (expert (eq org-fast-tag-selection-single-key 'expert))
12270 (buffer-tags nil)
12271 (fwidth (+ maxlen 3 1 3))
12272 (ncol (/ (- (window-width) 4) fwidth))
12273 (i-face 'org-done)
12274 (c-face 'org-todo)
12275 tg cnt e c char c1 c2 ntable tbl rtn
12276 ov-start ov-end ov-prefix
12277 (exit-after-next org-fast-tag-selection-single-key)
12278 (done-keywords org-done-keywords)
12279 groups ingroup)
12280 (save-excursion
12281 (beginning-of-line 1)
12282 (if (looking-at
12283 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12284 (setq ov-start (match-beginning 1)
12285 ov-end (match-end 1)
12286 ov-prefix "")
12287 (setq ov-start (1- (point-at-eol))
12288 ov-end (1+ ov-start))
12289 (skip-chars-forward "^\n\r")
12290 (setq ov-prefix
12291 (concat
12292 (buffer-substring (1- (point)) (point))
12293 (if (> (current-column) org-tags-column)
12295 (make-string (- org-tags-column (current-column)) ?\ ))))))
12296 (org-move-overlay org-tags-overlay ov-start ov-end)
12297 (save-window-excursion
12298 (if expert
12299 (set-buffer (get-buffer-create " *Org tags*"))
12300 (delete-other-windows)
12301 (split-window-vertically)
12302 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12303 (erase-buffer)
12304 (org-set-local 'org-done-keywords done-keywords)
12305 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12306 (org-fast-tag-insert "Current" current c-face "\n\n")
12307 (org-fast-tag-show-exit exit-after-next)
12308 (org-set-current-tags-overlay current ov-prefix)
12309 (setq tbl fulltable char ?a cnt 0)
12310 (while (setq e (pop tbl))
12311 (cond
12312 ((equal (car e) :startgroup)
12313 (push '() groups) (setq ingroup t)
12314 (when (not (= cnt 0))
12315 (setq cnt 0)
12316 (insert "\n"))
12317 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12318 ((equal (car e) :endgroup)
12319 (setq ingroup nil cnt 0)
12320 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12321 ((equal e '(:newline))
12322 (when (not (= cnt 0))
12323 (setq cnt 0)
12324 (insert "\n")
12325 (setq e (car tbl))
12326 (while (equal (car tbl) '(:newline))
12327 (insert "\n")
12328 (setq tbl (cdr tbl)))))
12330 (setq tg (copy-sequence (car e)) c2 nil)
12331 (if (cdr e)
12332 (setq c (cdr e))
12333 ;; automatically assign a character.
12334 (setq c1 (string-to-char
12335 (downcase (substring
12336 tg (if (= (string-to-char tg) ?@) 1 0)))))
12337 (if (or (rassoc c1 ntable) (rassoc c1 table))
12338 (while (or (rassoc char ntable) (rassoc char table))
12339 (setq char (1+ char)))
12340 (setq c2 c1))
12341 (setq c (or c2 char)))
12342 (if ingroup (push tg (car groups)))
12343 (setq tg (org-add-props tg nil 'face
12344 (cond
12345 ((not (assoc tg table))
12346 (org-get-todo-face tg))
12347 ((member tg current) c-face)
12348 ((member tg inherited) i-face)
12349 (t nil))))
12350 (if (and (= cnt 0) (not ingroup)) (insert " "))
12351 (insert "[" c "] " tg (make-string
12352 (- fwidth 4 (length tg)) ?\ ))
12353 (push (cons tg c) ntable)
12354 (when (= (setq cnt (1+ cnt)) ncol)
12355 (insert "\n")
12356 (if ingroup (insert " "))
12357 (setq cnt 0)))))
12358 (setq ntable (nreverse ntable))
12359 (insert "\n")
12360 (goto-char (point-min))
12361 (if (not expert) (org-fit-window-to-buffer))
12362 (setq rtn
12363 (catch 'exit
12364 (while t
12365 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12366 (if (not groups) "no " "")
12367 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12368 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12369 (setq org-last-tag-selection-key c)
12370 (cond
12371 ((= c ?\r) (throw 'exit t))
12372 ((= c ?!)
12373 (setq groups (not groups))
12374 (goto-char (point-min))
12375 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12376 ((= c ?\C-c)
12377 (if (not expert)
12378 (org-fast-tag-show-exit
12379 (setq exit-after-next (not exit-after-next)))
12380 (setq expert nil)
12381 (delete-other-windows)
12382 (split-window-vertically)
12383 (org-switch-to-buffer-other-window " *Org tags*")
12384 (org-fit-window-to-buffer)))
12385 ((or (= c ?\C-g)
12386 (and (= c ?q) (not (rassoc c ntable))))
12387 (org-detach-overlay org-tags-overlay)
12388 (setq quit-flag t))
12389 ((= c ?\ )
12390 (setq current nil)
12391 (if exit-after-next (setq exit-after-next 'now)))
12392 ((= c ?\t)
12393 (condition-case nil
12394 (setq tg (org-icompleting-read
12395 "Tag: "
12396 (or buffer-tags
12397 (with-current-buffer buf
12398 (org-get-buffer-tags)))))
12399 (quit (setq tg "")))
12400 (when (string-match "\\S-" tg)
12401 (add-to-list 'buffer-tags (list tg))
12402 (if (member tg current)
12403 (setq current (delete tg current))
12404 (push tg current)))
12405 (if exit-after-next (setq exit-after-next 'now)))
12406 ((setq e (rassoc c todo-table) tg (car e))
12407 (with-current-buffer buf
12408 (save-excursion (org-todo tg)))
12409 (if exit-after-next (setq exit-after-next 'now)))
12410 ((setq e (rassoc c ntable) tg (car e))
12411 (if (member tg current)
12412 (setq current (delete tg current))
12413 (loop for g in groups do
12414 (if (member tg g)
12415 (mapc (lambda (x)
12416 (setq current (delete x current)))
12417 g)))
12418 (push tg current))
12419 (if exit-after-next (setq exit-after-next 'now))))
12421 ;; Create a sorted list
12422 (setq current
12423 (sort current
12424 (lambda (a b)
12425 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12426 (if (eq exit-after-next 'now) (throw 'exit t))
12427 (goto-char (point-min))
12428 (beginning-of-line 2)
12429 (delete-region (point) (point-at-eol))
12430 (org-fast-tag-insert "Current" current c-face)
12431 (org-set-current-tags-overlay current ov-prefix)
12432 (while (re-search-forward
12433 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12434 (setq tg (match-string 1))
12435 (add-text-properties
12436 (match-beginning 1) (match-end 1)
12437 (list 'face
12438 (cond
12439 ((member tg current) c-face)
12440 ((member tg inherited) i-face)
12441 (t (get-text-property (match-beginning 1) 'face))))))
12442 (goto-char (point-min)))))
12443 (org-detach-overlay org-tags-overlay)
12444 (if rtn
12445 (mapconcat 'identity current ":")
12446 nil))))
12448 (defun org-get-tags-string ()
12449 "Get the TAGS string in the current headline."
12450 (unless (org-on-heading-p t)
12451 (error "Not on a heading"))
12452 (save-excursion
12453 (beginning-of-line 1)
12454 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12455 (org-match-string-no-properties 1)
12456 "")))
12458 (defun org-get-tags ()
12459 "Get the list of tags specified in the current headline."
12460 (org-split-string (org-get-tags-string) ":"))
12462 (defun org-get-buffer-tags ()
12463 "Get a table of all tags used in the buffer, for completion."
12464 (let (tags)
12465 (save-excursion
12466 (goto-char (point-min))
12467 (while (re-search-forward
12468 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12469 (when (equal (char-after (point-at-bol 0)) ?*)
12470 (mapc (lambda (x) (add-to-list 'tags x))
12471 (org-split-string (org-match-string-no-properties 1) ":")))))
12472 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12473 (mapcar 'list tags)))
12475 ;;;; The mapping API
12477 ;;;###autoload
12478 (defun org-map-entries (func &optional match scope &rest skip)
12479 "Call FUNC at each headline selected by MATCH in SCOPE.
12481 FUNC is a function or a lisp form. The function will be called without
12482 arguments, with the cursor positioned at the beginning of the headline.
12483 The return values of all calls to the function will be collected and
12484 returned as a list.
12486 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12487 does not need to preserve point. After evaluation, the cursor will be
12488 moved to the end of the line (presumably of the headline of the
12489 processed entry) and search continues from there. Under some
12490 circumstances, this may not produce the wanted results. For example,
12491 if you have removed (e.g. archived) the current (sub)tree it could
12492 mean that the next entry will be skipped entirely. In such cases, you
12493 can specify the position from where search should continue by making
12494 FUNC set the variable `org-map-continue-from' to the desired buffer
12495 position.
12497 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12498 Only headlines that are matched by this query will be considered during
12499 the iteration. When MATCH is nil or t, all headlines will be
12500 visited by the iteration.
12502 SCOPE determines the scope of this command. It can be any of:
12504 nil The current buffer, respecting the restriction if any
12505 tree The subtree started with the entry at point
12506 file The current buffer, without restriction
12507 file-with-archives
12508 The current buffer, and any archives associated with it
12509 agenda All agenda files
12510 agenda-with-archives
12511 All agenda files with any archive files associated with them
12512 \(file1 file2 ...)
12513 If this is a list, all files in the list will be scanned
12515 The remaining args are treated as settings for the skipping facilities of
12516 the scanner. The following items can be given here:
12518 archive skip trees with the archive tag.
12519 comment skip trees with the COMMENT keyword
12520 function or Emacs Lisp form:
12521 will be used as value for `org-agenda-skip-function', so whenever
12522 the function returns t, FUNC will not be called for that
12523 entry and search will continue from the point where the
12524 function leaves it.
12526 If your function needs to retrieve the tags including inherited tags
12527 at the *current* entry, you can use the value of the variable
12528 `org-scanner-tags' which will be much faster than getting the value
12529 with `org-get-tags-at'. If your function gets properties with
12530 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12531 to t around the call to `org-entry-properties' to get the same speedup.
12532 Note that if your function moves around to retrieve tags and properties at
12533 a *different* entry, you cannot use these techniques."
12534 (let* ((org-agenda-archives-mode nil) ; just to make sure
12535 (org-agenda-skip-archived-trees (memq 'archive skip))
12536 (org-agenda-skip-comment-trees (memq 'comment skip))
12537 (org-agenda-skip-function
12538 (car (org-delete-all '(comment archive) skip)))
12539 (org-tags-match-list-sublevels t)
12540 matcher file res
12541 org-todo-keywords-for-agenda
12542 org-done-keywords-for-agenda
12543 org-todo-keyword-alist-for-agenda
12544 org-drawers-for-agenda
12545 org-tag-alist-for-agenda)
12547 (cond
12548 ((eq match t) (setq matcher t))
12549 ((eq match nil) (setq matcher t))
12550 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12552 (save-excursion
12553 (save-restriction
12554 (when (eq scope 'tree)
12555 (org-back-to-heading t)
12556 (org-narrow-to-subtree)
12557 (setq scope nil))
12559 (if (not scope)
12560 (progn
12561 (org-prepare-agenda-buffers
12562 (list (buffer-file-name (current-buffer))))
12563 (setq res (org-scan-tags func matcher)))
12564 ;; Get the right scope
12565 (cond
12566 ((and scope (listp scope) (symbolp (car scope)))
12567 (setq scope (eval scope)))
12568 ((eq scope 'agenda)
12569 (setq scope (org-agenda-files t)))
12570 ((eq scope 'agenda-with-archives)
12571 (setq scope (org-agenda-files t))
12572 (setq scope (org-add-archive-files scope)))
12573 ((eq scope 'file)
12574 (setq scope (list (buffer-file-name))))
12575 ((eq scope 'file-with-archives)
12576 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12577 (org-prepare-agenda-buffers scope)
12578 (while (setq file (pop scope))
12579 (with-current-buffer (org-find-base-buffer-visiting file)
12580 (save-excursion
12581 (save-restriction
12582 (widen)
12583 (goto-char (point-min))
12584 (setq res (append res (org-scan-tags func matcher))))))))))
12585 res))
12587 ;;;; Properties
12589 ;;; Setting and retrieving properties
12591 (defconst org-special-properties
12592 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12593 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
12594 "The special properties valid in Org-mode.
12596 These are properties that are not defined in the property drawer,
12597 but in some other way.")
12599 (defconst org-default-properties
12600 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12601 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12602 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12603 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12604 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12605 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
12606 "Some properties that are used by Org-mode for various purposes.
12607 Being in this list makes sure that they are offered for completion.")
12609 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12610 "Regular expression matching the first line of a property drawer.")
12612 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12613 "Regular expression matching the last line of a property drawer.")
12615 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12616 "Regular expression matching the first line of a property drawer.")
12618 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12619 "Regular expression matching the first line of a property drawer.")
12621 (defconst org-property-drawer-re
12622 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12623 org-property-end-re "\\)\n?")
12624 "Matches an entire property drawer.")
12626 (defconst org-clock-drawer-re
12627 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12628 org-property-end-re "\\)\n?")
12629 "Matches an entire clock drawer.")
12631 (defun org-property-action ()
12632 "Do an action on properties."
12633 (interactive)
12634 (let (c)
12635 (org-at-property-p)
12636 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12637 (setq c (read-char-exclusive))
12638 (cond
12639 ((equal c ?s)
12640 (call-interactively 'org-set-property))
12641 ((equal c ?d)
12642 (call-interactively 'org-delete-property))
12643 ((equal c ?D)
12644 (call-interactively 'org-delete-property-globally))
12645 ((equal c ?c)
12646 (call-interactively 'org-compute-property-at-point))
12647 (t (error "No such property action %c" c)))))
12649 (defun org-set-effort (&optional value)
12650 "Set the effort property of the current entry.
12651 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12652 allowed value."
12653 (interactive "P")
12654 (if (equal value 0) (setq value 10))
12655 (let* ((completion-ignore-case t)
12656 (prop org-effort-property)
12657 (cur (org-entry-get nil prop))
12658 (allowed (org-property-get-allowed-values nil prop 'table))
12659 (existing (mapcar 'list (org-property-values prop)))
12661 (val (cond
12662 ((stringp value) value)
12663 ((and allowed (integerp value))
12664 (or (car (nth (1- value) allowed))
12665 (car (org-last allowed))))
12666 (allowed
12667 (message "Select 1-9,0, [RET%s]: %s"
12668 (if cur (concat "=" cur) "")
12669 (mapconcat 'car allowed " "))
12670 (setq rpl (read-char-exclusive))
12671 (if (equal rpl ?\r)
12673 (setq rpl (- rpl ?0))
12674 (if (equal rpl 0) (setq rpl 10))
12675 (if (and (> rpl 0) (<= rpl (length allowed)))
12676 (car (nth (1- rpl) allowed))
12677 (org-completing-read "Effort: " allowed nil))))
12679 (let (org-completion-use-ido org-completion-use-iswitchb)
12680 (org-completing-read
12681 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12682 (concat "[" cur "]") "")
12683 ": ")
12684 existing nil nil "" nil cur))))))
12685 (unless (equal (org-entry-get nil prop) val)
12686 (org-entry-put nil prop val))
12687 (message "%s is now %s" prop val)))
12689 (defun org-at-property-p ()
12690 "Is cursor inside a property drawer?"
12691 (save-excursion
12692 (beginning-of-line 1)
12693 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
12694 (let ((match (match-data)) ;; Keep match-data for use by calling
12695 (p (point)) ;; procedures.
12696 (range (unless (org-before-first-heading-p)
12697 (org-get-property-block))))
12698 (prog1 (and range (<= (car range) p) (< p (cdr range)))
12699 (set-match-data match))))))
12701 (defun org-get-property-block (&optional beg end force)
12702 "Return the (beg . end) range of the body of the property drawer.
12703 BEG and END can be beginning and end of subtree, if not given
12704 they will be found.
12705 If the drawer does not exist and FORCE is non-nil, create the drawer."
12706 (catch 'exit
12707 (save-excursion
12708 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12709 (end (or end (progn (outline-next-heading) (point)))))
12710 (goto-char beg)
12711 (if (re-search-forward org-property-start-re end t)
12712 (setq beg (1+ (match-end 0)))
12713 (if force
12714 (save-excursion
12715 (org-insert-property-drawer)
12716 (setq end (progn (outline-next-heading) (point))))
12717 (throw 'exit nil))
12718 (goto-char beg)
12719 (if (re-search-forward org-property-start-re end t)
12720 (setq beg (1+ (match-end 0)))))
12721 (if (re-search-forward org-property-end-re end t)
12722 (setq end (match-beginning 0))
12723 (or force (throw 'exit nil))
12724 (goto-char beg)
12725 (setq end beg)
12726 (org-indent-line-function)
12727 (insert ":END:\n"))
12728 (cons beg end)))))
12730 (defun org-entry-properties (&optional pom which specific)
12731 "Get all properties of the entry at point-or-marker POM.
12732 This includes the TODO keyword, the tags, time strings for deadline,
12733 scheduled, and clocking, and any additional properties defined in the
12734 entry. The return value is an alist, keys may occur multiple times
12735 if the property key was used several times.
12736 POM may also be nil, in which case the current entry is used.
12737 If WHICH is nil or `all', get all properties. If WHICH is
12738 `special' or `standard', only get that subclass. If WHICH
12739 is a string only get exactly this property. Specific can be a string, the
12740 specific property we are interested in. Specifying it can speed
12741 things up because then unnecessary parsing is avoided."
12742 (setq which (or which 'all))
12743 (org-with-point-at pom
12744 (let ((clockstr (substring org-clock-string 0 -1))
12745 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
12746 (case-fold-search nil)
12747 beg end range props sum-props key value string clocksum)
12748 (save-excursion
12749 (when (condition-case nil
12750 (and (org-mode-p) (org-back-to-heading t))
12751 (error nil))
12752 (setq beg (point))
12753 (setq sum-props (get-text-property (point) 'org-summaries))
12754 (setq clocksum (get-text-property (point) :org-clock-minutes))
12755 (outline-next-heading)
12756 (setq end (point))
12757 (when (memq which '(all special))
12758 ;; Get the special properties, like TODO and tags
12759 (goto-char beg)
12760 (when (and (or (not specific) (string= specific "TODO"))
12761 (looking-at org-todo-line-regexp) (match-end 2))
12762 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12763 (when (and (or (not specific) (string= specific "PRIORITY"))
12764 (looking-at org-priority-regexp))
12765 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12766 (when (and (or (not specific) (string= specific "TAGS"))
12767 (setq value (org-get-tags-string))
12768 (string-match "\\S-" value))
12769 (push (cons "TAGS" value) props))
12770 (when (and (or (not specific) (string= specific "ALLTAGS"))
12771 (setq value (org-get-tags-at)))
12772 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
12773 ":"))
12774 props))
12775 (when (or (not specific) (string= specific "BLOCKED"))
12776 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
12777 (when (or (not specific)
12778 (member specific org-all-time-keywords)
12779 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
12780 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12781 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12782 string (if (equal key clockstr)
12783 (org-no-properties
12784 (org-trim
12785 (buffer-substring
12786 (match-beginning 3) (goto-char (point-at-eol)))))
12787 (substring (org-match-string-no-properties 3) 1 -1)))
12788 (unless key
12789 (if (= (char-after (match-beginning 3)) ?\[)
12790 (setq key "TIMESTAMP_IA")
12791 (setq key "TIMESTAMP")))
12792 (when (or (equal key clockstr) (not (assoc key props)))
12793 (push (cons key string) props))))
12797 (when (memq which '(all standard))
12798 ;; Get the standard properties, like :PROP: ...
12799 (setq range (org-get-property-block beg end))
12800 (when range
12801 (goto-char (car range))
12802 (while (re-search-forward
12803 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12804 (cdr range) t)
12805 (setq key (org-match-string-no-properties 1)
12806 value (org-trim (or (org-match-string-no-properties 2) "")))
12807 (unless (member key excluded)
12808 (push (cons key (or value "")) props)))))
12809 (if clocksum
12810 (push (cons "CLOCKSUM"
12811 (org-columns-number-to-string (/ (float clocksum) 60.)
12812 'add_times))
12813 props))
12814 (unless (assoc "CATEGORY" props)
12815 (setq value (or (org-get-category)
12816 (progn (org-refresh-category-properties)
12817 (org-get-category))))
12818 (push (cons "CATEGORY" value) props))
12819 (append sum-props (nreverse props)))))))
12821 (defun org-entry-get (pom property &optional inherit)
12822 "Get value of PROPERTY for entry at point-or-marker POM.
12823 If INHERIT is non-nil and the entry does not have the property,
12824 then also check higher levels of the hierarchy.
12825 If INHERIT is the symbol `selective', use inheritance only if the setting
12826 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12827 If the property is present but empty, the return value is the empty string.
12828 If the property is not present at all, nil is returned."
12829 (org-with-point-at pom
12830 (if (and inherit (if (eq inherit 'selective)
12831 (org-property-inherit-p property)
12833 (org-entry-get-with-inheritance property)
12834 (if (member property org-special-properties)
12835 ;; We need a special property. Use `org-entry-properties' to
12836 ;; retrieve it, but specify the wanted property
12837 (cdr (assoc property (org-entry-properties nil 'special property)))
12838 (let ((range (org-get-property-block)))
12839 (if (and range
12840 (goto-char (car range))
12841 (re-search-forward
12842 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12843 (cdr range) t))
12844 ;; Found the property, return it.
12845 (if (match-end 1)
12846 (org-match-string-no-properties 1)
12847 "")))))))
12849 (defun org-property-or-variable-value (var &optional inherit)
12850 "Check if there is a property fixing the value of VAR.
12851 If yes, return this value. If not, return the current value of the variable."
12852 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12853 (if (and prop (stringp prop) (string-match "\\S-" prop))
12854 (read prop)
12855 (symbol-value var))))
12857 (defun org-entry-delete (pom property)
12858 "Delete the property PROPERTY from entry at point-or-marker POM."
12859 (org-with-point-at pom
12860 (if (member property org-special-properties)
12861 nil ; cannot delete these properties.
12862 (let ((range (org-get-property-block)))
12863 (if (and range
12864 (goto-char (car range))
12865 (re-search-forward
12866 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12867 (cdr range) t))
12868 (progn
12869 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12871 nil)))))
12873 ;; Multi-values properties are properties that contain multiple values
12874 ;; These values are assumed to be single words, separated by whitespace.
12875 (defun org-entry-add-to-multivalued-property (pom property value)
12876 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12877 (let* ((old (org-entry-get pom property))
12878 (values (and old (org-split-string old "[ \t]"))))
12879 (setq value (org-entry-protect-space value))
12880 (unless (member value values)
12881 (setq values (cons value values))
12882 (org-entry-put pom property
12883 (mapconcat 'identity values " ")))))
12885 (defun org-entry-remove-from-multivalued-property (pom property value)
12886 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12887 (let* ((old (org-entry-get pom property))
12888 (values (and old (org-split-string old "[ \t]"))))
12889 (setq value (org-entry-protect-space value))
12890 (when (member value values)
12891 (setq values (delete value values))
12892 (org-entry-put pom property
12893 (mapconcat 'identity values " ")))))
12895 (defun org-entry-member-in-multivalued-property (pom property value)
12896 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12897 (let* ((old (org-entry-get pom property))
12898 (values (and old (org-split-string old "[ \t]"))))
12899 (setq value (org-entry-protect-space value))
12900 (member value values)))
12902 (defun org-entry-get-multivalued-property (pom property)
12903 "Return a list of values in a multivalued property."
12904 (let* ((value (org-entry-get pom property))
12905 (values (and value (org-split-string value "[ \t]"))))
12906 (mapcar 'org-entry-restore-space values)))
12908 (defun org-entry-put-multivalued-property (pom property &rest values)
12909 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12910 VALUES should be a list of strings. Spaces will be protected."
12911 (org-entry-put pom property
12912 (mapconcat 'org-entry-protect-space values " "))
12913 (let* ((value (org-entry-get pom property))
12914 (values (and value (org-split-string value "[ \t]"))))
12915 (mapcar 'org-entry-restore-space values)))
12917 (defun org-entry-protect-space (s)
12918 "Protect spaces and newline in string S."
12919 (while (string-match " " s)
12920 (setq s (replace-match "%20" t t s)))
12921 (while (string-match "\n" s)
12922 (setq s (replace-match "%0A" t t s)))
12925 (defun org-entry-restore-space (s)
12926 "Restore spaces and newline in string S."
12927 (while (string-match "%20" s)
12928 (setq s (replace-match " " t t s)))
12929 (while (string-match "%0A" s)
12930 (setq s (replace-match "\n" t t s)))
12933 (defvar org-entry-property-inherited-from (make-marker)
12934 "Marker pointing to the entry from where a property was inherited.
12935 Each call to `org-entry-get-with-inheritance' will set this marker to the
12936 location of the entry where the inheritance search matched. If there was
12937 no match, the marker will point nowhere.
12938 Note that also `org-entry-get' calls this function, if the INHERIT flag
12939 is set.")
12941 (defun org-entry-get-with-inheritance (property)
12942 "Get entry property, and search higher levels if not present."
12943 (move-marker org-entry-property-inherited-from nil)
12944 (let (tmp)
12945 (save-excursion
12946 (save-restriction
12947 (widen)
12948 (catch 'ex
12949 (while t
12950 (when (setq tmp (org-entry-get nil property))
12951 (org-back-to-heading t)
12952 (move-marker org-entry-property-inherited-from (point))
12953 (throw 'ex tmp))
12954 (or (org-up-heading-safe) (throw 'ex nil)))))
12955 (or tmp
12956 (cdr (assoc property org-file-properties))
12957 (cdr (assoc property org-global-properties))
12958 (cdr (assoc property org-global-properties-fixed))))))
12960 (defvar org-property-changed-functions nil
12961 "Hook called when the value of a property has changed.
12962 Each hook function should accept two arguments, the name of the property
12963 and the new value.")
12965 (defun org-entry-put (pom property value)
12966 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12967 (org-with-point-at pom
12968 (org-back-to-heading t)
12969 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12970 range)
12971 (cond
12972 ((equal property "TODO")
12973 (when (and (stringp value) (string-match "\\S-" value)
12974 (not (member value org-todo-keywords-1)))
12975 (error "\"%s\" is not a valid TODO state" value))
12976 (if (or (not value)
12977 (not (string-match "\\S-" value)))
12978 (setq value 'none))
12979 (org-todo value)
12980 (org-set-tags nil 'align))
12981 ((equal property "PRIORITY")
12982 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12983 (string-to-char value) ?\ ))
12984 (org-set-tags nil 'align))
12985 ((equal property "SCHEDULED")
12986 (if (re-search-forward org-scheduled-time-regexp end t)
12987 (cond
12988 ((eq value 'earlier) (org-timestamp-change -1 'day))
12989 ((eq value 'later) (org-timestamp-change 1 'day))
12990 (t (call-interactively 'org-schedule)))
12991 (call-interactively 'org-schedule)))
12992 ((equal property "DEADLINE")
12993 (if (re-search-forward org-deadline-time-regexp end t)
12994 (cond
12995 ((eq value 'earlier) (org-timestamp-change -1 'day))
12996 ((eq value 'later) (org-timestamp-change 1 'day))
12997 (t (call-interactively 'org-deadline)))
12998 (call-interactively 'org-deadline)))
12999 ((member property org-special-properties)
13000 (error "The %s property can not yet be set with `org-entry-put'"
13001 property))
13002 (t ; a non-special property
13003 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13004 (setq range (org-get-property-block beg end 'force))
13005 (goto-char (car range))
13006 (if (re-search-forward
13007 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13008 (progn
13009 (delete-region (match-beginning 1) (match-end 1))
13010 (goto-char (match-beginning 1)))
13011 (goto-char (cdr range))
13012 (insert "\n")
13013 (backward-char 1)
13014 (org-indent-line-function)
13015 (insert ":" property ":"))
13016 (and value (insert " " value))
13017 (org-indent-line-function)))))
13018 (run-hook-with-args 'org-property-changed-functions property value)))
13020 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13021 "Get all property keys in the current buffer.
13022 With INCLUDE-SPECIALS, also list the special properties that reflect things
13023 like tags and TODO state.
13024 With INCLUDE-DEFAULTS, also include properties that has special meaning
13025 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
13026 With INCLUDE-COLUMNS, also include property names given in COLUMN
13027 formats in the current buffer."
13028 (let (rtn range cfmt s p)
13029 (save-excursion
13030 (save-restriction
13031 (widen)
13032 (goto-char (point-min))
13033 (while (re-search-forward org-property-start-re nil t)
13034 (setq range (org-get-property-block))
13035 (goto-char (car range))
13036 (while (re-search-forward
13037 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13038 (cdr range) t)
13039 (add-to-list 'rtn (org-match-string-no-properties 1)))
13040 (outline-next-heading))))
13042 (when include-specials
13043 (setq rtn (append org-special-properties rtn)))
13045 (when include-defaults
13046 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13047 (add-to-list 'rtn org-effort-property))
13049 (when include-columns
13050 (save-excursion
13051 (save-restriction
13052 (widen)
13053 (goto-char (point-min))
13054 (while (re-search-forward
13055 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13056 nil t)
13057 (setq cfmt (match-string 2) s 0)
13058 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13059 cfmt s)
13060 (setq s (match-end 0)
13061 p (match-string 1 cfmt))
13062 (unless (or (equal p "ITEM")
13063 (member p org-special-properties))
13064 (add-to-list 'rtn (match-string 1 cfmt))))))))
13066 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13068 (defun org-property-values (key)
13069 "Return a list of all values of property KEY."
13070 (save-excursion
13071 (save-restriction
13072 (widen)
13073 (goto-char (point-min))
13074 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
13075 values)
13076 (while (re-search-forward re nil t)
13077 (add-to-list 'values (org-trim (match-string 1))))
13078 (delete "" values)))))
13080 (defun org-insert-property-drawer ()
13081 "Insert a property drawer into the current entry."
13082 (interactive)
13083 (org-back-to-heading t)
13084 (looking-at outline-regexp)
13085 (let ((indent (if org-adapt-indentation
13086 (- (match-end 0)(match-beginning 0))
13088 (beg (point))
13089 (re (concat "^[ \t]*" org-keyword-time-regexp))
13090 end hiddenp)
13091 (outline-next-heading)
13092 (setq end (point))
13093 (goto-char beg)
13094 (while (re-search-forward re end t))
13095 (setq hiddenp (org-invisible-p))
13096 (end-of-line 1)
13097 (and (equal (char-after) ?\n) (forward-char 1))
13098 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
13099 (if (member (match-string 1) '("CLOCK:" ":END:"))
13100 ;; just skip this line
13101 (beginning-of-line 2)
13102 ;; Drawer start, find the end
13103 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
13104 (beginning-of-line 1)))
13105 (org-skip-over-state-notes)
13106 (skip-chars-backward " \t\n\r")
13107 (if (eq (char-before) ?*) (forward-char 1))
13108 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
13109 (beginning-of-line 0)
13110 (org-indent-to-column indent)
13111 (beginning-of-line 2)
13112 (org-indent-to-column indent)
13113 (beginning-of-line 0)
13114 (if hiddenp
13115 (save-excursion
13116 (org-back-to-heading t)
13117 (hide-entry))
13118 (org-flag-drawer t))))
13120 (defun org-set-property (property value)
13121 "In the current entry, set PROPERTY to VALUE.
13122 When called interactively, this will prompt for a property name, offering
13123 completion on existing and default properties. And then it will prompt
13124 for a value, offering completion either on allowed values (via an inherited
13125 xxx_ALL property) or on existing values in other instances of this property
13126 in the current file."
13127 (interactive
13128 (let* ((completion-ignore-case t)
13129 (keys (org-buffer-property-keys nil t t))
13130 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
13131 (prop (if (member prop0 keys)
13132 prop0
13133 (or (cdr (assoc (downcase prop0)
13134 (mapcar (lambda (x) (cons (downcase x) x))
13135 keys)))
13136 prop0)))
13137 (cur (org-entry-get nil prop))
13138 (prompt (concat prop " value"
13139 (if (and cur (string-match "\\S-" cur))
13140 (concat " [" cur "]") "") ": "))
13141 (allowed (org-property-get-allowed-values nil prop 'table))
13142 (existing (mapcar 'list (org-property-values prop)))
13143 (val (if allowed
13144 (org-completing-read prompt allowed nil
13145 (not (get-text-property 0 'org-unrestricted
13146 (caar allowed))))
13147 (let (org-completion-use-ido org-completion-use-iswitchb)
13148 (org-completing-read prompt existing nil nil "" nil cur)))))
13149 (list prop (if (equal val "") cur val))))
13150 (unless (equal (org-entry-get nil property) value)
13151 (org-entry-put nil property value)))
13153 (defun org-delete-property (property)
13154 "In the current entry, delete PROPERTY."
13155 (interactive
13156 (let* ((completion-ignore-case t)
13157 (prop (org-icompleting-read "Property: " (org-entry-properties nil 'standard))))
13158 (list prop)))
13159 (message "Property %s %s" property
13160 (if (org-entry-delete nil property)
13161 "deleted"
13162 "was not present in the entry")))
13164 (defun org-delete-property-globally (property)
13165 "Remove PROPERTY globally, from all entries."
13166 (interactive
13167 (let* ((completion-ignore-case t)
13168 (prop (org-icompleting-read
13169 "Globally remove property: "
13170 (mapcar 'list (org-buffer-property-keys)))))
13171 (list prop)))
13172 (save-excursion
13173 (save-restriction
13174 (widen)
13175 (goto-char (point-min))
13176 (let ((cnt 0))
13177 (while (re-search-forward
13178 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
13179 nil t)
13180 (setq cnt (1+ cnt))
13181 (replace-match ""))
13182 (message "Property \"%s\" removed from %d entries" property cnt)))))
13184 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
13186 (defun org-compute-property-at-point ()
13187 "Compute the property at point.
13188 This looks for an enclosing column format, extracts the operator and
13189 then applies it to the property in the column format's scope."
13190 (interactive)
13191 (unless (org-at-property-p)
13192 (error "Not at a property"))
13193 (let ((prop (org-match-string-no-properties 2)))
13194 (org-columns-get-format-and-top-level)
13195 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
13196 (error "No operator defined for property %s" prop))
13197 (org-columns-compute prop)))
13199 (defvar org-property-allowed-value-functions nil
13200 "Hook for functions supplying allowed values for a specific property.
13201 The functions must take a single argument, the name of the property, and
13202 return a flat list of allowed values. If \":ETC\" is one of
13203 the values, this means that these values are intended as defaults for
13204 completion, but that other values should be allowed too.
13205 The functions must return nil if they are not responsible for this
13206 property.")
13208 (defun org-property-get-allowed-values (pom property &optional table)
13209 "Get allowed values for the property PROPERTY.
13210 When TABLE is non-nil, return an alist that can directly be used for
13211 completion."
13212 (let (vals)
13213 (cond
13214 ((equal property "TODO")
13215 (setq vals (org-with-point-at pom
13216 (append org-todo-keywords-1 '("")))))
13217 ((equal property "PRIORITY")
13218 (let ((n org-lowest-priority))
13219 (while (>= n org-highest-priority)
13220 (push (char-to-string n) vals)
13221 (setq n (1- n)))))
13222 ((member property org-special-properties))
13223 ((setq vals (run-hook-with-args-until-success
13224 'org-property-allowed-value-functions property)))
13226 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13227 (when (and vals (string-match "\\S-" vals))
13228 (setq vals (car (read-from-string (concat "(" vals ")"))))
13229 (setq vals (mapcar (lambda (x)
13230 (cond ((stringp x) x)
13231 ((numberp x) (number-to-string x))
13232 ((symbolp x) (symbol-name x))
13233 (t "???")))
13234 vals)))))
13235 (when (member ":ETC" vals)
13236 (setq vals (remove ":ETC" vals))
13237 (org-add-props (car vals) '(org-unrestricted t)))
13238 (if table (mapcar 'list vals) vals)))
13240 (defun org-property-previous-allowed-value (&optional previous)
13241 "Switch to the next allowed value for this property."
13242 (interactive)
13243 (org-property-next-allowed-value t))
13245 (defun org-property-next-allowed-value (&optional previous)
13246 "Switch to the next allowed value for this property."
13247 (interactive)
13248 (unless (org-at-property-p)
13249 (error "Not at a property"))
13250 (let* ((key (match-string 2))
13251 (value (match-string 3))
13252 (allowed (or (org-property-get-allowed-values (point) key)
13253 (and (member value '("[ ]" "[-]" "[X]"))
13254 '("[ ]" "[X]"))))
13255 nval)
13256 (unless allowed
13257 (error "Allowed values for this property have not been defined"))
13258 (if previous (setq allowed (reverse allowed)))
13259 (if (member value allowed)
13260 (setq nval (car (cdr (member value allowed)))))
13261 (setq nval (or nval (car allowed)))
13262 (if (equal nval value)
13263 (error "Only one allowed value for this property"))
13264 (org-at-property-p)
13265 (replace-match (concat " :" key ": " nval) t t)
13266 (org-indent-line-function)
13267 (beginning-of-line 1)
13268 (skip-chars-forward " \t")
13269 (run-hook-with-args 'org-property-changed-functions key nval)))
13271 (defun org-find-entry-with-id (ident)
13272 "Locate the entry that contains the ID property with exact value IDENT.
13273 IDENT can be a string, a symbol or a number, this function will search for
13274 the string representation of it.
13275 Return the position where this entry starts, or nil if there is no such entry."
13276 (interactive "sID: ")
13277 (let ((id (cond
13278 ((stringp ident) ident)
13279 ((symbol-name ident) (symbol-name ident))
13280 ((numberp ident) (number-to-string ident))
13281 (t (error "IDENT %s must be a string, symbol or number" ident))))
13282 (case-fold-search nil))
13283 (save-excursion
13284 (save-restriction
13285 (widen)
13286 (goto-char (point-min))
13287 (when (re-search-forward
13288 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13289 nil t)
13290 (org-back-to-heading t)
13291 (point))))))
13293 ;;;; Timestamps
13295 (defvar org-last-changed-timestamp nil)
13296 (defvar org-last-inserted-timestamp nil
13297 "The last time stamp inserted with `org-insert-time-stamp'.")
13298 (defvar org-time-was-given) ; dynamically scoped parameter
13299 (defvar org-end-time-was-given) ; dynamically scoped parameter
13300 (defvar org-ts-what) ; dynamically scoped parameter
13302 (defun org-time-stamp (arg &optional inactive)
13303 "Prompt for a date/time and insert a time stamp.
13304 If the user specifies a time like HH:MM, or if this command is called
13305 with a prefix argument, the time stamp will contain date and time.
13306 Otherwise, only the date will be included. All parts of a date not
13307 specified by the user will be filled in from the current date/time.
13308 So if you press just return without typing anything, the time stamp
13309 will represent the current date/time. If there is already a timestamp
13310 at the cursor, it will be modified."
13311 (interactive "P")
13312 (let* ((ts nil)
13313 (default-time
13314 ;; Default time is either today, or, when entering a range,
13315 ;; the range start.
13316 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13317 (save-excursion
13318 (re-search-backward
13319 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13320 (- (point) 20) t)))
13321 (apply 'encode-time (org-parse-time-string (match-string 1)))
13322 (current-time)))
13323 (default-input (and ts (org-get-compact-tod ts)))
13324 org-time-was-given org-end-time-was-given time)
13325 (cond
13326 ((and (org-at-timestamp-p t)
13327 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13328 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13329 (insert "--")
13330 (setq time (let ((this-command this-command))
13331 (org-read-date arg 'totime nil nil
13332 default-time default-input)))
13333 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13334 ((org-at-timestamp-p t)
13335 (setq time (let ((this-command this-command))
13336 (org-read-date arg 'totime nil nil default-time default-input)))
13337 (when (org-at-timestamp-p t) ; just to get the match data
13338 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13339 (replace-match "")
13340 (setq org-last-changed-timestamp
13341 (org-insert-time-stamp
13342 time (or org-time-was-given arg)
13343 inactive nil nil (list org-end-time-was-given))))
13344 (message "Timestamp updated"))
13346 (setq time (let ((this-command this-command))
13347 (org-read-date arg 'totime nil nil default-time default-input)))
13348 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13349 nil nil (list org-end-time-was-given))))))
13351 ;; FIXME: can we use this for something else, like computing time differences?
13352 (defun org-get-compact-tod (s)
13353 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13354 (let* ((t1 (match-string 1 s))
13355 (h1 (string-to-number (match-string 2 s)))
13356 (m1 (string-to-number (match-string 3 s)))
13357 (t2 (and (match-end 4) (match-string 5 s)))
13358 (h2 (and t2 (string-to-number (match-string 6 s))))
13359 (m2 (and t2 (string-to-number (match-string 7 s))))
13360 dh dm)
13361 (if (not t2)
13363 (setq dh (- h2 h1) dm (- m2 m1))
13364 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13365 (concat t1 "+" (number-to-string dh)
13366 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13368 (defun org-time-stamp-inactive (&optional arg)
13369 "Insert an inactive time stamp.
13370 An inactive time stamp is enclosed in square brackets instead of angle
13371 brackets. It is inactive in the sense that it does not trigger agenda entries,
13372 does not link to the calendar and cannot be changed with the S-cursor keys.
13373 So these are more for recording a certain time/date."
13374 (interactive "P")
13375 (org-time-stamp arg 'inactive))
13377 (defvar org-date-ovl (org-make-overlay 1 1))
13378 (org-overlay-put org-date-ovl 'face 'org-warning)
13379 (org-detach-overlay org-date-ovl)
13381 (defvar org-ans1) ; dynamically scoped parameter
13382 (defvar org-ans2) ; dynamically scoped parameter
13384 (defvar org-plain-time-of-day-regexp) ; defined below
13386 (defvar org-overriding-default-time nil) ; dynamically scoped
13387 (defvar org-read-date-overlay nil)
13388 (defvar org-dcst nil) ; dynamically scoped
13389 (defvar org-read-date-history nil)
13390 (defvar org-read-date-final-answer nil)
13392 (defun org-read-date (&optional with-time to-time from-string prompt
13393 default-time default-input)
13394 "Read a date, possibly a time, and make things smooth for the user.
13395 The prompt will suggest to enter an ISO date, but you can also enter anything
13396 which will at least partially be understood by `parse-time-string'.
13397 Unrecognized parts of the date will default to the current day, month, year,
13398 hour and minute. If this command is called to replace a timestamp at point,
13399 of to enter the second timestamp of a range, the default time is taken from the
13400 existing stamp. For example,
13401 3-2-5 --> 2003-02-05
13402 feb 15 --> currentyear-02-15
13403 sep 12 9 --> 2009-09-12
13404 12:45 --> today 12:45
13405 22 sept 0:34 --> currentyear-09-22 0:34
13406 12 --> currentyear-currentmonth-12
13407 Fri --> nearest Friday (today or later)
13408 etc.
13410 Furthermore you can specify a relative date by giving, as the *first* thing
13411 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13412 change in days weeks, months, years.
13413 With a single plus or minus, the date is relative to today. With a double
13414 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13415 +4d --> four days from today
13416 +4 --> same as above
13417 +2w --> two weeks from today
13418 ++5 --> five days from default date
13420 The function understands only English month and weekday abbreviations,
13421 but this can be configured with the variables `parse-time-months' and
13422 `parse-time-weekdays'.
13424 While prompting, a calendar is popped up - you can also select the
13425 date with the mouse (button 1). The calendar shows a period of three
13426 months. To scroll it to other months, use the keys `>' and `<'.
13427 If you don't like the calendar, turn it off with
13428 \(setq org-read-date-popup-calendar nil)
13430 With optional argument TO-TIME, the date will immediately be converted
13431 to an internal time.
13432 With an optional argument WITH-TIME, the prompt will suggest to also
13433 insert a time. Note that when WITH-TIME is not set, you can still
13434 enter a time, and this function will inform the calling routine about
13435 this change. The calling routine may then choose to change the format
13436 used to insert the time stamp into the buffer to include the time.
13437 With optional argument FROM-STRING, read from this string instead from
13438 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13439 the time/date that is used for everything that is not specified by the
13440 user."
13441 (require 'parse-time)
13442 (let* ((org-time-stamp-rounding-minutes
13443 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13444 (org-dcst org-display-custom-times)
13445 (ct (org-current-time))
13446 (def (or org-overriding-default-time default-time ct))
13447 (defdecode (decode-time def))
13448 (dummy (progn
13449 (when (< (nth 2 defdecode) org-extend-today-until)
13450 (setcar (nthcdr 2 defdecode) -1)
13451 (setcar (nthcdr 1 defdecode) 59)
13452 (setq def (apply 'encode-time defdecode)
13453 defdecode (decode-time def)))))
13454 (calendar-frame-setup nil)
13455 (calendar-move-hook nil)
13456 (calendar-view-diary-initially-flag nil)
13457 (view-diary-entries-initially nil)
13458 (calendar-view-holidays-initially-flag nil)
13459 (view-calendar-holidays-initially nil)
13460 (timestr (format-time-string
13461 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
13462 (prompt (concat (if prompt (concat prompt " ") "")
13463 (format "Date+time [%s]: " timestr)))
13464 ans (org-ans0 "") org-ans1 org-ans2 final)
13466 (cond
13467 (from-string (setq ans from-string))
13468 (org-read-date-popup-calendar
13469 (save-excursion
13470 (save-window-excursion
13471 (calendar)
13472 (calendar-forward-day (- (time-to-days def)
13473 (calendar-absolute-from-gregorian
13474 (calendar-current-date))))
13475 (org-eval-in-calendar nil t)
13476 (let* ((old-map (current-local-map))
13477 (map (copy-keymap calendar-mode-map))
13478 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13479 (org-defkey map (kbd "RET") 'org-calendar-select)
13480 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
13481 'org-calendar-select-mouse)
13482 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
13483 'org-calendar-select-mouse)
13484 (org-defkey minibuffer-local-map [(meta shift left)]
13485 (lambda () (interactive)
13486 (org-eval-in-calendar '(calendar-backward-month 1))))
13487 (org-defkey minibuffer-local-map [(meta shift right)]
13488 (lambda () (interactive)
13489 (org-eval-in-calendar '(calendar-forward-month 1))))
13490 (org-defkey minibuffer-local-map [(meta shift up)]
13491 (lambda () (interactive)
13492 (org-eval-in-calendar '(calendar-backward-year 1))))
13493 (org-defkey minibuffer-local-map [(meta shift down)]
13494 (lambda () (interactive)
13495 (org-eval-in-calendar '(calendar-forward-year 1))))
13496 (org-defkey minibuffer-local-map [?\e (shift left)]
13497 (lambda () (interactive)
13498 (org-eval-in-calendar '(calendar-backward-month 1))))
13499 (org-defkey minibuffer-local-map [?\e (shift right)]
13500 (lambda () (interactive)
13501 (org-eval-in-calendar '(calendar-forward-month 1))))
13502 (org-defkey minibuffer-local-map [?\e (shift up)]
13503 (lambda () (interactive)
13504 (org-eval-in-calendar '(calendar-backward-year 1))))
13505 (org-defkey minibuffer-local-map [?\e (shift down)]
13506 (lambda () (interactive)
13507 (org-eval-in-calendar '(calendar-forward-year 1))))
13508 (org-defkey minibuffer-local-map [(shift up)]
13509 (lambda () (interactive)
13510 (org-eval-in-calendar '(calendar-backward-week 1))))
13511 (org-defkey minibuffer-local-map [(shift down)]
13512 (lambda () (interactive)
13513 (org-eval-in-calendar '(calendar-forward-week 1))))
13514 (org-defkey minibuffer-local-map [(shift left)]
13515 (lambda () (interactive)
13516 (org-eval-in-calendar '(calendar-backward-day 1))))
13517 (org-defkey minibuffer-local-map [(shift right)]
13518 (lambda () (interactive)
13519 (org-eval-in-calendar '(calendar-forward-day 1))))
13520 (org-defkey minibuffer-local-map ">"
13521 (lambda () (interactive)
13522 (org-eval-in-calendar '(scroll-calendar-left 1))))
13523 (org-defkey minibuffer-local-map "<"
13524 (lambda () (interactive)
13525 (org-eval-in-calendar '(scroll-calendar-right 1))))
13526 (run-hooks 'org-read-date-minibuffer-setup-hook)
13527 (unwind-protect
13528 (progn
13529 (use-local-map map)
13530 (add-hook 'post-command-hook 'org-read-date-display)
13531 (setq org-ans0 (read-string prompt default-input
13532 'org-read-date-history nil))
13533 ;; org-ans0: from prompt
13534 ;; org-ans1: from mouse click
13535 ;; org-ans2: from calendar motion
13536 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13537 (remove-hook 'post-command-hook 'org-read-date-display)
13538 (use-local-map old-map)
13539 (when org-read-date-overlay
13540 (org-delete-overlay org-read-date-overlay)
13541 (setq org-read-date-overlay nil)))))))
13543 (t ; Naked prompt only
13544 (unwind-protect
13545 (setq ans (read-string prompt default-input
13546 'org-read-date-history timestr))
13547 (when org-read-date-overlay
13548 (org-delete-overlay org-read-date-overlay)
13549 (setq org-read-date-overlay nil)))))
13551 (setq final (org-read-date-analyze ans def defdecode))
13552 (setq org-read-date-final-answer ans)
13554 (if to-time
13555 (apply 'encode-time final)
13556 (if (and (boundp 'org-time-was-given) org-time-was-given)
13557 (format "%04d-%02d-%02d %02d:%02d"
13558 (nth 5 final) (nth 4 final) (nth 3 final)
13559 (nth 2 final) (nth 1 final))
13560 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13562 (defvar def)
13563 (defvar defdecode)
13564 (defvar with-time)
13565 (defvar org-read-date-analyze-futurep nil)
13566 (defun org-read-date-display ()
13567 "Display the current date prompt interpretation in the minibuffer."
13568 (when org-read-date-display-live
13569 (when org-read-date-overlay
13570 (org-delete-overlay org-read-date-overlay))
13571 (let ((p (point)))
13572 (end-of-line 1)
13573 (while (not (equal (buffer-substring
13574 (max (point-min) (- (point) 4)) (point))
13575 " "))
13576 (insert " "))
13577 (goto-char p))
13578 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13579 " " (or org-ans1 org-ans2)))
13580 (org-end-time-was-given nil)
13581 (f (org-read-date-analyze ans def defdecode))
13582 (fmts (if org-dcst
13583 org-time-stamp-custom-formats
13584 org-time-stamp-formats))
13585 (fmt (if (or with-time
13586 (and (boundp 'org-time-was-given) org-time-was-given))
13587 (cdr fmts)
13588 (car fmts)))
13589 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13590 (when (and org-end-time-was-given
13591 (string-match org-plain-time-of-day-regexp txt))
13592 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13593 org-end-time-was-given
13594 (substring txt (match-end 0)))))
13595 (when org-read-date-analyze-futurep
13596 (setq txt (concat txt " (=>F)")))
13597 (setq org-read-date-overlay
13598 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13599 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13601 (defun org-read-date-analyze (ans def defdecode)
13602 "Analyse the combined answer of the date prompt."
13603 ;; FIXME: cleanup and comment
13604 (let ((nowdecode (decode-time (current-time)))
13605 delta deltan deltaw deltadef year month day
13606 hour minute second wday pm h2 m2 tl wday1
13607 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
13608 (setq org-read-date-analyze-futurep nil)
13609 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13610 (setq ans "+0"))
13612 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13613 (setq ans (replace-match "" t t ans)
13614 deltan (car delta)
13615 deltaw (nth 1 delta)
13616 deltadef (nth 2 delta)))
13618 ;; Check if there is an iso week date in there
13619 ;; If yes, store the info and postpone interpreting it until the rest
13620 ;; of the parsing is done
13621 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13622 (setq iso-year (if (match-end 1)
13623 (org-small-year-to-year
13624 (string-to-number (match-string 1 ans))))
13625 iso-weekday (if (match-end 3)
13626 (string-to-number (match-string 3 ans)))
13627 iso-week (string-to-number (match-string 2 ans)))
13628 (setq ans (replace-match "" t t ans)))
13630 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
13631 (when (string-match
13632 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13633 (setq year (if (match-end 2)
13634 (string-to-number (match-string 2 ans))
13635 (progn (setq kill-year t)
13636 (string-to-number (format-time-string "%Y"))))
13637 month (string-to-number (match-string 3 ans))
13638 day (string-to-number (match-string 4 ans)))
13639 (if (< year 100) (setq year (+ 2000 year)))
13640 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13641 t nil ans)))
13642 ;; Help matching american dates, like 5/30 or 5/30/7
13643 (when (string-match
13644 "^ *\\([0-3]?[0-9]\\)/\\([0-1]?[0-9]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
13645 (setq year (if (match-end 4)
13646 (string-to-number (match-string 4 ans))
13647 (progn (setq kill-year t)
13648 (string-to-number (format-time-string "%Y"))))
13649 month (string-to-number (match-string 1 ans))
13650 day (string-to-number (match-string 2 ans)))
13651 (if (< year 100) (setq year (+ 2000 year)))
13652 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13653 t nil ans)))
13654 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13655 ;; If there is a time with am/pm, and *no* time without it, we convert
13656 ;; so that matching will be successful.
13657 (loop for i from 1 to 2 do ; twice, for end time as well
13658 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13659 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13660 (setq hour (string-to-number (match-string 1 ans))
13661 minute (if (match-end 3)
13662 (string-to-number (match-string 3 ans))
13664 pm (equal ?p
13665 (string-to-char (downcase (match-string 4 ans)))))
13666 (if (and (= hour 12) (not pm))
13667 (setq hour 0)
13668 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13669 (setq ans (replace-match (format "%02d:%02d" hour minute)
13670 t t ans))))
13672 ;; Check if a time range is given as a duration
13673 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13674 (setq hour (string-to-number (match-string 1 ans))
13675 h2 (+ hour (string-to-number (match-string 3 ans)))
13676 minute (string-to-number (match-string 2 ans))
13677 m2 (+ minute (if (match-end 5) (string-to-number
13678 (match-string 5 ans))0)))
13679 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13680 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13681 t t ans)))
13683 ;; Check if there is a time range
13684 (when (boundp 'org-end-time-was-given)
13685 (setq org-time-was-given nil)
13686 (when (and (string-match org-plain-time-of-day-regexp ans)
13687 (match-end 8))
13688 (setq org-end-time-was-given (match-string 8 ans))
13689 (setq ans (concat (substring ans 0 (match-beginning 7))
13690 (substring ans (match-end 7))))))
13692 (setq tl (parse-time-string ans)
13693 day (or (nth 3 tl) (nth 3 defdecode))
13694 month (or (nth 4 tl)
13695 (if (and org-read-date-prefer-future
13696 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
13697 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
13698 (nth 4 defdecode)))
13699 year (or (and (not kill-year) (nth 5 tl))
13700 (if (and org-read-date-prefer-future
13701 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
13702 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
13703 (nth 5 defdecode)))
13704 hour (or (nth 2 tl) (nth 2 defdecode))
13705 minute (or (nth 1 tl) (nth 1 defdecode))
13706 second (or (nth 0 tl) 0)
13707 wday (nth 6 tl))
13709 (when (and (eq org-read-date-prefer-future 'time)
13710 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13711 (equal day (nth 3 nowdecode))
13712 (equal month (nth 4 nowdecode))
13713 (equal year (nth 5 nowdecode))
13714 (nth 2 tl)
13715 (or (< (nth 2 tl) (nth 2 nowdecode))
13716 (and (= (nth 2 tl) (nth 2 nowdecode))
13717 (nth 1 tl)
13718 (< (nth 1 tl) (nth 1 nowdecode)))))
13719 (setq day (1+ day)
13720 futurep t))
13722 ;; Special date definitions below
13723 (cond
13724 (iso-week
13725 ;; There was an iso week
13726 (require 'cal-iso)
13727 (setq futurep nil)
13728 (setq year (or iso-year year)
13729 day (or iso-weekday wday 1)
13730 wday nil ; to make sure that the trigger below does not match
13731 iso-date (calendar-gregorian-from-absolute
13732 (calendar-absolute-from-iso
13733 (list iso-week day year))))
13734 ; FIXME: Should we also push ISO weeks into the future?
13735 ; (when (and org-read-date-prefer-future
13736 ; (not iso-year)
13737 ; (< (calendar-absolute-from-gregorian iso-date)
13738 ; (time-to-days (current-time))))
13739 ; (setq year (1+ year)
13740 ; iso-date (calendar-gregorian-from-absolute
13741 ; (calendar-absolute-from-iso
13742 ; (list iso-week day year)))))
13743 (setq month (car iso-date)
13744 year (nth 2 iso-date)
13745 day (nth 1 iso-date)))
13746 (deltan
13747 (setq futurep nil)
13748 (unless deltadef
13749 (let ((now (decode-time (current-time))))
13750 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13751 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13752 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13753 ((equal deltaw "m") (setq month (+ month deltan)))
13754 ((equal deltaw "y") (setq year (+ year deltan)))))
13755 ((and wday (not (nth 3 tl)))
13756 (setq futurep nil)
13757 ;; Weekday was given, but no day, so pick that day in the week
13758 ;; on or after the derived date.
13759 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13760 (unless (equal wday wday1)
13761 (setq day (+ day (% (- wday wday1 -7) 7))))))
13762 (if (and (boundp 'org-time-was-given)
13763 (nth 2 tl))
13764 (setq org-time-was-given t))
13765 (if (< year 100) (setq year (+ 2000 year)))
13766 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13767 (setq org-read-date-analyze-futurep futurep)
13768 (list second minute hour day month year)))
13770 (defvar parse-time-weekdays)
13772 (defun org-read-date-get-relative (s today default)
13773 "Check string S for special relative date string.
13774 TODAY and DEFAULT are internal times, for today and for a default.
13775 Return shift list (N what def-flag)
13776 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13777 N is the number of WHATs to shift.
13778 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13779 the DEFAULT date rather than TODAY."
13780 (when (and
13781 (string-match
13782 (concat
13783 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13784 "\\([0-9]+\\)?"
13785 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13786 "\\([ \t]\\|$\\)") s)
13787 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13788 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13789 (string-to-char (substring (match-string 1 s) -1))
13790 ?+))
13791 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13792 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13793 (what (if (match-end 3) (match-string 3 s) "d"))
13794 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13795 (date (if rel default today))
13796 (wday (nth 6 (decode-time date)))
13797 delta)
13798 (if wday1
13799 (progn
13800 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13801 (if (= dir ?-) (setq delta (- delta 7)))
13802 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13803 (list delta "d" rel))
13804 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13806 (defun org-order-calendar-date-args (arg1 arg2 arg3)
13807 "Turn a user-specified date into the internal representation.
13808 The internal representation needed by the calendar is (month day year).
13809 This is a wrapper to handle the brain-dead convention in calendar that
13810 user function argument order change dependent on argument order."
13811 (if (boundp 'calendar-date-style)
13812 (cond
13813 ((eq calendar-date-style 'american)
13814 (list arg1 arg2 arg3))
13815 ((eq calendar-date-style 'european)
13816 (list arg2 arg1 arg3))
13817 ((eq calendar-date-style 'iso)
13818 (list arg2 arg3 arg1)))
13819 (if (org-bound-and-true-p european-calendar-style)
13820 (list arg2 arg1 arg3)
13821 (list arg1 arg2 arg3))))
13823 (defun org-eval-in-calendar (form &optional keepdate)
13824 "Eval FORM in the calendar window and return to current window.
13825 Also, store the cursor date in variable org-ans2."
13826 (let ((sf (selected-frame))
13827 (sw (selected-window)))
13828 (select-window (get-buffer-window "*Calendar*" t))
13829 (eval form)
13830 (when (and (not keepdate) (calendar-cursor-to-date))
13831 (let* ((date (calendar-cursor-to-date))
13832 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13833 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13834 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13835 (select-window sw)
13836 (org-select-frame-set-input-focus sf)))
13838 (defun org-calendar-select ()
13839 "Return to `org-read-date' with the date currently selected.
13840 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13841 (interactive)
13842 (when (calendar-cursor-to-date)
13843 (let* ((date (calendar-cursor-to-date))
13844 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13845 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13846 (if (active-minibuffer-window) (exit-minibuffer))))
13848 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13849 "Insert a date stamp for the date given by the internal TIME.
13850 WITH-HM means use the stamp format that includes the time of the day.
13851 INACTIVE means use square brackets instead of angular ones, so that the
13852 stamp will not contribute to the agenda.
13853 PRE and POST are optional strings to be inserted before and after the
13854 stamp.
13855 The command returns the inserted time stamp."
13856 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13857 stamp)
13858 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13859 (insert-before-markers (or pre ""))
13860 (insert-before-markers (setq stamp (format-time-string fmt time)))
13861 (when (listp extra)
13862 (setq extra (car extra))
13863 (if (and (stringp extra)
13864 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13865 (setq extra (format "-%02d:%02d"
13866 (string-to-number (match-string 1 extra))
13867 (string-to-number (match-string 2 extra))))
13868 (setq extra nil)))
13869 (when extra
13870 (backward-char 1)
13871 (insert-before-markers extra)
13872 (forward-char 1))
13873 (insert-before-markers (or post ""))
13874 (setq org-last-inserted-timestamp stamp)))
13876 (defun org-toggle-time-stamp-overlays ()
13877 "Toggle the use of custom time stamp formats."
13878 (interactive)
13879 (setq org-display-custom-times (not org-display-custom-times))
13880 (unless org-display-custom-times
13881 (let ((p (point-min)) (bmp (buffer-modified-p)))
13882 (while (setq p (next-single-property-change p 'display))
13883 (if (and (get-text-property p 'display)
13884 (eq (get-text-property p 'face) 'org-date))
13885 (remove-text-properties
13886 p (setq p (next-single-property-change p 'display))
13887 '(display t))))
13888 (set-buffer-modified-p bmp)))
13889 (if (featurep 'xemacs)
13890 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13891 (org-restart-font-lock)
13892 (setq org-table-may-need-update t)
13893 (if org-display-custom-times
13894 (message "Time stamps are overlayed with custom format")
13895 (message "Time stamp overlays removed")))
13897 (defun org-display-custom-time (beg end)
13898 "Overlay modified time stamp format over timestamp between BEG and END."
13899 (let* ((ts (buffer-substring beg end))
13900 t1 w1 with-hm tf time str w2 (off 0))
13901 (save-match-data
13902 (setq t1 (org-parse-time-string ts t))
13903 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13904 (setq off (- (match-end 0) (match-beginning 0)))))
13905 (setq end (- end off))
13906 (setq w1 (- end beg)
13907 with-hm (and (nth 1 t1) (nth 2 t1))
13908 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13909 time (org-fix-decoded-time t1)
13910 str (org-add-props
13911 (format-time-string
13912 (substring tf 1 -1) (apply 'encode-time time))
13913 nil 'mouse-face 'highlight)
13914 w2 (length str))
13915 (if (not (= w2 w1))
13916 (add-text-properties (1+ beg) (+ 2 beg)
13917 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13918 (if (featurep 'xemacs)
13919 (progn
13920 (put-text-property beg end 'invisible t)
13921 (put-text-property beg end 'end-glyph (make-glyph str)))
13922 (put-text-property beg end 'display str))))
13924 (defun org-translate-time (string)
13925 "Translate all timestamps in STRING to custom format.
13926 But do this only if the variable `org-display-custom-times' is set."
13927 (when org-display-custom-times
13928 (save-match-data
13929 (let* ((start 0)
13930 (re org-ts-regexp-both)
13931 t1 with-hm inactive tf time str beg end)
13932 (while (setq start (string-match re string start))
13933 (setq beg (match-beginning 0)
13934 end (match-end 0)
13935 t1 (save-match-data
13936 (org-parse-time-string (substring string beg end) t))
13937 with-hm (and (nth 1 t1) (nth 2 t1))
13938 inactive (equal (substring string beg (1+ beg)) "[")
13939 tf (funcall (if with-hm 'cdr 'car)
13940 org-time-stamp-custom-formats)
13941 time (org-fix-decoded-time t1)
13942 str (format-time-string
13943 (concat
13944 (if inactive "[" "<") (substring tf 1 -1)
13945 (if inactive "]" ">"))
13946 (apply 'encode-time time))
13947 string (replace-match str t t string)
13948 start (+ start (length str)))))))
13949 string)
13951 (defun org-fix-decoded-time (time)
13952 "Set 0 instead of nil for the first 6 elements of time.
13953 Don't touch the rest."
13954 (let ((n 0))
13955 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13957 (defun org-days-to-time (timestamp-string)
13958 "Difference between TIMESTAMP-STRING and now in days."
13959 (- (time-to-days (org-time-string-to-time timestamp-string))
13960 (time-to-days (current-time))))
13962 (defun org-deadline-close (timestamp-string &optional ndays)
13963 "Is the time in TIMESTAMP-STRING close to the current date?"
13964 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13965 (and (< (org-days-to-time timestamp-string) ndays)
13966 (not (org-entry-is-done-p))))
13968 (defun org-get-wdays (ts)
13969 "Get the deadline lead time appropriate for timestring TS."
13970 (cond
13971 ((<= org-deadline-warning-days 0)
13972 ;; 0 or negative, enforce this value no matter what
13973 (- org-deadline-warning-days))
13974 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13975 ;; lead time is specified.
13976 (floor (* (string-to-number (match-string 1 ts))
13977 (cdr (assoc (match-string 2 ts)
13978 '(("d" . 1) ("w" . 7)
13979 ("m" . 30.4) ("y" . 365.25)))))))
13980 ;; go for the default.
13981 (t org-deadline-warning-days)))
13983 (defun org-calendar-select-mouse (ev)
13984 "Return to `org-read-date' with the date currently selected.
13985 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13986 (interactive "e")
13987 (mouse-set-point ev)
13988 (when (calendar-cursor-to-date)
13989 (let* ((date (calendar-cursor-to-date))
13990 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13991 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13992 (if (active-minibuffer-window) (exit-minibuffer))))
13994 (defun org-check-deadlines (ndays)
13995 "Check if there are any deadlines due or past due.
13996 A deadline is considered due if it happens within `org-deadline-warning-days'
13997 days from today's date. If the deadline appears in an entry marked DONE,
13998 it is not shown. The prefix arg NDAYS can be used to test that many
13999 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
14000 (interactive "P")
14001 (let* ((org-warn-days
14002 (cond
14003 ((equal ndays '(4)) 100000)
14004 (ndays (prefix-numeric-value ndays))
14005 (t (abs org-deadline-warning-days))))
14006 (case-fold-search nil)
14007 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
14008 (callback
14009 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
14011 (message "%d deadlines past-due or due within %d days"
14012 (org-occur regexp nil callback)
14013 org-warn-days)))
14015 (defun org-check-before-date (date)
14016 "Check if there are deadlines or scheduled entries before DATE."
14017 (interactive (list (org-read-date)))
14018 (let ((case-fold-search nil)
14019 (regexp (concat "\\<\\(" org-deadline-string
14020 "\\|" org-scheduled-string
14021 "\\) *<\\([^>]+\\)>"))
14022 (callback
14023 (lambda () (time-less-p
14024 (org-time-string-to-time (match-string 2))
14025 (org-time-string-to-time date)))))
14026 (message "%d entries before %s"
14027 (org-occur regexp nil callback) date)))
14029 (defun org-check-after-date (date)
14030 "Check if there are deadlines or scheduled entries after DATE."
14031 (interactive (list (org-read-date)))
14032 (let ((case-fold-search nil)
14033 (regexp (concat "\\<\\(" org-deadline-string
14034 "\\|" org-scheduled-string
14035 "\\) *<\\([^>]+\\)>"))
14036 (callback
14037 (lambda () (not
14038 (time-less-p
14039 (org-time-string-to-time (match-string 2))
14040 (org-time-string-to-time date))))))
14041 (message "%d entries after %s"
14042 (org-occur regexp nil callback) date)))
14044 (defun org-evaluate-time-range (&optional to-buffer)
14045 "Evaluate a time range by computing the difference between start and end.
14046 Normally the result is just printed in the echo area, but with prefix arg
14047 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
14048 If the time range is actually in a table, the result is inserted into the
14049 next column.
14050 For time difference computation, a year is assumed to be exactly 365
14051 days in order to avoid rounding problems."
14052 (interactive "P")
14054 (org-clock-update-time-maybe)
14055 (save-excursion
14056 (unless (org-at-date-range-p t)
14057 (goto-char (point-at-bol))
14058 (re-search-forward org-tr-regexp-both (point-at-eol) t))
14059 (if (not (org-at-date-range-p t))
14060 (error "Not at a time-stamp range, and none found in current line")))
14061 (let* ((ts1 (match-string 1))
14062 (ts2 (match-string 2))
14063 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
14064 (match-end (match-end 0))
14065 (time1 (org-time-string-to-time ts1))
14066 (time2 (org-time-string-to-time ts2))
14067 (t1 (org-float-time time1))
14068 (t2 (org-float-time time2))
14069 (diff (abs (- t2 t1)))
14070 (negative (< (- t2 t1) 0))
14071 ;; (ys (floor (* 365 24 60 60)))
14072 (ds (* 24 60 60))
14073 (hs (* 60 60))
14074 (fy "%dy %dd %02d:%02d")
14075 (fy1 "%dy %dd")
14076 (fd "%dd %02d:%02d")
14077 (fd1 "%dd")
14078 (fh "%02d:%02d")
14079 y d h m align)
14080 (if havetime
14081 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14083 d (floor (/ diff ds)) diff (mod diff ds)
14084 h (floor (/ diff hs)) diff (mod diff hs)
14085 m (floor (/ diff 60)))
14086 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14088 d (floor (+ (/ diff ds) 0.5))
14089 h 0 m 0))
14090 (if (not to-buffer)
14091 (message "%s" (org-make-tdiff-string y d h m))
14092 (if (org-at-table-p)
14093 (progn
14094 (goto-char match-end)
14095 (setq align t)
14096 (and (looking-at " *|") (goto-char (match-end 0))))
14097 (goto-char match-end))
14098 (if (looking-at
14099 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
14100 (replace-match ""))
14101 (if negative (insert " -"))
14102 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
14103 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
14104 (insert " " (format fh h m))))
14105 (if align (org-table-align))
14106 (message "Time difference inserted")))))
14108 (defun org-make-tdiff-string (y d h m)
14109 (let ((fmt "")
14110 (l nil))
14111 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
14112 l (push y l)))
14113 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
14114 l (push d l)))
14115 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
14116 l (push h l)))
14117 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
14118 l (push m l)))
14119 (apply 'format fmt (nreverse l))))
14121 (defun org-time-string-to-time (s)
14122 (apply 'encode-time (org-parse-time-string s)))
14123 (defun org-time-string-to-seconds (s)
14124 (org-float-time (org-time-string-to-time s)))
14126 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
14127 "Convert a time stamp to an absolute day number.
14128 If there is a specifyer for a cyclic time stamp, get the closest date to
14129 DAYNR.
14130 PREFER and SHOW-ALL are passed through to `org-closest-date'.
14131 the variable date is bound by the calendar when this is called."
14132 (cond
14133 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
14134 (if (org-diary-sexp-entry (match-string 1 s) "" date)
14135 daynr
14136 (+ daynr 1000)))
14137 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
14138 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
14139 (time-to-days (current-time))) (match-string 0 s)
14140 prefer show-all))
14141 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
14143 (defun org-days-to-iso-week (days)
14144 "Return the iso week number."
14145 (require 'cal-iso)
14146 (car (calendar-iso-from-absolute days)))
14148 (defun org-small-year-to-year (year)
14149 "Convert 2-digit years into 4-digit years.
14150 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
14151 The year 2000 cannot be abbreviated. Any year larger than 99
14152 is returned unchanged."
14153 (if (< year 38)
14154 (setq year (+ 2000 year))
14155 (if (< year 100)
14156 (setq year (+ 1900 year))))
14157 year)
14159 (defun org-time-from-absolute (d)
14160 "Return the time corresponding to date D.
14161 D may be an absolute day number, or a calendar-type list (month day year)."
14162 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
14163 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
14165 (defun org-calendar-holiday ()
14166 "List of holidays, for Diary display in Org-mode."
14167 (require 'holidays)
14168 (let ((hl (funcall
14169 (if (fboundp 'calendar-check-holidays)
14170 'calendar-check-holidays 'check-calendar-holidays) date)))
14171 (if hl (mapconcat 'identity hl "; "))))
14173 (defun org-diary-sexp-entry (sexp entry date)
14174 "Process a SEXP diary ENTRY for DATE."
14175 (require 'diary-lib)
14176 (let ((result (if calendar-debug-sexp
14177 (let ((stack-trace-on-error t))
14178 (eval (car (read-from-string sexp))))
14179 (condition-case nil
14180 (eval (car (read-from-string sexp)))
14181 (error
14182 (beep)
14183 (message "Bad sexp at line %d in %s: %s"
14184 (org-current-line)
14185 (buffer-file-name) sexp)
14186 (sleep-for 2))))))
14187 (cond ((stringp result) result)
14188 ((and (consp result)
14189 (stringp (cdr result))) (cdr result))
14190 (result entry)
14191 (t nil))))
14193 (defun org-diary-to-ical-string (frombuf)
14194 "Get iCalendar entries from diary entries in buffer FROMBUF.
14195 This uses the icalendar.el library."
14196 (let* ((tmpdir (if (featurep 'xemacs)
14197 (temp-directory)
14198 temporary-file-directory))
14199 (tmpfile (make-temp-name
14200 (expand-file-name "orgics" tmpdir)))
14201 buf rtn b e)
14202 (with-current-buffer frombuf
14203 (icalendar-export-region (point-min) (point-max) tmpfile)
14204 (setq buf (find-buffer-visiting tmpfile))
14205 (set-buffer buf)
14206 (goto-char (point-min))
14207 (if (re-search-forward "^BEGIN:VEVENT" nil t)
14208 (setq b (match-beginning 0)))
14209 (goto-char (point-max))
14210 (if (re-search-backward "^END:VEVENT" nil t)
14211 (setq e (match-end 0)))
14212 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
14213 (kill-buffer buf)
14214 (delete-file tmpfile)
14215 rtn))
14217 (defun org-closest-date (start current change prefer show-all)
14218 "Find the date closest to CURRENT that is consistent with START and CHANGE.
14219 When PREFER is `past' return a date that is either CURRENT or past.
14220 When PREFER is `future', return a date that is either CURRENT or future.
14221 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
14222 ;; Make the proper lists from the dates
14223 (catch 'exit
14224 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
14225 dn dw sday cday n1 n2 n0
14226 d m y y1 y2 date1 date2 nmonths nm ny m2)
14228 (setq start (org-date-to-gregorian start)
14229 current (org-date-to-gregorian
14230 (if show-all
14231 current
14232 (time-to-days (current-time))))
14233 sday (calendar-absolute-from-gregorian start)
14234 cday (calendar-absolute-from-gregorian current))
14236 (if (<= cday sday) (throw 'exit sday))
14238 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
14239 (setq dn (string-to-number (match-string 1 change))
14240 dw (cdr (assoc (match-string 2 change) a1)))
14241 (error "Invalid change specifyer: %s" change))
14242 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
14243 (cond
14244 ((eq dw 'day)
14245 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
14246 n2 (+ n1 dn)))
14247 ((eq dw 'year)
14248 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
14249 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
14250 (setq date1 (list m d y1)
14251 n1 (calendar-absolute-from-gregorian date1)
14252 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
14253 n2 (calendar-absolute-from-gregorian date2)))
14254 ((eq dw 'month)
14255 ;; approx number of month between the two dates
14256 (setq nmonths (floor (/ (- cday sday) 30.436875)))
14257 ;; How often does dn fit in there?
14258 (setq d (nth 1 start) m (car start) y (nth 2 start)
14259 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
14260 m (+ m nm)
14261 ny (floor (/ m 12))
14262 y (+ y ny)
14263 m (- m (* ny 12)))
14264 (while (> m 12) (setq m (- m 12) y (1+ y)))
14265 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14266 (setq m2 (+ m dn) y2 y)
14267 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14268 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14269 (while (<= n2 cday)
14270 (setq n1 n2 m m2 y y2)
14271 (setq m2 (+ m dn) y2 y)
14272 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14273 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14274 ;; Make sure n1 is the earlier date
14275 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14276 (if show-all
14277 (cond
14278 ((eq prefer 'past) (if (= cday n2) n2 n1))
14279 ((eq prefer 'future) (if (= cday n1) n1 n2))
14280 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14281 (cond
14282 ((eq prefer 'past) (if (= cday n2) n2 n1))
14283 ((eq prefer 'future) (if (= cday n1) n1 n2))
14284 (t (if (= cday n1) n1 n2)))))))
14286 (defun org-date-to-gregorian (date)
14287 "Turn any specification of DATE into a gregorian date for the calendar."
14288 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14289 ((and (listp date) (= (length date) 3)) date)
14290 ((stringp date)
14291 (setq date (org-parse-time-string date))
14292 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14293 ((listp date)
14294 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14296 (defun org-parse-time-string (s &optional nodefault)
14297 "Parse the standard Org-mode time string.
14298 This should be a lot faster than the normal `parse-time-string'.
14299 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14300 hour and minute fields will be nil if not given."
14301 (if (string-match org-ts-regexp0 s)
14302 (list 0
14303 (if (or (match-beginning 8) (not nodefault))
14304 (string-to-number (or (match-string 8 s) "0")))
14305 (if (or (match-beginning 7) (not nodefault))
14306 (string-to-number (or (match-string 7 s) "0")))
14307 (string-to-number (match-string 4 s))
14308 (string-to-number (match-string 3 s))
14309 (string-to-number (match-string 2 s))
14310 nil nil nil)
14311 (error "Not a standard Org-mode time string: %s" s)))
14313 (defun org-timestamp-up (&optional arg)
14314 "Increase the date item at the cursor by one.
14315 If the cursor is on the year, change the year. If it is on the month or
14316 the day, change that.
14317 With prefix ARG, change by that many units."
14318 (interactive "p")
14319 (org-timestamp-change (prefix-numeric-value arg)))
14321 (defun org-timestamp-down (&optional arg)
14322 "Decrease the date item at the cursor by one.
14323 If the cursor is on the year, change the year. If it is on the month or
14324 the day, change that.
14325 With prefix ARG, change by that many units."
14326 (interactive "p")
14327 (org-timestamp-change (- (prefix-numeric-value arg))))
14329 (defun org-timestamp-up-day (&optional arg)
14330 "Increase the date in the time stamp by one day.
14331 With prefix ARG, change that many days."
14332 (interactive "p")
14333 (if (and (not (org-at-timestamp-p t))
14334 (org-on-heading-p))
14335 (org-todo 'up)
14336 (org-timestamp-change (prefix-numeric-value arg) 'day)))
14338 (defun org-timestamp-down-day (&optional arg)
14339 "Decrease the date in the time stamp by one day.
14340 With prefix ARG, change that many days."
14341 (interactive "p")
14342 (if (and (not (org-at-timestamp-p t))
14343 (org-on-heading-p))
14344 (org-todo 'down)
14345 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
14347 (defun org-at-timestamp-p (&optional inactive-ok)
14348 "Determine if the cursor is in or at a timestamp."
14349 (interactive)
14350 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
14351 (pos (point))
14352 (ans (or (looking-at tsr)
14353 (save-excursion
14354 (skip-chars-backward "^[<\n\r\t")
14355 (if (> (point) (point-min)) (backward-char 1))
14356 (and (looking-at tsr)
14357 (> (- (match-end 0) pos) -1))))))
14358 (and ans
14359 (boundp 'org-ts-what)
14360 (setq org-ts-what
14361 (cond
14362 ((= pos (match-beginning 0)) 'bracket)
14363 ((= pos (1- (match-end 0))) 'bracket)
14364 ((org-pos-in-match-range pos 2) 'year)
14365 ((org-pos-in-match-range pos 3) 'month)
14366 ((org-pos-in-match-range pos 7) 'hour)
14367 ((org-pos-in-match-range pos 8) 'minute)
14368 ((or (org-pos-in-match-range pos 4)
14369 (org-pos-in-match-range pos 5)) 'day)
14370 ((and (> pos (or (match-end 8) (match-end 5)))
14371 (< pos (match-end 0)))
14372 (- pos (or (match-end 8) (match-end 5))))
14373 (t 'day))))
14374 ans))
14376 (defun org-toggle-timestamp-type ()
14377 "Toggle the type (<active> or [inactive]) of a time stamp."
14378 (interactive)
14379 (when (org-at-timestamp-p t)
14380 (let ((beg (match-beginning 0)) (end (match-end 0))
14381 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14382 (save-excursion
14383 (goto-char beg)
14384 (while (re-search-forward "[][<>]" end t)
14385 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14386 t t)))
14387 (message "Timestamp is now %sactive"
14388 (if (equal (char-after beg) ?<) "" "in")))))
14390 (defun org-timestamp-change (n &optional what)
14391 "Change the date in the time stamp at point.
14392 The date will be changed by N times WHAT. WHAT can be `day', `month',
14393 `year', `minute', `second'. If WHAT is not given, the cursor position
14394 in the timestamp determines what will be changed."
14395 (let ((pos (point))
14396 with-hm inactive
14397 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14398 org-ts-what
14399 extra rem
14400 ts time time0)
14401 (if (not (org-at-timestamp-p t))
14402 (error "Not at a timestamp"))
14403 (if (and (not what) (eq org-ts-what 'bracket))
14404 (org-toggle-timestamp-type)
14405 (if (and (not what) (not (eq org-ts-what 'day))
14406 org-display-custom-times
14407 (get-text-property (point) 'display)
14408 (not (get-text-property (1- (point)) 'display)))
14409 (setq org-ts-what 'day))
14410 (setq org-ts-what (or what org-ts-what)
14411 inactive (= (char-after (match-beginning 0)) ?\[)
14412 ts (match-string 0))
14413 (replace-match "")
14414 (if (string-match
14415 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14417 (setq extra (match-string 1 ts)))
14418 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14419 (setq with-hm t))
14420 (setq time0 (org-parse-time-string ts))
14421 (when (and (eq org-ts-what 'minute)
14422 (eq current-prefix-arg nil))
14423 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14424 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14425 (setcar (cdr time0) (+ (nth 1 time0)
14426 (if (> n 0) (- rem) (- dm rem))))))
14427 (setq time
14428 (encode-time (or (car time0) 0)
14429 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14430 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14431 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14432 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14433 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14434 (nthcdr 6 time0)))
14435 (when (and (member org-ts-what '(hour minute))
14436 extra
14437 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14438 (setq extra (org-modify-ts-extra
14439 extra
14440 (if (eq org-ts-what 'hour) 2 5)
14441 n dm)))
14442 (when (integerp org-ts-what)
14443 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14444 (if (eq what 'calendar)
14445 (let ((cal-date (org-get-date-from-calendar)))
14446 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14447 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14448 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14449 (setcar time0 (or (car time0) 0))
14450 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
14451 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
14452 (setq time (apply 'encode-time time0))))
14453 (setq org-last-changed-timestamp
14454 (org-insert-time-stamp time with-hm inactive nil nil extra))
14455 (org-clock-update-time-maybe)
14456 (goto-char pos)
14457 ;; Try to recenter the calendar window, if any
14458 (if (and org-calendar-follow-timestamp-change
14459 (get-buffer-window "*Calendar*" t)
14460 (memq org-ts-what '(day month year)))
14461 (org-recenter-calendar (time-to-days time))))))
14463 (defun org-modify-ts-extra (s pos n dm)
14464 "Change the different parts of the lead-time and repeat fields in timestamp."
14465 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
14466 ng h m new rem)
14467 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
14468 (cond
14469 ((or (org-pos-in-match-range pos 2)
14470 (org-pos-in-match-range pos 3))
14471 (setq m (string-to-number (match-string 3 s))
14472 h (string-to-number (match-string 2 s)))
14473 (if (org-pos-in-match-range pos 2)
14474 (setq h (+ h n))
14475 (setq n (* dm (org-no-warnings (signum n))))
14476 (when (not (= 0 (setq rem (% m dm))))
14477 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
14478 (setq m (+ m n)))
14479 (if (< m 0) (setq m (+ m 60) h (1- h)))
14480 (if (> m 59) (setq m (- m 60) h (1+ h)))
14481 (setq h (min 24 (max 0 h)))
14482 (setq ng 1 new (format "-%02d:%02d" h m)))
14483 ((org-pos-in-match-range pos 6)
14484 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
14485 ((org-pos-in-match-range pos 5)
14486 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
14488 ((org-pos-in-match-range pos 9)
14489 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
14490 ((org-pos-in-match-range pos 8)
14491 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
14493 (when ng
14494 (setq s (concat
14495 (substring s 0 (match-beginning ng))
14497 (substring s (match-end ng))))))
14500 (defun org-recenter-calendar (date)
14501 "If the calendar is visible, recenter it to DATE."
14502 (let* ((win (selected-window))
14503 (cwin (get-buffer-window "*Calendar*" t))
14504 (calendar-move-hook nil))
14505 (when cwin
14506 (select-window cwin)
14507 (calendar-goto-date (if (listp date) date
14508 (calendar-gregorian-from-absolute date)))
14509 (select-window win))))
14511 (defun org-goto-calendar (&optional arg)
14512 "Go to the Emacs calendar at the current date.
14513 If there is a time stamp in the current line, go to that date.
14514 A prefix ARG can be used to force the current date."
14515 (interactive "P")
14516 (let ((tsr org-ts-regexp) diff
14517 (calendar-move-hook nil)
14518 (calendar-view-holidays-initially-flag nil)
14519 (view-calendar-holidays-initially nil)
14520 (calendar-view-diary-initially-flag nil)
14521 (view-diary-entries-initially nil))
14522 (if (or (org-at-timestamp-p)
14523 (save-excursion
14524 (beginning-of-line 1)
14525 (looking-at (concat ".*" tsr))))
14526 (let ((d1 (time-to-days (current-time)))
14527 (d2 (time-to-days
14528 (org-time-string-to-time (match-string 1)))))
14529 (setq diff (- d2 d1))))
14530 (calendar)
14531 (calendar-goto-today)
14532 (if (and diff (not arg)) (calendar-forward-day diff))))
14534 (defun org-get-date-from-calendar ()
14535 "Return a list (month day year) of date at point in calendar."
14536 (with-current-buffer "*Calendar*"
14537 (save-match-data
14538 (calendar-cursor-to-date))))
14540 (defun org-date-from-calendar ()
14541 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14542 If there is already a time stamp at the cursor position, update it."
14543 (interactive)
14544 (if (org-at-timestamp-p t)
14545 (org-timestamp-change 0 'calendar)
14546 (let ((cal-date (org-get-date-from-calendar)))
14547 (org-insert-time-stamp
14548 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14550 (defun org-minutes-to-hh:mm-string (m)
14551 "Compute H:MM from a number of minutes."
14552 (let ((h (/ m 60)))
14553 (setq m (- m (* 60 h)))
14554 (format org-time-clocksum-format h m)))
14556 (defun org-hh:mm-string-to-minutes (s)
14557 "Convert a string H:MM to a number of minutes.
14558 If the string is just a number, interpret it as minutes.
14559 In fact, the first hh:mm or number in the string will be taken,
14560 there can be extra stuff in the string.
14561 If no number is found, the return value is 0."
14562 (cond
14563 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14564 (+ (* (string-to-number (match-string 1 s)) 60)
14565 (string-to-number (match-string 2 s))))
14566 ((string-match "\\([0-9]+\\)" s)
14567 (string-to-number (match-string 1 s)))
14568 (t 0)))
14570 ;;;; Files
14572 (defun org-save-all-org-buffers ()
14573 "Save all Org-mode buffers without user confirmation."
14574 (interactive)
14575 (message "Saving all Org-mode buffers...")
14576 (save-some-buffers t 'org-mode-p)
14577 (when (featurep 'org-id) (org-id-locations-save))
14578 (message "Saving all Org-mode buffers... done"))
14580 (defun org-revert-all-org-buffers ()
14581 "Revert all Org-mode buffers.
14582 Prompt for confirmation when there are unsaved changes.
14583 Be sure you know what you are doing before letting this function
14584 overwrite your changes.
14586 This function is useful in a setup where one tracks org files
14587 with a version control system, to revert on one machine after pulling
14588 changes from another. I believe the procedure must be like this:
14590 1. M-x org-save-all-org-buffers
14591 2. Pull changes from the other machine, resolve conflicts
14592 3. M-x org-revert-all-org-buffers"
14593 (interactive)
14594 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14595 (error "Abort"))
14596 (save-excursion
14597 (save-window-excursion
14598 (mapc
14599 (lambda (b)
14600 (when (and (with-current-buffer b (org-mode-p))
14601 (with-current-buffer b buffer-file-name))
14602 (switch-to-buffer b)
14603 (revert-buffer t 'no-confirm)))
14604 (buffer-list))
14605 (when (and (featurep 'org-id) org-id-track-globally)
14606 (org-id-locations-load)))))
14608 ;;;; Agenda files
14610 ;;;###autoload
14611 (defun org-iswitchb (&optional arg)
14612 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14613 With a prefix argument, restrict available to files.
14614 With two prefix arguments, restrict available buffers to agenda files."
14615 (interactive "P")
14616 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14617 ((equal arg '(16)) (org-buffer-list 'agenda))
14618 (t (org-buffer-list)))))
14619 (switch-to-buffer
14620 (org-icompleting-read "Org buffer: "
14621 (mapcar 'list (mapcar 'buffer-name blist))
14622 nil t))))
14624 ;;;###autoload
14625 (defalias 'org-ido-switchb 'org-iswitchb)
14627 (defun org-buffer-list (&optional predicate exclude-tmp)
14628 "Return a list of Org buffers.
14629 PREDICATE can be `export', `files' or `agenda'.
14631 export restrict the list to Export buffers.
14632 files restrict the list to buffers visiting Org files.
14633 agenda restrict the list to buffers visiting agenda files.
14635 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14636 (let* ((bfn nil)
14637 (agenda-files (and (eq predicate 'agenda)
14638 (mapcar 'file-truename (org-agenda-files t))))
14639 (filter
14640 (cond
14641 ((eq predicate 'files)
14642 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14643 ((eq predicate 'export)
14644 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14645 ((eq predicate 'agenda)
14646 (lambda (b)
14647 (with-current-buffer b
14648 (and (eq major-mode 'org-mode)
14649 (setq bfn (buffer-file-name b))
14650 (member (file-truename bfn) agenda-files)))))
14651 (t (lambda (b) (with-current-buffer b
14652 (or (eq major-mode 'org-mode)
14653 (string-match "\*Org .*Export"
14654 (buffer-name b)))))))))
14655 (delq nil
14656 (mapcar
14657 (lambda(b)
14658 (if (and (funcall filter b)
14659 (or (not exclude-tmp)
14660 (not (string-match "tmp" (buffer-name b)))))
14662 nil))
14663 (buffer-list)))))
14665 (defun org-agenda-files (&optional unrestricted archives)
14666 "Get the list of agenda files.
14667 Optional UNRESTRICTED means return the full list even if a restriction
14668 is currently in place.
14669 When ARCHIVES is t, include all archive files that are really being
14670 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14671 `org-agenda-archives-mode' is t."
14672 (let ((files
14673 (cond
14674 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14675 ((stringp org-agenda-files) (org-read-agenda-file-list))
14676 ((listp org-agenda-files) org-agenda-files)
14677 (t (error "Invalid value of `org-agenda-files'")))))
14678 (setq files (apply 'append
14679 (mapcar (lambda (f)
14680 (if (file-directory-p f)
14681 (directory-files
14682 f t org-agenda-file-regexp)
14683 (list f)))
14684 files)))
14685 (when org-agenda-skip-unavailable-files
14686 (setq files (delq nil
14687 (mapcar (function
14688 (lambda (file)
14689 (and (file-readable-p file) file)))
14690 files))))
14691 (when (or (eq archives t)
14692 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14693 (setq files (org-add-archive-files files)))
14694 files))
14696 (defun org-edit-agenda-file-list ()
14697 "Edit the list of agenda files.
14698 Depending on setup, this either uses customize to edit the variable
14699 `org-agenda-files', or it visits the file that is holding the list. In the
14700 latter case, the buffer is set up in a way that saving it automatically kills
14701 the buffer and restores the previous window configuration."
14702 (interactive)
14703 (if (stringp org-agenda-files)
14704 (let ((cw (current-window-configuration)))
14705 (find-file org-agenda-files)
14706 (org-set-local 'org-window-configuration cw)
14707 (org-add-hook 'after-save-hook
14708 (lambda ()
14709 (set-window-configuration
14710 (prog1 org-window-configuration
14711 (kill-buffer (current-buffer))))
14712 (org-install-agenda-files-menu)
14713 (message "New agenda file list installed"))
14714 nil 'local)
14715 (message "%s" (substitute-command-keys
14716 "Edit list and finish with \\[save-buffer]")))
14717 (customize-variable 'org-agenda-files)))
14719 (defun org-store-new-agenda-file-list (list)
14720 "Set new value for the agenda file list and save it correctly."
14721 (if (stringp org-agenda-files)
14722 (let ((fe (org-read-agenda-file-list t)) b u)
14723 (while (setq b (find-buffer-visiting org-agenda-files))
14724 (kill-buffer b))
14725 (with-temp-file org-agenda-files
14726 (insert
14727 (mapconcat
14728 (lambda (f) ;; Keep un-expanded entries.
14729 (if (setq u (assoc f fe))
14730 (cdr u)
14732 list "\n")
14733 "\n")))
14734 (let ((org-mode-hook nil) (org-inhibit-startup t)
14735 (org-insert-mode-line-in-empty-file nil))
14736 (setq org-agenda-files list)
14737 (customize-save-variable 'org-agenda-files org-agenda-files))))
14739 (defun org-read-agenda-file-list (&optional pair-with-expansion)
14740 "Read the list of agenda files from a file.
14741 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
14742 filenames, used by `org-store-new-agenda-file-list' to write back
14743 un-expanded file names."
14744 (when (file-directory-p org-agenda-files)
14745 (error "`org-agenda-files' cannot be a single directory"))
14746 (when (stringp org-agenda-files)
14747 (with-temp-buffer
14748 (insert-file-contents org-agenda-files)
14749 (mapcar
14750 (lambda (f)
14751 (let ((e (expand-file-name (substitute-in-file-name f)
14752 org-directory)))
14753 (if pair-with-expansion
14754 (cons e f)
14755 e)))
14756 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
14758 ;;;###autoload
14759 (defun org-cycle-agenda-files ()
14760 "Cycle through the files in `org-agenda-files'.
14761 If the current buffer visits an agenda file, find the next one in the list.
14762 If the current buffer does not, find the first agenda file."
14763 (interactive)
14764 (let* ((fs (org-agenda-files t))
14765 (files (append fs (list (car fs))))
14766 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14767 file)
14768 (unless files (error "No agenda files"))
14769 (catch 'exit
14770 (while (setq file (pop files))
14771 (if (equal (file-truename file) tcf)
14772 (when (car files)
14773 (find-file (car files))
14774 (throw 'exit t))))
14775 (find-file (car fs)))
14776 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14778 (defun org-agenda-file-to-front (&optional to-end)
14779 "Move/add the current file to the top of the agenda file list.
14780 If the file is not present in the list, it is added to the front. If it is
14781 present, it is moved there. With optional argument TO-END, add/move to the
14782 end of the list."
14783 (interactive "P")
14784 (let ((org-agenda-skip-unavailable-files nil)
14785 (file-alist (mapcar (lambda (x)
14786 (cons (file-truename x) x))
14787 (org-agenda-files t)))
14788 (ctf (file-truename buffer-file-name))
14789 x had)
14790 (setq x (assoc ctf file-alist) had x)
14792 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14793 (if to-end
14794 (setq file-alist (append (delq x file-alist) (list x)))
14795 (setq file-alist (cons x (delq x file-alist))))
14796 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14797 (org-install-agenda-files-menu)
14798 (message "File %s to %s of agenda file list"
14799 (if had "moved" "added") (if to-end "end" "front"))))
14801 (defun org-remove-file (&optional file)
14802 "Remove current file from the list of files in variable `org-agenda-files'.
14803 These are the files which are being checked for agenda entries.
14804 Optional argument FILE means use this file instead of the current."
14805 (interactive)
14806 (let* ((org-agenda-skip-unavailable-files nil)
14807 (file (or file buffer-file-name))
14808 (true-file (file-truename file))
14809 (afile (abbreviate-file-name file))
14810 (files (delq nil (mapcar
14811 (lambda (x)
14812 (if (equal true-file
14813 (file-truename x))
14814 nil x))
14815 (org-agenda-files t)))))
14816 (if (not (= (length files) (length (org-agenda-files t))))
14817 (progn
14818 (org-store-new-agenda-file-list files)
14819 (org-install-agenda-files-menu)
14820 (message "Removed file: %s" afile))
14821 (message "File was not in list: %s (not removed)" afile))))
14823 (defun org-file-menu-entry (file)
14824 (vector file (list 'find-file file) t))
14826 (defun org-check-agenda-file (file)
14827 "Make sure FILE exists. If not, ask user what to do."
14828 (when (not (file-exists-p file))
14829 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14830 (abbreviate-file-name file))
14831 (let ((r (downcase (read-char-exclusive))))
14832 (cond
14833 ((equal r ?r)
14834 (org-remove-file file)
14835 (throw 'nextfile t))
14836 (t (error "Abort"))))))
14838 (defun org-get-agenda-file-buffer (file)
14839 "Get a buffer visiting FILE. If the buffer needs to be created, add
14840 it to the list of buffers which might be released later."
14841 (let ((buf (org-find-base-buffer-visiting file)))
14842 (if buf
14843 buf ; just return it
14844 ;; Make a new buffer and remember it
14845 (setq buf (find-file-noselect file))
14846 (if buf (push buf org-agenda-new-buffers))
14847 buf)))
14849 (defun org-release-buffers (blist)
14850 "Release all buffers in list, asking the user for confirmation when needed.
14851 When a buffer is unmodified, it is just killed. When modified, it is saved
14852 \(if the user agrees) and then killed."
14853 (let (buf file)
14854 (while (setq buf (pop blist))
14855 (setq file (buffer-file-name buf))
14856 (when (and (buffer-modified-p buf)
14857 file
14858 (y-or-n-p (format "Save file %s? " file)))
14859 (with-current-buffer buf (save-buffer)))
14860 (kill-buffer buf))))
14862 (defun org-prepare-agenda-buffers (files)
14863 "Create buffers for all agenda files, protect archived trees and comments."
14864 (interactive)
14865 (let ((pa '(:org-archived t))
14866 (pc '(:org-comment t))
14867 (pall '(:org-archived t :org-comment t))
14868 (inhibit-read-only t)
14869 (rea (concat ":" org-archive-tag ":"))
14870 bmp file re)
14871 (save-excursion
14872 (save-restriction
14873 (while (setq file (pop files))
14874 (catch 'nextfile
14875 (if (bufferp file)
14876 (set-buffer file)
14877 (org-check-agenda-file file)
14878 (set-buffer (org-get-agenda-file-buffer file)))
14879 (widen)
14880 (setq bmp (buffer-modified-p))
14881 (org-refresh-category-properties)
14882 (setq org-todo-keywords-for-agenda
14883 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14884 (setq org-done-keywords-for-agenda
14885 (append org-done-keywords-for-agenda org-done-keywords))
14886 (setq org-todo-keyword-alist-for-agenda
14887 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14888 (setq org-drawers-for-agenda
14889 (append org-drawers-for-agenda org-drawers))
14890 (setq org-tag-alist-for-agenda
14891 (append org-tag-alist-for-agenda org-tag-alist))
14893 (save-excursion
14894 (remove-text-properties (point-min) (point-max) pall)
14895 (when org-agenda-skip-archived-trees
14896 (goto-char (point-min))
14897 (while (re-search-forward rea nil t)
14898 (if (org-on-heading-p t)
14899 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14900 (goto-char (point-min))
14901 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14902 (while (re-search-forward re nil t)
14903 (add-text-properties
14904 (match-beginning 0) (org-end-of-subtree t) pc)))
14905 (set-buffer-modified-p bmp)))))
14906 (setq org-todo-keyword-alist-for-agenda
14907 (org-uniquify org-todo-keyword-alist-for-agenda)
14908 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14910 ;;;; Embedded LaTeX
14912 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14913 "Keymap for the minor `org-cdlatex-mode'.")
14915 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14916 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14917 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14918 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14919 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14921 (defvar org-cdlatex-texmathp-advice-is-done nil
14922 "Flag remembering if we have applied the advice to texmathp already.")
14924 (define-minor-mode org-cdlatex-mode
14925 "Toggle the minor `org-cdlatex-mode'.
14926 This mode supports entering LaTeX environment and math in LaTeX fragments
14927 in Org-mode.
14928 \\{org-cdlatex-mode-map}"
14929 nil " OCDL" nil
14930 (when org-cdlatex-mode (require 'cdlatex))
14931 (unless org-cdlatex-texmathp-advice-is-done
14932 (setq org-cdlatex-texmathp-advice-is-done t)
14933 (defadvice texmathp (around org-math-always-on activate)
14934 "Always return t in org-mode buffers.
14935 This is because we want to insert math symbols without dollars even outside
14936 the LaTeX math segments. If Orgmode thinks that point is actually inside
14937 an embedded LaTeX fragment, let texmathp do its job.
14938 \\[org-cdlatex-mode-map]"
14939 (interactive)
14940 (let (p)
14941 (cond
14942 ((not (org-mode-p)) ad-do-it)
14943 ((eq this-command 'cdlatex-math-symbol)
14944 (setq ad-return-value t
14945 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14947 (let ((p (org-inside-LaTeX-fragment-p)))
14948 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14949 (setq ad-return-value t
14950 texmathp-why '("Org-mode embedded math" . 0))
14951 (if p ad-do-it)))))))))
14953 (defun turn-on-org-cdlatex ()
14954 "Unconditionally turn on `org-cdlatex-mode'."
14955 (org-cdlatex-mode 1))
14957 (defun org-inside-LaTeX-fragment-p ()
14958 "Test if point is inside a LaTeX fragment.
14959 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14960 sequence appearing also before point.
14961 Even though the matchers for math are configurable, this function assumes
14962 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14963 delimiters are skipped when they have been removed by customization.
14964 The return value is nil, or a cons cell with the delimiter and
14965 and the position of this delimiter.
14967 This function does a reasonably good job, but can locally be fooled by
14968 for example currency specifications. For example it will assume being in
14969 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14970 fragments that are properly closed, but during editing, we have to live
14971 with the uncertainty caused by missing closing delimiters. This function
14972 looks only before point, not after."
14973 (catch 'exit
14974 (let ((pos (point))
14975 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14976 (lim (progn
14977 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14978 (point)))
14979 dd-on str (start 0) m re)
14980 (goto-char pos)
14981 (when dodollar
14982 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14983 re (nth 1 (assoc "$" org-latex-regexps)))
14984 (while (string-match re str start)
14985 (cond
14986 ((= (match-end 0) (length str))
14987 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14988 ((= (match-end 0) (- (length str) 5))
14989 (throw 'exit nil))
14990 (t (setq start (match-end 0))))))
14991 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14992 (goto-char pos)
14993 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14994 (and (match-beginning 2) (throw 'exit nil))
14995 ;; count $$
14996 (while (re-search-backward "\\$\\$" lim t)
14997 (setq dd-on (not dd-on)))
14998 (goto-char pos)
14999 (if dd-on (cons "$$" m))))))
15001 (defun org-inside-latex-macro-p ()
15002 "Is point inside a LaTeX macro or its arguments?"
15003 (save-match-data
15004 (org-in-regexp
15005 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
15007 (defun test ()
15008 (interactive)
15009 (message "%s" (org-inside-latex-macro-p)))
15011 (defun org-try-cdlatex-tab ()
15012 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15013 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15014 - inside a LaTeX fragment, or
15015 - after the first word in a line, where an abbreviation expansion could
15016 insert a LaTeX environment."
15017 (when org-cdlatex-mode
15018 (cond
15019 ((save-excursion
15020 (skip-chars-backward "a-zA-Z0-9*")
15021 (skip-chars-backward " \t")
15022 (bolp))
15023 (cdlatex-tab) t)
15024 ((org-inside-LaTeX-fragment-p)
15025 (cdlatex-tab) t)
15026 (t nil))))
15028 (defun org-cdlatex-underscore-caret (&optional arg)
15029 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15030 Revert to the normal definition outside of these fragments."
15031 (interactive "P")
15032 (if (org-inside-LaTeX-fragment-p)
15033 (call-interactively 'cdlatex-sub-superscript)
15034 (let (org-cdlatex-mode)
15035 (call-interactively (key-binding (vector last-input-event))))))
15037 (defun org-cdlatex-math-modify (&optional arg)
15038 "Execute `cdlatex-math-modify' in LaTeX fragments.
15039 Revert to the normal definition outside of these fragments."
15040 (interactive "P")
15041 (if (org-inside-LaTeX-fragment-p)
15042 (call-interactively 'cdlatex-math-modify)
15043 (let (org-cdlatex-mode)
15044 (call-interactively (key-binding (vector last-input-event))))))
15046 (defvar org-latex-fragment-image-overlays nil
15047 "List of overlays carrying the images of latex fragments.")
15048 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15050 (defun org-remove-latex-fragment-image-overlays ()
15051 "Remove all overlays with LaTeX fragment images in current buffer."
15052 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
15053 (setq org-latex-fragment-image-overlays nil))
15055 (defun org-preview-latex-fragment (&optional subtree)
15056 "Preview the LaTeX fragment at point, or all locally or globally.
15057 If the cursor is in a LaTeX fragment, create the image and overlay
15058 it over the source code. If there is no fragment at point, display
15059 all fragments in the current text, from one headline to the next. With
15060 prefix SUBTREE, display all fragments in the current subtree. With a
15061 double prefix `C-u C-u', or when the cursor is before the first headline,
15062 display all fragments in the buffer.
15063 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15064 (interactive "P")
15065 (org-remove-latex-fragment-image-overlays)
15066 (save-excursion
15067 (save-restriction
15068 (let (beg end at msg)
15069 (cond
15070 ((or (equal subtree '(16))
15071 (not (save-excursion
15072 (re-search-backward (concat "^" outline-regexp) nil t))))
15073 (setq beg (point-min) end (point-max)
15074 msg "Creating images for buffer...%s"))
15075 ((equal subtree '(4))
15076 (org-back-to-heading)
15077 (setq beg (point) end (org-end-of-subtree t)
15078 msg "Creating images for subtree...%s"))
15080 (if (setq at (org-inside-LaTeX-fragment-p))
15081 (goto-char (max (point-min) (- (cdr at) 2)))
15082 (org-back-to-heading))
15083 (setq beg (point) end (progn (outline-next-heading) (point))
15084 msg (if at "Creating image...%s"
15085 "Creating images for entry...%s"))))
15086 (message msg "")
15087 (narrow-to-region beg end)
15088 (goto-char beg)
15089 (org-format-latex
15090 (concat "ltxpng/" (file-name-sans-extension
15091 (file-name-nondirectory
15092 buffer-file-name)))
15093 default-directory 'overlays msg at 'forbuffer)
15094 (message msg "done. Use `C-c C-c' to remove images.")))))
15096 (defvar org-latex-regexps
15097 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15098 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15099 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15100 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15101 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15102 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15103 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
15104 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
15105 "Regular expressions for matching embedded LaTeX.")
15107 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
15108 "Replace LaTeX fragments with links to an image, and produce images.
15109 Some of the options can be changed using the variable
15110 `org-format-latex-options'."
15111 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15112 (let* ((prefixnodir (file-name-nondirectory prefix))
15113 (absprefix (expand-file-name prefix dir))
15114 (todir (file-name-directory absprefix))
15115 (opt org-format-latex-options)
15116 (matchers (plist-get opt :matchers))
15117 (re-list org-latex-regexps)
15118 (org-format-latex-header-extra
15119 (plist-get (org-infile-export-plist) :latex-header-extra))
15120 (cnt 0) txt hash link beg end re e checkdir
15121 executables-checked
15122 m n block linkfile movefile ov)
15123 ;; Check the different regular expressions
15124 (while (setq e (pop re-list))
15125 (setq m (car e) re (nth 1 e) n (nth 2 e)
15126 block (if (nth 3 e) "\n\n" ""))
15127 (when (member m matchers)
15128 (goto-char (point-min))
15129 (while (re-search-forward re nil t)
15130 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
15131 (not (get-text-property (match-beginning n)
15132 'org-protected))
15133 (or (not overlays)
15134 (not (eq (get-char-property (match-beginning n)
15135 'org-overlay-type)
15136 'org-latex-overlay))))
15137 (setq txt (match-string n)
15138 beg (match-beginning n) end (match-end n)
15139 cnt (1+ cnt))
15140 (let (print-length print-level) ; make sure full list is printed
15141 (setq hash (sha1 (prin1-to-string
15142 (list org-format-latex-header
15143 org-format-latex-header-extra
15144 org-export-latex-packages-alist
15145 org-format-latex-options
15146 forbuffer txt)))
15147 linkfile (format "%s_%s.png" prefix hash)
15148 movefile (format "%s_%s.png" absprefix hash)))
15149 (setq link (concat block "[[file:" linkfile "]]" block))
15150 (if msg (message msg cnt))
15151 (goto-char beg)
15152 (unless checkdir ; make sure the directory exists
15153 (setq checkdir t)
15154 (or (file-directory-p todir) (make-directory todir)))
15156 (unless executables-checked
15157 (org-check-external-command
15158 "latex" "needed to convert LaTeX fragments to images")
15159 (org-check-external-command
15160 "dvipng" "needed to convert LaTeX fragments to images")
15161 (setq executables-checked t))
15163 (unless (file-exists-p movefile)
15164 (org-create-formula-image
15165 txt movefile opt forbuffer))
15166 (if overlays
15167 (progn
15168 (mapc (lambda (o)
15169 (if (eq (org-overlay-get o 'org-overlay-type)
15170 'org-latex-overlay)
15171 (org-delete-overlay o)))
15172 (org-overlays-in beg end))
15173 (setq ov (org-make-overlay beg end))
15174 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
15175 (if (featurep 'xemacs)
15176 (progn
15177 (org-overlay-put ov 'invisible t)
15178 (org-overlay-put
15179 ov 'end-glyph
15180 (make-glyph (vector 'png :file movefile))))
15181 (org-overlay-put
15182 ov 'display
15183 (list 'image :type 'png :file movefile :ascent 'center)))
15184 (push ov org-latex-fragment-image-overlays)
15185 (goto-char end))
15186 (delete-region beg end)
15187 (insert (org-add-props link
15188 (list 'org-latex-src
15189 (replace-regexp-in-string "\"" "" txt)))))))))))
15191 ;; This function borrows from Ganesh Swami's latex2png.el
15192 (defun org-create-formula-image (string tofile options buffer)
15193 "This calls dvipng."
15194 (require 'org-latex)
15195 (let* ((tmpdir (if (featurep 'xemacs)
15196 (temp-directory)
15197 temporary-file-directory))
15198 (texfilebase (make-temp-name
15199 (expand-file-name "orgtex" tmpdir)))
15200 (texfile (concat texfilebase ".tex"))
15201 (dvifile (concat texfilebase ".dvi"))
15202 (pngfile (concat texfilebase ".png"))
15203 (fnh (if (featurep 'xemacs)
15204 (font-height (get-face-font 'default))
15205 (face-attribute 'default :height nil)))
15206 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
15207 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
15208 (fg (or (plist-get options (if buffer :foreground :html-foreground))
15209 "Black"))
15210 (bg (or (plist-get options (if buffer :background :html-background))
15211 "Transparent")))
15212 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
15213 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
15214 (with-temp-file texfile
15215 (insert org-format-latex-header
15216 (if org-export-latex-packages-alist
15217 (concat "\n"
15218 (mapconcat (lambda(p)
15219 (if (equal "" (car p))
15220 (format "\\usepackage{%s}" (cadr p))
15221 (format "\\usepackage[%s]{%s}"
15222 (car p) (cadr p))))
15223 org-export-latex-packages-alist "\n"))
15225 (if org-format-latex-header-extra
15226 (concat "\n" org-format-latex-header-extra)
15228 "\n\\begin{document}\n" string "\n\\end{document}\n"))
15229 (let ((dir default-directory))
15230 (condition-case nil
15231 (progn
15232 (cd tmpdir)
15233 (call-process "latex" nil nil nil texfile))
15234 (error nil))
15235 (cd dir))
15236 (if (not (file-exists-p dvifile))
15237 (progn (message "Failed to create dvi file from %s" texfile) nil)
15238 (condition-case nil
15239 (call-process "dvipng" nil nil nil
15240 "-fg" fg "-bg" bg
15241 "-D" dpi
15242 ;;"-x" scale "-y" scale
15243 "-T" "tight"
15244 "-o" pngfile
15245 dvifile)
15246 (error nil))
15247 (if (not (file-exists-p pngfile))
15248 (if org-format-latex-signal-error
15249 (error "Failed to create png file from %s" texfile)
15250 (message "Failed to create png file from %s" texfile)
15251 nil)
15252 ;; Use the requested file name and clean up
15253 (copy-file pngfile tofile 'replace)
15254 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15255 (delete-file (concat texfilebase e)))
15256 pngfile))))
15258 (defun org-dvipng-color (attr)
15259 "Return an rgb color specification for dvipng."
15260 (apply 'format "rgb %s %s %s"
15261 (mapcar 'org-normalize-color
15262 (color-values (face-attribute 'default attr nil)))))
15264 (defun org-normalize-color (value)
15265 "Return string to be used as color value for an RGB component."
15266 (format "%g" (/ value 65535.0)))
15268 ;;;; Key bindings
15270 ;; Make `C-c C-x' a prefix key
15271 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
15273 ;; TAB key with modifiers
15274 (org-defkey org-mode-map "\C-i" 'org-cycle)
15275 (org-defkey org-mode-map [(tab)] 'org-cycle)
15276 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
15277 (org-defkey org-mode-map [(meta tab)] 'org-complete)
15278 (org-defkey org-mode-map "\M-\t" 'org-complete)
15279 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
15280 ;; The following line is necessary under Suse GNU/Linux
15281 (unless (featurep 'xemacs)
15282 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
15283 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
15284 (define-key org-mode-map [backtab] 'org-shifttab)
15286 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
15287 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15288 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
15290 ;; Cursor keys with modifiers
15291 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
15292 (org-defkey org-mode-map [(meta right)] 'org-metaright)
15293 (org-defkey org-mode-map [(meta up)] 'org-metaup)
15294 (org-defkey org-mode-map [(meta down)] 'org-metadown)
15296 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15297 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
15298 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
15299 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
15301 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
15302 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
15303 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
15304 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
15306 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
15307 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
15309 ;;; Extra keys for tty access.
15310 ;; We only set them when really needed because otherwise the
15311 ;; menus don't show the simple keys
15313 (when (or org-use-extra-keys
15314 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
15315 (not window-system))
15316 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
15317 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
15318 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
15319 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
15320 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
15321 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
15322 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
15323 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
15324 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
15325 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
15326 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
15327 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
15328 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
15329 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
15330 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
15331 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
15332 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
15333 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
15334 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
15335 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
15336 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
15337 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
15338 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
15339 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
15340 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
15341 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
15342 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
15343 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
15345 ;; All the other keys
15347 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15348 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
15349 (if (boundp 'narrow-map)
15350 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
15351 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
15352 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
15353 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
15354 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
15355 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
15356 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
15357 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
15358 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
15359 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
15360 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
15361 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
15362 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
15363 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
15364 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
15365 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
15366 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15367 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
15368 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
15369 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
15370 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
15371 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
15372 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
15373 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
15374 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
15375 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
15376 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
15377 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
15378 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
15379 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
15380 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
15381 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
15382 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15383 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15384 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15385 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15386 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
15387 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
15388 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15389 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
15390 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
15391 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
15392 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
15393 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15394 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
15395 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
15396 (org-defkey org-mode-map "\C-c^" 'org-sort)
15397 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15398 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
15399 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
15400 (org-defkey org-mode-map "\C-m" 'org-return)
15401 (org-defkey org-mode-map "\C-j" 'org-return-indent)
15402 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
15403 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
15404 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
15405 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
15406 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
15407 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
15408 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15409 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15410 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
15411 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
15412 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
15413 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
15414 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
15415 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15416 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
15417 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
15418 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
15419 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
15420 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
15421 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
15423 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
15424 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15425 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15426 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15428 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
15429 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15430 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15431 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
15432 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15433 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15434 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15435 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15436 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15437 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15438 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
15439 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
15440 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
15441 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
15442 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
15444 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
15445 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
15446 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
15447 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
15449 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
15451 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
15453 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
15454 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
15456 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
15459 (when (featurep 'xemacs)
15460 (org-defkey org-mode-map 'button3 'popup-mode-menu))
15463 (defconst org-speed-commands-default
15465 ("Outline Navigation")
15466 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
15467 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
15468 ("f" . (org-speed-move-safe 'org-forward-same-level))
15469 ("b" . (org-speed-move-safe 'org-backward-same-level))
15470 ("u" . (org-speed-move-safe 'outline-up-heading))
15471 ("j" . org-goto)
15472 ("g" . (org-refile t))
15473 ("Outline Visibility")
15474 ("c" . org-cycle)
15475 ("C" . org-shifttab)
15476 (" " . org-display-outline-path)
15477 ("Outline Structure Editing")
15478 ("U" . org-shiftmetaup)
15479 ("D" . org-shiftmetadown)
15480 ("r" . org-metaright)
15481 ("l" . org-metaleft)
15482 ("R" . org-shiftmetaright)
15483 ("L" . org-shiftmetaleft)
15484 ("i" . (progn (forward-char 1) (call-interactively
15485 'org-insert-heading-respect-content)))
15486 ("^" . org-sort)
15487 ("w" . org-refile)
15488 ("a" . org-archive-subtree-default-with-confirmation)
15489 ("." . outline-mark-subtree)
15490 ("Clock Commands")
15491 ("I" . org-clock-in)
15492 ("O" . org-clock-out)
15493 ("Meta Data Editing")
15494 ("t" . org-todo)
15495 ("0" . (org-priority ?\ ))
15496 ("1" . (org-priority ?A))
15497 ("2" . (org-priority ?B))
15498 ("3" . (org-priority ?C))
15499 (";" . org-set-tags-command)
15500 ("e" . org-set-effort)
15501 ("Agenda Views etc")
15502 ("v" . org-agenda)
15503 ("/" . org-sparse-tree)
15504 ("Misc")
15505 ("o" . org-open-at-point)
15506 ("?" . org-speed-command-help)
15508 "The default speed commands.")
15510 (defun org-print-speed-command (e)
15511 (if (> (length (car e)) 1)
15512 (progn
15513 (princ "\n")
15514 (princ (car e))
15515 (princ "\n")
15516 (princ (make-string (length (car e)) ?-))
15517 (princ "\n"))
15518 (princ (car e))
15519 (princ " ")
15520 (if (symbolp (cdr e))
15521 (princ (symbol-name (cdr e)))
15522 (prin1 (cdr e)))
15523 (princ "\n")))
15525 (defun org-speed-command-help ()
15526 "Show the available speed commands."
15527 (interactive)
15528 (if (not org-use-speed-commands)
15529 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
15530 (with-output-to-temp-buffer "*Help*"
15531 (princ "User-defined Speed commands\n===========================\n")
15532 (mapc 'org-print-speed-command org-speed-commands-user)
15533 (princ "\n")
15534 (princ "Built-in Speed commands\n=======================\n")
15535 (mapc 'org-print-speed-command org-speed-commands-default))
15536 (with-current-buffer "*Help*"
15537 (setq truncate-lines t))))
15539 (defun org-speed-move-safe (cmd)
15540 "Execute CMD, but make sure that the cursor always ends up in a headline.
15541 If not, return to the original position and throw an error."
15542 (interactive)
15543 (let ((pos (point)))
15544 (call-interactively cmd)
15545 (unless (and (bolp) (org-on-heading-p))
15546 (goto-char pos)
15547 (error "Boundary reached while executing %s" cmd))))
15549 (defvar org-self-insert-command-undo-counter 0)
15551 (defvar org-table-auto-blank-field) ; defined in org-table.el
15552 (defvar org-speed-command nil)
15553 (defun org-self-insert-command (N)
15554 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15555 If the cursor is in a table looking at whitespace, the whitespace is
15556 overwritten, and the table is not marked as requiring realignment."
15557 (interactive "p")
15558 (cond
15559 ((and org-use-speed-commands
15560 (or (and (bolp) (looking-at outline-regexp))
15561 (and (functionp org-use-speed-commands)
15562 (funcall org-use-speed-commands)))
15563 (setq
15564 org-speed-command
15565 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15566 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15567 (cond
15568 ((commandp org-speed-command)
15569 (setq this-command org-speed-command)
15570 (call-interactively org-speed-command))
15571 ((functionp org-speed-command)
15572 (funcall org-speed-command))
15573 ((and org-speed-command (listp org-speed-command))
15574 (eval org-speed-command))
15575 (t (let (org-use-speed-commands)
15576 (call-interactively 'org-self-insert-command)))))
15577 ((and
15578 (org-table-p)
15579 (progn
15580 ;; check if we blank the field, and if that triggers align
15581 (and (featurep 'org-table) org-table-auto-blank-field
15582 (member last-command
15583 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15584 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15585 ;; got extra space, this field does not determine column width
15586 (let (org-table-may-need-update) (org-table-blank-field))
15587 ;; no extra space, this field may determine column width
15588 (org-table-blank-field)))
15590 (eq N 1)
15591 (looking-at "[^|\n]* |"))
15592 (let (org-table-may-need-update)
15593 (goto-char (1- (match-end 0)))
15594 (delete-backward-char 1)
15595 (goto-char (match-beginning 0))
15596 (self-insert-command N)))
15598 (setq org-table-may-need-update t)
15599 (self-insert-command N)
15600 (org-fix-tags-on-the-fly)
15601 (if org-self-insert-cluster-for-undo
15602 (if (not (eq last-command 'org-self-insert-command))
15603 (setq org-self-insert-command-undo-counter 1)
15604 (if (>= org-self-insert-command-undo-counter 20)
15605 (setq org-self-insert-command-undo-counter 1)
15606 (and (> org-self-insert-command-undo-counter 0)
15607 buffer-undo-list
15608 (not (cadr buffer-undo-list)) ; remove nil entry
15609 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15610 (setq org-self-insert-command-undo-counter
15611 (1+ org-self-insert-command-undo-counter))))))))
15613 (defun org-fix-tags-on-the-fly ()
15614 (when (and (equal (char-after (point-at-bol)) ?*)
15615 (org-on-heading-p))
15616 (org-align-tags-here org-tags-column)))
15618 (defun org-delete-backward-char (N)
15619 "Like `delete-backward-char', insert whitespace at field end in tables.
15620 When deleting backwards, in tables this function will insert whitespace in
15621 front of the next \"|\" separator, to keep the table aligned. The table will
15622 still be marked for re-alignment if the field did fill the entire column,
15623 because, in this case the deletion might narrow the column."
15624 (interactive "p")
15625 (if (and (org-table-p)
15626 (eq N 1)
15627 (string-match "|" (buffer-substring (point-at-bol) (point)))
15628 (looking-at ".*?|"))
15629 (let ((pos (point))
15630 (noalign (looking-at "[^|\n\r]* |"))
15631 (c org-table-may-need-update))
15632 (backward-delete-char N)
15633 (skip-chars-forward "^|")
15634 (insert " ")
15635 (goto-char (1- pos))
15636 ;; noalign: if there were two spaces at the end, this field
15637 ;; does not determine the width of the column.
15638 (if noalign (setq org-table-may-need-update c)))
15639 (backward-delete-char N)
15640 (org-fix-tags-on-the-fly)))
15642 (defun org-delete-char (N)
15643 "Like `delete-char', but insert whitespace at field end in tables.
15644 When deleting characters, in tables this function will insert whitespace in
15645 front of the next \"|\" separator, to keep the table aligned. The table will
15646 still be marked for re-alignment if the field did fill the entire column,
15647 because, in this case the deletion might narrow the column."
15648 (interactive "p")
15649 (if (and (org-table-p)
15650 (not (bolp))
15651 (not (= (char-after) ?|))
15652 (eq N 1))
15653 (if (looking-at ".*?|")
15654 (let ((pos (point))
15655 (noalign (looking-at "[^|\n\r]* |"))
15656 (c org-table-may-need-update))
15657 (replace-match (concat
15658 (substring (match-string 0) 1 -1)
15659 " |"))
15660 (goto-char pos)
15661 ;; noalign: if there were two spaces at the end, this field
15662 ;; does not determine the width of the column.
15663 (if noalign (setq org-table-may-need-update c)))
15664 (delete-char N))
15665 (delete-char N)
15666 (org-fix-tags-on-the-fly)))
15668 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15669 (put 'org-self-insert-command 'delete-selection t)
15670 (put 'orgtbl-self-insert-command 'delete-selection t)
15671 (put 'org-delete-char 'delete-selection 'supersede)
15672 (put 'org-delete-backward-char 'delete-selection 'supersede)
15673 (put 'org-yank 'delete-selection 'yank)
15675 ;; Make `flyspell-mode' delay after some commands
15676 (put 'org-self-insert-command 'flyspell-delayed t)
15677 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15678 (put 'org-delete-char 'flyspell-delayed t)
15679 (put 'org-delete-backward-char 'flyspell-delayed t)
15681 ;; Make pabbrev-mode expand after org-mode commands
15682 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15683 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15685 ;; How to do this: Measure non-white length of current string
15686 ;; If equal to column width, we should realign.
15688 (defun org-remap (map &rest commands)
15689 "In MAP, remap the functions given in COMMANDS.
15690 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15691 (let (new old)
15692 (while commands
15693 (setq old (pop commands) new (pop commands))
15694 (if (fboundp 'command-remapping)
15695 (org-defkey map (vector 'remap old) new)
15696 (substitute-key-definition old new map global-map)))))
15698 (when (eq org-enable-table-editor 'optimized)
15699 ;; If the user wants maximum table support, we need to hijack
15700 ;; some standard editing functions
15701 (org-remap org-mode-map
15702 'self-insert-command 'org-self-insert-command
15703 'delete-char 'org-delete-char
15704 'delete-backward-char 'org-delete-backward-char)
15705 (org-defkey org-mode-map "|" 'org-force-self-insert))
15707 (defvar org-ctrl-c-ctrl-c-hook nil
15708 "Hook for functions attaching themselves to `C-c C-c'.
15709 This can be used to add additional functionality to the C-c C-c key which
15710 executes context-dependent commands.
15711 Each function will be called with no arguments. The function must check
15712 if the context is appropriate for it to act. If yes, it should do its
15713 thing and then return a non-nil value. If the context is wrong,
15714 just do nothing and return nil.")
15716 (defvar org-tab-first-hook nil
15717 "Hook for functions to attach themselves to TAB.
15718 See `org-ctrl-c-ctrl-c-hook' for more information.
15719 This hook runs as the first action when TAB is pressed, even before
15720 `org-cycle' messes around with the `outline-regexp' to cater for
15721 inline tasks and plain list item folding.
15722 If any function in this hook returns t, not other actions like table
15723 field motion visibility cycling will be done.")
15725 (defvar org-tab-after-check-for-table-hook nil
15726 "Hook for functions to attach themselves to TAB.
15727 See `org-ctrl-c-ctrl-c-hook' for more information.
15728 This hook runs after it has been established that the cursor is not in a
15729 table, but before checking if the cursor is in a headline or if global cycling
15730 should be done.
15731 If any function in this hook returns t, not other actions like visibility
15732 cycling will be done.")
15734 (defvar org-tab-after-check-for-cycling-hook nil
15735 "Hook for functions to attach themselves to TAB.
15736 See `org-ctrl-c-ctrl-c-hook' for more information.
15737 This hook runs after it has been established that not table field motion and
15738 not visibility should be done because of current context. This is probably
15739 the place where a package like yasnippets can hook in.")
15741 (defvar org-tab-before-tab-emulation-hook nil
15742 "Hook for functions to attach themselves to TAB.
15743 See `org-ctrl-c-ctrl-c-hook' for more information.
15744 This hook runs after every other options for TAB have been exhausted, but
15745 before indentation and \t insertion takes place.")
15747 (defvar org-metaleft-hook nil
15748 "Hook for functions attaching themselves to `M-left'.
15749 See `org-ctrl-c-ctrl-c-hook' for more information.")
15750 (defvar org-metaright-hook nil
15751 "Hook for functions attaching themselves to `M-right'.
15752 See `org-ctrl-c-ctrl-c-hook' for more information.")
15753 (defvar org-metaup-hook nil
15754 "Hook for functions attaching themselves to `M-up'.
15755 See `org-ctrl-c-ctrl-c-hook' for more information.")
15756 (defvar org-metadown-hook nil
15757 "Hook for functions attaching themselves to `M-down'.
15758 See `org-ctrl-c-ctrl-c-hook' for more information.")
15759 (defvar org-shiftmetaleft-hook nil
15760 "Hook for functions attaching themselves to `M-S-left'.
15761 See `org-ctrl-c-ctrl-c-hook' for more information.")
15762 (defvar org-shiftmetaright-hook nil
15763 "Hook for functions attaching themselves to `M-S-right'.
15764 See `org-ctrl-c-ctrl-c-hook' for more information.")
15765 (defvar org-shiftmetaup-hook nil
15766 "Hook for functions attaching themselves to `M-S-up'.
15767 See `org-ctrl-c-ctrl-c-hook' for more information.")
15768 (defvar org-shiftmetadown-hook nil
15769 "Hook for functions attaching themselves to `M-S-down'.
15770 See `org-ctrl-c-ctrl-c-hook' for more information.")
15771 (defvar org-metareturn-hook nil
15772 "Hook for functions attaching themselves to `M-RET'.
15773 See `org-ctrl-c-ctrl-c-hook' for more information.")
15775 (defun org-modifier-cursor-error ()
15776 "Throw an error, a modified cursor command was applied in wrong context."
15777 (error "This command is active in special context like tables, headlines or items"))
15779 (defun org-shiftselect-error ()
15780 "Throw an error because Shift-Cursor command was applied in wrong context."
15781 (if (and (boundp 'shift-select-mode) shift-select-mode)
15782 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15783 (error "This command works only in special context like headlines or timestamps")))
15785 (defun org-call-for-shift-select (cmd)
15786 (let ((this-command-keys-shift-translated t))
15787 (call-interactively cmd)))
15789 (defun org-shifttab (&optional arg)
15790 "Global visibility cycling or move to previous table field.
15791 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15792 on context.
15793 See the individual commands for more information."
15794 (interactive "P")
15795 (cond
15796 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15797 ((integerp arg)
15798 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15799 (message "Content view to level: %d" arg)
15800 (org-content (prefix-numeric-value arg2))
15801 (setq org-cycle-global-status 'overview)))
15802 (t (call-interactively 'org-global-cycle))))
15804 (defun org-shiftmetaleft ()
15805 "Promote subtree or delete table column.
15806 Calls `org-promote-subtree', `org-outdent-item',
15807 or `org-table-delete-column', depending on context.
15808 See the individual commands for more information."
15809 (interactive)
15810 (cond
15811 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15812 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15813 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15814 ((org-at-item-p) (call-interactively 'org-outdent-item))
15815 (t (org-modifier-cursor-error))))
15817 (defun org-shiftmetaright ()
15818 "Demote subtree or insert table column.
15819 Calls `org-demote-subtree', `org-indent-item',
15820 or `org-table-insert-column', depending on context.
15821 See the individual commands for more information."
15822 (interactive)
15823 (cond
15824 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15825 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15826 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15827 ((org-at-item-p) (call-interactively 'org-indent-item))
15828 (t (org-modifier-cursor-error))))
15830 (defun org-shiftmetaup (&optional arg)
15831 "Move subtree up or kill table row.
15832 Calls `org-move-subtree-up' or `org-table-kill-row' or
15833 `org-move-item-up' depending on context. See the individual commands
15834 for more information."
15835 (interactive "P")
15836 (cond
15837 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15838 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15839 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15840 ((org-at-item-p) (call-interactively 'org-move-item-up))
15841 (t (org-modifier-cursor-error))))
15843 (defun org-shiftmetadown (&optional arg)
15844 "Move subtree down or insert table row.
15845 Calls `org-move-subtree-down' or `org-table-insert-row' or
15846 `org-move-item-down', depending on context. See the individual
15847 commands for more information."
15848 (interactive "P")
15849 (cond
15850 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15851 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15852 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15853 ((org-at-item-p) (call-interactively 'org-move-item-down))
15854 (t (org-modifier-cursor-error))))
15856 (defun org-metaleft (&optional arg)
15857 "Promote heading or move table column to left.
15858 Calls `org-do-promote' or `org-table-move-column', depending on context.
15859 With no specific context, calls the Emacs default `backward-word'.
15860 See the individual commands for more information."
15861 (interactive "P")
15862 (cond
15863 ((run-hook-with-args-until-success 'org-metaleft-hook))
15864 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15865 ((or (org-on-heading-p)
15866 (and (org-region-active-p)
15867 (save-excursion
15868 (goto-char (region-beginning))
15869 (org-on-heading-p))))
15870 (call-interactively 'org-do-promote))
15871 ((or (org-at-item-p)
15872 (and (org-region-active-p)
15873 (save-excursion
15874 (goto-char (region-beginning))
15875 (org-at-item-p))))
15876 (call-interactively 'org-outdent-item))
15877 (t (call-interactively 'backward-word))))
15879 (defun org-metaright (&optional arg)
15880 "Demote subtree or move table column to right.
15881 Calls `org-do-demote' or `org-table-move-column', depending on context.
15882 With no specific context, calls the Emacs default `forward-word'.
15883 See the individual commands for more information."
15884 (interactive "P")
15885 (cond
15886 ((run-hook-with-args-until-success 'org-metaright-hook))
15887 ((org-at-table-p) (call-interactively 'org-table-move-column))
15888 ((or (org-on-heading-p)
15889 (and (org-region-active-p)
15890 (save-excursion
15891 (goto-char (region-beginning))
15892 (org-on-heading-p))))
15893 (call-interactively 'org-do-demote))
15894 ((or (org-at-item-p)
15895 (and (org-region-active-p)
15896 (save-excursion
15897 (goto-char (region-beginning))
15898 (org-at-item-p))))
15899 (call-interactively 'org-indent-item))
15900 (t (call-interactively 'forward-word))))
15902 (defun org-metaup (&optional arg)
15903 "Move subtree up or move table row up.
15904 Calls `org-move-subtree-up' or `org-table-move-row' or
15905 `org-move-item-up', depending on context. See the individual commands
15906 for more information."
15907 (interactive "P")
15908 (cond
15909 ((run-hook-with-args-until-success 'org-metaup-hook))
15910 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15911 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15912 ((org-at-item-p) (call-interactively 'org-move-item-up))
15913 (t (transpose-lines 1) (beginning-of-line -1))))
15915 (defun org-metadown (&optional arg)
15916 "Move subtree down or move table row down.
15917 Calls `org-move-subtree-down' or `org-table-move-row' or
15918 `org-move-item-down', depending on context. See the individual
15919 commands for more information."
15920 (interactive "P")
15921 (cond
15922 ((run-hook-with-args-until-success 'org-metadown-hook))
15923 ((org-at-table-p) (call-interactively 'org-table-move-row))
15924 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15925 ((org-at-item-p) (call-interactively 'org-move-item-down))
15926 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15928 (defun org-shiftup (&optional arg)
15929 "Increase item in timestamp or increase priority of current headline.
15930 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15931 depending on context. See the individual commands for more information."
15932 (interactive "P")
15933 (cond
15934 ((and org-support-shift-select (org-region-active-p))
15935 (org-call-for-shift-select 'previous-line))
15936 ((org-at-timestamp-p t)
15937 (call-interactively (if org-edit-timestamp-down-means-later
15938 'org-timestamp-down 'org-timestamp-up)))
15939 ((and (not (eq org-support-shift-select 'always))
15940 org-enable-priority-commands
15941 (org-on-heading-p))
15942 (call-interactively 'org-priority-up))
15943 ((and (not org-support-shift-select) (org-at-item-p))
15944 (call-interactively 'org-previous-item))
15945 ((org-clocktable-try-shift 'up arg))
15946 (org-support-shift-select
15947 (org-call-for-shift-select 'previous-line))
15948 (t (org-shiftselect-error))))
15950 (defun org-shiftdown (&optional arg)
15951 "Decrease item in timestamp or decrease priority of current headline.
15952 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15953 depending on context. See the individual commands for more information."
15954 (interactive "P")
15955 (cond
15956 ((and org-support-shift-select (org-region-active-p))
15957 (org-call-for-shift-select 'next-line))
15958 ((org-at-timestamp-p t)
15959 (call-interactively (if org-edit-timestamp-down-means-later
15960 'org-timestamp-up 'org-timestamp-down)))
15961 ((and (not (eq org-support-shift-select 'always))
15962 org-enable-priority-commands
15963 (org-on-heading-p))
15964 (call-interactively 'org-priority-down))
15965 ((and (not org-support-shift-select) (org-at-item-p))
15966 (call-interactively 'org-next-item))
15967 ((org-clocktable-try-shift 'down arg))
15968 (org-support-shift-select
15969 (org-call-for-shift-select 'next-line))
15970 (t (org-shiftselect-error))))
15972 (defun org-shiftright (&optional arg)
15973 "Cycle the thing at point or in the current line, depending on context.
15974 Depending on context, this does one of the following:
15976 - switch a timestamp at point one day into the future
15977 - on a headline, switch to the next TODO keyword.
15978 - on an item, switch entire list to the next bullet type
15979 - on a property line, switch to the next allowed value
15980 - on a clocktable definition line, move time block into the future"
15981 (interactive "P")
15982 (cond
15983 ((and org-support-shift-select (org-region-active-p))
15984 (org-call-for-shift-select 'forward-char))
15985 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15986 ((and (not (eq org-support-shift-select 'always))
15987 (org-on-heading-p))
15988 (let ((org-inhibit-logging
15989 (not org-treat-S-cursor-todo-selection-as-state-change))
15990 (org-inhibit-blocking
15991 (not org-treat-S-cursor-todo-selection-as-state-change)))
15992 (org-call-with-arg 'org-todo 'right)))
15993 ((or (and org-support-shift-select
15994 (not (eq org-support-shift-select 'always))
15995 (org-at-item-bullet-p))
15996 (and (not org-support-shift-select) (org-at-item-p)))
15997 (org-call-with-arg 'org-cycle-list-bullet nil))
15998 ((and (not (eq org-support-shift-select 'always))
15999 (org-at-property-p))
16000 (call-interactively 'org-property-next-allowed-value))
16001 ((org-clocktable-try-shift 'right arg))
16002 (org-support-shift-select
16003 (org-call-for-shift-select 'forward-char))
16004 (t (org-shiftselect-error))))
16006 (defun org-shiftleft (&optional arg)
16007 "Cycle the thing at point or in the current line, depending on context.
16008 Depending on context, this does one of the following:
16010 - switch a timestamp at point one day into the past
16011 - on a headline, switch to the previous TODO keyword.
16012 - on an item, switch entire list to the previous bullet type
16013 - on a property line, switch to the previous allowed value
16014 - on a clocktable definition line, move time block into the past"
16015 (interactive "P")
16016 (cond
16017 ((and org-support-shift-select (org-region-active-p))
16018 (org-call-for-shift-select 'backward-char))
16019 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
16020 ((and (not (eq org-support-shift-select 'always))
16021 (org-on-heading-p))
16022 (let ((org-inhibit-logging
16023 (not org-treat-S-cursor-todo-selection-as-state-change))
16024 (org-inhibit-blocking
16025 (not org-treat-S-cursor-todo-selection-as-state-change)))
16026 (org-call-with-arg 'org-todo 'left)))
16027 ((or (and org-support-shift-select
16028 (not (eq org-support-shift-select 'always))
16029 (org-at-item-bullet-p))
16030 (and (not org-support-shift-select) (org-at-item-p)))
16031 (org-call-with-arg 'org-cycle-list-bullet 'previous))
16032 ((and (not (eq org-support-shift-select 'always))
16033 (org-at-property-p))
16034 (call-interactively 'org-property-previous-allowed-value))
16035 ((org-clocktable-try-shift 'left arg))
16036 (org-support-shift-select
16037 (org-call-for-shift-select 'backward-char))
16038 (t (org-shiftselect-error))))
16040 (defun org-shiftcontrolright ()
16041 "Switch to next TODO set."
16042 (interactive)
16043 (cond
16044 ((and org-support-shift-select (org-region-active-p))
16045 (org-call-for-shift-select 'forward-word))
16046 ((and (not (eq org-support-shift-select 'always))
16047 (org-on-heading-p))
16048 (org-call-with-arg 'org-todo 'nextset))
16049 (org-support-shift-select
16050 (org-call-for-shift-select 'forward-word))
16051 (t (org-shiftselect-error))))
16053 (defun org-shiftcontrolleft ()
16054 "Switch to previous TODO set."
16055 (interactive)
16056 (cond
16057 ((and org-support-shift-select (org-region-active-p))
16058 (org-call-for-shift-select 'backward-word))
16059 ((and (not (eq org-support-shift-select 'always))
16060 (org-on-heading-p))
16061 (org-call-with-arg 'org-todo 'previousset))
16062 (org-support-shift-select
16063 (org-call-for-shift-select 'backward-word))
16064 (t (org-shiftselect-error))))
16066 (defun org-ctrl-c-ret ()
16067 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
16068 (interactive)
16069 (cond
16070 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
16071 (t (call-interactively 'org-insert-heading))))
16073 (defun org-copy-special ()
16074 "Copy region in table or copy current subtree.
16075 Calls `org-table-copy' or `org-copy-subtree', depending on context.
16076 See the individual commands for more information."
16077 (interactive)
16078 (call-interactively
16079 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
16081 (defun org-cut-special ()
16082 "Cut region in table or cut current subtree.
16083 Calls `org-table-copy' or `org-cut-subtree', depending on context.
16084 See the individual commands for more information."
16085 (interactive)
16086 (call-interactively
16087 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
16089 (defun org-paste-special (arg)
16090 "Paste rectangular region into table, or past subtree relative to level.
16091 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
16092 See the individual commands for more information."
16093 (interactive "P")
16094 (if (org-at-table-p)
16095 (org-table-paste-rectangle)
16096 (org-paste-subtree arg)))
16098 (defun org-edit-special ()
16099 "Call a special editor for the stuff at point.
16100 When at a table, call the formula editor with `org-table-edit-formulas'.
16101 When at the first line of an src example, call `org-edit-src-code'.
16102 When in an #+include line, visit the include file. Otherwise call
16103 `ffap' to visit the file at point."
16104 (interactive)
16105 (cond
16106 ((org-at-table.el-p)
16107 (org-edit-src-code))
16108 ((org-at-table-p)
16109 (call-interactively 'org-table-edit-formulas))
16110 ((save-excursion
16111 (beginning-of-line 1)
16112 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
16113 (find-file (org-trim (match-string 1))))
16114 ((org-edit-src-code))
16115 ((org-edit-fixed-width-region))
16116 (t (call-interactively 'ffap))))
16119 (defun org-ctrl-c-ctrl-c (&optional arg)
16120 "Set tags in headline, or update according to changed information at point.
16122 This command does many different things, depending on context:
16124 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
16125 this is what we do.
16127 - If the cursor is on a statistics cookie, update it.
16129 - If the cursor is in a headline, prompt for tags and insert them
16130 into the current line, aligned to `org-tags-column'. When called
16131 with prefix arg, realign all tags in the current buffer.
16133 - If the cursor is in one of the special #+KEYWORD lines, this
16134 triggers scanning the buffer for these lines and updating the
16135 information.
16137 - If the cursor is inside a table, realign the table. This command
16138 works even if the automatic table editor has been turned off.
16140 - If the cursor is on a #+TBLFM line, re-apply the formulas to
16141 the entire table.
16143 - If the cursor is at a footnote reference or definition, jump to
16144 the corresponding definition or references, respectively.
16146 - If the cursor is a the beginning of a dynamic block, update it.
16148 - If the current buffer is a remember buffer, close note and file
16149 it. A prefix argument of 1 files to the default location
16150 without further interaction. A prefix argument of 2 files to
16151 the currently clocking task.
16153 - If the cursor is on a <<<target>>>, update radio targets and corresponding
16154 links in this buffer.
16156 - If the cursor is on a numbered item in a plain list, renumber the
16157 ordered list.
16159 - If the cursor is on a checkbox, toggle it."
16160 (interactive "P")
16161 (let ((org-enable-table-editor t))
16162 (cond
16163 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
16164 org-occur-highlights
16165 org-latex-fragment-image-overlays)
16166 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
16167 (org-remove-occur-highlights)
16168 (org-remove-latex-fragment-image-overlays)
16169 (message "Temporary highlights/overlays removed from current buffer"))
16170 ((and (local-variable-p 'org-finish-function (current-buffer))
16171 (fboundp org-finish-function))
16172 (funcall org-finish-function))
16173 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
16174 ((or (looking-at (org-re org-property-start-re))
16175 (org-at-property-p))
16176 (call-interactively 'org-property-action))
16177 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
16178 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
16179 (or (org-on-heading-p) (org-at-item-p)))
16180 (call-interactively 'org-update-statistics-cookies))
16181 ((org-on-heading-p) (call-interactively 'org-set-tags))
16182 ((org-at-table.el-p)
16183 (message "Use C-c ' to edit table.el tables"))
16184 ((org-at-table-p)
16185 (org-table-maybe-eval-formula)
16186 (if arg
16187 (call-interactively 'org-table-recalculate)
16188 (org-table-maybe-recalculate-line))
16189 (call-interactively 'org-table-align))
16190 ((or (org-footnote-at-reference-p)
16191 (org-footnote-at-definition-p))
16192 (call-interactively 'org-footnote-action))
16193 ((org-at-item-checkbox-p)
16194 (call-interactively 'org-toggle-checkbox))
16195 ((org-at-item-p)
16196 (if arg
16197 (call-interactively 'org-toggle-checkbox)
16198 (call-interactively 'org-maybe-renumber-ordered-list)))
16199 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
16200 ;; Dynamic block
16201 (beginning-of-line 1)
16202 (save-excursion (org-update-dblock)))
16203 ((save-excursion
16204 (beginning-of-line 1)
16205 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
16206 (cond
16207 ((equal (match-string 1) "TBLFM")
16208 ;; Recalculate the table before this line
16209 (save-excursion
16210 (beginning-of-line 1)
16211 (skip-chars-backward " \r\n\t")
16212 (if (org-at-table-p)
16213 (org-call-with-arg 'org-table-recalculate (or arg t)))))
16215 (let ((org-inhibit-startup-visibility-stuff t)
16216 (org-startup-align-all-tables nil))
16217 (org-save-outline-visibility 'use-markers (org-mode-restart)))
16218 (message "Local setup has been refreshed"))))
16219 ((org-clock-update-time-maybe))
16220 (t (error "C-c C-c can do nothing useful at this location")))))
16222 (defun org-mode-restart ()
16223 "Restart Org-mode, to scan again for special lines.
16224 Also updates the keyword regular expressions."
16225 (interactive)
16226 (org-mode)
16227 (message "Org-mode restarted"))
16229 (defun org-kill-note-or-show-branches ()
16230 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
16231 (interactive)
16232 (if (not org-finish-function)
16233 (call-interactively 'show-branches)
16234 (let ((org-note-abort t))
16235 (funcall org-finish-function))))
16237 (defun org-return (&optional indent)
16238 "Goto next table row or insert a newline.
16239 Calls `org-table-next-row' or `newline', depending on context.
16240 See the individual commands for more information."
16241 (interactive)
16242 (cond
16243 ((bobp) (if indent (newline-and-indent) (newline)))
16244 ((org-at-table-p)
16245 (org-table-justify-field-maybe)
16246 (call-interactively 'org-table-next-row))
16247 ((and org-return-follows-link
16248 (eq (get-text-property (point) 'face) 'org-link))
16249 (call-interactively 'org-open-at-point))
16250 ((and (org-at-heading-p)
16251 (looking-at
16252 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
16253 (org-show-entry)
16254 (end-of-line 1)
16255 (newline))
16256 (t (if indent (newline-and-indent) (newline)))))
16258 (defun org-return-indent ()
16259 "Goto next table row or insert a newline and indent.
16260 Calls `org-table-next-row' or `newline-and-indent', depending on
16261 context. See the individual commands for more information."
16262 (interactive)
16263 (org-return t))
16265 (defun org-ctrl-c-star ()
16266 "Compute table, or change heading status of lines.
16267 Calls `org-table-recalculate' or `org-toggle-heading',
16268 depending on context."
16269 (interactive)
16270 (cond
16271 ((org-at-table-p)
16272 (call-interactively 'org-table-recalculate))
16274 ;; Convert all lines in region to list items
16275 (call-interactively 'org-toggle-heading))))
16277 (defun org-ctrl-c-minus ()
16278 "Insert separator line in table or modify bullet status of line.
16279 Also turns a plain line or a region of lines into list items.
16280 Calls `org-table-insert-hline', `org-toggle-item', or
16281 `org-cycle-list-bullet', depending on context."
16282 (interactive)
16283 (cond
16284 ((org-at-table-p)
16285 (call-interactively 'org-table-insert-hline))
16286 ((org-region-active-p)
16287 (call-interactively 'org-toggle-item))
16288 ((org-in-item-p)
16289 (call-interactively 'org-cycle-list-bullet))
16291 (call-interactively 'org-toggle-item))))
16293 (defun org-toggle-item ()
16294 "Convert headings or normal lines to items, items to normal lines.
16295 If there is no active region, only the current line is considered.
16297 If the first line in the region is a headline, convert all headlines to items.
16299 If the first line in the region is an item, convert all items to normal lines.
16301 If the first line is normal text, add an item bullet to each line."
16302 (interactive)
16303 (let (l2 l beg end)
16304 (if (org-region-active-p)
16305 (setq beg (region-beginning) end (region-end))
16306 (setq beg (point-at-bol)
16307 end (min (1+ (point-at-eol)) (point-max))))
16308 (save-excursion
16309 (goto-char end)
16310 (setq l2 (org-current-line))
16311 (goto-char beg)
16312 (beginning-of-line 1)
16313 (setq l (1- (org-current-line)))
16314 (if (org-at-item-p)
16315 ;; We already have items, de-itemize
16316 (while (< (setq l (1+ l)) l2)
16317 (when (org-at-item-p)
16318 (goto-char (match-beginning 2))
16319 (delete-region (match-beginning 2) (match-end 2))
16320 (and (looking-at "[ \t]+") (replace-match "")))
16321 (beginning-of-line 2))
16322 (if (org-on-heading-p)
16323 ;; Headings, convert to items
16324 (while (< (setq l (1+ l)) l2)
16325 (if (looking-at org-outline-regexp)
16326 (replace-match "- " t t))
16327 (beginning-of-line 2))
16328 ;; normal lines, turn them into items
16329 (while (< (setq l (1+ l)) l2)
16330 (unless (org-at-item-p)
16331 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16332 (replace-match "\\1- \\2")))
16333 (beginning-of-line 2)))))))
16335 (defun org-toggle-heading (&optional nstars)
16336 "Convert headings to normal text, or items or text to headings.
16337 If there is no active region, only the current line is considered.
16339 If the first line is a heading, remove the stars from all headlines
16340 in the region.
16342 If the first line is a plain list item, turn all plain list items
16343 into headings.
16345 If the first line is a normal line, turn each and every line in the
16346 region into a heading.
16348 When converting a line into a heading, the number of stars is chosen
16349 such that the lines become children of the current entry. However,
16350 when a prefix argument is given, its value determines the number of
16351 stars to add."
16352 (interactive "P")
16353 (let (l2 l itemp beg end)
16354 (if (org-region-active-p)
16355 (setq beg (region-beginning) end (region-end))
16356 (setq beg (point-at-bol)
16357 end (min (1+ (point-at-eol)) (point-max))))
16358 (save-excursion
16359 (goto-char end)
16360 (setq l2 (org-current-line))
16361 (goto-char beg)
16362 (beginning-of-line 1)
16363 (setq l (1- (org-current-line)))
16364 (if (org-on-heading-p)
16365 ;; We already have headlines, de-star them
16366 (while (< (setq l (1+ l)) l2)
16367 (when (org-on-heading-p t)
16368 (and (looking-at outline-regexp) (replace-match "")))
16369 (beginning-of-line 2))
16370 (setq itemp (org-at-item-p))
16371 (let* ((stars
16372 (if nstars
16373 (make-string (prefix-numeric-value current-prefix-arg)
16375 (save-excursion
16376 (if (re-search-backward org-complex-heading-regexp nil t)
16377 (match-string 1) ""))))
16378 (add-stars (cond (nstars "")
16379 ((equal stars "") "*")
16380 (org-odd-levels-only "**")
16381 (t "*")))
16382 (rpl (concat stars add-stars " ")))
16383 (while (< (setq l (1+ l)) l2)
16384 (if itemp
16385 (and (org-at-item-p) (replace-match rpl t t))
16386 (unless (org-on-heading-p)
16387 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16388 (replace-match (concat rpl (match-string 2))))))
16389 (beginning-of-line 2)))))))
16391 (defun org-meta-return (&optional arg)
16392 "Insert a new heading or wrap a region in a table.
16393 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16394 See the individual commands for more information."
16395 (interactive "P")
16396 (cond
16397 ((run-hook-with-args-until-success 'org-metareturn-hook))
16398 ((org-at-table-p)
16399 (call-interactively 'org-table-wrap-region))
16400 (t (call-interactively 'org-insert-heading))))
16402 ;;; Menu entries
16404 ;; Define the Org-mode menus
16405 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16406 '("Tbl"
16407 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
16408 ["Next Field" org-cycle (org-at-table-p)]
16409 ["Previous Field" org-shifttab (org-at-table-p)]
16410 ["Next Row" org-return (org-at-table-p)]
16411 "--"
16412 ["Blank Field" org-table-blank-field (org-at-table-p)]
16413 ["Edit Field" org-table-edit-field (org-at-table-p)]
16414 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16415 "--"
16416 ("Column"
16417 ["Move Column Left" org-metaleft (org-at-table-p)]
16418 ["Move Column Right" org-metaright (org-at-table-p)]
16419 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16420 ["Insert Column" org-shiftmetaright (org-at-table-p)])
16421 ("Row"
16422 ["Move Row Up" org-metaup (org-at-table-p)]
16423 ["Move Row Down" org-metadown (org-at-table-p)]
16424 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16425 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16426 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16427 "--"
16428 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
16429 ("Rectangle"
16430 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16431 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16432 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16433 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16434 "--"
16435 ("Calculate"
16436 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16437 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16438 ["Edit Formulas" org-edit-special (org-at-table-p)]
16439 "--"
16440 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16441 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16442 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
16443 "--"
16444 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16445 "--"
16446 ["Sum Column/Rectangle" org-table-sum
16447 (or (org-at-table-p) (org-region-active-p))]
16448 ["Which Column?" org-table-current-column (org-at-table-p)])
16449 ["Debug Formulas"
16450 org-table-toggle-formula-debugger
16451 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
16452 ["Show Col/Row Numbers"
16453 org-table-toggle-coordinate-overlays
16454 :style toggle
16455 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
16456 "--"
16457 ["Create" org-table-create (and (not (org-at-table-p))
16458 org-enable-table-editor)]
16459 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16460 ["Import from File" org-table-import (not (org-at-table-p))]
16461 ["Export to File" org-table-export (org-at-table-p)]
16462 "--"
16463 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16465 (easy-menu-define org-org-menu org-mode-map "Org menu"
16466 '("Org"
16467 ("Show/Hide"
16468 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
16469 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
16470 ["Sparse Tree..." org-sparse-tree t]
16471 ["Reveal Context" org-reveal t]
16472 ["Show All" show-all t]
16473 "--"
16474 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
16475 "--"
16476 ["New Heading" org-insert-heading t]
16477 ("Navigate Headings"
16478 ["Up" outline-up-heading t]
16479 ["Next" outline-next-visible-heading t]
16480 ["Previous" outline-previous-visible-heading t]
16481 ["Next Same Level" outline-forward-same-level t]
16482 ["Previous Same Level" outline-backward-same-level t]
16483 "--"
16484 ["Jump" org-goto t])
16485 ("Edit Structure"
16486 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16487 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16488 "--"
16489 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16490 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16491 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16492 "--"
16493 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
16494 "--"
16495 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16496 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16497 ["Demote Heading" org-metaright (not (org-at-table-p))]
16498 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16499 "--"
16500 ["Sort Region/Children" org-sort (not (org-at-table-p))]
16501 "--"
16502 ["Convert to odd levels" org-convert-to-odd-levels t]
16503 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16504 ("Editing"
16505 ["Emphasis..." org-emphasize t]
16506 ["Edit Source Example" org-edit-special t]
16507 "--"
16508 ["Footnote new/jump" org-footnote-action t]
16509 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
16510 ("Archive"
16511 ["Archive (default method)" org-archive-subtree-default t]
16512 "--"
16513 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
16514 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16515 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
16517 "--"
16518 ("Hyperlinks"
16519 ["Store Link (Global)" org-store-link t]
16520 ["Find existing link to here" org-occur-link-in-agenda-files t]
16521 ["Insert Link" org-insert-link t]
16522 ["Follow Link" org-open-at-point t]
16523 "--"
16524 ["Next link" org-next-link t]
16525 ["Previous link" org-previous-link t]
16526 "--"
16527 ["Descriptive Links"
16528 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16529 :style radio
16530 :selected (member '(org-link) buffer-invisibility-spec)]
16531 ["Literal Links"
16532 (progn
16533 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16534 :style radio
16535 :selected (not (member '(org-link) buffer-invisibility-spec))])
16536 "--"
16537 ("TODO Lists"
16538 ["TODO/DONE/-" org-todo t]
16539 ("Select keyword"
16540 ["Next keyword" org-shiftright (org-on-heading-p)]
16541 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16542 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
16543 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
16544 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
16545 ["Show TODO Tree" org-show-todo-tree t]
16546 ["Global TODO list" org-todo-list t]
16547 "--"
16548 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
16549 :selected org-enforce-todo-dependencies :style toggle :active t]
16550 "Settings for tree at point"
16551 ["Do Children sequentially" org-toggle-ordered-property :style radio
16552 :selected (ignore-errors (org-entry-get nil "ORDERED"))
16553 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16554 ["Do Children parallel" org-toggle-ordered-property :style radio
16555 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
16556 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16557 "--"
16558 ["Set Priority" org-priority t]
16559 ["Priority Up" org-shiftup t]
16560 ["Priority Down" org-shiftdown t]
16561 "--"
16562 ["Get news from all feeds" org-feed-update-all t]
16563 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16564 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16565 ("TAGS and Properties"
16566 ["Set Tags" org-set-tags-command t]
16567 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16568 "--"
16569 ["Set property" org-set-property t]
16570 ["Column view of properties" org-columns t]
16571 ["Insert Column View DBlock" org-insert-columns-dblock t])
16572 ("Dates and Scheduling"
16573 ["Timestamp" org-time-stamp t]
16574 ["Timestamp (inactive)" org-time-stamp-inactive t]
16575 ("Change Date"
16576 ["1 Day Later" org-shiftright t]
16577 ["1 Day Earlier" org-shiftleft t]
16578 ["1 ... Later" org-shiftup t]
16579 ["1 ... Earlier" org-shiftdown t])
16580 ["Compute Time Range" org-evaluate-time-range t]
16581 ["Schedule Item" org-schedule t]
16582 ["Deadline" org-deadline t]
16583 "--"
16584 ["Custom time format" org-toggle-time-stamp-overlays
16585 :style radio :selected org-display-custom-times]
16586 "--"
16587 ["Goto Calendar" org-goto-calendar t]
16588 ["Date from Calendar" org-date-from-calendar t]
16589 "--"
16590 ["Start/Restart Timer" org-timer-start t]
16591 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16592 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16593 ["Insert Timer String" org-timer t]
16594 ["Insert Timer Item" org-timer-item t])
16595 ("Logging work"
16596 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16597 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16598 ["Clock out" org-clock-out t]
16599 ["Clock cancel" org-clock-cancel t]
16600 "--"
16601 ["Mark as default task" org-clock-mark-default-task t]
16602 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16603 ["Goto running clock" org-clock-goto t]
16604 "--"
16605 ["Display times" org-clock-display t]
16606 ["Create clock table" org-clock-report t]
16607 "--"
16608 ["Record DONE time"
16609 (progn (setq org-log-done (not org-log-done))
16610 (message "Switching to %s will %s record a timestamp"
16611 (car org-done-keywords)
16612 (if org-log-done "automatically" "not")))
16613 :style toggle :selected org-log-done])
16614 "--"
16615 ["Agenda Command..." org-agenda t]
16616 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16617 ("File List for Agenda")
16618 ("Special views current file"
16619 ["TODO Tree" org-show-todo-tree t]
16620 ["Check Deadlines" org-check-deadlines t]
16621 ["Timeline" org-timeline t]
16622 ["Tags/Property tree" org-match-sparse-tree t])
16623 "--"
16624 ["Export/Publish..." org-export t]
16625 ("LaTeX"
16626 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16627 :selected org-cdlatex-mode]
16628 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16629 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16630 ["Modify math symbol" org-cdlatex-math-modify
16631 (org-inside-LaTeX-fragment-p)]
16632 ["Insert citation" org-reftex-citation t]
16633 "--"
16634 ["Export LaTeX fragments as images"
16635 (if (featurep 'org-exp)
16636 (setq org-export-with-LaTeX-fragments
16637 (not org-export-with-LaTeX-fragments))
16638 (require 'org-exp))
16639 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16640 org-export-with-LaTeX-fragments)]
16641 "--"
16642 ["Template for BEAMER" org-beamer-settings-template t])
16643 "--"
16644 ("MobileOrg"
16645 ["Push Files and Views" org-mobile-push t]
16646 ["Get Captured and Flagged" org-mobile-pull t]
16647 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16648 "--"
16649 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16650 "--"
16651 ("Documentation"
16652 ["Show Version" org-version t]
16653 ["Info Documentation" org-info t])
16654 ("Customize"
16655 ["Browse Org Group" org-customize t]
16656 "--"
16657 ["Expand This Menu" org-create-customize-menu
16658 (fboundp 'customize-menu-create)])
16659 ["Send bug report" org-submit-bug-report t]
16660 "--"
16661 ("Refresh/Reload"
16662 ["Refresh setup current buffer" org-mode-restart t]
16663 ["Reload Org (after update)" org-reload t]
16664 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16667 (defun org-info (&optional node)
16668 "Read documentation for Org-mode in the info system.
16669 With optional NODE, go directly to that node."
16670 (interactive)
16671 (info (format "(org)%s" (or node ""))))
16673 ;;;###autoload
16674 (defun org-submit-bug-report ()
16675 "Submit a bug report on Org-mode via mail.
16677 Don't hesitate to report any problems or inaccurate documentation.
16679 If you don't have setup sending mail from (X)Emacs, please copy the
16680 output buffer into your mail program, as it gives us important
16681 information about your Org-mode version and configuration."
16682 (interactive)
16683 (require 'reporter)
16684 (org-load-modules-maybe)
16685 (org-require-autoloaded-modules)
16686 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16687 (reporter-submit-bug-report
16688 "emacs-orgmode@gnu.org"
16689 (org-version)
16690 (let (list)
16691 (save-window-excursion
16692 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16693 (delete-other-windows)
16694 (erase-buffer)
16695 (insert "You are about to submit a bug report to the Org-mode mailing list.
16697 We would like to add your full Org-mode and Outline configuration to the
16698 bug report. This greatly simplifies the work of the maintainer and
16699 other experts on the mailing list.
16701 HOWEVER, some variables you have customized may contain private
16702 information. The names of customers, colleagues, or friends, might
16703 appear in the form of file names, tags, todo states, or search strings.
16704 If you answer yes to the prompt, you might want to check and remove
16705 such private information before sending the email.")
16706 (add-text-properties (point-min) (point-max) '(face org-warning))
16707 (when (yes-or-no-p "Include your Org-mode configuration ")
16708 (mapatoms
16709 (lambda (v)
16710 (and (boundp v)
16711 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16712 (or (and (symbol-value v)
16713 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16714 (and
16715 (get v 'custom-type) (get v 'standard-value)
16716 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16717 (push v list)))))
16718 (kill-buffer (get-buffer "*Warn about privacy*"))
16719 list))
16720 nil nil
16721 "Remember to cover the basics, that is, what you expected to happen and
16722 what in fact did happen. You don't know how to make a good report? See
16724 http://orgmode.org/manual/Feedback.html#Feedback
16726 Your bug report will be posted to the Org-mode mailing list.
16727 ------------------------------------------------------------------------")
16728 (save-excursion
16729 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16730 (replace-match "\\1Bug: \\3 [\\2]")))))
16733 (defun org-install-agenda-files-menu ()
16734 (let ((bl (buffer-list)))
16735 (save-excursion
16736 (while bl
16737 (set-buffer (pop bl))
16738 (if (org-mode-p) (setq bl nil)))
16739 (when (org-mode-p)
16740 (easy-menu-change
16741 '("Org") "File List for Agenda"
16742 (append
16743 (list
16744 ["Edit File List" (org-edit-agenda-file-list) t]
16745 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16746 ["Remove Current File from List" org-remove-file t]
16747 ["Cycle through agenda files" org-cycle-agenda-files t]
16748 ["Occur in all agenda files" org-occur-in-agenda-files t]
16749 "--")
16750 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16752 ;;;; Documentation
16754 ;;;###autoload
16755 (defun org-require-autoloaded-modules ()
16756 (interactive)
16757 (mapc 'require
16758 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16759 org-docbook org-exp org-html org-icalendar
16760 org-id org-latex
16761 org-publish org-remember org-table
16762 org-timer org-xoxo)))
16764 ;;;###autoload
16765 (defun org-reload (&optional uncompiled)
16766 "Reload all org lisp files.
16767 With prefix arg UNCOMPILED, load the uncompiled versions."
16768 (interactive "P")
16769 (require 'find-func)
16770 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16771 (dir-org (file-name-directory (org-find-library-name "org")))
16772 (dir-org-contrib (ignore-errors
16773 (file-name-directory
16774 (org-find-library-name "org-contribdir"))))
16775 (files
16776 (append (directory-files dir-org t file-re)
16777 (and dir-org-contrib
16778 (directory-files dir-org-contrib t file-re))))
16779 (remove-re (concat (if (featurep 'xemacs)
16780 "org-colview" "org-colview-xemacs")
16781 "\\'")))
16782 (setq files (mapcar 'file-name-sans-extension files))
16783 (setq files (mapcar
16784 (lambda (x) (if (string-match remove-re x) nil x))
16785 files))
16786 (setq files (delq nil files))
16787 (mapc
16788 (lambda (f)
16789 (when (featurep (intern (file-name-nondirectory f)))
16790 (if (and (not uncompiled)
16791 (file-exists-p (concat f ".elc")))
16792 (load (concat f ".elc") nil nil t)
16793 (load (concat f ".el") nil nil t))))
16794 files))
16795 (org-version))
16797 ;;;###autoload
16798 (defun org-customize ()
16799 "Call the customize function with org as argument."
16800 (interactive)
16801 (org-load-modules-maybe)
16802 (org-require-autoloaded-modules)
16803 (customize-browse 'org))
16805 (defun org-create-customize-menu ()
16806 "Create a full customization menu for Org-mode, insert it into the menu."
16807 (interactive)
16808 (org-load-modules-maybe)
16809 (org-require-autoloaded-modules)
16810 (if (fboundp 'customize-menu-create)
16811 (progn
16812 (easy-menu-change
16813 '("Org") "Customize"
16814 `(["Browse Org group" org-customize t]
16815 "--"
16816 ,(customize-menu-create 'org)
16817 ["Set" Custom-set t]
16818 ["Save" Custom-save t]
16819 ["Reset to Current" Custom-reset-current t]
16820 ["Reset to Saved" Custom-reset-saved t]
16821 ["Reset to Standard Settings" Custom-reset-standard t]))
16822 (message "\"Org\"-menu now contains full customization menu"))
16823 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16825 ;;;; Miscellaneous stuff
16827 ;;; Generally useful functions
16829 (defun org-get-at-bol (property)
16830 "Get text property PROPERTY at beginning of line."
16831 (get-text-property (point-at-bol) property))
16833 (defun org-find-text-property-in-string (prop s)
16834 "Return the first non-nil value of property PROP in string S."
16835 (or (get-text-property 0 prop s)
16836 (get-text-property (or (next-single-property-change 0 prop s) 0)
16837 prop s)))
16839 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16840 "Display the given MESSAGE as a warning."
16841 (if (fboundp 'display-warning)
16842 (display-warning 'org message
16843 (if (featurep 'xemacs)
16844 'warning
16845 :warning))
16846 (let ((buf (get-buffer-create "*Org warnings*")))
16847 (with-current-buffer buf
16848 (goto-char (point-max))
16849 (insert "Warning (Org): " message)
16850 (unless (bolp)
16851 (newline)))
16852 (display-buffer buf)
16853 (sit-for 0))))
16855 (defun org-in-commented-line ()
16856 "Is point in a line starting with `#'?"
16857 (equal (char-after (point-at-bol)) ?#))
16859 (defun org-in-verbatim-emphasis ()
16860 (save-match-data
16861 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16863 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16864 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16865 (if (and marker (marker-buffer marker)
16866 (buffer-live-p (marker-buffer marker)))
16867 (progn
16868 (switch-to-buffer (marker-buffer marker))
16869 (if (or (> marker (point-max)) (< marker (point-min)))
16870 (widen))
16871 (goto-char marker)
16872 (org-show-context 'org-goto))
16873 (if bookmark
16874 (bookmark-jump bookmark)
16875 (error "Cannot find location"))))
16877 (defun org-quote-csv-field (s)
16878 "Quote field for inclusion in CSV material."
16879 (if (string-match "[\",]" s)
16880 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16883 (defun org-plist-delete (plist property)
16884 "Delete PROPERTY from PLIST.
16885 This is in contrast to merely setting it to 0."
16886 (let (p)
16887 (while plist
16888 (if (not (eq property (car plist)))
16889 (setq p (plist-put p (car plist) (nth 1 plist))))
16890 (setq plist (cddr plist)))
16893 (defun org-force-self-insert (N)
16894 "Needed to enforce self-insert under remapping."
16895 (interactive "p")
16896 (self-insert-command N))
16898 (defun org-string-width (s)
16899 "Compute width of string, ignoring invisible characters.
16900 This ignores character with invisibility property `org-link', and also
16901 characters with property `org-cwidth', because these will become invisible
16902 upon the next fontification round."
16903 (let (b l)
16904 (when (or (eq t buffer-invisibility-spec)
16905 (assq 'org-link buffer-invisibility-spec))
16906 (while (setq b (text-property-any 0 (length s)
16907 'invisible 'org-link s))
16908 (setq s (concat (substring s 0 b)
16909 (substring s (or (next-single-property-change
16910 b 'invisible s) (length s)))))))
16911 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16912 (setq s (concat (substring s 0 b)
16913 (substring s (or (next-single-property-change
16914 b 'org-cwidth s) (length s))))))
16915 (setq l (string-width s) b -1)
16916 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16917 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16920 (defun org-get-indentation (&optional line)
16921 "Get the indentation of the current line, interpreting tabs.
16922 When LINE is given, assume it represents a line and compute its indentation."
16923 (if line
16924 (if (string-match "^ *" (org-remove-tabs line))
16925 (match-end 0))
16926 (save-excursion
16927 (beginning-of-line 1)
16928 (skip-chars-forward " \t")
16929 (current-column))))
16931 (defun org-remove-tabs (s &optional width)
16932 "Replace tabulators in S with spaces.
16933 Assumes that s is a single line, starting in column 0."
16934 (setq width (or width tab-width))
16935 (while (string-match "\t" s)
16936 (setq s (replace-match
16937 (make-string
16938 (- (* width (/ (+ (match-beginning 0) width) width))
16939 (match-beginning 0)) ?\ )
16940 t t s)))
16943 (defun org-fix-indentation (line ind)
16944 "Fix indentation in LINE.
16945 IND is a cons cell with target and minimum indentation.
16946 If the current indentation in LINE is smaller than the minimum,
16947 leave it alone. If it is larger than ind, set it to the target."
16948 (let* ((l (org-remove-tabs line))
16949 (i (org-get-indentation l))
16950 (i1 (car ind)) (i2 (cdr ind)))
16951 (if (>= i i2) (setq l (substring line i2)))
16952 (if (> i1 0)
16953 (concat (make-string i1 ?\ ) l)
16954 l)))
16956 (defun org-remove-indentation (code &optional n)
16957 "Remove the maximum common indentation from the lines in CODE.
16958 N may optionally be the number of spaces to remove."
16959 (with-temp-buffer
16960 (insert code)
16961 (org-do-remove-indentation n)
16962 (buffer-string)))
16964 (defun org-do-remove-indentation (&optional n)
16965 "Remove the maximum common indentation from the buffer."
16966 (untabify (point-min) (point-max))
16967 (let ((min 10000) re)
16968 (if n
16969 (setq min n)
16970 (goto-char (point-min))
16971 (while (re-search-forward "^ *[^ \n]" nil t)
16972 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16973 (unless (or (= min 0) (= min 10000))
16974 (setq re (format "^ \\{%d\\}" min))
16975 (goto-char (point-min))
16976 (while (re-search-forward re nil t)
16977 (replace-match "")
16978 (end-of-line 1))
16979 min)))
16981 (defun org-fill-template (template alist)
16982 "Find each %key of ALIST in TEMPLATE and replace it."
16983 (let ((case-fold-search nil)
16984 entry key value)
16985 (setq alist (sort (copy-sequence alist)
16986 (lambda (a b) (< (length (car a)) (length (car b))))))
16987 (while (setq entry (pop alist))
16988 (setq template
16989 (replace-regexp-in-string
16990 (concat "%" (regexp-quote (car entry)))
16991 (cdr entry) template t t)))
16992 template))
16994 (defun org-base-buffer (buffer)
16995 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16996 (if (not buffer)
16997 buffer
16998 (or (buffer-base-buffer buffer)
16999 buffer)))
17001 (defun org-trim (s)
17002 "Remove whitespace at beginning and end of string."
17003 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
17004 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
17007 (defun org-wrap (string &optional width lines)
17008 "Wrap string to either a number of lines, or a width in characters.
17009 If WIDTH is non-nil, the string is wrapped to that width, however many lines
17010 that costs. If there is a word longer than WIDTH, the text is actually
17011 wrapped to the length of that word.
17012 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
17013 many lines, whatever width that takes.
17014 The return value is a list of lines, without newlines at the end."
17015 (let* ((words (org-split-string string "[ \t\n]+"))
17016 (maxword (apply 'max (mapcar 'org-string-width words)))
17017 w ll)
17018 (cond (width
17019 (org-do-wrap words (max maxword width)))
17020 (lines
17021 (setq w maxword)
17022 (setq ll (org-do-wrap words maxword))
17023 (if (<= (length ll) lines)
17025 (setq ll words)
17026 (while (> (length ll) lines)
17027 (setq w (1+ w))
17028 (setq ll (org-do-wrap words w)))
17029 ll))
17030 (t (error "Cannot wrap this")))))
17032 (defun org-do-wrap (words width)
17033 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
17034 (let (lines line)
17035 (while words
17036 (setq line (pop words))
17037 (while (and words (< (+ (length line) (length (car words))) width))
17038 (setq line (concat line " " (pop words))))
17039 (setq lines (push line lines)))
17040 (nreverse lines)))
17042 (defun org-split-string (string &optional separators)
17043 "Splits STRING into substrings at SEPARATORS.
17044 No empty strings are returned if there are matches at the beginning
17045 and end of string."
17046 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
17047 (start 0)
17048 notfirst
17049 (list nil))
17050 (while (and (string-match rexp string
17051 (if (and notfirst
17052 (= start (match-beginning 0))
17053 (< start (length string)))
17054 (1+ start) start))
17055 (< (match-beginning 0) (length string)))
17056 (setq notfirst t)
17057 (or (eq (match-beginning 0) 0)
17058 (and (eq (match-beginning 0) (match-end 0))
17059 (eq (match-beginning 0) start))
17060 (setq list
17061 (cons (substring string start (match-beginning 0))
17062 list)))
17063 (setq start (match-end 0)))
17064 (or (eq start (length string))
17065 (setq list
17066 (cons (substring string start)
17067 list)))
17068 (nreverse list)))
17070 (defun org-quote-vert (s)
17071 "Replace \"|\" with \"\\vert\"."
17072 (while (string-match "|" s)
17073 (setq s (replace-match "\\vert" t t s)))
17076 (defun org-uuidgen-p (s)
17077 "Is S an ID created by UUIDGEN?"
17078 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
17080 (defun org-context ()
17081 "Return a list of contexts of the current cursor position.
17082 If several contexts apply, all are returned.
17083 Each context entry is a list with a symbol naming the context, and
17084 two positions indicating start and end of the context. Possible
17085 contexts are:
17087 :headline anywhere in a headline
17088 :headline-stars on the leading stars in a headline
17089 :todo-keyword on a TODO keyword (including DONE) in a headline
17090 :tags on the TAGS in a headline
17091 :priority on the priority cookie in a headline
17092 :item on the first line of a plain list item
17093 :item-bullet on the bullet/number of a plain list item
17094 :checkbox on the checkbox in a plain list item
17095 :table in an org-mode table
17096 :table-special on a special filed in a table
17097 :table-table in a table.el table
17098 :link on a hyperlink
17099 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
17100 :target on a <<target>>
17101 :radio-target on a <<<radio-target>>>
17102 :latex-fragment on a LaTeX fragment
17103 :latex-preview on a LaTeX fragment with overlayed preview image
17105 This function expects the position to be visible because it uses font-lock
17106 faces as a help to recognize the following contexts: :table-special, :link,
17107 and :keyword."
17108 (let* ((f (get-text-property (point) 'face))
17109 (faces (if (listp f) f (list f)))
17110 (p (point)) clist o)
17111 ;; First the large context
17112 (cond
17113 ((org-on-heading-p t)
17114 (push (list :headline (point-at-bol) (point-at-eol)) clist)
17115 (when (progn
17116 (beginning-of-line 1)
17117 (looking-at org-todo-line-tags-regexp))
17118 (push (org-point-in-group p 1 :headline-stars) clist)
17119 (push (org-point-in-group p 2 :todo-keyword) clist)
17120 (push (org-point-in-group p 4 :tags) clist))
17121 (goto-char p)
17122 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
17123 (if (looking-at "\\[#[A-Z0-9]\\]")
17124 (push (org-point-in-group p 0 :priority) clist)))
17126 ((org-at-item-p)
17127 (push (org-point-in-group p 2 :item-bullet) clist)
17128 (push (list :item (point-at-bol)
17129 (save-excursion (org-end-of-item) (point)))
17130 clist)
17131 (and (org-at-item-checkbox-p)
17132 (push (org-point-in-group p 0 :checkbox) clist)))
17134 ((org-at-table-p)
17135 (push (list :table (org-table-begin) (org-table-end)) clist)
17136 (if (memq 'org-formula faces)
17137 (push (list :table-special
17138 (previous-single-property-change p 'face)
17139 (next-single-property-change p 'face)) clist)))
17140 ((org-at-table-p 'any)
17141 (push (list :table-table) clist)))
17142 (goto-char p)
17144 ;; Now the small context
17145 (cond
17146 ((org-at-timestamp-p)
17147 (push (org-point-in-group p 0 :timestamp) clist))
17148 ((memq 'org-link faces)
17149 (push (list :link
17150 (previous-single-property-change p 'face)
17151 (next-single-property-change p 'face)) clist))
17152 ((memq 'org-special-keyword faces)
17153 (push (list :keyword
17154 (previous-single-property-change p 'face)
17155 (next-single-property-change p 'face)) clist))
17156 ((org-on-target-p)
17157 (push (org-point-in-group p 0 :target) clist)
17158 (goto-char (1- (match-beginning 0)))
17159 (if (looking-at org-radio-target-regexp)
17160 (push (org-point-in-group p 0 :radio-target) clist))
17161 (goto-char p))
17162 ((setq o (car (delq nil
17163 (mapcar
17164 (lambda (x)
17165 (if (memq x org-latex-fragment-image-overlays) x))
17166 (org-overlays-at (point))))))
17167 (push (list :latex-fragment
17168 (org-overlay-start o) (org-overlay-end o)) clist)
17169 (push (list :latex-preview
17170 (org-overlay-start o) (org-overlay-end o)) clist))
17171 ((org-inside-LaTeX-fragment-p)
17172 ;; FIXME: positions wrong.
17173 (push (list :latex-fragment (point) (point)) clist)))
17175 (setq clist (nreverse (delq nil clist)))
17176 clist))
17178 ;; FIXME: Compare with at-regexp-p Do we need both?
17179 (defun org-in-regexp (re &optional nlines visually)
17180 "Check if point is inside a match of regexp.
17181 Normally only the current line is checked, but you can include NLINES extra
17182 lines both before and after point into the search.
17183 If VISUALLY is set, require that the cursor is not after the match but
17184 really on, so that the block visually is on the match."
17185 (catch 'exit
17186 (let ((pos (point))
17187 (eol (point-at-eol (+ 1 (or nlines 0))))
17188 (inc (if visually 1 0)))
17189 (save-excursion
17190 (beginning-of-line (- 1 (or nlines 0)))
17191 (while (re-search-forward re eol t)
17192 (if (and (<= (match-beginning 0) pos)
17193 (>= (+ inc (match-end 0)) pos))
17194 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
17196 (defun org-at-regexp-p (regexp)
17197 "Is point inside a match of REGEXP in the current line?"
17198 (catch 'exit
17199 (save-excursion
17200 (let ((pos (point)) (end (point-at-eol)))
17201 (beginning-of-line 1)
17202 (while (re-search-forward regexp end t)
17203 (if (and (<= (match-beginning 0) pos)
17204 (>= (match-end 0) pos))
17205 (throw 'exit t)))
17206 nil))))
17208 (defun org-in-regexps-block-p (start-re end-re)
17209 "Returns t if the current point is between matches of START-RE and END-RE.
17210 This will also return to if point is on one of the two matches."
17211 (interactive)
17212 (let ((p (point)))
17213 (save-excursion
17214 (and (or (org-at-regexp-p start-re)
17215 (re-search-backward start-re nil t))
17216 (re-search-forward end-re nil t)
17217 (>= (point) p)))))
17219 (defun org-occur-in-agenda-files (regexp &optional nlines)
17220 "Call `multi-occur' with buffers for all agenda files."
17221 (interactive "sOrg-files matching: \np")
17222 (let* ((files (org-agenda-files))
17223 (tnames (mapcar 'file-truename files))
17224 (extra org-agenda-text-search-extra-files)
17226 (when (eq (car extra) 'agenda-archives)
17227 (setq extra (cdr extra))
17228 (setq files (org-add-archive-files files)))
17229 (while (setq f (pop extra))
17230 (unless (member (file-truename f) tnames)
17231 (add-to-list 'files f 'append)
17232 (add-to-list 'tnames (file-truename f) 'append)))
17233 (multi-occur
17234 (mapcar (lambda (x)
17235 (with-current-buffer
17236 (or (get-file-buffer x) (find-file-noselect x))
17237 (widen)
17238 (current-buffer)))
17239 files)
17240 regexp)))
17242 (if (boundp 'occur-mode-find-occurrence-hook)
17243 ;; Emacs 23
17244 (add-hook 'occur-mode-find-occurrence-hook
17245 (lambda ()
17246 (when (org-mode-p)
17247 (org-reveal))))
17248 ;; Emacs 22
17249 (defadvice occur-mode-goto-occurrence
17250 (after org-occur-reveal activate)
17251 (and (org-mode-p) (org-reveal)))
17252 (defadvice occur-mode-goto-occurrence-other-window
17253 (after org-occur-reveal activate)
17254 (and (org-mode-p) (org-reveal)))
17255 (defadvice occur-mode-display-occurrence
17256 (after org-occur-reveal activate)
17257 (when (org-mode-p)
17258 (let ((pos (occur-mode-find-occurrence)))
17259 (with-current-buffer (marker-buffer pos)
17260 (save-excursion
17261 (goto-char pos)
17262 (org-reveal)))))))
17264 (defun org-occur-link-in-agenda-files ()
17265 "Create a link and search for it in the agendas.
17266 The link is not stored in `org-stored-links', it is just created
17267 for the search purpose."
17268 (interactive)
17269 (let ((link (condition-case nil
17270 (org-store-link nil)
17271 (error "Unable to create a link to here"))))
17272 (org-occur-in-agenda-files (regexp-quote link))))
17274 (defun org-uniquify (list)
17275 "Remove duplicate elements from LIST."
17276 (let (res)
17277 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
17278 res))
17280 (defun org-delete-all (elts list)
17281 "Remove all elements in ELTS from LIST."
17282 (while elts
17283 (setq list (delete (pop elts) list)))
17284 list)
17286 (defun org-back-over-empty-lines ()
17287 "Move backwards over whitespace, to the beginning of the first empty line.
17288 Returns the number of empty lines passed."
17289 (let ((pos (point)))
17290 (skip-chars-backward " \t\n\r")
17291 (beginning-of-line 2)
17292 (goto-char (min (point) pos))
17293 (count-lines (point) pos)))
17295 (defun org-skip-whitespace ()
17296 (skip-chars-forward " \t\n\r"))
17298 (defun org-point-in-group (point group &optional context)
17299 "Check if POINT is in match-group GROUP.
17300 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
17301 match. If the match group does ot exist or point is not inside it,
17302 return nil."
17303 (and (match-beginning group)
17304 (>= point (match-beginning group))
17305 (<= point (match-end group))
17306 (if context
17307 (list context (match-beginning group) (match-end group))
17308 t)))
17310 (defun org-switch-to-buffer-other-window (&rest args)
17311 "Switch to buffer in a second window on the current frame.
17312 In particular, do not allow pop-up frames."
17313 (let (pop-up-frames special-display-buffer-names special-display-regexps
17314 special-display-function)
17315 (apply 'switch-to-buffer-other-window args)))
17317 (defun org-combine-plists (&rest plists)
17318 "Create a single property list from all plists in PLISTS.
17319 The process starts by copying the first list, and then setting properties
17320 from the other lists. Settings in the last list are the most significant
17321 ones and overrule settings in the other lists."
17322 (let ((rtn (copy-sequence (pop plists)))
17323 p v ls)
17324 (while plists
17325 (setq ls (pop plists))
17326 (while ls
17327 (setq p (pop ls) v (pop ls))
17328 (setq rtn (plist-put rtn p v))))
17329 rtn))
17331 (defun org-move-line-down (arg)
17332 "Move the current line down. With prefix argument, move it past ARG lines."
17333 (interactive "p")
17334 (let ((col (current-column))
17335 beg end pos)
17336 (beginning-of-line 1) (setq beg (point))
17337 (beginning-of-line 2) (setq end (point))
17338 (beginning-of-line (+ 1 arg))
17339 (setq pos (move-marker (make-marker) (point)))
17340 (insert (delete-and-extract-region beg end))
17341 (goto-char pos)
17342 (org-move-to-column col)))
17344 (defun org-move-line-up (arg)
17345 "Move the current line up. With prefix argument, move it past ARG lines."
17346 (interactive "p")
17347 (let ((col (current-column))
17348 beg end pos)
17349 (beginning-of-line 1) (setq beg (point))
17350 (beginning-of-line 2) (setq end (point))
17351 (beginning-of-line (- arg))
17352 (setq pos (move-marker (make-marker) (point)))
17353 (insert (delete-and-extract-region beg end))
17354 (goto-char pos)
17355 (org-move-to-column col)))
17357 (defun org-replace-escapes (string table)
17358 "Replace %-escapes in STRING with values in TABLE.
17359 TABLE is an association list with keys like \"%a\" and string values.
17360 The sequences in STRING may contain normal field width and padding information,
17361 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
17362 so values can contain further %-escapes if they are define later in TABLE."
17363 (let ((case-fold-search nil)
17364 e re rpl)
17365 (while (setq e (pop table))
17366 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
17367 (while (string-match re string)
17368 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
17369 (cdr e)))
17370 (setq string (replace-match rpl t t string))))
17371 string))
17374 (defun org-sublist (list start end)
17375 "Return a section of LIST, from START to END.
17376 Counting starts at 1."
17377 (let (rtn (c start))
17378 (setq list (nthcdr (1- start) list))
17379 (while (and list (<= c end))
17380 (push (pop list) rtn)
17381 (setq c (1+ c)))
17382 (nreverse rtn)))
17384 (defun org-find-base-buffer-visiting (file)
17385 "Like `find-buffer-visiting' but always return the base buffer and
17386 not an indirect buffer."
17387 (let ((buf (or (get-file-buffer file)
17388 (find-buffer-visiting file))))
17389 (if buf
17390 (or (buffer-base-buffer buf) buf)
17391 nil)))
17393 (defun org-image-file-name-regexp (&optional extensions)
17394 "Return regexp matching the file names of images.
17395 If EXTENSIONS is given, only match these."
17396 (if (and (not extensions) (fboundp 'image-file-name-regexp))
17397 (image-file-name-regexp)
17398 (let ((image-file-name-extensions
17399 (or extensions
17400 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
17401 "xbm" "xpm" "pbm" "pgm" "ppm"))))
17402 (concat "\\."
17403 (regexp-opt (nconc (mapcar 'upcase
17404 image-file-name-extensions)
17405 image-file-name-extensions)
17407 "\\'"))))
17409 (defun org-file-image-p (file &optional extensions)
17410 "Return non-nil if FILE is an image."
17411 (save-match-data
17412 (string-match (org-image-file-name-regexp extensions) file)))
17414 (defun org-get-cursor-date ()
17415 "Return the date at cursor in as a time.
17416 This works in the calendar and in the agenda, anywhere else it just
17417 returns the current time."
17418 (let (date day defd)
17419 (cond
17420 ((eq major-mode 'calendar-mode)
17421 (setq date (calendar-cursor-to-date)
17422 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17423 ((eq major-mode 'org-agenda-mode)
17424 (setq day (get-text-property (point) 'day))
17425 (if day
17426 (setq date (calendar-gregorian-from-absolute day)
17427 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
17428 (nth 2 date))))))
17429 (or defd (current-time))))
17431 (defvar org-agenda-action-marker (make-marker)
17432 "Marker pointing to the entry for the next agenda action.")
17434 (defun org-mark-entry-for-agenda-action ()
17435 "Mark the current entry as target of an agenda action.
17436 Agenda actions are actions executed from the agenda with the key `k',
17437 which make use of the date at the cursor."
17438 (interactive)
17439 (move-marker org-agenda-action-marker
17440 (save-excursion (org-back-to-heading t) (point))
17441 (current-buffer))
17442 (message
17443 "Entry marked for action; press `k' at desired date in agenda or calendar"))
17445 ;;; Paragraph filling stuff.
17446 ;; We want this to be just right, so use the full arsenal.
17448 (defun org-indent-line-function ()
17449 "Indent line like previous, but further if previous was headline or item."
17450 (interactive)
17451 (let* ((pos (point))
17452 (itemp (org-at-item-p))
17453 (case-fold-search t)
17454 (org-drawer-regexp (or org-drawer-regexp "\000"))
17455 column bpos bcol tpos tcol bullet btype bullet-type)
17456 ;; Find the previous relevant line
17457 (beginning-of-line 1)
17458 (cond
17459 ((looking-at "#") (setq column 0))
17460 ((looking-at "\\*+ ") (setq column 0))
17461 ((and (looking-at "[ \t]*:END:")
17462 (save-excursion (re-search-backward org-drawer-regexp nil t)))
17463 (save-excursion
17464 (goto-char (1- (match-beginning 1)))
17465 (setq column (current-column))))
17466 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
17467 (save-excursion
17468 (re-search-backward
17469 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
17470 (setq column (org-get-indentation (match-string 0))))
17472 (beginning-of-line 0)
17473 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
17474 (not (looking-at "[ \t]*:END:"))
17475 (not (looking-at org-drawer-regexp)))
17476 (beginning-of-line 0))
17477 (cond
17478 ((looking-at "\\*+[ \t]+")
17479 (if (not org-adapt-indentation)
17480 (setq column 0)
17481 (goto-char (match-end 0))
17482 (setq column (current-column))))
17483 ((looking-at org-drawer-regexp)
17484 (goto-char (1- (match-beginning 1)))
17485 (setq column (current-column)))
17486 ((looking-at "\\([ \t]*\\):END:")
17487 (goto-char (match-end 1))
17488 (setq column (current-column)))
17489 ((org-in-item-p)
17490 (org-beginning-of-item)
17491 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
17492 (setq bpos (match-beginning 1) tpos (match-end 0)
17493 bcol (progn (goto-char bpos) (current-column))
17494 tcol (progn (goto-char tpos) (current-column))
17495 bullet (match-string 1)
17496 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
17497 (if (> tcol (+ bcol org-description-max-indent))
17498 (setq tcol (+ bcol 5)))
17499 (if (not itemp)
17500 (setq column tcol)
17501 (goto-char pos)
17502 (beginning-of-line 1)
17503 (if (looking-at "\\S-")
17504 (progn
17505 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
17506 (setq bullet (match-string 1)
17507 btype (if (string-match "[0-9]" bullet) "n" bullet))
17508 (setq column (if (equal btype bullet-type) bcol tcol)))
17509 (setq column (org-get-indentation)))))
17510 (t (setq column (org-get-indentation))))))
17511 (goto-char pos)
17512 (if (<= (current-column) (current-indentation))
17513 (org-indent-line-to column)
17514 (save-excursion (org-indent-line-to column)))
17515 (setq column (current-column))
17516 (beginning-of-line 1)
17517 (if (looking-at
17518 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
17519 (replace-match (concat (match-string 1)
17520 (format org-property-format
17521 (match-string 2) (match-string 3)))
17522 t t))
17523 (org-move-to-column column)))
17525 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
17526 "Variable to store copy of `adaptive-fill-regexp'.
17527 Since `adaptive-fill-regexp' is set to never match, we need to
17528 store a backup of its value before entering `org-mode' so that
17529 the functionality can be provided as a fall-back.")
17531 (defun org-set-autofill-regexps ()
17532 (interactive)
17533 ;; In the paragraph separator we include headlines, because filling
17534 ;; text in a line directly attached to a headline would otherwise
17535 ;; fill the headline as well.
17536 (org-set-local 'comment-start-skip "^#+[ \t]*")
17537 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
17538 ;; The paragraph starter includes hand-formatted lists.
17539 (org-set-local
17540 'paragraph-start
17541 (concat
17542 "\f" "\\|"
17543 "[ ]*$" "\\|"
17544 "\\*+ " "\\|"
17545 "[ \t]*#" "\\|"
17546 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
17547 "[ \t]*[:|]" "\\|"
17548 "\\$\\$" "\\|"
17549 "\\\\\\(begin\\|end\\|[][]\\)"))
17550 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17551 ;; But only if the user has not turned off tables or fixed-width regions
17552 (org-set-local
17553 'auto-fill-inhibit-regexp
17554 (concat "\\*+ \\|#\\+"
17555 "\\|[ \t]*" org-keyword-time-regexp
17556 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17557 (concat
17558 "\\|[ \t]*["
17559 (if org-enable-table-editor "|" "")
17560 (if org-enable-fixed-width-editor ":" "")
17561 "]"))))
17562 ;; We use our own fill-paragraph function, to make sure that tables
17563 ;; and fixed-width regions are not wrapped. That function will pass
17564 ;; through to `fill-paragraph' when appropriate.
17565 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17566 ;; Adaptive filling: To get full control, first make sure that
17567 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17568 (unless (local-variable-p 'adaptive-fill-regexp)
17569 (org-set-local 'org-adaptive-fill-regexp-backup
17570 adaptive-fill-regexp))
17571 (org-set-local 'adaptive-fill-regexp "\000")
17572 (org-set-local 'adaptive-fill-function
17573 'org-adaptive-fill-function)
17574 (org-set-local
17575 'align-mode-rules-list
17576 '((org-in-buffer-settings
17577 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
17578 (modes . '(org-mode))))))
17580 (defun org-fill-paragraph (&optional justify)
17581 "Re-align a table, pass through to fill-paragraph if no table."
17582 (let ((table-p (org-at-table-p))
17583 (table.el-p (org-at-table.el-p)))
17584 (cond ((and (equal (char-after (point-at-bol)) ?*)
17585 (save-excursion (goto-char (point-at-bol))
17586 (looking-at outline-regexp)))
17587 t) ; skip headlines
17588 (table.el-p t) ; skip table.el tables
17589 (table-p (org-table-align) t) ; align org-mode tables
17590 (t nil)))) ; call paragraph-fill
17592 ;; For reference, this is the default value of adaptive-fill-regexp
17593 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17595 (defun org-adaptive-fill-function ()
17596 "Return a fill prefix for org-mode files.
17597 In particular, this makes sure hanging paragraphs for hand-formatted lists
17598 work correctly."
17599 (cond
17600 ;; Comment line
17601 ((looking-at "#[ \t]+")
17602 (match-string-no-properties 0))
17603 ;; Description list
17604 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17605 (save-excursion
17606 (if (> (match-end 1) (+ (match-beginning 1)
17607 org-description-max-indent))
17608 (goto-char (+ (match-beginning 1) 5))
17609 (goto-char (match-end 0)))
17610 (make-string (current-column) ?\ )))
17611 ;; Ordered or unordered list
17612 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)")
17613 (save-excursion
17614 (goto-char (match-end 0))
17615 (make-string (current-column) ?\ )))
17616 ;; Other text
17617 ((looking-at org-adaptive-fill-regexp-backup)
17618 (match-string-no-properties 0))))
17620 ;;; Other stuff.
17622 (defun org-toggle-fixed-width-section (arg)
17623 "Toggle the fixed-width export.
17624 If there is no active region, the QUOTE keyword at the current headline is
17625 inserted or removed. When present, it causes the text between this headline
17626 and the next to be exported as fixed-width text, and unmodified.
17627 If there is an active region, this command adds or removes a colon as the
17628 first character of this line. If the first character of a line is a colon,
17629 this line is also exported in fixed-width font."
17630 (interactive "P")
17631 (let* ((cc 0)
17632 (regionp (org-region-active-p))
17633 (beg (if regionp (region-beginning) (point)))
17634 (end (if regionp (region-end)))
17635 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17636 (case-fold-search nil)
17637 (re "[ \t]*\\(: \\)")
17638 off)
17639 (if regionp
17640 (save-excursion
17641 (goto-char beg)
17642 (setq cc (current-column))
17643 (beginning-of-line 1)
17644 (setq off (looking-at re))
17645 (while (> nlines 0)
17646 (setq nlines (1- nlines))
17647 (beginning-of-line 1)
17648 (cond
17649 (arg
17650 (org-move-to-column cc t)
17651 (insert ": \n")
17652 (forward-line -1))
17653 ((and off (looking-at re))
17654 (replace-match "" t t nil 1))
17655 ((not off) (org-move-to-column cc t) (insert ": ")))
17656 (forward-line 1)))
17657 (save-excursion
17658 (org-back-to-heading)
17659 (if (looking-at (concat outline-regexp
17660 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17661 (replace-match "" t t nil 1)
17662 (if (looking-at outline-regexp)
17663 (progn
17664 (goto-char (match-end 0))
17665 (insert org-quote-string " "))))))))
17667 (defun org-reftex-citation ()
17668 "Use reftex-citation to insert a citation into the buffer.
17669 This looks for a line like
17671 #+BIBLIOGRAPHY: foo plain option:-d
17673 and derives from it that foo.bib is the bibliography file relevant
17674 for this document. It then installs the necessary environment for RefTeX
17675 to work in this buffer and calls `reftex-citation' to insert a citation
17676 into the buffer.
17678 Export of such citations to both LaTeX and HTML is handled by the contributed
17679 package org-exp-bibtex by Taru Karttunen."
17680 (interactive)
17681 (let ((reftex-docstruct-symbol 'rds)
17682 (reftex-cite-format "\\cite{%l}")
17683 rds bib)
17684 (save-excursion
17685 (save-restriction
17686 (widen)
17687 (let ((case-fold-search t)
17688 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17689 (if (not (save-excursion
17690 (or (re-search-forward re nil t)
17691 (re-search-backward re nil t))))
17692 (error "No bibliography defined in file")
17693 (setq bib (concat (match-string 1) ".bib")
17694 rds (list (list 'bib bib)))))))
17695 (call-interactively 'reftex-citation)))
17697 ;;;; Functions extending outline functionality
17699 (defun org-beginning-of-line (&optional arg)
17700 "Go to the beginning of the current line. If that is invisible, continue
17701 to a visible line beginning. This makes the function of C-a more intuitive.
17702 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17703 first attempt, and only move to after the tags when the cursor is already
17704 beyond the end of the headline."
17705 (interactive "P")
17706 (let ((pos (point))
17707 (special (if (consp org-special-ctrl-a/e)
17708 (car org-special-ctrl-a/e)
17709 org-special-ctrl-a/e))
17710 refpos)
17711 (if (org-bound-and-true-p line-move-visual)
17712 (beginning-of-visual-line 1)
17713 (beginning-of-line 1))
17714 (if (and arg (fboundp 'move-beginning-of-line))
17715 (call-interactively 'move-beginning-of-line)
17716 (if (bobp)
17718 (backward-char 1)
17719 (if (org-invisible-p)
17720 (while (and (not (bobp)) (org-invisible-p))
17721 (backward-char 1)
17722 (beginning-of-line 1))
17723 (forward-char 1))))
17724 (when special
17725 (cond
17726 ((and (looking-at org-complex-heading-regexp)
17727 (= (char-after (match-end 1)) ?\ ))
17728 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17729 (point-at-eol)))
17730 (goto-char
17731 (if (eq special t)
17732 (cond ((> pos refpos) refpos)
17733 ((= pos (point)) refpos)
17734 (t (point)))
17735 (cond ((> pos (point)) (point))
17736 ((not (eq last-command this-command)) (point))
17737 (t refpos)))))
17738 ((org-at-item-p)
17739 (goto-char
17740 (if (eq special t)
17741 (cond ((> pos (match-end 4)) (match-end 4))
17742 ((= pos (point)) (match-end 4))
17743 (t (point)))
17744 (cond ((> pos (point)) (point))
17745 ((not (eq last-command this-command)) (point))
17746 (t (match-end 4))))))))
17747 (org-no-warnings
17748 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17750 (defun org-end-of-line (&optional arg)
17751 "Go to the end of the line.
17752 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17753 first attempt, and only move to after the tags when the cursor is already
17754 beyond the end of the headline."
17755 (interactive "P")
17756 (let ((special (if (consp org-special-ctrl-a/e)
17757 (cdr org-special-ctrl-a/e)
17758 org-special-ctrl-a/e)))
17759 (if (or (not special)
17760 (not (org-on-heading-p))
17761 arg)
17762 (call-interactively
17763 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17764 ((fboundp 'move-end-of-line) 'move-end-of-line)
17765 (t 'end-of-line)))
17766 (let ((pos (point)))
17767 (beginning-of-line 1)
17768 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17769 (if (eq special t)
17770 (if (or (< pos (match-beginning 1))
17771 (= pos (match-end 0)))
17772 (goto-char (match-beginning 1))
17773 (goto-char (match-end 0)))
17774 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17775 (goto-char (match-end 0))
17776 (goto-char (match-beginning 1))))
17777 (call-interactively (if (fboundp 'move-end-of-line)
17778 'move-end-of-line
17779 'end-of-line)))))
17780 (org-no-warnings
17781 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17783 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17784 (define-key org-mode-map "\C-e" 'org-end-of-line)
17785 (define-key org-mode-map [home] 'org-beginning-of-line)
17786 (define-key org-mode-map [end] 'org-end-of-line)
17788 (defun org-backward-sentence (&optional arg)
17789 "Go to beginning of sentence, or beginning of table field.
17790 This will call `backward-sentence' or `org-table-beginning-of-field',
17791 depending on context."
17792 (interactive "P")
17793 (cond
17794 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17795 (t (call-interactively 'backward-sentence))))
17797 (defun org-forward-sentence (&optional arg)
17798 "Go to end of sentence, or end of table field.
17799 This will call `forward-sentence' or `org-table-end-of-field',
17800 depending on context."
17801 (interactive "P")
17802 (cond
17803 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17804 (t (call-interactively 'forward-sentence))))
17806 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17807 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17809 (defun org-kill-line (&optional arg)
17810 "Kill line, to tags or end of line."
17811 (interactive "P")
17812 (cond
17813 ((or (not org-special-ctrl-k)
17814 (bolp)
17815 (not (org-on-heading-p)))
17816 (call-interactively 'kill-line))
17817 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17818 (kill-region (point) (match-beginning 1))
17819 (org-set-tags nil t))
17820 (t (kill-region (point) (point-at-eol)))))
17822 (define-key org-mode-map "\C-k" 'org-kill-line)
17824 (defun org-yank (&optional arg)
17825 "Yank. If the kill is a subtree, treat it specially.
17826 This command will look at the current kill and check if is a single
17827 subtree, or a series of subtrees[1]. If it passes the test, and if the
17828 cursor is at the beginning of a line or after the stars of a currently
17829 empty headline, then the yank is handled specially. How exactly depends
17830 on the value of the following variables, both set by default.
17832 org-yank-folded-subtrees
17833 When set, the subtree(s) will be folded after insertion, but only
17834 if doing so would now swallow text after the yanked text.
17836 org-yank-adjusted-subtrees
17837 When set, the subtree will be promoted or demoted in order to
17838 fit into the local outline tree structure, which means that the level
17839 will be adjusted so that it becomes the smaller one of the two
17840 *visible* surrounding headings.
17842 Any prefix to this command will cause `yank' to be called directly with
17843 no special treatment. In particular, a simple `C-u' prefix will just
17844 plainly yank the text as it is.
17846 \[1] The test checks if the first non-white line is a heading
17847 and if there are no other headings with fewer stars."
17848 (interactive "P")
17849 (org-yank-generic 'yank arg))
17851 (defun org-yank-generic (command arg)
17852 "Perform some yank-like command.
17854 This function implements the behavior described in the `org-yank'
17855 documentation. However, it has been generalized to work for any
17856 interactive command with similar behavior."
17858 ;; pretend to be command COMMAND
17859 (setq this-command command)
17861 (if arg
17862 (call-interactively command)
17864 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17865 (and (org-kill-is-subtree-p)
17866 (or (bolp)
17867 (and (looking-at "[ \t]*$")
17868 (string-match
17869 "\\`\\*+\\'"
17870 (buffer-substring (point-at-bol) (point)))))))
17871 swallowp)
17872 (cond
17873 ((and subtreep org-yank-folded-subtrees)
17874 (let ((beg (point))
17875 end)
17876 (if (and subtreep org-yank-adjusted-subtrees)
17877 (org-paste-subtree nil nil 'for-yank)
17878 (call-interactively command))
17880 (setq end (point))
17881 (goto-char beg)
17882 (when (and (bolp) subtreep
17883 (not (setq swallowp
17884 (org-yank-folding-would-swallow-text beg end))))
17885 (or (looking-at outline-regexp)
17886 (re-search-forward (concat "^" outline-regexp) end t))
17887 (while (and (< (point) end) (looking-at outline-regexp))
17888 (hide-subtree)
17889 (org-cycle-show-empty-lines 'folded)
17890 (condition-case nil
17891 (outline-forward-same-level 1)
17892 (error (goto-char end)))))
17893 (when swallowp
17894 (message
17895 "Inserted text not folded because that would swallow text"))
17897 (goto-char end)
17898 (skip-chars-forward " \t\n\r")
17899 (beginning-of-line 1)
17900 (push-mark beg 'nomsg)))
17901 ((and subtreep org-yank-adjusted-subtrees)
17902 (let ((beg (point-at-bol)))
17903 (org-paste-subtree nil nil 'for-yank)
17904 (push-mark beg 'nomsg)))
17906 (call-interactively command))))))
17908 (defun org-yank-folding-would-swallow-text (beg end)
17909 "Would hide-subtree at BEG swallow any text after END?"
17910 (let (level)
17911 (save-excursion
17912 (goto-char beg)
17913 (when (or (looking-at outline-regexp)
17914 (re-search-forward (concat "^" outline-regexp) end t))
17915 (setq level (org-outline-level)))
17916 (goto-char end)
17917 (skip-chars-forward " \t\r\n\v\f")
17918 (if (or (eobp)
17919 (and (bolp) (looking-at org-outline-regexp)
17920 (<= (org-outline-level) level)))
17921 nil ; Nothing would be swallowed
17922 t)))) ; something would swallow
17924 (define-key org-mode-map "\C-y" 'org-yank)
17926 (defun org-invisible-p ()
17927 "Check if point is at a character currently not visible."
17928 ;; Early versions of noutline don't have `outline-invisible-p'.
17929 (if (fboundp 'outline-invisible-p)
17930 (outline-invisible-p)
17931 (get-char-property (point) 'invisible)))
17933 (defun org-invisible-p2 ()
17934 "Check if point is at a character currently not visible."
17935 (save-excursion
17936 (if (and (eolp) (not (bobp))) (backward-char 1))
17937 ;; Early versions of noutline don't have `outline-invisible-p'.
17938 (if (fboundp 'outline-invisible-p)
17939 (outline-invisible-p)
17940 (get-char-property (point) 'invisible))))
17942 (defun org-back-to-heading (&optional invisible-ok)
17943 "Call `outline-back-to-heading', but provide a better error message."
17944 (condition-case nil
17945 (outline-back-to-heading invisible-ok)
17946 (error (error "Before first headline at position %d in buffer %s"
17947 (point) (current-buffer)))))
17949 (defun org-before-first-heading-p ()
17950 "Before first heading?"
17951 (save-excursion
17952 (null (re-search-backward "^\\*+ " nil t))))
17954 (defun org-on-heading-p (&optional ignored)
17955 (outline-on-heading-p t))
17956 (defun org-at-heading-p (&optional ignored)
17957 (outline-on-heading-p t))
17959 (defun org-point-at-end-of-empty-headline ()
17960 "If point is at the end of an empty headline, return t, else nil.
17961 If the heading only contains a TODO keyword, it is still still considered
17962 empty."
17963 (and (looking-at "[ \t]*$")
17964 (save-excursion
17965 (beginning-of-line 1)
17966 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
17967 "\\)?[ \t]*$")))))
17968 (defun org-at-heading-or-item-p ()
17969 (or (org-on-heading-p) (org-at-item-p)))
17971 (defun org-on-target-p ()
17972 (or (org-in-regexp org-radio-target-regexp)
17973 (org-in-regexp org-target-regexp)))
17975 (defun org-up-heading-all (arg)
17976 "Move to the heading line of which the present line is a subheading.
17977 This function considers both visible and invisible heading lines.
17978 With argument, move up ARG levels."
17979 (if (fboundp 'outline-up-heading-all)
17980 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17981 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17983 (defun org-up-heading-safe ()
17984 "Move to the heading line of which the present line is a subheading.
17985 This version will not throw an error. It will return the level of the
17986 headline found, or nil if no higher level is found.
17988 Also, this function will be a lot faster than `outline-up-heading',
17989 because it relies on stars being the outline starters. This can really
17990 make a significant difference in outlines with very many siblings."
17991 (let (start-level re)
17992 (org-back-to-heading t)
17993 (setq start-level (funcall outline-level))
17994 (if (equal start-level 1)
17996 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17997 (if (re-search-backward re nil t)
17998 (funcall outline-level)))))
18000 (defun org-first-sibling-p ()
18001 "Is this heading the first child of its parents?"
18002 (interactive)
18003 (let ((re (concat "^" outline-regexp))
18004 level l)
18005 (unless (org-at-heading-p t)
18006 (error "Not at a heading"))
18007 (setq level (funcall outline-level))
18008 (save-excursion
18009 (if (not (re-search-backward re nil t))
18011 (setq l (funcall outline-level))
18012 (< l level)))))
18014 (defun org-goto-sibling (&optional previous)
18015 "Goto the next sibling, even if it is invisible.
18016 When PREVIOUS is set, go to the previous sibling instead. Returns t
18017 when a sibling was found. When none is found, return nil and don't
18018 move point."
18019 (let ((fun (if previous 're-search-backward 're-search-forward))
18020 (pos (point))
18021 (re (concat "^" outline-regexp))
18022 level l)
18023 (when (condition-case nil (org-back-to-heading t) (error nil))
18024 (setq level (funcall outline-level))
18025 (catch 'exit
18026 (or previous (forward-char 1))
18027 (while (funcall fun re nil t)
18028 (setq l (funcall outline-level))
18029 (when (< l level) (goto-char pos) (throw 'exit nil))
18030 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
18031 (goto-char pos)
18032 nil))))
18034 (defun org-show-siblings ()
18035 "Show all siblings of the current headline."
18036 (save-excursion
18037 (while (org-goto-sibling) (org-flag-heading nil)))
18038 (save-excursion
18039 (while (org-goto-sibling 'previous)
18040 (org-flag-heading nil))))
18042 (defun org-show-hidden-entry ()
18043 "Show an entry where even the heading is hidden."
18044 (save-excursion
18045 (org-show-entry)))
18047 (defun org-flag-heading (flag &optional entry)
18048 "Flag the current heading. FLAG non-nil means make invisible.
18049 When ENTRY is non-nil, show the entire entry."
18050 (save-excursion
18051 (org-back-to-heading t)
18052 ;; Check if we should show the entire entry
18053 (if entry
18054 (progn
18055 (org-show-entry)
18056 (save-excursion
18057 (and (outline-next-heading)
18058 (org-flag-heading nil))))
18059 (outline-flag-region (max (point-min) (1- (point)))
18060 (save-excursion (outline-end-of-heading) (point))
18061 flag))))
18063 (defun org-get-next-sibling ()
18064 "Move to next heading of the same level, and return point.
18065 If there is no such heading, return nil.
18066 This is like outline-next-sibling, but invisible headings are ok."
18067 (let ((level (funcall outline-level)))
18068 (outline-next-heading)
18069 (while (and (not (eobp)) (> (funcall outline-level) level))
18070 (outline-next-heading))
18071 (if (or (eobp) (< (funcall outline-level) level))
18073 (point))))
18075 (defun org-get-last-sibling ()
18076 "Move to previous heading of the same level, and return point.
18077 If there is no such heading, return nil."
18078 (let ((opoint (point))
18079 (level (funcall outline-level)))
18080 (outline-previous-heading)
18081 (when (and (/= (point) opoint) (outline-on-heading-p t))
18082 (while (and (> (funcall outline-level) level)
18083 (not (bobp)))
18084 (outline-previous-heading))
18085 (if (< (funcall outline-level) level)
18087 (point)))))
18089 (defun org-end-of-subtree (&optional invisible-OK to-heading)
18090 ;; This contains an exact copy of the original function, but it uses
18091 ;; `org-back-to-heading', to make it work also in invisible
18092 ;; trees. And is uses an invisible-OK argument.
18093 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
18094 ;; Furthermore, when used inside Org, finding the end of a large subtree
18095 ;; with many children and grandchildren etc, this can be much faster
18096 ;; than the outline version.
18097 (org-back-to-heading invisible-OK)
18098 (let ((first t)
18099 (level (funcall outline-level)))
18100 (if (and (org-mode-p) (< level 1000))
18101 ;; A true heading (not a plain list item), in Org-mode
18102 ;; This means we can easily find the end by looking
18103 ;; only for the right number of stars. Using a regexp to do
18104 ;; this is so much faster than using a Lisp loop.
18105 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
18106 (forward-char 1)
18107 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
18108 ;; something else, do it the slow way
18109 (while (and (not (eobp))
18110 (or first (> (funcall outline-level) level)))
18111 (setq first nil)
18112 (outline-next-heading)))
18113 (unless to-heading
18114 (if (memq (preceding-char) '(?\n ?\^M))
18115 (progn
18116 ;; Go to end of line before heading
18117 (forward-char -1)
18118 (if (memq (preceding-char) '(?\n ?\^M))
18119 ;; leave blank line before heading
18120 (forward-char -1))))))
18121 (point))
18123 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
18124 "Use Org version in org-mode, for dramatic speed-up."
18125 (if (eq major-mode 'org-mode)
18126 (progn
18127 (org-end-of-subtree nil t)
18128 (unless (eobp) (backward-char 1)))
18129 ad-do-it))
18131 (defun org-forward-same-level (arg &optional invisible-ok)
18132 "Move forward to the arg'th subheading at same level as this one.
18133 Stop at the first and last subheadings of a superior heading."
18134 (interactive "p")
18135 (org-back-to-heading invisible-ok)
18136 (org-on-heading-p)
18137 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18138 (re (format "^\\*\\{1,%d\\} " level))
18140 (forward-char 1)
18141 (while (> arg 0)
18142 (while (and (re-search-forward re nil 'move)
18143 (setq l (- (match-end 0) (match-beginning 0) 1))
18144 (= l level)
18145 (not invisible-ok)
18146 (progn (backward-char 1) (org-invisible-p)))
18147 (if (< l level) (setq arg 1)))
18148 (setq arg (1- arg)))
18149 (beginning-of-line 1)))
18151 (defun org-backward-same-level (arg &optional invisible-ok)
18152 "Move backward to the arg'th subheading at same level as this one.
18153 Stop at the first and last subheadings of a superior heading."
18154 (interactive "p")
18155 (org-back-to-heading)
18156 (org-on-heading-p)
18157 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18158 (re (format "^\\*\\{1,%d\\} " level))
18160 (while (> arg 0)
18161 (while (and (re-search-backward re nil 'move)
18162 (setq l (- (match-end 0) (match-beginning 0) 1))
18163 (= l level)
18164 (not invisible-ok)
18165 (org-invisible-p))
18166 (if (< l level) (setq arg 1)))
18167 (setq arg (1- arg)))))
18169 (defun org-show-subtree ()
18170 "Show everything after this heading at deeper levels."
18171 (outline-flag-region
18172 (point)
18173 (save-excursion
18174 (org-end-of-subtree t t))
18175 nil))
18177 (defun org-show-entry ()
18178 "Show the body directly following this heading.
18179 Show the heading too, if it is currently invisible."
18180 (interactive)
18181 (save-excursion
18182 (condition-case nil
18183 (progn
18184 (org-back-to-heading t)
18185 (outline-flag-region
18186 (max (point-min) (1- (point)))
18187 (save-excursion
18188 (if (re-search-forward
18189 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
18190 (match-beginning 1)
18191 (point-max)))
18192 nil)
18193 (org-cycle-hide-drawers 'children))
18194 (error nil))))
18196 (defun org-make-options-regexp (kwds &optional extra)
18197 "Make a regular expression for keyword lines."
18198 (concat
18200 "#?[ \t]*\\+\\("
18201 (mapconcat 'regexp-quote kwds "\\|")
18202 (if extra (concat "\\|" extra))
18203 "\\):[ \t]*"
18204 "\\(.*\\)"))
18206 ;; Make isearch reveal the necessary context
18207 (defun org-isearch-end ()
18208 "Reveal context after isearch exits."
18209 (when isearch-success ; only if search was successful
18210 (if (featurep 'xemacs)
18211 ;; Under XEmacs, the hook is run in the correct place,
18212 ;; we directly show the context.
18213 (org-show-context 'isearch)
18214 ;; In Emacs the hook runs *before* restoring the overlays.
18215 ;; So we have to use a one-time post-command-hook to do this.
18216 ;; (Emacs 22 has a special variable, see function `org-mode')
18217 (unless (and (boundp 'isearch-mode-end-hook-quit)
18218 isearch-mode-end-hook-quit)
18219 ;; Only when the isearch was not quitted.
18220 (org-add-hook 'post-command-hook 'org-isearch-post-command
18221 'append 'local)))))
18223 (defun org-isearch-post-command ()
18224 "Remove self from hook, and show context."
18225 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
18226 (org-show-context 'isearch))
18229 ;;;; Integration with and fixes for other packages
18231 ;;; Imenu support
18233 (defvar org-imenu-markers nil
18234 "All markers currently used by Imenu.")
18235 (make-variable-buffer-local 'org-imenu-markers)
18237 (defun org-imenu-new-marker (&optional pos)
18238 "Return a new marker for use by Imenu, and remember the marker."
18239 (let ((m (make-marker)))
18240 (move-marker m (or pos (point)))
18241 (push m org-imenu-markers)
18244 (defun org-imenu-get-tree ()
18245 "Produce the index for Imenu."
18246 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
18247 (setq org-imenu-markers nil)
18248 (let* ((n org-imenu-depth)
18249 (re (concat "^" outline-regexp))
18250 (subs (make-vector (1+ n) nil))
18251 (last-level 0)
18252 m level head)
18253 (save-excursion
18254 (save-restriction
18255 (widen)
18256 (goto-char (point-max))
18257 (while (re-search-backward re nil t)
18258 (setq level (org-reduced-level (funcall outline-level)))
18259 (when (<= level n)
18260 (looking-at org-complex-heading-regexp)
18261 (setq head (org-link-display-format
18262 (org-match-string-no-properties 4))
18263 m (org-imenu-new-marker))
18264 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
18265 (if (>= level last-level)
18266 (push (cons head m) (aref subs level))
18267 (push (cons head (aref subs (1+ level))) (aref subs level))
18268 (loop for i from (1+ level) to n do (aset subs i nil)))
18269 (setq last-level level)))))
18270 (aref subs 1)))
18272 (eval-after-load "imenu"
18273 '(progn
18274 (add-hook 'imenu-after-jump-hook
18275 (lambda ()
18276 (if (eq major-mode 'org-mode)
18277 (org-show-context 'org-goto))))))
18279 (defun org-link-display-format (link)
18280 "Replace a link with either the description, or the link target
18281 if no description is present"
18282 (save-match-data
18283 (if (string-match org-bracket-link-analytic-regexp link)
18284 (replace-match (if (match-end 5)
18285 (match-string 5 link)
18286 (concat (match-string 1 link)
18287 (match-string 3 link)))
18288 nil t link)
18289 link)))
18291 ;; Speedbar support
18293 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
18294 "Overlay marking the agenda restriction line in speedbar.")
18295 (org-overlay-put org-speedbar-restriction-lock-overlay
18296 'face 'org-agenda-restriction-lock)
18297 (org-overlay-put org-speedbar-restriction-lock-overlay
18298 'help-echo "Agendas are currently limited to this item.")
18299 (org-detach-overlay org-speedbar-restriction-lock-overlay)
18301 (defun org-speedbar-set-agenda-restriction ()
18302 "Restrict future agenda commands to the location at point in speedbar.
18303 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
18304 (interactive)
18305 (require 'org-agenda)
18306 (let (p m tp np dir txt)
18307 (cond
18308 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18309 'org-imenu t))
18310 (setq m (get-text-property p 'org-imenu-marker))
18311 (with-current-buffer (marker-buffer m)
18312 (goto-char m)
18313 (org-agenda-set-restriction-lock 'subtree)))
18314 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18315 'speedbar-function 'speedbar-find-file))
18316 (setq tp (previous-single-property-change
18317 (1+ p) 'speedbar-function)
18318 np (next-single-property-change
18319 tp 'speedbar-function)
18320 dir (speedbar-line-directory)
18321 txt (buffer-substring-no-properties (or tp (point-min))
18322 (or np (point-max))))
18323 (with-current-buffer (find-file-noselect
18324 (let ((default-directory dir))
18325 (expand-file-name txt)))
18326 (unless (org-mode-p)
18327 (error "Cannot restrict to non-Org-mode file"))
18328 (org-agenda-set-restriction-lock 'file)))
18329 (t (error "Don't know how to restrict Org-mode's agenda")))
18330 (org-move-overlay org-speedbar-restriction-lock-overlay
18331 (point-at-bol) (point-at-eol))
18332 (setq current-prefix-arg nil)
18333 (org-agenda-maybe-redo)))
18335 (eval-after-load "speedbar"
18336 '(progn
18337 (speedbar-add-supported-extension ".org")
18338 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
18339 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
18340 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
18341 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18342 (add-hook 'speedbar-visiting-tag-hook
18343 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
18346 ;;; Fixes and Hacks for problems with other packages
18348 ;; Make flyspell not check words in links, to not mess up our keymap
18349 (defun org-mode-flyspell-verify ()
18350 "Don't let flyspell put overlays at active buttons."
18351 (and (not (get-text-property (point) 'keymap))
18352 (not (get-text-property (point) 'org-no-flyspell))))
18354 (defun org-remove-flyspell-overlays-in (beg end)
18355 "Remove flyspell overlays in region."
18356 (and (org-bound-and-true-p flyspell-mode)
18357 (fboundp 'flyspell-delete-region-overlays)
18358 (flyspell-delete-region-overlays beg end))
18359 (add-text-properties beg end '(org-no-flyspell t)))
18361 ;; Make `bookmark-jump' shows the jump location if it was hidden.
18362 (eval-after-load "bookmark"
18363 '(if (boundp 'bookmark-after-jump-hook)
18364 ;; We can use the hook
18365 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
18366 ;; Hook not available, use advice
18367 (defadvice bookmark-jump (after org-make-visible activate)
18368 "Make the position visible."
18369 (org-bookmark-jump-unhide))))
18371 ;; Make sure saveplace shows the location if it was hidden
18372 (eval-after-load "saveplace"
18373 '(defadvice save-place-find-file-hook (after org-make-visible activate)
18374 "Make the position visible."
18375 (org-bookmark-jump-unhide)))
18377 ;; Make sure ecb shows the location if it was hidden
18378 (eval-after-load "ecb"
18379 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
18380 "Make hierarchy visible when jumping into location from ECB tree buffer."
18381 (if (eq major-mode 'org-mode)
18382 (org-show-context))))
18384 (defun org-bookmark-jump-unhide ()
18385 "Unhide the current position, to show the bookmark location."
18386 (and (org-mode-p)
18387 (or (org-invisible-p)
18388 (save-excursion (goto-char (max (point-min) (1- (point))))
18389 (org-invisible-p)))
18390 (org-show-context 'bookmark-jump)))
18392 ;; Make session.el ignore our circular variable
18393 (eval-after-load "session"
18394 '(add-to-list 'session-globals-exclude 'org-mark-ring))
18396 ;;;; Experimental code
18398 (defun org-closed-in-range ()
18399 "Sparse tree of items closed in a certain time range.
18400 Still experimental, may disappear in the future."
18401 (interactive)
18402 ;; Get the time interval from the user.
18403 (let* ((time1 (org-float-time
18404 (org-read-date nil 'to-time nil "Starting date: ")))
18405 (time2 (org-float-time
18406 (org-read-date nil 'to-time nil "End date:")))
18407 ;; callback function
18408 (callback (lambda ()
18409 (let ((time
18410 (org-float-time
18411 (apply 'encode-time
18412 (org-parse-time-string
18413 (match-string 1))))))
18414 ;; check if time in interval
18415 (and (>= time time1) (<= time time2))))))
18416 ;; make tree, check each match with the callback
18417 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
18419 ;;;; Finish up
18421 (provide 'org)
18423 (run-hooks 'org-load-hook)
18425 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
18427 ;;; org.el ends here