Make it possible to record logbook entries when scheduling/deadlines change
[org-mode.git] / lisp / org.el
blob8f2bea78cf26ac44f08c235659d6f9f2a759a80e
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.32trans
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum)
76 (require 'calendar))
77 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
78 ;; the file noutline.el being loaded.
79 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
80 ;; We require noutline, which might be provided in outline.el
81 (require 'outline) (require 'noutline)
82 ;; Other stuff we need.
83 (require 'time-date)
84 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
85 (require 'easymenu)
87 (require 'org-macs)
88 (require 'org-compat)
89 (require 'org-faces)
90 (require 'org-list)
91 (require 'org-src)
92 (require 'org-footnote)
94 ;;;; Customization variables
96 ;;; Version
98 (defconst org-version "6.32trans"
99 "The version number of the file org.el.")
101 (defun org-version (&optional here)
102 "Show the org-mode version in the echo area.
103 With prefix arg HERE, insert it at point."
104 (interactive "P")
105 (let* ((version org-version)
106 (git-version)
107 (dir (concat (file-name-directory (locate-library "org")) "../" )))
108 (if (and (file-exists-p (expand-file-name ".git" dir))
109 (executable-find "git"))
110 (let ((pwd (substring (pwd) 10)))
111 (cd dir)
112 (if (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
113 (with-current-buffer "*Shell Command Output*"
114 (goto-char (point-min))
115 (re-search-forward "[^\n]+")
116 (setq git-version (match-string 0))
117 (subst-char-in-string ?- ?. git-version t)
118 (shell-command "git diff-index --name-only HEAD --")
119 (unless (eql 1 (point-max))
120 (setq git-version (concat git-version ".dirty")))
121 (setq version (concat version " (" git-version ")")))
122 (cd pwd))))
123 (setq version (format "Org-mode version %s" version))
124 (if here (insert version))
125 (message version)
126 version))
128 ;;; Compatibility constants
130 ;;; The custom variables
132 (defgroup org nil
133 "Outline-based notes management and organizer."
134 :tag "Org"
135 :group 'outlines
136 :group 'hypermedia
137 :group 'calendar)
139 (defcustom org-mode-hook nil
140 "Mode hook for Org-mode, run after the mode was turned on."
141 :group 'org
142 :type 'hook)
144 (defcustom org-load-hook nil
145 "Hook that is run after org.el has been loaded."
146 :group 'org
147 :type 'hook)
149 (defvar org-modules) ; defined below
150 (defvar org-modules-loaded nil
151 "Have the modules been loaded already?")
153 (defun org-load-modules-maybe (&optional force)
154 "Load all extensions listed in `org-modules'."
155 (when (or force (not org-modules-loaded))
156 (mapc (lambda (ext)
157 (condition-case nil (require ext)
158 (error (message "Problems while trying to load feature `%s'" ext))))
159 org-modules)
160 (setq org-modules-loaded t)))
162 (defun org-set-modules (var value)
163 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
164 (set var value)
165 (when (featurep 'org)
166 (org-load-modules-maybe 'force)))
168 (when (org-bound-and-true-p org-modules)
169 (let ((a (member 'org-infojs org-modules)))
170 (and a (setcar a 'org-jsinfo))))
172 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
173 "Modules that should always be loaded together with org.el.
174 If a description starts with <C>, the file is not part of Emacs
175 and loading it will require that you have downloaded and properly installed
176 the org-mode distribution.
178 You can also use this system to load external packages (i.e. neither Org
179 core modules, nor modules from the CONTRIB directory). Just add symbols
180 to the end of the list. If the package is called org-xyz.el, then you need
181 to add the symbol `xyz', and the package must have a call to
183 (provide 'org-xyz)"
184 :group 'org
185 :set 'org-set-modules
186 :type
187 '(set :greedy t
188 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
189 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
190 (const :tag " crypt: Encryption of subtrees" org-crypt)
191 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
192 (const :tag " id: Global IDs for identifying entries" org-id)
193 (const :tag " info: Links to Info nodes" org-info)
194 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
195 (const :tag " habit: Track your consistency with habits" org-habit)
196 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
197 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
198 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
199 (const :tag " mew Links to Mew folders/messages" org-mew)
200 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
201 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
202 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
203 (const :tag " vm: Links to VM folders/messages" org-vm)
204 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
205 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
206 (const :tag " mouse: Additional mouse support" org-mouse)
208 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
209 (const :tag "C annotation-helper: Call Remember directly from Browser\n\t\t\t(OBSOLETE, use org-protocol)" org-annotation-helper)
210 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
211 (const :tag "C browser-url: Store link, directly from Browser\n\t\t\t(OBSOLETE, use org-protocol)" org-browser-url)
212 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
213 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
214 (const :tag "C collector: Collect properties into tables" org-collector)
215 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
216 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
217 (const :tag "C eval: Include command output as text" org-eval)
218 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
219 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
220 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
221 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
222 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
224 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
226 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
227 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
228 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
229 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
230 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
231 (const :tag "C mtags: Support for muse-like tags" org-mtags)
232 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
233 (const :tag "C R: Computation using the R language" org-R)
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 special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
238 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
239 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
240 (const :tag "C track: Keep up with Org-mode development" org-track)
241 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
243 (defcustom org-support-shift-select nil
244 "Non-nil means, make shift-cursor commands select text when possible.
246 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
247 selecting a region, or enlarge thusly regions started in this way.
248 In Org-mode, in special contexts, these same keys are used for other
249 purposes, important enough to compete with shift selection. Org tries
250 to balance these needs by supporting `shift-select-mode' outside these
251 special contexts, under control of this variable.
253 The default of this variable is nil, to avoid confusing behavior. Shifted
254 cursor keys will then execute Org commands in the following contexts:
255 - on a headline, changing TODO state (left/right) and priority (up/down)
256 - on a time stamp, changing the time
257 - in a plain list item, changing the bullet type
258 - in a property definition line, switching between allowed values
259 - in the BEGIN line of a clock table (changing the time block).
260 Outside these contexts, the commands will throw an error.
262 When this variable is t and the cursor is not in a special context,
263 Org-mode will support shift-selection for making and enlarging regions.
264 To make this more effective, the bullet cycling will no longer happen
265 anywhere in an item line, but only if the cursor is exactly on the bullet.
267 If you set this variable to the symbol `always', then the keys
268 will not be special in headlines, property lines, and item lines, to make
269 shift selection work there as well. If this is what you want, you can
270 use the following alternative commands: `C-c C-t' and `C-c ,' to
271 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
272 TODO sets, `C-c -' to cycle item bullet types, and properties can be
273 edited by hand or in column view.
275 However, when the cursor is on a timestamp, shift-cursor commands
276 will still edit the time stamp - this is just too good to give up.
278 XEmacs user should have this variable set to nil, because shift-select-mode
279 is Emacs 23 only."
280 :group 'org
281 :type '(choice
282 (const :tag "Never" nil)
283 (const :tag "When outside special context" t)
284 (const :tag "Everywhere except timestamps" always)))
286 (defgroup org-startup nil
287 "Options concerning startup of Org-mode."
288 :tag "Org Startup"
289 :group 'org)
291 (defcustom org-startup-folded t
292 "Non-nil means, entering Org-mode will switch to OVERVIEW.
293 This can also be configured on a per-file basis by adding one of
294 the following lines anywhere in the buffer:
296 #+STARTUP: fold (or `overview', this is equivalent)
297 #+STARTUP: nofold (or `showall', this is equivalent)
298 #+STARTUP: content
299 #+STARTUP: showeverything"
300 :group 'org-startup
301 :type '(choice
302 (const :tag "nofold: show all" nil)
303 (const :tag "fold: overview" t)
304 (const :tag "content: all headlines" content)
305 (const :tag "show everything, even drawers" showeverything)))
307 (defcustom org-startup-truncated t
308 "Non-nil means, entering Org-mode will set `truncate-lines'.
309 This is useful since some lines containing links can be very long and
310 uninteresting. Also tables look terrible when wrapped."
311 :group 'org-startup
312 :type 'boolean)
314 (defcustom org-startup-indented nil
315 "Non-nil means, turn on `org-indent-mode' on startup.
316 This can also be configured on a per-file basis by adding one of
317 the following lines anywhere in the buffer:
319 #+STARTUP: indent
320 #+STARTUP: noindent"
321 :group 'org-structure
322 :type '(choice
323 (const :tag "Not" nil)
324 (const :tag "Globally (slow on startup in large files)" t)))
326 (defcustom org-startup-align-all-tables nil
327 "Non-nil means, align all tables when visiting a file.
328 This is useful when the column width in tables is forced with <N> cookies
329 in table fields. Such tables will look correct only after the first re-align.
330 This can also be configured on a per-file basis by adding one of
331 the following lines anywhere in the buffer:
332 #+STARTUP: align
333 #+STARTUP: noalign"
334 :group 'org-startup
335 :type 'boolean)
337 (defcustom org-insert-mode-line-in-empty-file nil
338 "Non-nil means insert the first line setting Org-mode in empty files.
339 When the function `org-mode' is called interactively in an empty file, this
340 normally means that the file name does not automatically trigger Org-mode.
341 To ensure that the file will always be in Org-mode in the future, a
342 line enforcing Org-mode will be inserted into the buffer, if this option
343 has been set."
344 :group 'org-startup
345 :type 'boolean)
347 (defcustom org-replace-disputed-keys nil
348 "Non-nil means use alternative key bindings for some keys.
349 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
350 These keys are also used by other packages like shift-selection-mode'
351 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
352 If you want to use Org-mode together with one of these other modes,
353 or more generally if you would like to move some Org-mode commands to
354 other keys, set this variable and configure the keys with the variable
355 `org-disputed-keys'.
357 This option is only relevant at load-time of Org-mode, and must be set
358 *before* org.el is loaded. Changing it requires a restart of Emacs to
359 become effective."
360 :group 'org-startup
361 :type 'boolean)
363 (defcustom org-use-extra-keys nil
364 "Non-nil means use extra key sequence definitions for certain
365 commands. This happens automatically if you run XEmacs or if
366 window-system is nil. This variable lets you do the same
367 manually. You must set it before loading org.
369 Example: on Carbon Emacs 22 running graphically, with an external
370 keyboard on a Powerbook, the default way of setting M-left might
371 not work for either Alt or ESC. Setting this variable will make
372 it work for ESC."
373 :group 'org-startup
374 :type 'boolean)
376 (if (fboundp 'defvaralias)
377 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
379 (defcustom org-disputed-keys
380 '(([(shift up)] . [(meta p)])
381 ([(shift down)] . [(meta n)])
382 ([(shift left)] . [(meta -)])
383 ([(shift right)] . [(meta +)])
384 ([(control shift right)] . [(meta shift +)])
385 ([(control shift left)] . [(meta shift -)]))
386 "Keys for which Org-mode and other modes compete.
387 This is an alist, cars are the default keys, second element specifies
388 the alternative to use when `org-replace-disputed-keys' is t.
390 Keys can be specified in any syntax supported by `define-key'.
391 The value of this option takes effect only at Org-mode's startup,
392 therefore you'll have to restart Emacs to apply it after changing."
393 :group 'org-startup
394 :type 'alist)
396 (defun org-key (key)
397 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
398 Or return the original if not disputed."
399 (if org-replace-disputed-keys
400 (let* ((nkey (key-description key))
401 (x (org-find-if (lambda (x)
402 (equal (key-description (car x)) nkey))
403 org-disputed-keys)))
404 (if x (cdr x) key))
405 key))
407 (defun org-find-if (predicate seq)
408 (catch 'exit
409 (while seq
410 (if (funcall predicate (car seq))
411 (throw 'exit (car seq))
412 (pop seq)))))
414 (defun org-defkey (keymap key def)
415 "Define a key, possibly translated, as returned by `org-key'."
416 (define-key keymap (org-key key) def))
418 (defcustom org-ellipsis nil
419 "The ellipsis to use in the Org-mode outline.
420 When nil, just use the standard three dots. When a string, use that instead,
421 When a face, use the standard 3 dots, but with the specified face.
422 The change affects only Org-mode (which will then use its own display table).
423 Changing this requires executing `M-x org-mode' in a buffer to become
424 effective."
425 :group 'org-startup
426 :type '(choice (const :tag "Default" nil)
427 (face :tag "Face" :value org-warning)
428 (string :tag "String" :value "...#")))
430 (defvar org-display-table nil
431 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
433 (defgroup org-keywords nil
434 "Keywords in Org-mode."
435 :tag "Org Keywords"
436 :group 'org)
438 (defcustom org-deadline-string "DEADLINE:"
439 "String to mark deadline entries.
440 A deadline is this string, followed by a time stamp. Should be a word,
441 terminated by a colon. You can insert a schedule keyword and
442 a timestamp with \\[org-deadline].
443 Changes become only effective after restarting Emacs."
444 :group 'org-keywords
445 :type 'string)
447 (defcustom org-scheduled-string "SCHEDULED:"
448 "String to mark scheduled TODO entries.
449 A schedule is this string, followed by a time stamp. Should be a word,
450 terminated by a colon. You can insert a schedule keyword and
451 a timestamp with \\[org-schedule].
452 Changes become only effective after restarting Emacs."
453 :group 'org-keywords
454 :type 'string)
456 (defcustom org-closed-string "CLOSED:"
457 "String used as the prefix for timestamps logging closing a TODO entry."
458 :group 'org-keywords
459 :type 'string)
461 (defcustom org-clock-string "CLOCK:"
462 "String used as prefix for timestamps clocking work hours on an item."
463 :group 'org-keywords
464 :type 'string)
466 (defcustom org-comment-string "COMMENT"
467 "Entries starting with this keyword will never be exported.
468 An entry can be toggled between COMMENT and normal with
469 \\[org-toggle-comment].
470 Changes become only effective after restarting Emacs."
471 :group 'org-keywords
472 :type 'string)
474 (defcustom org-quote-string "QUOTE"
475 "Entries starting with this keyword will be exported in fixed-width font.
476 Quoting applies only to the text in the entry following the headline, and does
477 not extend beyond the next headline, even if that is lower level.
478 An entry can be toggled between QUOTE and normal with
479 \\[org-toggle-fixed-width-section]."
480 :group 'org-keywords
481 :type 'string)
483 (defconst org-repeat-re
484 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
485 "Regular expression for specifying repeated events.
486 After a match, group 1 contains the repeat expression.")
488 (defgroup org-structure nil
489 "Options concerning the general structure of Org-mode files."
490 :tag "Org Structure"
491 :group 'org)
493 (defgroup org-reveal-location nil
494 "Options about how to make context of a location visible."
495 :tag "Org Reveal Location"
496 :group 'org-structure)
498 (defconst org-context-choice
499 '(choice
500 (const :tag "Always" t)
501 (const :tag "Never" nil)
502 (repeat :greedy t :tag "Individual contexts"
503 (cons
504 (choice :tag "Context"
505 (const agenda)
506 (const org-goto)
507 (const occur-tree)
508 (const tags-tree)
509 (const link-search)
510 (const mark-goto)
511 (const bookmark-jump)
512 (const isearch)
513 (const default))
514 (boolean))))
515 "Contexts for the reveal options.")
517 (defcustom org-show-hierarchy-above '((default . t))
518 "Non-nil means, show full hierarchy when revealing a location.
519 Org-mode often shows locations in an org-mode file which might have
520 been invisible before. When this is set, the hierarchy of headings
521 above the exposed location is shown.
522 Turning this off for example for sparse trees makes them very compact.
523 Instead of t, this can also be an alist specifying this option for different
524 contexts. Valid contexts are
525 agenda when exposing an entry from the agenda
526 org-goto when using the command `org-goto' on key C-c C-j
527 occur-tree when using the command `org-occur' on key C-c /
528 tags-tree when constructing a sparse tree based on tags matches
529 link-search when exposing search matches associated with a link
530 mark-goto when exposing the jump goal of a mark
531 bookmark-jump when exposing a bookmark location
532 isearch when exiting from an incremental search
533 default default for all contexts not set explicitly"
534 :group 'org-reveal-location
535 :type org-context-choice)
537 (defcustom org-show-following-heading '((default . nil))
538 "Non-nil means, show following heading when revealing a location.
539 Org-mode often shows locations in an org-mode file which might have
540 been invisible before. When this is set, the heading following the
541 match is shown.
542 Turning this off for example for sparse trees makes them very compact,
543 but makes it harder to edit the location of the match. In such a case,
544 use the command \\[org-reveal] to show more context.
545 Instead of t, this can also be an alist specifying this option for different
546 contexts. See `org-show-hierarchy-above' for valid contexts."
547 :group 'org-reveal-location
548 :type org-context-choice)
550 (defcustom org-show-siblings '((default . nil) (isearch t))
551 "Non-nil means, show all sibling heading when revealing a location.
552 Org-mode often shows locations in an org-mode file which might have
553 been invisible before. When this is set, the sibling of the current entry
554 heading are all made visible. If `org-show-hierarchy-above' is t,
555 the same happens on each level of the hierarchy above the current entry.
557 By default this is on for the isearch context, off for all other contexts.
558 Turning this off for example for sparse trees makes them very compact,
559 but makes it harder to edit the location of the match. In such a case,
560 use the command \\[org-reveal] to show more context.
561 Instead of t, this can also be an alist specifying this option for different
562 contexts. See `org-show-hierarchy-above' for valid contexts."
563 :group 'org-reveal-location
564 :type org-context-choice)
566 (defcustom org-show-entry-below '((default . nil))
567 "Non-nil means, show the entry below a headline when revealing a location.
568 Org-mode often shows locations in an org-mode file which might have
569 been invisible before. When this is set, the text below the headline that is
570 exposed is also shown.
572 By default this is off for all contexts.
573 Instead of t, this can also be an alist specifying this option for different
574 contexts. See `org-show-hierarchy-above' for valid contexts."
575 :group 'org-reveal-location
576 :type org-context-choice)
578 (defcustom org-indirect-buffer-display 'other-window
579 "How should indirect tree buffers be displayed?
580 This applies to indirect buffers created with the commands
581 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
582 Valid values are:
583 current-window Display in the current window
584 other-window Just display in another window.
585 dedicated-frame Create one new frame, and re-use it each time.
586 new-frame Make a new frame each time. Note that in this case
587 previously-made indirect buffers are kept, and you need to
588 kill these buffers yourself."
589 :group 'org-structure
590 :group 'org-agenda-windows
591 :type '(choice
592 (const :tag "In current window" current-window)
593 (const :tag "In current frame, other window" other-window)
594 (const :tag "Each time a new frame" new-frame)
595 (const :tag "One dedicated frame" dedicated-frame)))
597 (defcustom org-use-speed-commands nil
598 "Non-nil means, activate single letter commands at beginning of a headline."
599 :group 'org-structure
600 :type 'boolean)
602 (defcustom org-speed-commands-user nil
603 "Alist of additional speed commands.
604 This list will be checked before `org-speed-commands-default'
605 when the variable `org-use-speed-commands' is non-nil
606 and when the cursor is at the beginning of a headline.
607 The car if each entry is a string with a single letter, which must
608 be assigned to `self-insert-command' in the global map.
609 The cdr is either a command to be called interactively, a function
610 to be called, or a form to be evaluated."
611 :group 'org-structure
612 :type '(repeat
613 (cons
614 (string "Command letter")
615 (choice
616 (function)
617 (sexp)))))
619 (defgroup org-cycle nil
620 "Options concerning visibility cycling in Org-mode."
621 :tag "Org Cycle"
622 :group 'org-structure)
624 (defcustom org-cycle-skip-children-state-if-no-children t
625 "Non-nil means, skip CHILDREN state in entries that don't have any."
626 :group 'org-cycle
627 :type 'boolean)
629 (defcustom org-cycle-max-level nil
630 "Maximum level which should still be subject to visibility cycling.
631 Levels higher than this will, for cycling, be treated as text, not a headline.
632 When `org-odd-levels-only' is set, a value of N in this variable actually
633 means 2N-1 stars as the limiting headline.
634 When nil, cycle all levels.
635 Note that the limiting level of cycling is also influenced by
636 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
637 `org-inlinetask-min-level' is, cycling will be limited to levels one less
638 than its value."
639 :group 'org-cycle
640 :type '(choice
641 (const :tag "No limit" nil)
642 (integer :tag "Maximum level")))
644 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
645 "Names of drawers. Drawers are not opened by cycling on the headline above.
646 Drawers only open with a TAB on the drawer line itself. A drawer looks like
647 this:
648 :DRAWERNAME:
649 .....
650 :END:
651 The drawer \"PROPERTIES\" is special for capturing properties through
652 the property API.
654 Drawers can be defined on the per-file basis with a line like:
656 #+DRAWERS: HIDDEN STATE PROPERTIES"
657 :group 'org-structure
658 :group 'org-cycle
659 :type '(repeat (string :tag "Drawer Name")))
661 (defcustom org-hide-block-startup nil
662 "Non-nil means, , entering Org-mode will fold all blocks.
663 This can also be set in on a per-file basis with
665 #+STARTUP: hideblocks
666 #+STARTUP: showblocks"
667 :group 'org-startup
668 :group 'org-cycle
669 :type 'boolean)
671 (defcustom org-cycle-global-at-bob nil
672 "Cycle globally if cursor is at beginning of buffer and not at a headline.
673 This makes it possible to do global cycling without having to use S-TAB or
674 C-u TAB. For this special case to work, the first line of the buffer
675 must not be a headline - it may be empty or some other text. When used in
676 this way, `org-cycle-hook' is disables temporarily, to make sure the
677 cursor stays at the beginning of the buffer.
678 When this option is nil, don't do anything special at the beginning
679 of the buffer."
680 :group 'org-cycle
681 :type 'boolean)
683 (defcustom org-cycle-level-after-item/entry-creation t
684 "Non-nil means, cycle entry level or item indentation in new empty entries.
686 When the cursor is at the end of an empty headline, i.e with only stars
687 and maybe a TODO keyword, TAB will then switch the entry to become a child,
688 and then all possible anchestor states, before returning to the original state.
689 This makes data entry extremely fast: M-RET to create a new hedline,
690 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
692 When the cursor is at the end of an empty plain list item, one TAB will
693 make it a subitem, two or more tabs will back up to make this an item
694 higher up in the item hierarchy."
695 :group 'org-cycle
696 :type 'boolean)
698 (defcustom org-cycle-emulate-tab t
699 "Where should `org-cycle' emulate TAB.
700 nil Never
701 white Only in completely white lines
702 whitestart Only at the beginning of lines, before the first non-white char
703 t Everywhere except in headlines
704 exc-hl-bol Everywhere except at the start of a headline
705 If TAB is used in a place where it does not emulate TAB, the current subtree
706 visibility is cycled."
707 :group 'org-cycle
708 :type '(choice (const :tag "Never" nil)
709 (const :tag "Only in completely white lines" white)
710 (const :tag "Before first char in a line" whitestart)
711 (const :tag "Everywhere except in headlines" t)
712 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
715 (defcustom org-cycle-separator-lines 2
716 "Number of empty lines needed to keep an empty line between collapsed trees.
717 If you leave an empty line between the end of a subtree and the following
718 headline, this empty line is hidden when the subtree is folded.
719 Org-mode will leave (exactly) one empty line visible if the number of
720 empty lines is equal or larger to the number given in this variable.
721 So the default 2 means, at least 2 empty lines after the end of a subtree
722 are needed to produce free space between a collapsed subtree and the
723 following headline.
725 If the number is negative, and the number of empty lines is at least -N,
726 all empty lines are shown.
728 Special case: when 0, never leave empty lines in collapsed view."
729 :group 'org-cycle
730 :type 'integer)
731 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
733 (defcustom org-pre-cycle-hook nil
734 "Hook that is run before visibility cycling is happening.
735 The function(s) in this hook must accept a single argument which indicates
736 the new state that will be set right after running this hook. The
737 argument is a symbol. Before a global state change, it can have the values
738 `overview', `content', or `all'. Before a local state change, it can have
739 the values `folded', `children', or `subtree'."
740 :group 'org-cycle
741 :type 'hook)
743 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
744 org-cycle-hide-drawers
745 org-cycle-show-empty-lines
746 org-optimize-window-after-visibility-change)
747 "Hook that is run after `org-cycle' has changed the buffer visibility.
748 The function(s) in this hook must accept a single argument which indicates
749 the new state that was set by the most recent `org-cycle' command. The
750 argument is a symbol. After a global state change, it can have the values
751 `overview', `content', or `all'. After a local state change, it can have
752 the values `folded', `children', or `subtree'."
753 :group 'org-cycle
754 :type 'hook)
756 (defgroup org-edit-structure nil
757 "Options concerning structure editing in Org-mode."
758 :tag "Org Edit Structure"
759 :group 'org-structure)
761 (defcustom org-odd-levels-only nil
762 "Non-nil means, skip even levels and only use odd levels for the outline.
763 This has the effect that two stars are being added/taken away in
764 promotion/demotion commands. It also influences how levels are
765 handled by the exporters.
766 Changing it requires restart of `font-lock-mode' to become effective
767 for fontification also in regions already fontified.
768 You may also set this on a per-file basis by adding one of the following
769 lines to the buffer:
771 #+STARTUP: odd
772 #+STARTUP: oddeven"
773 :group 'org-edit-structure
774 :group 'org-font-lock
775 :type 'boolean)
777 (defcustom org-adapt-indentation t
778 "Non-nil means, adapt indentation to outline node level.
780 When this variable is set, Org assumes that you write outlines by
781 indenting text in each node to align with the headline (after the stars).
782 The following issues are influenced by this variable:
784 - When this is set and the *entire* text in an entry is indented, the
785 indentation is increased by one space in a demotion command, and
786 decreased by one in a promotion command. If any line in the entry
787 body starts with text at column 0, indentation is not changed at all.
789 - Property drawers and planning information is inserted indented when
790 this variable s set. When nil, they will not be indented.
792 - TAB indents a line relative to context. The lines below a headline
793 will be indented when this variable is set.
795 Note that this is all about true indentation, by adding and removing
796 space characters. See also `org-indent.el' which does level-dependent
797 indentation in a virtual way, i.e. at display time in Emacs."
798 :group 'org-edit-structure
799 :type 'boolean)
801 (defcustom org-special-ctrl-a/e nil
802 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
804 When t, `C-a' will bring back the cursor to the beginning of the
805 headline text, i.e. after the stars and after a possible TODO keyword.
806 In an item, this will be the position after the bullet.
807 When the cursor is already at that position, another `C-a' will bring
808 it to the beginning of the line.
810 `C-e' will jump to the end of the headline, ignoring the presence of tags
811 in the headline. A second `C-e' will then jump to the true end of the
812 line, after any tags. This also means that, when this variable is
813 non-nil, `C-e' also will never jump beyond the end of the heading of a
814 folded section, i.e. not after the ellipses.
816 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
817 going to the true line boundary first. Only a directly following, identical
818 keypress will bring the cursor to the special positions.
820 This may also be a cons cell where the behavior for `C-a' and `C-e' is
821 set separately."
822 :group 'org-edit-structure
823 :type '(choice
824 (const :tag "off" nil)
825 (const :tag "on: after stars/bullet and before tags first" t)
826 (const :tag "reversed: true line boundary first" reversed)
827 (cons :tag "Set C-a and C-e separately"
828 (choice :tag "Special C-a"
829 (const :tag "off" nil)
830 (const :tag "on: after stars/bullet first" t)
831 (const :tag "reversed: before stars/bullet first" reversed))
832 (choice :tag "Special C-e"
833 (const :tag "off" nil)
834 (const :tag "on: before tags first" t)
835 (const :tag "reversed: after tags first" reversed)))))
836 (if (fboundp 'defvaralias)
837 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
839 (defcustom org-special-ctrl-k nil
840 "Non-nil means `C-k' will behave specially in headlines.
841 When nil, `C-k' will call the default `kill-line' command.
842 When t, the following will happen while the cursor is in the headline:
844 - When the cursor is at the beginning of a headline, kill the entire
845 line and possible the folded subtree below the line.
846 - When in the middle of the headline text, kill the headline up to the tags.
847 - When after the headline text, kill the tags."
848 :group 'org-edit-structure
849 :type 'boolean)
851 (defcustom org-yank-folded-subtrees t
852 "Non-nil means, when yanking subtrees, fold them.
853 If the kill is a single subtree, or a sequence of subtrees, i.e. if
854 it starts with a heading and all other headings in it are either children
855 or siblings, then fold all the subtrees. However, do this only if no
856 text after the yank would be swallowed into a folded tree by this action."
857 :group 'org-edit-structure
858 :type 'boolean)
860 (defcustom org-yank-adjusted-subtrees nil
861 "Non-nil means, when yanking subtrees, adjust the level.
862 With this setting, `org-paste-subtree' is used to insert the subtree, see
863 this function for details."
864 :group 'org-edit-structure
865 :type 'boolean)
867 (defcustom org-M-RET-may-split-line '((default . t))
868 "Non-nil means, M-RET will split the line at the cursor position.
869 When nil, it will go to the end of the line before making a
870 new line.
871 You may also set this option in a different way for different
872 contexts. Valid contexts are:
874 headline when creating a new headline
875 item when creating a new item
876 table in a table field
877 default the value to be used for all contexts not explicitly
878 customized"
879 :group 'org-structure
880 :group 'org-table
881 :type '(choice
882 (const :tag "Always" t)
883 (const :tag "Never" nil)
884 (repeat :greedy t :tag "Individual contexts"
885 (cons
886 (choice :tag "Context"
887 (const headline)
888 (const item)
889 (const table)
890 (const default))
891 (boolean)))))
894 (defcustom org-insert-heading-respect-content nil
895 "Non-nil means, insert new headings after the current subtree.
896 When nil, the new heading is created directly after the current line.
897 The commands \\[org-insert-heading-respect-content] and
898 \\[org-insert-todo-heading-respect-content] turn this variable on
899 for the duration of the command."
900 :group 'org-structure
901 :type 'boolean)
903 (defcustom org-blank-before-new-entry '((heading . auto)
904 (plain-list-item . auto))
905 "Should `org-insert-heading' leave a blank line before new heading/item?
906 The value is an alist, with `heading' and `plain-list-item' as car,
907 and a boolean flag as cdr. For plain lists, if the variable
908 `org-empty-line-terminates-plain-lists' is set, the setting here
909 is ignored and no empty line is inserted, to keep the list in tact."
910 :group 'org-edit-structure
911 :type '(list
912 (cons (const heading)
913 (choice (const :tag "Never" nil)
914 (const :tag "Always" t)
915 (const :tag "Auto" auto)))
916 (cons (const plain-list-item)
917 (choice (const :tag "Never" nil)
918 (const :tag "Always" t)
919 (const :tag "Auto" auto)))))
921 (defcustom org-insert-heading-hook nil
922 "Hook being run after inserting a new heading."
923 :group 'org-edit-structure
924 :type 'hook)
926 (defcustom org-enable-fixed-width-editor t
927 "Non-nil means, lines starting with \":\" are treated as fixed-width.
928 This currently only means, they are never auto-wrapped.
929 When nil, such lines will be treated like ordinary lines.
930 See also the QUOTE keyword."
931 :group 'org-edit-structure
932 :type 'boolean)
935 (defcustom org-goto-auto-isearch t
936 "Non-nil means, typing characters in org-goto starts incremental search."
937 :group 'org-edit-structure
938 :type 'boolean)
940 (defgroup org-sparse-trees nil
941 "Options concerning sparse trees in Org-mode."
942 :tag "Org Sparse Trees"
943 :group 'org-structure)
945 (defcustom org-highlight-sparse-tree-matches t
946 "Non-nil means, highlight all matches that define a sparse tree.
947 The highlights will automatically disappear the next time the buffer is
948 changed by an edit command."
949 :group 'org-sparse-trees
950 :type 'boolean)
952 (defcustom org-remove-highlights-with-change t
953 "Non-nil means, any change to the buffer will remove temporary highlights.
954 Such highlights are created by `org-occur' and `org-clock-display'.
955 When nil, `C-c C-c needs to be used to get rid of the highlights.
956 The highlights created by `org-preview-latex-fragment' always need
957 `C-c C-c' to be removed."
958 :group 'org-sparse-trees
959 :group 'org-time
960 :type 'boolean)
963 (defcustom org-occur-hook '(org-first-headline-recenter)
964 "Hook that is run after `org-occur' has constructed a sparse tree.
965 This can be used to recenter the window to show as much of the structure
966 as possible."
967 :group 'org-sparse-trees
968 :type 'hook)
970 (defgroup org-imenu-and-speedbar nil
971 "Options concerning imenu and speedbar in Org-mode."
972 :tag "Org Imenu and Speedbar"
973 :group 'org-structure)
975 (defcustom org-imenu-depth 2
976 "The maximum level for Imenu access to Org-mode headlines.
977 This also applied for speedbar access."
978 :group 'org-imenu-and-speedbar
979 :type 'integer)
981 (defgroup org-table nil
982 "Options concerning tables in Org-mode."
983 :tag "Org Table"
984 :group 'org)
986 (defcustom org-enable-table-editor 'optimized
987 "Non-nil means, lines starting with \"|\" are handled by the table editor.
988 When nil, such lines will be treated like ordinary lines.
990 When equal to the symbol `optimized', the table editor will be optimized to
991 do the following:
992 - Automatic overwrite mode in front of whitespace in table fields.
993 This makes the structure of the table stay in tact as long as the edited
994 field does not exceed the column width.
995 - Minimize the number of realigns. Normally, the table is aligned each time
996 TAB or RET are pressed to move to another field. With optimization this
997 happens only if changes to a field might have changed the column width.
998 Optimization requires replacing the functions `self-insert-command',
999 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1000 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1001 very good at guessing when a re-align will be necessary, but you can always
1002 force one with \\[org-ctrl-c-ctrl-c].
1004 If you would like to use the optimized version in Org-mode, but the
1005 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1007 This variable can be used to turn on and off the table editor during a session,
1008 but in order to toggle optimization, a restart is required.
1010 See also the variable `org-table-auto-blank-field'."
1011 :group 'org-table
1012 :type '(choice
1013 (const :tag "off" nil)
1014 (const :tag "on" t)
1015 (const :tag "on, optimized" optimized)))
1017 (defcustom org-self-insert-cluster-for-undo t
1018 "Non-nil means cluster self-insert commands for undo when possible.
1019 If this is set, then, like in the Emacs command loop, 20 consequtive
1020 characters will be undone together.
1021 This is configurable, because there is some impact on typing performance."
1022 :group 'org-table
1023 :type 'boolean)
1025 (defcustom org-table-tab-recognizes-table.el t
1026 "Non-nil means, TAB will automatically notice a table.el table.
1027 When it sees such a table, it moves point into it and - if necessary -
1028 calls `table-recognize-table'."
1029 :group 'org-table-editing
1030 :type 'boolean)
1032 (defgroup org-link nil
1033 "Options concerning links in Org-mode."
1034 :tag "Org Link"
1035 :group 'org)
1037 (defvar org-link-abbrev-alist-local nil
1038 "Buffer-local version of `org-link-abbrev-alist', which see.
1039 The value of this is taken from the #+LINK lines.")
1040 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1042 (defcustom org-link-abbrev-alist nil
1043 "Alist of link abbreviations.
1044 The car of each element is a string, to be replaced at the start of a link.
1045 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1046 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1048 [[linkkey:tag][description]]
1050 The 'linkkey' must be a word word, starting with a letter, followed
1051 by letters, numbers, '-' or '_'.
1053 If REPLACE is a string, the tag will simply be appended to create the link.
1054 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1055 the placeholder \"%h\" will cause a url-encoded version of the tag to
1056 be inserted at that point (see the function `url-hexify-string').
1058 REPLACE may also be a function that will be called with the tag as the
1059 only argument to create the link, which should be returned as a string.
1061 See the manual for examples."
1062 :group 'org-link
1063 :type '(repeat
1064 (cons
1065 (string :tag "Protocol")
1066 (choice
1067 (string :tag "Format")
1068 (function)))))
1070 (defcustom org-descriptive-links t
1071 "Non-nil means, hide link part and only show description of bracket links.
1072 Bracket links are like [[link][description]]. This variable sets the initial
1073 state in new org-mode buffers. The setting can then be toggled on a
1074 per-buffer basis from the Org->Hyperlinks menu."
1075 :group 'org-link
1076 :type 'boolean)
1078 (defcustom org-link-file-path-type 'adaptive
1079 "How the path name in file links should be stored.
1080 Valid values are:
1082 relative Relative to the current directory, i.e. the directory of the file
1083 into which the link is being inserted.
1084 absolute Absolute path, if possible with ~ for home directory.
1085 noabbrev Absolute path, no abbreviation of home directory.
1086 adaptive Use relative path for files in the current directory and sub-
1087 directories of it. For other files, use an absolute path."
1088 :group 'org-link
1089 :type '(choice
1090 (const relative)
1091 (const absolute)
1092 (const noabbrev)
1093 (const adaptive)))
1095 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1096 "Types of links that should be activated in Org-mode files.
1097 This is a list of symbols, each leading to the activation of a certain link
1098 type. In principle, it does not hurt to turn on most link types - there may
1099 be a small gain when turning off unused link types. The types are:
1101 bracket The recommended [[link][description]] or [[link]] links with hiding.
1102 angular Links in angular brackets that may contain whitespace like
1103 <bbdb:Carsten Dominik>.
1104 plain Plain links in normal text, no whitespace, like http://google.com.
1105 radio Text that is matched by a radio target, see manual for details.
1106 tag Tag settings in a headline (link to tag search).
1107 date Time stamps (link to calendar).
1108 footnote Footnote labels.
1110 Changing this variable requires a restart of Emacs to become effective."
1111 :group 'org-link
1112 :type '(set :greedy t
1113 (const :tag "Double bracket links (new style)" bracket)
1114 (const :tag "Angular bracket links (old style)" angular)
1115 (const :tag "Plain text links" plain)
1116 (const :tag "Radio target matches" radio)
1117 (const :tag "Tags" tag)
1118 (const :tag "Timestamps" date)
1119 (const :tag "Footnotes" footnote)))
1121 (defcustom org-make-link-description-function nil
1122 "Function to use to generate link descriptions from links. If
1123 nil the link location will be used. This function must take two
1124 parameters; the first is the link and the second the description
1125 org-insert-link has generated, and should return the description
1126 to use."
1127 :group 'org-link
1128 :type 'function)
1130 (defgroup org-link-store nil
1131 "Options concerning storing links in Org-mode."
1132 :tag "Org Store Link"
1133 :group 'org-link)
1135 (defcustom org-email-link-description-format "Email %c: %.30s"
1136 "Format of the description part of a link to an email or usenet message.
1137 The following %-escapes will be replaced by corresponding information:
1139 %F full \"From\" field
1140 %f name, taken from \"From\" field, address if no name
1141 %T full \"To\" field
1142 %t first name in \"To\" field, address if no name
1143 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1144 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1145 %s subject
1146 %m message-id.
1148 You may use normal field width specification between the % and the letter.
1149 This is for example useful to limit the length of the subject.
1151 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1152 :group 'org-link-store
1153 :type 'string)
1155 (defcustom org-from-is-user-regexp
1156 (let (r1 r2)
1157 (when (and user-mail-address (not (string= user-mail-address "")))
1158 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1159 (when (and user-full-name (not (string= user-full-name "")))
1160 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1161 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1162 "Regexp matched against the \"From:\" header of an email or usenet message.
1163 It should match if the message is from the user him/herself."
1164 :group 'org-link-store
1165 :type 'regexp)
1167 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1168 "Non-nil means, storing a link to an Org file will use entry IDs.
1170 Note that before this variable is even considered, org-id must be loaded,
1171 so please customize `org-modules' and turn it on.
1173 The variable can have the following values:
1175 t Create an ID if needed to make a link to the current entry.
1177 create-if-interactive
1178 If `org-store-link' is called directly (interactively, as a user
1179 command), do create an ID to support the link. But when doing the
1180 job for remember, only use the ID if it already exists. The
1181 purpose of this setting is to avoid proliferation of unwanted
1182 IDs, just because you happen to be in an Org file when you
1183 call `org-remember' that automatically and preemptively
1184 creates a link. If you do want to get an ID link in a remember
1185 template to an entry not having an ID, create it first by
1186 explicitly creating a link to it, using `C-c C-l' first.
1188 create-if-interactive-and-no-custom-id
1189 Like create-if-interactive, but do not create an ID if there is
1190 a CUSTOM_ID property defined in the entry. This is the default.
1192 use-existing
1193 Use existing ID, do not create one.
1195 nil Never use an ID to make a link, instead link using a text search for
1196 the headline text."
1197 :group 'org-link-store
1198 :type '(choice
1199 (const :tag "Create ID to make link" t)
1200 (const :tag "Create if storing link interactively"
1201 create-if-interactive)
1202 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1203 create-if-interactive-and-no-custom-id)
1204 (const :tag "Only use existing" use-existing)
1205 (const :tag "Do not use ID to create link" nil)))
1207 (defcustom org-context-in-file-links t
1208 "Non-nil means, file links from `org-store-link' contain context.
1209 A search string will be added to the file name with :: as separator and
1210 used to find the context when the link is activated by the command
1211 `org-open-at-point'.
1212 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1213 negates this setting for the duration of the command."
1214 :group 'org-link-store
1215 :type 'boolean)
1217 (defcustom org-keep-stored-link-after-insertion nil
1218 "Non-nil means, keep link in list for entire session.
1220 The command `org-store-link' adds a link pointing to the current
1221 location to an internal list. These links accumulate during a session.
1222 The command `org-insert-link' can be used to insert links into any
1223 Org-mode file (offering completion for all stored links). When this
1224 option is nil, every link which has been inserted once using \\[org-insert-link]
1225 will be removed from the list, to make completing the unused links
1226 more efficient."
1227 :group 'org-link-store
1228 :type 'boolean)
1230 (defgroup org-link-follow nil
1231 "Options concerning following links in Org-mode."
1232 :tag "Org Follow Link"
1233 :group 'org-link)
1235 (defcustom org-link-translation-function nil
1236 "Function to translate links with different syntax to Org syntax.
1237 This can be used to translate links created for example by the Planner
1238 or emacs-wiki packages to Org syntax.
1239 The function must accept two parameters, a TYPE containing the link
1240 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1241 which is everything after the link protocol. It should return a cons
1242 with possibly modified values of type and path.
1243 Org contains a function for this, so if you set this variable to
1244 `org-translate-link-from-planner', you should be able follow many
1245 links created by planner."
1246 :group 'org-link-follow
1247 :type 'function)
1249 (defcustom org-follow-link-hook nil
1250 "Hook that is run after a link has been followed."
1251 :group 'org-link-follow
1252 :type 'hook)
1254 (defcustom org-tab-follows-link nil
1255 "Non-nil means, on links TAB will follow the link.
1256 Needs to be set before org.el is loaded.
1257 This really should not be used, it does not make sense, and the
1258 implementation is bad."
1259 :group 'org-link-follow
1260 :type 'boolean)
1262 (defcustom org-return-follows-link nil
1263 "Non-nil means, on links RET will follow the link.
1264 Needs to be set before org.el is loaded."
1265 :group 'org-link-follow
1266 :type 'boolean)
1268 (defcustom org-mouse-1-follows-link
1269 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1270 "Non-nil means, mouse-1 on a link will follow the link.
1271 A longer mouse click will still set point. Does not work on XEmacs.
1272 Needs to be set before org.el is loaded."
1273 :group 'org-link-follow
1274 :type 'boolean)
1276 (defcustom org-mark-ring-length 4
1277 "Number of different positions to be recorded in the ring
1278 Changing this requires a restart of Emacs to work correctly."
1279 :group 'org-link-follow
1280 :type 'integer)
1282 (defcustom org-link-frame-setup
1283 '((vm . vm-visit-folder-other-frame)
1284 (gnus . gnus-other-frame)
1285 (file . find-file-other-window))
1286 "Setup the frame configuration for following links.
1287 When following a link with Emacs, it may often be useful to display
1288 this link in another window or frame. This variable can be used to
1289 set this up for the different types of links.
1290 For VM, use any of
1291 `vm-visit-folder'
1292 `vm-visit-folder-other-frame'
1293 For Gnus, use any of
1294 `gnus'
1295 `gnus-other-frame'
1296 `org-gnus-no-new-news'
1297 For FILE, use any of
1298 `find-file'
1299 `find-file-other-window'
1300 `find-file-other-frame'
1301 For the calendar, use the variable `calendar-setup'.
1302 For BBDB, it is currently only possible to display the matches in
1303 another window."
1304 :group 'org-link-follow
1305 :type '(list
1306 (cons (const vm)
1307 (choice
1308 (const vm-visit-folder)
1309 (const vm-visit-folder-other-window)
1310 (const vm-visit-folder-other-frame)))
1311 (cons (const gnus)
1312 (choice
1313 (const gnus)
1314 (const gnus-other-frame)
1315 (const org-gnus-no-new-news)))
1316 (cons (const file)
1317 (choice
1318 (const find-file)
1319 (const find-file-other-window)
1320 (const find-file-other-frame)))))
1322 (defcustom org-display-internal-link-with-indirect-buffer nil
1323 "Non-nil means, use indirect buffer to display infile links.
1324 Activating internal links (from one location in a file to another location
1325 in the same file) normally just jumps to the location. When the link is
1326 activated with a C-u prefix (or with mouse-3), the link is displayed in
1327 another window. When this option is set, the other window actually displays
1328 an indirect buffer clone of the current buffer, to avoid any visibility
1329 changes to the current buffer."
1330 :group 'org-link-follow
1331 :type 'boolean)
1333 (defcustom org-open-non-existing-files nil
1334 "Non-nil means, `org-open-file' will open non-existing files.
1335 When nil, an error will be generated.
1336 This variable applies only to external applications because they
1337 might choke on non-existing files. If the link is to a file that
1338 will be openend in Emacs, the variable is ignored."
1339 :group 'org-link-follow
1340 :type 'boolean)
1342 (defcustom org-open-directory-means-index-dot-org nil
1343 "Non-nil means, a link to a directory really means to index.org.
1344 When nil, following a directory link will run dired or open a finder/explorer
1345 window on that directory."
1346 :group 'org-link-follow
1347 :type 'boolean)
1349 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1350 "Function and arguments to call for following mailto links.
1351 This is a list with the first element being a lisp function, and the
1352 remaining elements being arguments to the function. In string arguments,
1353 %a will be replaced by the address, and %s will be replaced by the subject
1354 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1355 :group 'org-link-follow
1356 :type '(choice
1357 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1358 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1359 (const :tag "message-mail" (message-mail "%a" "%s"))
1360 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1362 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1363 "Non-nil means, ask for confirmation before executing shell links.
1364 Shell links can be dangerous: just think about a link
1366 [[shell:rm -rf ~/*][Google Search]]
1368 This link would show up in your Org-mode document as \"Google Search\",
1369 but really it would remove your entire home directory.
1370 Therefore we advise against setting this variable to nil.
1371 Just change it to `y-or-n-p' if you want to confirm with a
1372 single keystroke rather than having to type \"yes\"."
1373 :group 'org-link-follow
1374 :type '(choice
1375 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1376 (const :tag "with y-or-n (faster)" y-or-n-p)
1377 (const :tag "no confirmation (dangerous)" nil)))
1379 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1380 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1381 Elisp links can be dangerous: just think about a link
1383 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1385 This link would show up in your Org-mode document as \"Google Search\",
1386 but really it would remove your entire home directory.
1387 Therefore we advise against setting this variable to nil.
1388 Just change it to `y-or-n-p' if you want to confirm with a
1389 single keystroke rather than having to type \"yes\"."
1390 :group 'org-link-follow
1391 :type '(choice
1392 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1393 (const :tag "with y-or-n (faster)" y-or-n-p)
1394 (const :tag "no confirmation (dangerous)" nil)))
1396 (defconst org-file-apps-defaults-gnu
1397 '((remote . emacs)
1398 (system . mailcap)
1399 (t . mailcap))
1400 "Default file applications on a UNIX or GNU/Linux system.
1401 See `org-file-apps'.")
1403 (defconst org-file-apps-defaults-macosx
1404 '((remote . emacs)
1405 (t . "open %s")
1406 (system . "open %s")
1407 ("ps.gz" . "gv %s")
1408 ("eps.gz" . "gv %s")
1409 ("dvi" . "xdvi %s")
1410 ("fig" . "xfig %s"))
1411 "Default file applications on a MacOS X system.
1412 The system \"open\" is known as a default, but we use X11 applications
1413 for some files for which the OS does not have a good default.
1414 See `org-file-apps'.")
1416 (defconst org-file-apps-defaults-windowsnt
1417 (list
1418 '(remote . emacs)
1419 (cons t
1420 (list (if (featurep 'xemacs)
1421 'mswindows-shell-execute
1422 'w32-shell-execute)
1423 "open" 'file))
1424 (cons 'system
1425 (list (if (featurep 'xemacs)
1426 'mswindows-shell-execute
1427 'w32-shell-execute)
1428 "open" 'file)))
1429 "Default file applications on a Windows NT system.
1430 The system \"open\" is used for most files.
1431 See `org-file-apps'.")
1433 (defcustom org-file-apps
1435 (auto-mode . emacs)
1436 ("\\.mm\\'" . default)
1437 ("\\.x?html?\\'" . default)
1438 ("\\.pdf\\'" . default)
1440 "External applications for opening `file:path' items in a document.
1441 Org-mode uses system defaults for different file types, but
1442 you can use this variable to set the application for a given file
1443 extension. The entries in this list are cons cells where the car identifies
1444 files and the cdr the corresponding command. Possible values for the
1445 file identifier are
1446 \"regex\" Regular expression matched against the file name. For backward
1447 compatibility, this can also be a string with only alphanumeric
1448 characters, which is then interpreted as an extension.
1449 `directory' Matches a directory
1450 `remote' Matches a remote file, accessible through tramp or efs.
1451 Remote files most likely should be visited through Emacs
1452 because external applications cannot handle such paths.
1453 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1454 so all files Emacs knows how to handle. Using this with
1455 command `emacs' will open most files in Emacs. Beware that this
1456 will also open html files inside Emacs, unless you add
1457 (\"html\" . default) to the list as well.
1458 t Default for files not matched by any of the other options.
1459 `system' The system command to open files, like `open' on Windows
1460 and Mac OS X, and mailcap under GNU/Linux. This is the command
1461 that will be selected if you call `C-c C-o' with a double
1462 `C-u C-u' prefix.
1464 Possible values for the command are:
1465 `emacs' The file will be visited by the current Emacs process.
1466 `default' Use the default application for this file type, which is the
1467 association for t in the list, most likely in the system-specific
1468 part.
1469 This can be used to overrule an unwanted setting in the
1470 system-specific variable.
1471 `system' Use the system command for opening files, like \"open\".
1472 This command is specified by the entry whose car is `system'.
1473 Most likely, the system-specific version of this variable
1474 does define this command, but you can overrule/replace it
1475 here.
1476 string A command to be executed by a shell; %s will be replaced
1477 by the path to the file.
1478 sexp A Lisp form which will be evaluated. The file path will
1479 be available in the Lisp variable `file'.
1480 For more examples, see the system specific constants
1481 `org-file-apps-defaults-macosx'
1482 `org-file-apps-defaults-windowsnt'
1483 `org-file-apps-defaults-gnu'."
1484 :group 'org-link-follow
1485 :type '(repeat
1486 (cons (choice :value ""
1487 (string :tag "Extension")
1488 (const :tag "System command to open files" system)
1489 (const :tag "Default for unrecognized files" t)
1490 (const :tag "Remote file" remote)
1491 (const :tag "Links to a directory" directory)
1492 (const :tag "Any files that have Emacs modes"
1493 auto-mode))
1494 (choice :value ""
1495 (const :tag "Visit with Emacs" emacs)
1496 (const :tag "Use default" default)
1497 (const :tag "Use the system command" system)
1498 (string :tag "Command")
1499 (sexp :tag "Lisp form")))))
1501 (defgroup org-refile nil
1502 "Options concerning refiling entries in Org-mode."
1503 :tag "Org Refile"
1504 :group 'org)
1506 (defcustom org-directory "~/org"
1507 "Directory with org files.
1508 This is just a default location to look for Org files. There is no need
1509 at all to put your files into this directory. It is only used in the
1510 following situations:
1512 1. When a remember template specifies a target file that is not an
1513 absolute path. The path will then be interpreted relative to
1514 `org-directory'
1515 2. When a remember note is filed away in an interactive way (when exiting the
1516 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1517 with `org-directory' as the default path."
1518 :group 'org-refile
1519 :group 'org-remember
1520 :type 'directory)
1522 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1523 "Default target for storing notes.
1524 Used by the hooks for remember.el. This can be a string, or nil to mean
1525 the value of `remember-data-file'.
1526 You can set this on a per-template basis with the variable
1527 `org-remember-templates'."
1528 :group 'org-refile
1529 :group 'org-remember
1530 :type '(choice
1531 (const :tag "Default from remember-data-file" nil)
1532 file))
1534 (defcustom org-goto-interface 'outline
1535 "The default interface to be used for `org-goto'.
1536 Allowed values are:
1537 outline The interface shows an outline of the relevant file
1538 and the correct heading is found by moving through
1539 the outline or by searching with incremental search.
1540 outline-path-completion Headlines in the current buffer are offered via
1541 completion. This is the interface also used by
1542 the refile command."
1543 :group 'org-refile
1544 :type '(choice
1545 (const :tag "Outline" outline)
1546 (const :tag "Outline-path-completion" outline-path-completion)))
1548 (defcustom org-goto-max-level 5
1549 "Maximum level to be considered when running org-goto with refile interface."
1550 :group 'org-refile
1551 :type 'integer)
1553 (defcustom org-reverse-note-order nil
1554 "Non-nil means, store new notes at the beginning of a file or entry.
1555 When nil, new notes will be filed to the end of a file or entry.
1556 This can also be a list with cons cells of regular expressions that
1557 are matched against file names, and values."
1558 :group 'org-remember
1559 :group 'org-refile
1560 :type '(choice
1561 (const :tag "Reverse always" t)
1562 (const :tag "Reverse never" nil)
1563 (repeat :tag "By file name regexp"
1564 (cons regexp boolean))))
1566 (defcustom org-refile-targets nil
1567 "Targets for refiling entries with \\[org-refile].
1568 This is list of cons cells. Each cell contains:
1569 - a specification of the files to be considered, either a list of files,
1570 or a symbol whose function or variable value will be used to retrieve
1571 a file name or a list of file names. If you use `org-agenda-files' for
1572 that, all agenda files will be scanned for targets. Nil means, consider
1573 headings in the current buffer.
1574 - A specification of how to find candidate refile targets. This may be
1575 any of:
1576 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1577 This tag has to be present in all target headlines, inheritance will
1578 not be considered.
1579 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1580 todo keyword.
1581 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1582 headlines that are refiling targets.
1583 - a cons cell (:level . N). Any headline of level N is considered a target.
1584 Note that, when `org-odd-levels-only' is set, level corresponds to
1585 order in hierarchy, not to the number of stars.
1586 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1587 Note that, when `org-odd-levels-only' is set, level corresponds to
1588 order in hierarchy, not to the number of stars.
1590 You can set the variable `org-refile-target-verify-function' to a function
1591 to verify each headline found by the simple critery above.
1593 When this variable is nil, all top-level headlines in the current buffer
1594 are used, equivalent to the value `((nil . (:level . 1))'."
1595 :group 'org-refile
1596 :type '(repeat
1597 (cons
1598 (choice :value org-agenda-files
1599 (const :tag "All agenda files" org-agenda-files)
1600 (const :tag "Current buffer" nil)
1601 (function) (variable) (file))
1602 (choice :tag "Identify target headline by"
1603 (cons :tag "Specific tag" (const :value :tag) (string))
1604 (cons :tag "TODO keyword" (const :value :todo) (string))
1605 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1606 (cons :tag "Level number" (const :value :level) (integer))
1607 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1609 (defcustom org-refile-target-verify-function nil
1610 "Function to verify if the headline at point should be a refile target.
1611 The function will be called without arguments, with point at the
1612 beginning of the headline. It should return t and leave point
1613 where it is if the headline is a valid target for refiling.
1615 If the target should not be selected, the function must return nil.
1616 In addition to this, it may move point to a place from where the search
1617 should be continued. For example, the function may decide that the entire
1618 subtree of the current entry should be excluded and move point to the end
1619 of the subtree."
1620 :group 'org-refile
1621 :type 'function)
1623 (defcustom org-refile-use-outline-path nil
1624 "Non-nil means, provide refile targets as paths.
1625 So a level 3 headline will be available as level1/level2/level3.
1627 When the value is `file', also include the file name (without directory)
1628 into the path. In this case, you can also stop the completion after
1629 the file name, to get entries inserted as top level in the file.
1631 When `full-file-path', include the full file path."
1632 :group 'org-refile
1633 :type '(choice
1634 (const :tag "Not" nil)
1635 (const :tag "Yes" t)
1636 (const :tag "Start with file name" file)
1637 (const :tag "Start with full file path" full-file-path)))
1639 (defcustom org-outline-path-complete-in-steps t
1640 "Non-nil means, complete the outline path in hierarchical steps.
1641 When Org-mode uses the refile interface to select an outline path
1642 \(see variable `org-refile-use-outline-path'), the completion of
1643 the path can be done is a single go, or if can be done in steps down
1644 the headline hierarchy. Going in steps is probably the best if you
1645 do not use a special completion package like `ido' or `icicles'.
1646 However, when using these packages, going in one step can be very
1647 fast, while still showing the whole path to the entry."
1648 :group 'org-refile
1649 :type 'boolean)
1651 (defcustom org-refile-allow-creating-parent-nodes nil
1652 "Non-nil means, allow to create new nodes as refile targets.
1653 New nodes are then created by adding \"/new node name\" to the completion
1654 of an existing node. When the value of this variable is `confirm',
1655 new node creation must be confirmed by the user (recommended)
1656 When nil, the completion must match an existing entry.
1658 Note that, if the new heading is not seen by the criteria
1659 listed in `org-refile-targets', multiple instances of the same
1660 heading would be created by trying again to file under the new
1661 heading."
1662 :group 'org-refile
1663 :type '(choice
1664 (const :tag "Never" nil)
1665 (const :tag "Always" t)
1666 (const :tag "Prompt for confirmation" confirm)))
1668 (defgroup org-todo nil
1669 "Options concerning TODO items in Org-mode."
1670 :tag "Org TODO"
1671 :group 'org)
1673 (defgroup org-progress nil
1674 "Options concerning Progress logging in Org-mode."
1675 :tag "Org Progress"
1676 :group 'org-time)
1678 (defvar org-todo-interpretation-widgets
1680 (:tag "Sequence (cycling hits every state)" sequence)
1681 (:tag "Type (cycling directly to DONE)" type))
1682 "The available interpretation symbols for customizing
1683 `org-todo-keywords'.
1684 Interested libraries should add to this list.")
1686 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1687 "List of TODO entry keyword sequences and their interpretation.
1688 \\<org-mode-map>This is a list of sequences.
1690 Each sequence starts with a symbol, either `sequence' or `type',
1691 indicating if the keywords should be interpreted as a sequence of
1692 action steps, or as different types of TODO items. The first
1693 keywords are states requiring action - these states will select a headline
1694 for inclusion into the global TODO list Org-mode produces. If one of
1695 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1696 signify that no further action is necessary. If \"|\" is not found,
1697 the last keyword is treated as the only DONE state of the sequence.
1699 The command \\[org-todo] cycles an entry through these states, and one
1700 additional state where no keyword is present. For details about this
1701 cycling, see the manual.
1703 TODO keywords and interpretation can also be set on a per-file basis with
1704 the special #+SEQ_TODO and #+TYP_TODO lines.
1706 Each keyword can optionally specify a character for fast state selection
1707 \(in combination with the variable `org-use-fast-todo-selection')
1708 and specifiers for state change logging, using the same syntax
1709 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1710 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1711 indicates to record a time stamp each time this state is selected.
1713 Each keyword may also specify if a timestamp or a note should be
1714 recorded when entering or leaving the state, by adding additional
1715 characters in the parenthesis after the keyword. This looks like this:
1716 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1717 record only the time of the state change. With X and Y being either
1718 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1719 Y when leaving the state if and only if the *target* state does not
1720 define X. You may omit any of the fast-selection key or X or /Y,
1721 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1723 For backward compatibility, this variable may also be just a list
1724 of keywords - in this case the interpretation (sequence or type) will be
1725 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1726 :group 'org-todo
1727 :group 'org-keywords
1728 :type '(choice
1729 (repeat :tag "Old syntax, just keywords"
1730 (string :tag "Keyword"))
1731 (repeat :tag "New syntax"
1732 (cons
1733 (choice
1734 :tag "Interpretation"
1735 ;;Quick and dirty way to see
1736 ;;`org-todo-interpretations'. This takes the
1737 ;;place of item arguments
1738 :convert-widget
1739 (lambda (widget)
1740 (widget-put widget
1741 :args (mapcar
1742 #'(lambda (x)
1743 (widget-convert
1744 (cons 'const x)))
1745 org-todo-interpretation-widgets))
1746 widget))
1747 (repeat
1748 (string :tag "Keyword"))))))
1750 (defvar org-todo-keywords-1 nil
1751 "All TODO and DONE keywords active in a buffer.")
1752 (make-variable-buffer-local 'org-todo-keywords-1)
1753 (defvar org-todo-keywords-for-agenda nil)
1754 (defvar org-done-keywords-for-agenda nil)
1755 (defvar org-drawers-for-agenda nil)
1756 (defvar org-todo-keyword-alist-for-agenda nil)
1757 (defvar org-tag-alist-for-agenda nil)
1758 (defvar org-agenda-contributing-files nil)
1759 (defvar org-not-done-keywords nil)
1760 (make-variable-buffer-local 'org-not-done-keywords)
1761 (defvar org-done-keywords nil)
1762 (make-variable-buffer-local 'org-done-keywords)
1763 (defvar org-todo-heads nil)
1764 (make-variable-buffer-local 'org-todo-heads)
1765 (defvar org-todo-sets nil)
1766 (make-variable-buffer-local 'org-todo-sets)
1767 (defvar org-todo-log-states nil)
1768 (make-variable-buffer-local 'org-todo-log-states)
1769 (defvar org-todo-kwd-alist nil)
1770 (make-variable-buffer-local 'org-todo-kwd-alist)
1771 (defvar org-todo-key-alist nil)
1772 (make-variable-buffer-local 'org-todo-key-alist)
1773 (defvar org-todo-key-trigger nil)
1774 (make-variable-buffer-local 'org-todo-key-trigger)
1776 (defcustom org-todo-interpretation 'sequence
1777 "Controls how TODO keywords are interpreted.
1778 This variable is in principle obsolete and is only used for
1779 backward compatibility, if the interpretation of todo keywords is
1780 not given already in `org-todo-keywords'. See that variable for
1781 more information."
1782 :group 'org-todo
1783 :group 'org-keywords
1784 :type '(choice (const sequence)
1785 (const type)))
1787 (defcustom org-use-fast-todo-selection t
1788 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1789 This variable describes if and under what circumstances the cycling
1790 mechanism for TODO keywords will be replaced by a single-key, direct
1791 selection scheme.
1793 When nil, fast selection is never used.
1795 When the symbol `prefix', it will be used when `org-todo' is called with
1796 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1797 in an agenda buffer.
1799 When t, fast selection is used by default. In this case, the prefix
1800 argument forces cycling instead.
1802 In all cases, the special interface is only used if access keys have actually
1803 been assigned by the user, i.e. if keywords in the configuration are followed
1804 by a letter in parenthesis, like TODO(t)."
1805 :group 'org-todo
1806 :type '(choice
1807 (const :tag "Never" nil)
1808 (const :tag "By default" t)
1809 (const :tag "Only with C-u C-c C-t" prefix)))
1811 (defcustom org-provide-todo-statistics t
1812 "Non-nil means, update todo statistics after insert and toggle.
1813 ALL-HEADLINES means update todo statistics by including headlines
1814 with no TODO keyword as well, counting them as not done.
1815 A list of TODO keywords means the same, but skip keywords that are
1816 not in this list.
1818 When this is set, todo statistics is updated in the parent of the
1819 current entry each time a todo state is changed."
1820 :group 'org-todo
1821 :type '(choice
1822 (const :tag "Yes, only for TODO entries" t)
1823 (const :tag "Yes, including all entries" 'all-headlines)
1824 (repeat :tag "Yes, for TODOs in this list"
1825 (string :tag "TODO keyword"))
1826 (other :tag "No TODO statistics" nil)))
1828 (defcustom org-hierarchical-todo-statistics t
1829 "Non-nil means, TODO statistics covers just direct children.
1830 When nil, all entries in the subtree are considered.
1831 This has only an effect if `org-provide-todo-statistics' is set.
1832 To set this to nil for only a single subtree, use a COOKIE_DATA
1833 property and include the word \"recursive\" into the value."
1834 :group 'org-todo
1835 :type 'boolean)
1837 (defcustom org-after-todo-state-change-hook nil
1838 "Hook which is run after the state of a TODO item was changed.
1839 The new state (a string with a TODO keyword, or nil) is available in the
1840 Lisp variable `state'."
1841 :group 'org-todo
1842 :type 'hook)
1844 (defvar org-blocker-hook nil
1845 "Hook for functions that are allowed to block a state change.
1847 Each function gets as its single argument a property list, see
1848 `org-trigger-hook' for more information about this list.
1850 If any of the functions in this hook returns nil, the state change
1851 is blocked.")
1853 (defvar org-trigger-hook nil
1854 "Hook for functions that are triggered by a state change.
1856 Each function gets as its single argument a property list with at least
1857 the following elements:
1859 (:type type-of-change :position pos-at-entry-start
1860 :from old-state :to new-state)
1862 Depending on the type, more properties may be present.
1864 This mechanism is currently implemented for:
1866 TODO state changes
1867 ------------------
1868 :type todo-state-change
1869 :from previous state (keyword as a string), or nil, or a symbol
1870 'todo' or 'done', to indicate the general type of state.
1871 :to new state, like in :from")
1873 (defcustom org-enforce-todo-dependencies nil
1874 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1875 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1876 be blocked if any prior sibling is not yet done.
1877 Finally, if the parent is blocked because of ordered siblings of its own,
1878 the child will also be blocked.
1879 This variable needs to be set before org.el is loaded, and you need to
1880 restart Emacs after a change to make the change effective. The only way
1881 to change is while Emacs is running is through the customize interface."
1882 :set (lambda (var val)
1883 (set var val)
1884 (if val
1885 (add-hook 'org-blocker-hook
1886 'org-block-todo-from-children-or-siblings-or-parent)
1887 (remove-hook 'org-blocker-hook
1888 'org-block-todo-from-children-or-siblings-or-parent)))
1889 :group 'org-todo
1890 :type 'boolean)
1892 (defcustom org-enforce-todo-checkbox-dependencies nil
1893 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1894 When this is nil, checkboxes have no influence on switching TODO states.
1895 When non-nil, you first need to check off all check boxes before the TODO
1896 entry can be switched to DONE.
1897 This variable needs to be set before org.el is loaded, and you need to
1898 restart Emacs after a change to make the change effective. The only way
1899 to change is while Emacs is running is through the customize interface."
1900 :set (lambda (var val)
1901 (set var val)
1902 (if val
1903 (add-hook 'org-blocker-hook
1904 'org-block-todo-from-checkboxes)
1905 (remove-hook 'org-blocker-hook
1906 'org-block-todo-from-checkboxes)))
1907 :group 'org-todo
1908 :type 'boolean)
1910 (defcustom org-treat-insert-todo-heading-as-state-change nil
1911 "Non-nil means, inserting a TODO heading is treated as state change.
1912 So when the command \\[org-insert-todo-heading] is used, state change
1913 logging will apply if appropriate. When nil, the new TODO item will
1914 be inserted directly, and no logging will take place."
1915 :group 'org-todo
1916 :type 'boolean)
1918 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1919 "Non-nil means, switching TODO states with S-cursor counts as state change.
1920 This is the default behavior. However, setting this to nil allows a
1921 convenient way to select a TODO state and bypass any logging associated
1922 with that."
1923 :group 'org-todo
1924 :type 'boolean)
1926 (defcustom org-todo-state-tags-triggers nil
1927 "Tag changes that should be triggered by TODO state changes.
1928 This is a list. Each entry is
1930 (state-change (tag . flag) .......)
1932 State-change can be a string with a state, and empty string to indicate the
1933 state that has no TODO keyword, or it can be one of the symbols `todo'
1934 or `done', meaning any not-done or done state, respectively."
1935 :group 'org-todo
1936 :group 'org-tags
1937 :type '(repeat
1938 (cons (choice :tag "When changing to"
1939 (const :tag "Not-done state" todo)
1940 (const :tag "Done state" done)
1941 (string :tag "State"))
1942 (repeat
1943 (cons :tag "Tag action"
1944 (string :tag "Tag")
1945 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1947 (defcustom org-log-done nil
1948 "Information to record when a task moves to the DONE state.
1950 Possible values are:
1952 nil Don't add anything, just change the keyword
1953 time Add a time stamp to the task
1954 note Prompt for a note and add it with template `org-log-note-headings'
1956 This option can also be set with on a per-file-basis with
1958 #+STARTUP: nologdone
1959 #+STARTUP: logdone
1960 #+STARTUP: lognotedone
1962 You can have local logging settings for a subtree by setting the LOGGING
1963 property to one or more of these keywords."
1964 :group 'org-todo
1965 :group 'org-progress
1966 :type '(choice
1967 (const :tag "No logging" nil)
1968 (const :tag "Record CLOSED timestamp" time)
1969 (const :tag "Record CLOSED timestamp with note." note)))
1971 ;; Normalize old uses of org-log-done.
1972 (cond
1973 ((eq org-log-done t) (setq org-log-done 'time))
1974 ((and (listp org-log-done) (memq 'done org-log-done))
1975 (setq org-log-done 'note)))
1977 (defcustom org-log-reschedule nil
1978 "Information to record when the scheduling date of a tasks is modified.
1980 Possible values are:
1982 nil Don't add anything, just change the date
1983 time Add a time stamp to the task
1984 note Prompt for a note and add it with template `org-log-note-headings'
1986 This option can also be set with on a per-file-basis with
1988 #+STARTUP: nologreschedule
1989 #+STARTUP: logreschedule
1990 #+STARTUP: lognotereschedule"
1991 :group 'org-todo
1992 :group 'org-progress
1993 :type '(choice
1994 (const :tag "No logging" nil)
1995 (const :tag "Record timestamp" time)
1996 (const :tag "Record timestamp with note." note)))
1998 (defcustom org-log-redeadline nil
1999 "Information to record when the deadline date of a tasks is modified.
2001 Possible values are:
2003 nil Don't add anything, just change the date
2004 time Add a time stamp to the task
2005 note Prompt for a note and add it with template `org-log-note-headings'
2007 This option can also be set with on a per-file-basis with
2009 #+STARTUP: nologredeadline
2010 #+STARTUP: logredeadline
2011 #+STARTUP: lognoteredeadline
2013 You can have local logging settings for a subtree by setting the LOGGING
2014 property to one or more of these keywords."
2015 :group 'org-todo
2016 :group 'org-progress
2017 :type '(choice
2018 (const :tag "No logging" nil)
2019 (const :tag "Record timestamp" time)
2020 (const :tag "Record timestamp with note." note)))
2022 (defcustom org-log-note-clock-out nil
2023 "Non-nil means, record a note when clocking out of an item.
2024 This can also be configured on a per-file basis by adding one of
2025 the following lines anywhere in the buffer:
2027 #+STARTUP: lognoteclock-out
2028 #+STARTUP: nolognoteclock-out"
2029 :group 'org-todo
2030 :group 'org-progress
2031 :type 'boolean)
2033 (defcustom org-log-done-with-time t
2034 "Non-nil means, the CLOSED time stamp will contain date and time.
2035 When nil, only the date will be recorded."
2036 :group 'org-progress
2037 :type 'boolean)
2039 (defcustom org-log-note-headings
2040 '((done . "CLOSING NOTE %t")
2041 (state . "State %-12s from %-12S %t")
2042 (note . "Note taken on %t")
2043 (reschedule . "Rescheduled from %S on %t")
2044 (redeadline . "New deadline from %S on %t")
2045 (clock-out . ""))
2046 "Headings for notes added to entries.
2047 The value is an alist, with the car being a symbol indicating the note
2048 context, and the cdr is the heading to be used. The heading may also be the
2049 empty string.
2050 %t in the heading will be replaced by a time stamp.
2051 %s will be replaced by the new TODO state, in double quotes.
2052 %S will be replaced by the old TODO state, in double quotes.
2053 %u will be replaced by the user name.
2054 %U will be replaced by the full user name."
2055 :group 'org-todo
2056 :group 'org-progress
2057 :type '(list :greedy t
2058 (cons (const :tag "Heading when closing an item" done) string)
2059 (cons (const :tag
2060 "Heading when changing todo state (todo sequence only)"
2061 state) string)
2062 (cons (const :tag "Heading when just taking a note" note) string)
2063 (cons (const :tag "Heading when clocking out" clock-out) string)
2064 (cons (const :tag "Heading when rescheduling" reschedule) string)
2065 (cons (const :tag "Heading when changing deadline" redeadline) string)))
2067 (unless (assq 'note org-log-note-headings)
2068 (push '(note . "%t") org-log-note-headings))
2070 (defcustom org-log-into-drawer nil
2071 "Non-nil means, insert state change notes and time stamps into a drawer.
2072 When nil, state changes notes will be inserted after the headline and
2073 any scheduling and clock lines, but not inside a drawer.
2075 The value of this variable should be the name of the drawer to use.
2076 LOGBOOK is proposed at the default drawer for this purpose, you can
2077 also set this to a string to define the drawer of your choice.
2079 A value of t is also allowed, representing \"LOGBOOK\".
2081 If this variable is set, `org-log-state-notes-insert-after-drawers'
2082 will be ignored.
2084 You can set the property LOG_INTO_DRAWER to overrule this setting for
2085 a subtree."
2086 :group 'org-todo
2087 :group 'org-progress
2088 :type '(choice
2089 (const :tag "Not into a drawer" nil)
2090 (const :tag "LOGBOOK" t)
2091 (string :tag "Other")))
2093 (if (fboundp 'defvaralias)
2094 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2096 (defun org-log-into-drawer ()
2097 "Return the value of `org-log-into-drawer', but let properties overrule.
2098 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2099 used instead of the default value."
2100 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2101 (cond
2102 ((or (not p) (equal p "nil")) org-log-into-drawer)
2103 ((equal p "t") "LOGBOOK")
2104 (t p))))
2106 (defcustom org-log-state-notes-insert-after-drawers nil
2107 "Non-nil means, insert state change notes after any drawers in entry.
2108 Only the drawers that *immediately* follow the headline and the
2109 deadline/scheduled line are skipped.
2110 When nil, insert notes right after the heading and perhaps the line
2111 with deadline/scheduling if present.
2113 This variable will have no effect if `org-log-into-drawer' is
2114 set."
2115 :group 'org-todo
2116 :group 'org-progress
2117 :type 'boolean)
2119 (defcustom org-log-states-order-reversed t
2120 "Non-nil means, the latest state change note will be directly after heading.
2121 When nil, the notes will be orderer according to time."
2122 :group 'org-todo
2123 :group 'org-progress
2124 :type 'boolean)
2126 (defcustom org-log-repeat 'time
2127 "Non-nil means, record moving through the DONE state when triggering repeat.
2128 An auto-repeating task is immediately switched back to TODO when
2129 marked DONE. If you are not logging state changes (by adding \"@\"
2130 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2131 record a closing note, there will be no record of the task moving
2132 through DONE. This variable forces taking a note anyway.
2134 nil Don't force a record
2135 time Record a time stamp
2136 note Record a note
2138 This option can also be set with on a per-file-basis with
2140 #+STARTUP: logrepeat
2141 #+STARTUP: lognoterepeat
2142 #+STARTUP: nologrepeat
2144 You can have local logging settings for a subtree by setting the LOGGING
2145 property to one or more of these keywords."
2146 :group 'org-todo
2147 :group 'org-progress
2148 :type '(choice
2149 (const :tag "Don't force a record" nil)
2150 (const :tag "Force recording the DONE state" time)
2151 (const :tag "Force recording a note with the DONE state" note)))
2154 (defgroup org-priorities nil
2155 "Priorities in Org-mode."
2156 :tag "Org Priorities"
2157 :group 'org-todo)
2159 (defcustom org-enable-priority-commands t
2160 "Non-nil means, priority commands are active.
2161 When nil, these commands will be disabled, so that you never accidentally
2162 set a priority."
2163 :group 'org-priorities
2164 :type 'boolean)
2166 (defcustom org-highest-priority ?A
2167 "The highest priority of TODO items. A character like ?A, ?B etc.
2168 Must have a smaller ASCII number than `org-lowest-priority'."
2169 :group 'org-priorities
2170 :type 'character)
2172 (defcustom org-lowest-priority ?C
2173 "The lowest priority of TODO items. A character like ?A, ?B etc.
2174 Must have a larger ASCII number than `org-highest-priority'."
2175 :group 'org-priorities
2176 :type 'character)
2178 (defcustom org-default-priority ?B
2179 "The default priority of TODO items.
2180 This is the priority an item get if no explicit priority is given."
2181 :group 'org-priorities
2182 :type 'character)
2184 (defcustom org-priority-start-cycle-with-default t
2185 "Non-nil means, start with default priority when starting to cycle.
2186 When this is nil, the first step in the cycle will be (depending on the
2187 command used) one higher or lower that the default priority."
2188 :group 'org-priorities
2189 :type 'boolean)
2191 (defgroup org-time nil
2192 "Options concerning time stamps and deadlines in Org-mode."
2193 :tag "Org Time"
2194 :group 'org)
2196 (defcustom org-insert-labeled-timestamps-at-point nil
2197 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2198 When nil, these labeled time stamps are forces into the second line of an
2199 entry, just after the headline. When scheduling from the global TODO list,
2200 the time stamp will always be forced into the second line."
2201 :group 'org-time
2202 :type 'boolean)
2204 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2205 "Formats for `format-time-string' which are used for time stamps.
2206 It is not recommended to change this constant.")
2208 (defcustom org-time-stamp-rounding-minutes '(0 5)
2209 "Number of minutes to round time stamps to.
2210 These are two values, the first applies when first creating a time stamp.
2211 The second applies when changing it with the commands `S-up' and `S-down'.
2212 When changing the time stamp, this means that it will change in steps
2213 of N minutes, as given by the second value.
2215 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2216 numbers should be factors of 60, so for example 5, 10, 15.
2218 When this is larger than 1, you can still force an exact time-stamp by using
2219 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2220 and by using a prefix arg to `S-up/down' to specify the exact number
2221 of minutes to shift."
2222 :group 'org-time
2223 :get '(lambda (var) ; Make sure all entries have 5 elements
2224 (if (integerp (default-value var))
2225 (list (default-value var) 5)
2226 (default-value var)))
2227 :type '(list
2228 (integer :tag "when inserting times")
2229 (integer :tag "when modifying times")))
2231 ;; Normalize old customizations of this variable.
2232 (when (integerp org-time-stamp-rounding-minutes)
2233 (setq org-time-stamp-rounding-minutes
2234 (list org-time-stamp-rounding-minutes
2235 org-time-stamp-rounding-minutes)))
2237 (defcustom org-display-custom-times nil
2238 "Non-nil means, overlay custom formats over all time stamps.
2239 The formats are defined through the variable `org-time-stamp-custom-formats'.
2240 To turn this on on a per-file basis, insert anywhere in the file:
2241 #+STARTUP: customtime"
2242 :group 'org-time
2243 :set 'set-default
2244 :type 'sexp)
2245 (make-variable-buffer-local 'org-display-custom-times)
2247 (defcustom org-time-stamp-custom-formats
2248 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2249 "Custom formats for time stamps. See `format-time-string' for the syntax.
2250 These are overlayed over the default ISO format if the variable
2251 `org-display-custom-times' is set. Time like %H:%M should be at the
2252 end of the second format. The custom formats are also honored by export
2253 commands, if custom time display is turned on at the time of export."
2254 :group 'org-time
2255 :type 'sexp)
2257 (defun org-time-stamp-format (&optional long inactive)
2258 "Get the right format for a time string."
2259 (let ((f (if long (cdr org-time-stamp-formats)
2260 (car org-time-stamp-formats))))
2261 (if inactive
2262 (concat "[" (substring f 1 -1) "]")
2263 f)))
2265 (defcustom org-time-clocksum-format "%d:%02d"
2266 "The format string used when creating CLOCKSUM lines, or when
2267 org-mode generates a time duration."
2268 :group 'org-time
2269 :type 'string)
2271 (defcustom org-time-clocksum-use-fractional nil
2272 "If non-nil, \\[org-clock-display] uses fractional times.
2273 org-mode generates a time duration."
2274 :group 'org-time
2275 :type 'boolean)
2277 (defcustom org-time-clocksum-fractional-format "%.2f"
2278 "The format string used when creating CLOCKSUM lines, or when
2279 org-mode generates a time duration."
2280 :group 'org-time
2281 :type 'string)
2283 (defcustom org-deadline-warning-days 14
2284 "No. of days before expiration during which a deadline becomes active.
2285 This variable governs the display in sparse trees and in the agenda.
2286 When 0 or negative, it means use this number (the absolute value of it)
2287 even if a deadline has a different individual lead time specified.
2289 Custom commands can set this variable in the options section."
2290 :group 'org-time
2291 :group 'org-agenda-daily/weekly
2292 :type 'integer)
2294 (defcustom org-read-date-prefer-future t
2295 "Non-nil means, assume future for incomplete date input from user.
2296 This affects the following situations:
2297 1. The user gives a month but not a year.
2298 For example, if it is april and you enter \"feb 2\", this will be read
2299 as feb 2, *next* year. \"May 5\", however, will be this year.
2300 2. The user gives a day, but no month.
2301 For example, if today is the 15th, and you enter \"3\", Org-mode will
2302 read this as the third of *next* month. However, if you enter \"17\",
2303 it will be considered as *this* month.
2305 If you set this variable to the symbol `time', then also the following
2306 will work:
2308 3. If the user gives a time, but no day. If the time is before now,
2309 to will be interpreted as tomorrow.
2311 Currently none of this works for ISO week specifications.
2313 When this option is nil, the current day, month and year will always be
2314 used as defaults."
2315 :group 'org-time
2316 :type '(choice
2317 (const :tag "Never" nil)
2318 (const :tag "Check month and day" t)
2319 (const :tag "Check month, day, and time" time)))
2321 (defcustom org-read-date-display-live t
2322 "Non-nil means, display current interpretation of date prompt live.
2323 This display will be in an overlay, in the minibuffer."
2324 :group 'org-time
2325 :type 'boolean)
2327 (defcustom org-read-date-popup-calendar t
2328 "Non-nil means, pop up a calendar when prompting for a date.
2329 In the calendar, the date can be selected with mouse-1. However, the
2330 minibuffer will also be active, and you can simply enter the date as well.
2331 When nil, only the minibuffer will be available."
2332 :group 'org-time
2333 :type 'boolean)
2334 (if (fboundp 'defvaralias)
2335 (defvaralias 'org-popup-calendar-for-date-prompt
2336 'org-read-date-popup-calendar))
2338 (defcustom org-read-date-minibuffer-setup-hook nil
2339 "Hook to be used to set up keys for the date/time interface.
2340 Add key definitions to `minibuffer-local-map', which will be a temporary
2341 copy."
2342 :group 'org-time
2343 :type 'hook)
2345 (defcustom org-extend-today-until 0
2346 "The hour when your day really ends. Must be an integer.
2347 This has influence for the following applications:
2348 - When switching the agenda to \"today\". It it is still earlier than
2349 the time given here, the day recognized as TODAY is actually yesterday.
2350 - When a date is read from the user and it is still before the time given
2351 here, the current date and time will be assumed to be yesterday, 23:59.
2352 Also, timestamps inserted in remember templates follow this rule.
2354 IMPORTANT: This is a feature whose implementation is and likely will
2355 remain incomplete. Really, it is only here because past midnight seems to
2356 be the favorite working time of John Wiegley :-)"
2357 :group 'org-time
2358 :type 'integer)
2360 (defcustom org-edit-timestamp-down-means-later nil
2361 "Non-nil means, S-down will increase the time in a time stamp.
2362 When nil, S-up will increase."
2363 :group 'org-time
2364 :type 'boolean)
2366 (defcustom org-calendar-follow-timestamp-change t
2367 "Non-nil means, make the calendar window follow timestamp changes.
2368 When a timestamp is modified and the calendar window is visible, it will be
2369 moved to the new date."
2370 :group 'org-time
2371 :type 'boolean)
2373 (defgroup org-tags nil
2374 "Options concerning tags in Org-mode."
2375 :tag "Org Tags"
2376 :group 'org)
2378 (defcustom org-tag-alist nil
2379 "List of tags allowed in Org-mode files.
2380 When this list is nil, Org-mode will base TAG input on what is already in the
2381 buffer.
2382 The value of this variable is an alist, the car of each entry must be a
2383 keyword as a string, the cdr may be a character that is used to select
2384 that tag through the fast-tag-selection interface.
2385 See the manual for details."
2386 :group 'org-tags
2387 :type '(repeat
2388 (choice
2389 (cons (string :tag "Tag name")
2390 (character :tag "Access char"))
2391 (list :tag "Start radio group"
2392 (const :startgroup)
2393 (option (string :tag "Group description")))
2394 (list :tag "End radio group"
2395 (const :endgroup)
2396 (option (string :tag "Group description")))
2397 (const :tag "New line" (:newline)))))
2399 (defcustom org-tag-persistent-alist nil
2400 "List of tags that will always appear in all Org-mode files.
2401 This is in addition to any in buffer settings or customizations
2402 of `org-tag-alist'.
2403 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2404 The value of this variable is an alist, the car of each entry must be a
2405 keyword as a string, the cdr may be a character that is used to select
2406 that tag through the fast-tag-selection interface.
2407 See the manual for details.
2408 To disable these tags on a per-file basis, insert anywhere in the file:
2409 #+STARTUP: noptag"
2410 :group 'org-tags
2411 :type '(repeat
2412 (choice
2413 (cons (string :tag "Tag name")
2414 (character :tag "Access char"))
2415 (const :tag "Start radio group" (:startgroup))
2416 (const :tag "End radio group" (:endgroup))
2417 (const :tag "New line" (:newline)))))
2419 (defvar org-file-tags nil
2420 "List of tags that can be inherited by all entries in the file.
2421 The tags will be inherited if the variable `org-use-tag-inheritance'
2422 says they should be.
2423 This variable is populated from #+FILETAGS lines.")
2425 (defcustom org-use-fast-tag-selection 'auto
2426 "Non-nil means, use fast tag selection scheme.
2427 This is a special interface to select and deselect tags with single keys.
2428 When nil, fast selection is never used.
2429 When the symbol `auto', fast selection is used if and only if selection
2430 characters for tags have been configured, either through the variable
2431 `org-tag-alist' or through a #+TAGS line in the buffer.
2432 When t, fast selection is always used and selection keys are assigned
2433 automatically if necessary."
2434 :group 'org-tags
2435 :type '(choice
2436 (const :tag "Always" t)
2437 (const :tag "Never" nil)
2438 (const :tag "When selection characters are configured" 'auto)))
2440 (defcustom org-fast-tag-selection-single-key nil
2441 "Non-nil means, fast tag selection exits after first change.
2442 When nil, you have to press RET to exit it.
2443 During fast tag selection, you can toggle this flag with `C-c'.
2444 This variable can also have the value `expert'. In this case, the window
2445 displaying the tags menu is not even shown, until you press C-c again."
2446 :group 'org-tags
2447 :type '(choice
2448 (const :tag "No" nil)
2449 (const :tag "Yes" t)
2450 (const :tag "Expert" expert)))
2452 (defvar org-fast-tag-selection-include-todo nil
2453 "Non-nil means, fast tags selection interface will also offer TODO states.
2454 This is an undocumented feature, you should not rely on it.")
2456 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2457 "The column to which tags should be indented in a headline.
2458 If this number is positive, it specifies the column. If it is negative,
2459 it means that the tags should be flushright to that column. For example,
2460 -80 works well for a normal 80 character screen."
2461 :group 'org-tags
2462 :type 'integer)
2464 (defcustom org-auto-align-tags t
2465 "Non-nil means, realign tags after pro/demotion of TODO state change.
2466 These operations change the length of a headline and therefore shift
2467 the tags around. With this options turned on, after each such operation
2468 the tags are again aligned to `org-tags-column'."
2469 :group 'org-tags
2470 :type 'boolean)
2472 (defcustom org-use-tag-inheritance t
2473 "Non-nil means, tags in levels apply also for sublevels.
2474 When nil, only the tags directly given in a specific line apply there.
2475 This may also be a list of tags that should be inherited, or a regexp that
2476 matches tags that should be inherited. Additional control is possible
2477 with the variable `org-tags-exclude-from-inheritance' which gives an
2478 explicit list of tags to be excluded from inheritance., even if the value of
2479 `org-use-tag-inheritance' would select it for inheritance.
2481 If this option is t, a match early-on in a tree can lead to a large
2482 number of matches in the subtree when constructing the agenda or creating
2483 a sparse tree. If you only want to see the first match in a tree during
2484 a search, check out the variable `org-tags-match-list-sublevels'."
2485 :group 'org-tags
2486 :type '(choice
2487 (const :tag "Not" nil)
2488 (const :tag "Always" t)
2489 (repeat :tag "Specific tags" (string :tag "Tag"))
2490 (regexp :tag "Tags matched by regexp")))
2492 (defcustom org-tags-exclude-from-inheritance nil
2493 "List of tags that should never be inherited.
2494 This is a way to exclude a few tags from inheritance. For way to do
2495 the opposite, to actively allow inheritance for selected tags,
2496 see the variable `org-use-tag-inheritance'."
2497 :group 'org-tags
2498 :type '(repeat (string :tag "Tag")))
2500 (defun org-tag-inherit-p (tag)
2501 "Check if TAG is one that should be inherited."
2502 (cond
2503 ((member tag org-tags-exclude-from-inheritance) nil)
2504 ((eq org-use-tag-inheritance t) t)
2505 ((not org-use-tag-inheritance) nil)
2506 ((stringp org-use-tag-inheritance)
2507 (string-match org-use-tag-inheritance tag))
2508 ((listp org-use-tag-inheritance)
2509 (member tag org-use-tag-inheritance))
2510 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2512 (defcustom org-tags-match-list-sublevels t
2513 "Non-nil means list also sublevels of headlines matching a search.
2514 This variable applies to tags/property searches, and also to stuck
2515 projects because this search is based on a tags match as well.
2517 When set to the symbol `indented', sublevels are indented with
2518 leading dots.
2520 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2521 the sublevels of a headline matching a tag search often also match
2522 the same search. Listing all of them can create very long lists.
2523 Setting this variable to nil causes subtrees of a match to be skipped.
2525 This variable is semi-obsolete and probably should always be true. It
2526 is better to limit inheritance to certain tags using the variables
2527 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2528 :group 'org-tags
2529 :type '(choice
2530 (const :tag "No, don't list them" nil)
2531 (const :tag "Yes, do list them" t)
2532 (const :tag "List them, indented with leading dots" indented)))
2534 (defcustom org-tags-sort-function nil
2535 "When set, tags are sorted using this function as a comparator"
2536 :group 'org-tags
2537 :type '(choice
2538 (const :tag "No sorting" nil)
2539 (const :tag "Alphabetical" string<)
2540 (const :tag "Reverse alphabetical" string>)
2541 (function :tag "Custom function" nil)))
2543 (defvar org-tags-history nil
2544 "History of minibuffer reads for tags.")
2545 (defvar org-last-tags-completion-table nil
2546 "The last used completion table for tags.")
2547 (defvar org-after-tags-change-hook nil
2548 "Hook that is run after the tags in a line have changed.")
2550 (defgroup org-properties nil
2551 "Options concerning properties in Org-mode."
2552 :tag "Org Properties"
2553 :group 'org)
2555 (defcustom org-property-format "%-10s %s"
2556 "How property key/value pairs should be formatted by `indent-line'.
2557 When `indent-line' hits a property definition, it will format the line
2558 according to this format, mainly to make sure that the values are
2559 lined-up with respect to each other."
2560 :group 'org-properties
2561 :type 'string)
2563 (defcustom org-use-property-inheritance nil
2564 "Non-nil means, properties apply also for sublevels.
2566 This setting is chiefly used during property searches. Turning it on can
2567 cause significant overhead when doing a search, which is why it is not
2568 on by default.
2570 When nil, only the properties directly given in the current entry count.
2571 When t, every property is inherited. The value may also be a list of
2572 properties that should have inheritance, or a regular expression matching
2573 properties that should be inherited.
2575 However, note that some special properties use inheritance under special
2576 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2577 and the properties ending in \"_ALL\" when they are used as descriptor
2578 for valid values of a property.
2580 Note for programmers:
2581 When querying an entry with `org-entry-get', you can control if inheritance
2582 should be used. By default, `org-entry-get' looks only at the local
2583 properties. You can request inheritance by setting the inherit argument
2584 to t (to force inheritance) or to `selective' (to respect the setting
2585 in this variable)."
2586 :group 'org-properties
2587 :type '(choice
2588 (const :tag "Not" nil)
2589 (const :tag "Always" t)
2590 (repeat :tag "Specific properties" (string :tag "Property"))
2591 (regexp :tag "Properties matched by regexp")))
2593 (defun org-property-inherit-p (property)
2594 "Check if PROPERTY is one that should be inherited."
2595 (cond
2596 ((eq org-use-property-inheritance t) t)
2597 ((not org-use-property-inheritance) nil)
2598 ((stringp org-use-property-inheritance)
2599 (string-match org-use-property-inheritance property))
2600 ((listp org-use-property-inheritance)
2601 (member property org-use-property-inheritance))
2602 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2604 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2605 "The default column format, if no other format has been defined.
2606 This variable can be set on the per-file basis by inserting a line
2608 #+COLUMNS: %25ITEM ....."
2609 :group 'org-properties
2610 :type 'string)
2612 (defcustom org-columns-ellipses ".."
2613 "The ellipses to be used when a field in column view is truncated.
2614 When this is the empty string, as many characters as possible are shown,
2615 but then there will be no visual indication that the field has been truncated.
2616 When this is a string of length N, the last N characters of a truncated
2617 field are replaced by this string. If the column is narrower than the
2618 ellipses string, only part of the ellipses string will be shown."
2619 :group 'org-properties
2620 :type 'string)
2622 (defcustom org-columns-modify-value-for-display-function nil
2623 "Function that modifies values for display in column view.
2624 For example, it can be used to cut out a certain part from a time stamp.
2625 The function must take 2 arguments:
2627 column-title The title of the column (*not* the property name)
2628 value The value that should be modified.
2630 The function should return the value that should be displayed,
2631 or nil if the normal value should be used."
2632 :group 'org-properties
2633 :type 'function)
2635 (defcustom org-effort-property "Effort"
2636 "The property that is being used to keep track of effort estimates.
2637 Effort estimates given in this property need to have the format H:MM."
2638 :group 'org-properties
2639 :group 'org-progress
2640 :type '(string :tag "Property"))
2642 (defconst org-global-properties-fixed
2643 '(("VISIBILITY_ALL" . "folded children content all")
2644 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2645 "List of property/value pairs that can be inherited by any entry.
2647 These are fixed values, for the preset properties. The user variable
2648 that can be used to add to this list is `org-global-properties'.
2650 The entries in this list are cons cells where the car is a property
2651 name and cdr is a string with the value. If the value represents
2652 multiple items like an \"_ALL\" property, separate the items by
2653 spaces.")
2655 (defcustom org-global-properties nil
2656 "List of property/value pairs that can be inherited by any entry.
2658 This list will be combined with the constant `org-global-properties-fixed'.
2660 The entries in this list are cons cells where the car is a property
2661 name and cdr is a string with the value.
2663 You can set buffer-local values for the same purpose in the variable
2664 `org-file-properties' this by adding lines like
2666 #+PROPERTY: NAME VALUE"
2667 :group 'org-properties
2668 :type '(repeat
2669 (cons (string :tag "Property")
2670 (string :tag "Value"))))
2672 (defvar org-file-properties nil
2673 "List of property/value pairs that can be inherited by any entry.
2674 Valid for the current buffer.
2675 This variable is populated from #+PROPERTY lines.")
2676 (make-variable-buffer-local 'org-file-properties)
2678 (defgroup org-agenda nil
2679 "Options concerning agenda views in Org-mode."
2680 :tag "Org Agenda"
2681 :group 'org)
2683 (defvar org-category nil
2684 "Variable used by org files to set a category for agenda display.
2685 Such files should use a file variable to set it, for example
2687 # -*- mode: org; org-category: \"ELisp\"
2689 or contain a special line
2691 #+CATEGORY: ELisp
2693 If the file does not specify a category, then file's base name
2694 is used instead.")
2695 (make-variable-buffer-local 'org-category)
2696 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2698 (defcustom org-agenda-files nil
2699 "The files to be used for agenda display.
2700 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2701 \\[org-remove-file]. You can also use customize to edit the list.
2703 If an entry is a directory, all files in that directory that are matched by
2704 `org-agenda-file-regexp' will be part of the file list.
2706 If the value of the variable is not a list but a single file name, then
2707 the list of agenda files is actually stored and maintained in that file, one
2708 agenda file per line."
2709 :group 'org-agenda
2710 :type '(choice
2711 (repeat :tag "List of files and directories" file)
2712 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2714 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2715 "Regular expression to match files for `org-agenda-files'.
2716 If any element in the list in that variable contains a directory instead
2717 of a normal file, all files in that directory that are matched by this
2718 regular expression will be included."
2719 :group 'org-agenda
2720 :type 'regexp)
2722 (defcustom org-agenda-text-search-extra-files nil
2723 "List of extra files to be searched by text search commands.
2724 These files will be search in addition to the agenda files by the
2725 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2726 Note that these files will only be searched for text search commands,
2727 not for the other agenda views like todo lists, tag searches or the weekly
2728 agenda. This variable is intended to list notes and possibly archive files
2729 that should also be searched by these two commands.
2730 In fact, if the first element in the list is the symbol `agenda-archives',
2731 than all archive files of all agenda files will be added to the search
2732 scope."
2733 :group 'org-agenda
2734 :type '(set :greedy t
2735 (const :tag "Agenda Archives" agenda-archives)
2736 (repeat :inline t (file))))
2738 (if (fboundp 'defvaralias)
2739 (defvaralias 'org-agenda-multi-occur-extra-files
2740 'org-agenda-text-search-extra-files))
2742 (defcustom org-agenda-skip-unavailable-files nil
2743 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2744 A nil value means to remove them, after a query, from the list."
2745 :group 'org-agenda
2746 :type 'boolean)
2748 (defcustom org-calendar-to-agenda-key [?c]
2749 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2750 The command `org-calendar-goto-agenda' will be bound to this key. The
2751 default is the character `c' because then `c' can be used to switch back and
2752 forth between agenda and calendar."
2753 :group 'org-agenda
2754 :type 'sexp)
2756 (defcustom org-calendar-agenda-action-key [?k]
2757 "The key to be installed in `calendar-mode-map' for agenda-action.
2758 The command `org-agenda-action' will be bound to this key. The
2759 default is the character `k' because we use the same key in the agenda."
2760 :group 'org-agenda
2761 :type 'sexp)
2763 (eval-after-load "calendar"
2764 '(progn
2765 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2766 'org-calendar-goto-agenda)
2767 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2768 'org-agenda-action)))
2770 (defgroup org-latex nil
2771 "Options for embedding LaTeX code into Org-mode."
2772 :tag "Org LaTeX"
2773 :group 'org)
2775 (defcustom org-format-latex-options
2776 '(:foreground default :background default :scale 1.0
2777 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2778 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2779 "Options for creating images from LaTeX fragments.
2780 This is a property list with the following properties:
2781 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2782 `default' means use the foreground of the default face.
2783 :background the background color, or \"Transparent\".
2784 `default' means use the background of the default face.
2785 :scale a scaling factor for the size of the images.
2786 :html-foreground, :html-background, :html-scale
2787 the same numbers for HTML export.
2788 :matchers a list indicating which matchers should be used to
2789 find LaTeX fragments. Valid members of this list are:
2790 \"begin\" find environments
2791 \"$1\" find single characters surrounded by $.$
2792 \"$\" find math expressions surrounded by $...$
2793 \"$$\" find math expressions surrounded by $$....$$
2794 \"\\(\" find math expressions surrounded by \\(...\\)
2795 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2796 :group 'org-latex
2797 :type 'plist)
2799 (defcustom org-format-latex-header "\\documentclass{article}
2800 \\usepackage{amssymb}
2801 \\usepackage[usenames]{color}
2802 \\usepackage{amsmath}
2803 \\usepackage{latexsym}
2804 \\usepackage[mathscr]{eucal}
2805 \\pagestyle{empty} % do not remove
2806 % The settings below are copied from fullpage.sty
2807 \\setlength{\\textwidth}{\\paperwidth}
2808 \\addtolength{\\textwidth}{-3cm}
2809 \\setlength{\\oddsidemargin}{1.5cm}
2810 \\addtolength{\\oddsidemargin}{-2.54cm}
2811 \\setlength{\\evensidemargin}{\\oddsidemargin}
2812 \\setlength{\\textheight}{\\paperheight}
2813 \\addtolength{\\textheight}{-\\headheight}
2814 \\addtolength{\\textheight}{-\\headsep}
2815 \\addtolength{\\textheight}{-\\footskip}
2816 \\addtolength{\\textheight}{-3cm}
2817 \\setlength{\\topmargin}{1.5cm}
2818 \\addtolength{\\topmargin}{-2.54cm}"
2819 "The document header used for processing LaTeX fragments.
2820 It is imperative that this header make sure that no page number
2821 appears on the page."
2822 :group 'org-latex
2823 :type 'string)
2826 (defgroup org-font-lock nil
2827 "Font-lock settings for highlighting in Org-mode."
2828 :tag "Org Font Lock"
2829 :group 'org)
2831 (defcustom org-level-color-stars-only nil
2832 "Non-nil means fontify only the stars in each headline.
2833 When nil, the entire headline is fontified.
2834 Changing it requires restart of `font-lock-mode' to become effective
2835 also in regions already fontified."
2836 :group 'org-font-lock
2837 :type 'boolean)
2839 (defcustom org-hide-leading-stars nil
2840 "Non-nil means, hide the first N-1 stars in a headline.
2841 This works by using the face `org-hide' for these stars. This
2842 face is white for a light background, and black for a dark
2843 background. You may have to customize the face `org-hide' to
2844 make this work.
2845 Changing it requires restart of `font-lock-mode' to become effective
2846 also in regions already fontified.
2847 You may also set this on a per-file basis by adding one of the following
2848 lines to the buffer:
2850 #+STARTUP: hidestars
2851 #+STARTUP: showstars"
2852 :group 'org-font-lock
2853 :type 'boolean)
2855 (defcustom org-fontify-done-headline nil
2856 "Non-nil means, change the face of a headline if it is marked DONE.
2857 Normally, only the TODO/DONE keyword indicates the state of a headline.
2858 When this is non-nil, the headline after the keyword is set to the
2859 `org-headline-done' as an additional indication."
2860 :group 'org-font-lock
2861 :type 'boolean)
2863 (defcustom org-fontify-emphasized-text t
2864 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2865 Changing this variable requires a restart of Emacs to take effect."
2866 :group 'org-font-lock
2867 :type 'boolean)
2869 (defcustom org-fontify-whole-heading-line nil
2870 "Non-nil means fontify the whole line for headings.
2871 This is useful when setting a background color for the
2872 org-leve-* faces."
2873 :group 'org-font-lock
2874 :type 'boolean)
2876 (defcustom org-highlight-latex-fragments-and-specials nil
2877 "Non-nil means, fontify what is treated specially by the exporters."
2878 :group 'org-font-lock
2879 :type 'boolean)
2881 (defcustom org-hide-emphasis-markers nil
2882 "Non-nil mean font-lock should hide the emphasis marker characters."
2883 :group 'org-font-lock
2884 :type 'boolean)
2886 (defvar org-emph-re nil
2887 "Regular expression for matching emphasis.")
2888 (defvar org-verbatim-re nil
2889 "Regular expression for matching verbatim text.")
2890 (defvar org-emphasis-regexp-components) ; defined just below
2891 (defvar org-emphasis-alist) ; defined just below
2892 (defun org-set-emph-re (var val)
2893 "Set variable and compute the emphasis regular expression."
2894 (set var val)
2895 (when (and (boundp 'org-emphasis-alist)
2896 (boundp 'org-emphasis-regexp-components)
2897 org-emphasis-alist org-emphasis-regexp-components)
2898 (let* ((e org-emphasis-regexp-components)
2899 (pre (car e))
2900 (post (nth 1 e))
2901 (border (nth 2 e))
2902 (body (nth 3 e))
2903 (nl (nth 4 e))
2904 (body1 (concat body "*?"))
2905 (markers (mapconcat 'car org-emphasis-alist ""))
2906 (vmarkers (mapconcat
2907 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2908 org-emphasis-alist "")))
2909 ;; make sure special characters appear at the right position in the class
2910 (if (string-match "\\^" markers)
2911 (setq markers (concat (replace-match "" t t markers) "^")))
2912 (if (string-match "-" markers)
2913 (setq markers (concat (replace-match "" t t markers) "-")))
2914 (if (string-match "\\^" vmarkers)
2915 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2916 (if (string-match "-" vmarkers)
2917 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2918 (if (> nl 0)
2919 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2920 (int-to-string nl) "\\}")))
2921 ;; Make the regexp
2922 (setq org-emph-re
2923 (concat "\\([" pre "]\\|^\\)"
2924 "\\("
2925 "\\([" markers "]\\)"
2926 "\\("
2927 "[^" border "]\\|"
2928 "[^" border "]"
2929 body1
2930 "[^" border "]"
2931 "\\)"
2932 "\\3\\)"
2933 "\\([" post "]\\|$\\)"))
2934 (setq org-verbatim-re
2935 (concat "\\([" pre "]\\|^\\)"
2936 "\\("
2937 "\\([" vmarkers "]\\)"
2938 "\\("
2939 "[^" border "]\\|"
2940 "[^" border "]"
2941 body1
2942 "[^" border "]"
2943 "\\)"
2944 "\\3\\)"
2945 "\\([" post "]\\|$\\)")))))
2947 (defcustom org-emphasis-regexp-components
2948 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
2949 "Components used to build the regular expression for emphasis.
2950 This is a list with 6 entries. Terminology: In an emphasis string
2951 like \" *strong word* \", we call the initial space PREMATCH, the final
2952 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2953 and \"trong wor\" is the body. The different components in this variable
2954 specify what is allowed/forbidden in each part:
2956 pre Chars allowed as prematch. Beginning of line will be allowed too.
2957 post Chars allowed as postmatch. End of line will be allowed too.
2958 border The chars *forbidden* as border characters.
2959 body-regexp A regexp like \".\" to match a body character. Don't use
2960 non-shy groups here, and don't allow newline here.
2961 newline The maximum number of newlines allowed in an emphasis exp.
2963 Use customize to modify this, or restart Emacs after changing it."
2964 :group 'org-font-lock
2965 :set 'org-set-emph-re
2966 :type '(list
2967 (sexp :tag "Allowed chars in pre ")
2968 (sexp :tag "Allowed chars in post ")
2969 (sexp :tag "Forbidden chars in border ")
2970 (sexp :tag "Regexp for body ")
2971 (integer :tag "number of newlines allowed")
2972 (option (boolean :tag "Please ignore this button"))))
2974 (defcustom org-emphasis-alist
2975 `(("*" bold "<b>" "</b>")
2976 ("/" italic "<i>" "</i>")
2977 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2978 ("=" org-code "<code>" "</code>" verbatim)
2979 ("~" org-verbatim "<code>" "</code>" verbatim)
2980 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2981 "<del>" "</del>")
2983 "Special syntax for emphasized text.
2984 Text starting and ending with a special character will be emphasized, for
2985 example *bold*, _underlined_ and /italic/. This variable sets the marker
2986 characters, the face to be used by font-lock for highlighting in Org-mode
2987 Emacs buffers, and the HTML tags to be used for this.
2988 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2989 Use customize to modify this, or restart Emacs after changing it."
2990 :group 'org-font-lock
2991 :set 'org-set-emph-re
2992 :type '(repeat
2993 (list
2994 (string :tag "Marker character")
2995 (choice
2996 (face :tag "Font-lock-face")
2997 (plist :tag "Face property list"))
2998 (string :tag "HTML start tag")
2999 (string :tag "HTML end tag")
3000 (option (const verbatim)))))
3002 (defvar org-protecting-blocks
3003 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3004 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3005 This is needed for font-lock setup.")
3007 ;;; Miscellaneous options
3009 (defgroup org-completion nil
3010 "Completion in Org-mode."
3011 :tag "Org Completion"
3012 :group 'org)
3014 (defcustom org-completion-use-ido nil
3015 "Non-nil means, use ido completion wherever possible.
3016 Note that `ido-mode' must be active for this variable to be relevant.
3017 If you decide to turn this variable on, you might well want to turn off
3018 `org-outline-path-complete-in-steps'.
3019 See also `org-completion-use-iswitchb'."
3020 :group 'org-completion
3021 :type 'boolean)
3023 (defcustom org-completion-use-iswitchb nil
3024 "Non-nil means, use iswitchb completion wherever possible.
3025 Note that `iswitchb-mode' must be active for this variable to be relevant.
3026 If you decide to turn this variable on, you might well want to turn off
3027 `org-outline-path-complete-in-steps'.
3028 Note that thi variable has only an effect if `org-completion-use-ido' is nil."
3029 :group 'org-completion
3030 :type 'boolean)
3032 (defcustom org-completion-fallback-command 'hippie-expand
3033 "The expansion command called by \\[org-complete] in normal context.
3034 Normal means, no org-mode-specific context."
3035 :group 'org-completion
3036 :type 'function)
3038 ;;; Functions and variables from ther packages
3039 ;; Declared here to avoid compiler warnings
3041 ;; XEmacs only
3042 (defvar outline-mode-menu-heading)
3043 (defvar outline-mode-menu-show)
3044 (defvar outline-mode-menu-hide)
3045 (defvar zmacs-regions) ; XEmacs regions
3047 ;; Emacs only
3048 (defvar mark-active)
3050 ;; Various packages
3051 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3052 (declare-function calendar-forward-day "cal-move" (arg))
3053 (declare-function calendar-goto-date "cal-move" (date))
3054 (declare-function calendar-goto-today "cal-move" ())
3055 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3056 (defvar calc-embedded-close-formula)
3057 (defvar calc-embedded-open-formula)
3058 (declare-function cdlatex-tab "ext:cdlatex" ())
3059 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3060 (defvar font-lock-unfontify-region-function)
3061 (declare-function iswitchb-read-buffer "iswitchb"
3062 (prompt &optional default require-match start matches-set))
3063 (defvar iswitchb-temp-buflist)
3064 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3065 (defvar org-agenda-tags-todo-honor-ignore-options)
3066 (declare-function org-agenda-skip "org-agenda" ())
3067 (declare-function org-format-agenda-item "org-agenda"
3068 (extra txt &optional category tags dotime noprefix remove-re))
3069 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3070 (declare-function org-agenda-change-all-lines "org-agenda"
3071 (newhead hdmarker &optional fixface just-this))
3072 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3073 (declare-function org-agenda-maybe-redo "org-agenda" ())
3074 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3075 (beg end))
3076 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3077 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3078 "org-agenda" (&optional end))
3079 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3080 (declare-function org-indent-mode "org-indent" (&optional arg))
3081 (declare-function parse-time-string "parse-time" (string))
3082 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3083 (defvar remember-data-file)
3084 (defvar texmathp-why)
3085 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3086 (declare-function table--at-cell-p "table" (position &optional object at-column))
3088 (defvar w3m-current-url)
3089 (defvar w3m-current-title)
3091 (defvar org-latex-regexps)
3093 ;;; Autoload and prepare some org modules
3095 ;; Some table stuff that needs to be defined here, because it is used
3096 ;; by the functions setting up org-mode or checking for table context.
3098 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3099 "Detects an org-type or table-type table.")
3100 (defconst org-table-line-regexp "^[ \t]*|"
3101 "Detects an org-type table line.")
3102 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3103 "Detects an org-type table line.")
3104 (defconst org-table-hline-regexp "^[ \t]*|-"
3105 "Detects an org-type table hline.")
3106 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3107 "Detects a table-type table hline.")
3108 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3109 "Searching from within a table (any type) this finds the first line
3110 outside the table.")
3112 ;; Autoload the functions in org-table.el that are needed by functions here.
3114 (eval-and-compile
3115 (org-autoload "org-table"
3116 '(org-table-align org-table-begin org-table-blank-field
3117 org-table-convert org-table-convert-region org-table-copy-down
3118 org-table-copy-region org-table-create
3119 org-table-create-or-convert-from-region
3120 org-table-create-with-table.el org-table-current-dline
3121 org-table-cut-region org-table-delete-column org-table-edit-field
3122 org-table-edit-formulas org-table-end org-table-eval-formula
3123 org-table-export org-table-field-info
3124 org-table-get-stored-formulas org-table-goto-column
3125 org-table-hline-and-move org-table-import org-table-insert-column
3126 org-table-insert-hline org-table-insert-row org-table-iterate
3127 org-table-justify-field-maybe org-table-kill-row
3128 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3129 org-table-move-column org-table-move-column-left
3130 org-table-move-column-right org-table-move-row
3131 org-table-move-row-down org-table-move-row-up
3132 org-table-next-field org-table-next-row org-table-paste-rectangle
3133 org-table-previous-field org-table-recalculate
3134 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3135 org-table-toggle-coordinate-overlays
3136 org-table-toggle-formula-debugger org-table-wrap-region
3137 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3139 (defun org-at-table-p (&optional table-type)
3140 "Return t if the cursor is inside an org-type table.
3141 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3142 (if org-enable-table-editor
3143 (save-excursion
3144 (beginning-of-line 1)
3145 (looking-at (if table-type org-table-any-line-regexp
3146 org-table-line-regexp)))
3147 nil))
3148 (defsubst org-table-p () (org-at-table-p))
3150 (defun org-at-table.el-p ()
3151 "Return t if and only if we are at a table.el table."
3152 (and (org-at-table-p 'any)
3153 (save-excursion
3154 (goto-char (org-table-begin 'any))
3155 (looking-at org-table1-hline-regexp))))
3156 (defun org-table-recognize-table.el ()
3157 "If there is a table.el table nearby, recognize it and move into it."
3158 (if org-table-tab-recognizes-table.el
3159 (if (org-at-table.el-p)
3160 (progn
3161 (beginning-of-line 1)
3162 (if (looking-at org-table-dataline-regexp)
3164 (if (looking-at org-table1-hline-regexp)
3165 (progn
3166 (beginning-of-line 2)
3167 (if (looking-at org-table-any-border-regexp)
3168 (beginning-of-line -1)))))
3169 (if (re-search-forward "|" (org-table-end t) t)
3170 (progn
3171 (require 'table)
3172 (if (table--at-cell-p (point))
3174 (message "recognizing table.el table...")
3175 (table-recognize-table)
3176 (message "recognizing table.el table...done")))
3177 (error "This should not happen..."))
3179 nil)
3180 nil))
3182 (defun org-at-table-hline-p ()
3183 "Return t if the cursor is inside a hline in a table."
3184 (if org-enable-table-editor
3185 (save-excursion
3186 (beginning-of-line 1)
3187 (looking-at org-table-hline-regexp))
3188 nil))
3190 (defvar org-table-clean-did-remove-column nil)
3192 (defun org-table-map-tables (function)
3193 "Apply FUNCTION to the start of all tables in the buffer."
3194 (save-excursion
3195 (save-restriction
3196 (widen)
3197 (goto-char (point-min))
3198 (while (re-search-forward org-table-any-line-regexp nil t)
3199 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3200 (beginning-of-line 1)
3201 (when (looking-at org-table-line-regexp)
3202 (save-excursion (funcall function))
3203 (or (looking-at org-table-line-regexp)
3204 (forward-char 1)))
3205 (re-search-forward org-table-any-border-regexp nil 1))))
3206 (message "Mapping tables: done"))
3208 ;; Declare and autoload functions from org-exp.el & Co
3210 (declare-function org-default-export-plist "org-exp")
3211 (declare-function org-infile-export-plist "org-exp")
3212 (declare-function org-get-current-options "org-exp")
3213 (eval-and-compile
3214 (org-autoload "org-exp"
3215 '(org-export org-export-visible
3216 org-insert-export-options-template
3217 org-table-clean-before-export))
3218 (org-autoload "org-ascii"
3219 '(org-export-as-ascii org-export-ascii-preprocess
3220 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3221 org-export-region-as-ascii))
3222 (org-autoload "org-html"
3223 '(org-export-as-html-and-open
3224 org-export-as-html-batch org-export-as-html-to-buffer
3225 org-replace-region-by-html org-export-region-as-html
3226 org-export-as-html))
3227 (org-autoload "org-icalendar"
3228 '(org-export-icalendar-this-file
3229 org-export-icalendar-all-agenda-files
3230 org-export-icalendar-combine-agenda-files))
3231 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3233 ;; Declare and autoload functions from org-agenda.el
3235 (eval-and-compile
3236 (org-autoload "org-agenda"
3237 '(org-agenda org-agenda-list org-search-view
3238 org-todo-list org-tags-view org-agenda-list-stuck-projects
3239 org-diary org-agenda-to-appt
3240 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3242 ;; Autoload org-remember
3244 (eval-and-compile
3245 (org-autoload "org-remember"
3246 '(org-remember-insinuate org-remember-annotation
3247 org-remember-apply-template org-remember org-remember-handler)))
3249 ;; Autoload org-clock.el
3252 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3253 (beg end))
3254 (declare-function org-clock-update-mode-line "org-clock" ())
3255 (declare-function org-resolve-clocks "org-clock"
3256 (&optional also-non-dangling-p prompt last-valid))
3257 (defvar org-clock-start-time)
3258 (defvar org-clock-marker (make-marker)
3259 "Marker recording the last clock-in.")
3260 (defvar org-clock-hd-marker (make-marker)
3261 "Marker recording the last clock-in, but the headline position.")
3262 (defvar org-clock-heading ""
3263 "The heading of the current clock entry.")
3264 (defun org-clock-is-active ()
3265 "Return non-nil if clock is currently running.
3266 The return value is actually the clock marker."
3267 (marker-buffer org-clock-marker))
3269 (eval-and-compile
3270 (org-autoload
3271 "org-clock"
3272 '(org-clock-in org-clock-out org-clock-cancel
3273 org-clock-goto org-clock-sum org-clock-display
3274 org-clock-remove-overlays org-clock-report
3275 org-clocktable-shift org-dblock-write:clocktable
3276 org-get-clocktable org-resolve-clocks)))
3278 (defun org-clock-update-time-maybe ()
3279 "If this is a CLOCK line, update it and return t.
3280 Otherwise, return nil."
3281 (interactive)
3282 (save-excursion
3283 (beginning-of-line 1)
3284 (skip-chars-forward " \t")
3285 (when (looking-at org-clock-string)
3286 (let ((re (concat "[ \t]*" org-clock-string
3287 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3288 "\\([ \t]*=>.*\\)?\\)?"))
3289 ts te h m s neg)
3290 (cond
3291 ((not (looking-at re))
3292 nil)
3293 ((not (match-end 2))
3294 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3295 (> org-clock-marker (point))
3296 (<= org-clock-marker (point-at-eol)))
3297 ;; The clock is running here
3298 (setq org-clock-start-time
3299 (apply 'encode-time
3300 (org-parse-time-string (match-string 1))))
3301 (org-clock-update-mode-line)))
3303 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3304 (end-of-line 1)
3305 (setq ts (match-string 1)
3306 te (match-string 3))
3307 (setq s (- (org-float-time
3308 (apply 'encode-time (org-parse-time-string te)))
3309 (org-float-time
3310 (apply 'encode-time (org-parse-time-string ts))))
3311 neg (< s 0)
3312 s (abs s)
3313 h (floor (/ s 3600))
3314 s (- s (* 3600 h))
3315 m (floor (/ s 60))
3316 s (- s (* 60 s)))
3317 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3318 t))))))
3320 (defun org-check-running-clock ()
3321 "Check if the current buffer contains the running clock.
3322 If yes, offer to stop it and to save the buffer with the changes."
3323 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3324 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3325 (buffer-name))))
3326 (org-clock-out)
3327 (when (y-or-n-p "Save changed buffer?")
3328 (save-buffer))))
3330 (defun org-clocktable-try-shift (dir n)
3331 "Check if this line starts a clock table, if yes, shift the time block."
3332 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3333 (org-clocktable-shift dir n)))
3335 ;; Autoload org-timer.el
3337 (eval-and-compile
3338 (org-autoload
3339 "org-timer"
3340 '(org-timer-start org-timer org-timer-item
3341 org-timer-change-times-in-region
3342 org-timer-set-timer
3343 org-timer-reset-timers
3344 org-timer-show-remaining-time)))
3346 ;; Autoload org-feed.el
3348 (eval-and-compile
3349 (org-autoload
3350 "org-feed"
3351 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3354 ;; Autoload org-indent.el
3356 ;; Define the variable already here, to make sure we have it.
3357 (defvar org-indent-mode nil
3358 "Non-nil if Org-Indent mode is enabled.
3359 Use the command `org-indent-mode' to change this variable.")
3361 (eval-and-compile
3362 (org-autoload
3363 "org-indent"
3364 '(org-indent-mode)))
3366 ;; Autoload org-mobile.el
3368 (eval-and-compile
3369 (org-autoload
3370 "org-mobile"
3371 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3373 ;; Autoload archiving code
3374 ;; The stuff that is needed for cycling and tags has to be defined here.
3376 (defgroup org-archive nil
3377 "Options concerning archiving in Org-mode."
3378 :tag "Org Archive"
3379 :group 'org-structure)
3381 (defcustom org-archive-location "%s_archive::"
3382 "The location where subtrees should be archived.
3384 The value of this variable is a string, consisting of two parts,
3385 separated by a double-colon. The first part is a filename and
3386 the second part is a headline.
3388 When the filename is omitted, archiving happens in the same file.
3389 %s in the filename will be replaced by the current file
3390 name (without the directory part). Archiving to a different file
3391 is useful to keep archived entries from contributing to the
3392 Org-mode Agenda.
3394 The archived entries will be filed as subtrees of the specified
3395 headline. When the headline is omitted, the subtrees are simply
3396 filed away at the end of the file, as top-level entries. Also in
3397 the heading you can use %s to represent the file name, this can be
3398 useful when using the same archive for a number of different files.
3400 Here are a few examples:
3401 \"%s_archive::\"
3402 If the current file is Projects.org, archive in file
3403 Projects.org_archive, as top-level trees. This is the default.
3405 \"::* Archived Tasks\"
3406 Archive in the current file, under the top-level headline
3407 \"* Archived Tasks\".
3409 \"~/org/archive.org::\"
3410 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3412 \"~/org/archive.org::From %s\"
3413 Archive in file ~/org/archive.org (absolute path), und headlines
3414 \"From FILENAME\" where file name is the current file name.
3416 \"basement::** Finished Tasks\"
3417 Archive in file ./basement (relative path), as level 3 trees
3418 below the level 2 heading \"** Finished Tasks\".
3420 You may set this option on a per-file basis by adding to the buffer a
3421 line like
3423 #+ARCHIVE: basement::** Finished Tasks
3425 You may also define it locally for a subtree by setting an ARCHIVE property
3426 in the entry. If such a property is found in an entry, or anywhere up
3427 the hierarchy, it will be used."
3428 :group 'org-archive
3429 :type 'string)
3431 (defcustom org-archive-tag "ARCHIVE"
3432 "The tag that marks a subtree as archived.
3433 An archived subtree does not open during visibility cycling, and does
3434 not contribute to the agenda listings.
3435 After changing this, font-lock must be restarted in the relevant buffers to
3436 get the proper fontification."
3437 :group 'org-archive
3438 :group 'org-keywords
3439 :type 'string)
3441 (defcustom org-agenda-skip-archived-trees t
3442 "Non-nil means, the agenda will skip any items located in archived trees.
3443 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3444 variable is no longer recommended, you should leave it at the value t.
3445 Instead, use the key `v' to cycle the archives-mode in the agenda."
3446 :group 'org-archive
3447 :group 'org-agenda-skip
3448 :type 'boolean)
3450 (defcustom org-columns-skip-archived-trees t
3451 "Non-nil means, ignore archived trees when creating column view."
3452 :group 'org-archive
3453 :group 'org-properties
3454 :type 'boolean)
3456 (defcustom org-cycle-open-archived-trees nil
3457 "Non-nil means, `org-cycle' will open archived trees.
3458 An archived tree is a tree marked with the tag ARCHIVE.
3459 When nil, archived trees will stay folded. You can still open them with
3460 normal outline commands like `show-all', but not with the cycling commands."
3461 :group 'org-archive
3462 :group 'org-cycle
3463 :type 'boolean)
3465 (defcustom org-sparse-tree-open-archived-trees nil
3466 "Non-nil means sparse tree construction shows matches in archived trees.
3467 When nil, matches in these trees are highlighted, but the trees are kept in
3468 collapsed state."
3469 :group 'org-archive
3470 :group 'org-sparse-trees
3471 :type 'boolean)
3473 (defun org-cycle-hide-archived-subtrees (state)
3474 "Re-hide all archived subtrees after a visibility state change."
3475 (when (and (not org-cycle-open-archived-trees)
3476 (not (memq state '(overview folded))))
3477 (save-excursion
3478 (let* ((globalp (memq state '(contents all)))
3479 (beg (if globalp (point-min) (point)))
3480 (end (if globalp (point-max) (org-end-of-subtree t))))
3481 (org-hide-archived-subtrees beg end)
3482 (goto-char beg)
3483 (if (looking-at (concat ".*:" org-archive-tag ":"))
3484 (message "%s" (substitute-command-keys
3485 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3487 (defun org-force-cycle-archived ()
3488 "Cycle subtree even if it is archived."
3489 (interactive)
3490 (setq this-command 'org-cycle)
3491 (let ((org-cycle-open-archived-trees t))
3492 (call-interactively 'org-cycle)))
3494 (defun org-hide-archived-subtrees (beg end)
3495 "Re-hide all archived subtrees after a visibility state change."
3496 (save-excursion
3497 (let* ((re (concat ":" org-archive-tag ":")))
3498 (goto-char beg)
3499 (while (re-search-forward re end t)
3500 (and (org-on-heading-p) (org-flag-subtree t))
3501 (org-end-of-subtree t)))))
3503 (defun org-flag-subtree (flag)
3504 (save-excursion
3505 (org-back-to-heading t)
3506 (outline-end-of-heading)
3507 (outline-flag-region (point)
3508 (progn (org-end-of-subtree t) (point))
3509 flag)))
3511 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3513 (eval-and-compile
3514 (org-autoload "org-archive"
3515 '(org-add-archive-files org-archive-subtree
3516 org-archive-to-archive-sibling org-toggle-archive-tag)))
3518 ;; Autoload Column View Code
3520 (declare-function org-columns-number-to-string "org-colview")
3521 (declare-function org-columns-get-format-and-top-level "org-colview")
3522 (declare-function org-columns-compute "org-colview")
3524 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3525 '(org-columns-number-to-string org-columns-get-format-and-top-level
3526 org-columns-compute org-agenda-columns org-columns-remove-overlays
3527 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3529 ;; Autoload ID code
3531 (declare-function org-id-store-link "org-id")
3532 (declare-function org-id-locations-load "org-id")
3533 (declare-function org-id-locations-save "org-id")
3534 (defvar org-id-track-globally)
3535 (org-autoload "org-id"
3536 '(org-id-get-create org-id-new org-id-copy org-id-get
3537 org-id-get-with-outline-path-completion
3538 org-id-get-with-outline-drilling
3539 org-id-goto org-id-find org-id-store-link))
3541 ;; Autoload Plotting Code
3543 (org-autoload "org-plot"
3544 '(org-plot/gnuplot))
3546 ;;; Variables for pre-computed regular expressions, all buffer local
3548 (defvar org-drawer-regexp nil
3549 "Matches first line of a hidden block.")
3550 (make-variable-buffer-local 'org-drawer-regexp)
3551 (defvar org-todo-regexp nil
3552 "Matches any of the TODO state keywords.")
3553 (make-variable-buffer-local 'org-todo-regexp)
3554 (defvar org-not-done-regexp nil
3555 "Matches any of the TODO state keywords except the last one.")
3556 (make-variable-buffer-local 'org-not-done-regexp)
3557 (defvar org-not-done-heading-regexp nil
3558 "Matches a TODO headline that is not done.")
3559 (make-variable-buffer-local 'org-not-done-regexp)
3560 (defvar org-todo-line-regexp nil
3561 "Matches a headline and puts TODO state into group 2 if present.")
3562 (make-variable-buffer-local 'org-todo-line-regexp)
3563 (defvar org-complex-heading-regexp nil
3564 "Matches a headline and puts everything into groups:
3565 group 1: the stars
3566 group 2: The todo keyword, maybe
3567 group 3: Priority cookie
3568 group 4: True headline
3569 group 5: Tags")
3570 (make-variable-buffer-local 'org-complex-heading-regexp)
3571 (defvar org-complex-heading-regexp-format nil)
3572 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3573 (defvar org-todo-line-tags-regexp nil
3574 "Matches a headline and puts TODO state into group 2 if present.
3575 Also put tags into group 4 if tags are present.")
3576 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3577 (defvar org-nl-done-regexp nil
3578 "Matches newline followed by a headline with the DONE keyword.")
3579 (make-variable-buffer-local 'org-nl-done-regexp)
3580 (defvar org-looking-at-done-regexp nil
3581 "Matches the DONE keyword a point.")
3582 (make-variable-buffer-local 'org-looking-at-done-regexp)
3583 (defvar org-ds-keyword-length 12
3584 "Maximum length of the Deadline and SCHEDULED keywords.")
3585 (make-variable-buffer-local 'org-ds-keyword-length)
3586 (defvar org-deadline-regexp nil
3587 "Matches the DEADLINE keyword.")
3588 (make-variable-buffer-local 'org-deadline-regexp)
3589 (defvar org-deadline-time-regexp nil
3590 "Matches the DEADLINE keyword together with a time stamp.")
3591 (make-variable-buffer-local 'org-deadline-time-regexp)
3592 (defvar org-deadline-line-regexp nil
3593 "Matches the DEADLINE keyword and the rest of the line.")
3594 (make-variable-buffer-local 'org-deadline-line-regexp)
3595 (defvar org-scheduled-regexp nil
3596 "Matches the SCHEDULED keyword.")
3597 (make-variable-buffer-local 'org-scheduled-regexp)
3598 (defvar org-scheduled-time-regexp nil
3599 "Matches the SCHEDULED keyword together with a time stamp.")
3600 (make-variable-buffer-local 'org-scheduled-time-regexp)
3601 (defvar org-closed-time-regexp nil
3602 "Matches the CLOSED keyword together with a time stamp.")
3603 (make-variable-buffer-local 'org-closed-time-regexp)
3605 (defvar org-keyword-time-regexp nil
3606 "Matches any of the 4 keywords, together with the time stamp.")
3607 (make-variable-buffer-local 'org-keyword-time-regexp)
3608 (defvar org-keyword-time-not-clock-regexp nil
3609 "Matches any of the 3 keywords, together with the time stamp.")
3610 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3611 (defvar org-maybe-keyword-time-regexp nil
3612 "Matches a timestamp, possibly preceeded by a keyword.")
3613 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3614 (defvar org-planning-or-clock-line-re nil
3615 "Matches a line with planning or clock info.")
3616 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3618 (defconst org-plain-time-of-day-regexp
3619 (concat
3620 "\\(\\<[012]?[0-9]"
3621 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3622 "\\(--?"
3623 "\\(\\<[012]?[0-9]"
3624 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3625 "\\)?")
3626 "Regular expression to match a plain time or time range.
3627 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3628 groups carry important information:
3629 0 the full match
3630 1 the first time, range or not
3631 8 the second time, if it is a range.")
3633 (defconst org-plain-time-extension-regexp
3634 (concat
3635 "\\(\\<[012]?[0-9]"
3636 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3637 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3638 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3639 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3640 groups carry important information:
3641 0 the full match
3642 7 hours of duration
3643 9 minutes of duration")
3645 (defconst org-stamp-time-of-day-regexp
3646 (concat
3647 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3648 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3649 "\\(--?"
3650 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3651 "Regular expression to match a timestamp time or time range.
3652 After a match, the following groups carry important information:
3653 0 the full match
3654 1 date plus weekday, for backreferencing to make sure both times on same day
3655 2 the first time, range or not
3656 4 the second time, if it is a range.")
3658 (defconst org-startup-options
3659 '(("fold" org-startup-folded t)
3660 ("overview" org-startup-folded t)
3661 ("nofold" org-startup-folded nil)
3662 ("showall" org-startup-folded nil)
3663 ("showeverything" org-startup-folded showeverything)
3664 ("content" org-startup-folded content)
3665 ("indent" org-startup-indented t)
3666 ("noindent" org-startup-indented nil)
3667 ("hidestars" org-hide-leading-stars t)
3668 ("showstars" org-hide-leading-stars nil)
3669 ("odd" org-odd-levels-only t)
3670 ("oddeven" org-odd-levels-only nil)
3671 ("align" org-startup-align-all-tables t)
3672 ("noalign" org-startup-align-all-tables nil)
3673 ("customtime" org-display-custom-times t)
3674 ("logdone" org-log-done time)
3675 ("lognotedone" org-log-done note)
3676 ("nologdone" org-log-done nil)
3677 ("lognoteclock-out" org-log-note-clock-out t)
3678 ("nolognoteclock-out" org-log-note-clock-out nil)
3679 ("logrepeat" org-log-repeat state)
3680 ("lognoterepeat" org-log-repeat note)
3681 ("nologrepeat" org-log-repeat nil)
3682 ("logreschedule" org-log-reschedule time)
3683 ("lognotereschedule" org-log-reschedule note)
3684 ("nologreschedule" org-log-reschedule nil)
3685 ("logredeadline" org-log-redeadline time)
3686 ("lognoteredeadline" org-log-redeadline note)
3687 ("nologredeadline" org-log-redeadline nil)
3688 ("fninline" org-footnote-define-inline t)
3689 ("nofninline" org-footnote-define-inline nil)
3690 ("fnlocal" org-footnote-section nil)
3691 ("fnauto" org-footnote-auto-label t)
3692 ("fnprompt" org-footnote-auto-label nil)
3693 ("fnconfirm" org-footnote-auto-label confirm)
3694 ("fnplain" org-footnote-auto-label plain)
3695 ("fnadjust" org-footnote-auto-adjust t)
3696 ("nofnadjust" org-footnote-auto-adjust nil)
3697 ("constcgs" constants-unit-system cgs)
3698 ("constSI" constants-unit-system SI)
3699 ("noptag" org-tag-persistent-alist nil)
3700 ("hideblocks" org-hide-block-startup t)
3701 ("nohideblocks" org-hide-block-startup nil))
3702 "Variable associated with STARTUP options for org-mode.
3703 Each element is a list of three items: The startup options as written
3704 in the #+STARTUP line, the corresponding variable, and the value to
3705 set this variable to if the option is found. An optional forth element PUSH
3706 means to push this value onto the list in the variable.")
3708 (defun org-set-regexps-and-options ()
3709 "Precompute regular expressions for current buffer."
3710 (when (org-mode-p)
3711 (org-set-local 'org-todo-kwd-alist nil)
3712 (org-set-local 'org-todo-key-alist nil)
3713 (org-set-local 'org-todo-key-trigger nil)
3714 (org-set-local 'org-todo-keywords-1 nil)
3715 (org-set-local 'org-done-keywords nil)
3716 (org-set-local 'org-todo-heads nil)
3717 (org-set-local 'org-todo-sets nil)
3718 (org-set-local 'org-todo-log-states nil)
3719 (org-set-local 'org-file-properties nil)
3720 (org-set-local 'org-file-tags nil)
3721 (let ((re (org-make-options-regexp
3722 '("CATEGORY" "TODO" "COLUMNS"
3723 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3724 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3725 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3726 (splitre "[ \t]+")
3727 kwds kws0 kwsa key log value cat arch tags const links hw dws
3728 tail sep kws1 prio props ftags drawers
3729 ext-setup-or-nil setup-contents (start 0))
3730 (save-excursion
3731 (save-restriction
3732 (widen)
3733 (goto-char (point-min))
3734 (while (or (and ext-setup-or-nil
3735 (string-match re ext-setup-or-nil start)
3736 (setq start (match-end 0)))
3737 (and (setq ext-setup-or-nil nil start 0)
3738 (re-search-forward re nil t)))
3739 (setq key (upcase (match-string 1 ext-setup-or-nil))
3740 value (org-match-string-no-properties 2 ext-setup-or-nil))
3741 (cond
3742 ((equal key "CATEGORY")
3743 (if (string-match "[ \t]+$" value)
3744 (setq value (replace-match "" t t value)))
3745 (setq cat value))
3746 ((member key '("SEQ_TODO" "TODO"))
3747 (push (cons 'sequence (org-split-string value splitre)) kwds))
3748 ((equal key "TYP_TODO")
3749 (push (cons 'type (org-split-string value splitre)) kwds))
3750 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3751 ;; general TODO-like setup
3752 (push (cons (intern (downcase (match-string 1 key)))
3753 (org-split-string value splitre)) kwds))
3754 ((equal key "TAGS")
3755 (setq tags (append tags (if tags '("\\n") nil)
3756 (org-split-string value splitre))))
3757 ((equal key "COLUMNS")
3758 (org-set-local 'org-columns-default-format value))
3759 ((equal key "LINK")
3760 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3761 (push (cons (match-string 1 value)
3762 (org-trim (match-string 2 value)))
3763 links)))
3764 ((equal key "PRIORITIES")
3765 (setq prio (org-split-string value " +")))
3766 ((equal key "PROPERTY")
3767 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3768 (push (cons (match-string 1 value) (match-string 2 value))
3769 props)))
3770 ((equal key "FILETAGS")
3771 (when (string-match "\\S-" value)
3772 (setq ftags
3773 (append
3774 ftags
3775 (apply 'append
3776 (mapcar (lambda (x) (org-split-string x ":"))
3777 (org-split-string value)))))))
3778 ((equal key "DRAWERS")
3779 (setq drawers (org-split-string value splitre)))
3780 ((equal key "CONSTANTS")
3781 (setq const (append const (org-split-string value splitre))))
3782 ((equal key "STARTUP")
3783 (let ((opts (org-split-string value splitre))
3784 l var val)
3785 (while (setq l (pop opts))
3786 (when (setq l (assoc l org-startup-options))
3787 (setq var (nth 1 l) val (nth 2 l))
3788 (if (not (nth 3 l))
3789 (set (make-local-variable var) val)
3790 (if (not (listp (symbol-value var)))
3791 (set (make-local-variable var) nil))
3792 (set (make-local-variable var) (symbol-value var))
3793 (add-to-list var val))))))
3794 ((equal key "ARCHIVE")
3795 (string-match " *$" value)
3796 (setq arch (replace-match "" t t value))
3797 (remove-text-properties 0 (length arch)
3798 '(face t fontified t) arch))
3799 ((equal key "SETUPFILE")
3800 (setq setup-contents (org-file-contents
3801 (expand-file-name
3802 (org-remove-double-quotes value))
3803 'noerror))
3804 (if (not ext-setup-or-nil)
3805 (setq ext-setup-or-nil setup-contents start 0)
3806 (setq ext-setup-or-nil
3807 (concat (substring ext-setup-or-nil 0 start)
3808 "\n" setup-contents "\n"
3809 (substring ext-setup-or-nil start)))))
3810 ))))
3811 (when cat
3812 (org-set-local 'org-category (intern cat))
3813 (push (cons "CATEGORY" cat) props))
3814 (when prio
3815 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3816 (setq prio (mapcar 'string-to-char prio))
3817 (org-set-local 'org-highest-priority (nth 0 prio))
3818 (org-set-local 'org-lowest-priority (nth 1 prio))
3819 (org-set-local 'org-default-priority (nth 2 prio)))
3820 (and props (org-set-local 'org-file-properties (nreverse props)))
3821 (and ftags (org-set-local 'org-file-tags
3822 (mapcar 'org-add-prop-inherited ftags)))
3823 (and drawers (org-set-local 'org-drawers drawers))
3824 (and arch (org-set-local 'org-archive-location arch))
3825 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3826 ;; Process the TODO keywords
3827 (unless kwds
3828 ;; Use the global values as if they had been given locally.
3829 (setq kwds (default-value 'org-todo-keywords))
3830 (if (stringp (car kwds))
3831 (setq kwds (list (cons org-todo-interpretation
3832 (default-value 'org-todo-keywords)))))
3833 (setq kwds (reverse kwds)))
3834 (setq kwds (nreverse kwds))
3835 (let (inter kws kw)
3836 (while (setq kws (pop kwds))
3837 (let ((kws (or
3838 (run-hook-with-args-until-success
3839 'org-todo-setup-filter-hook kws)
3840 kws)))
3841 (setq inter (pop kws) sep (member "|" kws)
3842 kws0 (delete "|" (copy-sequence kws))
3843 kwsa nil
3844 kws1 (mapcar
3845 (lambda (x)
3846 ;; 1 2
3847 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3848 (progn
3849 (setq kw (match-string 1 x)
3850 key (and (match-end 2) (match-string 2 x))
3851 log (org-extract-log-state-settings x))
3852 (push (cons kw (and key (string-to-char key))) kwsa)
3853 (and log (push log org-todo-log-states))
3855 (error "Invalid TODO keyword %s" x)))
3856 kws0)
3857 kwsa (if kwsa (append '((:startgroup))
3858 (nreverse kwsa)
3859 '((:endgroup))))
3860 hw (car kws1)
3861 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3862 tail (list inter hw (car dws) (org-last dws))))
3863 (add-to-list 'org-todo-heads hw 'append)
3864 (push kws1 org-todo-sets)
3865 (setq org-done-keywords (append org-done-keywords dws nil))
3866 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3867 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3868 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3869 (setq org-todo-sets (nreverse org-todo-sets)
3870 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3871 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3872 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3873 ;; Process the constants
3874 (when const
3875 (let (e cst)
3876 (while (setq e (pop const))
3877 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3878 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3879 (setq org-table-formula-constants-local cst)))
3881 ;; Process the tags.
3882 (when tags
3883 (let (e tgs)
3884 (while (setq e (pop tags))
3885 (cond
3886 ((equal e "{") (push '(:startgroup) tgs))
3887 ((equal e "}") (push '(:endgroup) tgs))
3888 ((equal e "\\n") (push '(:newline) tgs))
3889 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3890 (push (cons (match-string 1 e)
3891 (string-to-char (match-string 2 e)))
3892 tgs))
3893 (t (push (list e) tgs))))
3894 (org-set-local 'org-tag-alist nil)
3895 (while (setq e (pop tgs))
3896 (or (and (stringp (car e))
3897 (assoc (car e) org-tag-alist))
3898 (push e org-tag-alist)))))
3900 ;; Compute the regular expressions and other local variables
3901 (if (not org-done-keywords)
3902 (setq org-done-keywords (and org-todo-keywords-1
3903 (list (org-last org-todo-keywords-1)))))
3904 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3905 (length org-scheduled-string)
3906 (length org-clock-string)
3907 (length org-closed-string)))
3908 org-drawer-regexp
3909 (concat "^[ \t]*:\\("
3910 (mapconcat 'regexp-quote org-drawers "\\|")
3911 "\\):[ \t]*$")
3912 org-not-done-keywords
3913 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3914 org-todo-regexp
3915 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3916 "\\|") "\\)\\>")
3917 org-not-done-regexp
3918 (concat "\\<\\("
3919 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3920 "\\)\\>")
3921 org-not-done-heading-regexp
3922 (concat "^\\(\\*+\\)[ \t]+\\("
3923 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3924 "\\)\\>")
3925 org-todo-line-regexp
3926 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3927 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3928 "\\)\\>\\)?[ \t]*\\(.*\\)")
3929 org-complex-heading-regexp
3930 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3931 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3932 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3933 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3934 org-complex-heading-regexp-format
3935 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3936 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3937 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
3938 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3939 org-nl-done-regexp
3940 (concat "\n\\*+[ \t]+"
3941 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3942 "\\)" "\\>")
3943 org-todo-line-tags-regexp
3944 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3945 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3946 (org-re
3947 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3948 org-looking-at-done-regexp
3949 (concat "^" "\\(?:"
3950 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3951 "\\>")
3952 org-deadline-regexp (concat "\\<" org-deadline-string)
3953 org-deadline-time-regexp
3954 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3955 org-deadline-line-regexp
3956 (concat "\\<\\(" org-deadline-string "\\).*")
3957 org-scheduled-regexp
3958 (concat "\\<" org-scheduled-string)
3959 org-scheduled-time-regexp
3960 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3961 org-closed-time-regexp
3962 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3963 org-keyword-time-regexp
3964 (concat "\\<\\(" org-scheduled-string
3965 "\\|" org-deadline-string
3966 "\\|" org-closed-string
3967 "\\|" org-clock-string "\\)"
3968 " *[[<]\\([^]>]+\\)[]>]")
3969 org-keyword-time-not-clock-regexp
3970 (concat "\\<\\(" org-scheduled-string
3971 "\\|" org-deadline-string
3972 "\\|" org-closed-string
3973 "\\)"
3974 " *[[<]\\([^]>]+\\)[]>]")
3975 org-maybe-keyword-time-regexp
3976 (concat "\\(\\<\\(" org-scheduled-string
3977 "\\|" org-deadline-string
3978 "\\|" org-closed-string
3979 "\\|" org-clock-string "\\)\\)?"
3980 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3981 org-planning-or-clock-line-re
3982 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3983 "\\|" org-deadline-string
3984 "\\|" org-closed-string "\\|" org-clock-string
3985 "\\)\\>\\)")
3987 (org-compute-latex-and-specials-regexp)
3988 (org-set-font-lock-defaults))))
3990 (defun org-file-contents (file &optional noerror)
3991 "Return the contents of FILE, as a string."
3992 (if (or (not file)
3993 (not (file-readable-p file)))
3994 (if noerror
3995 (progn
3996 (message "Cannot read file %s" file)
3997 (ding) (sit-for 2)
3999 (error "Cannot read file %s" file))
4000 (with-temp-buffer
4001 (insert-file-contents file)
4002 (buffer-string))))
4004 (defun org-extract-log-state-settings (x)
4005 "Extract the log state setting from a TODO keyword string.
4006 This will extract info from a string like \"WAIT(w@/!)\"."
4007 (let (kw key log1 log2)
4008 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4009 (setq kw (match-string 1 x)
4010 key (and (match-end 2) (match-string 2 x))
4011 log1 (and (match-end 3) (match-string 3 x))
4012 log2 (and (match-end 4) (match-string 4 x)))
4013 (and (or log1 log2)
4014 (list kw
4015 (and log1 (if (equal log1 "!") 'time 'note))
4016 (and log2 (if (equal log2 "!") 'time 'note)))))))
4018 (defun org-remove-keyword-keys (list)
4019 "Remove a pair of parenthesis at the end of each string in LIST."
4020 (mapcar (lambda (x)
4021 (if (string-match "(.*)$" x)
4022 (substring x 0 (match-beginning 0))
4024 list))
4026 ;; FIXME: this could be done much better, using second characters etc.
4027 (defun org-assign-fast-keys (alist)
4028 "Assign fast keys to a keyword-key alist.
4029 Respect keys that are already there."
4030 (let (new e k c c1 c2 (char ?a))
4031 (while (setq e (pop alist))
4032 (cond
4033 ((equal e '(:startgroup)) (push e new))
4034 ((equal e '(:endgroup)) (push e new))
4035 ((equal e '(:newline)) (push e new))
4037 (setq k (car e) c2 nil)
4038 (if (cdr e)
4039 (setq c (cdr e))
4040 ;; automatically assign a character.
4041 (setq c1 (string-to-char
4042 (downcase (substring
4043 k (if (= (string-to-char k) ?@) 1 0)))))
4044 (if (or (rassoc c1 new) (rassoc c1 alist))
4045 (while (or (rassoc char new) (rassoc char alist))
4046 (setq char (1+ char)))
4047 (setq c2 c1))
4048 (setq c (or c2 char)))
4049 (push (cons k c) new))))
4050 (nreverse new)))
4052 ;;; Some variables used in various places
4054 (defvar org-window-configuration nil
4055 "Used in various places to store a window configuration.")
4056 (defvar org-selected-window nil
4057 "Used in various places to store a window configuration.")
4058 (defvar org-finish-function nil
4059 "Function to be called when `C-c C-c' is used.
4060 This is for getting out of special buffers like remember.")
4063 ;; FIXME: Occasionally check by commenting these, to make sure
4064 ;; no other functions uses these, forgetting to let-bind them.
4065 (defvar entry)
4066 (defvar last-state)
4067 (defvar date)
4069 ;; Defined somewhere in this file, but used before definition.
4070 (defvar org-html-entities)
4071 (defvar org-struct-menu)
4072 (defvar org-org-menu)
4073 (defvar org-tbl-menu)
4075 ;;;; Define the Org-mode
4077 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4078 (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."))
4081 ;; We use a before-change function to check if a table might need
4082 ;; an update.
4083 (defvar org-table-may-need-update t
4084 "Indicates that a table might need an update.
4085 This variable is set by `org-before-change-function'.
4086 `org-table-align' sets it back to nil.")
4087 (defun org-before-change-function (beg end)
4088 "Every change indicates that a table might need an update."
4089 (setq org-table-may-need-update t))
4090 (defvar org-mode-map)
4091 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4092 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4093 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4094 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4095 (defvar org-table-buffer-is-an nil)
4096 (defconst org-outline-regexp "\\*+ ")
4098 ;;;###autoload
4099 (define-derived-mode org-mode outline-mode "Org"
4100 "Outline-based notes management and organizer, alias
4101 \"Carsten's outline-mode for keeping track of everything.\"
4103 Org-mode develops organizational tasks around a NOTES file which
4104 contains information about projects as plain text. Org-mode is
4105 implemented on top of outline-mode, which is ideal to keep the content
4106 of large files well structured. It supports ToDo items, deadlines and
4107 time stamps, which magically appear in the diary listing of the Emacs
4108 calendar. Tables are easily created with a built-in table editor.
4109 Plain text URL-like links connect to websites, emails (VM), Usenet
4110 messages (Gnus), BBDB entries, and any files related to the project.
4111 For printing and sharing of notes, an Org-mode file (or a part of it)
4112 can be exported as a structured ASCII or HTML file.
4114 The following commands are available:
4116 \\{org-mode-map}"
4118 ;; Get rid of Outline menus, they are not needed
4119 ;; Need to do this here because define-derived-mode sets up
4120 ;; the keymap so late. Still, it is a waste to call this each time
4121 ;; we switch another buffer into org-mode.
4122 (if (featurep 'xemacs)
4123 (when (boundp 'outline-mode-menu-heading)
4124 ;; Assume this is Greg's port, it used easymenu
4125 (easy-menu-remove outline-mode-menu-heading)
4126 (easy-menu-remove outline-mode-menu-show)
4127 (easy-menu-remove outline-mode-menu-hide))
4128 (define-key org-mode-map [menu-bar headings] 'undefined)
4129 (define-key org-mode-map [menu-bar hide] 'undefined)
4130 (define-key org-mode-map [menu-bar show] 'undefined))
4132 (org-load-modules-maybe)
4133 (easy-menu-add org-org-menu)
4134 (easy-menu-add org-tbl-menu)
4135 (org-install-agenda-files-menu)
4136 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4137 (org-add-to-invisibility-spec '(org-cwidth))
4138 (org-add-to-invisibility-spec '(org-hide-block . t))
4139 (when (featurep 'xemacs)
4140 (org-set-local 'line-move-ignore-invisible t))
4141 (org-set-local 'outline-regexp org-outline-regexp)
4142 (org-set-local 'outline-level 'org-outline-level)
4143 (when (and org-ellipsis
4144 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4145 (fboundp 'make-glyph-code))
4146 (unless org-display-table
4147 (setq org-display-table (make-display-table)))
4148 (set-display-table-slot
4149 org-display-table 4
4150 (vconcat (mapcar
4151 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4152 org-ellipsis)))
4153 (if (stringp org-ellipsis) org-ellipsis "..."))))
4154 (setq buffer-display-table org-display-table))
4155 (org-set-regexps-and-options)
4156 (when (and org-tag-faces (not org-tags-special-faces-re))
4157 ;; tag faces set outside customize.... force initialization.
4158 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4159 ;; Calc embedded
4160 (org-set-local 'calc-embedded-open-mode "# ")
4161 (modify-syntax-entry ?# "<")
4162 (modify-syntax-entry ?@ "w")
4163 (if org-startup-truncated (setq truncate-lines t))
4164 (org-set-local 'font-lock-unfontify-region-function
4165 'org-unfontify-region)
4166 ;; Activate before-change-function
4167 (org-set-local 'org-table-may-need-update t)
4168 (org-add-hook 'before-change-functions 'org-before-change-function nil
4169 'local)
4170 ;; Check for running clock before killing a buffer
4171 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4172 ;; Paragraphs and auto-filling
4173 (org-set-autofill-regexps)
4174 (setq indent-line-function 'org-indent-line-function)
4175 (org-update-radio-target-regexp)
4176 ;; Make sure dependence stuff works reliably, even for users who set it
4177 ;; too late :-(
4178 (if org-enforce-todo-dependencies
4179 (add-hook 'org-blocker-hook
4180 'org-block-todo-from-children-or-siblings-or-parent)
4181 (remove-hook 'org-blocker-hook
4182 'org-block-todo-from-children-or-siblings-or-parent))
4183 (if org-enforce-todo-checkbox-dependencies
4184 (add-hook 'org-blocker-hook
4185 'org-block-todo-from-checkboxes)
4186 (remove-hook 'org-blocker-hook
4187 'org-block-todo-from-checkboxes))
4189 ;; Comment characters
4190 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4191 (org-set-local 'comment-padding " ")
4193 ;; Align options lines
4194 (org-set-local
4195 'align-mode-rules-list
4196 '((org-in-buffer-settings
4197 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4198 (modes . '(org-mode)))))
4200 ;; Imenu
4201 (org-set-local 'imenu-create-index-function
4202 'org-imenu-get-tree)
4204 ;; Make isearch reveal context
4205 (if (or (featurep 'xemacs)
4206 (not (boundp 'outline-isearch-open-invisible-function)))
4207 ;; Emacs 21 and XEmacs make use of the hook
4208 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4209 ;; Emacs 22 deals with this through a special variable
4210 (org-set-local 'outline-isearch-open-invisible-function
4211 (lambda (&rest ignore) (org-show-context 'isearch))))
4213 ;; If empty file that did not turn on org-mode automatically, make it to.
4214 (if (and org-insert-mode-line-in-empty-file
4215 (interactive-p)
4216 (= (point-min) (point-max)))
4217 (insert "# -*- mode: org -*-\n\n"))
4219 (unless org-inhibit-startup
4220 (when org-startup-align-all-tables
4221 (let ((bmp (buffer-modified-p)))
4222 (org-table-map-tables 'org-table-align)
4223 (set-buffer-modified-p bmp)))
4224 (when org-startup-indented
4225 (require 'org-indent)
4226 (org-indent-mode 1))
4227 (org-set-startup-visibility)))
4229 (when (fboundp 'abbrev-table-put)
4230 (abbrev-table-put org-mode-abbrev-table
4231 :parents (list text-mode-abbrev-table)))
4233 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4235 (defun org-current-time ()
4236 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4237 (if (> (car org-time-stamp-rounding-minutes) 1)
4238 (let ((r (car org-time-stamp-rounding-minutes))
4239 (time (decode-time)))
4240 (apply 'encode-time
4241 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4242 (nthcdr 2 time))))
4243 (current-time)))
4245 ;;;; Font-Lock stuff, including the activators
4247 (defvar org-mouse-map (make-sparse-keymap))
4248 (org-defkey org-mouse-map
4249 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4250 (org-defkey org-mouse-map
4251 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4252 (when org-mouse-1-follows-link
4253 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4254 (when org-tab-follows-link
4255 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4256 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4258 (require 'font-lock)
4260 (defconst org-non-link-chars "]\t\n\r<>")
4261 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4262 "shell" "elisp"))
4263 (defvar org-link-types-re nil
4264 "Matches a link that has a url-like prefix like \"http:\"")
4265 (defvar org-link-re-with-space nil
4266 "Matches a link with spaces, optional angular brackets around it.")
4267 (defvar org-link-re-with-space2 nil
4268 "Matches a link with spaces, optional angular brackets around it.")
4269 (defvar org-link-re-with-space3 nil
4270 "Matches a link with spaces, only for internal part in bracket links.")
4271 (defvar org-angle-link-re nil
4272 "Matches link with angular brackets, spaces are allowed.")
4273 (defvar org-plain-link-re nil
4274 "Matches plain link, without spaces.")
4275 (defvar org-bracket-link-regexp nil
4276 "Matches a link in double brackets.")
4277 (defvar org-bracket-link-analytic-regexp nil
4278 "Regular expression used to analyze links.
4279 Here is what the match groups contain after a match:
4280 1: http:
4281 2: http
4282 3: path
4283 4: [desc]
4284 5: desc")
4285 (defvar org-bracket-link-analytic-regexp++ nil
4286 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4287 (defvar org-any-link-re nil
4288 "Regular expression matching any link.")
4290 (defun org-make-link-regexps ()
4291 "Update the link regular expressions.
4292 This should be called after the variable `org-link-types' has changed."
4293 (setq org-link-types-re
4294 (concat
4295 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4296 org-link-re-with-space
4297 (concat
4298 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4299 "\\([^" org-non-link-chars " ]"
4300 "[^" org-non-link-chars "]*"
4301 "[^" org-non-link-chars " ]\\)>?")
4302 org-link-re-with-space2
4303 (concat
4304 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4305 "\\([^" org-non-link-chars " ]"
4306 "[^\t\n\r]*"
4307 "[^" org-non-link-chars " ]\\)>?")
4308 org-link-re-with-space3
4309 (concat
4310 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4311 "\\([^" org-non-link-chars " ]"
4312 "[^\t\n\r]*\\)")
4313 org-angle-link-re
4314 (concat
4315 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4316 "\\([^" org-non-link-chars " ]"
4317 "[^" org-non-link-chars "]*"
4318 "\\)>")
4319 org-plain-link-re
4320 (concat
4321 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4322 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4323 org-bracket-link-regexp
4324 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4325 org-bracket-link-analytic-regexp
4326 (concat
4327 "\\[\\["
4328 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4329 "\\([^]]+\\)"
4330 "\\]"
4331 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4332 "\\]")
4333 org-bracket-link-analytic-regexp++
4334 (concat
4335 "\\[\\["
4336 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4337 "\\([^]]+\\)"
4338 "\\]"
4339 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4340 "\\]")
4341 org-any-link-re
4342 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4343 org-angle-link-re "\\)\\|\\("
4344 org-plain-link-re "\\)")))
4346 (org-make-link-regexps)
4348 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4349 "Regular expression for fast time stamp matching.")
4350 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4351 "Regular expression for fast time stamp matching.")
4352 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4353 "Regular expression matching time strings for analysis.
4354 This one does not require the space after the date, so it can be used
4355 on a string that terminates immediately after the date.")
4356 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4357 "Regular expression matching time strings for analysis.")
4358 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4359 "Regular expression matching time stamps, with groups.")
4360 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4361 "Regular expression matching time stamps (also [..]), with groups.")
4362 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4363 "Regular expression matching a time stamp range.")
4364 (defconst org-tr-regexp-both
4365 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4366 "Regular expression matching a time stamp range.")
4367 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4368 org-ts-regexp "\\)?")
4369 "Regular expression matching a time stamp or time stamp range.")
4370 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4371 org-ts-regexp-both "\\)?")
4372 "Regular expression matching a time stamp or time stamp range.
4373 The time stamps may be either active or inactive.")
4375 (defvar org-emph-face nil)
4377 (defun org-do-emphasis-faces (limit)
4378 "Run through the buffer and add overlays to links."
4379 (let (rtn a)
4380 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4381 (if (not (= (char-after (match-beginning 3))
4382 (char-after (match-beginning 4))))
4383 (progn
4384 (setq rtn t)
4385 (setq a (assoc (match-string 3) org-emphasis-alist))
4386 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4387 'face
4388 (nth 1 a))
4389 (and (nth 4 a)
4390 (org-remove-flyspell-overlays-in
4391 (match-beginning 0) (match-end 0)))
4392 (add-text-properties (match-beginning 2) (match-end 2)
4393 '(font-lock-multiline t))
4394 (when org-hide-emphasis-markers
4395 (add-text-properties (match-end 4) (match-beginning 5)
4396 '(invisible org-link))
4397 (add-text-properties (match-beginning 3) (match-end 3)
4398 '(invisible org-link)))))
4399 (backward-char 1))
4400 rtn))
4402 (defun org-emphasize (&optional char)
4403 "Insert or change an emphasis, i.e. a font like bold or italic.
4404 If there is an active region, change that region to a new emphasis.
4405 If there is no region, just insert the marker characters and position
4406 the cursor between them.
4407 CHAR should be either the marker character, or the first character of the
4408 HTML tag associated with that emphasis. If CHAR is a space, the means
4409 to remove the emphasis of the selected region.
4410 If char is not given (for example in an interactive call) it
4411 will be prompted for."
4412 (interactive)
4413 (let ((eal org-emphasis-alist) e det
4414 (erc org-emphasis-regexp-components)
4415 (prompt "")
4416 (string "") beg end move tag c s)
4417 (if (org-region-active-p)
4418 (setq beg (region-beginning) end (region-end)
4419 string (buffer-substring beg end))
4420 (setq move t))
4422 (while (setq e (pop eal))
4423 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4424 c (aref tag 0))
4425 (push (cons c (string-to-char (car e))) det)
4426 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4427 (substring tag 1)))))
4428 (setq det (nreverse det))
4429 (unless char
4430 (message "%s" (concat "Emphasis marker or tag:" prompt))
4431 (setq char (read-char-exclusive)))
4432 (setq char (or (cdr (assoc char det)) char))
4433 (if (equal char ?\ )
4434 (setq s "" move nil)
4435 (unless (assoc (char-to-string char) org-emphasis-alist)
4436 (error "No such emphasis marker: \"%c\"" char))
4437 (setq s (char-to-string char)))
4438 (while (and (> (length string) 1)
4439 (equal (substring string 0 1) (substring string -1))
4440 (assoc (substring string 0 1) org-emphasis-alist))
4441 (setq string (substring string 1 -1)))
4442 (setq string (concat s string s))
4443 (if beg (delete-region beg end))
4444 (unless (or (bolp)
4445 (string-match (concat "[" (nth 0 erc) "\n]")
4446 (char-to-string (char-before (point)))))
4447 (insert " "))
4448 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4449 (char-to-string (char-after (point))))
4450 (insert " ") (backward-char 1))
4451 (insert string)
4452 (and move (backward-char 1))))
4454 (defconst org-nonsticky-props
4455 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4457 (defsubst org-rear-nonsticky-at (pos)
4458 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4460 (defun org-activate-plain-links (limit)
4461 "Run through the buffer and add overlays to links."
4462 (catch 'exit
4463 (let (f)
4464 (if (re-search-forward org-plain-link-re limit t)
4465 (progn
4466 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4467 (setq f (get-text-property (match-beginning 0) 'face))
4468 (if (or (eq f 'org-tag)
4469 (and (listp f) (memq 'org-tag f)))
4471 (add-text-properties (match-beginning 0) (match-end 0)
4472 (list 'mouse-face 'highlight
4473 'keymap org-mouse-map))
4474 (org-rear-nonsticky-at (match-end 0)))
4475 t)))))
4477 (defun org-activate-code (limit)
4478 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4479 (progn
4480 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4481 (remove-text-properties (match-beginning 0) (match-end 0)
4482 '(display t invisible t intangible t))
4483 t)))
4485 (defun org-fontify-meta-lines-and-blocks (limit)
4486 "Fontify #+ lines and blocks, in the correct ways."
4487 (let ((case-fold-search t))
4488 (if (re-search-forward
4489 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4490 limit t)
4491 (let ((beg (match-beginning 0))
4492 (beg1 (line-beginning-position 2))
4493 (dc1 (downcase (match-string 2)))
4494 (dc3 (downcase (match-string 3)))
4495 end end1 quoting)
4496 (cond
4497 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4498 ;; a single line of backend-specific content
4499 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4500 (remove-text-properties (match-beginning 0) (match-end 0)
4501 '(display t invisible t intangible t))
4502 (add-text-properties (match-beginning 1) (match-end 3)
4503 '(font-lock-fontified t face org-meta-line))
4504 (add-text-properties (match-beginning 6) (match-end 6)
4505 '(font-lock-fontified t face org-block))
4507 ((and (match-end 4) (equal dc3 "begin"))
4508 ;; Truely a block
4509 (setq quoting (member (downcase (match-string 5))
4510 org-protecting-blocks))
4511 (when (re-search-forward
4512 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4513 nil t) ;; on purpose, we look further than LIMIT
4514 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4515 (when quoting
4516 (remove-text-properties beg end
4517 '(display t invisible t intangible t)))
4518 (add-text-properties
4519 beg end
4520 '(font-lock-fontified t font-lock-multiline t))
4521 (add-text-properties beg beg1 '(face org-meta-line))
4522 (add-text-properties end1 end '(face org-meta-line))
4523 (when quoting
4524 (add-text-properties beg1 end1 '(face org-block)))
4526 ((not (member (char-after beg) '(?\ ?\t)))
4527 ;; just any other in-buffer setting, but not indented
4528 (add-text-properties
4529 beg (match-end 0)
4530 '(font-lock-fontified t face org-meta-line))
4532 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4533 "orgtbl:" "tblfm:" "tblname:"))
4534 (and (match-end 4) (equal dc3 "attr")))
4535 (add-text-properties
4536 beg (match-end 0)
4537 '(font-lock-fontified t face org-meta-line))
4539 ((member dc3 '(" " ""))
4540 (add-text-properties
4541 beg (match-end 0)
4542 '(font-lock-fontified t face font-lock-comment-face)))
4543 (t nil))))))
4545 (defun org-activate-angle-links (limit)
4546 "Run through the buffer and add overlays to links."
4547 (if (re-search-forward org-angle-link-re limit t)
4548 (progn
4549 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4550 (add-text-properties (match-beginning 0) (match-end 0)
4551 (list 'mouse-face 'highlight
4552 'keymap org-mouse-map))
4553 (org-rear-nonsticky-at (match-end 0))
4554 t)))
4556 (defun org-activate-footnote-links (limit)
4557 "Run through the buffer and add overlays to links."
4558 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4559 limit t)
4560 (progn
4561 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4562 (add-text-properties (match-beginning 2) (match-end 2)
4563 (list 'mouse-face 'highlight
4564 'keymap org-mouse-map
4565 'help-echo
4566 (if (= (point-at-bol) (match-beginning 2))
4567 "Footnote definition"
4568 "Footnote reference")
4570 (org-rear-nonsticky-at (match-end 2))
4571 t)))
4573 (defun org-activate-bracket-links (limit)
4574 "Run through the buffer and add overlays to bracketed links."
4575 (if (re-search-forward org-bracket-link-regexp limit t)
4576 (let* ((help (concat "LINK: "
4577 (org-match-string-no-properties 1)))
4578 ;; FIXME: above we should remove the escapes.
4579 ;; but that requires another match, protecting match data,
4580 ;; a lot of overhead for font-lock.
4581 (ip (org-maybe-intangible
4582 (list 'invisible 'org-link
4583 'keymap org-mouse-map 'mouse-face 'highlight
4584 'font-lock-multiline t 'help-echo help)))
4585 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4586 'font-lock-multiline t 'help-echo help)))
4587 ;; We need to remove the invisible property here. Table narrowing
4588 ;; may have made some of this invisible.
4589 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4590 (remove-text-properties (match-beginning 0) (match-end 0)
4591 '(invisible nil))
4592 (if (match-end 3)
4593 (progn
4594 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4595 (org-rear-nonsticky-at (match-beginning 3))
4596 (add-text-properties (match-beginning 3) (match-end 3) vp)
4597 (org-rear-nonsticky-at (match-end 3))
4598 (add-text-properties (match-end 3) (match-end 0) ip)
4599 (org-rear-nonsticky-at (match-end 0)))
4600 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4601 (org-rear-nonsticky-at (match-beginning 1))
4602 (add-text-properties (match-beginning 1) (match-end 1) vp)
4603 (org-rear-nonsticky-at (match-end 1))
4604 (add-text-properties (match-end 1) (match-end 0) ip)
4605 (org-rear-nonsticky-at (match-end 0)))
4606 t)))
4608 (defun org-activate-dates (limit)
4609 "Run through the buffer and add overlays to dates."
4610 (if (re-search-forward org-tsr-regexp-both limit t)
4611 (progn
4612 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4613 (add-text-properties (match-beginning 0) (match-end 0)
4614 (list 'mouse-face 'highlight
4615 'keymap org-mouse-map))
4616 (org-rear-nonsticky-at (match-end 0))
4617 (when org-display-custom-times
4618 (if (match-end 3)
4619 (org-display-custom-time (match-beginning 3) (match-end 3)))
4620 (org-display-custom-time (match-beginning 1) (match-end 1)))
4621 t)))
4623 (defvar org-target-link-regexp nil
4624 "Regular expression matching radio targets in plain text.")
4625 (make-variable-buffer-local 'org-target-link-regexp)
4626 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4627 "Regular expression matching a link target.")
4628 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4629 "Regular expression matching a radio target.")
4630 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4631 "Regular expression matching any target.")
4633 (defun org-activate-target-links (limit)
4634 "Run through the buffer and add overlays to target matches."
4635 (when org-target-link-regexp
4636 (let ((case-fold-search t))
4637 (if (re-search-forward org-target-link-regexp limit t)
4638 (progn
4639 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4640 (add-text-properties (match-beginning 0) (match-end 0)
4641 (list 'mouse-face 'highlight
4642 'keymap org-mouse-map
4643 'help-echo "Radio target link"
4644 'org-linked-text t))
4645 (org-rear-nonsticky-at (match-end 0))
4646 t)))))
4648 (defun org-update-radio-target-regexp ()
4649 "Find all radio targets in this file and update the regular expression."
4650 (interactive)
4651 (when (memq 'radio org-activate-links)
4652 (setq org-target-link-regexp
4653 (org-make-target-link-regexp (org-all-targets 'radio)))
4654 (org-restart-font-lock)))
4656 (defun org-hide-wide-columns (limit)
4657 (let (s e)
4658 (setq s (text-property-any (point) (or limit (point-max))
4659 'org-cwidth t))
4660 (when s
4661 (setq e (next-single-property-change s 'org-cwidth))
4662 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4663 (goto-char e)
4664 t)))
4666 (defvar org-latex-and-specials-regexp nil
4667 "Regular expression for highlighting export special stuff.")
4668 (defvar org-match-substring-regexp)
4669 (defvar org-match-substring-with-braces-regexp)
4671 ;; This should be with the exporter code, but we also use if for font-locking
4672 (defconst org-export-html-special-string-regexps
4673 '(("\\\\-" . "&shy;")
4674 ("---\\([^-]\\)" . "&mdash;\\1")
4675 ("--\\([^-]\\)" . "&ndash;\\1")
4676 ("\\.\\.\\." . "&hellip;"))
4677 "Regular expressions for special string conversion.")
4680 (defun org-compute-latex-and-specials-regexp ()
4681 "Compute regular expression for stuff treated specially by exporters."
4682 (if (not org-highlight-latex-fragments-and-specials)
4683 (org-set-local 'org-latex-and-specials-regexp nil)
4684 (require 'org-exp)
4685 (let*
4686 ((matchers (plist-get org-format-latex-options :matchers))
4687 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4688 org-latex-regexps)))
4689 (options (org-combine-plists (org-default-export-plist)
4690 (org-infile-export-plist)))
4691 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4692 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4693 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4694 (org-export-html-expand (plist-get options :expand-quoted-html))
4695 (org-export-with-special-strings (plist-get options :special-strings))
4696 (re-sub
4697 (cond
4698 ((equal org-export-with-sub-superscripts '{})
4699 (list org-match-substring-with-braces-regexp))
4700 (org-export-with-sub-superscripts
4701 (list org-match-substring-regexp))
4702 (t nil)))
4703 (re-latex
4704 (if org-export-with-LaTeX-fragments
4705 (mapcar (lambda (x) (nth 1 x)) latexs)))
4706 (re-macros
4707 (if org-export-with-TeX-macros
4708 (list (concat "\\\\"
4709 (regexp-opt
4710 (append (mapcar 'car org-html-entities)
4711 (if (boundp 'org-latex-entities)
4712 (mapcar (lambda (x)
4713 (or (car-safe x) x))
4714 org-latex-entities)
4715 nil))
4716 'words))) ; FIXME
4718 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4719 (re-special (if org-export-with-special-strings
4720 (mapcar (lambda (x) (car x))
4721 org-export-html-special-string-regexps)))
4722 (re-rest
4723 (delq nil
4724 (list
4725 (if org-export-html-expand "@<[^>\n]+>")
4726 ))))
4727 (org-set-local
4728 'org-latex-and-specials-regexp
4729 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4730 re-rest) "\\|")))))
4732 (defun org-do-latex-and-special-faces (limit)
4733 "Run through the buffer and add overlays to links."
4734 (when org-latex-and-specials-regexp
4735 (let (rtn d)
4736 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4737 limit t))
4738 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4739 'face))
4740 '(org-code org-verbatim underline)))
4741 (progn
4742 (setq rtn t
4743 d (cond ((member (char-after (1+ (match-beginning 0)))
4744 '(?_ ?^)) 1)
4745 (t 0)))
4746 (font-lock-prepend-text-property
4747 (+ d (match-beginning 0)) (match-end 0)
4748 'face 'org-latex-and-export-specials)
4749 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4750 '(font-lock-multiline t)))))
4751 rtn)))
4753 (defun org-restart-font-lock ()
4754 "Restart font-lock-mode, to force refontification."
4755 (when (and (boundp 'font-lock-mode) font-lock-mode)
4756 (font-lock-mode -1)
4757 (font-lock-mode 1)))
4759 (defun org-all-targets (&optional radio)
4760 "Return a list of all targets in this file.
4761 With optional argument RADIO, only find radio targets."
4762 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4763 rtn)
4764 (save-excursion
4765 (goto-char (point-min))
4766 (while (re-search-forward re nil t)
4767 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4768 rtn)))
4770 (defun org-make-target-link-regexp (targets)
4771 "Make regular expression matching all strings in TARGETS.
4772 The regular expression finds the targets also if there is a line break
4773 between words."
4774 (and targets
4775 (concat
4776 "\\<\\("
4777 (mapconcat
4778 (lambda (x)
4779 (while (string-match " +" x)
4780 (setq x (replace-match "\\s-+" t t x)))
4782 targets
4783 "\\|")
4784 "\\)\\>")))
4786 (defun org-activate-tags (limit)
4787 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4788 (progn
4789 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4790 (add-text-properties (match-beginning 1) (match-end 1)
4791 (list 'mouse-face 'highlight
4792 'keymap org-mouse-map))
4793 (org-rear-nonsticky-at (match-end 1))
4794 t)))
4796 (defun org-outline-level ()
4797 "Compute the outline level of the heading at point.
4798 This function assumes that the cursor is at the beginning of a line matched
4799 by outline-regexp. Otherwise it returns garbage.
4800 If this is called at a normal headline, the level is the number of stars.
4801 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4802 For plain list items, if they are matched by `outline-regexp', this returns
4803 1000 plus the line indentation."
4804 (save-excursion
4805 (looking-at outline-regexp)
4806 (if (match-beginning 1)
4807 (+ (org-get-string-indentation (match-string 1)) 1000)
4808 (1- (- (match-end 0) (match-beginning 0))))))
4810 (defvar org-font-lock-keywords nil)
4812 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4813 "Regular expression matching a property line.")
4815 (defvar org-font-lock-hook nil
4816 "Functions to be called for special font lock stuff.")
4818 (defun org-font-lock-hook (limit)
4819 (run-hook-with-args 'org-font-lock-hook limit))
4821 (defun org-set-font-lock-defaults ()
4822 (let* ((em org-fontify-emphasized-text)
4823 (lk org-activate-links)
4824 (org-font-lock-extra-keywords
4825 (list
4826 ;; Call the hook
4827 '(org-font-lock-hook)
4828 ;; Headlines
4829 `(,(if org-fontify-whole-heading-line
4830 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4831 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4832 (1 (org-get-level-face 1))
4833 (2 (org-get-level-face 2))
4834 (3 (org-get-level-face 3)))
4835 ;; Table lines
4836 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4837 (1 'org-table t))
4838 ;; Table internals
4839 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4840 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4841 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4842 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4843 ;; Drawers
4844 (list org-drawer-regexp '(0 'org-special-keyword t))
4845 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4846 ;; Properties
4847 (list org-property-re
4848 '(1 'org-special-keyword t)
4849 '(3 'org-property-value t))
4850 ;; Links
4851 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4852 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4853 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4854 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4855 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4856 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4857 (if (memq 'footnote lk) '(org-activate-footnote-links
4858 (2 'org-footnote t)))
4859 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4860 '(org-hide-wide-columns (0 nil append))
4861 ;; TODO lines
4862 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4863 '(1 (org-get-todo-face 1) t))
4864 ;; DONE
4865 (if org-fontify-done-headline
4866 (list (concat "^[*]+ +\\<\\("
4867 (mapconcat 'regexp-quote org-done-keywords "\\|")
4868 "\\)\\(.*\\)")
4869 '(2 'org-headline-done t))
4870 nil)
4871 ;; Priorities
4872 '(org-font-lock-add-priority-faces)
4873 ;; Tags
4874 '(org-font-lock-add-tag-faces)
4875 ;; Special keywords
4876 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4877 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4878 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4879 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4880 ;; Emphasis
4881 (if em
4882 (if (featurep 'xemacs)
4883 '(org-do-emphasis-faces (0 nil append))
4884 '(org-do-emphasis-faces)))
4885 ;; Checkboxes
4886 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4887 2 'org-checkbox prepend)
4888 (if org-provide-checkbox-statistics
4889 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4890 (0 (org-get-checkbox-statistics-face) t)))
4891 ;; Description list items
4892 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4893 2 'bold prepend)
4894 ;; ARCHIVEd headings
4895 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4896 '(1 'org-archived prepend))
4897 ;; Specials
4898 '(org-do-latex-and-special-faces)
4899 ;; Code
4900 '(org-activate-code (1 'org-code t))
4901 ;; COMMENT
4902 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4903 "\\|" org-quote-string "\\)\\>")
4904 '(1 'org-special-keyword t))
4905 '("^#.*" (0 'font-lock-comment-face t))
4906 ;; Blocks and meta lines
4907 '(org-fontify-meta-lines-and-blocks)
4909 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4910 ;; Now set the full font-lock-keywords
4911 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4912 (org-set-local 'font-lock-defaults
4913 '(org-font-lock-keywords t nil nil backward-paragraph))
4914 (kill-local-variable 'font-lock-keywords) nil))
4916 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4917 "Fontify string S like in Org-mode"
4918 (with-temp-buffer
4919 (insert s)
4920 (let ((org-odd-levels-only odd-levels))
4921 (org-mode)
4922 (font-lock-fontify-buffer)
4923 (buffer-string))))
4925 (defvar org-m nil)
4926 (defvar org-l nil)
4927 (defvar org-f nil)
4928 (defun org-get-level-face (n)
4929 "Get the right face for match N in font-lock matching of headlines."
4930 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4931 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4932 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4933 (cond
4934 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4935 ((eq n 2) org-f)
4936 (t (if org-level-color-stars-only nil org-f))))
4938 (defun org-get-todo-face (kwd)
4939 "Get the right face for a TODO keyword KWD.
4940 If KWD is a number, get the corresponding match group."
4941 (if (numberp kwd) (setq kwd (match-string kwd)))
4942 (or (cdr (assoc kwd org-todo-keyword-faces))
4943 (and (member kwd org-done-keywords) 'org-done)
4944 'org-todo))
4946 (defun org-font-lock-add-tag-faces (limit)
4947 "Add the special tag faces."
4948 (when (and org-tag-faces org-tags-special-faces-re)
4949 (while (re-search-forward org-tags-special-faces-re limit t)
4950 (add-text-properties (match-beginning 1) (match-end 1)
4951 (list 'face (org-get-tag-face 1)
4952 'font-lock-fontified t))
4953 (backward-char 1))))
4955 (defun org-font-lock-add-priority-faces (limit)
4956 "Add the special priority faces."
4957 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4958 (add-text-properties
4959 (match-beginning 0) (match-end 0)
4960 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4961 org-priority-faces))
4962 'org-special-keyword)
4963 'font-lock-fontified t))))
4965 (defun org-get-tag-face (kwd)
4966 "Get the right face for a TODO keyword KWD.
4967 If KWD is a number, get the corresponding match group."
4968 (if (numberp kwd) (setq kwd (match-string kwd)))
4969 (or (cdr (assoc kwd org-tag-faces))
4970 'org-tag))
4972 (defun org-unfontify-region (beg end &optional maybe_loudly)
4973 "Remove fontification and activation overlays from links."
4974 (font-lock-default-unfontify-region beg end)
4975 (let* ((buffer-undo-list t)
4976 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4977 (inhibit-modification-hooks t)
4978 deactivate-mark buffer-file-name buffer-file-truename)
4979 (remove-text-properties
4980 beg end
4981 (if org-indent-mode
4982 ;; also remove line-prefix and wrap-prefix properties
4983 '(mouse-face t keymap t org-linked-text t
4984 invisible t intangible t
4985 line-prefix t wrap-prefix t
4986 org-no-flyspell t)
4987 '(mouse-face t keymap t org-linked-text t
4988 invisible t intangible t
4989 org-no-flyspell t)))))
4991 ;;;; Visibility cycling, including org-goto and indirect buffer
4993 ;;; Cycling
4995 (defvar org-cycle-global-status nil)
4996 (make-variable-buffer-local 'org-cycle-global-status)
4997 (defvar org-cycle-subtree-status nil)
4998 (make-variable-buffer-local 'org-cycle-subtree-status)
5000 ;;;###autoload
5002 (defvar org-inlinetask-min-level)
5004 (defun org-cycle (&optional arg)
5005 "TAB-action and visibility cycling for Org-mode.
5007 This is the command invoked in Org-mode by the TAB key. Its main purpose
5008 is outine visibility cycling, but it also invokes other actions
5009 in special contexts.
5011 - When this function is called with a prefix argument, rotate the entire
5012 buffer through 3 states (global cycling)
5013 1. OVERVIEW: Show only top-level headlines.
5014 2. CONTENTS: Show all headlines of all levels, but no body text.
5015 3. SHOW ALL: Show everything.
5016 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5017 determined by the variable `org-startup-folded', and by any VISIBILITY
5018 properties in the buffer.
5019 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5020 including any drawers.
5022 - When inside a table, re-align the table and move to the next field.
5024 - When point is at the beginning of a headline, rotate the subtree started
5025 by this line through 3 different states (local cycling)
5026 1. FOLDED: Only the main headline is shown.
5027 2. CHILDREN: The main headline and the direct children are shown.
5028 From this state, you can move to one of the children
5029 and zoom in further.
5030 3. SUBTREE: Show the entire subtree, including body text.
5031 If there is no subtree, switch directly from CHILDREN to FOLDED.
5033 - When there is a numeric prefix, go up to a heading with level ARG, do
5034 a `show-subtree' and return to the previous cursor position. If ARG
5035 is negative, go up that many levels.
5037 - When point is not at the beginning of a headline, execute the global
5038 binding for TAB, which is re-indenting the line. See the option
5039 `org-cycle-emulate-tab' for details.
5041 - Special case: if point is at the beginning of the buffer and there is
5042 no headline in line 1, this function will act as if called with prefix arg.
5043 But only if also the variable `org-cycle-global-at-bob' is t."
5044 (interactive "P")
5045 (org-load-modules-maybe)
5046 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5047 (and org-cycle-level-after-item/entry-creation
5048 (or (org-cycle-level)
5049 (org-cycle-item-indentation))))
5050 (let* ((limit-level
5051 (or org-cycle-max-level
5052 (and (boundp 'org-inlinetask-min-level)
5053 org-inlinetask-min-level
5054 (1- org-inlinetask-min-level))))
5055 (nstars (and limit-level
5056 (if org-odd-levels-only
5057 (and limit-level (1- (* limit-level 2)))
5058 limit-level)))
5059 (outline-regexp
5060 (cond
5061 ((not (org-mode-p)) outline-regexp)
5062 ((or (eq org-cycle-include-plain-lists 'integrate)
5063 (and org-cycle-include-plain-lists (org-at-item-p)))
5064 (concat "\\(?:\\*"
5065 (if nstars (format "\\{1,%d\\}" nstars) "+")
5066 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5067 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5068 (bob-special (and org-cycle-global-at-bob (bobp)
5069 (not (looking-at outline-regexp))))
5070 (org-cycle-hook
5071 (if bob-special
5072 (delq 'org-optimize-window-after-visibility-change
5073 (copy-sequence org-cycle-hook))
5074 org-cycle-hook))
5075 (pos (point)))
5077 (if (or bob-special (equal arg '(4)))
5078 ;; special case: use global cycling
5079 (setq arg t))
5081 (cond
5083 ((equal arg '(16))
5084 (org-set-startup-visibility)
5085 (message "Startup visibility, plus VISIBILITY properties"))
5087 ((equal arg '(64))
5088 (show-all)
5089 (message "Entire buffer visible, including drawers"))
5091 ((org-at-table-p 'any)
5092 ;; Enter the table or move to the next field in the table
5093 (or (org-table-recognize-table.el)
5094 (progn
5095 (if arg (org-table-edit-field t)
5096 (org-table-justify-field-maybe)
5097 (call-interactively 'org-table-next-field)))))
5099 ((run-hook-with-args-until-success
5100 'org-tab-after-check-for-table-hook))
5102 ((eq arg t) ;; Global cycling
5103 (org-cycle-internal-global))
5105 ((and org-drawers org-drawer-regexp
5106 (save-excursion
5107 (beginning-of-line 1)
5108 (looking-at org-drawer-regexp)))
5109 ;; Toggle block visibility
5110 (org-flag-drawer
5111 (not (get-char-property (match-end 0) 'invisible))))
5113 ((integerp arg)
5114 ;; Show-subtree, ARG levels up from here.
5115 (save-excursion
5116 (org-back-to-heading)
5117 (outline-up-heading (if (< arg 0) (- arg)
5118 (- (funcall outline-level) arg)))
5119 (org-show-subtree)))
5121 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5122 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5124 (org-cycle-internal-local))
5126 ;; TAB emulation and template completion
5127 (buffer-read-only (org-back-to-heading))
5129 ((run-hook-with-args-until-success
5130 'org-tab-after-check-for-cycling-hook))
5132 ((org-try-structure-completion))
5134 ((org-try-cdlatex-tab))
5136 ((run-hook-with-args-until-success
5137 'org-tab-before-tab-emulation-hook))
5139 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5140 (or (not (bolp))
5141 (not (looking-at outline-regexp))))
5142 (call-interactively (global-key-binding "\t")))
5144 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5145 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5146 (or (and (eq org-cycle-emulate-tab 'white)
5147 (= (match-end 0) (point-at-eol)))
5148 (and (eq org-cycle-emulate-tab 'whitestart)
5149 (>= (match-end 0) pos))))
5151 (eq org-cycle-emulate-tab t))
5152 (call-interactively (global-key-binding "\t")))
5154 (t (save-excursion
5155 (org-back-to-heading)
5156 (org-cycle)))))))
5158 (defun org-cycle-internal-global ()
5159 "Do the global cycling action."
5160 (cond
5161 ((and (eq last-command this-command)
5162 (eq org-cycle-global-status 'overview))
5163 ;; We just created the overview - now do table of contents
5164 ;; This can be slow in very large buffers, so indicate action
5165 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5166 (message "CONTENTS...")
5167 (org-content)
5168 (message "CONTENTS...done")
5169 (setq org-cycle-global-status 'contents)
5170 (run-hook-with-args 'org-cycle-hook 'contents))
5172 ((and (eq last-command this-command)
5173 (eq org-cycle-global-status 'contents))
5174 ;; We just showed the table of contents - now show everything
5175 (run-hook-with-args 'org-pre-cycle-hook 'all)
5176 (show-all)
5177 (message "SHOW ALL")
5178 (setq org-cycle-global-status 'all)
5179 (run-hook-with-args 'org-cycle-hook 'all))
5182 ;; Default action: go to overview
5183 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5184 (org-overview)
5185 (message "OVERVIEW")
5186 (setq org-cycle-global-status 'overview)
5187 (run-hook-with-args 'org-cycle-hook 'overview))))
5189 (defun org-cycle-internal-local ()
5190 "Do the local cycling action."
5191 (org-back-to-heading)
5192 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5193 ;; First, some boundaries
5194 (save-excursion
5195 (org-back-to-heading)
5196 (setq level (funcall outline-level))
5197 (save-excursion
5198 (beginning-of-line 2)
5199 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5200 ; XEmacs does not have `next-single-char-property-change'
5201 ; I'm not sure about Emacs 21.
5202 (while (and (not (eobp)) ;; this is like `next-line'
5203 (get-char-property (1- (point)) 'invisible))
5204 (beginning-of-line 2))
5205 (while (and (not (eobp)) ;; this is like `next-line'
5206 (get-char-property (1- (point)) 'invisible))
5207 (goto-char (next-single-char-property-change (point) 'invisible))
5208 ;;;??? (or (bolp) (beginning-of-line 2))))
5209 (and (eolp) (beginning-of-line 2))))
5210 (setq eol (point)))
5211 (outline-end-of-heading) (setq eoh (point))
5212 (save-excursion
5213 (outline-next-heading)
5214 (setq has-children (and (org-at-heading-p t)
5215 (> (funcall outline-level) level))))
5216 (org-end-of-subtree t)
5217 (unless (eobp)
5218 (skip-chars-forward " \t\n")
5219 (beginning-of-line 1) ; in case this is an item
5221 (setq eos (if (eobp) (point) (1- (point)))))
5222 ;; Find out what to do next and set `this-command'
5223 (cond
5224 ((= eos eoh)
5225 ;; Nothing is hidden behind this heading
5226 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5227 (message "EMPTY ENTRY")
5228 (setq org-cycle-subtree-status nil)
5229 (save-excursion
5230 (goto-char eos)
5231 (outline-next-heading)
5232 (if (org-invisible-p) (org-flag-heading nil))))
5233 ((and (or (>= eol eos)
5234 (not (string-match "\\S-" (buffer-substring eol eos))))
5235 (or has-children
5236 (not (setq children-skipped
5237 org-cycle-skip-children-state-if-no-children))))
5238 ;; Entire subtree is hidden in one line: children view
5239 (run-hook-with-args 'org-pre-cycle-hook 'children)
5240 (org-show-entry)
5241 (show-children)
5242 (message "CHILDREN")
5243 (save-excursion
5244 (goto-char eos)
5245 (outline-next-heading)
5246 (if (org-invisible-p) (org-flag-heading nil)))
5247 (setq org-cycle-subtree-status 'children)
5248 (run-hook-with-args 'org-cycle-hook 'children))
5249 ((or children-skipped
5250 (and (eq last-command this-command)
5251 (eq org-cycle-subtree-status 'children)))
5252 ;; We just showed the children, or no children are there,
5253 ;; now show everything.
5254 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5255 (org-show-subtree)
5256 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5257 (setq org-cycle-subtree-status 'subtree)
5258 (run-hook-with-args 'org-cycle-hook 'subtree))
5260 ;; Default action: hide the subtree.
5261 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5262 (hide-subtree)
5263 (message "FOLDED")
5264 (setq org-cycle-subtree-status 'folded)
5265 (run-hook-with-args 'org-cycle-hook 'folded)))))
5267 ;;;###autoload
5268 (defun org-global-cycle (&optional arg)
5269 "Cycle the global visibility. For details see `org-cycle'.
5270 With C-u prefix arg, switch to startup visibility.
5271 With a numeric prefix, show all headlines up to that level."
5272 (interactive "P")
5273 (let ((org-cycle-include-plain-lists
5274 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5275 (cond
5276 ((integerp arg)
5277 (show-all)
5278 (hide-sublevels arg)
5279 (setq org-cycle-global-status 'contents))
5280 ((equal arg '(4))
5281 (org-set-startup-visibility)
5282 (message "Startup visibility, plus VISIBILITY properties."))
5284 (org-cycle '(4))))))
5286 (defun org-set-startup-visibility ()
5287 "Set the visibility required by startup options and properties."
5288 (cond
5289 ((eq org-startup-folded t)
5290 (org-cycle '(4)))
5291 ((eq org-startup-folded 'content)
5292 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5293 (org-cycle '(4)) (org-cycle '(4)))))
5294 (unless (eq org-startup-folded 'showeverything)
5295 (if org-hide-block-startup (org-hide-block-all))
5296 (org-set-visibility-according-to-property 'no-cleanup)
5297 (org-cycle-hide-archived-subtrees 'all)
5298 (org-cycle-hide-drawers 'all)
5299 (org-cycle-show-empty-lines 'all)))
5301 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5302 "Switch subtree visibilities according to :VISIBILITY: property."
5303 (interactive)
5304 (let (org-show-entry-below state)
5305 (save-excursion
5306 (goto-char (point-min))
5307 (while (re-search-forward
5308 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5309 nil t)
5310 (setq state (match-string 1))
5311 (save-excursion
5312 (org-back-to-heading t)
5313 (hide-subtree)
5314 (org-reveal)
5315 (cond
5316 ((equal state '("fold" "folded"))
5317 (hide-subtree))
5318 ((equal state "children")
5319 (org-show-hidden-entry)
5320 (show-children))
5321 ((equal state "content")
5322 (save-excursion
5323 (save-restriction
5324 (org-narrow-to-subtree)
5325 (org-content))))
5326 ((member state '("all" "showall"))
5327 (show-subtree)))))
5328 (unless no-cleanup
5329 (org-cycle-hide-archived-subtrees 'all)
5330 (org-cycle-hide-drawers 'all)
5331 (org-cycle-show-empty-lines 'all)))))
5333 (defun org-overview ()
5334 "Switch to overview mode, showing only top-level headlines.
5335 Really, this shows all headlines with level equal or greater than the level
5336 of the first headline in the buffer. This is important, because if the
5337 first headline is not level one, then (hide-sublevels 1) gives confusing
5338 results."
5339 (interactive)
5340 (let ((level (save-excursion
5341 (goto-char (point-min))
5342 (if (re-search-forward (concat "^" outline-regexp) nil t)
5343 (progn
5344 (goto-char (match-beginning 0))
5345 (funcall outline-level))))))
5346 (and level (hide-sublevels level))))
5348 (defun org-content (&optional arg)
5349 "Show all headlines in the buffer, like a table of contents.
5350 With numerical argument N, show content up to level N."
5351 (interactive "P")
5352 (save-excursion
5353 ;; Visit all headings and show their offspring
5354 (and (integerp arg) (org-overview))
5355 (goto-char (point-max))
5356 (catch 'exit
5357 (while (and (progn (condition-case nil
5358 (outline-previous-visible-heading 1)
5359 (error (goto-char (point-min))))
5361 (looking-at outline-regexp))
5362 (if (integerp arg)
5363 (show-children (1- arg))
5364 (show-branches))
5365 (if (bobp) (throw 'exit nil))))))
5368 (defun org-optimize-window-after-visibility-change (state)
5369 "Adjust the window after a change in outline visibility.
5370 This function is the default value of the hook `org-cycle-hook'."
5371 (when (get-buffer-window (current-buffer))
5372 (cond
5373 ((eq state 'content) nil)
5374 ((eq state 'all) nil)
5375 ((eq state 'folded) nil)
5376 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5377 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5379 ;; FIXME: no longer in use
5380 (defun org-compact-display-after-subtree-move ()
5381 "Show a compacter version of the tree of the entry's parent."
5382 (save-excursion
5383 (if (org-up-heading-safe)
5384 (progn
5385 (hide-subtree)
5386 (show-entry)
5387 (show-children)
5388 (org-cycle-show-empty-lines 'children)
5389 (org-cycle-hide-drawers 'children))
5390 (org-overview))))
5392 (defun org-remove-empty-overlays-at (pos)
5393 "Remove outline overlays that do not contain non-white stuff."
5394 (mapc
5395 (lambda (o)
5396 (and (eq 'outline (org-overlay-get o 'invisible))
5397 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5398 (org-overlay-end o))))
5399 (org-delete-overlay o)))
5400 (org-overlays-at pos)))
5402 (defun org-clean-visibility-after-subtree-move ()
5403 "Fix visibility issues after moving a subtree."
5404 ;; First, find a reasonable region to look at:
5405 ;; Start two siblings above, end three below
5406 (let* ((beg (save-excursion
5407 (and (org-get-last-sibling)
5408 (org-get-last-sibling))
5409 (point)))
5410 (end (save-excursion
5411 (and (org-get-next-sibling)
5412 (org-get-next-sibling)
5413 (org-get-next-sibling))
5414 (if (org-at-heading-p)
5415 (point-at-eol)
5416 (point))))
5417 (level (looking-at "\\*+"))
5418 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5419 (save-excursion
5420 (save-restriction
5421 (narrow-to-region beg end)
5422 (when re
5423 ;; Properly fold already folded siblings
5424 (goto-char (point-min))
5425 (while (re-search-forward re nil t)
5426 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5427 (hide-entry))))
5428 (org-cycle-show-empty-lines 'overview)
5429 (org-cycle-hide-drawers 'overview)))))
5431 (defun org-cycle-show-empty-lines (state)
5432 "Show empty lines above all visible headlines.
5433 The region to be covered depends on STATE when called through
5434 `org-cycle-hook'. Lisp program can use t for STATE to get the
5435 entire buffer covered. Note that an empty line is only shown if there
5436 are at least `org-cycle-separator-lines' empty lines before the headline."
5437 (when (not (= org-cycle-separator-lines 0))
5438 (save-excursion
5439 (let* ((n (abs org-cycle-separator-lines))
5440 (re (cond
5441 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5442 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5443 (t (let ((ns (number-to-string (- n 2))))
5444 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5445 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5446 beg end b e)
5447 (cond
5448 ((memq state '(overview contents t))
5449 (setq beg (point-min) end (point-max)))
5450 ((memq state '(children folded))
5451 (setq beg (point) end (progn (org-end-of-subtree t t)
5452 (beginning-of-line 2)
5453 (point)))))
5454 (when beg
5455 (goto-char beg)
5456 (while (re-search-forward re end t)
5457 (unless (get-char-property (match-end 1) 'invisible)
5458 (setq e (match-end 1))
5459 (if (< org-cycle-separator-lines 0)
5460 (setq b (save-excursion
5461 (goto-char (match-beginning 0))
5462 (org-back-over-empty-lines)
5463 (if (save-excursion
5464 (goto-char (max (point-min) (1- (point))))
5465 (org-on-heading-p))
5466 (1- (point))
5467 (point))))
5468 (setq b (match-beginning 1)))
5469 (outline-flag-region b e nil)))))))
5470 ;; Never hide empty lines at the end of the file.
5471 (save-excursion
5472 (goto-char (point-max))
5473 (outline-previous-heading)
5474 (outline-end-of-heading)
5475 (if (and (looking-at "[ \t\n]+")
5476 (= (match-end 0) (point-max)))
5477 (outline-flag-region (point) (match-end 0) nil))))
5479 (defun org-show-empty-lines-in-parent ()
5480 "Move to the parent and re-show empty lines before visible headlines."
5481 (save-excursion
5482 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5483 (org-cycle-show-empty-lines context))))
5485 (defun org-files-list ()
5486 "Return `org-agenda-files' list, plus all open org-mode files.
5487 This is useful for operations that need to scan all of a user's
5488 open and agenda-wise Org files."
5489 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5490 (dolist (buf (buffer-list))
5491 (with-current-buffer buf
5492 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5493 (let ((file (expand-file-name (buffer-file-name))))
5494 (unless (member file files)
5495 (push file files))))))
5496 files))
5498 (defsubst org-entry-beginning-position ()
5499 "Return the beginning position of the current entry."
5500 (save-excursion (outline-back-to-heading t) (point)))
5502 (defsubst org-entry-end-position ()
5503 "Return the end position of the current entry."
5504 (save-excursion (outline-next-heading) (point)))
5506 (defun org-cycle-hide-drawers (state)
5507 "Re-hide all drawers after a visibility state change."
5508 (when (and (org-mode-p)
5509 (not (memq state '(overview folded contents))))
5510 (save-excursion
5511 (let* ((globalp (memq state '(contents all)))
5512 (beg (if globalp (point-min) (point)))
5513 (end (if globalp (point-max)
5514 (if (eq state 'children)
5515 (save-excursion (outline-next-heading) (point))
5516 (org-end-of-subtree t)))))
5517 (goto-char beg)
5518 (while (re-search-forward org-drawer-regexp end t)
5519 (org-flag-drawer t))))))
5521 (defun org-flag-drawer (flag)
5522 (save-excursion
5523 (beginning-of-line 1)
5524 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5525 (let ((b (match-end 0))
5526 (outline-regexp org-outline-regexp))
5527 (if (re-search-forward
5528 "^[ \t]*:END:"
5529 (save-excursion (outline-next-heading) (point)) t)
5530 (outline-flag-region b (point-at-eol) flag)
5531 (error ":END: line missing at position %s" b))))))
5533 (defun org-subtree-end-visible-p ()
5534 "Is the end of the current subtree visible?"
5535 (pos-visible-in-window-p
5536 (save-excursion (org-end-of-subtree t) (point))))
5538 (defun org-first-headline-recenter (&optional N)
5539 "Move cursor to the first headline and recenter the headline.
5540 Optional argument N means, put the headline into the Nth line of the window."
5541 (goto-char (point-min))
5542 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5543 (beginning-of-line)
5544 (recenter (prefix-numeric-value N))))
5546 ;;; Folding of blocks
5548 (defconst org-block-regexp
5550 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5551 "Regular expression for hiding blocks.")
5553 (defvar org-hide-block-overlays nil
5554 "Overays hiding blocks.")
5555 (make-variable-buffer-local 'org-hide-block-overlays)
5557 (defun org-block-map (function &optional start end)
5558 "Call func at the head of all source blocks in the current
5559 buffer. Optional arguments START and END can be used to limit
5560 the range."
5561 (let ((start (or start (point-min)))
5562 (end (or end (point-max))))
5563 (save-excursion
5564 (goto-char start)
5565 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5566 (save-excursion
5567 (save-match-data
5568 (goto-char (match-beginning 0))
5569 (funcall function)))))))
5571 (defun org-hide-block-toggle-all ()
5572 "Toggle the visibility of all blocks in the current buffer."
5573 (org-block-map #'org-hide-block-toggle))
5575 (defun org-hide-block-all ()
5576 "Fold all blocks in the current buffer."
5577 (interactive)
5578 (org-show-block-all)
5579 (org-block-map #'org-hide-block-toggle-maybe))
5581 (defun org-show-block-all ()
5582 "Unfold all blocks in the current buffer."
5583 (mapc 'org-delete-overlay org-hide-block-overlays)
5584 (setq org-hide-block-overlays nil))
5586 (defun org-hide-block-toggle-maybe ()
5587 "Toggle visibility of block at point."
5588 (interactive)
5589 (let ((case-fold-search t))
5590 (if (save-excursion
5591 (beginning-of-line 1)
5592 (looking-at org-block-regexp))
5593 (progn (org-hide-block-toggle)
5594 t) ;; to signal that we took action
5595 nil))) ;; to signal that we did not
5597 (defun org-hide-block-toggle (&optional force)
5598 "Toggle the visibility of the current block."
5599 (interactive)
5600 (save-excursion
5601 (beginning-of-line)
5602 (if (re-search-forward org-block-regexp nil t)
5603 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5604 (end (match-end 0)) ;; end of entire body
5606 (if (memq t (mapcar (lambda (overlay)
5607 (eq (org-overlay-get overlay 'invisible)
5608 'org-hide-block))
5609 (org-overlays-at start)))
5610 (if (or (not force) (eq force 'off))
5611 (mapc (lambda (ov)
5612 (when (member ov org-hide-block-overlays)
5613 (setq org-hide-block-overlays
5614 (delq ov org-hide-block-overlays)))
5615 (when (eq (org-overlay-get ov 'invisible)
5616 'org-hide-block)
5617 (org-delete-overlay ov)))
5618 (org-overlays-at start)))
5619 (setq ov (org-make-overlay start end))
5620 (org-overlay-put ov 'invisible 'org-hide-block)
5621 ;; make the block accessible to isearch
5622 (org-overlay-put
5623 ov 'isearch-open-invisible
5624 (lambda (ov)
5625 (when (member ov org-hide-block-overlays)
5626 (setq org-hide-block-overlays
5627 (delq ov org-hide-block-overlays)))
5628 (when (eq (org-overlay-get ov 'invisible)
5629 'org-hide-block)
5630 (org-delete-overlay ov))))
5631 (push ov org-hide-block-overlays)))
5632 (error "Not looking at a source block"))))
5634 ;; org-tab-after-check-for-cycling-hook
5635 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5636 ;; Remove overlays when changing major mode
5637 (add-hook 'org-mode-hook
5638 (lambda () (org-add-hook 'change-major-mode-hook
5639 'org-show-block-all 'append 'local)))
5641 ;;; Org-goto
5643 (defvar org-goto-window-configuration nil)
5644 (defvar org-goto-marker nil)
5645 (defvar org-goto-map
5646 (let ((map (make-sparse-keymap)))
5647 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5648 (while (setq cmd (pop cmds))
5649 (substitute-key-definition cmd cmd map global-map)))
5650 (suppress-keymap map)
5651 (org-defkey map "\C-m" 'org-goto-ret)
5652 (org-defkey map [(return)] 'org-goto-ret)
5653 (org-defkey map [(left)] 'org-goto-left)
5654 (org-defkey map [(right)] 'org-goto-right)
5655 (org-defkey map [(control ?g)] 'org-goto-quit)
5656 (org-defkey map "\C-i" 'org-cycle)
5657 (org-defkey map [(tab)] 'org-cycle)
5658 (org-defkey map [(down)] 'outline-next-visible-heading)
5659 (org-defkey map [(up)] 'outline-previous-visible-heading)
5660 (if org-goto-auto-isearch
5661 (if (fboundp 'define-key-after)
5662 (define-key-after map [t] 'org-goto-local-auto-isearch)
5663 nil)
5664 (org-defkey map "q" 'org-goto-quit)
5665 (org-defkey map "n" 'outline-next-visible-heading)
5666 (org-defkey map "p" 'outline-previous-visible-heading)
5667 (org-defkey map "f" 'outline-forward-same-level)
5668 (org-defkey map "b" 'outline-backward-same-level)
5669 (org-defkey map "u" 'outline-up-heading))
5670 (org-defkey map "/" 'org-occur)
5671 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5672 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5673 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5674 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5675 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5676 map))
5678 (defconst org-goto-help
5679 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5680 RET=jump to location [Q]uit and return to previous location
5681 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5683 (defvar org-goto-start-pos) ; dynamically scoped parameter
5685 ;; FIXME: Docstring doe not mention both interfaces
5686 (defun org-goto (&optional alternative-interface)
5687 "Look up a different location in the current file, keeping current visibility.
5689 When you want look-up or go to a different location in a document, the
5690 fastest way is often to fold the entire buffer and then dive into the tree.
5691 This method has the disadvantage, that the previous location will be folded,
5692 which may not be what you want.
5694 This command works around this by showing a copy of the current buffer
5695 in an indirect buffer, in overview mode. You can dive into the tree in
5696 that copy, use org-occur and incremental search to find a location.
5697 When pressing RET or `Q', the command returns to the original buffer in
5698 which the visibility is still unchanged. After RET is will also jump to
5699 the location selected in the indirect buffer and expose the
5700 the headline hierarchy above."
5701 (interactive "P")
5702 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5703 (org-refile-use-outline-path t)
5704 (org-refile-target-verify-function nil)
5705 (interface
5706 (if (not alternative-interface)
5707 org-goto-interface
5708 (if (eq org-goto-interface 'outline)
5709 'outline-path-completion
5710 'outline)))
5711 (org-goto-start-pos (point))
5712 (selected-point
5713 (if (eq interface 'outline)
5714 (car (org-get-location (current-buffer) org-goto-help))
5715 (nth 3 (org-refile-get-location "Goto: ")))))
5716 (if selected-point
5717 (progn
5718 (org-mark-ring-push org-goto-start-pos)
5719 (goto-char selected-point)
5720 (if (or (org-invisible-p) (org-invisible-p2))
5721 (org-show-context 'org-goto)))
5722 (message "Quit"))))
5724 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5725 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5726 (defvar org-goto-local-auto-isearch-map) ; defined below
5728 (defun org-get-location (buf help)
5729 "Let the user select a location in the Org-mode buffer BUF.
5730 This function uses a recursive edit. It returns the selected position
5731 or nil."
5732 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5733 (isearch-hide-immediately nil)
5734 (isearch-search-fun-function
5735 (lambda () 'org-goto-local-search-headings))
5736 (org-goto-selected-point org-goto-exit-command))
5737 (save-excursion
5738 (save-window-excursion
5739 (delete-other-windows)
5740 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5741 (switch-to-buffer
5742 (condition-case nil
5743 (make-indirect-buffer (current-buffer) "*org-goto*")
5744 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5745 (with-output-to-temp-buffer "*Help*"
5746 (princ help))
5747 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5748 (setq buffer-read-only nil)
5749 (let ((org-startup-truncated t)
5750 (org-startup-folded nil)
5751 (org-startup-align-all-tables nil))
5752 (org-mode)
5753 (org-overview))
5754 (setq buffer-read-only t)
5755 (if (and (boundp 'org-goto-start-pos)
5756 (integer-or-marker-p org-goto-start-pos))
5757 (let ((org-show-hierarchy-above t)
5758 (org-show-siblings t)
5759 (org-show-following-heading t))
5760 (goto-char org-goto-start-pos)
5761 (and (org-invisible-p) (org-show-context)))
5762 (goto-char (point-min)))
5763 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5764 (message "Select location and press RET")
5765 (use-local-map org-goto-map)
5766 (recursive-edit)
5768 (kill-buffer "*org-goto*")
5769 (cons org-goto-selected-point org-goto-exit-command)))
5771 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5772 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5773 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5774 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5776 (defun org-goto-local-search-headings (string bound noerror)
5777 "Search and make sure that any matches are in headlines."
5778 (catch 'return
5779 (while (if isearch-forward
5780 (search-forward string bound noerror)
5781 (search-backward string bound noerror))
5782 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5783 (and (member :headline context)
5784 (not (member :tags context))))
5785 (throw 'return (point))))))
5787 (defun org-goto-local-auto-isearch ()
5788 "Start isearch."
5789 (interactive)
5790 (goto-char (point-min))
5791 (let ((keys (this-command-keys)))
5792 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5793 (isearch-mode t)
5794 (isearch-process-search-char (string-to-char keys)))))
5796 (defun org-goto-ret (&optional arg)
5797 "Finish `org-goto' by going to the new location."
5798 (interactive "P")
5799 (setq org-goto-selected-point (point)
5800 org-goto-exit-command 'return)
5801 (throw 'exit nil))
5803 (defun org-goto-left ()
5804 "Finish `org-goto' by going to the new location."
5805 (interactive)
5806 (if (org-on-heading-p)
5807 (progn
5808 (beginning-of-line 1)
5809 (setq org-goto-selected-point (point)
5810 org-goto-exit-command 'left)
5811 (throw 'exit nil))
5812 (error "Not on a heading")))
5814 (defun org-goto-right ()
5815 "Finish `org-goto' by going to the new location."
5816 (interactive)
5817 (if (org-on-heading-p)
5818 (progn
5819 (setq org-goto-selected-point (point)
5820 org-goto-exit-command 'right)
5821 (throw 'exit nil))
5822 (error "Not on a heading")))
5824 (defun org-goto-quit ()
5825 "Finish `org-goto' without cursor motion."
5826 (interactive)
5827 (setq org-goto-selected-point nil)
5828 (setq org-goto-exit-command 'quit)
5829 (throw 'exit nil))
5831 ;;; Indirect buffer display of subtrees
5833 (defvar org-indirect-dedicated-frame nil
5834 "This is the frame being used for indirect tree display.")
5835 (defvar org-last-indirect-buffer nil)
5837 (defun org-tree-to-indirect-buffer (&optional arg)
5838 "Create indirect buffer and narrow it to current subtree.
5839 With numerical prefix ARG, go up to this level and then take that tree.
5840 If ARG is negative, go up that many levels.
5841 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5842 indirect buffer previously made with this command, to avoid proliferation of
5843 indirect buffers. However, when you call the command with a `C-u' prefix, or
5844 when `org-indirect-buffer-display' is `new-frame', the last buffer
5845 is kept so that you can work with several indirect buffers at the same time.
5846 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5847 requests that a new frame be made for the new buffer, so that the dedicated
5848 frame is not changed."
5849 (interactive "P")
5850 (let ((cbuf (current-buffer))
5851 (cwin (selected-window))
5852 (pos (point))
5853 beg end level heading ibuf)
5854 (save-excursion
5855 (org-back-to-heading t)
5856 (when (numberp arg)
5857 (setq level (org-outline-level))
5858 (if (< arg 0) (setq arg (+ level arg)))
5859 (while (> (setq level (org-outline-level)) arg)
5860 (outline-up-heading 1 t)))
5861 (setq beg (point)
5862 heading (org-get-heading))
5863 (org-end-of-subtree t t) (setq end (point)))
5864 (if (and (buffer-live-p org-last-indirect-buffer)
5865 (not (eq org-indirect-buffer-display 'new-frame))
5866 (not arg))
5867 (kill-buffer org-last-indirect-buffer))
5868 (setq ibuf (org-get-indirect-buffer cbuf)
5869 org-last-indirect-buffer ibuf)
5870 (cond
5871 ((or (eq org-indirect-buffer-display 'new-frame)
5872 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5873 (select-frame (make-frame))
5874 (delete-other-windows)
5875 (switch-to-buffer ibuf)
5876 (org-set-frame-title heading))
5877 ((eq org-indirect-buffer-display 'dedicated-frame)
5878 (raise-frame
5879 (select-frame (or (and org-indirect-dedicated-frame
5880 (frame-live-p org-indirect-dedicated-frame)
5881 org-indirect-dedicated-frame)
5882 (setq org-indirect-dedicated-frame (make-frame)))))
5883 (delete-other-windows)
5884 (switch-to-buffer ibuf)
5885 (org-set-frame-title (concat "Indirect: " heading)))
5886 ((eq org-indirect-buffer-display 'current-window)
5887 (switch-to-buffer ibuf))
5888 ((eq org-indirect-buffer-display 'other-window)
5889 (pop-to-buffer ibuf))
5890 (t (error "Invalid value")))
5891 (if (featurep 'xemacs)
5892 (save-excursion (org-mode) (turn-on-font-lock)))
5893 (narrow-to-region beg end)
5894 (show-all)
5895 (goto-char pos)
5896 (and (window-live-p cwin) (select-window cwin))))
5898 (defun org-get-indirect-buffer (&optional buffer)
5899 (setq buffer (or buffer (current-buffer)))
5900 (let ((n 1) (base (buffer-name buffer)) bname)
5901 (while (buffer-live-p
5902 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5903 (setq n (1+ n)))
5904 (condition-case nil
5905 (make-indirect-buffer buffer bname 'clone)
5906 (error (make-indirect-buffer buffer bname)))))
5908 (defun org-set-frame-title (title)
5909 "Set the title of the current frame to the string TITLE."
5910 ;; FIXME: how to name a single frame in XEmacs???
5911 (unless (featurep 'xemacs)
5912 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5914 ;;;; Structure editing
5916 ;;; Inserting headlines
5918 (defun org-previous-line-empty-p ()
5919 (save-excursion
5920 (and (not (bobp))
5921 (or (beginning-of-line 0) t)
5922 (save-match-data
5923 (looking-at "[ \t]*$")))))
5925 (defun org-insert-heading (&optional force-heading)
5926 "Insert a new heading or item with same depth at point.
5927 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5928 If point is at the beginning of a headline, insert a sibling before the
5929 current headline. If point is not at the beginning, do not split the line,
5930 but create the new headline after the current line."
5931 (interactive "P")
5932 (if (= (buffer-size) 0)
5933 (insert "\n* ")
5934 (when (or force-heading (not (org-insert-item)))
5935 (let* ((empty-line-p nil)
5936 (head (save-excursion
5937 (condition-case nil
5938 (progn
5939 (org-back-to-heading)
5940 (setq empty-line-p (org-previous-line-empty-p))
5941 (match-string 0))
5942 (error "*"))))
5943 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5944 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5945 pos hide-previous previous-pos)
5946 (cond
5947 ((and (org-on-heading-p) (bolp)
5948 (or (bobp)
5949 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5950 ;; insert before the current line
5951 (open-line (if blank 2 1)))
5952 ((and (bolp)
5953 (not org-insert-heading-respect-content)
5954 (or (bobp)
5955 (save-excursion
5956 (backward-char 1) (not (org-invisible-p)))))
5957 ;; insert right here
5958 nil)
5960 ;; somewhere in the line
5961 (save-excursion
5962 (setq previous-pos (point-at-bol))
5963 (end-of-line)
5964 (setq hide-previous (org-invisible-p)))
5965 (and org-insert-heading-respect-content (org-show-subtree))
5966 (let ((split
5967 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5968 (save-excursion
5969 (let ((p (point)))
5970 (goto-char (point-at-bol))
5971 (and (looking-at org-complex-heading-regexp)
5972 (> p (match-beginning 4)))))))
5973 tags pos)
5974 (cond
5975 (org-insert-heading-respect-content
5976 (org-end-of-subtree nil t)
5977 (or (bolp) (newline))
5978 (or (org-previous-line-empty-p)
5979 (and blank (newline)))
5980 (open-line 1))
5981 ((org-on-heading-p)
5982 (when hide-previous
5983 (show-children)
5984 (org-show-entry))
5985 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5986 (setq tags (and (match-end 2) (match-string 2)))
5987 (and (match-end 1)
5988 (delete-region (match-beginning 1) (match-end 1)))
5989 (setq pos (point-at-bol))
5990 (or split (end-of-line 1))
5991 (delete-horizontal-space)
5992 (newline (if blank 2 1))
5993 (when tags
5994 (save-excursion
5995 (goto-char pos)
5996 (end-of-line 1)
5997 (insert " " tags)
5998 (org-set-tags nil 'align))))
6000 (or split (end-of-line 1))
6001 (newline (if blank 2 1)))))))
6002 (insert head) (just-one-space)
6003 (setq pos (point))
6004 (end-of-line 1)
6005 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6006 (when (and org-insert-heading-respect-content hide-previous)
6007 (save-excursion
6008 (goto-char previous-pos)
6009 (hide-subtree)))
6010 (run-hooks 'org-insert-heading-hook)))))
6012 (defun org-get-heading (&optional no-tags)
6013 "Return the heading of the current entry, without the stars."
6014 (save-excursion
6015 (org-back-to-heading t)
6016 (if (looking-at
6017 (if no-tags
6018 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6019 "\\*+[ \t]+\\([^\r\n]*\\)"))
6020 (match-string 1) "")))
6022 (defun org-heading-components ()
6023 "Return the components of the current heading.
6024 This is a list with the following elements:
6025 - the level as an integer
6026 - the reduced level, different if `org-odd-levels-only' is set.
6027 - the TODO keyword, or nil
6028 - the priority character, like ?A, or nil if no priority is given
6029 - the headline text itself, or the tags string if no headline text
6030 - the tags string, or nil."
6031 (save-excursion
6032 (org-back-to-heading t)
6033 (if (looking-at org-complex-heading-regexp)
6034 (list (length (match-string 1))
6035 (org-reduced-level (length (match-string 1)))
6036 (org-match-string-no-properties 2)
6037 (and (match-end 3) (aref (match-string 3) 2))
6038 (org-match-string-no-properties 4)
6039 (org-match-string-no-properties 5)))))
6041 (defun org-get-entry ()
6042 "Get the entry text, after heading, entire subtree."
6043 (save-excursion
6044 (org-back-to-heading t)
6045 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6047 (defun org-insert-heading-after-current ()
6048 "Insert a new heading with same level as current, after current subtree."
6049 (interactive)
6050 (org-back-to-heading)
6051 (org-insert-heading)
6052 (org-move-subtree-down)
6053 (end-of-line 1))
6055 (defun org-insert-heading-respect-content ()
6056 (interactive)
6057 (let ((org-insert-heading-respect-content t))
6058 (org-insert-heading t)))
6060 (defun org-insert-todo-heading-respect-content (&optional force-state)
6061 (interactive "P")
6062 (let ((org-insert-heading-respect-content t))
6063 (org-insert-todo-heading force-state t)))
6065 (defun org-insert-todo-heading (arg &optional force-heading)
6066 "Insert a new heading with the same level and TODO state as current heading.
6067 If the heading has no TODO state, or if the state is DONE, use the first
6068 state (TODO by default). Also with prefix arg, force first state."
6069 (interactive "P")
6070 (when (or force-heading (not (org-insert-item 'checkbox)))
6071 (org-insert-heading force-heading)
6072 (save-excursion
6073 (org-back-to-heading)
6074 (outline-previous-heading)
6075 (looking-at org-todo-line-regexp))
6076 (let*
6077 ((new-mark-x
6078 (if (or arg
6079 (not (match-beginning 2))
6080 (member (match-string 2) org-done-keywords))
6081 (car org-todo-keywords-1)
6082 (match-string 2)))
6083 (new-mark
6085 (run-hook-with-args-until-success
6086 'org-todo-get-default-hook new-mark-x nil)
6087 new-mark-x)))
6088 (beginning-of-line 1)
6089 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6090 (if org-treat-insert-todo-heading-as-state-change
6091 (org-todo new-mark)
6092 (insert new-mark " "))))
6093 (when org-provide-todo-statistics
6094 (org-update-parent-todo-statistics))))
6096 (defun org-insert-subheading (arg)
6097 "Insert a new subheading and demote it.
6098 Works for outline headings and for plain lists alike."
6099 (interactive "P")
6100 (org-insert-heading arg)
6101 (cond
6102 ((org-on-heading-p) (org-do-demote))
6103 ((org-at-item-p) (org-indent-item 1))))
6105 (defun org-insert-todo-subheading (arg)
6106 "Insert a new subheading with TODO keyword or checkbox and demote it.
6107 Works for outline headings and for plain lists alike."
6108 (interactive "P")
6109 (org-insert-todo-heading arg)
6110 (cond
6111 ((org-on-heading-p) (org-do-demote))
6112 ((org-at-item-p) (org-indent-item 1))))
6114 ;;; Promotion and Demotion
6116 (defvar org-after-demote-entry-hook nil
6117 "Hook run after an entry has been demoted.
6118 The cursor will be at the beginning of the entry.
6119 When a subtree is being demoted, the hook will be called for each node.")
6121 (defvar org-after-promote-entry-hook nil
6122 "Hook run after an entry has been promoted.
6123 The cursor will be at the beginning of the entry.
6124 When a subtree is being promoted, the hook will be called for each node.")
6126 (defun org-promote-subtree ()
6127 "Promote the entire subtree.
6128 See also `org-promote'."
6129 (interactive)
6130 (save-excursion
6131 (org-map-tree 'org-promote))
6132 (org-fix-position-after-promote))
6134 (defun org-demote-subtree ()
6135 "Demote the entire subtree. See `org-demote'.
6136 See also `org-promote'."
6137 (interactive)
6138 (save-excursion
6139 (org-map-tree 'org-demote))
6140 (org-fix-position-after-promote))
6143 (defun org-do-promote ()
6144 "Promote the current heading higher up the tree.
6145 If the region is active in `transient-mark-mode', promote all headings
6146 in the region."
6147 (interactive)
6148 (save-excursion
6149 (if (org-region-active-p)
6150 (org-map-region 'org-promote (region-beginning) (region-end))
6151 (org-promote)))
6152 (org-fix-position-after-promote))
6154 (defun org-do-demote ()
6155 "Demote the current heading lower down the tree.
6156 If the region is active in `transient-mark-mode', demote all headings
6157 in the region."
6158 (interactive)
6159 (save-excursion
6160 (if (org-region-active-p)
6161 (org-map-region 'org-demote (region-beginning) (region-end))
6162 (org-demote)))
6163 (org-fix-position-after-promote))
6165 (defun org-fix-position-after-promote ()
6166 "Make sure that after pro/demotion cursor position is right."
6167 (let ((pos (point)))
6168 (when (save-excursion
6169 (beginning-of-line 1)
6170 (looking-at org-todo-line-regexp)
6171 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6172 (cond ((eobp) (insert " "))
6173 ((eolp) (insert " "))
6174 ((equal (char-after) ?\ ) (forward-char 1))))))
6176 (defun org-current-level ()
6177 "Return the level of the current entry, or nil if before the first headline.
6178 The level is the number of stars at the beginning of the headline."
6179 (save-excursion
6180 (condition-case nil
6181 (progn
6182 (org-back-to-heading t)
6183 (funcall outline-level))
6184 (error nil))))
6186 (defun org-reduced-level (l)
6187 "Compute the effective level of a heading.
6188 This takes into account the setting of `org-odd-levels-only'."
6189 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6191 (defun org-get-valid-level (level &optional change)
6192 "Rectify a level change under the influence of `org-odd-levels-only'
6193 LEVEL is a current level, CHANGE is by how much the level should be
6194 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6195 even level numbers will become the next higher odd number."
6196 (if org-odd-levels-only
6197 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6198 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6199 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6200 (max 1 (+ level (or change 0)))))
6202 (if (boundp 'define-obsolete-function-alias)
6203 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6204 (define-obsolete-function-alias 'org-get-legal-level
6205 'org-get-valid-level)
6206 (define-obsolete-function-alias 'org-get-legal-level
6207 'org-get-valid-level "23.1")))
6209 (defun org-promote ()
6210 "Promote the current heading higher up the tree.
6211 If the region is active in `transient-mark-mode', promote all headings
6212 in the region."
6213 (org-back-to-heading t)
6214 (let* ((level (save-match-data (funcall outline-level)))
6215 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6216 (diff (abs (- level (length up-head) -1))))
6217 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6218 (replace-match up-head nil t)
6219 ;; Fixup tag positioning
6220 (and org-auto-align-tags (org-set-tags nil t))
6221 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6222 (run-hooks 'org-after-promote-entry-hook)))
6224 (defun org-demote ()
6225 "Demote the current heading lower down the tree.
6226 If the region is active in `transient-mark-mode', demote all headings
6227 in the region."
6228 (org-back-to-heading t)
6229 (let* ((level (save-match-data (funcall outline-level)))
6230 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6231 (diff (abs (- level (length down-head) -1))))
6232 (replace-match down-head nil t)
6233 ;; Fixup tag positioning
6234 (and org-auto-align-tags (org-set-tags nil t))
6235 (if org-adapt-indentation (org-fixup-indentation diff))
6236 (run-hooks 'org-after-demote-entry-hook)))
6238 (defvar org-tab-ind-state nil)
6240 (defun org-cycle-level ()
6241 (let ((org-adapt-indentation nil))
6242 (when (and (looking-at "[ \t]*$")
6243 (looking-back
6244 (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))
6245 (setq this-command 'org-cycle-level)
6246 (if (eq last-command 'org-cycle-level)
6247 (condition-case nil
6248 (progn (org-do-promote)
6249 (if (equal org-tab-ind-state (org-current-level))
6250 (org-do-promote)))
6251 (error
6252 (progn
6253 (save-excursion
6254 (beginning-of-line 1)
6255 (and (looking-at "\\*+")
6256 (replace-match
6257 (make-string org-tab-ind-state ?*))))
6258 (setq this-command 'org-cycle))))
6259 (setq org-tab-ind-state (- (match-end 1) (match-beginning 1)))
6260 (org-do-demote))
6261 t)))
6263 (defun org-map-tree (fun)
6264 "Call FUN for every heading underneath the current one."
6265 (org-back-to-heading)
6266 (let ((level (funcall outline-level)))
6267 (save-excursion
6268 (funcall fun)
6269 (while (and (progn
6270 (outline-next-heading)
6271 (> (funcall outline-level) level))
6272 (not (eobp)))
6273 (funcall fun)))))
6275 (defun org-map-region (fun beg end)
6276 "Call FUN for every heading between BEG and END."
6277 (let ((org-ignore-region t))
6278 (save-excursion
6279 (setq end (copy-marker end))
6280 (goto-char beg)
6281 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6282 (< (point) end))
6283 (funcall fun))
6284 (while (and (progn
6285 (outline-next-heading)
6286 (< (point) end))
6287 (not (eobp)))
6288 (funcall fun)))))
6290 (defun org-fixup-indentation (diff)
6291 "Change the indentation in the current entry by DIFF
6292 However, if any line in the current entry has no indentation, or if it
6293 would end up with no indentation after the change, nothing at all is done."
6294 (save-excursion
6295 (let ((end (save-excursion (outline-next-heading)
6296 (point-marker)))
6297 (prohibit (if (> diff 0)
6298 "^\\S-"
6299 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6300 col)
6301 (unless (save-excursion (end-of-line 1)
6302 (re-search-forward prohibit end t))
6303 (while (and (< (point) end)
6304 (re-search-forward "^[ \t]+" end t))
6305 (goto-char (match-end 0))
6306 (setq col (current-column))
6307 (if (< diff 0) (replace-match ""))
6308 (org-indent-to-column (+ diff col))))
6309 (move-marker end nil))))
6311 (defun org-convert-to-odd-levels ()
6312 "Convert an org-mode file with all levels allowed to one with odd levels.
6313 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6314 level 5 etc."
6315 (interactive)
6316 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6317 (let ((outline-regexp org-outline-regexp)
6318 (outline-level 'org-outline-level)
6319 (org-odd-levels-only nil) n)
6320 (save-excursion
6321 (goto-char (point-min))
6322 (while (re-search-forward "^\\*\\*+ " nil t)
6323 (setq n (- (length (match-string 0)) 2))
6324 (while (>= (setq n (1- n)) 0)
6325 (org-demote))
6326 (end-of-line 1))))))
6328 (defun org-convert-to-oddeven-levels ()
6329 "Convert an org-mode file with only odd levels to one with odd and even levels.
6330 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6331 section with an even level, conversion would destroy the structure of the file. An error
6332 is signaled in this case."
6333 (interactive)
6334 (goto-char (point-min))
6335 ;; First check if there are no even levels
6336 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6337 (org-show-context t)
6338 (error "Not all levels are odd in this file. Conversion not possible"))
6339 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6340 (let ((outline-regexp org-outline-regexp)
6341 (outline-level 'org-outline-level)
6342 (org-odd-levels-only nil) n)
6343 (save-excursion
6344 (goto-char (point-min))
6345 (while (re-search-forward "^\\*\\*+ " nil t)
6346 (setq n (/ (1- (length (match-string 0))) 2))
6347 (while (>= (setq n (1- n)) 0)
6348 (org-promote))
6349 (end-of-line 1))))))
6351 (defun org-tr-level (n)
6352 "Make N odd if required."
6353 (if org-odd-levels-only (1+ (/ n 2)) n))
6355 ;;; Vertical tree motion, cutting and pasting of subtrees
6357 (defun org-move-subtree-up (&optional arg)
6358 "Move the current subtree up past ARG headlines of the same level."
6359 (interactive "p")
6360 (org-move-subtree-down (- (prefix-numeric-value arg))))
6362 (defun org-move-subtree-down (&optional arg)
6363 "Move the current subtree down past ARG headlines of the same level."
6364 (interactive "p")
6365 (setq arg (prefix-numeric-value arg))
6366 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6367 'org-get-last-sibling))
6368 (ins-point (make-marker))
6369 (cnt (abs arg))
6370 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6371 ;; Select the tree
6372 (org-back-to-heading)
6373 (setq beg0 (point))
6374 (save-excursion
6375 (setq ne-beg (org-back-over-empty-lines))
6376 (setq beg (point)))
6377 (save-match-data
6378 (save-excursion (outline-end-of-heading)
6379 (setq folded (org-invisible-p)))
6380 (outline-end-of-subtree))
6381 (outline-next-heading)
6382 (setq ne-end (org-back-over-empty-lines))
6383 (setq end (point))
6384 (goto-char beg0)
6385 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6386 ;; include less whitespace
6387 (save-excursion
6388 (goto-char beg)
6389 (forward-line (- ne-beg ne-end))
6390 (setq beg (point))))
6391 ;; Find insertion point, with error handling
6392 (while (> cnt 0)
6393 (or (and (funcall movfunc) (looking-at outline-regexp))
6394 (progn (goto-char beg0)
6395 (error "Cannot move past superior level or buffer limit")))
6396 (setq cnt (1- cnt)))
6397 (if (> arg 0)
6398 ;; Moving forward - still need to move over subtree
6399 (progn (org-end-of-subtree t t)
6400 (save-excursion
6401 (org-back-over-empty-lines)
6402 (or (bolp) (newline)))))
6403 (setq ne-ins (org-back-over-empty-lines))
6404 (move-marker ins-point (point))
6405 (setq txt (buffer-substring beg end))
6406 (org-save-markers-in-region beg end)
6407 (delete-region beg end)
6408 (org-remove-empty-overlays-at beg)
6409 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6410 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6411 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6412 (let ((bbb (point)))
6413 (insert-before-markers txt)
6414 (org-reinstall-markers-in-region bbb)
6415 (move-marker ins-point bbb))
6416 (or (bolp) (insert "\n"))
6417 (setq ins-end (point))
6418 (goto-char ins-point)
6419 (org-skip-whitespace)
6420 (when (and (< arg 0)
6421 (org-first-sibling-p)
6422 (> ne-ins ne-beg))
6423 ;; Move whitespace back to beginning
6424 (save-excursion
6425 (goto-char ins-end)
6426 (let ((kill-whole-line t))
6427 (kill-line (- ne-ins ne-beg)) (point)))
6428 (insert (make-string (- ne-ins ne-beg) ?\n)))
6429 (move-marker ins-point nil)
6430 (if folded
6431 (hide-subtree)
6432 (org-show-entry)
6433 (show-children)
6434 (org-cycle-hide-drawers 'children))
6435 (org-clean-visibility-after-subtree-move)))
6437 (defvar org-subtree-clip ""
6438 "Clipboard for cut and paste of subtrees.
6439 This is actually only a copy of the kill, because we use the normal kill
6440 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6442 (defvar org-subtree-clip-folded nil
6443 "Was the last copied subtree folded?
6444 This is used to fold the tree back after pasting.")
6446 (defun org-cut-subtree (&optional n)
6447 "Cut the current subtree into the clipboard.
6448 With prefix arg N, cut this many sequential subtrees.
6449 This is a short-hand for marking the subtree and then cutting it."
6450 (interactive "p")
6451 (org-copy-subtree n 'cut))
6453 (defun org-copy-subtree (&optional n cut force-store-markers)
6454 "Cut the current subtree into the clipboard.
6455 With prefix arg N, cut this many sequential subtrees.
6456 This is a short-hand for marking the subtree and then copying it.
6457 If CUT is non-nil, actually cut the subtree.
6458 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6459 of some markers in the region, even if CUT is non-nil. This is
6460 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6461 (interactive "p")
6462 (let (beg end folded (beg0 (point)))
6463 (if (interactive-p)
6464 (org-back-to-heading nil) ; take what looks like a subtree
6465 (org-back-to-heading t)) ; take what is really there
6466 (org-back-over-empty-lines)
6467 (setq beg (point))
6468 (skip-chars-forward " \t\r\n")
6469 (save-match-data
6470 (save-excursion (outline-end-of-heading)
6471 (setq folded (org-invisible-p)))
6472 (condition-case nil
6473 (org-forward-same-level (1- n) t)
6474 (error nil))
6475 (org-end-of-subtree t t))
6476 (org-back-over-empty-lines)
6477 (setq end (point))
6478 (goto-char beg0)
6479 (when (> end beg)
6480 (setq org-subtree-clip-folded folded)
6481 (when (or cut force-store-markers)
6482 (org-save-markers-in-region beg end))
6483 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6484 (setq org-subtree-clip (current-kill 0))
6485 (message "%s: Subtree(s) with %d characters"
6486 (if cut "Cut" "Copied")
6487 (length org-subtree-clip)))))
6489 (defun org-paste-subtree (&optional level tree for-yank)
6490 "Paste the clipboard as a subtree, with modification of headline level.
6491 The entire subtree is promoted or demoted in order to match a new headline
6492 level.
6494 If the cursor is at the beginning of a headline, the same level as
6495 that headline is used to paste the tree
6497 If not, the new level is derived from the *visible* headings
6498 before and after the insertion point, and taken to be the inferior headline
6499 level of the two. So if the previous visible heading is level 3 and the
6500 next is level 4 (or vice versa), level 4 will be used for insertion.
6501 This makes sure that the subtree remains an independent subtree and does
6502 not swallow low level entries.
6504 You can also force a different level, either by using a numeric prefix
6505 argument, or by inserting the heading marker by hand. For example, if the
6506 cursor is after \"*****\", then the tree will be shifted to level 5.
6508 If optional TREE is given, use this text instead of the kill ring.
6510 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6511 move back over whitespace before inserting, and move point to the end of
6512 the inserted text when done."
6513 (interactive "P")
6514 (setq tree (or tree (and kill-ring (current-kill 0))))
6515 (unless (org-kill-is-subtree-p tree)
6516 (error "%s"
6517 (substitute-command-keys
6518 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6519 (let* ((visp (not (org-invisible-p)))
6520 (txt tree)
6521 (^re (concat "^\\(" outline-regexp "\\)"))
6522 (re (concat "\\(" outline-regexp "\\)"))
6523 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6525 (old-level (if (string-match ^re txt)
6526 (- (match-end 0) (match-beginning 0) 1)
6527 -1))
6528 (force-level (cond (level (prefix-numeric-value level))
6529 ((and (looking-at "[ \t]*$")
6530 (string-match
6531 ^re_ (buffer-substring
6532 (point-at-bol) (point))))
6533 (- (match-end 1) (match-beginning 1)))
6534 ((and (bolp)
6535 (looking-at org-outline-regexp))
6536 (- (match-end 0) (point) 1))
6537 (t nil)))
6538 (previous-level (save-excursion
6539 (condition-case nil
6540 (progn
6541 (outline-previous-visible-heading 1)
6542 (if (looking-at re)
6543 (- (match-end 0) (match-beginning 0) 1)
6545 (error 1))))
6546 (next-level (save-excursion
6547 (condition-case nil
6548 (progn
6549 (or (looking-at outline-regexp)
6550 (outline-next-visible-heading 1))
6551 (if (looking-at re)
6552 (- (match-end 0) (match-beginning 0) 1)
6554 (error 1))))
6555 (new-level (or force-level (max previous-level next-level)))
6556 (shift (if (or (= old-level -1)
6557 (= new-level -1)
6558 (= old-level new-level))
6560 (- new-level old-level)))
6561 (delta (if (> shift 0) -1 1))
6562 (func (if (> shift 0) 'org-demote 'org-promote))
6563 (org-odd-levels-only nil)
6564 beg end newend)
6565 ;; Remove the forced level indicator
6566 (if force-level
6567 (delete-region (point-at-bol) (point)))
6568 ;; Paste
6569 (beginning-of-line 1)
6570 (unless for-yank (org-back-over-empty-lines))
6571 (setq beg (point))
6572 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6573 (insert-before-markers txt)
6574 (unless (string-match "\n\\'" txt) (insert "\n"))
6575 (setq newend (point))
6576 (org-reinstall-markers-in-region beg)
6577 (setq end (point))
6578 (goto-char beg)
6579 (skip-chars-forward " \t\n\r")
6580 (setq beg (point))
6581 (if (and (org-invisible-p) visp)
6582 (save-excursion (outline-show-heading)))
6583 ;; Shift if necessary
6584 (unless (= shift 0)
6585 (save-restriction
6586 (narrow-to-region beg end)
6587 (while (not (= shift 0))
6588 (org-map-region func (point-min) (point-max))
6589 (setq shift (+ delta shift)))
6590 (goto-char (point-min))
6591 (setq newend (point-max))))
6592 (when (or (interactive-p) for-yank)
6593 (message "Clipboard pasted as level %d subtree" new-level))
6594 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6595 kill-ring
6596 (eq org-subtree-clip (current-kill 0))
6597 org-subtree-clip-folded)
6598 ;; The tree was folded before it was killed/copied
6599 (hide-subtree))
6600 (and for-yank (goto-char newend))))
6602 (defun org-kill-is-subtree-p (&optional txt)
6603 "Check if the current kill is an outline subtree, or a set of trees.
6604 Returns nil if kill does not start with a headline, or if the first
6605 headline level is not the largest headline level in the tree.
6606 So this will actually accept several entries of equal levels as well,
6607 which is OK for `org-paste-subtree'.
6608 If optional TXT is given, check this string instead of the current kill."
6609 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6610 (start-level (and kill
6611 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6612 org-outline-regexp "\\)")
6613 kill)
6614 (- (match-end 2) (match-beginning 2) 1)))
6615 (re (concat "^" org-outline-regexp))
6616 (start (1+ (or (match-beginning 2) -1))))
6617 (if (not start-level)
6618 (progn
6619 nil) ;; does not even start with a heading
6620 (catch 'exit
6621 (while (setq start (string-match re kill (1+ start)))
6622 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6623 (throw 'exit nil)))
6624 t))))
6626 (defvar org-markers-to-move nil
6627 "Markers that should be moved with a cut-and-paste operation.
6628 Those markers are stored together with their positions relative to
6629 the start of the region.")
6631 (defun org-save-markers-in-region (beg end)
6632 "Check markers in region.
6633 If these markers are between BEG and END, record their position relative
6634 to BEG, so that after moving the block of text, we can put the markers back
6635 into place.
6636 This function gets called just before an entry or tree gets cut from the
6637 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6638 called immediately, to move the markers with the entries."
6639 (setq org-markers-to-move nil)
6640 (when (featurep 'org-clock)
6641 (org-clock-save-markers-for-cut-and-paste beg end))
6642 (when (featurep 'org-agenda)
6643 (org-agenda-save-markers-for-cut-and-paste beg end)))
6645 (defun org-check-and-save-marker (marker beg end)
6646 "Check if MARKER is between BEG and END.
6647 If yes, remember the marker and the distance to BEG."
6648 (when (and (marker-buffer marker)
6649 (equal (marker-buffer marker) (current-buffer)))
6650 (if (and (>= marker beg) (< marker end))
6651 (push (cons marker (- marker beg)) org-markers-to-move))))
6653 (defun org-reinstall-markers-in-region (beg)
6654 "Move all remembered markers to their position relative to BEG."
6655 (mapc (lambda (x)
6656 (move-marker (car x) (+ beg (cdr x))))
6657 org-markers-to-move)
6658 (setq org-markers-to-move nil))
6660 (defun org-narrow-to-subtree ()
6661 "Narrow buffer to the current subtree."
6662 (interactive)
6663 (save-excursion
6664 (save-match-data
6665 (narrow-to-region
6666 (progn (org-back-to-heading t) (point))
6667 (progn (org-end-of-subtree t t) (point))))))
6669 (defun org-clone-subtree-with-time-shift (n &optional shift)
6670 "Clone the task (subtree) at point N times.
6671 The clones will be inserted as siblings.
6673 In interactive use, the user will be prompted for the number of clones
6674 to be produced, and for a time SHIFT, which may be a repeater as used
6675 in time stamps, for example `+3d'.
6677 When a valid repeater is given and the entry contains any time stamps,
6678 the clones will become a sequence in time, with time stamps in the
6679 subtree shifted for each clone produced. If SHIFT is nil or the
6680 empty string, time stamps will be left alone.
6682 If the original subtree did contain time stamps with a repeater,
6683 the following will happen:
6684 - the repeater will be removed in each clone
6685 - an additional clone will be produced, with the current, unshifted
6686 date(s) in the entry.
6687 - the original entry will be placed *after* all the clones, with
6688 repeater intact.
6689 - the start days in the repeater in the original entry will be shifted
6690 to past the last clone.
6691 I this way you can spell out a number of instances of a repeating task,
6692 and still retain the repeater to cover future instances of the task."
6693 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6694 (let (beg end template task
6695 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6696 (if (not (and (integerp n) (> n 0)))
6697 (error "Invalid number of replications %s" n))
6698 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6699 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6700 shift)))
6701 (error "Invalid shift specification %s" shift))
6702 (when doshift
6703 (setq shift-n (string-to-number (match-string 1 shift))
6704 shift-what (cdr (assoc (match-string 2 shift)
6705 '(("d" . day) ("w" . week)
6706 ("m" . month) ("y" . year))))))
6707 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6708 (setq nmin 1 nmax n)
6709 (org-back-to-heading t)
6710 (setq beg (point))
6711 (org-end-of-subtree t t)
6712 (setq end (point))
6713 (setq template (buffer-substring beg end))
6714 (when (and doshift
6715 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6716 (delete-region beg end)
6717 (setq end beg)
6718 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6719 (goto-char end)
6720 (loop for n from nmin to nmax do
6721 (if (not doshift)
6722 (setq task template)
6723 (with-temp-buffer
6724 (insert template)
6725 (org-mode)
6726 (goto-char (point-min))
6727 (while (re-search-forward org-ts-regexp-both nil t)
6728 (org-timestamp-change (* n shift-n) shift-what))
6729 (unless (= n n-no-remove)
6730 (goto-char (point-min))
6731 (while (re-search-forward org-ts-regexp nil t)
6732 (save-excursion
6733 (goto-char (match-beginning 0))
6734 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6735 (delete-region (match-beginning 1) (match-end 1))))))
6736 (setq task (buffer-string))))
6737 (insert task))
6738 (goto-char beg)))
6740 ;;; Outline Sorting
6742 (defun org-sort (with-case)
6743 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6744 Optional argument WITH-CASE means sort case-sensitively.
6745 With a double prefix argument, also remove duplicate entries."
6746 (interactive "P")
6747 (if (org-at-table-p)
6748 (org-call-with-arg 'org-table-sort-lines with-case)
6749 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6751 (defun org-sort-remove-invisible (s)
6752 (remove-text-properties 0 (length s) org-rm-props s)
6753 (while (string-match org-bracket-link-regexp s)
6754 (setq s (replace-match (if (match-end 2)
6755 (match-string 3 s)
6756 (match-string 1 s)) t t s)))
6759 (defvar org-priority-regexp) ; defined later in the file
6761 (defvar org-after-sorting-entries-or-items-hook nil
6762 "Hook that is run after a bunch of entries or items have been sorted.
6763 When children are sorted, the cursor is in the parent line when this
6764 hook gets called. When a region or a plain list is sorted, the cursor
6765 will be in the first entry of the sorted region/list.")
6767 (defun org-sort-entries-or-items
6768 (&optional with-case sorting-type getkey-func compare-func property)
6769 "Sort entries on a certain level of an outline tree, or plain list items.
6770 If there is an active region, the entries in the region are sorted.
6771 Else, if the cursor is before the first entry, sort the top-level items.
6772 Else, the children of the entry at point are sorted.
6773 If the cursor is at the first item in a plain list, the list items will be
6774 sorted.
6776 Sorting can be alphabetically, numerically, by date/time as given by
6777 a time stamp, by a property or by priority.
6779 The command prompts for the sorting type unless it has been given to the
6780 function through the SORTING-TYPE argument, which needs to a character,
6781 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6782 precise meaning of each character:
6784 n Numerically, by converting the beginning of the entry/item to a number.
6785 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6786 t By date/time, either the first active time stamp in the entry, or, if
6787 none exist, by the first inactive one.
6788 In items, only the first line will be chekced.
6789 s By the scheduled date/time.
6790 d By deadline date/time.
6791 c By creation time, which is assumed to be the first inactive time stamp
6792 at the beginning of a line.
6793 p By priority according to the cookie.
6794 r By the value of a property.
6796 Capital letters will reverse the sort order.
6798 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6799 called with point at the beginning of the record. It must return either
6800 a string or a number that should serve as the sorting key for that record.
6802 Comparing entries ignores case by default. However, with an optional argument
6803 WITH-CASE, the sorting considers case as well."
6804 (interactive "P")
6805 (let ((case-func (if with-case 'identity 'downcase))
6806 start beg end stars re re2
6807 txt what tmp plain-list-p)
6808 ;; Find beginning and end of region to sort
6809 (cond
6810 ((org-region-active-p)
6811 ;; we will sort the region
6812 (setq end (region-end)
6813 what "region")
6814 (goto-char (region-beginning))
6815 (if (not (org-on-heading-p)) (outline-next-heading))
6816 (setq start (point)))
6817 ((org-at-item-p)
6818 ;; we will sort this plain list
6819 (org-beginning-of-item-list) (setq start (point))
6820 (org-end-of-item-list) (setq end (point))
6821 (goto-char start)
6822 (setq plain-list-p t
6823 what "plain list"))
6824 ((or (org-on-heading-p)
6825 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6826 ;; we will sort the children of the current headline
6827 (org-back-to-heading)
6828 (setq start (point)
6829 end (progn (org-end-of-subtree t t)
6830 (org-back-over-empty-lines)
6831 (point))
6832 what "children")
6833 (goto-char start)
6834 (show-subtree)
6835 (outline-next-heading))
6837 ;; we will sort the top-level entries in this file
6838 (goto-char (point-min))
6839 (or (org-on-heading-p) (outline-next-heading))
6840 (setq start (point) end (point-max) what "top-level")
6841 (goto-char start)
6842 (show-all)))
6844 (setq beg (point))
6845 (if (>= beg end) (error "Nothing to sort"))
6847 (unless plain-list-p
6848 (looking-at "\\(\\*+\\)")
6849 (setq stars (match-string 1)
6850 re (concat "^" (regexp-quote stars) " +")
6851 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6852 txt (buffer-substring beg end))
6853 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6854 (if (and (not (equal stars "*")) (string-match re2 txt))
6855 (error "Region to sort contains a level above the first entry")))
6857 (unless sorting-type
6858 (message
6859 (if plain-list-p
6860 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6861 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6862 [t]ime [s]cheduled [d]eadline [c]reated
6863 A/N/T/S/D/C/P/O/F means reversed:")
6864 what)
6865 (setq sorting-type (read-char-exclusive))
6867 (and (= (downcase sorting-type) ?f)
6868 (setq getkey-func
6869 (org-icompleting-read "Sort using function: "
6870 obarray 'fboundp t nil nil))
6871 (setq getkey-func (intern getkey-func)))
6873 (and (= (downcase sorting-type) ?r)
6874 (setq property
6875 (org-icompleting-read "Property: "
6876 (mapcar 'list (org-buffer-property-keys t))
6877 nil t))))
6879 (message "Sorting entries...")
6881 (save-restriction
6882 (narrow-to-region start end)
6884 (let ((dcst (downcase sorting-type))
6885 (case-fold-search nil)
6886 (now (current-time)))
6887 (sort-subr
6888 (/= dcst sorting-type)
6889 ;; This function moves to the beginning character of the "record" to
6890 ;; be sorted.
6891 (if plain-list-p
6892 (lambda nil
6893 (if (org-at-item-p) t (goto-char (point-max))))
6894 (lambda nil
6895 (if (re-search-forward re nil t)
6896 (goto-char (match-beginning 0))
6897 (goto-char (point-max)))))
6898 ;; This function moves to the last character of the "record" being
6899 ;; sorted.
6900 (if plain-list-p
6901 'org-end-of-item
6902 (lambda nil
6903 (save-match-data
6904 (condition-case nil
6905 (outline-forward-same-level 1)
6906 (error
6907 (goto-char (point-max)))))))
6909 ;; This function returns the value that gets sorted against.
6910 (if plain-list-p
6911 (lambda nil
6912 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6913 (cond
6914 ((= dcst ?n)
6915 (string-to-number (buffer-substring (match-end 0)
6916 (point-at-eol))))
6917 ((= dcst ?a)
6918 (buffer-substring (match-end 0) (point-at-eol)))
6919 ((= dcst ?t)
6920 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6921 (re-search-forward org-ts-regexp-both
6922 (point-at-eol) t))
6923 (org-time-string-to-seconds (match-string 0))
6924 (org-float-time now)))
6925 ((= dcst ?f)
6926 (if getkey-func
6927 (progn
6928 (setq tmp (funcall getkey-func))
6929 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6930 tmp)
6931 (error "Invalid key function `%s'" getkey-func)))
6932 (t (error "Invalid sorting type `%c'" sorting-type)))))
6933 (lambda nil
6934 (cond
6935 ((= dcst ?n)
6936 (if (looking-at org-complex-heading-regexp)
6937 (string-to-number (match-string 4))
6938 nil))
6939 ((= dcst ?a)
6940 (if (looking-at org-complex-heading-regexp)
6941 (funcall case-func (match-string 4))
6942 nil))
6943 ((= dcst ?t)
6944 (let ((end (save-excursion (outline-next-heading) (point))))
6945 (if (or (re-search-forward org-ts-regexp end t)
6946 (re-search-forward org-ts-regexp-both end t))
6947 (org-time-string-to-seconds (match-string 0))
6948 (org-float-time now))))
6949 ((= dcst ?c)
6950 (let ((end (save-excursion (outline-next-heading) (point))))
6951 (if (re-search-forward
6952 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6953 end t)
6954 (org-time-string-to-seconds (match-string 0))
6955 (org-float-time now))))
6956 ((= dcst ?s)
6957 (let ((end (save-excursion (outline-next-heading) (point))))
6958 (if (re-search-forward org-scheduled-time-regexp end t)
6959 (org-time-string-to-seconds (match-string 1))
6960 (org-float-time now))))
6961 ((= dcst ?d)
6962 (let ((end (save-excursion (outline-next-heading) (point))))
6963 (if (re-search-forward org-deadline-time-regexp end t)
6964 (org-time-string-to-seconds (match-string 1))
6965 (org-float-time now))))
6966 ((= dcst ?p)
6967 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6968 (string-to-char (match-string 2))
6969 org-default-priority))
6970 ((= dcst ?r)
6971 (or (org-entry-get nil property) ""))
6972 ((= dcst ?o)
6973 (if (looking-at org-complex-heading-regexp)
6974 (- 9999 (length (member (match-string 2)
6975 org-todo-keywords-1)))))
6976 ((= dcst ?f)
6977 (if getkey-func
6978 (progn
6979 (setq tmp (funcall getkey-func))
6980 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6981 tmp)
6982 (error "Invalid key function `%s'" getkey-func)))
6983 (t (error "Invalid sorting type `%c'" sorting-type)))))
6985 (cond
6986 ((= dcst ?a) 'string<)
6987 ((= dcst ?f) compare-func)
6988 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6989 (t nil)))))
6990 (run-hooks 'org-after-sorting-entries-or-items-hook)
6991 (message "Sorting entries...done")))
6993 (defun org-do-sort (table what &optional with-case sorting-type)
6994 "Sort TABLE of WHAT according to SORTING-TYPE.
6995 The user will be prompted for the SORTING-TYPE if the call to this
6996 function does not specify it. WHAT is only for the prompt, to indicate
6997 what is being sorted. The sorting key will be extracted from
6998 the car of the elements of the table.
6999 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7000 (unless sorting-type
7001 (message
7002 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7003 what)
7004 (setq sorting-type (read-char-exclusive)))
7005 (let ((dcst (downcase sorting-type))
7006 extractfun comparefun)
7007 ;; Define the appropriate functions
7008 (cond
7009 ((= dcst ?n)
7010 (setq extractfun 'string-to-number
7011 comparefun (if (= dcst sorting-type) '< '>)))
7012 ((= dcst ?a)
7013 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7014 (lambda(x) (downcase (org-sort-remove-invisible x))))
7015 comparefun (if (= dcst sorting-type)
7016 'string<
7017 (lambda (a b) (and (not (string< a b))
7018 (not (string= a b)))))))
7019 ((= dcst ?t)
7020 (setq extractfun
7021 (lambda (x)
7022 (if (or (string-match org-ts-regexp x)
7023 (string-match org-ts-regexp-both x))
7024 (org-float-time
7025 (org-time-string-to-time (match-string 0 x)))
7027 comparefun (if (= dcst sorting-type) '< '>)))
7028 (t (error "Invalid sorting type `%c'" sorting-type)))
7030 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7031 table)
7032 (lambda (a b) (funcall comparefun (car a) (car b))))))
7035 ;;; The orgstruct minor mode
7037 ;; Define a minor mode which can be used in other modes in order to
7038 ;; integrate the org-mode structure editing commands.
7040 ;; This is really a hack, because the org-mode structure commands use
7041 ;; keys which normally belong to the major mode. Here is how it
7042 ;; works: The minor mode defines all the keys necessary to operate the
7043 ;; structure commands, but wraps the commands into a function which
7044 ;; tests if the cursor is currently at a headline or a plain list
7045 ;; item. If that is the case, the structure command is used,
7046 ;; temporarily setting many Org-mode variables like regular
7047 ;; expressions for filling etc. However, when any of those keys is
7048 ;; used at a different location, function uses `key-binding' to look
7049 ;; up if the key has an associated command in another currently active
7050 ;; keymap (minor modes, major mode, global), and executes that
7051 ;; command. There might be problems if any of the keys is otherwise
7052 ;; used as a prefix key.
7054 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7055 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7056 ;; addresses this by checking explicitly for both bindings.
7058 (defvar orgstruct-mode-map (make-sparse-keymap)
7059 "Keymap for the minor `orgstruct-mode'.")
7061 (defvar org-local-vars nil
7062 "List of local variables, for use by `orgstruct-mode'")
7064 ;;;###autoload
7065 (define-minor-mode orgstruct-mode
7066 "Toggle the minor more `orgstruct-mode'.
7067 This mode is for using Org-mode structure commands in other modes.
7068 The following key behave as if Org-mode was active, if the cursor
7069 is on a headline, or on a plain list item (both in the definition
7070 of Org-mode).
7072 M-up Move entry/item up
7073 M-down Move entry/item down
7074 M-left Promote
7075 M-right Demote
7076 M-S-up Move entry/item up
7077 M-S-down Move entry/item down
7078 M-S-left Promote subtree
7079 M-S-right Demote subtree
7080 M-q Fill paragraph and items like in Org-mode
7081 C-c ^ Sort entries
7082 C-c - Cycle list bullet
7083 TAB Cycle item visibility
7084 M-RET Insert new heading/item
7085 S-M-RET Insert new TODO heading / Checkbox item
7086 C-c C-c Set tags / toggle checkbox"
7087 nil " OrgStruct" nil
7088 (org-load-modules-maybe)
7089 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7091 ;;;###autoload
7092 (defun turn-on-orgstruct ()
7093 "Unconditionally turn on `orgstruct-mode'."
7094 (orgstruct-mode 1))
7096 (defun orgstruct++-mode (&optional arg)
7097 "Toggle `orgstruct-mode', the enhanced version of it.
7098 In addition to setting orgstruct-mode, this also exports all indentation
7099 and autofilling variables from org-mode into the buffer. It will also
7100 recognize item context in multiline items.
7101 Note that turning off orgstruct-mode will *not* remove the
7102 indentation/paragraph settings. This can only be done by refreshing the
7103 major mode, for example with \\[normal-mode]."
7104 (interactive "P")
7105 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7106 (if (< arg 1)
7107 (orgstruct-mode -1)
7108 (orgstruct-mode 1)
7109 (let (var val)
7110 (mapc
7111 (lambda (x)
7112 (when (string-match
7113 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7114 (symbol-name (car x)))
7115 (setq var (car x) val (nth 1 x))
7116 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7117 org-local-vars)
7118 (org-set-local 'orgstruct-is-++ t))))
7120 (defvar orgstruct-is-++ nil
7121 "Is orgstruct-mode in ++ version in the current-buffer?")
7122 (make-variable-buffer-local 'orgstruct-is-++)
7124 ;;;###autoload
7125 (defun turn-on-orgstruct++ ()
7126 "Unconditionally turn on `orgstruct++-mode'."
7127 (orgstruct++-mode 1))
7129 (defun orgstruct-error ()
7130 "Error when there is no default binding for a structure key."
7131 (interactive)
7132 (error "This key has no function outside structure elements"))
7134 (defun orgstruct-setup ()
7135 "Setup orgstruct keymaps."
7136 (let ((nfunc 0)
7137 (bindings
7138 (list
7139 '([(meta up)] org-metaup)
7140 '([(meta down)] org-metadown)
7141 '([(meta left)] org-metaleft)
7142 '([(meta right)] org-metaright)
7143 '([(meta shift up)] org-shiftmetaup)
7144 '([(meta shift down)] org-shiftmetadown)
7145 '([(meta shift left)] org-shiftmetaleft)
7146 '([(meta shift right)] org-shiftmetaright)
7147 '([?\e (up)] org-metaup)
7148 '([?\e (down)] org-metadown)
7149 '([?\e (left)] org-metaleft)
7150 '([?\e (right)] org-metaright)
7151 '([?\e (shift up)] org-shiftmetaup)
7152 '([?\e (shift down)] org-shiftmetadown)
7153 '([?\e (shift left)] org-shiftmetaleft)
7154 '([?\e (shift right)] org-shiftmetaright)
7155 '([(shift up)] org-shiftup)
7156 '([(shift down)] org-shiftdown)
7157 '([(shift left)] org-shiftleft)
7158 '([(shift right)] org-shiftright)
7159 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7160 '("\M-q" fill-paragraph)
7161 '("\C-c^" org-sort)
7162 '("\C-c-" org-cycle-list-bullet)))
7163 elt key fun cmd)
7164 (while (setq elt (pop bindings))
7165 (setq nfunc (1+ nfunc))
7166 (setq key (org-key (car elt))
7167 fun (nth 1 elt)
7168 cmd (orgstruct-make-binding fun nfunc key))
7169 (org-defkey orgstruct-mode-map key cmd))
7171 ;; Special treatment needed for TAB and RET
7172 (org-defkey orgstruct-mode-map [(tab)]
7173 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7174 (org-defkey orgstruct-mode-map "\C-i"
7175 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7177 (org-defkey orgstruct-mode-map "\M-\C-m"
7178 (orgstruct-make-binding 'org-insert-heading 105
7179 "\M-\C-m" [(meta return)]))
7180 (org-defkey orgstruct-mode-map [(meta return)]
7181 (orgstruct-make-binding 'org-insert-heading 106
7182 [(meta return)] "\M-\C-m"))
7184 (org-defkey orgstruct-mode-map [(shift meta return)]
7185 (orgstruct-make-binding 'org-insert-todo-heading 107
7186 [(meta return)] "\M-\C-m"))
7188 (org-defkey orgstruct-mode-map "\e\C-m"
7189 (orgstruct-make-binding 'org-insert-heading 108
7190 "\e\C-m" [?\e (return)]))
7191 (org-defkey orgstruct-mode-map [?\e (return)]
7192 (orgstruct-make-binding 'org-insert-heading 109
7193 [?\e (return)] "\e\C-m"))
7194 (org-defkey orgstruct-mode-map [?\e (shift return)]
7195 (orgstruct-make-binding 'org-insert-todo-heading 110
7196 [?\e (return)] "\e\C-m"))
7198 (unless org-local-vars
7199 (setq org-local-vars (org-get-local-variables)))
7203 (defun orgstruct-make-binding (fun n &rest keys)
7204 "Create a function for binding in the structure minor mode.
7205 FUN is the command to call inside a table. N is used to create a unique
7206 command name. KEYS are keys that should be checked in for a command
7207 to execute outside of tables."
7208 (eval
7209 (list 'defun
7210 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7211 '(arg)
7212 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7213 "Outside of structure, run the binding of `"
7214 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7215 "'.")
7216 '(interactive "p")
7217 (list 'if
7218 `(org-context-p 'headline 'item
7219 (and orgstruct-is-++
7220 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7221 'item-body))
7222 (list 'org-run-like-in-org-mode (list 'quote fun))
7223 (list 'let '(orgstruct-mode)
7224 (list 'call-interactively
7225 (append '(or)
7226 (mapcar (lambda (k)
7227 (list 'key-binding k))
7228 keys)
7229 '('orgstruct-error))))))))
7231 (defun org-context-p (&rest contexts)
7232 "Check if local context is any of CONTEXTS.
7233 Possible values in the list of contexts are `table', `headline', and `item'."
7234 (let ((pos (point)))
7235 (goto-char (point-at-bol))
7236 (prog1 (or (and (memq 'table contexts)
7237 (looking-at "[ \t]*|"))
7238 (and (memq 'headline contexts)
7239 ;;????????? (looking-at "\\*+"))
7240 (looking-at outline-regexp))
7241 (and (memq 'item contexts)
7242 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7243 (and (memq 'item-body contexts)
7244 (org-in-item-p)))
7245 (goto-char pos))))
7247 (defun org-get-local-variables ()
7248 "Return a list of all local variables in an org-mode buffer."
7249 (let (varlist)
7250 (with-current-buffer (get-buffer-create "*Org tmp*")
7251 (erase-buffer)
7252 (org-mode)
7253 (setq varlist (buffer-local-variables)))
7254 (kill-buffer "*Org tmp*")
7255 (delq nil
7256 (mapcar
7257 (lambda (x)
7258 (setq x
7259 (if (symbolp x)
7260 (list x)
7261 (list (car x) (list 'quote (cdr x)))))
7262 (if (string-match
7263 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7264 (symbol-name (car x)))
7265 x nil))
7266 varlist))))
7268 ;;;###autoload
7269 (defun org-run-like-in-org-mode (cmd)
7270 "Run a command, pretending that the current buffer is in Org-mode.
7271 This will temporarily bind local variables that are typically bound in
7272 Org-mode to the values they have in Org-mode, and then interactively
7273 call CMD."
7274 (org-load-modules-maybe)
7275 (unless org-local-vars
7276 (setq org-local-vars (org-get-local-variables)))
7277 (eval (list 'let org-local-vars
7278 (list 'call-interactively (list 'quote cmd)))))
7280 ;;;; Archiving
7282 (defun org-get-category (&optional pos)
7283 "Get the category applying to position POS."
7284 (get-text-property (or pos (point)) 'org-category))
7286 (defun org-refresh-category-properties ()
7287 "Refresh category text properties in the buffer."
7288 (let ((def-cat (cond
7289 ((null org-category)
7290 (if buffer-file-name
7291 (file-name-sans-extension
7292 (file-name-nondirectory buffer-file-name))
7293 "???"))
7294 ((symbolp org-category) (symbol-name org-category))
7295 (t org-category)))
7296 beg end cat pos optionp)
7297 (org-unmodified
7298 (save-excursion
7299 (save-restriction
7300 (widen)
7301 (goto-char (point-min))
7302 (put-text-property (point) (point-max) 'org-category def-cat)
7303 (while (re-search-forward
7304 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7305 (setq pos (match-end 0)
7306 optionp (equal (char-after (match-beginning 0)) ?#)
7307 cat (org-trim (match-string 2)))
7308 (if optionp
7309 (setq beg (point-at-bol) end (point-max))
7310 (org-back-to-heading t)
7311 (setq beg (point) end (org-end-of-subtree t t)))
7312 (put-text-property beg end 'org-category cat)
7313 (goto-char pos)))))))
7316 ;;;; Link Stuff
7318 ;;; Link abbreviations
7320 (defun org-link-expand-abbrev (link)
7321 "Apply replacements as defined in `org-link-abbrev-alist."
7322 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7323 (let* ((key (match-string 1 link))
7324 (as (or (assoc key org-link-abbrev-alist-local)
7325 (assoc key org-link-abbrev-alist)))
7326 (tag (and (match-end 2) (match-string 3 link)))
7327 rpl)
7328 (if (not as)
7329 link
7330 (setq rpl (cdr as))
7331 (cond
7332 ((symbolp rpl) (funcall rpl tag))
7333 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7334 ((string-match "%h" rpl)
7335 (replace-match (url-hexify-string (or tag "")) t t rpl))
7336 (t (concat rpl tag)))))
7337 link))
7339 ;;; Storing and inserting links
7341 (defvar org-insert-link-history nil
7342 "Minibuffer history for links inserted with `org-insert-link'.")
7344 (defvar org-stored-links nil
7345 "Contains the links stored with `org-store-link'.")
7347 (defvar org-store-link-plist nil
7348 "Plist with info about the most recently link created with `org-store-link'.")
7350 (defvar org-link-protocols nil
7351 "Link protocols added to Org-mode using `org-add-link-type'.")
7353 (defvar org-store-link-functions nil
7354 "List of functions that are called to create and store a link.
7355 Each function will be called in turn until one returns a non-nil
7356 value. Each function should check if it is responsible for creating
7357 this link (for example by looking at the major mode).
7358 If not, it must exit and return nil.
7359 If yes, it should return a non-nil value after a calling
7360 `org-store-link-props' with a list of properties and values.
7361 Special properties are:
7363 :type The link prefix. like \"http\". This must be given.
7364 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7365 This is obligatory as well.
7366 :description Optional default description for the second pair
7367 of brackets in an Org-mode link. The user can still change
7368 this when inserting this link into an Org-mode buffer.
7370 In addition to these, any additional properties can be specified
7371 and then used in remember templates.")
7373 (defun org-add-link-type (type &optional follow export)
7374 "Add TYPE to the list of `org-link-types'.
7375 Re-compute all regular expressions depending on `org-link-types'
7377 FOLLOW and EXPORT are two functions.
7379 FOLLOW should take the link path as the single argument and do whatever
7380 is necessary to follow the link, for example find a file or display
7381 a mail message.
7383 EXPORT should format the link path for export to one of the export formats.
7384 It should be a function accepting three arguments:
7386 path the path of the link, the text after the prefix (like \"http:\")
7387 desc the description of the link, if any, nil if there was no description
7388 format the export format, a symbol like `html' or `latex'.
7390 The function may use the FORMAT information to return different values
7391 depending on the format. The return value will be put literally into
7392 the exported file.
7393 Org-mode has a built-in default for exporting links. If you are happy with
7394 this default, there is no need to define an export function for the link
7395 type. For a simple example of an export function, see `org-bbdb.el'."
7396 (add-to-list 'org-link-types type t)
7397 (org-make-link-regexps)
7398 (if (assoc type org-link-protocols)
7399 (setcdr (assoc type org-link-protocols) (list follow export))
7400 (push (list type follow export) org-link-protocols)))
7402 (defvar org-agenda-buffer-name)
7404 ;;;###autoload
7405 (defun org-store-link (arg)
7406 "\\<org-mode-map>Store an org-link to the current location.
7407 This link is added to `org-stored-links' and can later be inserted
7408 into an org-buffer with \\[org-insert-link].
7410 For some link types, a prefix arg is interpreted:
7411 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7412 For file links, arg negates `org-context-in-file-links'."
7413 (interactive "P")
7414 (org-load-modules-maybe)
7415 (setq org-store-link-plist nil) ; reset
7416 (let ((outline-regexp (org-get-limited-outline-regexp))
7417 link cpltxt desc description search txt custom-id)
7418 (cond
7420 ((run-hook-with-args-until-success 'org-store-link-functions)
7421 (setq link (plist-get org-store-link-plist :link)
7422 desc (or (plist-get org-store-link-plist :description) link)))
7424 ((equal (buffer-name) "*Org Edit Src Example*")
7425 (let (label gc)
7426 (while (or (not label)
7427 (save-excursion
7428 (save-restriction
7429 (widen)
7430 (goto-char (point-min))
7431 (re-search-forward
7432 (regexp-quote (format org-coderef-label-format label))
7433 nil t))))
7434 (when label (message "Label exists already") (sit-for 2))
7435 (setq label (read-string "Code line label: " label)))
7436 (end-of-line 1)
7437 (setq link (format org-coderef-label-format label))
7438 (setq gc (- 79 (length link)))
7439 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7440 (insert link)
7441 (setq link (concat "(" label ")") desc nil)))
7443 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7444 ;; We are in the agenda, link to referenced location
7445 (let ((m (or (get-text-property (point) 'org-hd-marker)
7446 (get-text-property (point) 'org-marker))))
7447 (when m
7448 (org-with-point-at m
7449 (call-interactively 'org-store-link)))))
7451 ((eq major-mode 'calendar-mode)
7452 (let ((cd (calendar-cursor-to-date)))
7453 (setq link
7454 (format-time-string
7455 (car org-time-stamp-formats)
7456 (apply 'encode-time
7457 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7458 nil nil nil))))
7459 (org-store-link-props :type "calendar" :date cd)))
7461 ((eq major-mode 'w3-mode)
7462 (setq cpltxt (if (and (buffer-name)
7463 (not (string-match "Untitled" (buffer-name))))
7464 (buffer-name)
7465 (url-view-url t))
7466 link (org-make-link (url-view-url t)))
7467 (org-store-link-props :type "w3" :url (url-view-url t)))
7469 ((eq major-mode 'w3m-mode)
7470 (setq cpltxt (or w3m-current-title w3m-current-url)
7471 link (org-make-link w3m-current-url))
7472 (org-store-link-props :type "w3m" :url (url-view-url t)))
7474 ((setq search (run-hook-with-args-until-success
7475 'org-create-file-search-functions))
7476 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7477 "::" search))
7478 (setq cpltxt (or description link)))
7480 ((eq major-mode 'image-mode)
7481 (setq cpltxt (concat "file:"
7482 (abbreviate-file-name buffer-file-name))
7483 link (org-make-link cpltxt))
7484 (org-store-link-props :type "image" :file buffer-file-name))
7486 ((eq major-mode 'dired-mode)
7487 ;; link to the file in the current line
7488 (setq cpltxt (concat "file:"
7489 (abbreviate-file-name
7490 (expand-file-name
7491 (dired-get-filename nil t))))
7492 link (org-make-link cpltxt)))
7494 ((and buffer-file-name (org-mode-p))
7495 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7496 (cond
7497 ((org-in-regexp "<<\\(.*?\\)>>")
7498 (setq cpltxt
7499 (concat "file:"
7500 (abbreviate-file-name buffer-file-name)
7501 "::" (match-string 1))
7502 link (org-make-link cpltxt)))
7503 ((and (featurep 'org-id)
7504 (or (eq org-link-to-org-use-id t)
7505 (and (eq org-link-to-org-use-id 'create-if-interactive)
7506 (interactive-p))
7507 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7508 (interactive-p)
7509 (not custom-id))
7510 (and org-link-to-org-use-id
7511 (condition-case nil
7512 (org-entry-get nil "ID")
7513 (error nil)))))
7514 ;; We can make a link using the ID.
7515 (setq link (condition-case nil
7516 (prog1 (org-id-store-link)
7517 (setq desc (plist-get org-store-link-plist
7518 :description)))
7519 (error
7520 ;; probably before first headline, link to file only
7521 (concat "file:"
7522 (abbreviate-file-name buffer-file-name))))))
7524 ;; Just link to current headline
7525 (setq cpltxt (concat "file:"
7526 (abbreviate-file-name buffer-file-name)))
7527 ;; Add a context search string
7528 (when (org-xor org-context-in-file-links arg)
7529 (setq txt (cond
7530 ((org-on-heading-p) nil)
7531 ((org-region-active-p)
7532 (buffer-substring (region-beginning) (region-end)))
7533 (t nil)))
7534 (when (or (null txt) (string-match "\\S-" txt))
7535 (setq cpltxt
7536 (concat cpltxt "::"
7537 (condition-case nil
7538 (org-make-org-heading-search-string txt)
7539 (error "")))
7540 desc (or (nth 4 (ignore-errors
7541 (org-heading-components))) "NONE"))))
7542 (if (string-match "::\\'" cpltxt)
7543 (setq cpltxt (substring cpltxt 0 -2)))
7544 (setq link (org-make-link cpltxt)))))
7546 ((buffer-file-name (buffer-base-buffer))
7547 ;; Just link to this file here.
7548 (setq cpltxt (concat "file:"
7549 (abbreviate-file-name
7550 (buffer-file-name (buffer-base-buffer)))))
7551 ;; Add a context string
7552 (when (org-xor org-context-in-file-links arg)
7553 (setq txt (if (org-region-active-p)
7554 (buffer-substring (region-beginning) (region-end))
7555 (buffer-substring (point-at-bol) (point-at-eol))))
7556 ;; Only use search option if there is some text.
7557 (when (string-match "\\S-" txt)
7558 (setq cpltxt
7559 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7560 desc "NONE")))
7561 (setq link (org-make-link cpltxt)))
7563 ((interactive-p)
7564 (error "Cannot link to a buffer which is not visiting a file"))
7566 (t (setq link nil)))
7568 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7569 (setq link (or link cpltxt)
7570 desc (or desc cpltxt))
7571 (if (equal desc "NONE") (setq desc nil))
7573 (if (and (or (interactive-p) executing-kbd-macro) link)
7574 (progn
7575 (setq org-stored-links
7576 (cons (list link desc) org-stored-links))
7577 (message "Stored: %s" (or desc link))
7578 (when custom-id
7579 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7580 "::#" custom-id))
7581 (setq org-stored-links
7582 (cons (list link desc) org-stored-links))))
7583 (and link (org-make-link-string link desc)))))
7585 (defun org-store-link-props (&rest plist)
7586 "Store link properties, extract names and addresses."
7587 (let (x adr)
7588 (when (setq x (plist-get plist :from))
7589 (setq adr (mail-extract-address-components x))
7590 (setq plist (plist-put plist :fromname (car adr)))
7591 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7592 (when (setq x (plist-get plist :to))
7593 (setq adr (mail-extract-address-components x))
7594 (setq plist (plist-put plist :toname (car adr)))
7595 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7596 (let ((from (plist-get plist :from))
7597 (to (plist-get plist :to)))
7598 (when (and from to org-from-is-user-regexp)
7599 (setq plist
7600 (plist-put plist :fromto
7601 (if (string-match org-from-is-user-regexp from)
7602 (concat "to %t")
7603 (concat "from %f"))))))
7604 (setq org-store-link-plist plist))
7606 (defun org-add-link-props (&rest plist)
7607 "Add these properties to the link property list."
7608 (let (key value)
7609 (while plist
7610 (setq key (pop plist) value (pop plist))
7611 (setq org-store-link-plist
7612 (plist-put org-store-link-plist key value)))))
7614 (defun org-email-link-description (&optional fmt)
7615 "Return the description part of an email link.
7616 This takes information from `org-store-link-plist' and formats it
7617 according to FMT (default from `org-email-link-description-format')."
7618 (setq fmt (or fmt org-email-link-description-format))
7619 (let* ((p org-store-link-plist)
7620 (to (plist-get p :toaddress))
7621 (from (plist-get p :fromaddress))
7622 (table
7623 (list
7624 (cons "%c" (plist-get p :fromto))
7625 (cons "%F" (plist-get p :from))
7626 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7627 (cons "%T" (plist-get p :to))
7628 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7629 (cons "%s" (plist-get p :subject))
7630 (cons "%m" (plist-get p :message-id)))))
7631 (when (string-match "%c" fmt)
7632 ;; Check if the user wrote this message
7633 (if (and org-from-is-user-regexp from to
7634 (save-match-data (string-match org-from-is-user-regexp from)))
7635 (setq fmt (replace-match "to %t" t t fmt))
7636 (setq fmt (replace-match "from %f" t t fmt))))
7637 (org-replace-escapes fmt table)))
7639 (defun org-make-org-heading-search-string (&optional string heading)
7640 "Make search string for STRING or current headline."
7641 (interactive)
7642 (let ((s (or string (org-get-heading))))
7643 (unless (and string (not heading))
7644 ;; We are using a headline, clean up garbage in there.
7645 (if (string-match org-todo-regexp s)
7646 (setq s (replace-match "" t t s)))
7647 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7648 (setq s (replace-match "" t t s)))
7649 (setq s (org-trim s))
7650 (if (string-match (concat "^\\(" org-quote-string "\\|"
7651 org-comment-string "\\)") s)
7652 (setq s (replace-match "" t t s)))
7653 (while (string-match org-ts-regexp s)
7654 (setq s (replace-match "" t t s))))
7655 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7656 (setq s (replace-match " " t t s)))
7657 (or string (setq s (concat "*" s))) ; Add * for headlines
7658 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7660 (defun org-make-link (&rest strings)
7661 "Concatenate STRINGS."
7662 (apply 'concat strings))
7664 (defun org-make-link-string (link &optional description)
7665 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7666 (unless (string-match "\\S-" link)
7667 (error "Empty link"))
7668 (when (stringp description)
7669 ;; Remove brackets from the description, they are fatal.
7670 (while (string-match "\\[" description)
7671 (setq description (replace-match "{" t t description)))
7672 (while (string-match "\\]" description)
7673 (setq description (replace-match "}" t t description))))
7674 (when (equal (org-link-escape link) description)
7675 ;; No description needed, it is identical
7676 (setq description nil))
7677 (when (and (not description)
7678 (not (equal link (org-link-escape link))))
7679 (setq description (org-extract-attributes link)))
7680 (concat "[[" (org-link-escape link) "]"
7681 (if description (concat "[" description "]") "")
7682 "]"))
7684 (defconst org-link-escape-chars
7685 '((?\ . "%20")
7686 (?\[ . "%5B")
7687 (?\] . "%5D")
7688 (?\340 . "%E0") ; `a
7689 (?\342 . "%E2") ; ^a
7690 (?\347 . "%E7") ; ,c
7691 (?\350 . "%E8") ; `e
7692 (?\351 . "%E9") ; 'e
7693 (?\352 . "%EA") ; ^e
7694 (?\356 . "%EE") ; ^i
7695 (?\364 . "%F4") ; ^o
7696 (?\371 . "%F9") ; `u
7697 (?\373 . "%FB") ; ^u
7698 (?\; . "%3B")
7699 (?? . "%3F")
7700 (?= . "%3D")
7701 (?+ . "%2B")
7703 "Association list of escapes for some characters problematic in links.
7704 This is the list that is used for internal purposes.")
7706 (defvar org-url-encoding-use-url-hexify nil)
7708 (defconst org-link-escape-chars-browser
7709 '((?\ . "%20")) ; 32 for the SPC char
7710 "Association list of escapes for some characters problematic in links.
7711 This is the list that is used before handing over to the browser.")
7713 (defun org-link-escape (text &optional table)
7714 "Escape characters in TEXT that are problematic for links."
7715 (if org-url-encoding-use-url-hexify
7716 (url-hexify-string text)
7717 (setq table (or table org-link-escape-chars))
7718 (when text
7719 (let ((re (mapconcat (lambda (x) (regexp-quote
7720 (char-to-string (car x))))
7721 table "\\|")))
7722 (while (string-match re text)
7723 (setq text
7724 (replace-match
7725 (cdr (assoc (string-to-char (match-string 0 text))
7726 table))
7727 t t text)))
7728 text))))
7730 (defun org-link-unescape (text &optional table)
7731 "Reverse the action of `org-link-escape'."
7732 (if org-url-encoding-use-url-hexify
7733 (url-unhex-string text)
7734 (setq table (or table org-link-escape-chars))
7735 (when text
7736 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7737 table "\\|")))
7738 (while (string-match re text)
7739 (setq text
7740 (replace-match
7741 (char-to-string (car (rassoc (match-string 0 text) table)))
7742 t t text)))
7743 text))))
7745 (defun org-xor (a b)
7746 "Exclusive or."
7747 (if a (not b) b))
7749 (defun org-fixup-message-id-for-http (s)
7750 "Replace special characters in a message id, so it can be used in an http query."
7751 (while (string-match "<" s)
7752 (setq s (replace-match "%3C" t t s)))
7753 (while (string-match ">" s)
7754 (setq s (replace-match "%3E" t t s)))
7755 (while (string-match "@" s)
7756 (setq s (replace-match "%40" t t s)))
7759 ;;;###autoload
7760 (defun org-insert-link-global ()
7761 "Insert a link like Org-mode does.
7762 This command can be called in any mode to insert a link in Org-mode syntax."
7763 (interactive)
7764 (org-load-modules-maybe)
7765 (org-run-like-in-org-mode 'org-insert-link))
7767 (defun org-insert-link (&optional complete-file link-location)
7768 "Insert a link. At the prompt, enter the link.
7770 Completion can be used to insert any of the link protocol prefixes like
7771 http or ftp in use.
7773 The history can be used to select a link previously stored with
7774 `org-store-link'. When the empty string is entered (i.e. if you just
7775 press RET at the prompt), the link defaults to the most recently
7776 stored link. As SPC triggers completion in the minibuffer, you need to
7777 use M-SPC or C-q SPC to force the insertion of a space character.
7779 You will also be prompted for a description, and if one is given, it will
7780 be displayed in the buffer instead of the link.
7782 If there is already a link at point, this command will allow you to edit link
7783 and description parts.
7785 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7786 be selected using completion. The path to the file will be relative to the
7787 current directory if the file is in the current directory or a subdirectory.
7788 Otherwise, the link will be the absolute path as completed in the minibuffer
7789 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7790 option `org-link-file-path-type'.
7792 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7793 the current directory or below.
7795 With three \\[universal-argument] prefixes, negate the meaning of
7796 `org-keep-stored-link-after-insertion'.
7798 If `org-make-link-description-function' is non-nil, this function will be
7799 called with the link target, and the result will be the default
7800 link description.
7802 If the LINK-LOCATION parameter is non-nil, this value will be
7803 used as the link location instead of reading one interactively."
7804 (interactive "P")
7805 (let* ((wcf (current-window-configuration))
7806 (region (if (org-region-active-p)
7807 (buffer-substring (region-beginning) (region-end))))
7808 (remove (and region (list (region-beginning) (region-end))))
7809 (desc region)
7810 tmphist ; byte-compile incorrectly complains about this
7811 (link link-location)
7812 entry file all-prefixes)
7813 (cond
7814 (link-location) ; specified by arg, just use it.
7815 ((org-in-regexp org-bracket-link-regexp 1)
7816 ;; We do have a link at point, and we are going to edit it.
7817 (setq remove (list (match-beginning 0) (match-end 0)))
7818 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7819 (setq link (read-string "Link: "
7820 (org-link-unescape
7821 (org-match-string-no-properties 1)))))
7822 ((or (org-in-regexp org-angle-link-re)
7823 (org-in-regexp org-plain-link-re))
7824 ;; Convert to bracket link
7825 (setq remove (list (match-beginning 0) (match-end 0))
7826 link (read-string "Link: "
7827 (org-remove-angle-brackets (match-string 0)))))
7828 ((member complete-file '((4) (16)))
7829 ;; Completing read for file names.
7830 (setq link (org-file-complete-link complete-file)))
7832 ;; Read link, with completion for stored links.
7833 (with-output-to-temp-buffer "*Org Links*"
7834 (princ "Insert a link.
7835 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7836 (when org-stored-links
7837 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7838 (princ (mapconcat
7839 (lambda (x)
7840 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7841 (reverse org-stored-links) "\n"))))
7842 (let ((cw (selected-window)))
7843 (select-window (get-buffer-window "*Org Links*"))
7844 (setq truncate-lines t)
7845 (unless (pos-visible-in-window-p (point-max))
7846 (org-fit-window-to-buffer))
7847 (and (window-live-p cw) (select-window cw)))
7848 ;; Fake a link history, containing the stored links.
7849 (setq tmphist (append (mapcar 'car org-stored-links)
7850 org-insert-link-history))
7851 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7852 (mapcar 'car org-link-abbrev-alist)
7853 org-link-types))
7854 (unwind-protect
7855 (progn
7856 (setq link
7857 (let ((org-completion-use-ido nil)
7858 (org-completion-use-iswitchb nil))
7859 (org-completing-read
7860 "Link: "
7861 (append
7862 (mapcar (lambda (x) (list (concat x ":")))
7863 all-prefixes)
7864 (mapcar 'car org-stored-links))
7865 nil nil nil
7866 'tmphist
7867 (car (car org-stored-links)))))
7868 (if (or (member link all-prefixes)
7869 (and (equal ":" (substring link -1))
7870 (member (substring link 0 -1) all-prefixes)
7871 (setq link (substring link 0 -1))))
7872 (setq link (org-link-try-special-completion link))))
7873 (set-window-configuration wcf)
7874 (kill-buffer "*Org Links*"))
7875 (setq entry (assoc link org-stored-links))
7876 (or entry (push link org-insert-link-history))
7877 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7878 (not org-keep-stored-link-after-insertion))
7879 (setq org-stored-links (delq (assoc link org-stored-links)
7880 org-stored-links)))
7881 (setq desc (or desc (nth 1 entry)))))
7883 (if (string-match org-plain-link-re link)
7884 ;; URL-like link, normalize the use of angular brackets.
7885 (setq link (org-make-link (org-remove-angle-brackets link))))
7887 ;; Check if we are linking to the current file with a search option
7888 ;; If yes, simplify the link by using only the search option.
7889 (when (and buffer-file-name
7890 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7891 (let* ((path (match-string 1 link))
7892 (case-fold-search nil)
7893 (search (match-string 2 link)))
7894 (save-match-data
7895 (if (equal (file-truename buffer-file-name) (file-truename path))
7896 ;; We are linking to this same file, with a search option
7897 (setq link search)))))
7899 ;; Check if we can/should use a relative path. If yes, simplify the link
7900 (when (string-match "^file:\\(.*\\)" link)
7901 (let* ((path (match-string 1 link))
7902 (origpath path)
7903 (case-fold-search nil))
7904 (cond
7905 ((or (eq org-link-file-path-type 'absolute)
7906 (equal complete-file '(16)))
7907 (setq path (abbreviate-file-name (expand-file-name path))))
7908 ((eq org-link-file-path-type 'noabbrev)
7909 (setq path (expand-file-name path)))
7910 ((eq org-link-file-path-type 'relative)
7911 (setq path (file-relative-name path)))
7913 (save-match-data
7914 (if (string-match (concat "^" (regexp-quote
7915 (file-name-as-directory
7916 (expand-file-name "."))))
7917 (expand-file-name path))
7918 ;; We are linking a file with relative path name.
7919 (setq path (substring (expand-file-name path)
7920 (match-end 0)))
7921 (setq path (abbreviate-file-name (expand-file-name path)))))))
7922 (setq link (concat "file:" path))
7923 (if (equal desc origpath)
7924 (setq desc path))))
7926 (if org-make-link-description-function
7927 (setq desc (funcall org-make-link-description-function link desc)))
7929 (setq desc (read-string "Description: " desc))
7930 (unless (string-match "\\S-" desc) (setq desc nil))
7931 (if remove (apply 'delete-region remove))
7932 (insert (org-make-link-string link desc))))
7934 (defun org-link-try-special-completion (type)
7935 "If there is completion support for link type TYPE, offer it."
7936 (let ((fun (intern (concat "org-" type "-complete-link"))))
7937 (if (functionp fun)
7938 (funcall fun)
7939 (read-string "Link (no completion support): " (concat type ":")))))
7941 (defun org-file-complete-link (&optional arg)
7942 "Create a file link using completion."
7943 (let (file link)
7944 (setq file (read-file-name "File: "))
7945 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7946 (pwd1 (file-name-as-directory (abbreviate-file-name
7947 (expand-file-name ".")))))
7948 (cond
7949 ((equal arg '(16))
7950 (setq link (org-make-link
7951 "file:"
7952 (abbreviate-file-name (expand-file-name file)))))
7953 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7954 (setq link (org-make-link "file:" (match-string 1 file))))
7955 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7956 (expand-file-name file))
7957 (setq link (org-make-link
7958 "file:" (match-string 1 (expand-file-name file)))))
7959 (t (setq link (org-make-link "file:" file)))))
7960 link))
7962 (defun org-completing-read (&rest args)
7963 "Completing-read with SPACE being a normal character."
7964 (let ((minibuffer-local-completion-map
7965 (copy-keymap minibuffer-local-completion-map)))
7966 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7967 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7968 (apply 'org-icompleting-read args)))
7970 (defun org-completing-read-no-i (&rest args)
7971 (let (org-completion-use-ido org-completion-use-iswitchb)
7972 (apply 'org-completing-read args)))
7974 (defun org-iswitchb-completing-read (prompt choices &rest args)
7975 "Use iswitch as a completing-read replacement to choose from choices.
7976 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
7977 from."
7978 (let* ((iswitchb-use-virtual-buffers nil)
7979 (iswitchb-make-buflist-hook
7980 (lambda ()
7981 (setq iswitchb-temp-buflist choices))))
7982 (iswitchb-read-buffer prompt)))
7984 (defun org-icompleting-read (&rest args)
7985 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
7986 (org-without-partial-completion
7987 (if (and org-completion-use-ido
7988 (fboundp 'ido-completing-read)
7989 (boundp 'ido-mode) ido-mode
7990 (listp (second args)))
7991 (let ((ido-enter-matching-directory nil))
7992 (apply 'ido-completing-read (concat (car args))
7993 (if (consp (car (nth 1 args)))
7994 (mapcar (lambda (x) (car x)) (nth 1 args))
7995 (nth 1 args))
7996 (cddr args)))
7997 (if (and org-completion-use-iswitchb
7998 (boundp 'iswitchb-mode) iswitchb-mode
7999 (listp (second args)))
8000 (apply 'org-iswitchb-completing-read (concat (car args))
8001 (if (consp (car (nth 1 args)))
8002 (mapcar (lambda (x) (car x)) (nth 1 args))
8003 (nth 1 args))
8004 (cddr args))
8005 (apply 'completing-read args)))))
8007 (defun org-extract-attributes (s)
8008 "Extract the attributes cookie from a string and set as text property."
8009 (let (a attr (start 0) key value)
8010 (save-match-data
8011 (when (string-match "{{\\([^}]+\\)}}$" s)
8012 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8013 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8014 (setq key (match-string 1 a) value (match-string 2 a)
8015 start (match-end 0)
8016 attr (plist-put attr (intern key) value))))
8017 (org-add-props s nil 'org-attr attr))
8020 (defun org-extract-attributes-from-string (tag)
8021 (let (key value attr)
8022 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8023 (setq key (match-string 1 tag) value (match-string 2 tag)
8024 tag (replace-match "" t t tag)
8025 attr (plist-put attr (intern key) value)))
8026 (cons tag attr)))
8028 (defun org-attributes-to-string (plist)
8029 "Format a property list into an HTML attribute list."
8030 (let ((s "") key value)
8031 (while plist
8032 (setq key (pop plist) value (pop plist))
8033 (and value
8034 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8037 ;;; Opening/following a link
8039 (defvar org-link-search-failed nil)
8041 (defun org-next-link ()
8042 "Move forward to the next link.
8043 If the link is in hidden text, expose it."
8044 (interactive)
8045 (when (and org-link-search-failed (eq this-command last-command))
8046 (goto-char (point-min))
8047 (message "Link search wrapped back to beginning of buffer"))
8048 (setq org-link-search-failed nil)
8049 (let* ((pos (point))
8050 (ct (org-context))
8051 (a (assoc :link ct)))
8052 (if a (goto-char (nth 2 a)))
8053 (if (re-search-forward org-any-link-re nil t)
8054 (progn
8055 (goto-char (match-beginning 0))
8056 (if (org-invisible-p) (org-show-context)))
8057 (goto-char pos)
8058 (setq org-link-search-failed t)
8059 (error "No further link found"))))
8061 (defun org-previous-link ()
8062 "Move backward to the previous link.
8063 If the link is in hidden text, expose it."
8064 (interactive)
8065 (when (and org-link-search-failed (eq this-command last-command))
8066 (goto-char (point-max))
8067 (message "Link search wrapped back to end of buffer"))
8068 (setq org-link-search-failed nil)
8069 (let* ((pos (point))
8070 (ct (org-context))
8071 (a (assoc :link ct)))
8072 (if a (goto-char (nth 1 a)))
8073 (if (re-search-backward org-any-link-re nil t)
8074 (progn
8075 (goto-char (match-beginning 0))
8076 (if (org-invisible-p) (org-show-context)))
8077 (goto-char pos)
8078 (setq org-link-search-failed t)
8079 (error "No further link found"))))
8081 (defun org-translate-link (s)
8082 "Translate a link string if a translation function has been defined."
8083 (if (and org-link-translation-function
8084 (fboundp org-link-translation-function)
8085 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8086 (progn
8087 (setq s (funcall org-link-translation-function
8088 (match-string 1) (match-string 2)))
8089 (concat (car s) ":" (cdr s)))
8092 (defun org-translate-link-from-planner (type path)
8093 "Translate a link from Emacs Planner syntax so that Org can follow it.
8094 This is still an experimental function, your mileage may vary."
8095 (cond
8096 ((member type '("http" "https" "news" "ftp"))
8097 ;; standard Internet links are the same.
8098 nil)
8099 ((and (equal type "irc") (string-match "^//" path))
8100 ;; Planner has two / at the beginning of an irc link, we have 1.
8101 ;; We should have zero, actually....
8102 (setq path (substring path 1)))
8103 ((and (equal type "lisp") (string-match "^/" path))
8104 ;; Planner has a slash, we do not.
8105 (setq type "elisp" path (substring path 1)))
8106 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8107 ;; A typical message link. Planner has the id after the fina slash,
8108 ;; we separate it with a hash mark
8109 (setq path (concat (match-string 1 path) "#"
8110 (org-remove-angle-brackets (match-string 2 path)))))
8112 (cons type path))
8114 (defun org-find-file-at-mouse (ev)
8115 "Open file link or URL at mouse."
8116 (interactive "e")
8117 (mouse-set-point ev)
8118 (org-open-at-point 'in-emacs))
8120 (defun org-open-at-mouse (ev)
8121 "Open file link or URL at mouse."
8122 (interactive "e")
8123 (mouse-set-point ev)
8124 (if (eq major-mode 'org-agenda-mode)
8125 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8126 (org-open-at-point))
8128 (defvar org-window-config-before-follow-link nil
8129 "The window configuration before following a link.
8130 This is saved in case the need arises to restore it.")
8132 (defvar org-open-link-marker (make-marker)
8133 "Marker pointing to the location where `org-open-at-point; was called.")
8135 ;;;###autoload
8136 (defun org-open-at-point-global ()
8137 "Follow a link like Org-mode does.
8138 This command can be called in any mode to follow a link that has
8139 Org-mode syntax."
8140 (interactive)
8141 (org-run-like-in-org-mode 'org-open-at-point))
8143 ;;;###autoload
8144 (defun org-open-link-from-string (s &optional arg reference-buffer)
8145 "Open a link in the string S, as if it was in Org-mode."
8146 (interactive "sLink: \nP")
8147 (let ((reference-buffer (or reference-buffer (current-buffer))))
8148 (with-temp-buffer
8149 (let ((org-inhibit-startup t))
8150 (org-mode)
8151 (insert s)
8152 (goto-char (point-min))
8153 (org-open-at-point arg reference-buffer)))))
8155 (defun org-open-at-point (&optional in-emacs reference-buffer)
8156 "Open link at or after point.
8157 If there is no link at point, this function will search forward up to
8158 the end of the current line.
8159 Normally, files will be opened by an appropriate application. If the
8160 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8161 With a double prefix argument, try to open outside of Emacs, in the
8162 application the system uses for this file type."
8163 (interactive "P")
8164 (org-load-modules-maybe)
8165 (move-marker org-open-link-marker (point))
8166 (setq org-window-config-before-follow-link (current-window-configuration))
8167 (org-remove-occur-highlights nil nil t)
8168 (cond
8169 ((and (org-on-heading-p)
8170 (not (org-in-regexp
8171 (concat org-plain-link-re "\\|"
8172 org-bracket-link-regexp "\\|"
8173 org-angle-link-re "\\|"
8174 "[ \t]:[^ \t\n]+:[ \t]*$"))))
8175 (or (org-offer-links-in-entry in-emacs)
8176 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8177 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8178 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8179 (org-footnote-action))
8181 (let (type path link line search (pos (point)))
8182 (catch 'match
8183 (save-excursion
8184 (skip-chars-forward "^]\n\r")
8185 (when (org-in-regexp org-bracket-link-regexp)
8186 (setq link (org-extract-attributes
8187 (org-link-unescape (org-match-string-no-properties 1))))
8188 (while (string-match " *\n *" link)
8189 (setq link (replace-match " " t t link)))
8190 (setq link (org-link-expand-abbrev link))
8191 (cond
8192 ((or (file-name-absolute-p link)
8193 (string-match "^\\.\\.?/" link))
8194 (setq type "file" path link))
8195 ((string-match org-link-re-with-space3 link)
8196 (setq type (match-string 1 link) path (match-string 2 link)))
8197 (t (setq type "thisfile" path link)))
8198 (throw 'match t)))
8200 (when (get-text-property (point) 'org-linked-text)
8201 (setq type "thisfile"
8202 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8203 (1+ (point)) (point))
8204 path (buffer-substring
8205 (previous-single-property-change pos 'org-linked-text)
8206 (next-single-property-change pos 'org-linked-text)))
8207 (throw 'match t))
8209 (save-excursion
8210 (when (or (org-in-regexp org-angle-link-re)
8211 (org-in-regexp org-plain-link-re))
8212 (setq type (match-string 1) path (match-string 2))
8213 (throw 'match t)))
8214 (save-excursion
8215 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8216 (setq type "tags"
8217 path (match-string 1))
8218 (while (string-match ":" path)
8219 (setq path (replace-match "+" t t path)))
8220 (throw 'match t)))
8221 (when (org-in-regexp "<\\([^><\n]+\\)>")
8222 (setq type "tree-match"
8223 path (match-string 1))
8224 (throw 'match t)))
8225 (unless path
8226 (error "No link found"))
8228 ;; switch back to reference buffer
8229 ;; needed when if called in a temporary buffer through
8230 ;; org-open-link-from-string
8231 (with-current-buffer (or reference-buffer (current-buffer))
8233 ;; Remove any trailing spaces in path
8234 (if (string-match " +\\'" path)
8235 (setq path (replace-match "" t t path)))
8236 (if (and org-link-translation-function
8237 (fboundp org-link-translation-function))
8238 ;; Check if we need to translate the link
8239 (let ((tmp (funcall org-link-translation-function type path)))
8240 (setq type (car tmp) path (cdr tmp))))
8242 (cond
8244 ((assoc type org-link-protocols)
8245 (funcall (nth 1 (assoc type org-link-protocols)) path))
8247 ((equal type "mailto")
8248 (let ((cmd (car org-link-mailto-program))
8249 (args (cdr org-link-mailto-program)) args1
8250 (address path) (subject "") a)
8251 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8252 (setq address (match-string 1 path)
8253 subject (org-link-escape (match-string 2 path))))
8254 (while args
8255 (cond
8256 ((not (stringp (car args))) (push (pop args) args1))
8257 (t (setq a (pop args))
8258 (if (string-match "%a" a)
8259 (setq a (replace-match address t t a)))
8260 (if (string-match "%s" a)
8261 (setq a (replace-match subject t t a)))
8262 (push a args1))))
8263 (apply cmd (nreverse args1))))
8265 ((member type '("http" "https" "ftp" "news"))
8266 (browse-url (concat type ":" (org-link-escape
8267 path org-link-escape-chars-browser))))
8269 ((member type '("message"))
8270 (browse-url (concat type ":" path)))
8272 ((string= type "tags")
8273 (org-tags-view in-emacs path))
8274 ((string= type "thisfile")
8275 (if in-emacs
8276 (switch-to-buffer-other-window
8277 (org-get-buffer-for-internal-link (current-buffer)))
8278 (org-mark-ring-push))
8279 (let ((cmd `(org-link-search
8280 ,path
8281 ,(cond ((equal in-emacs '(4)) 'occur)
8282 ((equal in-emacs '(16)) 'org-occur)
8283 (t nil))
8284 ,pos)))
8285 (condition-case nil (eval cmd)
8286 (error (progn (widen) (eval cmd))))))
8288 ((string= type "tree-match")
8289 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8291 ((string= type "file")
8292 (if (string-match "::\\([0-9]+\\)\\'" path)
8293 (setq line (string-to-number (match-string 1 path))
8294 path (substring path 0 (match-beginning 0)))
8295 (if (string-match "::\\(.+\\)\\'" path)
8296 (setq search (match-string 1 path)
8297 path (substring path 0 (match-beginning 0)))))
8298 (if (string-match "[*?{]" (file-name-nondirectory path))
8299 (dired path)
8300 (org-open-file path in-emacs line search)))
8302 ((string= type "news")
8303 (require 'org-gnus)
8304 (org-gnus-follow-link path))
8306 ((string= type "shell")
8307 (let ((cmd path))
8308 (if (or (not org-confirm-shell-link-function)
8309 (funcall org-confirm-shell-link-function
8310 (format "Execute \"%s\" in shell? "
8311 (org-add-props cmd nil
8312 'face 'org-warning))))
8313 (progn
8314 (message "Executing %s" cmd)
8315 (shell-command cmd))
8316 (error "Abort"))))
8318 ((string= type "elisp")
8319 (let ((cmd path))
8320 (if (or (not org-confirm-elisp-link-function)
8321 (funcall org-confirm-elisp-link-function
8322 (format "Execute \"%s\" as elisp? "
8323 (org-add-props cmd nil
8324 'face 'org-warning))))
8325 (message "%s => %s" cmd
8326 (if (equal (string-to-char cmd) ?\()
8327 (eval (read cmd))
8328 (call-interactively (read cmd))))
8329 (error "Abort"))))
8332 (browse-url-at-point)))))))
8333 (move-marker org-open-link-marker nil)
8334 (run-hook-with-args 'org-follow-link-hook))
8336 (defun org-offer-links-in-entry (&optional nth zero)
8337 "Offer links in the curren entry and follow the selected link.
8338 If there is only one link, follow it immediately as well.
8339 If NTH is an integer, immediately pick the NTH link found.
8340 If ZERO is a string, check also this string for a link, and if
8341 there is one, offer it as link number zero."
8342 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8343 "\\(" org-angle-link-re "\\)\\|"
8344 "\\(" org-plain-link-re "\\)"))
8345 (cnt ?0)
8346 (in-emacs (if (integerp nth) nil nth))
8347 have-zero end links link c)
8348 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8349 (push (match-string 0 zero) links)
8350 (setq cnt (1- cnt) have-zero t))
8351 (save-excursion
8352 (org-back-to-heading t)
8353 (setq end (save-excursion (outline-next-heading) (point)))
8354 (while (re-search-forward re end t)
8355 (push (match-string 0) links))
8356 (setq links (org-uniquify (reverse links))))
8358 (cond
8359 ((null links)
8360 (message "No links"))
8361 ((equal (length links) 1)
8362 (setq link (car links)))
8363 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8364 (setq link (nth (if have-zero nth (1- nth)) links)))
8365 (t ; we have to select a link
8366 (save-excursion
8367 (save-window-excursion
8368 (delete-other-windows)
8369 (with-output-to-temp-buffer "*Select Link*"
8370 (mapc (lambda (l)
8371 (if (not (string-match org-bracket-link-regexp l))
8372 (princ (format "[%c] %s\n" (incf cnt)
8373 (org-remove-angle-brackets l)))
8374 (if (match-end 3)
8375 (princ (format "[%c] %s (%s)\n" (incf cnt)
8376 (match-string 3 l) (match-string 1 l)))
8377 (princ (format "[%c] %s\n" (incf cnt)
8378 (match-string 1 l))))))
8379 links))
8380 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8381 (message "Select link to open:")
8382 (setq c (read-char-exclusive))
8383 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8384 (when (equal c ?q) (error "Abort"))
8385 (setq nth (- c ?0))
8386 (if have-zero (setq nth (1+ nth)))
8387 (unless (and (integerp nth) (>= (length links) nth))
8388 (error "Invalid link selection"))
8389 (setq link (nth (1- nth) links))))
8390 (if link
8391 (progn (org-open-link-from-string link in-emacs (current-buffer)) t)
8392 nil)))
8394 ;;;; Time estimates
8396 (defun org-get-effort (&optional pom)
8397 "Get the effort estimate for the current entry."
8398 (org-entry-get pom org-effort-property))
8400 ;;; File search
8402 (defvar org-create-file-search-functions nil
8403 "List of functions to construct the right search string for a file link.
8404 These functions are called in turn with point at the location to
8405 which the link should point.
8407 A function in the hook should first test if it would like to
8408 handle this file type, for example by checking the major-mode or
8409 the file extension. If it decides not to handle this file, it
8410 should just return nil to give other functions a chance. If it
8411 does handle the file, it must return the search string to be used
8412 when following the link. The search string will be part of the
8413 file link, given after a double colon, and `org-open-at-point'
8414 will automatically search for it. If special measures must be
8415 taken to make the search successful, another function should be
8416 added to the companion hook `org-execute-file-search-functions',
8417 which see.
8419 A function in this hook may also use `setq' to set the variable
8420 `description' to provide a suggestion for the descriptive text to
8421 be used for this link when it gets inserted into an Org-mode
8422 buffer with \\[org-insert-link].")
8424 (defvar org-execute-file-search-functions nil
8425 "List of functions to execute a file search triggered by a link.
8427 Functions added to this hook must accept a single argument, the
8428 search string that was part of the file link, the part after the
8429 double colon. The function must first check if it would like to
8430 handle this search, for example by checking the major-mode or the
8431 file extension. If it decides not to handle this search, it
8432 should just return nil to give other functions a chance. If it
8433 does handle the search, it must return a non-nil value to keep
8434 other functions from trying.
8436 Each function can access the current prefix argument through the
8437 variable `current-prefix-argument'. Note that a single prefix is
8438 used to force opening a link in Emacs, so it may be good to only
8439 use a numeric or double prefix to guide the search function.
8441 In case this is needed, a function in this hook can also restore
8442 the window configuration before `org-open-at-point' was called using:
8444 (set-window-configuration org-window-config-before-follow-link)")
8446 (defun org-link-search (s &optional type avoid-pos)
8447 "Search for a link search option.
8448 If S is surrounded by forward slashes, it is interpreted as a
8449 regular expression. In org-mode files, this will create an `org-occur'
8450 sparse tree. In ordinary files, `occur' will be used to list matches.
8451 If the current buffer is in `dired-mode', grep will be used to search
8452 in all files. If AVOID-POS is given, ignore matches near that position."
8453 (let ((case-fold-search t)
8454 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8455 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8456 (append '(("") (" ") ("\t") ("\n"))
8457 org-emphasis-alist)
8458 "\\|") "\\)"))
8459 (pos (point))
8460 (pre nil) (post nil)
8461 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8462 (cond
8463 ;; First check if there are any special
8464 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8465 ;; Now try the builtin stuff
8466 ((and (equal (string-to-char s0) ?#)
8467 (> (length s0) 1)
8468 (save-excursion
8469 (goto-char (point-min))
8470 (and
8471 (re-search-forward
8472 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8473 (setq type 'dedicated
8474 pos (match-beginning 0))))
8475 ;; There is an exact target for this
8476 (goto-char pos)
8477 (org-back-to-heading t)))
8478 ((save-excursion
8479 (goto-char (point-min))
8480 (and
8481 (re-search-forward
8482 (concat "<<" (regexp-quote s0) ">>") nil t)
8483 (setq type 'dedicated
8484 pos (match-beginning 0))))
8485 ;; There is an exact target for this
8486 (goto-char pos))
8487 ((and (string-match "^(\\(.*\\))$" s0)
8488 (save-excursion
8489 (goto-char (point-min))
8490 (and
8491 (re-search-forward
8492 (concat "[^[]" (regexp-quote
8493 (format org-coderef-label-format
8494 (match-string 1 s0))))
8495 nil t)
8496 (setq type 'dedicated
8497 pos (1+ (match-beginning 0))))))
8498 ;; There is a coderef target for this
8499 (goto-char pos))
8500 ((string-match "^/\\(.*\\)/$" s)
8501 ;; A regular expression
8502 (cond
8503 ((org-mode-p)
8504 (org-occur (match-string 1 s)))
8505 ;;((eq major-mode 'dired-mode)
8506 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8507 (t (org-do-occur (match-string 1 s)))))
8509 ;; A normal search strings
8510 (when (equal (string-to-char s) ?*)
8511 ;; Anchor on headlines, post may include tags.
8512 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8513 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8514 s (substring s 1)))
8515 (remove-text-properties
8516 0 (length s)
8517 '(face nil mouse-face nil keymap nil fontified nil) s)
8518 ;; Make a series of regular expressions to find a match
8519 (setq words (org-split-string s "[ \n\r\t]+")
8521 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8522 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8523 "\\)" markers)
8524 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8525 re2a (concat "[ \t\r\n]" re2a_)
8526 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8527 re4 (concat "[^a-zA-Z_]" re4_)
8529 re1 (concat pre re2 post)
8530 re3 (concat pre (if pre re4_ re4) post)
8531 re5 (concat pre ".*" re4)
8532 re2 (concat pre re2)
8533 re2a (concat pre (if pre re2a_ re2a))
8534 re4 (concat pre (if pre re4_ re4))
8535 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8536 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8537 re5 "\\)"
8539 (cond
8540 ((eq type 'org-occur) (org-occur reall))
8541 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8542 (t (goto-char (point-min))
8543 (setq type 'fuzzy)
8544 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8545 (org-search-not-self 1 re1 nil t)
8546 (org-search-not-self 1 re2 nil t)
8547 (org-search-not-self 1 re2a nil t)
8548 (org-search-not-self 1 re3 nil t)
8549 (org-search-not-self 1 re4 nil t)
8550 (org-search-not-self 1 re5 nil t)
8552 (goto-char (match-beginning 1))
8553 (goto-char pos)
8554 (error "No match")))))
8556 ;; Normal string-search
8557 (goto-char (point-min))
8558 (if (search-forward s nil t)
8559 (goto-char (match-beginning 0))
8560 (error "No match"))))
8561 (and (org-mode-p) (org-show-context 'link-search))
8562 type))
8564 (defun org-search-not-self (group &rest args)
8565 "Execute `re-search-forward', but only accept matches that do not
8566 enclose the position of `org-open-link-marker'."
8567 (let ((m org-open-link-marker))
8568 (catch 'exit
8569 (while (apply 're-search-forward args)
8570 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8571 (goto-char (match-end group))
8572 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8573 (> (match-beginning 0) (marker-position m))
8574 (< (match-end 0) (marker-position m)))
8575 (save-match-data
8576 (or (not (org-in-regexp
8577 org-bracket-link-analytic-regexp 1))
8578 (not (match-end 4)) ; no description
8579 (and (<= (match-beginning 4) (point))
8580 (>= (match-end 4) (point))))))
8581 (throw 'exit (point))))))))
8583 (defun org-get-buffer-for-internal-link (buffer)
8584 "Return a buffer to be used for displaying the link target of internal links."
8585 (cond
8586 ((not org-display-internal-link-with-indirect-buffer)
8587 buffer)
8588 ((string-match "(Clone)$" (buffer-name buffer))
8589 (message "Buffer is already a clone, not making another one")
8590 ;; we also do not modify visibility in this case
8591 buffer)
8592 (t ; make a new indirect buffer for displaying the link
8593 (let* ((bn (buffer-name buffer))
8594 (ibn (concat bn "(Clone)"))
8595 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8596 (with-current-buffer ib (org-overview))
8597 ib))))
8599 (defun org-do-occur (regexp &optional cleanup)
8600 "Call the Emacs command `occur'.
8601 If CLEANUP is non-nil, remove the printout of the regular expression
8602 in the *Occur* buffer. This is useful if the regex is long and not useful
8603 to read."
8604 (occur regexp)
8605 (when cleanup
8606 (let ((cwin (selected-window)) win beg end)
8607 (when (setq win (get-buffer-window "*Occur*"))
8608 (select-window win))
8609 (goto-char (point-min))
8610 (when (re-search-forward "match[a-z]+" nil t)
8611 (setq beg (match-end 0))
8612 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8613 (setq end (1- (match-beginning 0)))))
8614 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8615 (goto-char (point-min))
8616 (select-window cwin))))
8618 ;;; The mark ring for links jumps
8620 (defvar org-mark-ring nil
8621 "Mark ring for positions before jumps in Org-mode.")
8622 (defvar org-mark-ring-last-goto nil
8623 "Last position in the mark ring used to go back.")
8624 ;; Fill and close the ring
8625 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8626 (loop for i from 1 to org-mark-ring-length do
8627 (push (make-marker) org-mark-ring))
8628 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8629 org-mark-ring)
8631 (defun org-mark-ring-push (&optional pos buffer)
8632 "Put the current position or POS into the mark ring and rotate it."
8633 (interactive)
8634 (setq pos (or pos (point)))
8635 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8636 (move-marker (car org-mark-ring)
8637 (or pos (point))
8638 (or buffer (current-buffer)))
8639 (message "%s"
8640 (substitute-command-keys
8641 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8643 (defun org-mark-ring-goto (&optional n)
8644 "Jump to the previous position in the mark ring.
8645 With prefix arg N, jump back that many stored positions. When
8646 called several times in succession, walk through the entire ring.
8647 Org-mode commands jumping to a different position in the current file,
8648 or to another Org-mode file, automatically push the old position
8649 onto the ring."
8650 (interactive "p")
8651 (let (p m)
8652 (if (eq last-command this-command)
8653 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8654 (setq p org-mark-ring))
8655 (setq org-mark-ring-last-goto p)
8656 (setq m (car p))
8657 (switch-to-buffer (marker-buffer m))
8658 (goto-char m)
8659 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8661 (defun org-remove-angle-brackets (s)
8662 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8663 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8665 (defun org-add-angle-brackets (s)
8666 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8667 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8669 (defun org-remove-double-quotes (s)
8670 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8671 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8674 ;;; Following specific links
8676 (defun org-follow-timestamp-link ()
8677 (cond
8678 ((org-at-date-range-p t)
8679 (let ((org-agenda-start-on-weekday)
8680 (t1 (match-string 1))
8681 (t2 (match-string 2)))
8682 (setq t1 (time-to-days (org-time-string-to-time t1))
8683 t2 (time-to-days (org-time-string-to-time t2)))
8684 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8685 ((org-at-timestamp-p t)
8686 (org-agenda-list nil (time-to-days (org-time-string-to-time
8687 (substring (match-string 1) 0 10)))
8689 (t (error "This should not happen"))))
8692 ;;; Following file links
8693 (defvar org-wait nil)
8694 (defun org-open-file (path &optional in-emacs line search)
8695 "Open the file at PATH.
8696 First, this expands any special file name abbreviations. Then the
8697 configuration variable `org-file-apps' is checked if it contains an
8698 entry for this file type, and if yes, the corresponding command is launched.
8700 If no application is found, Emacs simply visits the file.
8702 With optional prefix argument IN-EMACS, Emacs will visit the file.
8703 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8704 and o use an external application to visit the file.
8706 Optional LINE specifies a line to go to, optional SEARCH a string to
8707 search for. If LINE or SEARCH is given, the file will always be
8708 opened in Emacs.
8709 If the file does not exist, an error is thrown."
8710 (setq in-emacs (or in-emacs line search))
8711 (let* ((file (if (equal path "")
8712 buffer-file-name
8713 (substitute-in-file-name (expand-file-name path))))
8714 (apps (append org-file-apps (org-default-apps)))
8715 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8716 (dirp (if remp nil (file-directory-p file)))
8717 (file (if (and dirp org-open-directory-means-index-dot-org)
8718 (concat (file-name-as-directory file) "index.org")
8719 file))
8720 (a-m-a-p (assq 'auto-mode apps))
8721 (dfile (downcase file))
8722 (old-buffer (current-buffer))
8723 (old-pos (point))
8724 (old-mode major-mode)
8725 ext cmd)
8726 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8727 (setq ext (match-string 1 dfile))
8728 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8729 (setq ext (match-string 1 dfile))))
8730 (cond
8731 ((equal in-emacs '(16))
8732 (setq cmd (cdr (assoc 'system apps))))
8733 (in-emacs (setq cmd 'emacs))
8735 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8736 (and dirp (cdr (assoc 'directory apps)))
8737 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8738 'string-match)
8739 (cdr (assoc ext apps))
8740 (cdr (assoc t apps))))))
8741 (when (eq cmd 'system)
8742 (setq cmd (cdr (assoc 'system apps))))
8743 (when (eq cmd 'default)
8744 (setq cmd (cdr (assoc t apps))))
8745 (when (eq cmd 'mailcap)
8746 (require 'mailcap)
8747 (mailcap-parse-mailcaps)
8748 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8749 (command (mailcap-mime-info mime-type)))
8750 (if (stringp command)
8751 (setq cmd command)
8752 (setq cmd 'emacs))))
8753 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8754 (not (file-exists-p file))
8755 (not org-open-non-existing-files))
8756 (error "No such file: %s" file))
8757 (cond
8758 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8759 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8760 (while (string-match "['\"]%s['\"]" cmd)
8761 (setq cmd (replace-match "%s" t t cmd)))
8762 (while (string-match "%s" cmd)
8763 (setq cmd (replace-match
8764 (save-match-data
8765 (shell-quote-argument
8766 (convert-standard-filename file)))
8767 t t cmd)))
8768 (save-window-excursion
8769 (start-process-shell-command cmd nil cmd)
8770 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8772 ((or (stringp cmd)
8773 (eq cmd 'emacs))
8774 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8775 (widen)
8776 (if line (org-goto-line line)
8777 (if search (org-link-search search))))
8778 ((consp cmd)
8779 (let ((file (convert-standard-filename file)))
8780 (eval cmd)))
8781 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8782 (and (org-mode-p) (eq old-mode 'org-mode)
8783 (or (not (equal old-buffer (current-buffer)))
8784 (not (equal old-pos (point))))
8785 (org-mark-ring-push old-pos old-buffer))))
8787 (defun org-default-apps ()
8788 "Return the default applications for this operating system."
8789 (cond
8790 ((eq system-type 'darwin)
8791 org-file-apps-defaults-macosx)
8792 ((eq system-type 'windows-nt)
8793 org-file-apps-defaults-windowsnt)
8794 (t org-file-apps-defaults-gnu)))
8796 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8797 "Convert extensions to regular expressions in the cars of LIST.
8798 Also, weed out any non-string entries, because the return value is used
8799 only for regexp matching.
8800 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8801 point to the symbol `emacs', indicating that the file should
8802 be opened in Emacs."
8803 (append
8804 (delq nil
8805 (mapcar (lambda (x)
8806 (if (not (stringp (car x)))
8808 (if (string-match "\\W" (car x))
8810 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8811 list))
8812 (if add-auto-mode
8813 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8815 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8816 (defun org-file-remote-p (file)
8817 "Test whether FILE specifies a location on a remote system.
8818 Return non-nil if the location is indeed remote.
8820 For example, the filename \"/user@host:/foo\" specifies a location
8821 on the system \"/user@host:\"."
8822 (cond ((fboundp 'file-remote-p)
8823 (file-remote-p file))
8824 ((fboundp 'tramp-handle-file-remote-p)
8825 (tramp-handle-file-remote-p file))
8826 ((and (boundp 'ange-ftp-name-format)
8827 (string-match (car ange-ftp-name-format) file))
8829 (t nil)))
8832 ;;;; Refiling
8834 (defun org-get-org-file ()
8835 "Read a filename, with default directory `org-directory'."
8836 (let ((default (or org-default-notes-file remember-data-file)))
8837 (read-file-name (format "File name [%s]: " default)
8838 (file-name-as-directory org-directory)
8839 default)))
8841 (defun org-notes-order-reversed-p ()
8842 "Check if the current file should receive notes in reversed order."
8843 (cond
8844 ((not org-reverse-note-order) nil)
8845 ((eq t org-reverse-note-order) t)
8846 ((not (listp org-reverse-note-order)) nil)
8847 (t (catch 'exit
8848 (let ((all org-reverse-note-order)
8849 entry)
8850 (while (setq entry (pop all))
8851 (if (string-match (car entry) buffer-file-name)
8852 (throw 'exit (cdr entry))))
8853 nil)))))
8855 (defvar org-refile-target-table nil
8856 "The list of refile targets, created by `org-refile'.")
8858 (defvar org-agenda-new-buffers nil
8859 "Buffers created to visit agenda files.")
8861 (defun org-get-refile-targets (&optional default-buffer)
8862 "Produce a table with refile targets."
8863 (let ((case-fold-search nil)
8864 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8865 (entries (or org-refile-targets '((nil . (:level . 1)))))
8866 targets txt re files f desc descre fast-path-p level pos0)
8867 (message "Getting targets...")
8868 (with-current-buffer (or default-buffer (current-buffer))
8869 (while (setq entry (pop entries))
8870 (setq files (car entry) desc (cdr entry))
8871 (setq fast-path-p nil)
8872 (cond
8873 ((null files) (setq files (list (current-buffer))))
8874 ((eq files 'org-agenda-files)
8875 (setq files (org-agenda-files 'unrestricted)))
8876 ((and (symbolp files) (fboundp files))
8877 (setq files (funcall files)))
8878 ((and (symbolp files) (boundp files))
8879 (setq files (symbol-value files))))
8880 (if (stringp files) (setq files (list files)))
8881 (cond
8882 ((eq (car desc) :tag)
8883 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8884 ((eq (car desc) :todo)
8885 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8886 ((eq (car desc) :regexp)
8887 (setq descre (cdr desc)))
8888 ((eq (car desc) :level)
8889 (setq descre (concat "^\\*\\{" (number-to-string
8890 (if org-odd-levels-only
8891 (1- (* 2 (cdr desc)))
8892 (cdr desc)))
8893 "\\}[ \t]")))
8894 ((eq (car desc) :maxlevel)
8895 (setq fast-path-p t)
8896 (setq descre (concat "^\\*\\{1," (number-to-string
8897 (if org-odd-levels-only
8898 (1- (* 2 (cdr desc)))
8899 (cdr desc)))
8900 "\\}[ \t]")))
8901 (t (error "Bad refiling target description %s" desc)))
8902 (while (setq f (pop files))
8903 (with-current-buffer
8904 (if (bufferp f) f (org-get-agenda-file-buffer f))
8905 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8906 (setq f (expand-file-name f))
8907 (if (eq org-refile-use-outline-path 'file)
8908 (push (list (file-name-nondirectory f) f nil nil) targets))
8909 (save-excursion
8910 (save-restriction
8911 (widen)
8912 (goto-char (point-min))
8913 (while (re-search-forward descre nil t)
8914 (goto-char (setq pos0 (point-at-bol)))
8915 (catch 'next
8916 (when org-refile-target-verify-function
8917 (save-match-data
8918 (or (funcall org-refile-target-verify-function)
8919 (throw 'next t))))
8920 (when (looking-at org-complex-heading-regexp)
8921 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8922 txt (org-link-display-format (match-string 4))
8923 re (concat "^" (regexp-quote
8924 (buffer-substring (match-beginning 1)
8925 (match-end 4)))))
8926 (if (match-end 5) (setq re (concat re "[ \t]+"
8927 (regexp-quote
8928 (match-string 5)))))
8929 (setq re (concat re "[ \t]*$"))
8930 (when org-refile-use-outline-path
8931 (setq txt (mapconcat 'org-protect-slash
8932 (append
8933 (if (eq org-refile-use-outline-path 'file)
8934 (list (file-name-nondirectory
8935 (buffer-file-name (buffer-base-buffer))))
8936 (if (eq org-refile-use-outline-path 'full-file-path)
8937 (list (buffer-file-name (buffer-base-buffer)))))
8938 (org-get-outline-path fast-path-p level txt)
8939 (list txt))
8940 "/")))
8941 (push (list txt f re (point)) targets)))
8942 (when (= (point) pos0)
8943 ;; verification function has not moved point
8944 (goto-char (point-at-eol))))))))))
8945 (message "Getting targets...done")
8946 (nreverse targets)))
8948 (defun org-protect-slash (s)
8949 (while (string-match "/" s)
8950 (setq s (replace-match "\\" t t s)))
8953 (defvar org-olpa (make-vector 20 nil))
8955 (defun org-get-outline-path (&optional fastp level heading)
8956 "Return the outline path to the current entry, as a list."
8957 (if fastp
8958 (progn
8959 (if (> level 19)
8960 (error "Outline path failure, more than 19 levels."))
8961 (loop for i from level upto 19 do
8962 (aset org-olpa i nil))
8963 (prog1
8964 (delq nil (append org-olpa nil))
8965 (aset org-olpa level heading)))
8966 (let (rtn)
8967 (save-excursion
8968 (while (org-up-heading-safe)
8969 (when (looking-at org-complex-heading-regexp)
8970 (push (org-match-string-no-properties 4) rtn)))
8971 rtn))))
8973 (defvar org-refile-history nil
8974 "History for refiling operations.")
8976 (defvar org-after-refile-insert-hook nil
8977 "Hook run after `org-refile' has inserted its stuff at the new location.
8978 Note that this is still *before* the stuff will be removed from
8979 the *old* location.")
8981 (defun org-refile (&optional goto default-buffer rfloc)
8982 "Move the entry at point to another heading.
8983 The list of target headings is compiled using the information in
8984 `org-refile-targets', which see. This list is created before each use
8985 and will therefore always be up-to-date.
8987 At the target location, the entry is filed as a subitem of the target heading.
8988 Depending on `org-reverse-note-order', the new subitem will either be the
8989 first or the last subitem.
8991 If there is an active region, all entries in that region will be moved.
8992 However, the region must fulfil the requirement that the first heading
8993 is the first one sets the top-level of the moved text - at most siblings
8994 below it are allowed.
8996 With prefix arg GOTO, the command will only visit the target location,
8997 not actually move anything.
8998 With a double prefix `C-u C-u', go to the location where the last refiling
8999 operation has put the subtree.
9000 With a prefix argument of `2', refile to the running clock.
9002 RFLOC can be a refile location obtained in a different way.
9004 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9005 (interactive "P")
9006 (let* ((cbuf (current-buffer))
9007 (regionp (org-region-active-p))
9008 (region-start (and regionp (region-beginning)))
9009 (region-end (and regionp (region-end)))
9010 (region-length (and regionp (- region-end region-start)))
9011 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9012 pos it nbuf file re level reversed)
9013 (when regionp
9014 (goto-char region-start)
9015 (or (bolp) (goto-char (point-at-bol)))
9016 (setq region-start (point))
9017 (unless (org-kill-is-subtree-p
9018 (buffer-substring region-start region-end))
9019 (error "The region is not a (sequence of) subtree(s)")))
9020 (if (equal goto '(16))
9021 (org-refile-goto-last-stored)
9022 (when (or
9023 (and (equal goto 2)
9024 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9025 (prog1
9026 (setq it (list (or org-clock-heading "running clock")
9027 (buffer-file-name
9028 (marker-buffer org-clock-hd-marker))
9030 (marker-position org-clock-hd-marker)))
9031 (setq goto nil)))
9032 (setq it (or rfloc
9033 (save-excursion
9034 (org-refile-get-location
9035 (if goto "Goto: " "Refile to: ") default-buffer
9036 org-refile-allow-creating-parent-nodes)))))
9037 (setq file (nth 1 it)
9038 re (nth 2 it)
9039 pos (nth 3 it))
9040 (if (and (not goto)
9042 (equal (buffer-file-name) file)
9043 (if regionp
9044 (and (>= pos region-start)
9045 (<= pos region-end))
9046 (and (>= pos (point))
9047 (< pos (save-excursion
9048 (org-end-of-subtree t t))))))
9049 (error "Cannot refile to position inside the tree or region"))
9051 (setq nbuf (or (find-buffer-visiting file)
9052 (find-file-noselect file)))
9053 (if goto
9054 (progn
9055 (switch-to-buffer nbuf)
9056 (goto-char pos)
9057 (org-show-context 'org-goto))
9058 (if regionp
9059 (progn
9060 (org-kill-new (buffer-substring region-start region-end))
9061 (org-save-markers-in-region region-start region-end))
9062 (org-copy-subtree 1 nil t))
9063 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9064 (find-file-noselect file)))
9065 (setq reversed (org-notes-order-reversed-p))
9066 (save-excursion
9067 (save-restriction
9068 (widen)
9069 (if pos
9070 (progn
9071 (goto-char pos)
9072 (looking-at outline-regexp)
9073 (setq level (org-get-valid-level (funcall outline-level) 1))
9074 (goto-char
9075 (if reversed
9076 (or (outline-next-heading) (point-max))
9077 (or (save-excursion (org-get-next-sibling))
9078 (org-end-of-subtree t t)
9079 (point-max)))))
9080 (setq level 1)
9081 (if (not reversed)
9082 (goto-char (point-max))
9083 (goto-char (point-min))
9084 (or (outline-next-heading) (goto-char (point-max)))))
9085 (if (not (bolp)) (newline))
9086 (bookmark-set "org-refile-last-stored")
9087 (org-paste-subtree level)
9088 (if (fboundp 'deactivate-mark) (deactivate-mark))
9089 (run-hooks 'org-after-refile-insert-hook))))
9090 (if regionp
9091 (delete-region (point) (+ (point) region-length))
9092 (org-cut-subtree))
9093 (when (featurep 'org-inlinetask)
9094 (org-inlinetask-remove-END-maybe))
9095 (setq org-markers-to-move nil)
9096 (message "Refiled to \"%s\"" (car it))))))
9097 (org-reveal))
9099 (defun org-refile-goto-last-stored ()
9100 "Go to the location where the last refile was stored."
9101 (interactive)
9102 (bookmark-jump "org-refile-last-stored")
9103 (message "This is the location of the last refile"))
9105 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9106 "Prompt the user for a refile location, using PROMPT."
9107 (let ((org-refile-targets org-refile-targets)
9108 (org-refile-use-outline-path org-refile-use-outline-path))
9109 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9110 (unless org-refile-target-table
9111 (error "No refile targets"))
9112 (let* ((cbuf (current-buffer))
9113 (partial-completion-mode nil)
9114 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9115 (cfunc (if (and org-refile-use-outline-path
9116 org-outline-path-complete-in-steps)
9117 'org-olpath-completing-read
9118 'org-icompleting-read))
9119 (extra (if org-refile-use-outline-path "/" ""))
9120 (filename (and cfn (expand-file-name cfn)))
9121 (tbl (mapcar
9122 (lambda (x)
9123 (if (and (not (member org-refile-use-outline-path
9124 '(file full-file-path)))
9125 (not (equal filename (nth 1 x))))
9126 (cons (concat (car x) extra " ("
9127 (file-name-nondirectory (nth 1 x)) ")")
9128 (cdr x))
9129 (cons (concat (car x) extra) (cdr x))))
9130 org-refile-target-table))
9131 (completion-ignore-case t)
9132 pa answ parent-target child parent old-hist)
9133 (setq old-hist org-refile-history)
9134 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9135 nil 'org-refile-history))
9136 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9137 (if pa
9138 (progn
9139 (when (or (not org-refile-history)
9140 (not (eq old-hist org-refile-history))
9141 (not (equal (car pa) (car org-refile-history))))
9142 (setq org-refile-history
9143 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9144 org-refile-history
9145 (cdr org-refile-history))))
9146 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9147 (pop org-refile-history)))
9149 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9150 (setq parent (match-string 1 answ)
9151 child (match-string 2 answ))
9152 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
9153 (when (and parent-target
9154 (or (eq new-nodes t)
9155 (and (eq new-nodes 'confirm)
9156 (y-or-n-p (format "Create new node \"%s\"? " child)))))
9157 (org-refile-new-child parent-target child))))))
9159 (defun org-refile-new-child (parent-target child)
9160 "Use refile target PARENT-TARGET to add new CHILD below it."
9161 (unless parent-target
9162 (error "Cannot find parent for new node"))
9163 (let ((file (nth 1 parent-target))
9164 (pos (nth 3 parent-target))
9165 level)
9166 (with-current-buffer (or (find-buffer-visiting file)
9167 (find-file-noselect file))
9168 (save-excursion
9169 (save-restriction
9170 (widen)
9171 (if pos
9172 (goto-char pos)
9173 (goto-char (point-max))
9174 (if (not (bolp)) (newline)))
9175 (when (looking-at outline-regexp)
9176 (setq level (funcall outline-level))
9177 (org-end-of-subtree t t))
9178 (org-back-over-empty-lines)
9179 (insert "\n" (make-string
9180 (if pos (org-get-valid-level level 1) 1) ?*)
9181 " " child "\n")
9182 (beginning-of-line 0)
9183 (list (concat (car parent-target) "/" child) file "" (point)))))))
9185 (defun org-olpath-completing-read (prompt collection &rest args)
9186 "Read an outline path like a file name."
9187 (let ((thetable collection)
9188 (org-completion-use-ido nil) ; does not work with ido.
9189 (org-completion-use-iswitchb nil)) ; or iswitchb
9190 (apply
9191 'org-icompleting-read prompt
9192 (lambda (string predicate &optional flag)
9193 (let (rtn r f (l (length string)))
9194 (cond
9195 ((eq flag nil)
9196 ;; try completion
9197 (try-completion string thetable))
9198 ((eq flag t)
9199 ;; all-completions
9200 (setq rtn (all-completions string thetable predicate))
9201 (mapcar
9202 (lambda (x)
9203 (setq r (substring x l))
9204 (if (string-match " ([^)]*)$" x)
9205 (setq f (match-string 0 x))
9206 (setq f ""))
9207 (if (string-match "/" r)
9208 (concat string (substring r 0 (match-end 0)) f)
9210 rtn))
9211 ((eq flag 'lambda)
9212 ;; exact match?
9213 (assoc string thetable)))
9215 args)))
9217 ;;;; Dynamic blocks
9219 (defun org-find-dblock (name)
9220 "Find the first dynamic block with name NAME in the buffer.
9221 If not found, stay at current position and return nil."
9222 (let (pos)
9223 (save-excursion
9224 (goto-char (point-min))
9225 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9226 nil t)
9227 (match-beginning 0))))
9228 (if pos (goto-char pos))
9229 pos))
9231 (defconst org-dblock-start-re
9232 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9233 "Matches the startline of a dynamic block, with parameters.")
9235 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9236 "Matches the end of a dynamic block.")
9238 (defun org-create-dblock (plist)
9239 "Create a dynamic block section, with parameters taken from PLIST.
9240 PLIST must contain a :name entry which is used as name of the block."
9241 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9242 (end-of-line 1)
9243 (newline))
9244 (let ((col (current-column))
9245 (name (plist-get plist :name)))
9246 (insert "#+BEGIN: " name)
9247 (while plist
9248 (if (eq (car plist) :name)
9249 (setq plist (cddr plist))
9250 (insert " " (prin1-to-string (pop plist)))))
9251 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9252 (beginning-of-line -2)))
9254 (defun org-prepare-dblock ()
9255 "Prepare dynamic block for refresh.
9256 This empties the block, puts the cursor at the insert position and returns
9257 the property list including an extra property :name with the block name."
9258 (unless (looking-at org-dblock-start-re)
9259 (error "Not at a dynamic block"))
9260 (let* ((begdel (1+ (match-end 0)))
9261 (name (org-no-properties (match-string 1)))
9262 (params (append (list :name name)
9263 (read (concat "(" (match-string 3) ")")))))
9264 (save-excursion
9265 (beginning-of-line 1)
9266 (skip-chars-forward " \t")
9267 (setq params (plist-put params :indentation-column (current-column))))
9268 (unless (re-search-forward org-dblock-end-re nil t)
9269 (error "Dynamic block not terminated"))
9270 (setq params
9271 (append params
9272 (list :content (buffer-substring
9273 begdel (match-beginning 0)))))
9274 (delete-region begdel (match-beginning 0))
9275 (goto-char begdel)
9276 (open-line 1)
9277 params))
9279 (defun org-map-dblocks (&optional command)
9280 "Apply COMMAND to all dynamic blocks in the current buffer.
9281 If COMMAND is not given, use `org-update-dblock'."
9282 (let ((cmd (or command 'org-update-dblock))
9283 pos)
9284 (save-excursion
9285 (goto-char (point-min))
9286 (while (re-search-forward org-dblock-start-re nil t)
9287 (goto-char (setq pos (match-beginning 0)))
9288 (condition-case nil
9289 (funcall cmd)
9290 (error (message "Error during update of dynamic block")))
9291 (goto-char pos)
9292 (unless (re-search-forward org-dblock-end-re nil t)
9293 (error "Dynamic block not terminated"))))))
9295 (defun org-dblock-update (&optional arg)
9296 "User command for updating dynamic blocks.
9297 Update the dynamic block at point. With prefix ARG, update all dynamic
9298 blocks in the buffer."
9299 (interactive "P")
9300 (if arg
9301 (org-update-all-dblocks)
9302 (or (looking-at org-dblock-start-re)
9303 (org-beginning-of-dblock))
9304 (org-update-dblock)))
9306 (defun org-update-dblock ()
9307 "Update the dynamic block at point
9308 This means to empty the block, parse for parameters and then call
9309 the correct writing function."
9310 (save-window-excursion
9311 (let* ((pos (point))
9312 (line (org-current-line))
9313 (params (org-prepare-dblock))
9314 (name (plist-get params :name))
9315 (indent (plist-get params :indentation-column))
9316 (cmd (intern (concat "org-dblock-write:" name))))
9317 (message "Updating dynamic block `%s' at line %d..." name line)
9318 (funcall cmd params)
9319 (message "Updating dynamic block `%s' at line %d...done" name line)
9320 (goto-char pos)
9321 (when (and indent (> indent 0))
9322 (setq indent (make-string indent ?\ ))
9323 (save-excursion
9324 (org-beginning-of-dblock)
9325 (forward-line 1)
9326 (while (not (looking-at org-dblock-end-re))
9327 (insert indent)
9328 (beginning-of-line 2))
9329 (when (looking-at org-dblock-end-re)
9330 (and (looking-at "[ \t]+")
9331 (replace-match ""))
9332 (insert indent)))))))
9334 (defun org-beginning-of-dblock ()
9335 "Find the beginning of the dynamic block at point.
9336 Error if there is no such block at point."
9337 (let ((pos (point))
9338 beg)
9339 (end-of-line 1)
9340 (if (and (re-search-backward org-dblock-start-re nil t)
9341 (setq beg (match-beginning 0))
9342 (re-search-forward org-dblock-end-re nil t)
9343 (> (match-end 0) pos))
9344 (goto-char beg)
9345 (goto-char pos)
9346 (error "Not in a dynamic block"))))
9348 (defun org-update-all-dblocks ()
9349 "Update all dynamic blocks in the buffer.
9350 This function can be used in a hook."
9351 (when (org-mode-p)
9352 (org-map-dblocks 'org-update-dblock)))
9355 ;;;; Completion
9357 (defconst org-additional-option-like-keywords
9358 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9359 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9360 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "LATEX_CLASS:" "ATTR_LaTeX"
9361 "BEGIN:" "END:"
9362 "ORGTBL" "TBLFM:" "TBLNAME:"
9363 "BEGIN_EXAMPLE" "END_EXAMPLE"
9364 "BEGIN_QUOTE" "END_QUOTE"
9365 "BEGIN_VERSE" "END_VERSE"
9366 "BEGIN_CENTER" "END_CENTER"
9367 "BEGIN_SRC" "END_SRC"
9368 "CATEGORY" "COLUMNS"
9369 "CAPTION" "LABEL"
9370 "SETUPFILE"
9371 "BIND"
9372 "MACRO"))
9374 (defcustom org-structure-template-alist
9376 ("s" "#+begin_src ?\n\n#+end_src"
9377 "<src lang=\"?\">\n\n</src>")
9378 ("e" "#+begin_example\n?\n#+end_example"
9379 "<example>\n?\n</example>")
9380 ("q" "#+begin_quote\n?\n#+end_quote"
9381 "<quote>\n?\n</quote>")
9382 ("v" "#+begin_verse\n?\n#+end_verse"
9383 "<verse>\n?\n/verse>")
9384 ("c" "#+begin_center\n?\n#+end_center"
9385 "<center>\n?\n/center>")
9386 ("l" "#+begin_latex\n?\n#+end_latex"
9387 "<literal style=\"latex\">\n?\n</literal>")
9388 ("L" "#+latex: "
9389 "<literal style=\"latex\">?</literal>")
9390 ("h" "#+begin_html\n?\n#+end_html"
9391 "<literal style=\"html\">\n?\n</literal>")
9392 ("H" "#+html: "
9393 "<literal style=\"html\">?</literal>")
9394 ("a" "#+begin_ascii\n?\n#+end_ascii")
9395 ("A" "#+ascii: ")
9396 ("i" "#+include %file ?"
9397 "<include file=%file markup=\"?\">")
9399 "Structure completion elements.
9400 This is a list of abbreviation keys and values. The value gets inserted
9401 it you type @samp{.} followed by the key and then the completion key,
9402 usually `M-TAB'. %file will be replaced by a file name after prompting
9403 for the file using completion.
9404 There are two templates for each key, the first uses the original Org syntax,
9405 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9406 the default when the /org-mtags.el/ module has been loaded. See also the
9407 variable `org-mtags-prefer-muse-templates'.
9408 This is an experimental feature, it is undecided if it is going to stay in."
9409 :group 'org-completion
9410 :type '(repeat
9411 (string :tag "Key")
9412 (string :tag "Template")
9413 (string :tag "Muse Template")))
9415 (defun org-try-structure-completion ()
9416 "Try to complete a structure template before point.
9417 This looks for strings like \"<e\" on an otherwise empty line and
9418 expands them."
9419 (let ((l (buffer-substring (point-at-bol) (point)))
9421 (when (and (looking-at "[ \t]*$")
9422 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9423 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9424 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9425 (match-beginning 1)) a)
9426 t)))
9428 (defun org-complete-expand-structure-template (start cell)
9429 "Expand a structure template."
9430 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9431 (rpl (nth (if musep 2 1) cell))
9432 (ind ""))
9433 (delete-region start (point))
9434 (when (string-match "\\`#\\+" rpl)
9435 (cond
9436 ((bolp))
9437 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9438 (setq ind (buffer-substring (point-at-bol) (point))))
9439 (t (newline))))
9440 (setq start (point))
9441 (if (string-match "%file" rpl)
9442 (setq rpl (replace-match
9443 (concat
9444 "\""
9445 (save-match-data
9446 (abbreviate-file-name (read-file-name "Include file: ")))
9447 "\"")
9448 t t rpl)))
9449 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9450 (concat "\n" ind)))
9451 (insert rpl)
9452 (if (re-search-backward "\\?" start t) (delete-char 1))))
9455 (defun org-complete (&optional arg)
9456 "Perform completion on word at point.
9457 At the beginning of a headline, this completes TODO keywords as given in
9458 `org-todo-keywords'.
9459 If the current word is preceded by a backslash, completes the TeX symbols
9460 that are supported for HTML support.
9461 If the current word is preceded by \"#+\", completes special words for
9462 setting file options.
9463 In the line after \"#+STARTUP:, complete valid keywords.\"
9464 At all other locations, this simply calls the value of
9465 `org-completion-fallback-command'."
9466 (interactive "P")
9467 (org-without-partial-completion
9468 (catch 'exit
9469 (let* ((a nil)
9470 (end (point))
9471 (beg1 (save-excursion
9472 (skip-chars-backward (org-re "[:alnum:]_@"))
9473 (point)))
9474 (beg (save-excursion
9475 (skip-chars-backward "a-zA-Z0-9_:$")
9476 (point)))
9477 (confirm (lambda (x) (stringp (car x))))
9478 (searchhead (equal (char-before beg) ?*))
9479 (struct
9480 (when (and (member (char-before beg1) '(?. ?<))
9481 (setq a (assoc (buffer-substring beg1 (point))
9482 org-structure-template-alist)))
9483 (org-complete-expand-structure-template (1- beg1) a)
9484 (throw 'exit t)))
9485 (tag (and (equal (char-before beg1) ?:)
9486 (equal (char-after (point-at-bol)) ?*)))
9487 (prop (and (equal (char-before beg1) ?:)
9488 (not (equal (char-after (point-at-bol)) ?*))))
9489 (texp (equal (char-before beg) ?\\))
9490 (link (equal (char-before beg) ?\[))
9491 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9492 beg)
9493 "#+"))
9494 (startup (string-match "^#\\+STARTUP:.*"
9495 (buffer-substring (point-at-bol) (point))))
9496 (completion-ignore-case opt)
9497 (type nil)
9498 (tbl nil)
9499 (table (cond
9500 (opt
9501 (setq type :opt)
9502 (require 'org-exp)
9503 (append
9504 (delq nil
9505 (mapcar
9506 (lambda (x)
9507 (if (string-match
9508 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9509 (cons (match-string 2 x)
9510 (match-string 1 x))))
9511 (org-split-string (org-get-current-options) "\n")))
9512 (mapcar 'list org-additional-option-like-keywords)))
9513 (startup
9514 (setq type :startup)
9515 org-startup-options)
9516 (link (append org-link-abbrev-alist-local
9517 org-link-abbrev-alist))
9518 (texp
9519 (setq type :tex)
9520 org-html-entities)
9521 ((string-match "\\`\\*+[ \t]+\\'"
9522 (buffer-substring (point-at-bol) beg))
9523 (setq type :todo)
9524 (mapcar 'list org-todo-keywords-1))
9525 (searchhead
9526 (setq type :searchhead)
9527 (save-excursion
9528 (goto-char (point-min))
9529 (while (re-search-forward org-todo-line-regexp nil t)
9530 (push (list
9531 (org-make-org-heading-search-string
9532 (match-string 3) t))
9533 tbl)))
9534 tbl)
9535 (tag (setq type :tag beg beg1)
9536 (or org-tag-alist (org-get-buffer-tags)))
9537 (prop (setq type :prop beg beg1)
9538 (mapcar 'list (org-buffer-property-keys nil t t)))
9539 (t (progn
9540 (call-interactively org-completion-fallback-command)
9541 (throw 'exit nil)))))
9542 (pattern (buffer-substring-no-properties beg end))
9543 (completion (try-completion pattern table confirm)))
9544 (cond ((eq completion t)
9545 (if (not (assoc (upcase pattern) table))
9546 (message "Already complete")
9547 (if (and (equal type :opt)
9548 (not (member (car (assoc (upcase pattern) table))
9549 org-additional-option-like-keywords)))
9550 (insert (substring (cdr (assoc (upcase pattern) table))
9551 (length pattern)))
9552 (if (memq type '(:tag :prop)) (insert ":")))))
9553 ((null completion)
9554 (message "Can't find completion for \"%s\"" pattern)
9555 (ding))
9556 ((not (string= pattern completion))
9557 (delete-region beg end)
9558 (if (string-match " +$" completion)
9559 (setq completion (replace-match "" t t completion)))
9560 (insert completion)
9561 (if (get-buffer-window "*Completions*")
9562 (delete-window (get-buffer-window "*Completions*")))
9563 (if (assoc completion table)
9564 (if (eq type :todo) (insert " ")
9565 (if (memq type '(:tag :prop)) (insert ":"))))
9566 (if (and (equal type :opt) (assoc completion table))
9567 (message "%s" (substitute-command-keys
9568 "Press \\[org-complete] again to insert example settings"))))
9570 (message "Making completion list...")
9571 (let ((list (sort (all-completions pattern table confirm)
9572 'string<)))
9573 (with-output-to-temp-buffer "*Completions*"
9574 (condition-case nil
9575 ;; Protection needed for XEmacs and emacs 21
9576 (display-completion-list list pattern)
9577 (error (display-completion-list list)))))
9578 (message "Making completion list...%s" "done")))))))
9580 ;;;; TODO, DEADLINE, Comments
9582 (defun org-toggle-comment ()
9583 "Change the COMMENT state of an entry."
9584 (interactive)
9585 (save-excursion
9586 (org-back-to-heading)
9587 (let (case-fold-search)
9588 (if (looking-at (concat outline-regexp
9589 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9590 (replace-match "" t t nil 1)
9591 (if (looking-at outline-regexp)
9592 (progn
9593 (goto-char (match-end 0))
9594 (insert org-comment-string " ")))))))
9596 (defvar org-last-todo-state-is-todo nil
9597 "This is non-nil when the last TODO state change led to a TODO state.
9598 If the last change removed the TODO tag or switched to DONE, then
9599 this is nil.")
9601 (defvar org-setting-tags nil) ; dynamically skipped
9603 (defun org-parse-local-options (string var)
9604 "Parse STRING for startup setting relevant for variable VAR."
9605 (let ((rtn (symbol-value var))
9606 e opts)
9607 (save-match-data
9608 (if (or (not string) (not (string-match "\\S-" string)))
9610 (setq opts (delq nil (mapcar (lambda (x)
9611 (setq e (assoc x org-startup-options))
9612 (if (eq (nth 1 e) var) e nil))
9613 (org-split-string string "[ \t]+"))))
9614 (if (not opts)
9616 (setq rtn nil)
9617 (while (setq e (pop opts))
9618 (if (not (nth 3 e))
9619 (setq rtn (nth 2 e))
9620 (if (not (listp rtn)) (setq rtn nil))
9621 (push (nth 2 e) rtn)))
9622 rtn)))))
9624 (defvar org-todo-setup-filter-hook nil
9625 "Hook for functions that pre-filter todo specs.
9627 Each function takes a todo spec and returns either `nil' or the spec
9628 transformed into canonical form." )
9630 (defvar org-todo-get-default-hook nil
9631 "Hook for functions that get a default item for todo.
9633 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9634 `nil' or a string to be used for the todo mark." )
9636 (defvar org-agenda-headline-snapshot-before-repeat)
9638 (defun org-todo (&optional arg)
9639 "Change the TODO state of an item.
9640 The state of an item is given by a keyword at the start of the heading,
9641 like
9642 *** TODO Write paper
9643 *** DONE Call mom
9645 The different keywords are specified in the variable `org-todo-keywords'.
9646 By default the available states are \"TODO\" and \"DONE\".
9647 So for this example: when the item starts with TODO, it is changed to DONE.
9648 When it starts with DONE, the DONE is removed. And when neither TODO nor
9649 DONE are present, add TODO at the beginning of the heading.
9651 With C-u prefix arg, use completion to determine the new state.
9652 With numeric prefix arg, switch to that state.
9653 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9654 With a tripple C-u prefix, circumvent any state blocking.
9656 For calling through lisp, arg is also interpreted in the following way:
9657 'none -> empty state
9658 \"\"(empty string) -> switch to empty state
9659 'done -> switch to DONE
9660 'nextset -> switch to the next set of keywords
9661 'previousset -> switch to the previous set of keywords
9662 \"WAITING\" -> switch to the specified keyword, but only if it
9663 really is a member of `org-todo-keywords'."
9664 (interactive "P")
9665 (if (equal arg '(16)) (setq arg 'nextset))
9666 (let ((org-blocker-hook org-blocker-hook)
9667 (case-fold-search nil))
9668 (when (equal arg '(64))
9669 (setq arg nil org-blocker-hook nil))
9670 (when (and org-blocker-hook
9671 (or org-inhibit-blocking
9672 (org-entry-get nil "NOBLOCKING")))
9673 (setq org-blocker-hook nil))
9674 (save-excursion
9675 (catch 'exit
9676 (org-back-to-heading t)
9677 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9678 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9679 (looking-at " *"))
9680 (let* ((match-data (match-data))
9681 (startpos (point-at-bol))
9682 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9683 (org-log-done org-log-done)
9684 (org-log-repeat org-log-repeat)
9685 (org-todo-log-states org-todo-log-states)
9686 (this (match-string 1))
9687 (hl-pos (match-beginning 0))
9688 (head (org-get-todo-sequence-head this))
9689 (ass (assoc head org-todo-kwd-alist))
9690 (interpret (nth 1 ass))
9691 (done-word (nth 3 ass))
9692 (final-done-word (nth 4 ass))
9693 (last-state (or this ""))
9694 (completion-ignore-case t)
9695 (member (member this org-todo-keywords-1))
9696 (tail (cdr member))
9697 (state (cond
9698 ((and org-todo-key-trigger
9699 (or (and (equal arg '(4))
9700 (eq org-use-fast-todo-selection 'prefix))
9701 (and (not arg) org-use-fast-todo-selection
9702 (not (eq org-use-fast-todo-selection
9703 'prefix)))))
9704 ;; Use fast selection
9705 (org-fast-todo-selection))
9706 ((and (equal arg '(4))
9707 (or (not org-use-fast-todo-selection)
9708 (not org-todo-key-trigger)))
9709 ;; Read a state with completion
9710 (org-icompleting-read
9711 "State: " (mapcar (lambda(x) (list x))
9712 org-todo-keywords-1)
9713 nil t))
9714 ((eq arg 'right)
9715 (if this
9716 (if tail (car tail) nil)
9717 (car org-todo-keywords-1)))
9718 ((eq arg 'left)
9719 (if (equal member org-todo-keywords-1)
9721 (if this
9722 (nth (- (length org-todo-keywords-1)
9723 (length tail) 2)
9724 org-todo-keywords-1)
9725 (org-last org-todo-keywords-1))))
9726 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9727 (setq arg nil))) ; hack to fall back to cycling
9728 (arg
9729 ;; user or caller requests a specific state
9730 (cond
9731 ((equal arg "") nil)
9732 ((eq arg 'none) nil)
9733 ((eq arg 'done) (or done-word (car org-done-keywords)))
9734 ((eq arg 'nextset)
9735 (or (car (cdr (member head org-todo-heads)))
9736 (car org-todo-heads)))
9737 ((eq arg 'previousset)
9738 (let ((org-todo-heads (reverse org-todo-heads)))
9739 (or (car (cdr (member head org-todo-heads)))
9740 (car org-todo-heads))))
9741 ((car (member arg org-todo-keywords-1)))
9742 ((stringp arg)
9743 (error "State `%s' not valid in this file" arg))
9744 ((nth (1- (prefix-numeric-value arg))
9745 org-todo-keywords-1))))
9746 ((null member) (or head (car org-todo-keywords-1)))
9747 ((equal this final-done-word) nil) ;; -> make empty
9748 ((null tail) nil) ;; -> first entry
9749 ((memq interpret '(type priority))
9750 (if (eq this-command last-command)
9751 (car tail)
9752 (if (> (length tail) 0)
9753 (or done-word (car org-done-keywords))
9754 nil)))
9756 (car tail))))
9757 (state (or
9758 (run-hook-with-args-until-success
9759 'org-todo-get-default-hook state last-state)
9760 state))
9761 (next (if state (concat " " state " ") " "))
9762 (change-plist (list :type 'todo-state-change :from this :to state
9763 :position startpos))
9764 dolog now-done-p)
9765 (when org-blocker-hook
9766 (setq org-last-todo-state-is-todo
9767 (not (member this org-done-keywords)))
9768 (unless (save-excursion
9769 (save-match-data
9770 (run-hook-with-args-until-failure
9771 'org-blocker-hook change-plist)))
9772 (if (interactive-p)
9773 (error "TODO state change from %s to %s blocked" this state)
9774 ;; fail silently
9775 (message "TODO state change from %s to %s blocked" this state)
9776 (throw 'exit nil))))
9777 (store-match-data match-data)
9778 (replace-match next t t)
9779 (unless (pos-visible-in-window-p hl-pos)
9780 (message "TODO state changed to %s" (org-trim next)))
9781 (unless head
9782 (setq head (org-get-todo-sequence-head state)
9783 ass (assoc head org-todo-kwd-alist)
9784 interpret (nth 1 ass)
9785 done-word (nth 3 ass)
9786 final-done-word (nth 4 ass)))
9787 (when (memq arg '(nextset previousset))
9788 (message "Keyword-Set %d/%d: %s"
9789 (- (length org-todo-sets) -1
9790 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9791 (length org-todo-sets)
9792 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9793 (setq org-last-todo-state-is-todo
9794 (not (member state org-done-keywords)))
9795 (setq now-done-p (and (member state org-done-keywords)
9796 (not (member this org-done-keywords))))
9797 (and logging (org-local-logging logging))
9798 (when (and (or org-todo-log-states org-log-done)
9799 (not (eq org-inhibit-logging t))
9800 (not (memq arg '(nextset previousset))))
9801 ;; we need to look at recording a time and note
9802 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9803 (nth 2 (assoc this org-todo-log-states))))
9804 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9805 (setq dolog 'time))
9806 (when (and state
9807 (member state org-not-done-keywords)
9808 (not (member this org-not-done-keywords)))
9809 ;; This is now a todo state and was not one before
9810 ;; If there was a CLOSED time stamp, get rid of it.
9811 (org-add-planning-info nil nil 'closed))
9812 (when (and now-done-p org-log-done)
9813 ;; It is now done, and it was not done before
9814 (org-add-planning-info 'closed (org-current-time))
9815 (if (and (not dolog) (eq 'note org-log-done))
9816 (org-add-log-setup 'done state this 'findpos 'note)))
9817 (when (and state dolog)
9818 ;; This is a non-nil state, and we need to log it
9819 (org-add-log-setup 'state state this 'findpos dolog)))
9820 ;; Fixup tag positioning
9821 (org-todo-trigger-tag-changes state)
9822 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9823 (when org-provide-todo-statistics
9824 (org-update-parent-todo-statistics))
9825 (run-hooks 'org-after-todo-state-change-hook)
9826 (if (and arg (not (member state org-done-keywords)))
9827 (setq head (org-get-todo-sequence-head state)))
9828 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9829 ;; Do we need to trigger a repeat?
9830 (when now-done-p
9831 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9832 ;; This is for the agenda, take a snapshot of the headline.
9833 (save-match-data
9834 (setq org-agenda-headline-snapshot-before-repeat
9835 (org-get-heading))))
9836 (org-auto-repeat-maybe state))
9837 ;; Fixup cursor location if close to the keyword
9838 (if (and (outline-on-heading-p)
9839 (not (bolp))
9840 (save-excursion (beginning-of-line 1)
9841 (looking-at org-todo-line-regexp))
9842 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9843 (progn
9844 (goto-char (or (match-end 2) (match-end 1)))
9845 (and (looking-at " ") (just-one-space))))
9846 (when org-trigger-hook
9847 (save-excursion
9848 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9850 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9851 "Block turning an entry into a TODO, using the hierarchy.
9852 This checks whether the current task should be blocked from state
9853 changes. Such blocking occurs when:
9855 1. The task has children which are not all in a completed state.
9857 2. A task has a parent with the property :ORDERED:, and there
9858 are siblings prior to the current task with incomplete
9859 status.
9861 3. The parent of the task is blocked because it has siblings that should
9862 be done first, or is child of a block grandparent TODO entry."
9864 (catch 'dont-block
9865 ;; If this is not a todo state change, or if this entry is already DONE,
9866 ;; do not block
9867 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9868 (member (plist-get change-plist :from)
9869 (cons 'done org-done-keywords))
9870 (member (plist-get change-plist :to)
9871 (cons 'todo org-not-done-keywords)))
9872 (throw 'dont-block t))
9873 ;; If this task has children, and any are undone, it's blocked
9874 (save-excursion
9875 (org-back-to-heading t)
9876 (let ((this-level (funcall outline-level)))
9877 (outline-next-heading)
9878 (let ((child-level (funcall outline-level)))
9879 (while (and (not (eobp))
9880 (> child-level this-level))
9881 ;; this todo has children, check whether they are all
9882 ;; completed
9883 (if (and (not (org-entry-is-done-p))
9884 (org-entry-is-todo-p))
9885 (throw 'dont-block nil))
9886 (outline-next-heading)
9887 (setq child-level (funcall outline-level))))))
9888 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9889 ;; any previous siblings are undone, it's blocked
9890 (save-excursion
9891 (org-back-to-heading t)
9892 (let* ((pos (point))
9893 (parent-pos (and (org-up-heading-safe) (point))))
9894 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9895 (when (and (org-entry-get (point) "ORDERED")
9896 (forward-line 1)
9897 (re-search-forward org-not-done-heading-regexp pos t))
9898 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9899 ;; Search further up the hierarchy, to see if an anchestor is blocked
9900 (while t
9901 (goto-char parent-pos)
9902 (if (not (looking-at org-not-done-heading-regexp))
9903 (throw 'dont-block t)) ; do not block, parent is not a TODO
9904 (setq pos (point))
9905 (setq parent-pos (and (org-up-heading-safe) (point)))
9906 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9907 (when (and (org-entry-get (point) "ORDERED")
9908 (forward-line 1)
9909 (re-search-forward org-not-done-heading-regexp pos t))
9910 (throw 'dont-block nil))))))) ; block, older sibling not done.
9912 (defcustom org-track-ordered-property-with-tag nil
9913 "Should the ORDERED property also be shown as a tag?
9914 The ORDERED property decides if an entry should require subtasks to be
9915 completed in sequence. Since a property is not very visible, setting
9916 this option means that toggling the ORDERED property with the command
9917 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9918 not relevant for the behavior, but it makes things more visible.
9920 Note that toggling the tag with tags commands will not change the property
9921 and therefore not influence behavior!
9923 This can be t, meaning the tag ORDERED should be used, It can also be a
9924 string to select a different tag for this task."
9925 :group 'org-todo
9926 :type '(choice
9927 (const :tag "No tracking" nil)
9928 (const :tag "Track with ORDERED tag" t)
9929 (string :tag "Use other tag")))
9931 (defun org-toggle-ordered-property ()
9932 "Toggle the ORDERED property of the current entry.
9933 For better visibility, you can track the value of this property with a tag.
9934 See variable `org-track-ordered-property-with-tag'."
9935 (interactive)
9936 (let* ((t1 org-track-ordered-property-with-tag)
9937 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9938 (save-excursion
9939 (org-back-to-heading)
9940 (if (org-entry-get nil "ORDERED")
9941 (progn
9942 (org-delete-property "ORDERED")
9943 (and tag (org-toggle-tag tag 'off))
9944 (message "Subtasks can be completed in arbitrary order"))
9945 (org-entry-put nil "ORDERED" "t")
9946 (and tag (org-toggle-tag tag 'on))
9947 (message "Subtasks must be completed in sequence")))))
9949 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9950 (defun org-block-todo-from-checkboxes (change-plist)
9951 "Block turning an entry into a TODO, using checkboxes.
9952 This checks whether the current task should be blocked from state
9953 changes because there are uncheckd boxes in this entry."
9954 (catch 'dont-block
9955 ;; If this is not a todo state change, or if this entry is already DONE,
9956 ;; do not block
9957 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9958 (member (plist-get change-plist :from)
9959 (cons 'done org-done-keywords))
9960 (member (plist-get change-plist :to)
9961 (cons 'todo org-not-done-keywords)))
9962 (throw 'dont-block t))
9963 ;; If this task has checkboxes that are not checked, it's blocked
9964 (save-excursion
9965 (org-back-to-heading t)
9966 (let ((beg (point)) end)
9967 (outline-next-heading)
9968 (setq end (point))
9969 (goto-char beg)
9970 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9971 end t)
9972 (progn
9973 (if (boundp 'org-blocked-by-checkboxes)
9974 (setq org-blocked-by-checkboxes t))
9975 (throw 'dont-block nil)))))
9976 t)) ; do not block
9978 (defun org-update-statistics-cookies (all)
9979 "Update the statistics cookie, either from TODO or from checkboxes.
9980 This should be called with the cursor in a line with a statistics cookie."
9981 (interactive "P")
9982 (if all
9983 (progn
9984 (org-update-checkbox-count 'all)
9985 (org-map-entries 'org-update-parent-todo-statistics))
9986 (if (not (org-on-heading-p))
9987 (org-update-checkbox-count)
9988 (let ((pos (move-marker (make-marker) (point)))
9989 end l1 l2)
9990 (ignore-errors (org-back-to-heading t))
9991 (if (not (org-on-heading-p))
9992 (org-update-checkbox-count)
9993 (setq l1 (org-outline-level))
9994 (setq end (save-excursion
9995 (outline-next-heading)
9996 (if (org-on-heading-p) (setq l2 (org-outline-level)))
9997 (point)))
9998 (if (and (save-excursion (re-search-forward
9999 "^[ \t]*[-+*] \\[[- X]\\]" end t))
10000 (not (save-excursion (re-search-forward
10001 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10002 (org-update-checkbox-count)
10003 (if (and l2 (> l2 l1))
10004 (progn
10005 (goto-char end)
10006 (org-update-parent-todo-statistics))
10007 (error "No data for statistics cookie"))))
10008 (goto-char pos)
10009 (move-marker pos nil)))))
10011 (defvar org-entry-property-inherited-from) ;; defined below
10012 (defun org-update-parent-todo-statistics ()
10013 "Update any statistics cookie in the parent of the current headline.
10014 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10015 the entire subtree and this will travel up the hierarchy and update
10016 statistics everywhere."
10017 (interactive)
10018 (let* ((lim 0) prop
10019 (recursive (or (not org-hierarchical-todo-statistics)
10020 (string-match
10021 "\\<recursive\\>"
10022 (or (setq prop (org-entry-get
10023 nil "COOKIE_DATA" 'inherit)) ""))))
10024 (lim (or (and prop (marker-position
10025 org-entry-property-inherited-from))
10026 lim))
10027 (first t)
10028 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10029 level ltoggle l1 new ndel
10030 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10031 (catch 'exit
10032 (save-excursion
10033 (beginning-of-line 1)
10034 (if (org-at-heading-p)
10035 (setq ltoggle (funcall outline-level))
10036 (error "This should not happen"))
10037 (while (and (setq level (org-up-heading-safe))
10038 (or recursive first)
10039 (>= (point) lim))
10040 (setq first nil cookie-present nil)
10041 (unless (and level
10042 (not (string-match
10043 "\\<checkbox\\>"
10044 (downcase
10045 (or (org-entry-get
10046 nil "COOKIE_DATA")
10047 "")))))
10048 (throw 'exit nil))
10049 (while (re-search-forward box-re (point-at-eol) t)
10050 (setq cnt-all 0 cnt-done 0 cookie-present t)
10051 (setq is-percent (match-end 2))
10052 (save-match-data
10053 (unless (outline-next-heading) (throw 'exit nil))
10054 (while (and (looking-at org-complex-heading-regexp)
10055 (> (setq l1 (length (match-string 1))) level))
10056 (setq kwd (and (or recursive (= l1 ltoggle))
10057 (match-string 2)))
10058 (if (or (eq org-provide-todo-statistics 'all-headlines)
10059 (and (listp org-provide-todo-statistics)
10060 (or (member kwd org-provide-todo-statistics)
10061 (member kwd org-done-keywords))))
10062 (setq cnt-all (1+ cnt-all))
10063 (if (eq org-provide-todo-statistics t)
10064 (and kwd (setq cnt-all (1+ cnt-all)))))
10065 (and (member kwd org-done-keywords)
10066 (setq cnt-done (1+ cnt-done)))
10067 (outline-next-heading)))
10068 (setq new
10069 (if is-percent
10070 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10071 (format "[%d/%d]" cnt-done cnt-all))
10072 ndel (- (match-end 0) (match-beginning 0)))
10073 (goto-char (match-beginning 0))
10074 (insert new)
10075 (delete-region (point) (+ (point) ndel)))
10076 (when cookie-present
10077 (run-hook-with-args 'org-after-todo-statistics-hook
10078 cnt-done (- cnt-all cnt-done))))))
10079 (run-hooks 'org-todo-statistics-hook)))
10081 (defvar org-after-todo-statistics-hook nil
10082 "Hook that is called after a TODO statistics cookie has been updated.
10083 Each function is called with two arguments: the number of not-done entries
10084 and the number of done entries.
10086 For example, the following function, when added to this hook, will switch
10087 an entry to DONE when all children are done, and back to TODO when new
10088 entries are set to a TODO status. Note that this hook is only called
10089 when there is a statistics cookie in the headline!
10091 (defun org-summary-todo (n-done n-not-done)
10092 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10093 (let (org-log-done org-log-states) ; turn off logging
10094 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10097 (defvar org-todo-statistics-hook nil
10098 "Hook that is run whenever Org thinks TODO statistics should be updated.
10099 This hook runs even if there is no statisics cookie present, in which case
10100 `org-after-todo-statistics-hook' would not run.")
10102 (defun org-todo-trigger-tag-changes (state)
10103 "Apply the changes defined in `org-todo-state-tags-triggers'."
10104 (let ((l org-todo-state-tags-triggers)
10105 changes)
10106 (when (or (not state) (equal state ""))
10107 (setq changes (append changes (cdr (assoc "" l)))))
10108 (when (and (stringp state) (> (length state) 0))
10109 (setq changes (append changes (cdr (assoc state l)))))
10110 (when (member state org-not-done-keywords)
10111 (setq changes (append changes (cdr (assoc 'todo l)))))
10112 (when (member state org-done-keywords)
10113 (setq changes (append changes (cdr (assoc 'done l)))))
10114 (dolist (c changes)
10115 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10117 (defun org-local-logging (value)
10118 "Get logging settings from a property VALUE."
10119 (let* (words w a)
10120 ;; directly set the variables, they are already local.
10121 (setq org-log-done nil
10122 org-log-repeat nil
10123 org-todo-log-states nil)
10124 (setq words (org-split-string value))
10125 (while (setq w (pop words))
10126 (cond
10127 ((setq a (assoc w org-startup-options))
10128 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10129 (set (nth 1 a) (nth 2 a))))
10130 ((setq a (org-extract-log-state-settings w))
10131 (and (member (car a) org-todo-keywords-1)
10132 (push a org-todo-log-states)))))))
10134 (defun org-get-todo-sequence-head (kwd)
10135 "Return the head of the TODO sequence to which KWD belongs.
10136 If KWD is not set, check if there is a text property remembering the
10137 right sequence."
10138 (let (p)
10139 (cond
10140 ((not kwd)
10141 (or (get-text-property (point-at-bol) 'org-todo-head)
10142 (progn
10143 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10144 nil (point-at-eol)))
10145 (get-text-property p 'org-todo-head))))
10146 ((not (member kwd org-todo-keywords-1))
10147 (car org-todo-keywords-1))
10148 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10150 (defun org-fast-todo-selection ()
10151 "Fast TODO keyword selection with single keys.
10152 Returns the new TODO keyword, or nil if no state change should occur."
10153 (let* ((fulltable org-todo-key-alist)
10154 (done-keywords org-done-keywords) ;; needed for the faces.
10155 (maxlen (apply 'max (mapcar
10156 (lambda (x)
10157 (if (stringp (car x)) (string-width (car x)) 0))
10158 fulltable)))
10159 (expert nil)
10160 (fwidth (+ maxlen 3 1 3))
10161 (ncol (/ (- (window-width) 4) fwidth))
10162 tg cnt e c tbl
10163 groups ingroup)
10164 (save-excursion
10165 (save-window-excursion
10166 (if expert
10167 (set-buffer (get-buffer-create " *Org todo*"))
10168 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10169 (erase-buffer)
10170 (org-set-local 'org-done-keywords done-keywords)
10171 (setq tbl fulltable cnt 0)
10172 (while (setq e (pop tbl))
10173 (cond
10174 ((equal e '(:startgroup))
10175 (push '() groups) (setq ingroup t)
10176 (when (not (= cnt 0))
10177 (setq cnt 0)
10178 (insert "\n"))
10179 (insert "{ "))
10180 ((equal e '(:endgroup))
10181 (setq ingroup nil cnt 0)
10182 (insert "}\n"))
10183 ((equal e '(:newline))
10184 (when (not (= cnt 0))
10185 (setq cnt 0)
10186 (insert "\n")
10187 (setq e (car tbl))
10188 (while (equal (car tbl) '(:newline))
10189 (insert "\n")
10190 (setq tbl (cdr tbl)))))
10192 (setq tg (car e) c (cdr e))
10193 (if ingroup (push tg (car groups)))
10194 (setq tg (org-add-props tg nil 'face
10195 (org-get-todo-face tg)))
10196 (if (and (= cnt 0) (not ingroup)) (insert " "))
10197 (insert "[" c "] " tg (make-string
10198 (- fwidth 4 (length tg)) ?\ ))
10199 (when (= (setq cnt (1+ cnt)) ncol)
10200 (insert "\n")
10201 (if ingroup (insert " "))
10202 (setq cnt 0)))))
10203 (insert "\n")
10204 (goto-char (point-min))
10205 (if (not expert) (org-fit-window-to-buffer))
10206 (message "[a-z..]:Set [SPC]:clear")
10207 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10208 (cond
10209 ((or (= c ?\C-g)
10210 (and (= c ?q) (not (rassoc c fulltable))))
10211 (setq quit-flag t))
10212 ((= c ?\ ) nil)
10213 ((setq e (rassoc c fulltable) tg (car e))
10215 (t (setq quit-flag t)))))))
10217 (defun org-entry-is-todo-p ()
10218 (member (org-get-todo-state) org-not-done-keywords))
10220 (defun org-entry-is-done-p ()
10221 (member (org-get-todo-state) org-done-keywords))
10223 (defun org-get-todo-state ()
10224 (save-excursion
10225 (org-back-to-heading t)
10226 (and (looking-at org-todo-line-regexp)
10227 (match-end 2)
10228 (match-string 2))))
10230 (defun org-at-date-range-p (&optional inactive-ok)
10231 "Is the cursor inside a date range?"
10232 (interactive)
10233 (save-excursion
10234 (catch 'exit
10235 (let ((pos (point)))
10236 (skip-chars-backward "^[<\r\n")
10237 (skip-chars-backward "<[")
10238 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10239 (>= (match-end 0) pos)
10240 (throw 'exit t))
10241 (skip-chars-backward "^<[\r\n")
10242 (skip-chars-backward "<[")
10243 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10244 (>= (match-end 0) pos)
10245 (throw 'exit t)))
10246 nil)))
10248 (defun org-get-repeat (&optional tagline)
10249 "Check if there is a deadline/schedule with repeater in this entry."
10250 (save-match-data
10251 (save-excursion
10252 (org-back-to-heading t)
10253 (and (re-search-forward (if tagline
10254 (concat tagline "\\s-*" org-repeat-re)
10255 org-repeat-re)
10256 (org-entry-end-position) t)
10257 (match-string-no-properties 1)))))
10259 (defvar org-last-changed-timestamp)
10260 (defvar org-last-inserted-timestamp)
10261 (defvar org-log-post-message)
10262 (defvar org-log-note-purpose)
10263 (defvar org-log-note-how)
10264 (defvar org-log-note-extra)
10265 (defun org-auto-repeat-maybe (done-word)
10266 "Check if the current headline contains a repeated deadline/schedule.
10267 If yes, set TODO state back to what it was and change the base date
10268 of repeating deadline/scheduled time stamps to new date.
10269 This function is run automatically after each state change to a DONE state."
10270 ;; last-state is dynamically scoped into this function
10271 (let* ((repeat (org-get-repeat))
10272 (aa (assoc last-state org-todo-kwd-alist))
10273 (interpret (nth 1 aa))
10274 (head (nth 2 aa))
10275 (whata '(("d" . day) ("m" . month) ("y" . year)))
10276 (msg "Entry repeats: ")
10277 (org-log-done nil)
10278 (org-todo-log-states nil)
10279 (nshiftmax 10) (nshift 0)
10280 re type n what ts time)
10281 (when repeat
10282 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10283 (org-todo (if (eq interpret 'type) last-state head))
10284 (org-entry-put nil "LAST_REPEAT" (format-time-string
10285 (org-time-stamp-format t t)))
10286 (when org-log-repeat
10287 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10288 (memq 'org-add-log-note post-command-hook))
10289 ;; OK, we are already setup for some record
10290 (if (eq org-log-repeat 'note)
10291 ;; make sure we take a note, not only a time stamp
10292 (setq org-log-note-how 'note))
10293 ;; Set up for taking a record
10294 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10295 last-state
10296 'findpos org-log-repeat)))
10297 (org-back-to-heading t)
10298 (org-add-planning-info nil nil 'closed)
10299 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10300 org-deadline-time-regexp "\\)\\|\\("
10301 org-ts-regexp "\\)"))
10302 (while (re-search-forward
10303 re (save-excursion (outline-next-heading) (point)) t)
10304 (setq type (if (match-end 1) org-scheduled-string
10305 (if (match-end 3) org-deadline-string "Plain:"))
10306 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10307 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10308 (setq n (string-to-number (match-string 2 ts))
10309 what (match-string 3 ts))
10310 (if (equal what "w") (setq n (* n 7) what "d"))
10311 ;; Preparation, see if we need to modify the start date for the change
10312 (when (match-end 1)
10313 (setq time (save-match-data (org-time-string-to-time ts)))
10314 (cond
10315 ((equal (match-string 1 ts) ".")
10316 ;; Shift starting date to today
10317 (org-timestamp-change
10318 (- (time-to-days (current-time)) (time-to-days time))
10319 'day))
10320 ((equal (match-string 1 ts) "+")
10321 (while (or (= nshift 0)
10322 (<= (time-to-days time) (time-to-days (current-time))))
10323 (when (= (incf nshift) nshiftmax)
10324 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10325 (error "Abort")))
10326 (org-timestamp-change n (cdr (assoc what whata)))
10327 (org-at-timestamp-p t)
10328 (setq ts (match-string 1))
10329 (setq time (save-match-data (org-time-string-to-time ts))))
10330 (org-timestamp-change (- n) (cdr (assoc what whata)))
10331 ;; rematch, so that we have everything in place for the real shift
10332 (org-at-timestamp-p t)
10333 (setq ts (match-string 1))
10334 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10335 (org-timestamp-change n (cdr (assoc what whata)))
10336 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10337 (setq org-log-post-message msg)
10338 (message "%s" msg))))
10340 (defun org-show-todo-tree (arg)
10341 "Make a compact tree which shows all headlines marked with TODO.
10342 The tree will show the lines where the regexp matches, and all higher
10343 headlines above the match.
10344 With a \\[universal-argument] prefix, prompt for a regexp to match.
10345 With a numeric prefix N, construct a sparse tree for the Nth element
10346 of `org-todo-keywords-1'."
10347 (interactive "P")
10348 (let ((case-fold-search nil)
10349 (kwd-re
10350 (cond ((null arg) org-not-done-regexp)
10351 ((equal arg '(4))
10352 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10353 (mapcar 'list org-todo-keywords-1))))
10354 (concat "\\("
10355 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10356 "\\)\\>")))
10357 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10358 (regexp-quote (nth (1- (prefix-numeric-value arg))
10359 org-todo-keywords-1)))
10360 (t (error "Invalid prefix argument: %s" arg)))))
10361 (message "%d TODO entries found"
10362 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10364 (defun org-deadline (&optional remove time)
10365 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10366 With argument REMOVE, remove any deadline from the item.
10367 When TIME is set, it should be an internal time specification, and the
10368 scheduling will use the corresponding date."
10369 (interactive "P")
10370 (let ((old-date (org-entry-get nil "DEADLINE")))
10371 (if remove
10372 (progn
10373 (org-remove-timestamp-with-keyword org-deadline-string)
10374 (message "Item no longer has a deadline."))
10375 (if (org-get-repeat)
10376 (error "Cannot change deadline on task with repeater, please do that by hand")
10377 (org-add-planning-info 'deadline time 'closed)
10378 (when (and old-date org-log-redeadline
10379 (not (equal old-date
10380 (substring org-last-inserted-timestamp 1 -1))))
10381 (org-add-log-setup 'redeadline nil old-date 'findpos
10382 org-log-redeadline))
10383 (message "Deadline on %s" org-last-inserted-timestamp)))))
10385 (defun org-schedule (&optional remove time)
10386 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10387 With argument REMOVE, remove any scheduling date from the item.
10388 When TIME is set, it should be an internal time specification, and the
10389 scheduling will use the corresponding date."
10390 (interactive "P")
10391 (let ((old-date (org-entry-get nil "SCHEDULED")))
10392 (if remove
10393 (progn
10394 (org-remove-timestamp-with-keyword org-scheduled-string)
10395 (message "Item is no longer scheduled."))
10396 (if (org-get-repeat)
10397 (error "Cannot reschedule task with repeater, please do that by hand")
10398 (org-add-planning-info 'scheduled time 'closed)
10399 (when (and old-date org-log-reschedule
10400 (not (equal old-date
10401 (substring org-last-inserted-timestamp 1 -1))))
10402 (org-add-log-setup 'reschedule nil old-date 'findpos
10403 org-log-reschedule))
10404 (message "Scheduled to %s" org-last-inserted-timestamp)))))
10406 (defun org-get-scheduled-time (pom &optional inherit)
10407 "Get the scheduled time as a time tuple, of a format suitable
10408 for calling org-schedule with, or if there is no scheduling,
10409 returns nil."
10410 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10411 (when time
10412 (apply 'encode-time (org-parse-time-string time)))))
10414 (defun org-get-deadline-time (pom &optional inherit)
10415 "Get the deadine as a time tuple, of a format suitable for
10416 calling org-deadlin with, or if there is no scheduling, returns
10417 nil."
10418 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10419 (when time
10420 (apply 'encode-time (org-parse-time-string time)))))
10422 (defun org-remove-timestamp-with-keyword (keyword)
10423 "Remove all time stamps with KEYWORD in the current entry."
10424 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10425 beg)
10426 (save-excursion
10427 (org-back-to-heading t)
10428 (setq beg (point))
10429 (outline-next-heading)
10430 (while (re-search-backward re beg t)
10431 (replace-match "")
10432 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10433 (equal (char-before) ?\ ))
10434 (backward-delete-char 1)
10435 (if (string-match "^[ \t]*$" (buffer-substring
10436 (point-at-bol) (point-at-eol)))
10437 (delete-region (point-at-bol)
10438 (min (point-max) (1+ (point-at-eol))))))))))
10440 (defun org-add-planning-info (what &optional time &rest remove)
10441 "Insert new timestamp with keyword in the line directly after the headline.
10442 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10443 If non is given, the user is prompted for a date.
10444 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10445 be removed."
10446 (interactive)
10447 (let (org-time-was-given org-end-time-was-given ts
10448 end default-time default-input)
10450 (catch 'exit
10451 (when (and (not time) (memq what '(scheduled deadline)))
10452 ;; Try to get a default date/time from existing timestamp
10453 (save-excursion
10454 (org-back-to-heading t)
10455 (setq end (save-excursion (outline-next-heading) (point)))
10456 (when (re-search-forward (if (eq what 'scheduled)
10457 org-scheduled-time-regexp
10458 org-deadline-time-regexp)
10459 end t)
10460 (setq ts (match-string 1)
10461 default-time
10462 (apply 'encode-time (org-parse-time-string ts))
10463 default-input (and ts (org-get-compact-tod ts))))))
10464 (when what
10465 ;; If necessary, get the time from the user
10466 (setq time (or time (org-read-date nil 'to-time nil nil
10467 default-time default-input))))
10469 (when (and org-insert-labeled-timestamps-at-point
10470 (member what '(scheduled deadline)))
10471 (insert
10472 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10473 (org-insert-time-stamp time org-time-was-given
10474 nil nil nil (list org-end-time-was-given))
10475 (setq what nil))
10476 (save-excursion
10477 (save-restriction
10478 (let (col list elt ts buffer-invisibility-spec)
10479 (org-back-to-heading t)
10480 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10481 (goto-char (match-end 1))
10482 (setq col (current-column))
10483 (goto-char (match-end 0))
10484 (if (eobp) (insert "\n") (forward-char 1))
10485 (when (and (not what)
10486 (not (looking-at
10487 (concat "[ \t]*"
10488 org-keyword-time-not-clock-regexp))))
10489 ;; Nothing to add, nothing to remove...... :-)
10490 (throw 'exit nil))
10491 (if (and (not (looking-at outline-regexp))
10492 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10493 "[^\r\n]*"))
10494 (not (equal (match-string 1) org-clock-string)))
10495 (narrow-to-region (match-beginning 0) (match-end 0))
10496 (insert-before-markers "\n")
10497 (backward-char 1)
10498 (narrow-to-region (point) (point))
10499 (and org-adapt-indentation (org-indent-to-column col)))
10500 ;; Check if we have to remove something.
10501 (setq list (cons what remove))
10502 (while list
10503 (setq elt (pop list))
10504 (goto-char (point-min))
10505 (when (or (and (eq elt 'scheduled)
10506 (re-search-forward org-scheduled-time-regexp nil t))
10507 (and (eq elt 'deadline)
10508 (re-search-forward org-deadline-time-regexp nil t))
10509 (and (eq elt 'closed)
10510 (re-search-forward org-closed-time-regexp nil t)))
10511 (replace-match "")
10512 (if (looking-at "--+<[^>]+>") (replace-match ""))
10513 (skip-chars-backward " ")
10514 (if (looking-at " +") (replace-match ""))))
10515 (goto-char (point-max))
10516 (and org-adapt-indentation (bolp) (org-indent-to-column col))
10517 (when what
10518 (insert
10519 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10520 (cond ((eq what 'scheduled) org-scheduled-string)
10521 ((eq what 'deadline) org-deadline-string)
10522 ((eq what 'closed) org-closed-string))
10523 " ")
10524 (setq ts (org-insert-time-stamp
10525 time
10526 (or org-time-was-given
10527 (and (eq what 'closed) org-log-done-with-time))
10528 (eq what 'closed)
10529 nil nil (list org-end-time-was-given)))
10530 (end-of-line 1))
10531 (goto-char (point-min))
10532 (widen)
10533 (if (and (looking-at "[ \t]+\n")
10534 (equal (char-before) ?\n))
10535 (delete-region (1- (point)) (point-at-eol)))
10536 ts))))))
10538 (defvar org-log-note-marker (make-marker))
10539 (defvar org-log-note-purpose nil)
10540 (defvar org-log-note-state nil)
10541 (defvar org-log-note-previous-state nil)
10542 (defvar org-log-note-how nil)
10543 (defvar org-log-note-extra nil)
10544 (defvar org-log-note-window-configuration nil)
10545 (defvar org-log-note-return-to (make-marker))
10546 (defvar org-log-post-message nil
10547 "Message to be displayed after a log note has been stored.
10548 The auto-repeater uses this.")
10550 (defun org-add-note ()
10551 "Add a note to the current entry.
10552 This is done in the same way as adding a state change note."
10553 (interactive)
10554 (org-add-log-setup 'note nil nil 'findpos nil))
10556 (defvar org-property-end-re)
10557 (defun org-add-log-setup (&optional purpose state prev-state
10558 findpos how &optional extra)
10559 "Set up the post command hook to take a note.
10560 If this is about to TODO state change, the new state is expected in STATE.
10561 When FINDPOS is non-nil, find the correct position for the note in
10562 the current entry. If not, assume that it can be inserted at point.
10563 HOW is an indicator what kind of note should be created.
10564 EXTRA is additional text that will be inserted into the notes buffer."
10565 (let* ((org-log-into-drawer (org-log-into-drawer))
10566 (drawer (cond ((stringp org-log-into-drawer)
10567 org-log-into-drawer)
10568 (org-log-into-drawer "LOGBOOK")
10569 (t nil))))
10570 (save-restriction
10571 (save-excursion
10572 (when findpos
10573 (org-back-to-heading t)
10574 (narrow-to-region (point) (save-excursion
10575 (outline-next-heading) (point)))
10576 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10577 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10578 "[^\r\n]*\\)?"))
10579 (goto-char (match-end 0))
10580 (cond
10581 (drawer
10582 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10583 nil t)
10584 (progn
10585 (goto-char (match-end 0))
10586 (or org-log-states-order-reversed
10587 (and (re-search-forward org-property-end-re nil t)
10588 (goto-char (1- (match-beginning 0))))))
10589 (insert "\n:" drawer ":\n:END:")
10590 (beginning-of-line 0)
10591 (org-indent-line-function)
10592 (beginning-of-line 2)
10593 (org-indent-line-function)
10594 (end-of-line 0)))
10595 ((and org-log-state-notes-insert-after-drawers
10596 (save-excursion
10597 (forward-line) (looking-at org-drawer-regexp)))
10598 (forward-line)
10599 (while (looking-at org-drawer-regexp)
10600 (goto-char (match-end 0))
10601 (re-search-forward org-property-end-re (point-max) t)
10602 (forward-line))
10603 (forward-line -1)))
10604 (unless org-log-states-order-reversed
10605 (and (= (char-after) ?\n) (forward-char 1))
10606 (org-skip-over-state-notes)
10607 (skip-chars-backward " \t\n\r")))
10608 (move-marker org-log-note-marker (point))
10609 (setq org-log-note-purpose purpose
10610 org-log-note-state state
10611 org-log-note-previous-state prev-state
10612 org-log-note-how how
10613 org-log-note-extra extra)
10614 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10616 (defun org-skip-over-state-notes ()
10617 "Skip past the list of State notes in an entry."
10618 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10619 (while (looking-at "[ \t]*- State")
10620 (condition-case nil
10621 (org-next-item)
10622 (error (org-end-of-item)))))
10624 (defun org-add-log-note (&optional purpose)
10625 "Pop up a window for taking a note, and add this note later at point."
10626 (remove-hook 'post-command-hook 'org-add-log-note)
10627 (setq org-log-note-window-configuration (current-window-configuration))
10628 (delete-other-windows)
10629 (move-marker org-log-note-return-to (point))
10630 (switch-to-buffer (marker-buffer org-log-note-marker))
10631 (goto-char org-log-note-marker)
10632 (org-switch-to-buffer-other-window "*Org Note*")
10633 (erase-buffer)
10634 (if (memq org-log-note-how '(time state))
10635 (let (current-prefix-arg) (org-store-log-note))
10636 (let ((org-inhibit-startup t)) (org-mode))
10637 (insert (format "# Insert note for %s.
10638 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10639 (cond
10640 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10641 ((eq org-log-note-purpose 'done) "closed todo item")
10642 ((eq org-log-note-purpose 'state)
10643 (format "state change from \"%s\" to \"%s\""
10644 (or org-log-note-previous-state "")
10645 (or org-log-note-state "")))
10646 ((eq org-log-note-purpose 'reschedule)
10647 "rescheduling")
10648 ((eq org-log-note-purpose 'redeadline)
10649 "changing deadline")
10650 ((eq org-log-note-purpose 'note)
10651 "this entry")
10652 (t (error "This should not happen")))))
10653 (if org-log-note-extra (insert org-log-note-extra))
10654 (org-set-local 'org-finish-function 'org-store-log-note)))
10656 (defvar org-note-abort nil) ; dynamically scoped
10657 (defun org-store-log-note ()
10658 "Finish taking a log note, and insert it to where it belongs."
10659 (let ((txt (buffer-string))
10660 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10661 lines ind)
10662 (kill-buffer (current-buffer))
10663 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10664 (setq txt (replace-match "" t t txt)))
10665 (if (string-match "\\s-+\\'" txt)
10666 (setq txt (replace-match "" t t txt)))
10667 (setq lines (org-split-string txt "\n"))
10668 (when (and note (string-match "\\S-" note))
10669 (setq note
10670 (org-replace-escapes
10671 note
10672 (list (cons "%u" (user-login-name))
10673 (cons "%U" user-full-name)
10674 (cons "%t" (format-time-string
10675 (org-time-stamp-format 'long 'inactive)
10676 (current-time)))
10677 (cons "%s" (if org-log-note-state
10678 (concat "\"" org-log-note-state "\"")
10679 ""))
10680 (cons "%S" (if org-log-note-previous-state
10681 (concat "\"" org-log-note-previous-state "\"")
10682 "\"\"")))))
10683 (if lines (setq note (concat note " \\\\")))
10684 (push note lines))
10685 (when (or current-prefix-arg org-note-abort)
10686 (when org-log-into-drawer
10687 (org-remove-empty-drawer-at
10688 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10689 org-log-note-marker))
10690 (setq lines nil))
10691 (when lines
10692 (with-current-buffer (marker-buffer org-log-note-marker)
10693 (save-excursion
10694 (goto-char org-log-note-marker)
10695 (move-marker org-log-note-marker nil)
10696 (end-of-line 1)
10697 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10698 (insert "- " (pop lines))
10699 (org-indent-line-function)
10700 (beginning-of-line 1)
10701 (looking-at "[ \t]*")
10702 (setq ind (concat (match-string 0) " "))
10703 (end-of-line 1)
10704 (while lines (insert "\n" ind (pop lines)))
10705 (message "Note stored")
10706 (org-back-to-heading t)
10707 (org-cycle-hide-drawers 'children)))))
10708 (set-window-configuration org-log-note-window-configuration)
10709 (with-current-buffer (marker-buffer org-log-note-return-to)
10710 (goto-char org-log-note-return-to))
10711 (move-marker org-log-note-return-to nil)
10712 (and org-log-post-message (message "%s" org-log-post-message)))
10714 (defun org-remove-empty-drawer-at (drawer pos)
10715 "Remove an emptyr DARWER drawer at position POS.
10716 POS may also be a marker."
10717 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10718 (save-excursion
10719 (save-restriction
10720 (widen)
10721 (goto-char pos)
10722 (if (org-in-regexp
10723 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10724 (replace-match ""))))))
10726 (defun org-sparse-tree (&optional arg)
10727 "Create a sparse tree, prompt for the details.
10728 This command can create sparse trees. You first need to select the type
10729 of match used to create the tree:
10731 t Show entries with a specific TODO keyword.
10732 m Show entries selected by a tags/property match.
10733 p Enter a property name and its value (both with completion on existing
10734 names/values) and show entries with that property.
10735 / Show entries matching a regular expression (`r' can be used as well)
10736 d Show deadlines due within `org-deadline-warning-days'.
10737 b Show deadlines and scheduled items before a date.
10738 a Show deadlines and scheduled items after a date."
10739 (interactive "P")
10740 (let (ans kwd value)
10741 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10742 (setq ans (read-char-exclusive))
10743 (cond
10744 ((equal ans ?d)
10745 (call-interactively 'org-check-deadlines))
10746 ((equal ans ?b)
10747 (call-interactively 'org-check-before-date))
10748 ((equal ans ?a)
10749 (call-interactively 'org-check-after-date))
10750 ((equal ans ?t)
10751 (org-show-todo-tree '(4)))
10752 ((member ans '(?T ?m))
10753 (call-interactively 'org-match-sparse-tree))
10754 ((member ans '(?p ?P))
10755 (setq kwd (org-icompleting-read "Property: "
10756 (mapcar 'list (org-buffer-property-keys))))
10757 (setq value (org-icompleting-read "Value: "
10758 (mapcar 'list (org-property-values kwd))))
10759 (unless (string-match "\\`{.*}\\'" value)
10760 (setq value (concat "\"" value "\"")))
10761 (org-match-sparse-tree arg (concat kwd "=" value)))
10762 ((member ans '(?r ?R ?/))
10763 (call-interactively 'org-occur))
10764 (t (error "No such sparse tree command \"%c\"" ans)))))
10766 (defvar org-occur-highlights nil
10767 "List of overlays used for occur matches.")
10768 (make-variable-buffer-local 'org-occur-highlights)
10769 (defvar org-occur-parameters nil
10770 "Parameters of the active org-occur calls.
10771 This is a list, each call to org-occur pushes as cons cell,
10772 containing the regular expression and the callback, onto the list.
10773 The list can contain several entries if `org-occur' has been called
10774 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10775 will only contain one set of parameters. When the highlights are
10776 removed (for example with `C-c C-c', or with the next edit (depending
10777 on `org-remove-highlights-with-change'), this variable is emptied
10778 as well.")
10779 (make-variable-buffer-local 'org-occur-parameters)
10781 (defun org-occur (regexp &optional keep-previous callback)
10782 "Make a compact tree which shows all matches of REGEXP.
10783 The tree will show the lines where the regexp matches, and all higher
10784 headlines above the match. It will also show the heading after the match,
10785 to make sure editing the matching entry is easy.
10786 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10787 call to `org-occur' will be kept, to allow stacking of calls to this
10788 command.
10789 If CALLBACK is non-nil, it is a function which is called to confirm
10790 that the match should indeed be shown."
10791 (interactive "sRegexp: \nP")
10792 (when (equal regexp "")
10793 (error "Regexp cannot be empty"))
10794 (unless keep-previous
10795 (org-remove-occur-highlights nil nil t))
10796 (push (cons regexp callback) org-occur-parameters)
10797 (let ((cnt 0))
10798 (save-excursion
10799 (goto-char (point-min))
10800 (if (or (not keep-previous) ; do not want to keep
10801 (not org-occur-highlights)) ; no previous matches
10802 ;; hide everything
10803 (org-overview))
10804 (while (re-search-forward regexp nil t)
10805 (when (or (not callback)
10806 (save-match-data (funcall callback)))
10807 (setq cnt (1+ cnt))
10808 (when org-highlight-sparse-tree-matches
10809 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10810 (org-show-context 'occur-tree))))
10811 (when org-remove-highlights-with-change
10812 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10813 nil 'local))
10814 (unless org-sparse-tree-open-archived-trees
10815 (org-hide-archived-subtrees (point-min) (point-max)))
10816 (run-hooks 'org-occur-hook)
10817 (if (interactive-p)
10818 (message "%d match(es) for regexp %s" cnt regexp))
10819 cnt))
10821 (defun org-show-context (&optional key)
10822 "Make sure point and context and visible.
10823 How much context is shown depends upon the variables
10824 `org-show-hierarchy-above', `org-show-following-heading'. and
10825 `org-show-siblings'."
10826 (let ((heading-p (org-on-heading-p t))
10827 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10828 (following-p (org-get-alist-option org-show-following-heading key))
10829 (entry-p (org-get-alist-option org-show-entry-below key))
10830 (siblings-p (org-get-alist-option org-show-siblings key)))
10831 (catch 'exit
10832 ;; Show heading or entry text
10833 (if (and heading-p (not entry-p))
10834 (org-flag-heading nil) ; only show the heading
10835 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10836 (org-show-hidden-entry))) ; show entire entry
10837 (when following-p
10838 ;; Show next sibling, or heading below text
10839 (save-excursion
10840 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10841 (org-flag-heading nil))))
10842 (when siblings-p (org-show-siblings))
10843 (when hierarchy-p
10844 ;; show all higher headings, possibly with siblings
10845 (save-excursion
10846 (while (and (condition-case nil
10847 (progn (org-up-heading-all 1) t)
10848 (error nil))
10849 (not (bobp)))
10850 (org-flag-heading nil)
10851 (when siblings-p (org-show-siblings))))))))
10853 (defun org-reveal (&optional siblings)
10854 "Show current entry, hierarchy above it, and the following headline.
10855 This can be used to show a consistent set of context around locations
10856 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10857 not t for the search context.
10859 With optional argument SIBLINGS, on each level of the hierarchy all
10860 siblings are shown. This repairs the tree structure to what it would
10861 look like when opened with hierarchical calls to `org-cycle'."
10862 (interactive "P")
10863 (let ((org-show-hierarchy-above t)
10864 (org-show-following-heading t)
10865 (org-show-siblings (if siblings t org-show-siblings)))
10866 (org-show-context nil)))
10868 (defun org-highlight-new-match (beg end)
10869 "Highlight from BEG to END and mark the highlight is an occur headline."
10870 (let ((ov (org-make-overlay beg end)))
10871 (org-overlay-put ov 'face 'secondary-selection)
10872 (push ov org-occur-highlights)))
10874 (defun org-remove-occur-highlights (&optional beg end noremove)
10875 "Remove the occur highlights from the buffer.
10876 BEG and END are ignored. If NOREMOVE is nil, remove this function
10877 from the `before-change-functions' in the current buffer."
10878 (interactive)
10879 (unless org-inhibit-highlight-removal
10880 (mapc 'org-delete-overlay org-occur-highlights)
10881 (setq org-occur-highlights nil)
10882 (setq org-occur-parameters nil)
10883 (unless noremove
10884 (remove-hook 'before-change-functions
10885 'org-remove-occur-highlights 'local))))
10887 ;;;; Priorities
10889 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10890 "Regular expression matching the priority indicator.")
10892 (defvar org-remove-priority-next-time nil)
10894 (defun org-priority-up ()
10895 "Increase the priority of the current item."
10896 (interactive)
10897 (org-priority 'up))
10899 (defun org-priority-down ()
10900 "Decrease the priority of the current item."
10901 (interactive)
10902 (org-priority 'down))
10904 (defun org-priority (&optional action)
10905 "Change the priority of an item by ARG.
10906 ACTION can be `set', `up', `down', or a character."
10907 (interactive)
10908 (unless org-enable-priority-commands
10909 (error "Priority commands are disabled"))
10910 (setq action (or action 'set))
10911 (let (current new news have remove)
10912 (save-excursion
10913 (org-back-to-heading t)
10914 (if (looking-at org-priority-regexp)
10915 (setq current (string-to-char (match-string 2))
10916 have t)
10917 (setq current org-default-priority))
10918 (cond
10919 ((eq action 'remove)
10920 (setq remove t new ?\ ))
10921 ((or (eq action 'set)
10922 (if (featurep 'xemacs) (characterp action) (integerp action)))
10923 (if (not (eq action 'set))
10924 (setq new action)
10925 (message "Priority %c-%c, SPC to remove: "
10926 org-highest-priority org-lowest-priority)
10927 (setq new (read-char-exclusive)))
10928 (if (and (= (upcase org-highest-priority) org-highest-priority)
10929 (= (upcase org-lowest-priority) org-lowest-priority))
10930 (setq new (upcase new)))
10931 (cond ((equal new ?\ ) (setq remove t))
10932 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10933 (error "Priority must be between `%c' and `%c'"
10934 org-highest-priority org-lowest-priority))))
10935 ((eq action 'up)
10936 (if (and (not have) (eq last-command this-command))
10937 (setq new org-lowest-priority)
10938 (setq new (if (and org-priority-start-cycle-with-default (not have))
10939 org-default-priority (1- current)))))
10940 ((eq action 'down)
10941 (if (and (not have) (eq last-command this-command))
10942 (setq new org-highest-priority)
10943 (setq new (if (and org-priority-start-cycle-with-default (not have))
10944 org-default-priority (1+ current)))))
10945 (t (error "Invalid action")))
10946 (if (or (< (upcase new) org-highest-priority)
10947 (> (upcase new) org-lowest-priority))
10948 (setq remove t))
10949 (setq news (format "%c" new))
10950 (if have
10951 (if remove
10952 (replace-match "" t t nil 1)
10953 (replace-match news t t nil 2))
10954 (if remove
10955 (error "No priority cookie found in line")
10956 (let ((case-fold-search nil))
10957 (looking-at org-todo-line-regexp))
10958 (if (match-end 2)
10959 (progn
10960 (goto-char (match-end 2))
10961 (insert " [#" news "]"))
10962 (goto-char (match-beginning 3))
10963 (insert "[#" news "] "))))
10964 (org-preserve-lc (org-set-tags nil 'align)))
10965 (if remove
10966 (message "Priority removed")
10967 (message "Priority of current item set to %s" news))))
10969 (defun org-get-priority (s)
10970 "Find priority cookie and return priority."
10971 (save-match-data
10972 (if (not (string-match org-priority-regexp s))
10973 (* 1000 (- org-lowest-priority org-default-priority))
10974 (* 1000 (- org-lowest-priority
10975 (string-to-char (match-string 2 s)))))))
10977 ;;;; Tags
10979 (defvar org-agenda-archives-mode)
10980 (defvar org-map-continue-from nil
10981 "Position from where mapping should continue.
10982 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10984 (defvar org-scanner-tags nil
10985 "The current tag list while the tags scanner is running.")
10986 (defvar org-trust-scanner-tags nil
10987 "Should `org-get-tags-at' use the tags fro the scanner.
10988 This is for internal dynamical scoping only.
10989 When this is non-nil, the function `org-get-tags-at' will return the value
10990 of `org-scanner-tags' instead of building the list by itself. This
10991 can lead to large speed-ups when the tags scanner is used in a file with
10992 many entries, and when the list of tags is retrieved, for example to
10993 obtain a list of properties. Building the tags list for each entry in such
10994 a file becomes an N^2 operation - but with this variable set, it scales
10995 as N.")
10997 (defun org-scan-tags (action matcher &optional todo-only)
10998 "Scan headline tags with inheritance and produce output ACTION.
11000 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11001 or `agenda' to produce an entry list for an agenda view. It can also be
11002 a Lisp form or a function that should be called at each matched headline, in
11003 this case the return value is a list of all return values from these calls.
11005 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11006 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11007 only lines with a TODO keyword are included in the output."
11008 (require 'org-agenda)
11009 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11010 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11011 (org-re
11012 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11013 (props (list 'face 'default
11014 'done-face 'org-agenda-done
11015 'undone-face 'default
11016 'mouse-face 'highlight
11017 'org-not-done-regexp org-not-done-regexp
11018 'org-todo-regexp org-todo-regexp
11019 'help-echo
11020 (format "mouse-2 or RET jump to org file %s"
11021 (abbreviate-file-name
11022 (or (buffer-file-name (buffer-base-buffer))
11023 (buffer-name (buffer-base-buffer)))))))
11024 (case-fold-search nil)
11025 (org-map-continue-from nil)
11026 lspos tags tags-list
11027 (tags-alist (list (cons 0 org-file-tags)))
11028 (llast 0) rtn rtn1 level category i txt
11029 todo marker entry priority)
11030 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11031 (setq action (list 'lambda nil action)))
11032 (save-excursion
11033 (goto-char (point-min))
11034 (when (eq action 'sparse-tree)
11035 (org-overview)
11036 (org-remove-occur-highlights))
11037 (while (re-search-forward re nil t)
11038 (catch :skip
11039 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11040 tags (if (match-end 4) (org-match-string-no-properties 4)))
11041 (goto-char (setq lspos (match-beginning 0)))
11042 (setq level (org-reduced-level (funcall outline-level))
11043 category (org-get-category))
11044 (setq i llast llast level)
11045 ;; remove tag lists from same and sublevels
11046 (while (>= i level)
11047 (when (setq entry (assoc i tags-alist))
11048 (setq tags-alist (delete entry tags-alist)))
11049 (setq i (1- i)))
11050 ;; add the next tags
11051 (when tags
11052 (setq tags (org-split-string tags ":")
11053 tags-alist
11054 (cons (cons level tags) tags-alist)))
11055 ;; compile tags for current headline
11056 (setq tags-list
11057 (if org-use-tag-inheritance
11058 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11059 tags)
11060 org-scanner-tags tags-list)
11061 (when org-use-tag-inheritance
11062 (setcdr (car tags-alist)
11063 (mapcar (lambda (x)
11064 (setq x (copy-sequence x))
11065 (org-add-prop-inherited x))
11066 (cdar tags-alist))))
11067 (when (and tags org-use-tag-inheritance
11068 (or (not (eq t org-use-tag-inheritance))
11069 org-tags-exclude-from-inheritance))
11070 ;; selective inheritance, remove uninherited ones
11071 (setcdr (car tags-alist)
11072 (org-remove-uniherited-tags (cdar tags-alist))))
11073 (when (and (or (not todo-only)
11074 (and (member todo org-not-done-keywords)
11075 (or (not org-agenda-tags-todo-honor-ignore-options)
11076 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11077 (let ((case-fold-search t)) (eval matcher))
11079 (not (member org-archive-tag tags-list))
11080 ;; we have an archive tag, should we use this anyway?
11081 (or (not org-agenda-skip-archived-trees)
11082 (and (eq action 'agenda) org-agenda-archives-mode))))
11083 (unless (eq action 'sparse-tree) (org-agenda-skip))
11085 ;; select this headline
11087 (cond
11088 ((eq action 'sparse-tree)
11089 (and org-highlight-sparse-tree-matches
11090 (org-get-heading) (match-end 0)
11091 (org-highlight-new-match
11092 (match-beginning 0) (match-beginning 1)))
11093 (org-show-context 'tags-tree))
11094 ((eq action 'agenda)
11095 (setq txt (org-format-agenda-item
11097 (concat
11098 (if (eq org-tags-match-list-sublevels 'indented)
11099 (make-string (1- level) ?.) "")
11100 (org-get-heading))
11101 category
11102 tags-list
11104 priority (org-get-priority txt))
11105 (goto-char lspos)
11106 (setq marker (org-agenda-new-marker))
11107 (org-add-props txt props
11108 'org-marker marker 'org-hd-marker marker 'org-category category
11109 'todo-state todo
11110 'priority priority 'type "tagsmatch")
11111 (push txt rtn))
11112 ((functionp action)
11113 (setq org-map-continue-from nil)
11114 (save-excursion
11115 (setq rtn1 (funcall action))
11116 (push rtn1 rtn)))
11117 (t (error "Invalid action")))
11119 ;; if we are to skip sublevels, jump to end of subtree
11120 (unless org-tags-match-list-sublevels
11121 (org-end-of-subtree t)
11122 (backward-char 1))))
11123 ;; Get the correct position from where to continue
11124 (if org-map-continue-from
11125 (goto-char org-map-continue-from)
11126 (and (= (point) lspos) (end-of-line 1)))))
11127 (when (and (eq action 'sparse-tree)
11128 (not org-sparse-tree-open-archived-trees))
11129 (org-hide-archived-subtrees (point-min) (point-max)))
11130 (nreverse rtn)))
11132 (defun org-remove-uniherited-tags (tags)
11133 "Remove all tags that are not inherited from the list TAGS."
11134 (cond
11135 ((eq org-use-tag-inheritance t)
11136 (if org-tags-exclude-from-inheritance
11137 (org-delete-all org-tags-exclude-from-inheritance tags)
11138 tags))
11139 ((not org-use-tag-inheritance) nil)
11140 ((stringp org-use-tag-inheritance)
11141 (delq nil (mapcar
11142 (lambda (x)
11143 (if (and (string-match org-use-tag-inheritance x)
11144 (not (member x org-tags-exclude-from-inheritance)))
11145 x nil))
11146 tags)))
11147 ((listp org-use-tag-inheritance)
11148 (delq nil (mapcar
11149 (lambda (x)
11150 (if (member x org-use-tag-inheritance) x nil))
11151 tags)))))
11153 (defvar todo-only) ;; dynamically scoped
11155 (defun org-match-sparse-tree (&optional todo-only match)
11156 "Create a sparse tree according to tags string MATCH.
11157 MATCH can contain positive and negative selection of tags, like
11158 \"+WORK+URGENT-WITHBOSS\".
11159 If optional argument TODO-ONLY is non-nil, only select lines that are
11160 also TODO lines."
11161 (interactive "P")
11162 (org-prepare-agenda-buffers (list (current-buffer)))
11163 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11165 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11167 (defvar org-cached-props nil)
11168 (defun org-cached-entry-get (pom property)
11169 (if (or (eq t org-use-property-inheritance)
11170 (and (stringp org-use-property-inheritance)
11171 (string-match org-use-property-inheritance property))
11172 (and (listp org-use-property-inheritance)
11173 (member property org-use-property-inheritance)))
11174 ;; Caching is not possible, check it directly
11175 (org-entry-get pom property 'inherit)
11176 ;; Get all properties, so that we can do complicated checks easily
11177 (cdr (assoc property (or org-cached-props
11178 (setq org-cached-props
11179 (org-entry-properties pom)))))))
11181 (defun org-global-tags-completion-table (&optional files)
11182 "Return the list of all tags in all agenda buffer/files."
11183 (save-excursion
11184 (org-uniquify
11185 (delq nil
11186 (apply 'append
11187 (mapcar
11188 (lambda (file)
11189 (set-buffer (find-file-noselect file))
11190 (append (org-get-buffer-tags)
11191 (mapcar (lambda (x) (if (stringp (car-safe x))
11192 (list (car-safe x)) nil))
11193 org-tag-alist)))
11194 (if (and files (car files))
11195 files
11196 (org-agenda-files))))))))
11198 (defun org-make-tags-matcher (match)
11199 "Create the TAGS//TODO matcher form for the selection string MATCH."
11200 ;; todo-only is scoped dynamically into this function, and the function
11201 ;; may change it if the matcher asks for it.
11202 (unless match
11203 ;; Get a new match request, with completion
11204 (let ((org-last-tags-completion-table
11205 (org-global-tags-completion-table)))
11206 (setq match (org-completing-read-no-i
11207 "Match: " 'org-tags-completion-function nil nil nil
11208 'org-tags-history))))
11210 ;; Parse the string and create a lisp form
11211 (let ((match0 match)
11212 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11213 minus tag mm
11214 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11215 orterms term orlist re-p str-p level-p level-op time-p
11216 prop-p pn pv po cat-p gv rest)
11217 (if (string-match "/+" match)
11218 ;; match contains also a todo-matching request
11219 (progn
11220 (setq tagsmatch (substring match 0 (match-beginning 0))
11221 todomatch (substring match (match-end 0)))
11222 (if (string-match "^!" todomatch)
11223 (setq todo-only t todomatch (substring todomatch 1)))
11224 (if (string-match "^\\s-*$" todomatch)
11225 (setq todomatch nil)))
11226 ;; only matching tags
11227 (setq tagsmatch match todomatch nil))
11229 ;; Make the tags matcher
11230 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11231 (setq tagsmatcher t)
11232 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11233 (while (setq term (pop orterms))
11234 (while (and (equal (substring term -1) "\\") orterms)
11235 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11236 (while (string-match re term)
11237 (setq rest (substring term (match-end 0))
11238 minus (and (match-end 1)
11239 (equal (match-string 1 term) "-"))
11240 tag (match-string 2 term)
11241 re-p (equal (string-to-char tag) ?{)
11242 level-p (match-end 4)
11243 prop-p (match-end 5)
11244 mm (cond
11245 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11246 (level-p
11247 (setq level-op (org-op-to-function (match-string 3 term)))
11248 `(,level-op level ,(string-to-number
11249 (match-string 4 term))))
11250 (prop-p
11251 (setq pn (match-string 5 term)
11252 po (match-string 6 term)
11253 pv (match-string 7 term)
11254 cat-p (equal pn "CATEGORY")
11255 re-p (equal (string-to-char pv) ?{)
11256 str-p (equal (string-to-char pv) ?\")
11257 time-p (save-match-data
11258 (string-match "^\"[[<].*[]>]\"$" pv))
11259 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11260 (if time-p (setq pv (org-matcher-time pv)))
11261 (setq po (org-op-to-function po (if time-p 'time str-p)))
11262 (cond
11263 ((equal pn "CATEGORY")
11264 (setq gv '(get-text-property (point) 'org-category)))
11265 ((equal pn "TODO")
11266 (setq gv 'todo))
11268 (setq gv `(org-cached-entry-get nil ,pn))))
11269 (if re-p
11270 (if (eq po 'org<>)
11271 `(not (string-match ,pv (or ,gv "")))
11272 `(string-match ,pv (or ,gv "")))
11273 (if str-p
11274 `(,po (or ,gv "") ,pv)
11275 `(,po (string-to-number (or ,gv ""))
11276 ,(string-to-number pv) ))))
11277 (t `(member ,tag tags-list)))
11278 mm (if minus (list 'not mm) mm)
11279 term rest)
11280 (push mm tagsmatcher))
11281 (push (if (> (length tagsmatcher) 1)
11282 (cons 'and tagsmatcher)
11283 (car tagsmatcher))
11284 orlist)
11285 (setq tagsmatcher nil))
11286 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11287 (setq tagsmatcher
11288 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11289 ;; Make the todo matcher
11290 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11291 (setq todomatcher t)
11292 (setq orterms (org-split-string todomatch "|") orlist nil)
11293 (while (setq term (pop orterms))
11294 (while (string-match re term)
11295 (setq minus (and (match-end 1)
11296 (equal (match-string 1 term) "-"))
11297 kwd (match-string 2 term)
11298 re-p (equal (string-to-char kwd) ?{)
11299 term (substring term (match-end 0))
11300 mm (if re-p
11301 `(string-match ,(substring kwd 1 -1) todo)
11302 (list 'equal 'todo kwd))
11303 mm (if minus (list 'not mm) mm))
11304 (push mm todomatcher))
11305 (push (if (> (length todomatcher) 1)
11306 (cons 'and todomatcher)
11307 (car todomatcher))
11308 orlist)
11309 (setq todomatcher nil))
11310 (setq todomatcher (if (> (length orlist) 1)
11311 (cons 'or orlist) (car orlist))))
11313 ;; Return the string and lisp forms of the matcher
11314 (setq matcher (if todomatcher
11315 (list 'and tagsmatcher todomatcher)
11316 tagsmatcher))
11317 (cons match0 matcher)))
11319 (defun org-op-to-function (op &optional stringp)
11320 "Turn an operator into the appropriate function."
11321 (setq op
11322 (cond
11323 ((equal op "<" ) '(< string< org-time<))
11324 ((equal op ">" ) '(> org-string> org-time>))
11325 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11326 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11327 ((member op '("=" "==")) '(= string= org-time=))
11328 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11329 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11331 (defun org<> (a b) (not (= a b)))
11332 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11333 (defun org-string>= (a b) (not (string< a b)))
11334 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11335 (defun org-string<> (a b) (not (string= a b)))
11336 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11337 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11338 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11339 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11340 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11341 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11342 (defun org-2ft (s)
11343 "Convert S to a floating point time.
11344 If S is already a number, just return it. If it is a string, parse
11345 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11346 (cond
11347 ((numberp s) s)
11348 ((stringp s)
11349 (condition-case nil
11350 (float-time (apply 'encode-time (org-parse-time-string s)))
11351 (error 0.)))
11352 (t 0.)))
11354 (defun org-time-today ()
11355 "Time in seconds today at 0:00.
11356 Returns the float number of seconds since the beginning of the
11357 epoch to the beginning of today (00:00)."
11358 (float-time (apply 'encode-time
11359 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11361 (defun org-matcher-time (s)
11362 "Interpret a time comparison value."
11363 (save-match-data
11364 (cond
11365 ((string= s "<now>") (float-time))
11366 ((string= s "<today>") (org-time-today))
11367 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11368 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11369 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11370 (+ (org-time-today)
11371 (* (string-to-number (match-string 1 s))
11372 (cdr (assoc (match-string 2 s)
11373 '(("d" . 86400.0) ("w" . 604800.0)
11374 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11375 (t (org-2ft s)))))
11377 (defun org-match-any-p (re list)
11378 "Does re match any element of list?"
11379 (setq list (mapcar (lambda (x) (string-match re x)) list))
11380 (delq nil list))
11382 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11383 (defvar org-tags-overlay (org-make-overlay 1 1))
11384 (org-detach-overlay org-tags-overlay)
11386 (defun org-get-local-tags-at (&optional pos)
11387 "Get a list of tags defined in the current headline."
11388 (org-get-tags-at pos 'local))
11390 (defun org-get-local-tags ()
11391 "Get a list of tags defined in the current headline."
11392 (org-get-tags-at nil 'local))
11394 (defun org-get-tags-at (&optional pos local)
11395 "Get a list of all headline tags applicable at POS.
11396 POS defaults to point. If tags are inherited, the list contains
11397 the targets in the same sequence as the headlines appear, i.e.
11398 the tags of the current headline come last.
11399 When LOCAL is non-nil, only return tags from the current headline,
11400 ignore inherited ones."
11401 (interactive)
11402 (if (and org-trust-scanner-tags
11403 (or (not pos) (equal pos (point)))
11404 (not local))
11405 org-scanner-tags
11406 (let (tags ltags lastpos parent)
11407 (save-excursion
11408 (save-restriction
11409 (widen)
11410 (goto-char (or pos (point)))
11411 (save-match-data
11412 (catch 'done
11413 (condition-case nil
11414 (progn
11415 (org-back-to-heading t)
11416 (while (not (equal lastpos (point)))
11417 (setq lastpos (point))
11418 (when (looking-at
11419 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11420 (setq ltags (org-split-string
11421 (org-match-string-no-properties 1) ":"))
11422 (when parent
11423 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11424 (setq tags (append
11425 (if parent
11426 (org-remove-uniherited-tags ltags)
11427 ltags)
11428 tags)))
11429 (or org-use-tag-inheritance (throw 'done t))
11430 (if local (throw 'done t))
11431 (or (org-up-heading-safe) (error nil))
11432 (setq parent t)))
11433 (error nil)))))
11434 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11436 (defun org-add-prop-inherited (s)
11437 (add-text-properties 0 (length s) '(inherited t) s)
11440 (defun org-toggle-tag (tag &optional onoff)
11441 "Toggle the tag TAG for the current line.
11442 If ONOFF is `on' or `off', don't toggle but set to this state."
11443 (let (res current)
11444 (save-excursion
11445 (org-back-to-heading t)
11446 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11447 (point-at-eol) t)
11448 (progn
11449 (setq current (match-string 1))
11450 (replace-match ""))
11451 (setq current ""))
11452 (setq current (nreverse (org-split-string current ":")))
11453 (cond
11454 ((eq onoff 'on)
11455 (setq res t)
11456 (or (member tag current) (push tag current)))
11457 ((eq onoff 'off)
11458 (or (not (member tag current)) (setq current (delete tag current))))
11459 (t (if (member tag current)
11460 (setq current (delete tag current))
11461 (setq res t)
11462 (push tag current))))
11463 (end-of-line 1)
11464 (if current
11465 (progn
11466 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11467 (org-set-tags nil t))
11468 (delete-horizontal-space))
11469 (run-hooks 'org-after-tags-change-hook))
11470 res))
11472 (defun org-align-tags-here (to-col)
11473 ;; Assumes that this is a headline
11474 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11475 (beginning-of-line 1)
11476 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11477 (< pos (match-beginning 2)))
11478 (progn
11479 (setq tags-l (- (match-end 2) (match-beginning 2)))
11480 (goto-char (match-beginning 1))
11481 (insert " ")
11482 (delete-region (point) (1+ (match-beginning 2)))
11483 (setq ncol (max (1+ (current-column))
11484 (1+ col)
11485 (if (> to-col 0)
11486 to-col
11487 (- (abs to-col) tags-l))))
11488 (setq p (point))
11489 (insert (make-string (- ncol (current-column)) ?\ ))
11490 (setq ncol (current-column))
11491 (when indent-tabs-mode (tabify p (point-at-eol)))
11492 (org-move-to-column (min ncol col) t))
11493 (goto-char pos))))
11495 (defun org-set-tags-command (&optional arg just-align)
11496 "Call the set-tags command for the current entry."
11497 (interactive "P")
11498 (if (org-on-heading-p)
11499 (org-set-tags arg just-align)
11500 (save-excursion
11501 (org-back-to-heading t)
11502 (org-set-tags arg just-align))))
11504 (defun org-set-tags-to (data)
11505 "Set the tags of the current entry to DATA, replacing the current tags.
11506 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11507 If DATA is nil or the empty string, any tags will be removed."
11508 (interactive "sTags: ")
11509 (setq data
11510 (cond
11511 ((eq data nil) "")
11512 ((equal data "") "")
11513 ((stringp data)
11514 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11515 ":"))
11516 ((listp data)
11517 (concat ":" (mapconcat 'identity data ":") ":"))
11518 (t nil)))
11519 (when data
11520 (save-excursion
11521 (org-back-to-heading t)
11522 (when (looking-at org-complex-heading-regexp)
11523 (if (match-end 5)
11524 (progn
11525 (goto-char (match-beginning 5))
11526 (insert data)
11527 (delete-region (point) (point-at-eol))
11528 (org-set-tags nil 'align))
11529 (goto-char (point-at-eol))
11530 (insert " " data)
11531 (org-set-tags nil 'align)))
11532 (beginning-of-line 1)
11533 (if (looking-at ".*?\\([ \t]+\\)$")
11534 (delete-region (match-beginning 1) (match-end 1))))))
11536 (defun org-set-tags (&optional arg just-align)
11537 "Set the tags for the current headline.
11538 With prefix ARG, realign all tags in headings in the current buffer."
11539 (interactive "P")
11540 (let* ((re (concat "^" outline-regexp))
11541 (current (org-get-tags-string))
11542 (col (current-column))
11543 (org-setting-tags t)
11544 table current-tags inherited-tags ; computed below when needed
11545 tags p0 c0 c1 rpl)
11546 (if arg
11547 (save-excursion
11548 (goto-char (point-min))
11549 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11550 (while (re-search-forward re nil t)
11551 (org-set-tags nil t)
11552 (end-of-line 1)))
11553 (message "All tags realigned to column %d" org-tags-column))
11554 (if just-align
11555 (setq tags current)
11556 ;; Get a new set of tags from the user
11557 (save-excursion
11558 (setq table (append org-tag-persistent-alist
11559 (or org-tag-alist (org-get-buffer-tags)))
11560 org-last-tags-completion-table table
11561 current-tags (org-split-string current ":")
11562 inherited-tags (nreverse
11563 (nthcdr (length current-tags)
11564 (nreverse (org-get-tags-at))))
11565 tags
11566 (if (or (eq t org-use-fast-tag-selection)
11567 (and org-use-fast-tag-selection
11568 (delq nil (mapcar 'cdr table))))
11569 (org-fast-tag-selection
11570 current-tags inherited-tags table
11571 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11572 (let ((org-add-colon-after-tag-completion t))
11573 (org-trim
11574 (org-without-partial-completion
11575 (org-icompleting-read "Tags: " 'org-tags-completion-function
11576 nil nil current 'org-tags-history)))))))
11577 (while (string-match "[-+&]+" tags)
11578 ;; No boolean logic, just a list
11579 (setq tags (replace-match ":" t t tags))))
11581 (if org-tags-sort-function
11582 (setq tags (mapconcat 'identity
11583 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11584 org-tags-sort-function) ":")))
11586 (if (string-match "\\`[\t ]*\\'" tags)
11587 (setq tags "")
11588 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11589 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11591 ;; Insert new tags at the correct column
11592 (beginning-of-line 1)
11593 (cond
11594 ((and (equal current "") (equal tags "")))
11595 ((re-search-forward
11596 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11597 (point-at-eol) t)
11598 (if (equal tags "")
11599 (setq rpl "")
11600 (goto-char (match-beginning 0))
11601 (setq c0 (current-column) p0 (point)
11602 c1 (max (1+ c0) (if (> org-tags-column 0)
11603 org-tags-column
11604 (- (- org-tags-column) (length tags))))
11605 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11606 (replace-match rpl t t)
11607 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11608 tags)
11609 (t (error "Tags alignment failed")))
11610 (org-move-to-column col)
11611 (unless just-align
11612 (run-hooks 'org-after-tags-change-hook)))))
11614 (defun org-change-tag-in-region (beg end tag off)
11615 "Add or remove TAG for each entry in the region.
11616 This works in the agenda, and also in an org-mode buffer."
11617 (interactive
11618 (list (region-beginning) (region-end)
11619 (let ((org-last-tags-completion-table
11620 (if (org-mode-p)
11621 (org-get-buffer-tags)
11622 (org-global-tags-completion-table))))
11623 (org-icompleting-read
11624 "Tag: " 'org-tags-completion-function nil nil nil
11625 'org-tags-history))
11626 (progn
11627 (message "[s]et or [r]emove? ")
11628 (equal (read-char-exclusive) ?r))))
11629 (if (fboundp 'deactivate-mark) (deactivate-mark))
11630 (let ((agendap (equal major-mode 'org-agenda-mode))
11631 l1 l2 m buf pos newhead (cnt 0))
11632 (goto-char end)
11633 (setq l2 (1- (org-current-line)))
11634 (goto-char beg)
11635 (setq l1 (org-current-line))
11636 (loop for l from l1 to l2 do
11637 (org-goto-line l)
11638 (setq m (get-text-property (point) 'org-hd-marker))
11639 (when (or (and (org-mode-p) (org-on-heading-p))
11640 (and agendap m))
11641 (setq buf (if agendap (marker-buffer m) (current-buffer))
11642 pos (if agendap m (point)))
11643 (with-current-buffer buf
11644 (save-excursion
11645 (save-restriction
11646 (goto-char pos)
11647 (setq cnt (1+ cnt))
11648 (org-toggle-tag tag (if off 'off 'on))
11649 (setq newhead (org-get-heading)))))
11650 (and agendap (org-agenda-change-all-lines newhead m))))
11651 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11653 (defun org-tags-completion-function (string predicate &optional flag)
11654 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11655 (confirm (lambda (x) (stringp (car x)))))
11656 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11657 (setq s1 (match-string 1 string)
11658 s2 (match-string 2 string))
11659 (setq s1 "" s2 string))
11660 (cond
11661 ((eq flag nil)
11662 ;; try completion
11663 (setq rtn (try-completion s2 ctable confirm))
11664 (if (stringp rtn)
11665 (setq rtn
11666 (concat s1 s2 (substring rtn (length s2))
11667 (if (and org-add-colon-after-tag-completion
11668 (assoc rtn ctable))
11669 ":" ""))))
11670 rtn)
11671 ((eq flag t)
11672 ;; all-completions
11673 (all-completions s2 ctable confirm)
11675 ((eq flag 'lambda)
11676 ;; exact match?
11677 (assoc s2 ctable)))
11680 (defun org-fast-tag-insert (kwd tags face &optional end)
11681 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11682 (insert (format "%-12s" (concat kwd ":"))
11683 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11684 (or end "")))
11686 (defun org-fast-tag-show-exit (flag)
11687 (save-excursion
11688 (org-goto-line 3)
11689 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11690 (replace-match ""))
11691 (when flag
11692 (end-of-line 1)
11693 (org-move-to-column (- (window-width) 19) t)
11694 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11696 (defun org-set-current-tags-overlay (current prefix)
11697 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11698 (if (featurep 'xemacs)
11699 (org-overlay-display org-tags-overlay (concat prefix s)
11700 'secondary-selection)
11701 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11702 (org-overlay-display org-tags-overlay (concat prefix s)))))
11704 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11705 "Fast tag selection with single keys.
11706 CURRENT is the current list of tags in the headline, INHERITED is the
11707 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11708 possibly with grouping information. TODO-TABLE is a similar table with
11709 TODO keywords, should these have keys assigned to them.
11710 If the keys are nil, a-z are automatically assigned.
11711 Returns the new tags string, or nil to not change the current settings."
11712 (let* ((fulltable (append table todo-table))
11713 (maxlen (apply 'max (mapcar
11714 (lambda (x)
11715 (if (stringp (car x)) (string-width (car x)) 0))
11716 fulltable)))
11717 (buf (current-buffer))
11718 (expert (eq org-fast-tag-selection-single-key 'expert))
11719 (buffer-tags nil)
11720 (fwidth (+ maxlen 3 1 3))
11721 (ncol (/ (- (window-width) 4) fwidth))
11722 (i-face 'org-done)
11723 (c-face 'org-todo)
11724 tg cnt e c char c1 c2 ntable tbl rtn
11725 ov-start ov-end ov-prefix
11726 (exit-after-next org-fast-tag-selection-single-key)
11727 (done-keywords org-done-keywords)
11728 groups ingroup)
11729 (save-excursion
11730 (beginning-of-line 1)
11731 (if (looking-at
11732 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11733 (setq ov-start (match-beginning 1)
11734 ov-end (match-end 1)
11735 ov-prefix "")
11736 (setq ov-start (1- (point-at-eol))
11737 ov-end (1+ ov-start))
11738 (skip-chars-forward "^\n\r")
11739 (setq ov-prefix
11740 (concat
11741 (buffer-substring (1- (point)) (point))
11742 (if (> (current-column) org-tags-column)
11744 (make-string (- org-tags-column (current-column)) ?\ ))))))
11745 (org-move-overlay org-tags-overlay ov-start ov-end)
11746 (save-window-excursion
11747 (if expert
11748 (set-buffer (get-buffer-create " *Org tags*"))
11749 (delete-other-windows)
11750 (split-window-vertically)
11751 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11752 (erase-buffer)
11753 (org-set-local 'org-done-keywords done-keywords)
11754 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11755 (org-fast-tag-insert "Current" current c-face "\n\n")
11756 (org-fast-tag-show-exit exit-after-next)
11757 (org-set-current-tags-overlay current ov-prefix)
11758 (setq tbl fulltable char ?a cnt 0)
11759 (while (setq e (pop tbl))
11760 (cond
11761 ((equal (car e) :startgroup)
11762 (push '() groups) (setq ingroup t)
11763 (when (not (= cnt 0))
11764 (setq cnt 0)
11765 (insert "\n"))
11766 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
11767 ((equal (car e) :endgroup)
11768 (setq ingroup nil cnt 0)
11769 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
11770 ((equal e '(:newline))
11771 (when (not (= cnt 0))
11772 (setq cnt 0)
11773 (insert "\n")
11774 (setq e (car tbl))
11775 (while (equal (car tbl) '(:newline))
11776 (insert "\n")
11777 (setq tbl (cdr tbl)))))
11779 (setq tg (copy-sequence (car e)) c2 nil)
11780 (if (cdr e)
11781 (setq c (cdr e))
11782 ;; automatically assign a character.
11783 (setq c1 (string-to-char
11784 (downcase (substring
11785 tg (if (= (string-to-char tg) ?@) 1 0)))))
11786 (if (or (rassoc c1 ntable) (rassoc c1 table))
11787 (while (or (rassoc char ntable) (rassoc char table))
11788 (setq char (1+ char)))
11789 (setq c2 c1))
11790 (setq c (or c2 char)))
11791 (if ingroup (push tg (car groups)))
11792 (setq tg (org-add-props tg nil 'face
11793 (cond
11794 ((not (assoc tg table))
11795 (org-get-todo-face tg))
11796 ((member tg current) c-face)
11797 ((member tg inherited) i-face)
11798 (t nil))))
11799 (if (and (= cnt 0) (not ingroup)) (insert " "))
11800 (insert "[" c "] " tg (make-string
11801 (- fwidth 4 (length tg)) ?\ ))
11802 (push (cons tg c) ntable)
11803 (when (= (setq cnt (1+ cnt)) ncol)
11804 (insert "\n")
11805 (if ingroup (insert " "))
11806 (setq cnt 0)))))
11807 (setq ntable (nreverse ntable))
11808 (insert "\n")
11809 (goto-char (point-min))
11810 (if (not expert) (org-fit-window-to-buffer))
11811 (setq rtn
11812 (catch 'exit
11813 (while t
11814 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
11815 (if (not groups) "no " "")
11816 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11817 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11818 (cond
11819 ((= c ?\r) (throw 'exit t))
11820 ((= c ?!)
11821 (setq groups (not groups))
11822 (goto-char (point-min))
11823 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11824 ((= c ?\C-c)
11825 (if (not expert)
11826 (org-fast-tag-show-exit
11827 (setq exit-after-next (not exit-after-next)))
11828 (setq expert nil)
11829 (delete-other-windows)
11830 (split-window-vertically)
11831 (org-switch-to-buffer-other-window " *Org tags*")
11832 (org-fit-window-to-buffer)))
11833 ((or (= c ?\C-g)
11834 (and (= c ?q) (not (rassoc c ntable))))
11835 (org-detach-overlay org-tags-overlay)
11836 (setq quit-flag t))
11837 ((= c ?\ )
11838 (setq current nil)
11839 (if exit-after-next (setq exit-after-next 'now)))
11840 ((= c ?\t)
11841 (condition-case nil
11842 (setq tg (org-icompleting-read
11843 "Tag: "
11844 (or buffer-tags
11845 (with-current-buffer buf
11846 (org-get-buffer-tags)))))
11847 (quit (setq tg "")))
11848 (when (string-match "\\S-" tg)
11849 (add-to-list 'buffer-tags (list tg))
11850 (if (member tg current)
11851 (setq current (delete tg current))
11852 (push tg current)))
11853 (if exit-after-next (setq exit-after-next 'now)))
11854 ((setq e (rassoc c todo-table) tg (car e))
11855 (with-current-buffer buf
11856 (save-excursion (org-todo tg)))
11857 (if exit-after-next (setq exit-after-next 'now)))
11858 ((setq e (rassoc c ntable) tg (car e))
11859 (if (member tg current)
11860 (setq current (delete tg current))
11861 (loop for g in groups do
11862 (if (member tg g)
11863 (mapc (lambda (x)
11864 (setq current (delete x current)))
11865 g)))
11866 (push tg current))
11867 (if exit-after-next (setq exit-after-next 'now))))
11869 ;; Create a sorted list
11870 (setq current
11871 (sort current
11872 (lambda (a b)
11873 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11874 (if (eq exit-after-next 'now) (throw 'exit t))
11875 (goto-char (point-min))
11876 (beginning-of-line 2)
11877 (delete-region (point) (point-at-eol))
11878 (org-fast-tag-insert "Current" current c-face)
11879 (org-set-current-tags-overlay current ov-prefix)
11880 (while (re-search-forward
11881 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11882 (setq tg (match-string 1))
11883 (add-text-properties
11884 (match-beginning 1) (match-end 1)
11885 (list 'face
11886 (cond
11887 ((member tg current) c-face)
11888 ((member tg inherited) i-face)
11889 (t (get-text-property (match-beginning 1) 'face))))))
11890 (goto-char (point-min)))))
11891 (org-detach-overlay org-tags-overlay)
11892 (if rtn
11893 (mapconcat 'identity current ":")
11894 nil))))
11896 (defun org-get-tags-string ()
11897 "Get the TAGS string in the current headline."
11898 (unless (org-on-heading-p t)
11899 (error "Not on a heading"))
11900 (save-excursion
11901 (beginning-of-line 1)
11902 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11903 (org-match-string-no-properties 1)
11904 "")))
11906 (defun org-get-tags ()
11907 "Get the list of tags specified in the current headline."
11908 (org-split-string (org-get-tags-string) ":"))
11910 (defun org-get-buffer-tags ()
11911 "Get a table of all tags used in the buffer, for completion."
11912 (let (tags)
11913 (save-excursion
11914 (goto-char (point-min))
11915 (while (re-search-forward
11916 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11917 (when (equal (char-after (point-at-bol 0)) ?*)
11918 (mapc (lambda (x) (add-to-list 'tags x))
11919 (org-split-string (org-match-string-no-properties 1) ":")))))
11920 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
11921 (mapcar 'list tags)))
11923 ;;;; The mapping API
11925 ;;;###autoload
11926 (defun org-map-entries (func &optional match scope &rest skip)
11927 "Call FUNC at each headline selected by MATCH in SCOPE.
11929 FUNC is a function or a lisp form. The function will be called without
11930 arguments, with the cursor positioned at the beginning of the headline.
11931 The return values of all calls to the function will be collected and
11932 returned as a list.
11934 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11935 does not need to preserve point. After evaluation, the cursor will be
11936 moved to the end of the line (presumably of the headline of the
11937 processed entry) and search continues from there. Under some
11938 circumstances, this may not produce the wanted results. For example,
11939 if you have removed (e.g. archived) the current (sub)tree it could
11940 mean that the next entry will be skipped entirely. In such cases, you
11941 can specify the position from where search should continue by making
11942 FUNC set the variable `org-map-continue-from' to the desired buffer
11943 position.
11945 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11946 Only headlines that are matched by this query will be considered during
11947 the iteration. When MATCH is nil or t, all headlines will be
11948 visited by the iteration.
11950 SCOPE determines the scope of this command. It can be any of:
11952 nil The current buffer, respecting the restriction if any
11953 tree The subtree started with the entry at point
11954 file The current buffer, without restriction
11955 file-with-archives
11956 The current buffer, and any archives associated with it
11957 agenda All agenda files
11958 agenda-with-archives
11959 All agenda files with any archive files associated with them
11960 \(file1 file2 ...)
11961 If this is a list, all files in the list will be scanned
11963 The remaining args are treated as settings for the skipping facilities of
11964 the scanner. The following items can be given here:
11966 archive skip trees with the archive tag.
11967 comment skip trees with the COMMENT keyword
11968 function or Emacs Lisp form:
11969 will be used as value for `org-agenda-skip-function', so whenever
11970 the function returns t, FUNC will not be called for that
11971 entry and search will continue from the point where the
11972 function leaves it.
11974 If your function needs to retrieve the tags including inherited tags
11975 at the *current* entry, you can use the value of the variable
11976 `org-scanner-tags' which will be much faster than getting the value
11977 with `org-get-tags-at'. If your function gets properties with
11978 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11979 to t around the call to `org-entry-properties' to get the same speedup.
11980 Note that if your function moves around to retrieve tags and properties at
11981 a *different* entry, you cannot use these techniques."
11982 (let* ((org-agenda-archives-mode nil) ; just to make sure
11983 (org-agenda-skip-archived-trees (memq 'archive skip))
11984 (org-agenda-skip-comment-trees (memq 'comment skip))
11985 (org-agenda-skip-function
11986 (car (org-delete-all '(comment archive) skip)))
11987 (org-tags-match-list-sublevels t)
11988 matcher file res
11989 org-todo-keywords-for-agenda
11990 org-done-keywords-for-agenda
11991 org-todo-keyword-alist-for-agenda
11992 org-drawers-for-agenda
11993 org-tag-alist-for-agenda)
11995 (cond
11996 ((eq match t) (setq matcher t))
11997 ((eq match nil) (setq matcher t))
11998 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12000 (save-excursion
12001 (save-restriction
12002 (when (eq scope 'tree)
12003 (org-back-to-heading t)
12004 (org-narrow-to-subtree)
12005 (setq scope nil))
12007 (if (not scope)
12008 (progn
12009 (org-prepare-agenda-buffers
12010 (list (buffer-file-name (current-buffer))))
12011 (setq res (org-scan-tags func matcher)))
12012 ;; Get the right scope
12013 (cond
12014 ((and scope (listp scope) (symbolp (car scope)))
12015 (setq scope (eval scope)))
12016 ((eq scope 'agenda)
12017 (setq scope (org-agenda-files t)))
12018 ((eq scope 'agenda-with-archives)
12019 (setq scope (org-agenda-files t))
12020 (setq scope (org-add-archive-files scope)))
12021 ((eq scope 'file)
12022 (setq scope (list (buffer-file-name))))
12023 ((eq scope 'file-with-archives)
12024 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12025 (org-prepare-agenda-buffers scope)
12026 (while (setq file (pop scope))
12027 (with-current-buffer (org-find-base-buffer-visiting file)
12028 (save-excursion
12029 (save-restriction
12030 (widen)
12031 (goto-char (point-min))
12032 (setq res (append res (org-scan-tags func matcher))))))))))
12033 res))
12035 ;;;; Properties
12037 ;;; Setting and retrieving properties
12039 (defconst org-special-properties
12040 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12041 "TIMESTAMP" "TIMESTAMP_IA")
12042 "The special properties valid in Org-mode.
12044 These are properties that are not defined in the property drawer,
12045 but in some other way.")
12047 (defconst org-default-properties
12048 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12049 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12050 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12051 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12052 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12053 "CLOCK_MODELINE_TOTAL" "STYLE")
12054 "Some properties that are used by Org-mode for various purposes.
12055 Being in this list makes sure that they are offered for completion.")
12057 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12058 "Regular expression matching the first line of a property drawer.")
12060 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12061 "Regular expression matching the first line of a property drawer.")
12063 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12064 "Regular expression matching the first line of a property drawer.")
12066 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12067 "Regular expression matching the first line of a property drawer.")
12069 (defconst org-property-drawer-re
12070 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12071 org-property-end-re "\\)\n?")
12072 "Matches an entire property drawer.")
12074 (defconst org-clock-drawer-re
12075 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12076 org-property-end-re "\\)\n?")
12077 "Matches an entire clock drawer.")
12079 (defun org-property-action ()
12080 "Do an action on properties."
12081 (interactive)
12082 (let (c)
12083 (org-at-property-p)
12084 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12085 (setq c (read-char-exclusive))
12086 (cond
12087 ((equal c ?s)
12088 (call-interactively 'org-set-property))
12089 ((equal c ?d)
12090 (call-interactively 'org-delete-property))
12091 ((equal c ?D)
12092 (call-interactively 'org-delete-property-globally))
12093 ((equal c ?c)
12094 (call-interactively 'org-compute-property-at-point))
12095 (t (error "No such property action %c" c)))))
12097 (defun org-set-effort (&optional value)
12098 "Set the effort property of the current entry.
12099 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12100 allowed value."
12101 (interactive "P")
12102 (if (equal value 0) (setq value 10))
12103 (let* ((completion-ignore-case t)
12104 (prop org-effort-property)
12105 (cur (org-entry-get nil prop))
12106 (allowed (org-property-get-allowed-values nil prop 'table))
12107 (existing (mapcar 'list (org-property-values prop)))
12109 (val (cond
12110 ((stringp value) value)
12111 ((and allowed (integerp value))
12112 (or (car (nth (1- value) allowed))
12113 (car (org-last allowed))))
12114 (allowed
12115 (message "Select 1-9,0, [RET%s]: %s"
12116 (if cur (concat "=" cur) "")
12117 (mapconcat 'car allowed " "))
12118 (setq rpl (read-char-exclusive))
12119 (if (equal rpl ?\r)
12121 (setq rpl (- rpl ?0))
12122 (if (equal rpl 0) (setq rpl 10))
12123 (if (and (> rpl 0) (<= rpl (length allowed)))
12124 (car (nth (1- rpl) allowed))
12125 (org-completing-read "Value: " allowed nil))))
12127 (let (org-completion-use-ido org-completion-use-iswitchb)
12128 (org-completing-read
12129 (concat "Value " (if (and cur (string-match "\\S-" cur))
12130 (concat "[" cur "]") "")
12131 ": ")
12132 existing nil nil "" nil cur))))))
12133 (unless (equal (org-entry-get nil prop) val)
12134 (org-entry-put nil prop val))
12135 (message "%s is now %s" prop val)))
12137 (defun org-at-property-p ()
12138 "Is the cursor in a property line?"
12139 ;; FIXME: Does not check if we are actually in the drawer.
12140 ;; FIXME: also returns true on any drawers.....
12141 ;; This is used by C-c C-c for property action.
12142 (save-excursion
12143 (beginning-of-line 1)
12144 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
12146 (defun org-get-property-block (&optional beg end force)
12147 "Return the (beg . end) range of the body of the property drawer.
12148 BEG and END can be beginning and end of subtree, if not given
12149 they will be found.
12150 If the drawer does not exist and FORCE is non-nil, create the drawer."
12151 (catch 'exit
12152 (save-excursion
12153 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12154 (end (or end (progn (outline-next-heading) (point)))))
12155 (goto-char beg)
12156 (if (re-search-forward org-property-start-re end t)
12157 (setq beg (1+ (match-end 0)))
12158 (if force
12159 (save-excursion
12160 (org-insert-property-drawer)
12161 (setq end (progn (outline-next-heading) (point))))
12162 (throw 'exit nil))
12163 (goto-char beg)
12164 (if (re-search-forward org-property-start-re end t)
12165 (setq beg (1+ (match-end 0)))))
12166 (if (re-search-forward org-property-end-re end t)
12167 (setq end (match-beginning 0))
12168 (or force (throw 'exit nil))
12169 (goto-char beg)
12170 (setq end beg)
12171 (org-indent-line-function)
12172 (insert ":END:\n"))
12173 (cons beg end)))))
12175 (defun org-entry-properties (&optional pom which)
12176 "Get all properties of the entry at point-or-marker POM.
12177 This includes the TODO keyword, the tags, time strings for deadline,
12178 scheduled, and clocking, and any additional properties defined in the
12179 entry. The return value is an alist, keys may occur multiple times
12180 if the property key was used several times.
12181 POM may also be nil, in which case the current entry is used.
12182 If WHICH is nil or `all', get all properties. If WHICH is
12183 `special' or `standard', only get that subclass."
12184 (setq which (or which 'all))
12185 (org-with-point-at pom
12186 (let ((clockstr (substring org-clock-string 0 -1))
12187 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
12188 beg end range props sum-props key value string clocksum)
12189 (save-excursion
12190 (when (condition-case nil
12191 (and (org-mode-p) (org-back-to-heading t))
12192 (error nil))
12193 (setq beg (point))
12194 (setq sum-props (get-text-property (point) 'org-summaries))
12195 (setq clocksum (get-text-property (point) :org-clock-minutes))
12196 (outline-next-heading)
12197 (setq end (point))
12198 (when (memq which '(all special))
12199 ;; Get the special properties, like TODO and tags
12200 (goto-char beg)
12201 (when (and (looking-at org-todo-line-regexp) (match-end 2))
12202 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12203 (when (looking-at org-priority-regexp)
12204 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12205 (when (and (setq value (org-get-tags-string))
12206 (string-match "\\S-" value))
12207 (push (cons "TAGS" value) props))
12208 (when (setq value (org-get-tags-at))
12209 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
12210 props))
12211 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12212 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12213 string (if (equal key clockstr)
12214 (org-no-properties
12215 (org-trim
12216 (buffer-substring
12217 (match-beginning 3) (goto-char (point-at-eol)))))
12218 (substring (org-match-string-no-properties 3) 1 -1)))
12219 (unless key
12220 (if (= (char-after (match-beginning 3)) ?\[)
12221 (setq key "TIMESTAMP_IA")
12222 (setq key "TIMESTAMP")))
12223 (when (or (equal key clockstr) (not (assoc key props)))
12224 (push (cons key string) props)))
12228 (when (memq which '(all standard))
12229 ;; Get the standard properties, like :PROP: ...
12230 (setq range (org-get-property-block beg end))
12231 (when range
12232 (goto-char (car range))
12233 (while (re-search-forward
12234 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12235 (cdr range) t)
12236 (setq key (org-match-string-no-properties 1)
12237 value (org-trim (or (org-match-string-no-properties 2) "")))
12238 (unless (member key excluded)
12239 (push (cons key (or value "")) props)))))
12240 (if clocksum
12241 (push (cons "CLOCKSUM"
12242 (org-columns-number-to-string (/ (float clocksum) 60.)
12243 'add_times))
12244 props))
12245 (unless (assoc "CATEGORY" props)
12246 (setq value (or (org-get-category)
12247 (progn (org-refresh-category-properties)
12248 (org-get-category))))
12249 (push (cons "CATEGORY" value) props))
12250 (append sum-props (nreverse props)))))))
12252 (defun org-entry-get (pom property &optional inherit)
12253 "Get value of PROPERTY for entry at point-or-marker POM.
12254 If INHERIT is non-nil and the entry does not have the property,
12255 then also check higher levels of the hierarchy.
12256 If INHERIT is the symbol `selective', use inheritance only if the setting
12257 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12258 If the property is present but empty, the return value is the empty string.
12259 If the property is not present at all, nil is returned."
12260 (org-with-point-at pom
12261 (if (and inherit (if (eq inherit 'selective)
12262 (org-property-inherit-p property)
12264 (org-entry-get-with-inheritance property)
12265 (if (member property org-special-properties)
12266 ;; We need a special property. Use brute force, get all properties.
12267 (cdr (assoc property (org-entry-properties nil 'special)))
12268 (let ((range (org-get-property-block)))
12269 (if (and range
12270 (goto-char (car range))
12271 (re-search-forward
12272 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12273 (cdr range) t))
12274 ;; Found the property, return it.
12275 (if (match-end 1)
12276 (org-match-string-no-properties 1)
12277 "")))))))
12279 (defun org-property-or-variable-value (var &optional inherit)
12280 "Check if there is a property fixing the value of VAR.
12281 If yes, return this value. If not, return the current value of the variable."
12282 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12283 (if (and prop (stringp prop) (string-match "\\S-" prop))
12284 (read prop)
12285 (symbol-value var))))
12287 (defun org-entry-delete (pom property)
12288 "Delete the property PROPERTY from entry at point-or-marker POM."
12289 (org-with-point-at pom
12290 (if (member property org-special-properties)
12291 nil ; cannot delete these properties.
12292 (let ((range (org-get-property-block)))
12293 (if (and range
12294 (goto-char (car range))
12295 (re-search-forward
12296 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12297 (cdr range) t))
12298 (progn
12299 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12301 nil)))))
12303 ;; Multi-values properties are properties that contain multiple values
12304 ;; These values are assumed to be single words, separated by whitespace.
12305 (defun org-entry-add-to-multivalued-property (pom property value)
12306 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12307 (let* ((old (org-entry-get pom property))
12308 (values (and old (org-split-string old "[ \t]"))))
12309 (setq value (org-entry-protect-space value))
12310 (unless (member value values)
12311 (setq values (cons value values))
12312 (org-entry-put pom property
12313 (mapconcat 'identity values " ")))))
12315 (defun org-entry-remove-from-multivalued-property (pom property value)
12316 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12317 (let* ((old (org-entry-get pom property))
12318 (values (and old (org-split-string old "[ \t]"))))
12319 (setq value (org-entry-protect-space value))
12320 (when (member value values)
12321 (setq values (delete value values))
12322 (org-entry-put pom property
12323 (mapconcat 'identity values " ")))))
12325 (defun org-entry-member-in-multivalued-property (pom property value)
12326 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12327 (let* ((old (org-entry-get pom property))
12328 (values (and old (org-split-string old "[ \t]"))))
12329 (setq value (org-entry-protect-space value))
12330 (member value values)))
12332 (defun org-entry-get-multivalued-property (pom property)
12333 "Return a list of values in a multivalued property."
12334 (let* ((value (org-entry-get pom property))
12335 (values (and value (org-split-string value "[ \t]"))))
12336 (mapcar 'org-entry-restore-space values)))
12338 (defun org-entry-put-multivalued-property (pom property &rest values)
12339 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12340 VALUES should be a list of strings. Spaces will be protected."
12341 (org-entry-put pom property
12342 (mapconcat 'org-entry-protect-space values " "))
12343 (let* ((value (org-entry-get pom property))
12344 (values (and value (org-split-string value "[ \t]"))))
12345 (mapcar 'org-entry-restore-space values)))
12347 (defun org-entry-protect-space (s)
12348 "Protect spaces and newline in string S."
12349 (while (string-match " " s)
12350 (setq s (replace-match "%20" t t s)))
12351 (while (string-match "\n" s)
12352 (setq s (replace-match "%0A" t t s)))
12355 (defun org-entry-restore-space (s)
12356 "Restore spaces and newline in string S."
12357 (while (string-match "%20" s)
12358 (setq s (replace-match " " t t s)))
12359 (while (string-match "%0A" s)
12360 (setq s (replace-match "\n" t t s)))
12363 (defvar org-entry-property-inherited-from (make-marker)
12364 "Marker pointing to the entry from where a property was inherited.
12365 Each call to `org-entry-get-with-inheritance' will set this marker to the
12366 location of the entry where the inheritance search matched. If there was
12367 no match, the marker will point nowhere.
12368 Note that also `org-entry-get' calls this function, if the INHERIT flag
12369 is set.")
12371 (defun org-entry-get-with-inheritance (property)
12372 "Get entry property, and search higher levels if not present."
12373 (move-marker org-entry-property-inherited-from nil)
12374 (let (tmp)
12375 (save-excursion
12376 (save-restriction
12377 (widen)
12378 (catch 'ex
12379 (while t
12380 (when (setq tmp (org-entry-get nil property))
12381 (org-back-to-heading t)
12382 (move-marker org-entry-property-inherited-from (point))
12383 (throw 'ex tmp))
12384 (or (org-up-heading-safe) (throw 'ex nil)))))
12385 (or tmp
12386 (cdr (assoc property org-file-properties))
12387 (cdr (assoc property org-global-properties))
12388 (cdr (assoc property org-global-properties-fixed))))))
12390 (defun org-entry-put (pom property value)
12391 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12392 (org-with-point-at pom
12393 (org-back-to-heading t)
12394 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12395 range)
12396 (cond
12397 ((equal property "TODO")
12398 (when (and (stringp value) (string-match "\\S-" value)
12399 (not (member value org-todo-keywords-1)))
12400 (error "\"%s\" is not a valid TODO state" value))
12401 (if (or (not value)
12402 (not (string-match "\\S-" value)))
12403 (setq value 'none))
12404 (org-todo value)
12405 (org-set-tags nil 'align))
12406 ((equal property "PRIORITY")
12407 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12408 (string-to-char value) ?\ ))
12409 (org-set-tags nil 'align))
12410 ((equal property "SCHEDULED")
12411 (if (re-search-forward org-scheduled-time-regexp end t)
12412 (cond
12413 ((eq value 'earlier) (org-timestamp-change -1 'day))
12414 ((eq value 'later) (org-timestamp-change 1 'day))
12415 (t (call-interactively 'org-schedule)))
12416 (call-interactively 'org-schedule)))
12417 ((equal property "DEADLINE")
12418 (if (re-search-forward org-deadline-time-regexp end t)
12419 (cond
12420 ((eq value 'earlier) (org-timestamp-change -1 'day))
12421 ((eq value 'later) (org-timestamp-change 1 'day))
12422 (t (call-interactively 'org-deadline)))
12423 (call-interactively 'org-deadline)))
12424 ((member property org-special-properties)
12425 (error "The %s property can not yet be set with `org-entry-put'"
12426 property))
12427 (t ; a non-special property
12428 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12429 (setq range (org-get-property-block beg end 'force))
12430 (goto-char (car range))
12431 (if (re-search-forward
12432 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12433 (progn
12434 (delete-region (match-beginning 1) (match-end 1))
12435 (goto-char (match-beginning 1)))
12436 (goto-char (cdr range))
12437 (insert "\n")
12438 (backward-char 1)
12439 (org-indent-line-function)
12440 (insert ":" property ":"))
12441 (and value (insert " " value))
12442 (org-indent-line-function)))))))
12444 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12445 "Get all property keys in the current buffer.
12446 With INCLUDE-SPECIALS, also list the special properties that reflect things
12447 like tags and TODO state.
12448 With INCLUDE-DEFAULTS, also include properties that has special meaning
12449 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12450 With INCLUDE-COLUMNS, also include property names given in COLUMN
12451 formats in the current buffer."
12452 (let (rtn range cfmt s p)
12453 (save-excursion
12454 (save-restriction
12455 (widen)
12456 (goto-char (point-min))
12457 (while (re-search-forward org-property-start-re nil t)
12458 (setq range (org-get-property-block))
12459 (goto-char (car range))
12460 (while (re-search-forward
12461 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12462 (cdr range) t)
12463 (add-to-list 'rtn (org-match-string-no-properties 1)))
12464 (outline-next-heading))))
12466 (when include-specials
12467 (setq rtn (append org-special-properties rtn)))
12469 (when include-defaults
12470 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12471 (add-to-list 'rtn org-effort-property))
12473 (when include-columns
12474 (save-excursion
12475 (save-restriction
12476 (widen)
12477 (goto-char (point-min))
12478 (while (re-search-forward
12479 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12480 nil t)
12481 (setq cfmt (match-string 2) s 0)
12482 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12483 cfmt s)
12484 (setq s (match-end 0)
12485 p (match-string 1 cfmt))
12486 (unless (or (equal p "ITEM")
12487 (member p org-special-properties))
12488 (add-to-list 'rtn (match-string 1 cfmt))))))))
12490 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12492 (defun org-property-values (key)
12493 "Return a list of all values of property KEY."
12494 (save-excursion
12495 (save-restriction
12496 (widen)
12497 (goto-char (point-min))
12498 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12499 values)
12500 (while (re-search-forward re nil t)
12501 (add-to-list 'values (org-trim (match-string 1))))
12502 (delete "" values)))))
12504 (defun org-insert-property-drawer ()
12505 "Insert a property drawer into the current entry."
12506 (interactive)
12507 (org-back-to-heading t)
12508 (looking-at outline-regexp)
12509 (let ((indent (if org-adapt-indentation
12510 (- (match-end 0)(match-beginning 0))
12512 (beg (point))
12513 (re (concat "^[ \t]*" org-keyword-time-regexp))
12514 end hiddenp)
12515 (outline-next-heading)
12516 (setq end (point))
12517 (goto-char beg)
12518 (while (re-search-forward re end t))
12519 (setq hiddenp (org-invisible-p))
12520 (end-of-line 1)
12521 (and (equal (char-after) ?\n) (forward-char 1))
12522 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12523 (if (member (match-string 1) '("CLOCK:" ":END:"))
12524 ;; just skip this line
12525 (beginning-of-line 2)
12526 ;; Drawer start, find the end
12527 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12528 (beginning-of-line 1)))
12529 (org-skip-over-state-notes)
12530 (skip-chars-backward " \t\n\r")
12531 (if (eq (char-before) ?*) (forward-char 1))
12532 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12533 (beginning-of-line 0)
12534 (org-indent-to-column indent)
12535 (beginning-of-line 2)
12536 (org-indent-to-column indent)
12537 (beginning-of-line 0)
12538 (if hiddenp
12539 (save-excursion
12540 (org-back-to-heading t)
12541 (hide-entry))
12542 (org-flag-drawer t))))
12544 (defun org-set-property (property value)
12545 "In the current entry, set PROPERTY to VALUE.
12546 When called interactively, this will prompt for a property name, offering
12547 completion on existing and default properties. And then it will prompt
12548 for a value, offering completion either on allowed values (via an inherited
12549 xxx_ALL property) or on existing values in other instances of this property
12550 in the current file."
12551 (interactive
12552 (let* ((completion-ignore-case t)
12553 (keys (org-buffer-property-keys nil t t))
12554 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12555 (prop (if (member prop0 keys)
12556 prop0
12557 (or (cdr (assoc (downcase prop0)
12558 (mapcar (lambda (x) (cons (downcase x) x))
12559 keys)))
12560 prop0)))
12561 (cur (org-entry-get nil prop))
12562 (allowed (org-property-get-allowed-values nil prop 'table))
12563 (existing (mapcar 'list (org-property-values prop)))
12564 (val (if allowed
12565 (org-completing-read "Value: " allowed nil 'req-match)
12566 (let (org-completion-use-ido org-completion-use-iswitchb)
12567 (org-completing-read
12568 (concat "Value " (if (and cur (string-match "\\S-" cur))
12569 (concat "[" cur "]") "")
12570 ": ")
12571 existing nil nil "" nil cur)))))
12572 (list prop (if (equal val "") cur val))))
12573 (unless (equal (org-entry-get nil property) value)
12574 (org-entry-put nil property value)))
12576 (defun org-delete-property (property)
12577 "In the current entry, delete PROPERTY."
12578 (interactive
12579 (let* ((completion-ignore-case t)
12580 (prop (org-icompleting-read
12581 "Property: " (org-entry-properties nil 'standard))))
12582 (list prop)))
12583 (message "Property %s %s" property
12584 (if (org-entry-delete nil property)
12585 "deleted"
12586 "was not present in the entry")))
12588 (defun org-delete-property-globally (property)
12589 "Remove PROPERTY globally, from all entries."
12590 (interactive
12591 (let* ((completion-ignore-case t)
12592 (prop (org-icompleting-read
12593 "Globally remove property: "
12594 (mapcar 'list (org-buffer-property-keys)))))
12595 (list prop)))
12596 (save-excursion
12597 (save-restriction
12598 (widen)
12599 (goto-char (point-min))
12600 (let ((cnt 0))
12601 (while (re-search-forward
12602 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12603 nil t)
12604 (setq cnt (1+ cnt))
12605 (replace-match ""))
12606 (message "Property \"%s\" removed from %d entries" property cnt)))))
12608 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12610 (defun org-compute-property-at-point ()
12611 "Compute the property at point.
12612 This looks for an enclosing column format, extracts the operator and
12613 then applies it to the property in the column format's scope."
12614 (interactive)
12615 (unless (org-at-property-p)
12616 (error "Not at a property"))
12617 (let ((prop (org-match-string-no-properties 2)))
12618 (org-columns-get-format-and-top-level)
12619 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12620 (error "No operator defined for property %s" prop))
12621 (org-columns-compute prop)))
12623 (defun org-property-get-allowed-values (pom property &optional table)
12624 "Get allowed values for the property PROPERTY.
12625 When TABLE is non-nil, return an alist that can directly be used for
12626 completion."
12627 (let (vals)
12628 (cond
12629 ((equal property "TODO")
12630 (setq vals (org-with-point-at pom
12631 (append org-todo-keywords-1 '("")))))
12632 ((equal property "PRIORITY")
12633 (let ((n org-lowest-priority))
12634 (while (>= n org-highest-priority)
12635 (push (char-to-string n) vals)
12636 (setq n (1- n)))))
12637 ((member property org-special-properties))
12639 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12641 (when (and vals (string-match "\\S-" vals))
12642 (setq vals (car (read-from-string (concat "(" vals ")"))))
12643 (setq vals (mapcar (lambda (x)
12644 (cond ((stringp x) x)
12645 ((numberp x) (number-to-string x))
12646 ((symbolp x) (symbol-name x))
12647 (t "???")))
12648 vals)))))
12649 (if table (mapcar 'list vals) vals)))
12651 (defun org-property-previous-allowed-value (&optional previous)
12652 "Switch to the next allowed value for this property."
12653 (interactive)
12654 (org-property-next-allowed-value t))
12656 (defun org-property-next-allowed-value (&optional previous)
12657 "Switch to the next allowed value for this property."
12658 (interactive)
12659 (unless (org-at-property-p)
12660 (error "Not at a property"))
12661 (let* ((key (match-string 2))
12662 (value (match-string 3))
12663 (allowed (or (org-property-get-allowed-values (point) key)
12664 (and (member value '("[ ]" "[-]" "[X]"))
12665 '("[ ]" "[X]"))))
12666 nval)
12667 (unless allowed
12668 (error "Allowed values for this property have not been defined"))
12669 (if previous (setq allowed (reverse allowed)))
12670 (if (member value allowed)
12671 (setq nval (car (cdr (member value allowed)))))
12672 (setq nval (or nval (car allowed)))
12673 (if (equal nval value)
12674 (error "Only one allowed value for this property"))
12675 (org-at-property-p)
12676 (replace-match (concat " :" key ": " nval) t t)
12677 (org-indent-line-function)
12678 (beginning-of-line 1)
12679 (skip-chars-forward " \t")))
12681 (defun org-find-entry-with-id (ident)
12682 "Locate the entry that contains the ID property with exact value IDENT.
12683 IDENT can be a string, a symbol or a number, this function will search for
12684 the string representation of it.
12685 Return the position where this entry starts, or nil if there is no such entry."
12686 (interactive "sID: ")
12687 (let ((id (cond
12688 ((stringp ident) ident)
12689 ((symbol-name ident) (symbol-name ident))
12690 ((numberp ident) (number-to-string ident))
12691 (t (error "IDENT %s must be a string, symbol or number" ident))))
12692 (case-fold-search nil))
12693 (save-excursion
12694 (save-restriction
12695 (widen)
12696 (goto-char (point-min))
12697 (when (re-search-forward
12698 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12699 nil t)
12700 (org-back-to-heading t)
12701 (point))))))
12703 ;;;; Timestamps
12705 (defvar org-last-changed-timestamp nil)
12706 (defvar org-last-inserted-timestamp nil
12707 "The last time stamp inserted with `org-insert-time-stamp'.")
12708 (defvar org-time-was-given) ; dynamically scoped parameter
12709 (defvar org-end-time-was-given) ; dynamically scoped parameter
12710 (defvar org-ts-what) ; dynamically scoped parameter
12712 (defun org-time-stamp (arg &optional inactive)
12713 "Prompt for a date/time and insert a time stamp.
12714 If the user specifies a time like HH:MM, or if this command is called
12715 with a prefix argument, the time stamp will contain date and time.
12716 Otherwise, only the date will be included. All parts of a date not
12717 specified by the user will be filled in from the current date/time.
12718 So if you press just return without typing anything, the time stamp
12719 will represent the current date/time. If there is already a timestamp
12720 at the cursor, it will be modified."
12721 (interactive "P")
12722 (let* ((ts nil)
12723 (default-time
12724 ;; Default time is either today, or, when entering a range,
12725 ;; the range start.
12726 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12727 (save-excursion
12728 (re-search-backward
12729 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12730 (- (point) 20) t)))
12731 (apply 'encode-time (org-parse-time-string (match-string 1)))
12732 (current-time)))
12733 (default-input (and ts (org-get-compact-tod ts)))
12734 org-time-was-given org-end-time-was-given time)
12735 (cond
12736 ((and (org-at-timestamp-p t)
12737 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12738 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12739 (insert "--")
12740 (setq time (let ((this-command this-command))
12741 (org-read-date arg 'totime nil nil
12742 default-time default-input)))
12743 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12744 ((org-at-timestamp-p t)
12745 (setq time (let ((this-command this-command))
12746 (org-read-date arg 'totime nil nil default-time default-input)))
12747 (when (org-at-timestamp-p t) ; just to get the match data
12748 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12749 (replace-match "")
12750 (setq org-last-changed-timestamp
12751 (org-insert-time-stamp
12752 time (or org-time-was-given arg)
12753 inactive nil nil (list org-end-time-was-given))))
12754 (message "Timestamp updated"))
12756 (setq time (let ((this-command this-command))
12757 (org-read-date arg 'totime nil nil default-time default-input)))
12758 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12759 nil nil (list org-end-time-was-given))))))
12761 ;; FIXME: can we use this for something else, like computing time differences?
12762 (defun org-get-compact-tod (s)
12763 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12764 (let* ((t1 (match-string 1 s))
12765 (h1 (string-to-number (match-string 2 s)))
12766 (m1 (string-to-number (match-string 3 s)))
12767 (t2 (and (match-end 4) (match-string 5 s)))
12768 (h2 (and t2 (string-to-number (match-string 6 s))))
12769 (m2 (and t2 (string-to-number (match-string 7 s))))
12770 dh dm)
12771 (if (not t2)
12773 (setq dh (- h2 h1) dm (- m2 m1))
12774 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12775 (concat t1 "+" (number-to-string dh)
12776 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12778 (defun org-time-stamp-inactive (&optional arg)
12779 "Insert an inactive time stamp.
12780 An inactive time stamp is enclosed in square brackets instead of angle
12781 brackets. It is inactive in the sense that it does not trigger agenda entries,
12782 does not link to the calendar and cannot be changed with the S-cursor keys.
12783 So these are more for recording a certain time/date."
12784 (interactive "P")
12785 (org-time-stamp arg 'inactive))
12787 (defvar org-date-ovl (org-make-overlay 1 1))
12788 (org-overlay-put org-date-ovl 'face 'org-warning)
12789 (org-detach-overlay org-date-ovl)
12791 (defvar org-ans1) ; dynamically scoped parameter
12792 (defvar org-ans2) ; dynamically scoped parameter
12794 (defvar org-plain-time-of-day-regexp) ; defined below
12796 (defvar org-overriding-default-time nil) ; dynamically scoped
12797 (defvar org-read-date-overlay nil)
12798 (defvar org-dcst nil) ; dynamically scoped
12799 (defvar org-read-date-history nil)
12800 (defvar org-read-date-final-answer nil)
12802 (defun org-read-date (&optional with-time to-time from-string prompt
12803 default-time default-input)
12804 "Read a date, possibly a time, and make things smooth for the user.
12805 The prompt will suggest to enter an ISO date, but you can also enter anything
12806 which will at least partially be understood by `parse-time-string'.
12807 Unrecognized parts of the date will default to the current day, month, year,
12808 hour and minute. If this command is called to replace a timestamp at point,
12809 of to enter the second timestamp of a range, the default time is taken from the
12810 existing stamp. For example,
12811 3-2-5 --> 2003-02-05
12812 feb 15 --> currentyear-02-15
12813 sep 12 9 --> 2009-09-12
12814 12:45 --> today 12:45
12815 22 sept 0:34 --> currentyear-09-22 0:34
12816 12 --> currentyear-currentmonth-12
12817 Fri --> nearest Friday (today or later)
12818 etc.
12820 Furthermore you can specify a relative date by giving, as the *first* thing
12821 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12822 change in days weeks, months, years.
12823 With a single plus or minus, the date is relative to today. With a double
12824 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12825 +4d --> four days from today
12826 +4 --> same as above
12827 +2w --> two weeks from today
12828 ++5 --> five days from default date
12830 The function understands only English month and weekday abbreviations,
12831 but this can be configured with the variables `parse-time-months' and
12832 `parse-time-weekdays'.
12834 While prompting, a calendar is popped up - you can also select the
12835 date with the mouse (button 1). The calendar shows a period of three
12836 months. To scroll it to other months, use the keys `>' and `<'.
12837 If you don't like the calendar, turn it off with
12838 \(setq org-read-date-popup-calendar nil)
12840 With optional argument TO-TIME, the date will immediately be converted
12841 to an internal time.
12842 With an optional argument WITH-TIME, the prompt will suggest to also
12843 insert a time. Note that when WITH-TIME is not set, you can still
12844 enter a time, and this function will inform the calling routine about
12845 this change. The calling routine may then choose to change the format
12846 used to insert the time stamp into the buffer to include the time.
12847 With optional argument FROM-STRING, read from this string instead from
12848 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12849 the time/date that is used for everything that is not specified by the
12850 user."
12851 (require 'parse-time)
12852 (let* ((org-time-stamp-rounding-minutes
12853 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12854 (org-dcst org-display-custom-times)
12855 (ct (org-current-time))
12856 (def (or org-overriding-default-time default-time ct))
12857 (defdecode (decode-time def))
12858 (dummy (progn
12859 (when (< (nth 2 defdecode) org-extend-today-until)
12860 (setcar (nthcdr 2 defdecode) -1)
12861 (setcar (nthcdr 1 defdecode) 59)
12862 (setq def (apply 'encode-time defdecode)
12863 defdecode (decode-time def)))))
12864 (calendar-frame-setup nil)
12865 (calendar-move-hook nil)
12866 (calendar-view-diary-initially-flag nil)
12867 (view-diary-entries-initially nil)
12868 (calendar-view-holidays-initially-flag nil)
12869 (view-calendar-holidays-initially nil)
12870 (timestr (format-time-string
12871 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12872 (prompt (concat (if prompt (concat prompt " ") "")
12873 (format "Date+time [%s]: " timestr)))
12874 ans (org-ans0 "") org-ans1 org-ans2 final)
12876 (cond
12877 (from-string (setq ans from-string))
12878 (org-read-date-popup-calendar
12879 (save-excursion
12880 (save-window-excursion
12881 (calendar)
12882 (calendar-forward-day (- (time-to-days def)
12883 (calendar-absolute-from-gregorian
12884 (calendar-current-date))))
12885 (org-eval-in-calendar nil t)
12886 (let* ((old-map (current-local-map))
12887 (map (copy-keymap calendar-mode-map))
12888 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12889 (org-defkey map (kbd "RET") 'org-calendar-select)
12890 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12891 'org-calendar-select-mouse)
12892 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12893 'org-calendar-select-mouse)
12894 (org-defkey minibuffer-local-map [(meta shift left)]
12895 (lambda () (interactive)
12896 (org-eval-in-calendar '(calendar-backward-month 1))))
12897 (org-defkey minibuffer-local-map [(meta shift right)]
12898 (lambda () (interactive)
12899 (org-eval-in-calendar '(calendar-forward-month 1))))
12900 (org-defkey minibuffer-local-map [(meta shift up)]
12901 (lambda () (interactive)
12902 (org-eval-in-calendar '(calendar-backward-year 1))))
12903 (org-defkey minibuffer-local-map [(meta shift down)]
12904 (lambda () (interactive)
12905 (org-eval-in-calendar '(calendar-forward-year 1))))
12906 (org-defkey minibuffer-local-map [?\e (shift left)]
12907 (lambda () (interactive)
12908 (org-eval-in-calendar '(calendar-backward-month 1))))
12909 (org-defkey minibuffer-local-map [?\e (shift right)]
12910 (lambda () (interactive)
12911 (org-eval-in-calendar '(calendar-forward-month 1))))
12912 (org-defkey minibuffer-local-map [?\e (shift up)]
12913 (lambda () (interactive)
12914 (org-eval-in-calendar '(calendar-backward-year 1))))
12915 (org-defkey minibuffer-local-map [?\e (shift down)]
12916 (lambda () (interactive)
12917 (org-eval-in-calendar '(calendar-forward-year 1))))
12918 (org-defkey minibuffer-local-map [(shift up)]
12919 (lambda () (interactive)
12920 (org-eval-in-calendar '(calendar-backward-week 1))))
12921 (org-defkey minibuffer-local-map [(shift down)]
12922 (lambda () (interactive)
12923 (org-eval-in-calendar '(calendar-forward-week 1))))
12924 (org-defkey minibuffer-local-map [(shift left)]
12925 (lambda () (interactive)
12926 (org-eval-in-calendar '(calendar-backward-day 1))))
12927 (org-defkey minibuffer-local-map [(shift right)]
12928 (lambda () (interactive)
12929 (org-eval-in-calendar '(calendar-forward-day 1))))
12930 (org-defkey minibuffer-local-map ">"
12931 (lambda () (interactive)
12932 (org-eval-in-calendar '(scroll-calendar-left 1))))
12933 (org-defkey minibuffer-local-map "<"
12934 (lambda () (interactive)
12935 (org-eval-in-calendar '(scroll-calendar-right 1))))
12936 (run-hooks 'org-read-date-minibuffer-setup-hook)
12937 (unwind-protect
12938 (progn
12939 (use-local-map map)
12940 (add-hook 'post-command-hook 'org-read-date-display)
12941 (setq org-ans0 (read-string prompt default-input
12942 'org-read-date-history nil))
12943 ;; org-ans0: from prompt
12944 ;; org-ans1: from mouse click
12945 ;; org-ans2: from calendar motion
12946 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12947 (remove-hook 'post-command-hook 'org-read-date-display)
12948 (use-local-map old-map)
12949 (when org-read-date-overlay
12950 (org-delete-overlay org-read-date-overlay)
12951 (setq org-read-date-overlay nil)))))))
12953 (t ; Naked prompt only
12954 (unwind-protect
12955 (setq ans (read-string prompt default-input
12956 'org-read-date-history timestr))
12957 (when org-read-date-overlay
12958 (org-delete-overlay org-read-date-overlay)
12959 (setq org-read-date-overlay nil)))))
12961 (setq final (org-read-date-analyze ans def defdecode))
12962 (setq org-read-date-final-answer ans)
12964 (if to-time
12965 (apply 'encode-time final)
12966 (if (and (boundp 'org-time-was-given) org-time-was-given)
12967 (format "%04d-%02d-%02d %02d:%02d"
12968 (nth 5 final) (nth 4 final) (nth 3 final)
12969 (nth 2 final) (nth 1 final))
12970 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12972 (defvar def)
12973 (defvar defdecode)
12974 (defvar with-time)
12975 (defvar org-read-date-analyze-futurep nil)
12976 (defun org-read-date-display ()
12977 "Display the current date prompt interpretation in the minibuffer."
12978 (when org-read-date-display-live
12979 (when org-read-date-overlay
12980 (org-delete-overlay org-read-date-overlay))
12981 (let ((p (point)))
12982 (end-of-line 1)
12983 (while (not (equal (buffer-substring
12984 (max (point-min) (- (point) 4)) (point))
12985 " "))
12986 (insert " "))
12987 (goto-char p))
12988 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12989 " " (or org-ans1 org-ans2)))
12990 (org-end-time-was-given nil)
12991 (f (org-read-date-analyze ans def defdecode))
12992 (fmts (if org-dcst
12993 org-time-stamp-custom-formats
12994 org-time-stamp-formats))
12995 (fmt (if (or with-time
12996 (and (boundp 'org-time-was-given) org-time-was-given))
12997 (cdr fmts)
12998 (car fmts)))
12999 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13000 (when (and org-end-time-was-given
13001 (string-match org-plain-time-of-day-regexp txt))
13002 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13003 org-end-time-was-given
13004 (substring txt (match-end 0)))))
13005 (when org-read-date-analyze-futurep
13006 (setq txt (concat txt " (=>F)")))
13007 (setq org-read-date-overlay
13008 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13009 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13011 (defun org-read-date-analyze (ans def defdecode)
13012 "Analyse the combined answer of the date prompt."
13013 ;; FIXME: cleanup and comment
13014 (let (delta deltan deltaw deltadef year month day
13015 hour minute second wday pm h2 m2 tl wday1
13016 iso-year iso-weekday iso-week iso-year iso-date futurep)
13017 (setq org-read-date-analyze-futurep nil)
13018 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13019 (setq ans "+0"))
13021 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13022 (setq ans (replace-match "" t t ans)
13023 deltan (car delta)
13024 deltaw (nth 1 delta)
13025 deltadef (nth 2 delta)))
13027 ;; Check if there is an iso week date in there
13028 ;; If yes, sore the info and postpone interpreting it until the rest
13029 ;; of the parsing is done
13030 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13031 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
13032 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
13033 iso-week (string-to-number (match-string 2 ans)))
13034 (setq ans (replace-match "" t t ans)))
13036 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
13037 (when (string-match
13038 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13039 (setq year (if (match-end 2)
13040 (string-to-number (match-string 2 ans))
13041 (string-to-number (format-time-string "%Y")))
13042 month (string-to-number (match-string 3 ans))
13043 day (string-to-number (match-string 4 ans)))
13044 (if (< year 100) (setq year (+ 2000 year)))
13045 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13046 t nil ans)))
13047 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13048 ;; If there is a time with am/pm, and *no* time without it, we convert
13049 ;; so that matching will be successful.
13050 (loop for i from 1 to 2 do ; twice, for end time as well
13051 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13052 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13053 (setq hour (string-to-number (match-string 1 ans))
13054 minute (if (match-end 3)
13055 (string-to-number (match-string 3 ans))
13057 pm (equal ?p
13058 (string-to-char (downcase (match-string 4 ans)))))
13059 (if (and (= hour 12) (not pm))
13060 (setq hour 0)
13061 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13062 (setq ans (replace-match (format "%02d:%02d" hour minute)
13063 t t ans))))
13065 ;; Check if a time range is given as a duration
13066 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13067 (setq hour (string-to-number (match-string 1 ans))
13068 h2 (+ hour (string-to-number (match-string 3 ans)))
13069 minute (string-to-number (match-string 2 ans))
13070 m2 (+ minute (if (match-end 5) (string-to-number
13071 (match-string 5 ans))0)))
13072 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13073 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13074 t t ans)))
13076 ;; Check if there is a time range
13077 (when (boundp 'org-end-time-was-given)
13078 (setq org-time-was-given nil)
13079 (when (and (string-match org-plain-time-of-day-regexp ans)
13080 (match-end 8))
13081 (setq org-end-time-was-given (match-string 8 ans))
13082 (setq ans (concat (substring ans 0 (match-beginning 7))
13083 (substring ans (match-end 7))))))
13085 (setq tl (parse-time-string ans)
13086 day (or (nth 3 tl) (nth 3 defdecode))
13087 month (or (nth 4 tl)
13088 (if (and org-read-date-prefer-future
13089 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
13090 (prog1 (1+ (nth 4 defdecode)) (setq futurep t))
13091 (nth 4 defdecode)))
13092 year (or (nth 5 tl)
13093 (if (and org-read-date-prefer-future
13094 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
13095 (prog1 (1+ (nth 5 defdecode)) (setq futurep t))
13096 (nth 5 defdecode)))
13097 hour (or (nth 2 tl) (nth 2 defdecode))
13098 minute (or (nth 1 tl) (nth 1 defdecode))
13099 second (or (nth 0 tl) 0)
13100 wday (nth 6 tl))
13102 (when (and (eq org-read-date-prefer-future 'time)
13103 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13104 (equal day (nth 3 defdecode))
13105 (equal month (nth 4 defdecode))
13106 (equal year (nth 5 defdecode))
13107 (nth 2 tl)
13108 (or (< (nth 2 tl) (nth 2 defdecode))
13109 (and (= (nth 2 tl) (nth 2 defdecode))
13110 (nth 1 tl)
13111 (< (nth 1 tl) (nth 1 defdecode)))))
13112 (setq day (1+ day)
13113 futurep t))
13115 ;; Special date definitions below
13116 (cond
13117 (iso-week
13118 ;; There was an iso week
13119 (setq futurep nil)
13120 (setq year (or iso-year year)
13121 day (or iso-weekday wday 1)
13122 wday nil ; to make sure that the trigger below does not match
13123 iso-date (calendar-gregorian-from-absolute
13124 (calendar-absolute-from-iso
13125 (list iso-week day year))))
13126 ; FIXME: Should we also push ISO weeks into the future?
13127 ; (when (and org-read-date-prefer-future
13128 ; (not iso-year)
13129 ; (< (calendar-absolute-from-gregorian iso-date)
13130 ; (time-to-days (current-time))))
13131 ; (setq year (1+ year)
13132 ; iso-date (calendar-gregorian-from-absolute
13133 ; (calendar-absolute-from-iso
13134 ; (list iso-week day year)))))
13135 (setq month (car iso-date)
13136 year (nth 2 iso-date)
13137 day (nth 1 iso-date)))
13138 (deltan
13139 (setq futurep nil)
13140 (unless deltadef
13141 (let ((now (decode-time (current-time))))
13142 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13143 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13144 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13145 ((equal deltaw "m") (setq month (+ month deltan)))
13146 ((equal deltaw "y") (setq year (+ year deltan)))))
13147 ((and wday (not (nth 3 tl)))
13148 (setq futurep nil)
13149 ;; Weekday was given, but no day, so pick that day in the week
13150 ;; on or after the derived date.
13151 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13152 (unless (equal wday wday1)
13153 (setq day (+ day (% (- wday wday1 -7) 7))))))
13154 (if (and (boundp 'org-time-was-given)
13155 (nth 2 tl))
13156 (setq org-time-was-given t))
13157 (if (< year 100) (setq year (+ 2000 year)))
13158 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13159 (setq org-read-date-analyze-futurep futurep)
13160 (list second minute hour day month year)))
13162 (defvar parse-time-weekdays)
13164 (defun org-read-date-get-relative (s today default)
13165 "Check string S for special relative date string.
13166 TODAY and DEFAULT are internal times, for today and for a default.
13167 Return shift list (N what def-flag)
13168 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13169 N is the number of WHATs to shift.
13170 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13171 the DEFAULT date rather than TODAY."
13172 (when (and
13173 (string-match
13174 (concat
13175 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13176 "\\([0-9]+\\)?"
13177 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13178 "\\([ \t]\\|$\\)") s)
13179 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13180 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13181 (string-to-char (substring (match-string 1 s) -1))
13182 ?+))
13183 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13184 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13185 (what (if (match-end 3) (match-string 3 s) "d"))
13186 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13187 (date (if rel default today))
13188 (wday (nth 6 (decode-time date)))
13189 delta)
13190 (if wday1
13191 (progn
13192 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13193 (if (= dir ?-) (setq delta (- delta 7)))
13194 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13195 (list delta "d" rel))
13196 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13198 (defun org-eval-in-calendar (form &optional keepdate)
13199 "Eval FORM in the calendar window and return to current window.
13200 Also, store the cursor date in variable org-ans2."
13201 (let ((sf (selected-frame))
13202 (sw (selected-window)))
13203 (select-window (get-buffer-window "*Calendar*" t))
13204 (eval form)
13205 (when (and (not keepdate) (calendar-cursor-to-date))
13206 (let* ((date (calendar-cursor-to-date))
13207 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13208 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13209 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13210 (select-window sw)
13211 (org-select-frame-set-input-focus sf)))
13213 (defun org-calendar-select ()
13214 "Return to `org-read-date' with the date currently selected.
13215 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13216 (interactive)
13217 (when (calendar-cursor-to-date)
13218 (let* ((date (calendar-cursor-to-date))
13219 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13220 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13221 (if (active-minibuffer-window) (exit-minibuffer))))
13223 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13224 "Insert a date stamp for the date given by the internal TIME.
13225 WITH-HM means, use the stamp format that includes the time of the day.
13226 INACTIVE means use square brackets instead of angular ones, so that the
13227 stamp will not contribute to the agenda.
13228 PRE and POST are optional strings to be inserted before and after the
13229 stamp.
13230 The command returns the inserted time stamp."
13231 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13232 stamp)
13233 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13234 (insert-before-markers (or pre ""))
13235 (insert-before-markers (setq stamp (format-time-string fmt time)))
13236 (when (listp extra)
13237 (setq extra (car extra))
13238 (if (and (stringp extra)
13239 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13240 (setq extra (format "-%02d:%02d"
13241 (string-to-number (match-string 1 extra))
13242 (string-to-number (match-string 2 extra))))
13243 (setq extra nil)))
13244 (when extra
13245 (backward-char 1)
13246 (insert-before-markers extra)
13247 (forward-char 1))
13248 (insert-before-markers (or post ""))
13249 (setq org-last-inserted-timestamp stamp)))
13251 (defun org-toggle-time-stamp-overlays ()
13252 "Toggle the use of custom time stamp formats."
13253 (interactive)
13254 (setq org-display-custom-times (not org-display-custom-times))
13255 (unless org-display-custom-times
13256 (let ((p (point-min)) (bmp (buffer-modified-p)))
13257 (while (setq p (next-single-property-change p 'display))
13258 (if (and (get-text-property p 'display)
13259 (eq (get-text-property p 'face) 'org-date))
13260 (remove-text-properties
13261 p (setq p (next-single-property-change p 'display))
13262 '(display t))))
13263 (set-buffer-modified-p bmp)))
13264 (if (featurep 'xemacs)
13265 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13266 (org-restart-font-lock)
13267 (setq org-table-may-need-update t)
13268 (if org-display-custom-times
13269 (message "Time stamps are overlayed with custom format")
13270 (message "Time stamp overlays removed")))
13272 (defun org-display-custom-time (beg end)
13273 "Overlay modified time stamp format over timestamp between BEG and END."
13274 (let* ((ts (buffer-substring beg end))
13275 t1 w1 with-hm tf time str w2 (off 0))
13276 (save-match-data
13277 (setq t1 (org-parse-time-string ts t))
13278 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13279 (setq off (- (match-end 0) (match-beginning 0)))))
13280 (setq end (- end off))
13281 (setq w1 (- end beg)
13282 with-hm (and (nth 1 t1) (nth 2 t1))
13283 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13284 time (org-fix-decoded-time t1)
13285 str (org-add-props
13286 (format-time-string
13287 (substring tf 1 -1) (apply 'encode-time time))
13288 nil 'mouse-face 'highlight)
13289 w2 (length str))
13290 (if (not (= w2 w1))
13291 (add-text-properties (1+ beg) (+ 2 beg)
13292 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13293 (if (featurep 'xemacs)
13294 (progn
13295 (put-text-property beg end 'invisible t)
13296 (put-text-property beg end 'end-glyph (make-glyph str)))
13297 (put-text-property beg end 'display str))))
13299 (defun org-translate-time (string)
13300 "Translate all timestamps in STRING to custom format.
13301 But do this only if the variable `org-display-custom-times' is set."
13302 (when org-display-custom-times
13303 (save-match-data
13304 (let* ((start 0)
13305 (re org-ts-regexp-both)
13306 t1 with-hm inactive tf time str beg end)
13307 (while (setq start (string-match re string start))
13308 (setq beg (match-beginning 0)
13309 end (match-end 0)
13310 t1 (save-match-data
13311 (org-parse-time-string (substring string beg end) t))
13312 with-hm (and (nth 1 t1) (nth 2 t1))
13313 inactive (equal (substring string beg (1+ beg)) "[")
13314 tf (funcall (if with-hm 'cdr 'car)
13315 org-time-stamp-custom-formats)
13316 time (org-fix-decoded-time t1)
13317 str (format-time-string
13318 (concat
13319 (if inactive "[" "<") (substring tf 1 -1)
13320 (if inactive "]" ">"))
13321 (apply 'encode-time time))
13322 string (replace-match str t t string)
13323 start (+ start (length str)))))))
13324 string)
13326 (defun org-fix-decoded-time (time)
13327 "Set 0 instead of nil for the first 6 elements of time.
13328 Don't touch the rest."
13329 (let ((n 0))
13330 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13332 (defun org-days-to-time (timestamp-string)
13333 "Difference between TIMESTAMP-STRING and now in days."
13334 (- (time-to-days (org-time-string-to-time timestamp-string))
13335 (time-to-days (current-time))))
13337 (defun org-deadline-close (timestamp-string &optional ndays)
13338 "Is the time in TIMESTAMP-STRING close to the current date?"
13339 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13340 (and (< (org-days-to-time timestamp-string) ndays)
13341 (not (org-entry-is-done-p))))
13343 (defun org-get-wdays (ts)
13344 "Get the deadline lead time appropriate for timestring TS."
13345 (cond
13346 ((<= org-deadline-warning-days 0)
13347 ;; 0 or negative, enforce this value no matter what
13348 (- org-deadline-warning-days))
13349 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13350 ;; lead time is specified.
13351 (floor (* (string-to-number (match-string 1 ts))
13352 (cdr (assoc (match-string 2 ts)
13353 '(("d" . 1) ("w" . 7)
13354 ("m" . 30.4) ("y" . 365.25)))))))
13355 ;; go for the default.
13356 (t org-deadline-warning-days)))
13358 (defun org-calendar-select-mouse (ev)
13359 "Return to `org-read-date' with the date currently selected.
13360 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13361 (interactive "e")
13362 (mouse-set-point ev)
13363 (when (calendar-cursor-to-date)
13364 (let* ((date (calendar-cursor-to-date))
13365 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13366 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13367 (if (active-minibuffer-window) (exit-minibuffer))))
13369 (defun org-check-deadlines (ndays)
13370 "Check if there are any deadlines due or past due.
13371 A deadline is considered due if it happens within `org-deadline-warning-days'
13372 days from today's date. If the deadline appears in an entry marked DONE,
13373 it is not shown. The prefix arg NDAYS can be used to test that many
13374 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13375 (interactive "P")
13376 (let* ((org-warn-days
13377 (cond
13378 ((equal ndays '(4)) 100000)
13379 (ndays (prefix-numeric-value ndays))
13380 (t (abs org-deadline-warning-days))))
13381 (case-fold-search nil)
13382 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13383 (callback
13384 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13386 (message "%d deadlines past-due or due within %d days"
13387 (org-occur regexp nil callback)
13388 org-warn-days)))
13390 (defun org-check-before-date (date)
13391 "Check if there are deadlines or scheduled entries before DATE."
13392 (interactive (list (org-read-date)))
13393 (let ((case-fold-search nil)
13394 (regexp (concat "\\<\\(" org-deadline-string
13395 "\\|" org-scheduled-string
13396 "\\) *<\\([^>]+\\)>"))
13397 (callback
13398 (lambda () (time-less-p
13399 (org-time-string-to-time (match-string 2))
13400 (org-time-string-to-time date)))))
13401 (message "%d entries before %s"
13402 (org-occur regexp nil callback) date)))
13404 (defun org-check-after-date (date)
13405 "Check if there are deadlines or scheduled entries after DATE."
13406 (interactive (list (org-read-date)))
13407 (let ((case-fold-search nil)
13408 (regexp (concat "\\<\\(" org-deadline-string
13409 "\\|" org-scheduled-string
13410 "\\) *<\\([^>]+\\)>"))
13411 (callback
13412 (lambda () (not
13413 (time-less-p
13414 (org-time-string-to-time (match-string 2))
13415 (org-time-string-to-time date))))))
13416 (message "%d entries after %s"
13417 (org-occur regexp nil callback) date)))
13419 (defun org-evaluate-time-range (&optional to-buffer)
13420 "Evaluate a time range by computing the difference between start and end.
13421 Normally the result is just printed in the echo area, but with prefix arg
13422 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13423 If the time range is actually in a table, the result is inserted into the
13424 next column.
13425 For time difference computation, a year is assumed to be exactly 365
13426 days in order to avoid rounding problems."
13427 (interactive "P")
13429 (org-clock-update-time-maybe)
13430 (save-excursion
13431 (unless (org-at-date-range-p t)
13432 (goto-char (point-at-bol))
13433 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13434 (if (not (org-at-date-range-p t))
13435 (error "Not at a time-stamp range, and none found in current line")))
13436 (let* ((ts1 (match-string 1))
13437 (ts2 (match-string 2))
13438 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13439 (match-end (match-end 0))
13440 (time1 (org-time-string-to-time ts1))
13441 (time2 (org-time-string-to-time ts2))
13442 (t1 (org-float-time time1))
13443 (t2 (org-float-time time2))
13444 (diff (abs (- t2 t1)))
13445 (negative (< (- t2 t1) 0))
13446 ;; (ys (floor (* 365 24 60 60)))
13447 (ds (* 24 60 60))
13448 (hs (* 60 60))
13449 (fy "%dy %dd %02d:%02d")
13450 (fy1 "%dy %dd")
13451 (fd "%dd %02d:%02d")
13452 (fd1 "%dd")
13453 (fh "%02d:%02d")
13454 y d h m align)
13455 (if havetime
13456 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13458 d (floor (/ diff ds)) diff (mod diff ds)
13459 h (floor (/ diff hs)) diff (mod diff hs)
13460 m (floor (/ diff 60)))
13461 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13463 d (floor (+ (/ diff ds) 0.5))
13464 h 0 m 0))
13465 (if (not to-buffer)
13466 (message "%s" (org-make-tdiff-string y d h m))
13467 (if (org-at-table-p)
13468 (progn
13469 (goto-char match-end)
13470 (setq align t)
13471 (and (looking-at " *|") (goto-char (match-end 0))))
13472 (goto-char match-end))
13473 (if (looking-at
13474 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13475 (replace-match ""))
13476 (if negative (insert " -"))
13477 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13478 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13479 (insert " " (format fh h m))))
13480 (if align (org-table-align))
13481 (message "Time difference inserted")))))
13483 (defun org-make-tdiff-string (y d h m)
13484 (let ((fmt "")
13485 (l nil))
13486 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13487 l (push y l)))
13488 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13489 l (push d l)))
13490 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13491 l (push h l)))
13492 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13493 l (push m l)))
13494 (apply 'format fmt (nreverse l))))
13496 (defun org-time-string-to-time (s)
13497 (apply 'encode-time (org-parse-time-string s)))
13498 (defun org-time-string-to-seconds (s)
13499 (org-float-time (org-time-string-to-time s)))
13501 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13502 "Convert a time stamp to an absolute day number.
13503 If there is a specifyer for a cyclic time stamp, get the closest date to
13504 DAYNR.
13505 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13506 the variable date is bound by the calendar when this is called."
13507 (cond
13508 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13509 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13510 daynr
13511 (+ daynr 1000)))
13512 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13513 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13514 (time-to-days (current-time))) (match-string 0 s)
13515 prefer show-all))
13516 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13518 (defun org-days-to-iso-week (days)
13519 "Return the iso week number."
13520 (require 'cal-iso)
13521 (car (calendar-iso-from-absolute days)))
13523 (defun org-small-year-to-year (year)
13524 "Convert 2-digit years into 4-digit years.
13525 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13526 The year 2000 cannot be abbreviated. Any year larger than 99
13527 is returned unchanged."
13528 (if (< year 38)
13529 (setq year (+ 2000 year))
13530 (if (< year 100)
13531 (setq year (+ 1900 year))))
13532 year)
13534 (defun org-time-from-absolute (d)
13535 "Return the time corresponding to date D.
13536 D may be an absolute day number, or a calendar-type list (month day year)."
13537 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13538 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13540 (defun org-calendar-holiday ()
13541 "List of holidays, for Diary display in Org-mode."
13542 (require 'holidays)
13543 (let ((hl (funcall
13544 (if (fboundp 'calendar-check-holidays)
13545 'calendar-check-holidays 'check-calendar-holidays) date)))
13546 (if hl (mapconcat 'identity hl "; "))))
13548 (defun org-diary-sexp-entry (sexp entry date)
13549 "Process a SEXP diary ENTRY for DATE."
13550 (require 'diary-lib)
13551 (let ((result (if calendar-debug-sexp
13552 (let ((stack-trace-on-error t))
13553 (eval (car (read-from-string sexp))))
13554 (condition-case nil
13555 (eval (car (read-from-string sexp)))
13556 (error
13557 (beep)
13558 (message "Bad sexp at line %d in %s: %s"
13559 (org-current-line)
13560 (buffer-file-name) sexp)
13561 (sleep-for 2))))))
13562 (cond ((stringp result) result)
13563 ((and (consp result)
13564 (stringp (cdr result))) (cdr result))
13565 (result entry)
13566 (t nil))))
13568 (defun org-diary-to-ical-string (frombuf)
13569 "Get iCalendar entries from diary entries in buffer FROMBUF.
13570 This uses the icalendar.el library."
13571 (let* ((tmpdir (if (featurep 'xemacs)
13572 (temp-directory)
13573 temporary-file-directory))
13574 (tmpfile (make-temp-name
13575 (expand-file-name "orgics" tmpdir)))
13576 buf rtn b e)
13577 (with-current-buffer frombuf
13578 (icalendar-export-region (point-min) (point-max) tmpfile)
13579 (setq buf (find-buffer-visiting tmpfile))
13580 (set-buffer buf)
13581 (goto-char (point-min))
13582 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13583 (setq b (match-beginning 0)))
13584 (goto-char (point-max))
13585 (if (re-search-backward "^END:VEVENT" nil t)
13586 (setq e (match-end 0)))
13587 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13588 (kill-buffer buf)
13589 (delete-file tmpfile)
13590 rtn))
13592 (defun org-closest-date (start current change prefer show-all)
13593 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13594 When PREFER is `past' return a date that is either CURRENT or past.
13595 When PREFER is `future', return a date that is either CURRENT or future.
13596 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13597 ;; Make the proper lists from the dates
13598 (catch 'exit
13599 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13600 dn dw sday cday n1 n2 n0
13601 d m y y1 y2 date1 date2 nmonths nm ny m2)
13603 (setq start (org-date-to-gregorian start)
13604 current (org-date-to-gregorian
13605 (if show-all
13606 current
13607 (time-to-days (current-time))))
13608 sday (calendar-absolute-from-gregorian start)
13609 cday (calendar-absolute-from-gregorian current))
13611 (if (<= cday sday) (throw 'exit sday))
13613 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13614 (setq dn (string-to-number (match-string 1 change))
13615 dw (cdr (assoc (match-string 2 change) a1)))
13616 (error "Invalid change specifyer: %s" change))
13617 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13618 (cond
13619 ((eq dw 'day)
13620 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13621 n2 (+ n1 dn)))
13622 ((eq dw 'year)
13623 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13624 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13625 (setq date1 (list m d y1)
13626 n1 (calendar-absolute-from-gregorian date1)
13627 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13628 n2 (calendar-absolute-from-gregorian date2)))
13629 ((eq dw 'month)
13630 ;; approx number of month between the two dates
13631 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13632 ;; How often does dn fit in there?
13633 (setq d (nth 1 start) m (car start) y (nth 2 start)
13634 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13635 m (+ m nm)
13636 ny (floor (/ m 12))
13637 y (+ y ny)
13638 m (- m (* ny 12)))
13639 (while (> m 12) (setq m (- m 12) y (1+ y)))
13640 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13641 (setq m2 (+ m dn) y2 y)
13642 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13643 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13644 (while (<= n2 cday)
13645 (setq n1 n2 m m2 y y2)
13646 (setq m2 (+ m dn) y2 y)
13647 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13648 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13649 ;; Make sure n1 is the earlier date
13650 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13651 (if show-all
13652 (cond
13653 ((eq prefer 'past) (if (= cday n2) n2 n1))
13654 ((eq prefer 'future) (if (= cday n1) n1 n2))
13655 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13656 (cond
13657 ((eq prefer 'past) (if (= cday n2) n2 n1))
13658 ((eq prefer 'future) (if (= cday n1) n1 n2))
13659 (t (if (= cday n1) n1 n2)))))))
13661 (defun org-date-to-gregorian (date)
13662 "Turn any specification of DATE into a gregorian date for the calendar."
13663 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13664 ((and (listp date) (= (length date) 3)) date)
13665 ((stringp date)
13666 (setq date (org-parse-time-string date))
13667 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13668 ((listp date)
13669 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13671 (defun org-parse-time-string (s &optional nodefault)
13672 "Parse the standard Org-mode time string.
13673 This should be a lot faster than the normal `parse-time-string'.
13674 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13675 hour and minute fields will be nil if not given."
13676 (if (string-match org-ts-regexp0 s)
13677 (list 0
13678 (if (or (match-beginning 8) (not nodefault))
13679 (string-to-number (or (match-string 8 s) "0")))
13680 (if (or (match-beginning 7) (not nodefault))
13681 (string-to-number (or (match-string 7 s) "0")))
13682 (string-to-number (match-string 4 s))
13683 (string-to-number (match-string 3 s))
13684 (string-to-number (match-string 2 s))
13685 nil nil nil)
13686 (error "Not a standard Org-mode time string: %s" s)))
13688 (defun org-timestamp-up (&optional arg)
13689 "Increase the date item at the cursor by one.
13690 If the cursor is on the year, change the year. If it is on the month or
13691 the day, change that.
13692 With prefix ARG, change by that many units."
13693 (interactive "p")
13694 (org-timestamp-change (prefix-numeric-value arg)))
13696 (defun org-timestamp-down (&optional arg)
13697 "Decrease the date item at the cursor by one.
13698 If the cursor is on the year, change the year. If it is on the month or
13699 the day, change that.
13700 With prefix ARG, change by that many units."
13701 (interactive "p")
13702 (org-timestamp-change (- (prefix-numeric-value arg))))
13704 (defun org-timestamp-up-day (&optional arg)
13705 "Increase the date in the time stamp by one day.
13706 With prefix ARG, change that many days."
13707 (interactive "p")
13708 (if (and (not (org-at-timestamp-p t))
13709 (org-on-heading-p))
13710 (org-todo 'up)
13711 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13713 (defun org-timestamp-down-day (&optional arg)
13714 "Decrease the date in the time stamp by one day.
13715 With prefix ARG, change that many days."
13716 (interactive "p")
13717 (if (and (not (org-at-timestamp-p t))
13718 (org-on-heading-p))
13719 (org-todo 'down)
13720 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13722 (defun org-at-timestamp-p (&optional inactive-ok)
13723 "Determine if the cursor is in or at a timestamp."
13724 (interactive)
13725 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13726 (pos (point))
13727 (ans (or (looking-at tsr)
13728 (save-excursion
13729 (skip-chars-backward "^[<\n\r\t")
13730 (if (> (point) (point-min)) (backward-char 1))
13731 (and (looking-at tsr)
13732 (> (- (match-end 0) pos) -1))))))
13733 (and ans
13734 (boundp 'org-ts-what)
13735 (setq org-ts-what
13736 (cond
13737 ((= pos (match-beginning 0)) 'bracket)
13738 ((= pos (1- (match-end 0))) 'bracket)
13739 ((org-pos-in-match-range pos 2) 'year)
13740 ((org-pos-in-match-range pos 3) 'month)
13741 ((org-pos-in-match-range pos 7) 'hour)
13742 ((org-pos-in-match-range pos 8) 'minute)
13743 ((or (org-pos-in-match-range pos 4)
13744 (org-pos-in-match-range pos 5)) 'day)
13745 ((and (> pos (or (match-end 8) (match-end 5)))
13746 (< pos (match-end 0)))
13747 (- pos (or (match-end 8) (match-end 5))))
13748 (t 'day))))
13749 ans))
13751 (defun org-toggle-timestamp-type ()
13752 "Toggle the type (<active> or [inactive]) of a time stamp."
13753 (interactive)
13754 (when (org-at-timestamp-p t)
13755 (let ((beg (match-beginning 0)) (end (match-end 0))
13756 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13757 (save-excursion
13758 (goto-char beg)
13759 (while (re-search-forward "[][<>]" end t)
13760 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13761 t t)))
13762 (message "Timestamp is now %sactive"
13763 (if (equal (char-after beg) ?<) "" "in")))))
13765 (defun org-timestamp-change (n &optional what)
13766 "Change the date in the time stamp at point.
13767 The date will be changed by N times WHAT. WHAT can be `day', `month',
13768 `year', `minute', `second'. If WHAT is not given, the cursor position
13769 in the timestamp determines what will be changed."
13770 (let ((pos (point))
13771 with-hm inactive
13772 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13773 org-ts-what
13774 extra rem
13775 ts time time0)
13776 (if (not (org-at-timestamp-p t))
13777 (error "Not at a timestamp"))
13778 (if (and (not what) (eq org-ts-what 'bracket))
13779 (org-toggle-timestamp-type)
13780 (if (and (not what) (not (eq org-ts-what 'day))
13781 org-display-custom-times
13782 (get-text-property (point) 'display)
13783 (not (get-text-property (1- (point)) 'display)))
13784 (setq org-ts-what 'day))
13785 (setq org-ts-what (or what org-ts-what)
13786 inactive (= (char-after (match-beginning 0)) ?\[)
13787 ts (match-string 0))
13788 (replace-match "")
13789 (if (string-match
13790 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
13792 (setq extra (match-string 1 ts)))
13793 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13794 (setq with-hm t))
13795 (setq time0 (org-parse-time-string ts))
13796 (when (and (eq org-ts-what 'minute)
13797 (eq current-prefix-arg nil))
13798 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13799 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13800 (setcar (cdr time0) (+ (nth 1 time0)
13801 (if (> n 0) (- rem) (- dm rem))))))
13802 (setq time
13803 (encode-time (or (car time0) 0)
13804 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13805 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13806 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13807 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13808 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13809 (nthcdr 6 time0)))
13810 (when (and (member org-ts-what '(hour minute))
13811 extra
13812 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13813 (setq extra (org-modify-ts-extra
13814 extra
13815 (if (eq org-ts-what 'hour) 2 5)
13816 n dm)))
13817 (when (integerp org-ts-what)
13818 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13819 (if (eq what 'calendar)
13820 (let ((cal-date (org-get-date-from-calendar)))
13821 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13822 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13823 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13824 (setcar time0 (or (car time0) 0))
13825 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13826 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13827 (setq time (apply 'encode-time time0))))
13828 (setq org-last-changed-timestamp
13829 (org-insert-time-stamp time with-hm inactive nil nil extra))
13830 (org-clock-update-time-maybe)
13831 (goto-char pos)
13832 ;; Try to recenter the calendar window, if any
13833 (if (and org-calendar-follow-timestamp-change
13834 (get-buffer-window "*Calendar*" t)
13835 (memq org-ts-what '(day month year)))
13836 (org-recenter-calendar (time-to-days time))))))
13838 (defun org-modify-ts-extra (s pos n dm)
13839 "Change the different parts of the lead-time and repeat fields in timestamp."
13840 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13841 ng h m new rem)
13842 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13843 (cond
13844 ((or (org-pos-in-match-range pos 2)
13845 (org-pos-in-match-range pos 3))
13846 (setq m (string-to-number (match-string 3 s))
13847 h (string-to-number (match-string 2 s)))
13848 (if (org-pos-in-match-range pos 2)
13849 (setq h (+ h n))
13850 (setq n (* dm (org-no-warnings (signum n))))
13851 (when (not (= 0 (setq rem (% m dm))))
13852 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13853 (setq m (+ m n)))
13854 (if (< m 0) (setq m (+ m 60) h (1- h)))
13855 (if (> m 59) (setq m (- m 60) h (1+ h)))
13856 (setq h (min 24 (max 0 h)))
13857 (setq ng 1 new (format "-%02d:%02d" h m)))
13858 ((org-pos-in-match-range pos 6)
13859 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13860 ((org-pos-in-match-range pos 5)
13861 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13863 ((org-pos-in-match-range pos 9)
13864 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13865 ((org-pos-in-match-range pos 8)
13866 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13868 (when ng
13869 (setq s (concat
13870 (substring s 0 (match-beginning ng))
13872 (substring s (match-end ng))))))
13875 (defun org-recenter-calendar (date)
13876 "If the calendar is visible, recenter it to DATE."
13877 (let* ((win (selected-window))
13878 (cwin (get-buffer-window "*Calendar*" t))
13879 (calendar-move-hook nil))
13880 (when cwin
13881 (select-window cwin)
13882 (calendar-goto-date (if (listp date) date
13883 (calendar-gregorian-from-absolute date)))
13884 (select-window win))))
13886 (defun org-goto-calendar (&optional arg)
13887 "Go to the Emacs calendar at the current date.
13888 If there is a time stamp in the current line, go to that date.
13889 A prefix ARG can be used to force the current date."
13890 (interactive "P")
13891 (let ((tsr org-ts-regexp) diff
13892 (calendar-move-hook nil)
13893 (calendar-view-holidays-initially-flag nil)
13894 (view-calendar-holidays-initially nil)
13895 (calendar-view-diary-initially-flag nil)
13896 (view-diary-entries-initially nil))
13897 (if (or (org-at-timestamp-p)
13898 (save-excursion
13899 (beginning-of-line 1)
13900 (looking-at (concat ".*" tsr))))
13901 (let ((d1 (time-to-days (current-time)))
13902 (d2 (time-to-days
13903 (org-time-string-to-time (match-string 1)))))
13904 (setq diff (- d2 d1))))
13905 (calendar)
13906 (calendar-goto-today)
13907 (if (and diff (not arg)) (calendar-forward-day diff))))
13909 (defun org-get-date-from-calendar ()
13910 "Return a list (month day year) of date at point in calendar."
13911 (with-current-buffer "*Calendar*"
13912 (save-match-data
13913 (calendar-cursor-to-date))))
13915 (defun org-date-from-calendar ()
13916 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13917 If there is already a time stamp at the cursor position, update it."
13918 (interactive)
13919 (if (org-at-timestamp-p t)
13920 (org-timestamp-change 0 'calendar)
13921 (let ((cal-date (org-get-date-from-calendar)))
13922 (org-insert-time-stamp
13923 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13925 (defun org-minutes-to-hh:mm-string (m)
13926 "Compute H:MM from a number of minutes."
13927 (let ((h (/ m 60)))
13928 (setq m (- m (* 60 h)))
13929 (format org-time-clocksum-format h m)))
13931 (defun org-hh:mm-string-to-minutes (s)
13932 "Convert a string H:MM to a number of minutes.
13933 If the string is just a number, interprete it as minutes.
13934 In fact, the first hh:mm or number in the string will be taken,
13935 there can be extra stuff in the string.
13936 If no number is found, the return value is 0."
13937 (cond
13938 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13939 (+ (* (string-to-number (match-string 1 s)) 60)
13940 (string-to-number (match-string 2 s))))
13941 ((string-match "\\([0-9]+\\)" s)
13942 (string-to-number (match-string 1 s)))
13943 (t 0)))
13945 ;;;; Files
13947 (defun org-save-all-org-buffers ()
13948 "Save all Org-mode buffers without user confirmation."
13949 (interactive)
13950 (message "Saving all Org-mode buffers...")
13951 (save-some-buffers t 'org-mode-p)
13952 (when (featurep 'org-id) (org-id-locations-save))
13953 (message "Saving all Org-mode buffers... done"))
13955 (defun org-revert-all-org-buffers ()
13956 "Revert all Org-mode buffers.
13957 Prompt for confirmation when there are unsaved changes.
13958 Be sure you know what you are doing before letting this function
13959 overwrite your changes.
13961 This function is useful in a setup where one tracks org files
13962 with a version control system, to revert on one machine after pulling
13963 changes from another. I believe the procedure must be like this:
13965 1. M-x org-save-all-org-buffers
13966 2. Pull changes from the other machine, resolve conflicts
13967 3. M-x org-revert-all-org-buffers"
13968 (interactive)
13969 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13970 (error "Abort"))
13971 (save-excursion
13972 (save-window-excursion
13973 (mapc
13974 (lambda (b)
13975 (when (and (with-current-buffer b (org-mode-p))
13976 (with-current-buffer b buffer-file-name))
13977 (switch-to-buffer b)
13978 (revert-buffer t 'no-confirm)))
13979 (buffer-list))
13980 (when (and (featurep 'org-id) org-id-track-globally)
13981 (org-id-locations-load)))))
13983 ;;;; Agenda files
13985 ;;;###autoload
13986 (defun org-iswitchb (&optional arg)
13987 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
13988 With a prefix argument, restrict available to files.
13989 With two prefix arguments, restrict available buffers to agenda files."
13990 (interactive "P")
13991 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13992 ((equal arg '(16)) (org-buffer-list 'agenda))
13993 (t (org-buffer-list)))))
13994 (switch-to-buffer
13995 (org-icompleting-read "Org buffer: "
13996 (mapcar 'list (mapcar 'buffer-name blist))
13997 nil t))))
13999 ;;;###autoload
14000 (defalias 'org-ido-switchb 'org-iswitchb)
14002 (defun org-buffer-list (&optional predicate exclude-tmp)
14003 "Return a list of Org buffers.
14004 PREDICATE can be `export', `files' or `agenda'.
14006 export restrict the list to Export buffers.
14007 files restrict the list to buffers visiting Org files.
14008 agenda restrict the list to buffers visiting agenda files.
14010 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14011 (let* ((bfn nil)
14012 (agenda-files (and (eq predicate 'agenda)
14013 (mapcar 'file-truename (org-agenda-files t))))
14014 (filter
14015 (cond
14016 ((eq predicate 'files)
14017 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14018 ((eq predicate 'export)
14019 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14020 ((eq predicate 'agenda)
14021 (lambda (b)
14022 (with-current-buffer b
14023 (and (eq major-mode 'org-mode)
14024 (setq bfn (buffer-file-name b))
14025 (member (file-truename bfn) agenda-files)))))
14026 (t (lambda (b) (with-current-buffer b
14027 (or (eq major-mode 'org-mode)
14028 (string-match "\*Org .*Export"
14029 (buffer-name b)))))))))
14030 (delq nil
14031 (mapcar
14032 (lambda(b)
14033 (if (and (funcall filter b)
14034 (or (not exclude-tmp)
14035 (not (string-match "tmp" (buffer-name b)))))
14037 nil))
14038 (buffer-list)))))
14040 (defun org-agenda-files (&optional unrestricted archives)
14041 "Get the list of agenda files.
14042 Optional UNRESTRICTED means return the full list even if a restriction
14043 is currently in place.
14044 When ARCHIVES is t, include all archive files hat are really being
14045 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14046 `org-agenda-archives-mode' is t."
14047 (let ((files
14048 (cond
14049 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14050 ((stringp org-agenda-files) (org-read-agenda-file-list))
14051 ((listp org-agenda-files) org-agenda-files)
14052 (t (error "Invalid value of `org-agenda-files'")))))
14053 (setq files (apply 'append
14054 (mapcar (lambda (f)
14055 (if (file-directory-p f)
14056 (directory-files
14057 f t org-agenda-file-regexp)
14058 (list f)))
14059 files)))
14060 (when org-agenda-skip-unavailable-files
14061 (setq files (delq nil
14062 (mapcar (function
14063 (lambda (file)
14064 (and (file-readable-p file) file)))
14065 files))))
14066 (when (or (eq archives t)
14067 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14068 (setq files (org-add-archive-files files)))
14069 files))
14071 (defun org-edit-agenda-file-list ()
14072 "Edit the list of agenda files.
14073 Depending on setup, this either uses customize to edit the variable
14074 `org-agenda-files', or it visits the file that is holding the list. In the
14075 latter case, the buffer is set up in a way that saving it automatically kills
14076 the buffer and restores the previous window configuration."
14077 (interactive)
14078 (if (stringp org-agenda-files)
14079 (let ((cw (current-window-configuration)))
14080 (find-file org-agenda-files)
14081 (org-set-local 'org-window-configuration cw)
14082 (org-add-hook 'after-save-hook
14083 (lambda ()
14084 (set-window-configuration
14085 (prog1 org-window-configuration
14086 (kill-buffer (current-buffer))))
14087 (org-install-agenda-files-menu)
14088 (message "New agenda file list installed"))
14089 nil 'local)
14090 (message "%s" (substitute-command-keys
14091 "Edit list and finish with \\[save-buffer]")))
14092 (customize-variable 'org-agenda-files)))
14094 (defun org-store-new-agenda-file-list (list)
14095 "Set new value for the agenda file list and save it correctly."
14096 (if (stringp org-agenda-files)
14097 (let ((f org-agenda-files) b)
14098 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14099 (with-temp-file f
14100 (insert (mapconcat 'identity list "\n") "\n")))
14101 (let ((org-mode-hook nil) (org-inhibit-startup t)
14102 (org-insert-mode-line-in-empty-file nil))
14103 (setq org-agenda-files list)
14104 (customize-save-variable 'org-agenda-files org-agenda-files))))
14106 (defun org-read-agenda-file-list ()
14107 "Read the list of agenda files from a file."
14108 (when (file-directory-p org-agenda-files)
14109 (error "`org-agenda-files' cannot be a single directory"))
14110 (when (stringp org-agenda-files)
14111 (with-temp-buffer
14112 (insert-file-contents org-agenda-files)
14113 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14116 ;;;###autoload
14117 (defun org-cycle-agenda-files ()
14118 "Cycle through the files in `org-agenda-files'.
14119 If the current buffer visits an agenda file, find the next one in the list.
14120 If the current buffer does not, find the first agenda file."
14121 (interactive)
14122 (let* ((fs (org-agenda-files t))
14123 (files (append fs (list (car fs))))
14124 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14125 file)
14126 (unless files (error "No agenda files"))
14127 (catch 'exit
14128 (while (setq file (pop files))
14129 (if (equal (file-truename file) tcf)
14130 (when (car files)
14131 (find-file (car files))
14132 (throw 'exit t))))
14133 (find-file (car fs)))
14134 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14136 (defun org-agenda-file-to-front (&optional to-end)
14137 "Move/add the current file to the top of the agenda file list.
14138 If the file is not present in the list, it is added to the front. If it is
14139 present, it is moved there. With optional argument TO-END, add/move to the
14140 end of the list."
14141 (interactive "P")
14142 (let ((org-agenda-skip-unavailable-files nil)
14143 (file-alist (mapcar (lambda (x)
14144 (cons (file-truename x) x))
14145 (org-agenda-files t)))
14146 (ctf (file-truename buffer-file-name))
14147 x had)
14148 (setq x (assoc ctf file-alist) had x)
14150 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14151 (if to-end
14152 (setq file-alist (append (delq x file-alist) (list x)))
14153 (setq file-alist (cons x (delq x file-alist))))
14154 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14155 (org-install-agenda-files-menu)
14156 (message "File %s to %s of agenda file list"
14157 (if had "moved" "added") (if to-end "end" "front"))))
14159 (defun org-remove-file (&optional file)
14160 "Remove current file from the list of files in variable `org-agenda-files'.
14161 These are the files which are being checked for agenda entries.
14162 Optional argument FILE means, use this file instead of the current."
14163 (interactive)
14164 (let* ((org-agenda-skip-unavailable-files nil)
14165 (file (or file buffer-file-name))
14166 (true-file (file-truename file))
14167 (afile (abbreviate-file-name file))
14168 (files (delq nil (mapcar
14169 (lambda (x)
14170 (if (equal true-file
14171 (file-truename x))
14172 nil x))
14173 (org-agenda-files t)))))
14174 (if (not (= (length files) (length (org-agenda-files t))))
14175 (progn
14176 (org-store-new-agenda-file-list files)
14177 (org-install-agenda-files-menu)
14178 (message "Removed file: %s" afile))
14179 (message "File was not in list: %s (not removed)" afile))))
14181 (defun org-file-menu-entry (file)
14182 (vector file (list 'find-file file) t))
14184 (defun org-check-agenda-file (file)
14185 "Make sure FILE exists. If not, ask user what to do."
14186 (when (not (file-exists-p file))
14187 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14188 (abbreviate-file-name file))
14189 (let ((r (downcase (read-char-exclusive))))
14190 (cond
14191 ((equal r ?r)
14192 (org-remove-file file)
14193 (throw 'nextfile t))
14194 (t (error "Abort"))))))
14196 (defun org-get-agenda-file-buffer (file)
14197 "Get a buffer visiting FILE. If the buffer needs to be created, add
14198 it to the list of buffers which might be released later."
14199 (let ((buf (org-find-base-buffer-visiting file)))
14200 (if buf
14201 buf ; just return it
14202 ;; Make a new buffer and remember it
14203 (setq buf (find-file-noselect file))
14204 (if buf (push buf org-agenda-new-buffers))
14205 buf)))
14207 (defun org-release-buffers (blist)
14208 "Release all buffers in list, asking the user for confirmation when needed.
14209 When a buffer is unmodified, it is just killed. When modified, it is saved
14210 \(if the user agrees) and then killed."
14211 (let (buf file)
14212 (while (setq buf (pop blist))
14213 (setq file (buffer-file-name buf))
14214 (when (and (buffer-modified-p buf)
14215 file
14216 (y-or-n-p (format "Save file %s? " file)))
14217 (with-current-buffer buf (save-buffer)))
14218 (kill-buffer buf))))
14220 (defun org-prepare-agenda-buffers (files)
14221 "Create buffers for all agenda files, protect archived trees and comments."
14222 (interactive)
14223 (let ((pa '(:org-archived t))
14224 (pc '(:org-comment t))
14225 (pall '(:org-archived t :org-comment t))
14226 (inhibit-read-only t)
14227 (rea (concat ":" org-archive-tag ":"))
14228 bmp file re)
14229 (save-excursion
14230 (save-restriction
14231 (while (setq file (pop files))
14232 (catch 'nextfile
14233 (if (bufferp file)
14234 (set-buffer file)
14235 (org-check-agenda-file file)
14236 (set-buffer (org-get-agenda-file-buffer file)))
14237 (widen)
14238 (setq bmp (buffer-modified-p))
14239 (org-refresh-category-properties)
14240 (setq org-todo-keywords-for-agenda
14241 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14242 (setq org-done-keywords-for-agenda
14243 (append org-done-keywords-for-agenda org-done-keywords))
14244 (setq org-todo-keyword-alist-for-agenda
14245 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14246 (setq org-drawers-for-agenda
14247 (append org-drawers-for-agenda org-drawers))
14248 (setq org-tag-alist-for-agenda
14249 (append org-tag-alist-for-agenda org-tag-alist))
14251 (save-excursion
14252 (remove-text-properties (point-min) (point-max) pall)
14253 (when org-agenda-skip-archived-trees
14254 (goto-char (point-min))
14255 (while (re-search-forward rea nil t)
14256 (if (org-on-heading-p t)
14257 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14258 (goto-char (point-min))
14259 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14260 (while (re-search-forward re nil t)
14261 (add-text-properties
14262 (match-beginning 0) (org-end-of-subtree t) pc)))
14263 (set-buffer-modified-p bmp)))))
14264 (setq org-todo-keyword-alist-for-agenda
14265 (org-uniquify org-todo-keyword-alist-for-agenda)
14266 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14268 ;;;; Embedded LaTeX
14270 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14271 "Keymap for the minor `org-cdlatex-mode'.")
14273 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14274 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14275 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14276 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14277 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14279 (defvar org-cdlatex-texmathp-advice-is-done nil
14280 "Flag remembering if we have applied the advice to texmathp already.")
14282 (define-minor-mode org-cdlatex-mode
14283 "Toggle the minor `org-cdlatex-mode'.
14284 This mode supports entering LaTeX environment and math in LaTeX fragments
14285 in Org-mode.
14286 \\{org-cdlatex-mode-map}"
14287 nil " OCDL" nil
14288 (when org-cdlatex-mode (require 'cdlatex))
14289 (unless org-cdlatex-texmathp-advice-is-done
14290 (setq org-cdlatex-texmathp-advice-is-done t)
14291 (defadvice texmathp (around org-math-always-on activate)
14292 "Always return t in org-mode buffers.
14293 This is because we want to insert math symbols without dollars even outside
14294 the LaTeX math segments. If Orgmode thinks that point is actually inside
14295 an embedded LaTeX fragment, let texmathp do its job.
14296 \\[org-cdlatex-mode-map]"
14297 (interactive)
14298 (let (p)
14299 (cond
14300 ((not (org-mode-p)) ad-do-it)
14301 ((eq this-command 'cdlatex-math-symbol)
14302 (setq ad-return-value t
14303 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14305 (let ((p (org-inside-LaTeX-fragment-p)))
14306 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14307 (setq ad-return-value t
14308 texmathp-why '("Org-mode embedded math" . 0))
14309 (if p ad-do-it)))))))))
14311 (defun turn-on-org-cdlatex ()
14312 "Unconditionally turn on `org-cdlatex-mode'."
14313 (org-cdlatex-mode 1))
14315 (defun org-inside-LaTeX-fragment-p ()
14316 "Test if point is inside a LaTeX fragment.
14317 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14318 sequence appearing also before point.
14319 Even though the matchers for math are configurable, this function assumes
14320 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14321 delimiters are skipped when they have been removed by customization.
14322 The return value is nil, or a cons cell with the delimiter and
14323 and the position of this delimiter.
14325 This function does a reasonably good job, but can locally be fooled by
14326 for example currency specifications. For example it will assume being in
14327 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14328 fragments that are properly closed, but during editing, we have to live
14329 with the uncertainty caused by missing closing delimiters. This function
14330 looks only before point, not after."
14331 (catch 'exit
14332 (let ((pos (point))
14333 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14334 (lim (progn
14335 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14336 (point)))
14337 dd-on str (start 0) m re)
14338 (goto-char pos)
14339 (when dodollar
14340 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14341 re (nth 1 (assoc "$" org-latex-regexps)))
14342 (while (string-match re str start)
14343 (cond
14344 ((= (match-end 0) (length str))
14345 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14346 ((= (match-end 0) (- (length str) 5))
14347 (throw 'exit nil))
14348 (t (setq start (match-end 0))))))
14349 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14350 (goto-char pos)
14351 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14352 (and (match-beginning 2) (throw 'exit nil))
14353 ;; count $$
14354 (while (re-search-backward "\\$\\$" lim t)
14355 (setq dd-on (not dd-on)))
14356 (goto-char pos)
14357 (if dd-on (cons "$$" m))))))
14360 (defun org-try-cdlatex-tab ()
14361 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14362 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14363 - inside a LaTeX fragment, or
14364 - after the first word in a line, where an abbreviation expansion could
14365 insert a LaTeX environment."
14366 (when org-cdlatex-mode
14367 (cond
14368 ((save-excursion
14369 (skip-chars-backward "a-zA-Z0-9*")
14370 (skip-chars-backward " \t")
14371 (bolp))
14372 (cdlatex-tab) t)
14373 ((org-inside-LaTeX-fragment-p)
14374 (cdlatex-tab) t)
14375 (t nil))))
14377 (defun org-cdlatex-underscore-caret (&optional arg)
14378 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14379 Revert to the normal definition outside of these fragments."
14380 (interactive "P")
14381 (if (org-inside-LaTeX-fragment-p)
14382 (call-interactively 'cdlatex-sub-superscript)
14383 (let (org-cdlatex-mode)
14384 (call-interactively (key-binding (vector last-input-event))))))
14386 (defun org-cdlatex-math-modify (&optional arg)
14387 "Execute `cdlatex-math-modify' in LaTeX fragments.
14388 Revert to the normal definition outside of these fragments."
14389 (interactive "P")
14390 (if (org-inside-LaTeX-fragment-p)
14391 (call-interactively 'cdlatex-math-modify)
14392 (let (org-cdlatex-mode)
14393 (call-interactively (key-binding (vector last-input-event))))))
14395 (defvar org-latex-fragment-image-overlays nil
14396 "List of overlays carrying the images of latex fragments.")
14397 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14399 (defun org-remove-latex-fragment-image-overlays ()
14400 "Remove all overlays with LaTeX fragment images in current buffer."
14401 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14402 (setq org-latex-fragment-image-overlays nil))
14404 (defun org-preview-latex-fragment (&optional subtree)
14405 "Preview the LaTeX fragment at point, or all locally or globally.
14406 If the cursor is in a LaTeX fragment, create the image and overlay
14407 it over the source code. If there is no fragment at point, display
14408 all fragments in the current text, from one headline to the next. With
14409 prefix SUBTREE, display all fragments in the current subtree. With a
14410 double prefix `C-u C-u', or when the cursor is before the first headline,
14411 display all fragments in the buffer.
14412 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14413 (interactive "P")
14414 (org-remove-latex-fragment-image-overlays)
14415 (save-excursion
14416 (save-restriction
14417 (let (beg end at msg)
14418 (cond
14419 ((or (equal subtree '(16))
14420 (not (save-excursion
14421 (re-search-backward (concat "^" outline-regexp) nil t))))
14422 (setq beg (point-min) end (point-max)
14423 msg "Creating images for buffer...%s"))
14424 ((equal subtree '(4))
14425 (org-back-to-heading)
14426 (setq beg (point) end (org-end-of-subtree t)
14427 msg "Creating images for subtree...%s"))
14429 (if (setq at (org-inside-LaTeX-fragment-p))
14430 (goto-char (max (point-min) (- (cdr at) 2)))
14431 (org-back-to-heading))
14432 (setq beg (point) end (progn (outline-next-heading) (point))
14433 msg (if at "Creating image...%s"
14434 "Creating images for entry...%s"))))
14435 (message msg "")
14436 (narrow-to-region beg end)
14437 (goto-char beg)
14438 (org-format-latex
14439 (concat "ltxpng/" (file-name-sans-extension
14440 (file-name-nondirectory
14441 buffer-file-name)))
14442 default-directory 'overlays msg at 'forbuffer)
14443 (message msg "done. Use `C-c C-c' to remove images.")))))
14445 (defvar org-latex-regexps
14446 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14447 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14448 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14449 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14450 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14451 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14452 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14453 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14454 "Regular expressions for matching embedded LaTeX.")
14456 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14457 "Replace LaTeX fragments with links to an image, and produce images.
14458 Some of the options can be changed using the variable
14459 `org-format-latex-options'."
14460 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14461 (let* ((prefixnodir (file-name-nondirectory prefix))
14462 (absprefix (expand-file-name prefix dir))
14463 (todir (file-name-directory absprefix))
14464 (opt org-format-latex-options)
14465 (matchers (plist-get opt :matchers))
14466 (re-list org-latex-regexps)
14467 (cnt 0) txt link beg end re e checkdir
14468 executables-checked
14469 m n block linkfile movefile ov)
14470 ;; Check if there are old images files with this prefix, and remove them
14471 (when (file-directory-p todir)
14472 (mapc 'delete-file
14473 (directory-files
14474 todir 'full
14475 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
14476 ;; Check the different regular expressions
14477 (while (setq e (pop re-list))
14478 (setq m (car e) re (nth 1 e) n (nth 2 e)
14479 block (if (nth 3 e) "\n\n" ""))
14480 (when (member m matchers)
14481 (goto-char (point-min))
14482 (while (re-search-forward re nil t)
14483 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14484 (not (get-text-property (match-beginning n)
14485 'org-protected))
14486 (or (not overlays)
14487 (not (eq (get-char-property (match-beginning n)
14488 'org-overlay-type)
14489 'org-latex-overlay))))
14490 (setq txt (match-string n)
14491 beg (match-beginning n) end (match-end n)
14492 cnt (1+ cnt)
14493 linkfile (format "%s_%04d.png" prefix cnt)
14494 movefile (format "%s_%04d.png" absprefix cnt)
14495 link (concat block "[[file:" linkfile "]]" block))
14496 (if msg (message msg cnt))
14497 (goto-char beg)
14498 (unless checkdir ; make sure the directory exists
14499 (setq checkdir t)
14500 (or (file-directory-p todir) (make-directory todir)))
14502 (unless executables-checked
14503 (org-check-external-command
14504 "latex" "needed to convert LaTeX fragments to images")
14505 (org-check-external-command
14506 "dvipng" "needed to convert LaTeX fragments to images")
14507 (setq executables-checked t))
14509 (org-create-formula-image
14510 txt movefile opt forbuffer)
14511 (if overlays
14512 (progn
14513 (mapc (lambda (o)
14514 (if (eq (org-overlay-get o 'org-overlay-type)
14515 'org-latex-overlay)
14516 (org-delete-overlay o)))
14517 (org-overlays-in beg end))
14518 (setq ov (org-make-overlay beg end))
14519 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14520 (if (featurep 'xemacs)
14521 (progn
14522 (org-overlay-put ov 'invisible t)
14523 (org-overlay-put
14524 ov 'end-glyph
14525 (make-glyph (vector 'png :file movefile))))
14526 (org-overlay-put
14527 ov 'display
14528 (list 'image :type 'png :file movefile :ascent 'center)))
14529 (push ov org-latex-fragment-image-overlays)
14530 (goto-char end))
14531 (delete-region beg end)
14532 (insert link))))))))
14534 (defvar org-export-latex-packages-alist) ;; defined in org-latex.el
14535 ;; This function borrows from Ganesh Swami's latex2png.el
14536 (defun org-create-formula-image (string tofile options buffer)
14537 "This calls dvipng."
14538 (require 'org-latex)
14539 (let* ((tmpdir (if (featurep 'xemacs)
14540 (temp-directory)
14541 temporary-file-directory))
14542 (texfilebase (make-temp-name
14543 (expand-file-name "orgtex" tmpdir)))
14544 (texfile (concat texfilebase ".tex"))
14545 (dvifile (concat texfilebase ".dvi"))
14546 (pngfile (concat texfilebase ".png"))
14547 (fnh (if (featurep 'xemacs)
14548 (font-height (get-face-font 'default))
14549 (face-attribute 'default :height nil)))
14550 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14551 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14552 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14553 "Black"))
14554 (bg (or (plist-get options (if buffer :background :html-background))
14555 "Transparent")))
14556 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14557 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14558 (with-temp-file texfile
14559 (insert org-format-latex-header
14560 (if org-export-latex-packages-alist
14561 (concat "\n"
14562 (mapconcat (lambda(p)
14563 (if (equal "" (car p))
14564 (format "\\usepackage{%s}" (cadr p))
14565 (format "\\usepackage[%s]{%s}"
14566 (car p) (cadr p))))
14567 org-export-latex-packages-alist "\n"))
14569 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14570 (let ((dir default-directory))
14571 (condition-case nil
14572 (progn
14573 (cd tmpdir)
14574 (call-process "latex" nil nil nil texfile))
14575 (error nil))
14576 (cd dir))
14577 (if (not (file-exists-p dvifile))
14578 (progn (message "Failed to create dvi file from %s" texfile) nil)
14579 (condition-case nil
14580 (call-process "dvipng" nil nil nil
14581 "-fg" fg "-bg" bg
14582 "-D" dpi
14583 ;;"-x" scale "-y" scale
14584 "-T" "tight"
14585 "-o" pngfile
14586 dvifile)
14587 (error nil))
14588 (if (not (file-exists-p pngfile))
14589 (progn (message "Failed to create png file from %s" texfile) nil)
14590 ;; Use the requested file name and clean up
14591 (copy-file pngfile tofile 'replace)
14592 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14593 (delete-file (concat texfilebase e)))
14594 pngfile))))
14596 (defun org-dvipng-color (attr)
14597 "Return an rgb color specification for dvipng."
14598 (apply 'format "rgb %s %s %s"
14599 (mapcar 'org-normalize-color
14600 (color-values (face-attribute 'default attr nil)))))
14602 (defun org-normalize-color (value)
14603 "Return string to be used as color value for an RGB component."
14604 (format "%g" (/ value 65535.0)))
14606 ;;;; Key bindings
14608 ;; Make `C-c C-x' a prefix key
14609 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14611 ;; TAB key with modifiers
14612 (org-defkey org-mode-map "\C-i" 'org-cycle)
14613 (org-defkey org-mode-map [(tab)] 'org-cycle)
14614 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14615 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14616 (org-defkey org-mode-map "\M-\t" 'org-complete)
14617 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14618 ;; The following line is necessary under Suse GNU/Linux
14619 (unless (featurep 'xemacs)
14620 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14621 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14622 (define-key org-mode-map [backtab] 'org-shifttab)
14624 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14625 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14626 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14628 ;; Cursor keys with modifiers
14629 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14630 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14631 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14632 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14634 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14635 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14636 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14637 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14639 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14640 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14641 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14642 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14644 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14645 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14647 ;;; Extra keys for tty access.
14648 ;; We only set them when really needed because otherwise the
14649 ;; menus don't show the simple keys
14651 (when (or org-use-extra-keys
14652 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14653 (not window-system))
14654 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14655 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14656 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14657 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14658 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14659 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14660 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14661 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14662 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14663 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14664 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14665 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14666 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14667 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14668 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14669 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14670 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14671 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14672 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14673 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14674 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14675 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14676 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14677 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14678 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14679 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14680 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14681 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14683 ;; All the other keys
14685 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14686 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14687 (if (boundp 'narrow-map)
14688 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14689 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14690 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14691 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14692 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14693 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14694 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
14695 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14696 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14697 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14698 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14699 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14700 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14701 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14702 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14703 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14704 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14705 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14706 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14707 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14708 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14709 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14710 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14711 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14712 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14713 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14714 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14715 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14716 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14717 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14718 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14719 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14720 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14721 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14722 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14723 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14724 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14725 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14726 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14727 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14728 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14729 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14730 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14731 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14732 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14733 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14734 (org-defkey org-mode-map "\C-c^" 'org-sort)
14735 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14736 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14737 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
14738 (org-defkey org-mode-map "\C-m" 'org-return)
14739 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14740 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14741 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14742 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14743 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14744 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14745 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14746 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14747 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14748 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14749 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14750 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14751 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14752 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14753 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14754 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14755 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14756 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
14757 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
14758 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14759 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14761 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14762 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14763 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14764 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14766 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14767 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14768 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14769 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14770 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14771 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14772 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14773 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14774 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14775 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14776 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14777 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
14778 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14779 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14780 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14782 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14783 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14784 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14785 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14787 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14789 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14791 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14792 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14794 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14797 (when (featurep 'xemacs)
14798 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14801 (defconst org-speed-commands-default
14803 ("a" . org-agenda)
14804 ("/" . org-sparse-tree)
14805 (";" . org-set-tags-command)
14806 ("I" . org-clock-in)
14807 ("O" . org-clock-out)
14808 ("c" . org-cycle)
14809 ("C" . org-shifttab)
14810 ("n" . outline-next-visible-heading)
14811 ("p" . outline-previous-visible-heading)
14812 ("f" . org-forward-same-level)
14813 ("b" . org-backward-same-level)
14814 ("u" . outline-up-heading)
14815 ("U" . org-shiftmetaup)
14816 ("D" . org-shiftmetadown)
14817 ("r" . org-metaright)
14818 ("l" . org-metaleft)
14819 ("R" . org-shiftmetaright)
14820 ("L" . org-shiftmetaleft)
14821 ("i" . (progn (forward-char 1) (call-interactively
14822 'org-insert-heading-respect-content)))
14823 ("o" . org-open-at-point)
14824 ("t" . org-todo)
14825 ("j" . org-goto)
14826 ("g" . (org-refile t))
14827 ("e" . org-set-effort)
14828 ("0" . (org-priority ?\ ))
14829 ("1" . (org-priority ?A))
14830 ("2" . (org-priority ?B))
14831 ("3" . (org-priority ?C))
14832 ("." . outline-mark-subtree)
14833 ("^" . org-sort)
14834 ("w" . org-refile)
14835 ("a" . org-archive-subtree-default-with-confirmation)
14836 ("/" . org-sparse-tree)
14837 ("?" . org-speed-command-help)
14839 "The default speed commands.")
14841 (defun org-print-speed-command (e)
14842 (princ (car e))
14843 (princ " ")
14844 (if (symbolp (cdr e))
14845 (princ (symbol-name (cdr e)))
14846 (prin1 (cdr e)))
14847 (princ "\n"))
14849 (defun org-speed-command-help ()
14850 "Show the available speed commands."
14851 (interactive)
14852 (if (not org-use-speed-commands)
14853 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
14854 (with-output-to-temp-buffer "*Help*"
14855 (princ "Speed commands\n==============\n")
14856 (mapc 'org-print-speed-command org-speed-commands-user)
14857 (princ "\n")
14858 (mapc 'org-print-speed-command org-speed-commands-default))))
14860 (defvar org-self-insert-command-undo-counter 0)
14862 (defvar org-table-auto-blank-field) ; defined in org-table.el
14863 (defvar org-speed-command nil)
14864 (defun org-self-insert-command (N)
14865 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14866 If the cursor is in a table looking at whitespace, the whitespace is
14867 overwritten, and the table is not marked as requiring realignment."
14868 (interactive "p")
14869 (cond
14870 ((and org-use-speed-commands
14871 (bolp)
14872 (looking-at outline-regexp)
14873 (setq
14874 org-speed-command
14875 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
14876 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
14877 (cond
14878 ((commandp org-speed-command)
14879 (setq this-command org-speed-command)
14880 (call-interactively org-speed-command))
14881 ((functionp org-speed-command)
14882 (funcall org-speed-command))
14883 ((and org-speed-command (listp org-speed-command))
14884 (eval org-speed-command))
14885 (t (let (org-use-speed-commands)
14886 (call-interactively 'org-self-insert-command)))))
14887 ((and
14888 (org-table-p)
14889 (progn
14890 ;; check if we blank the field, and if that triggers align
14891 (and (featurep 'org-table) org-table-auto-blank-field
14892 (member last-command
14893 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
14894 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14895 ;; got extra space, this field does not determine column width
14896 (let (org-table-may-need-update) (org-table-blank-field))
14897 ;; no extra space, this field may determine column width
14898 (org-table-blank-field)))
14900 (eq N 1)
14901 (looking-at "[^|\n]* |"))
14902 (let (org-table-may-need-update)
14903 (goto-char (1- (match-end 0)))
14904 (delete-backward-char 1)
14905 (goto-char (match-beginning 0))
14906 (self-insert-command N)))
14908 (setq org-table-may-need-update t)
14909 (self-insert-command N)
14910 (org-fix-tags-on-the-fly)
14911 (if org-self-insert-cluster-for-undo
14912 (if (not (eq last-command 'org-self-insert-command))
14913 (setq org-self-insert-command-undo-counter 1)
14914 (if (>= org-self-insert-command-undo-counter 20)
14915 (setq org-self-insert-command-undo-counter 1)
14916 (and (> org-self-insert-command-undo-counter 0)
14917 buffer-undo-list
14918 (not (cadr buffer-undo-list)) ; remove nil entry
14919 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14920 (setq org-self-insert-command-undo-counter
14921 (1+ org-self-insert-command-undo-counter))))))))
14923 (defun org-fix-tags-on-the-fly ()
14924 (when (and (equal (char-after (point-at-bol)) ?*)
14925 (org-on-heading-p))
14926 (org-align-tags-here org-tags-column)))
14928 (defun org-delete-backward-char (N)
14929 "Like `delete-backward-char', insert whitespace at field end in tables.
14930 When deleting backwards, in tables this function will insert whitespace in
14931 front of the next \"|\" separator, to keep the table aligned. The table will
14932 still be marked for re-alignment if the field did fill the entire column,
14933 because, in this case the deletion might narrow the column."
14934 (interactive "p")
14935 (if (and (org-table-p)
14936 (eq N 1)
14937 (string-match "|" (buffer-substring (point-at-bol) (point)))
14938 (looking-at ".*?|"))
14939 (let ((pos (point))
14940 (noalign (looking-at "[^|\n\r]* |"))
14941 (c org-table-may-need-update))
14942 (backward-delete-char N)
14943 (skip-chars-forward "^|")
14944 (insert " ")
14945 (goto-char (1- pos))
14946 ;; noalign: if there were two spaces at the end, this field
14947 ;; does not determine the width of the column.
14948 (if noalign (setq org-table-may-need-update c)))
14949 (backward-delete-char N)
14950 (org-fix-tags-on-the-fly)))
14952 (defun org-delete-char (N)
14953 "Like `delete-char', but insert whitespace at field end in tables.
14954 When deleting characters, in tables this function will insert whitespace in
14955 front of the next \"|\" separator, to keep the table aligned. The table will
14956 still be marked for re-alignment if the field did fill the entire column,
14957 because, in this case the deletion might narrow the column."
14958 (interactive "p")
14959 (if (and (org-table-p)
14960 (not (bolp))
14961 (not (= (char-after) ?|))
14962 (eq N 1))
14963 (if (looking-at ".*?|")
14964 (let ((pos (point))
14965 (noalign (looking-at "[^|\n\r]* |"))
14966 (c org-table-may-need-update))
14967 (replace-match (concat
14968 (substring (match-string 0) 1 -1)
14969 " |"))
14970 (goto-char pos)
14971 ;; noalign: if there were two spaces at the end, this field
14972 ;; does not determine the width of the column.
14973 (if noalign (setq org-table-may-need-update c)))
14974 (delete-char N))
14975 (delete-char N)
14976 (org-fix-tags-on-the-fly)))
14978 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14979 (put 'org-self-insert-command 'delete-selection t)
14980 (put 'orgtbl-self-insert-command 'delete-selection t)
14981 (put 'org-delete-char 'delete-selection 'supersede)
14982 (put 'org-delete-backward-char 'delete-selection 'supersede)
14983 (put 'org-yank 'delete-selection 'yank)
14985 ;; Make `flyspell-mode' delay after some commands
14986 (put 'org-self-insert-command 'flyspell-delayed t)
14987 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14988 (put 'org-delete-char 'flyspell-delayed t)
14989 (put 'org-delete-backward-char 'flyspell-delayed t)
14991 ;; Make pabbrev-mode expand after org-mode commands
14992 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14993 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14995 ;; How to do this: Measure non-white length of current string
14996 ;; If equal to column width, we should realign.
14998 (defun org-remap (map &rest commands)
14999 "In MAP, remap the functions given in COMMANDS.
15000 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15001 (let (new old)
15002 (while commands
15003 (setq old (pop commands) new (pop commands))
15004 (if (fboundp 'command-remapping)
15005 (org-defkey map (vector 'remap old) new)
15006 (substitute-key-definition old new map global-map)))))
15008 (when (eq org-enable-table-editor 'optimized)
15009 ;; If the user wants maximum table support, we need to hijack
15010 ;; some standard editing functions
15011 (org-remap org-mode-map
15012 'self-insert-command 'org-self-insert-command
15013 'delete-char 'org-delete-char
15014 'delete-backward-char 'org-delete-backward-char)
15015 (org-defkey org-mode-map "|" 'org-force-self-insert))
15017 (defvar org-ctrl-c-ctrl-c-hook nil
15018 "Hook for functions attaching themselves to `C-c C-c'.
15019 This can be used to add additional functionality to the C-c C-c key which
15020 executes context-dependent commands.
15021 Each function will be called with no arguments. The function must check
15022 if the context is appropriate for it to act. If yes, it should do its
15023 thing and then return a non-nil value. If the context is wrong,
15024 just do nothing and return nil.")
15026 (defvar org-tab-first-hook nil
15027 "Hook for functions to attach themselves to TAB.
15028 See `org-ctrl-c-ctrl-c-hook' for more information.
15029 This hook runs as the first action when TAB is pressed, even before
15030 `org-cycle' messes around with the `outline-regexp' to cater for
15031 inline tasks and plain list item folding.
15032 If any function in this hook returns t, not other actions like table
15033 field motion visibility cycling will be done.")
15035 (defvar org-tab-after-check-for-table-hook nil
15036 "Hook for functions to attach themselves to TAB.
15037 See `org-ctrl-c-ctrl-c-hook' for more information.
15038 This hook runs after it has been established that the cursor is not in a
15039 table, but before checking if the cursor is in a headline or if global cycling
15040 should be done.
15041 If any function in this hook returns t, not other actions like visibility
15042 cycling will be done.")
15044 (defvar org-tab-after-check-for-cycling-hook nil
15045 "Hook for functions to attach themselves to TAB.
15046 See `org-ctrl-c-ctrl-c-hook' for more information.
15047 This hook runs after it has been established that not table field motion and
15048 not visibility should be done because of current context. This is probably
15049 the place where a package like yasnippets can hook in.")
15051 (defvar org-tab-before-tab-emulation-hook nil
15052 "Hook for functions to attach themselves to TAB.
15053 See `org-ctrl-c-ctrl-c-hook' for more information.
15054 This hook runs after every other options for TAB have been exhausted, but
15055 before indentation and \t insertion takes place.")
15057 (defvar org-metaleft-hook nil
15058 "Hook for functions attaching themselves to `M-left'.
15059 See `org-ctrl-c-ctrl-c-hook' for more information.")
15060 (defvar org-metaright-hook nil
15061 "Hook for functions attaching themselves to `M-right'.
15062 See `org-ctrl-c-ctrl-c-hook' for more information.")
15063 (defvar org-metaup-hook nil
15064 "Hook for functions attaching themselves to `M-up'.
15065 See `org-ctrl-c-ctrl-c-hook' for more information.")
15066 (defvar org-metadown-hook nil
15067 "Hook for functions attaching themselves to `M-down'.
15068 See `org-ctrl-c-ctrl-c-hook' for more information.")
15069 (defvar org-shiftmetaleft-hook nil
15070 "Hook for functions attaching themselves to `M-S-left'.
15071 See `org-ctrl-c-ctrl-c-hook' for more information.")
15072 (defvar org-shiftmetaright-hook nil
15073 "Hook for functions attaching themselves to `M-S-right'.
15074 See `org-ctrl-c-ctrl-c-hook' for more information.")
15075 (defvar org-shiftmetaup-hook nil
15076 "Hook for functions attaching themselves to `M-S-up'.
15077 See `org-ctrl-c-ctrl-c-hook' for more information.")
15078 (defvar org-shiftmetadown-hook nil
15079 "Hook for functions attaching themselves to `M-S-down'.
15080 See `org-ctrl-c-ctrl-c-hook' for more information.")
15081 (defvar org-metareturn-hook nil
15082 "Hook for functions attaching themselves to `M-RET'.
15083 See `org-ctrl-c-ctrl-c-hook' for more information.")
15085 (defun org-modifier-cursor-error ()
15086 "Throw an error, a modified cursor command was applied in wrong context."
15087 (error "This command is active in special context like tables, headlines or items"))
15089 (defun org-shiftselect-error ()
15090 "Throw an error because Shift-Cursor command was applied in wrong context."
15091 (if (and (boundp 'shift-select-mode) shift-select-mode)
15092 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15093 (error "This command works only in special context like headlines or timestamps")))
15095 (defun org-call-for-shift-select (cmd)
15096 (let ((this-command-keys-shift-translated t))
15097 (call-interactively cmd)))
15099 (defun org-shifttab (&optional arg)
15100 "Global visibility cycling or move to previous table field.
15101 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15102 on context.
15103 See the individual commands for more information."
15104 (interactive "P")
15105 (cond
15106 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15107 ((integerp arg)
15108 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15109 (message "Content view to level: %d" arg)
15110 (org-content (prefix-numeric-value arg2))
15111 (setq org-cycle-global-status 'overview)))
15112 (t (call-interactively 'org-global-cycle))))
15114 (defun org-shiftmetaleft ()
15115 "Promote subtree or delete table column.
15116 Calls `org-promote-subtree', `org-outdent-item',
15117 or `org-table-delete-column', depending on context.
15118 See the individual commands for more information."
15119 (interactive)
15120 (cond
15121 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15122 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15123 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15124 ((org-at-item-p) (call-interactively 'org-outdent-item))
15125 (t (org-modifier-cursor-error))))
15127 (defun org-shiftmetaright ()
15128 "Demote subtree or insert table column.
15129 Calls `org-demote-subtree', `org-indent-item',
15130 or `org-table-insert-column', depending on context.
15131 See the individual commands for more information."
15132 (interactive)
15133 (cond
15134 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15135 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15136 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15137 ((org-at-item-p) (call-interactively 'org-indent-item))
15138 (t (org-modifier-cursor-error))))
15140 (defun org-shiftmetaup (&optional arg)
15141 "Move subtree up or kill table row.
15142 Calls `org-move-subtree-up' or `org-table-kill-row' or
15143 `org-move-item-up' depending on context. See the individual commands
15144 for more information."
15145 (interactive "P")
15146 (cond
15147 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15148 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15149 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15150 ((org-at-item-p) (call-interactively 'org-move-item-up))
15151 (t (org-modifier-cursor-error))))
15153 (defun org-shiftmetadown (&optional arg)
15154 "Move subtree down or insert table row.
15155 Calls `org-move-subtree-down' or `org-table-insert-row' or
15156 `org-move-item-down', depending on context. See the individual
15157 commands for more information."
15158 (interactive "P")
15159 (cond
15160 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15161 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15162 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15163 ((org-at-item-p) (call-interactively 'org-move-item-down))
15164 (t (org-modifier-cursor-error))))
15166 (defun org-metaleft (&optional arg)
15167 "Promote heading or move table column to left.
15168 Calls `org-do-promote' or `org-table-move-column', depending on context.
15169 With no specific context, calls the Emacs default `backward-word'.
15170 See the individual commands for more information."
15171 (interactive "P")
15172 (cond
15173 ((run-hook-with-args-until-success 'org-metaleft-hook))
15174 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15175 ((or (org-on-heading-p)
15176 (and (org-region-active-p)
15177 (save-excursion
15178 (goto-char (region-beginning))
15179 (org-on-heading-p))))
15180 (call-interactively 'org-do-promote))
15181 ((or (org-at-item-p)
15182 (and (org-region-active-p)
15183 (save-excursion
15184 (goto-char (region-beginning))
15185 (org-at-item-p))))
15186 (call-interactively 'org-outdent-item))
15187 (t (call-interactively 'backward-word))))
15189 (defun org-metaright (&optional arg)
15190 "Demote subtree or move table column to right.
15191 Calls `org-do-demote' or `org-table-move-column', depending on context.
15192 With no specific context, calls the Emacs default `forward-word'.
15193 See the individual commands for more information."
15194 (interactive "P")
15195 (cond
15196 ((run-hook-with-args-until-success 'org-metaright-hook))
15197 ((org-at-table-p) (call-interactively 'org-table-move-column))
15198 ((or (org-on-heading-p)
15199 (and (org-region-active-p)
15200 (save-excursion
15201 (goto-char (region-beginning))
15202 (org-on-heading-p))))
15203 (call-interactively 'org-do-demote))
15204 ((or (org-at-item-p)
15205 (and (org-region-active-p)
15206 (save-excursion
15207 (goto-char (region-beginning))
15208 (org-at-item-p))))
15209 (call-interactively 'org-indent-item))
15210 (t (call-interactively 'forward-word))))
15212 (defun org-metaup (&optional arg)
15213 "Move subtree up or move table row up.
15214 Calls `org-move-subtree-up' or `org-table-move-row' or
15215 `org-move-item-up', depending on context. See the individual commands
15216 for more information."
15217 (interactive "P")
15218 (cond
15219 ((run-hook-with-args-until-success 'org-metaup-hook))
15220 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15221 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15222 ((org-at-item-p) (call-interactively 'org-move-item-up))
15223 (t (transpose-lines 1) (beginning-of-line -1))))
15225 (defun org-metadown (&optional arg)
15226 "Move subtree down or move table row down.
15227 Calls `org-move-subtree-down' or `org-table-move-row' or
15228 `org-move-item-down', depending on context. See the individual
15229 commands for more information."
15230 (interactive "P")
15231 (cond
15232 ((run-hook-with-args-until-success 'org-metadown-hook))
15233 ((org-at-table-p) (call-interactively 'org-table-move-row))
15234 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15235 ((org-at-item-p) (call-interactively 'org-move-item-down))
15236 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15238 (defun org-shiftup (&optional arg)
15239 "Increase item in timestamp or increase priority of current headline.
15240 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15241 depending on context. See the individual commands for more information."
15242 (interactive "P")
15243 (cond
15244 ((and org-support-shift-select (org-region-active-p))
15245 (org-call-for-shift-select 'previous-line))
15246 ((org-at-timestamp-p t)
15247 (call-interactively (if org-edit-timestamp-down-means-later
15248 'org-timestamp-down 'org-timestamp-up)))
15249 ((and (not (eq org-support-shift-select 'always))
15250 org-enable-priority-commands
15251 (org-on-heading-p))
15252 (call-interactively 'org-priority-up))
15253 ((and (not org-support-shift-select) (org-at-item-p))
15254 (call-interactively 'org-previous-item))
15255 ((org-clocktable-try-shift 'up arg))
15256 (org-support-shift-select
15257 (org-call-for-shift-select 'previous-line))
15258 (t (org-shiftselect-error))))
15260 (defun org-shiftdown (&optional arg)
15261 "Decrease item in timestamp or decrease priority of current headline.
15262 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15263 depending on context. See the individual commands for more information."
15264 (interactive "P")
15265 (cond
15266 ((and org-support-shift-select (org-region-active-p))
15267 (org-call-for-shift-select 'next-line))
15268 ((org-at-timestamp-p t)
15269 (call-interactively (if org-edit-timestamp-down-means-later
15270 'org-timestamp-up 'org-timestamp-down)))
15271 ((and (not (eq org-support-shift-select 'always))
15272 org-enable-priority-commands
15273 (org-on-heading-p))
15274 (call-interactively 'org-priority-down))
15275 ((and (not org-support-shift-select) (org-at-item-p))
15276 (call-interactively 'org-next-item))
15277 ((org-clocktable-try-shift 'down arg))
15278 (org-support-shift-select
15279 (org-call-for-shift-select 'next-line))
15280 (t (org-shiftselect-error))))
15282 (defun org-shiftright (&optional arg)
15283 "Cycle the thing at point or in the current line, depending on context.
15284 Depending on context, this does one of the following:
15286 - switch a timestamp at point one day into the future
15287 - on a headline, switch to the next TODO keyword.
15288 - on an item, switch entire list to the next bullet type
15289 - on a property line, switch to the next allowed value
15290 - on a clocktable definition line, move time block into the future"
15291 (interactive "P")
15292 (cond
15293 ((and org-support-shift-select (org-region-active-p))
15294 (org-call-for-shift-select 'forward-char))
15295 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15296 ((and (not (eq org-support-shift-select 'always))
15297 (org-on-heading-p))
15298 (let ((org-inhibit-logging
15299 (not org-treat-S-cursor-todo-selection-as-state-change))
15300 (org-inhibit-blocking
15301 (not org-treat-S-cursor-todo-selection-as-state-change)))
15302 (org-call-with-arg 'org-todo 'right)))
15303 ((or (and org-support-shift-select
15304 (not (eq org-support-shift-select 'always))
15305 (org-at-item-bullet-p))
15306 (and (not org-support-shift-select) (org-at-item-p)))
15307 (org-call-with-arg 'org-cycle-list-bullet nil))
15308 ((and (not (eq org-support-shift-select 'always))
15309 (org-at-property-p))
15310 (call-interactively 'org-property-next-allowed-value))
15311 ((org-clocktable-try-shift 'right arg))
15312 (org-support-shift-select
15313 (org-call-for-shift-select 'forward-char))
15314 (t (org-shiftselect-error))))
15316 (defun org-shiftleft (&optional arg)
15317 "Cycle the thing at point or in the current line, depending on context.
15318 Depending on context, this does one of the following:
15320 - switch a timestamp at point one day into the past
15321 - on a headline, switch to the previous TODO keyword.
15322 - on an item, switch entire list to the previous bullet type
15323 - on a property line, switch to the previous allowed value
15324 - on a clocktable definition line, move time block into the past"
15325 (interactive "P")
15326 (cond
15327 ((and org-support-shift-select (org-region-active-p))
15328 (org-call-for-shift-select 'backward-char))
15329 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15330 ((and (not (eq org-support-shift-select 'always))
15331 (org-on-heading-p))
15332 (let ((org-inhibit-logging
15333 (not org-treat-S-cursor-todo-selection-as-state-change))
15334 (org-inhibit-blocking
15335 (not org-treat-S-cursor-todo-selection-as-state-change)))
15336 (org-call-with-arg 'org-todo 'left)))
15337 ((or (and org-support-shift-select
15338 (not (eq org-support-shift-select 'always))
15339 (org-at-item-bullet-p))
15340 (and (not org-support-shift-select) (org-at-item-p)))
15341 (org-call-with-arg 'org-cycle-list-bullet 'previous))
15342 ((and (not (eq org-support-shift-select 'always))
15343 (org-at-property-p))
15344 (call-interactively 'org-property-previous-allowed-value))
15345 ((org-clocktable-try-shift 'left arg))
15346 (org-support-shift-select
15347 (org-call-for-shift-select 'backward-char))
15348 (t (org-shiftselect-error))))
15350 (defun org-shiftcontrolright ()
15351 "Switch to next TODO set."
15352 (interactive)
15353 (cond
15354 ((and org-support-shift-select (org-region-active-p))
15355 (org-call-for-shift-select 'forward-word))
15356 ((and (not (eq org-support-shift-select 'always))
15357 (org-on-heading-p))
15358 (org-call-with-arg 'org-todo 'nextset))
15359 (org-support-shift-select
15360 (org-call-for-shift-select 'forward-word))
15361 (t (org-shiftselect-error))))
15363 (defun org-shiftcontrolleft ()
15364 "Switch to previous TODO set."
15365 (interactive)
15366 (cond
15367 ((and org-support-shift-select (org-region-active-p))
15368 (org-call-for-shift-select 'backward-word))
15369 ((and (not (eq org-support-shift-select 'always))
15370 (org-on-heading-p))
15371 (org-call-with-arg 'org-todo 'previousset))
15372 (org-support-shift-select
15373 (org-call-for-shift-select 'backward-word))
15374 (t (org-shiftselect-error))))
15376 (defun org-ctrl-c-ret ()
15377 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15378 (interactive)
15379 (cond
15380 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15381 (t (call-interactively 'org-insert-heading))))
15383 (defun org-copy-special ()
15384 "Copy region in table or copy current subtree.
15385 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15386 See the individual commands for more information."
15387 (interactive)
15388 (call-interactively
15389 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15391 (defun org-cut-special ()
15392 "Cut region in table or cut current subtree.
15393 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15394 See the individual commands for more information."
15395 (interactive)
15396 (call-interactively
15397 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15399 (defun org-paste-special (arg)
15400 "Paste rectangular region into table, or past subtree relative to level.
15401 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15402 See the individual commands for more information."
15403 (interactive "P")
15404 (if (org-at-table-p)
15405 (org-table-paste-rectangle)
15406 (org-paste-subtree arg)))
15408 (defun org-edit-special ()
15409 "Call a special editor for the stuff at point.
15410 When at a table, call the formula editor with `org-table-edit-formulas'.
15411 When at the first line of an src example, call `org-edit-src-code'.
15412 When in an #+include line, visit the include file. Otherwise call
15413 `ffap' to visit the file at point."
15414 (interactive)
15415 (cond
15416 ((org-at-table-p)
15417 (call-interactively 'org-table-edit-formulas))
15418 ((save-excursion
15419 (beginning-of-line 1)
15420 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
15421 (find-file (org-trim (match-string 1))))
15422 ((org-edit-src-code))
15423 ((org-edit-fixed-width-region))
15424 (t (call-interactively 'ffap))))
15427 (defun org-ctrl-c-ctrl-c (&optional arg)
15428 "Set tags in headline, or update according to changed information at point.
15430 This command does many different things, depending on context:
15432 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15433 this is what we do.
15435 - If the cursor is on a statistics cookie, update it.
15437 - If the cursor is in a headline, prompt for tags and insert them
15438 into the current line, aligned to `org-tags-column'. When called
15439 with prefix arg, realign all tags in the current buffer.
15441 - If the cursor is in one of the special #+KEYWORD lines, this
15442 triggers scanning the buffer for these lines and updating the
15443 information.
15445 - If the cursor is inside a table, realign the table. This command
15446 works even if the automatic table editor has been turned off.
15448 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15449 the entire table.
15451 - If the cursor is at a footnote reference or definition, jump to
15452 the corresponding definition or references, respectively.
15454 - If the cursor is a the beginning of a dynamic block, update it.
15456 - If the cursor is inside a table created by the table.el package,
15457 activate that table.
15459 - If the current buffer is a remember buffer, close note and file
15460 it. A prefix argument of 1 files to the default location
15461 without further interaction. A prefix argument of 2 files to
15462 the currently clocking task.
15464 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15465 links in this buffer.
15467 - If the cursor is on a numbered item in a plain list, renumber the
15468 ordered list.
15470 - If the cursor is on a checkbox, toggle it."
15471 (interactive "P")
15472 (let ((org-enable-table-editor t))
15473 (cond
15474 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15475 org-occur-highlights
15476 org-latex-fragment-image-overlays)
15477 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15478 (org-remove-occur-highlights)
15479 (org-remove-latex-fragment-image-overlays)
15480 (message "Temporary highlights/overlays removed from current buffer"))
15481 ((and (local-variable-p 'org-finish-function (current-buffer))
15482 (fboundp org-finish-function))
15483 (funcall org-finish-function))
15484 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15485 ((org-at-property-p)
15486 (call-interactively 'org-property-action))
15487 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15488 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15489 (or (org-on-heading-p) (org-at-item-p)))
15490 (call-interactively 'org-update-statistics-cookies))
15491 ((org-on-heading-p) (call-interactively 'org-set-tags))
15492 ((org-at-table.el-p)
15493 (require 'table)
15494 (beginning-of-line 1)
15495 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15496 (call-interactively 'table-recognize-table))
15497 ((org-at-table-p)
15498 (org-table-maybe-eval-formula)
15499 (if arg
15500 (call-interactively 'org-table-recalculate)
15501 (org-table-maybe-recalculate-line))
15502 (call-interactively 'org-table-align))
15503 ((or (org-footnote-at-reference-p)
15504 (org-footnote-at-definition-p))
15505 (call-interactively 'org-footnote-action))
15506 ((org-at-item-checkbox-p)
15507 (call-interactively 'org-toggle-checkbox))
15508 ((org-at-item-p)
15509 (if arg
15510 (call-interactively 'org-toggle-checkbox)
15511 (call-interactively 'org-maybe-renumber-ordered-list)))
15512 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15513 ;; Dynamic block
15514 (beginning-of-line 1)
15515 (save-excursion (org-update-dblock)))
15516 ((save-excursion
15517 (beginning-of-line 1)
15518 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15519 (cond
15520 ((equal (match-string 1) "TBLFM")
15521 ;; Recalculate the table before this line
15522 (save-excursion
15523 (beginning-of-line 1)
15524 (skip-chars-backward " \r\n\t")
15525 (if (org-at-table-p)
15526 (org-call-with-arg 'org-table-recalculate (or arg t)))))
15528 ; (org-set-regexps-and-options)
15529 ; (org-restart-font-lock)
15530 (let ((org-inhibit-startup t)) (org-mode-restart))
15531 (message "Local setup has been refreshed"))))
15532 ((org-clock-update-time-maybe))
15533 (t (error "C-c C-c can do nothing useful at this location")))))
15535 (defun org-mode-restart ()
15536 "Restart Org-mode, to scan again for special lines.
15537 Also updates the keyword regular expressions."
15538 (interactive)
15539 (org-mode)
15540 (message "Org-mode restarted"))
15542 (defun org-kill-note-or-show-branches ()
15543 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15544 (interactive)
15545 (if (not org-finish-function)
15546 (call-interactively 'show-branches)
15547 (let ((org-note-abort t))
15548 (funcall org-finish-function))))
15550 (defun org-return (&optional indent)
15551 "Goto next table row or insert a newline.
15552 Calls `org-table-next-row' or `newline', depending on context.
15553 See the individual commands for more information."
15554 (interactive)
15555 (cond
15556 ((bobp) (if indent (newline-and-indent) (newline)))
15557 ((org-at-table-p)
15558 (org-table-justify-field-maybe)
15559 (call-interactively 'org-table-next-row))
15560 ((and org-return-follows-link
15561 (eq (get-text-property (point) 'face) 'org-link))
15562 (call-interactively 'org-open-at-point))
15563 ((and (org-at-heading-p)
15564 (looking-at
15565 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15566 (org-show-entry)
15567 (end-of-line 1)
15568 (newline))
15569 (t (if indent (newline-and-indent) (newline)))))
15571 (defun org-return-indent ()
15572 "Goto next table row or insert a newline and indent.
15573 Calls `org-table-next-row' or `newline-and-indent', depending on
15574 context. See the individual commands for more information."
15575 (interactive)
15576 (org-return t))
15578 (defun org-ctrl-c-star ()
15579 "Compute table, or change heading status of lines.
15580 Calls `org-table-recalculate' or `org-toggle-heading',
15581 depending on context."
15582 (interactive)
15583 (cond
15584 ((org-at-table-p)
15585 (call-interactively 'org-table-recalculate))
15587 ;; Convert all lines in region to list items
15588 (call-interactively 'org-toggle-heading))))
15590 (defun org-ctrl-c-minus ()
15591 "Insert separator line in table or modify bullet status of line.
15592 Also turns a plain line or a region of lines into list items.
15593 Calls `org-table-insert-hline', `org-toggle-item', or
15594 `org-cycle-list-bullet', depending on context."
15595 (interactive)
15596 (cond
15597 ((org-at-table-p)
15598 (call-interactively 'org-table-insert-hline))
15599 ((org-region-active-p)
15600 (call-interactively 'org-toggle-item))
15601 ((org-in-item-p)
15602 (call-interactively 'org-cycle-list-bullet))
15604 (call-interactively 'org-toggle-item))))
15606 (defun org-toggle-item ()
15607 "Convert headings or normal lines to items, items to normal lines.
15608 If there is no active region, only the current line is considered.
15610 If the first line in the region is a headline, convert all headlines to items.
15612 If the first line in the region is an item, convert all items to normal lines.
15614 If the first line is normal text, add an item bullet to each line."
15615 (interactive)
15616 (let (l2 l beg end)
15617 (if (org-region-active-p)
15618 (setq beg (region-beginning) end (region-end))
15619 (setq beg (point-at-bol)
15620 end (min (1+ (point-at-eol)) (point-max))))
15621 (save-excursion
15622 (goto-char end)
15623 (setq l2 (org-current-line))
15624 (goto-char beg)
15625 (beginning-of-line 1)
15626 (setq l (1- (org-current-line)))
15627 (if (org-at-item-p)
15628 ;; We already have items, de-itemize
15629 (while (< (setq l (1+ l)) l2)
15630 (when (org-at-item-p)
15631 (goto-char (match-beginning 2))
15632 (delete-region (match-beginning 2) (match-end 2))
15633 (and (looking-at "[ \t]+") (replace-match "")))
15634 (beginning-of-line 2))
15635 (if (org-on-heading-p)
15636 ;; Headings, convert to items
15637 (while (< (setq l (1+ l)) l2)
15638 (if (looking-at org-outline-regexp)
15639 (replace-match "- " t t))
15640 (beginning-of-line 2))
15641 ;; normal lines, turn them into items
15642 (while (< (setq l (1+ l)) l2)
15643 (unless (org-at-item-p)
15644 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15645 (replace-match "\\1- \\2")))
15646 (beginning-of-line 2)))))))
15648 (defun org-toggle-heading (&optional nstars)
15649 "Convert headings to normal text, or items or text to headings.
15650 If there is no active region, only the current line is considered.
15652 If the first line is a heading, remove the stars from all headlines
15653 in the region.
15655 If the first line is a plain list item, turn all plain list items
15656 into headings.
15658 If the first line is a normal line, turn each and every line in the
15659 region into a heading.
15661 When converting a line into a heading, the number of stars is chosen
15662 such that the lines become children of the current entry. However,
15663 when a prefix argument is given, its value determines the number of
15664 stars to add."
15665 (interactive "P")
15666 (let (l2 l itemp beg end)
15667 (if (org-region-active-p)
15668 (setq beg (region-beginning) end (region-end))
15669 (setq beg (point-at-bol)
15670 end (min (1+ (point-at-eol)) (point-max))))
15671 (save-excursion
15672 (goto-char end)
15673 (setq l2 (org-current-line))
15674 (goto-char beg)
15675 (beginning-of-line 1)
15676 (setq l (1- (org-current-line)))
15677 (if (org-on-heading-p)
15678 ;; We already have headlines, de-star them
15679 (while (< (setq l (1+ l)) l2)
15680 (when (org-on-heading-p t)
15681 (and (looking-at outline-regexp) (replace-match "")))
15682 (beginning-of-line 2))
15683 (setq itemp (org-at-item-p))
15684 (let* ((stars
15685 (if nstars
15686 (make-string (prefix-numeric-value current-prefix-arg)
15688 (save-excursion
15689 (if (re-search-backward org-complex-heading-regexp nil t)
15690 (match-string 1) ""))))
15691 (add-stars (cond (nstars "")
15692 ((equal stars "") "*")
15693 (org-odd-levels-only "**")
15694 (t "*")))
15695 (rpl (concat stars add-stars " ")))
15696 (while (< (setq l (1+ l)) l2)
15697 (if itemp
15698 (and (org-at-item-p) (replace-match rpl t t))
15699 (unless (org-on-heading-p)
15700 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15701 (replace-match (concat rpl (match-string 2))))))
15702 (beginning-of-line 2)))))))
15704 (defun org-meta-return (&optional arg)
15705 "Insert a new heading or wrap a region in a table.
15706 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15707 See the individual commands for more information."
15708 (interactive "P")
15709 (cond
15710 ((run-hook-with-args-until-success 'org-metareturn-hook))
15711 ((org-at-table-p)
15712 (call-interactively 'org-table-wrap-region))
15713 (t (call-interactively 'org-insert-heading))))
15715 ;;; Menu entries
15717 ;; Define the Org-mode menus
15718 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15719 '("Tbl"
15720 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15721 ["Next Field" org-cycle (org-at-table-p)]
15722 ["Previous Field" org-shifttab (org-at-table-p)]
15723 ["Next Row" org-return (org-at-table-p)]
15724 "--"
15725 ["Blank Field" org-table-blank-field (org-at-table-p)]
15726 ["Edit Field" org-table-edit-field (org-at-table-p)]
15727 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15728 "--"
15729 ("Column"
15730 ["Move Column Left" org-metaleft (org-at-table-p)]
15731 ["Move Column Right" org-metaright (org-at-table-p)]
15732 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15733 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15734 ("Row"
15735 ["Move Row Up" org-metaup (org-at-table-p)]
15736 ["Move Row Down" org-metadown (org-at-table-p)]
15737 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15738 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15739 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15740 "--"
15741 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15742 ("Rectangle"
15743 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15744 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15745 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15746 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15747 "--"
15748 ("Calculate"
15749 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15750 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15751 ["Edit Formulas" org-edit-special (org-at-table-p)]
15752 "--"
15753 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15754 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15755 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15756 "--"
15757 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15758 "--"
15759 ["Sum Column/Rectangle" org-table-sum
15760 (or (org-at-table-p) (org-region-active-p))]
15761 ["Which Column?" org-table-current-column (org-at-table-p)])
15762 ["Debug Formulas"
15763 org-table-toggle-formula-debugger
15764 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15765 ["Show Col/Row Numbers"
15766 org-table-toggle-coordinate-overlays
15767 :style toggle
15768 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15769 "--"
15770 ["Create" org-table-create (and (not (org-at-table-p))
15771 org-enable-table-editor)]
15772 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15773 ["Import from File" org-table-import (not (org-at-table-p))]
15774 ["Export to File" org-table-export (org-at-table-p)]
15775 "--"
15776 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15778 (easy-menu-define org-org-menu org-mode-map "Org menu"
15779 '("Org"
15780 ("Show/Hide"
15781 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15782 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15783 ["Sparse Tree..." org-sparse-tree t]
15784 ["Reveal Context" org-reveal t]
15785 ["Show All" show-all t]
15786 "--"
15787 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15788 "--"
15789 ["New Heading" org-insert-heading t]
15790 ("Navigate Headings"
15791 ["Up" outline-up-heading t]
15792 ["Next" outline-next-visible-heading t]
15793 ["Previous" outline-previous-visible-heading t]
15794 ["Next Same Level" outline-forward-same-level t]
15795 ["Previous Same Level" outline-backward-same-level t]
15796 "--"
15797 ["Jump" org-goto t])
15798 ("Edit Structure"
15799 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15800 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15801 "--"
15802 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15803 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15804 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15805 "--"
15806 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15807 "--"
15808 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15809 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15810 ["Demote Heading" org-metaright (not (org-at-table-p))]
15811 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15812 "--"
15813 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15814 "--"
15815 ["Convert to odd levels" org-convert-to-odd-levels t]
15816 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15817 ("Editing"
15818 ["Emphasis..." org-emphasize t]
15819 ["Edit Source Example" org-edit-special t]
15820 "--"
15821 ["Footnote new/jump" org-footnote-action t]
15822 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15823 ("Archive"
15824 ["Archive (default method)" org-archive-subtree-default t]
15825 "--"
15826 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
15827 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15828 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
15830 "--"
15831 ("Hyperlinks"
15832 ["Store Link (Global)" org-store-link t]
15833 ["Find existing link to here" org-occur-link-in-agenda-files t]
15834 ["Insert Link" org-insert-link t]
15835 ["Follow Link" org-open-at-point t]
15836 "--"
15837 ["Next link" org-next-link t]
15838 ["Previous link" org-previous-link t]
15839 "--"
15840 ["Descriptive Links"
15841 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15842 :style radio
15843 :selected (member '(org-link) buffer-invisibility-spec)]
15844 ["Literal Links"
15845 (progn
15846 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15847 :style radio
15848 :selected (not (member '(org-link) buffer-invisibility-spec))])
15849 "--"
15850 ("TODO Lists"
15851 ["TODO/DONE/-" org-todo t]
15852 ("Select keyword"
15853 ["Next keyword" org-shiftright (org-on-heading-p)]
15854 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15855 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15856 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15857 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15858 ["Show TODO Tree" org-show-todo-tree t]
15859 ["Global TODO list" org-todo-list t]
15860 "--"
15861 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15862 :selected org-enforce-todo-dependencies :style toggle :active t]
15863 "Settings for tree at point"
15864 ["Do Children sequentially" org-toggle-ordered-property :style radio
15865 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15866 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15867 ["Do Children parallel" org-toggle-ordered-property :style radio
15868 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15869 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15870 "--"
15871 ["Set Priority" org-priority t]
15872 ["Priority Up" org-shiftup t]
15873 ["Priority Down" org-shiftdown t]
15874 "--"
15875 ["Get news from all feeds" org-feed-update-all t]
15876 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15877 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15878 ("TAGS and Properties"
15879 ["Set Tags" org-set-tags-command t]
15880 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15881 "--"
15882 ["Set property" org-set-property t]
15883 ["Column view of properties" org-columns t]
15884 ["Insert Column View DBlock" org-insert-columns-dblock t])
15885 ("Dates and Scheduling"
15886 ["Timestamp" org-time-stamp t]
15887 ["Timestamp (inactive)" org-time-stamp-inactive t]
15888 ("Change Date"
15889 ["1 Day Later" org-shiftright t]
15890 ["1 Day Earlier" org-shiftleft t]
15891 ["1 ... Later" org-shiftup t]
15892 ["1 ... Earlier" org-shiftdown t])
15893 ["Compute Time Range" org-evaluate-time-range t]
15894 ["Schedule Item" org-schedule t]
15895 ["Deadline" org-deadline t]
15896 "--"
15897 ["Custom time format" org-toggle-time-stamp-overlays
15898 :style radio :selected org-display-custom-times]
15899 "--"
15900 ["Goto Calendar" org-goto-calendar t]
15901 ["Date from Calendar" org-date-from-calendar t]
15902 "--"
15903 ["Start/Restart Timer" org-timer-start t]
15904 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15905 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15906 ["Insert Timer String" org-timer t]
15907 ["Insert Timer Item" org-timer-item t])
15908 ("Logging work"
15909 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
15910 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
15911 ["Clock out" org-clock-out t]
15912 ["Clock cancel" org-clock-cancel t]
15913 "--"
15914 ["Mark as default task" org-clock-mark-default-task t]
15915 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
15916 ["Goto running clock" org-clock-goto t]
15917 "--"
15918 ["Display times" org-clock-display t]
15919 ["Create clock table" org-clock-report t]
15920 "--"
15921 ["Record DONE time"
15922 (progn (setq org-log-done (not org-log-done))
15923 (message "Switching to %s will %s record a timestamp"
15924 (car org-done-keywords)
15925 (if org-log-done "automatically" "not")))
15926 :style toggle :selected org-log-done])
15927 "--"
15928 ["Agenda Command..." org-agenda t]
15929 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15930 ("File List for Agenda")
15931 ("Special views current file"
15932 ["TODO Tree" org-show-todo-tree t]
15933 ["Check Deadlines" org-check-deadlines t]
15934 ["Timeline" org-timeline t]
15935 ["Tags/Property tree" org-match-sparse-tree t])
15936 "--"
15937 ["Export/Publish..." org-export t]
15938 ("LaTeX"
15939 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15940 :selected org-cdlatex-mode]
15941 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15942 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15943 ["Modify math symbol" org-cdlatex-math-modify
15944 (org-inside-LaTeX-fragment-p)]
15945 ["Insert citation" org-reftex-citation t]
15946 "--"
15947 ["Export LaTeX fragments as images"
15948 (if (featurep 'org-exp)
15949 (setq org-export-with-LaTeX-fragments
15950 (not org-export-with-LaTeX-fragments))
15951 (require 'org-exp))
15952 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15953 org-export-with-LaTeX-fragments)])
15954 "--"
15955 ("MobileOrg"
15956 ["Push Files and Views" org-mobile-push t]
15957 ["Get Captured and Flagged" org-mobile-pull t]
15958 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
15959 "--"
15960 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
15961 "--"
15962 ("Documentation"
15963 ["Show Version" org-version t]
15964 ["Info Documentation" org-info t])
15965 ("Customize"
15966 ["Browse Org Group" org-customize t]
15967 "--"
15968 ["Expand This Menu" org-create-customize-menu
15969 (fboundp 'customize-menu-create)])
15970 ["Send bug report" org-submit-bug-report t]
15971 "--"
15972 ("Refresh/Reload"
15973 ["Refresh setup current buffer" org-mode-restart t]
15974 ["Reload Org (after update)" org-reload t]
15975 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15978 (defun org-info (&optional node)
15979 "Read documentation for Org-mode in the info system.
15980 With optional NODE, go directly to that node."
15981 (interactive)
15982 (info (format "(org)%s" (or node ""))))
15984 ;;;###autoload
15985 (defun org-submit-bug-report ()
15986 "Submit a bug report on Org-mode via mail.
15988 Don't hesitate to report any problems or inaccurate documentation.
15990 If you don't have setup sending mail from (X)Emacs, please copy the
15991 output buffer into your mail program, as it gives us important
15992 information about your Org-mode version and configuration."
15993 (interactive)
15994 (require 'reporter)
15995 (org-load-modules-maybe)
15996 (org-require-autoloaded-modules)
15997 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
15998 (reporter-submit-bug-report
15999 "emacs-orgmode@gnu.org"
16000 (org-version)
16001 (let (list)
16002 (save-window-excursion
16003 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16004 (delete-other-windows)
16005 (erase-buffer)
16006 (insert "You are about to submit a bug report to the Org-mode mailing list.
16008 We would like to add your full Org-mode and Outline configuration to the
16009 bug report. This greatly simplifies the work of the maintainer and
16010 other experts on the mailing list.
16012 HOWEVER, some variables you have customized may contain private
16013 information. The names of customers, colleagues, or friends, might
16014 appear in the form of file names, tags, todo states, or search strings.
16015 If you answer yes to the prompt, you might want to check and remove
16016 such private information before sending the email.")
16017 (add-text-properties (point-min) (point-max) '(face org-warning))
16018 (when (yes-or-no-p "Include your Org-mode configuration ")
16019 (mapatoms
16020 (lambda (v)
16021 (and (boundp v)
16022 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16023 (or (and (symbol-value v)
16024 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16025 (and
16026 (get v 'custom-type) (get v 'standard-value)
16027 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16028 (push v list)))))
16029 (kill-buffer (get-buffer "*Warn about privacy*"))
16030 list))
16031 nil nil
16032 "Remember to cover the basics, that is, what you expected to happen and
16033 what in fact did happen. You don't know how to make a good report? See
16035 http://orgmode.org/manual/Feedback.html#Feedback
16037 Your bug report will be posted to the Org-mode mailing list.
16038 ------------------------------------------------------------------------")))
16040 (defun org-install-agenda-files-menu ()
16041 (let ((bl (buffer-list)))
16042 (save-excursion
16043 (while bl
16044 (set-buffer (pop bl))
16045 (if (org-mode-p) (setq bl nil)))
16046 (when (org-mode-p)
16047 (easy-menu-change
16048 '("Org") "File List for Agenda"
16049 (append
16050 (list
16051 ["Edit File List" (org-edit-agenda-file-list) t]
16052 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16053 ["Remove Current File from List" org-remove-file t]
16054 ["Cycle through agenda files" org-cycle-agenda-files t]
16055 ["Occur in all agenda files" org-occur-in-agenda-files t]
16056 "--")
16057 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16059 ;;;; Documentation
16061 ;;;###autoload
16062 (defun org-require-autoloaded-modules ()
16063 (interactive)
16064 (mapc 'require
16065 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16066 org-docbook org-exp org-html org-icalendar
16067 org-id org-latex
16068 org-publish org-remember org-table
16069 org-timer org-xoxo)))
16071 ;;;###autoload
16072 (defun org-reload (&optional uncompiled)
16073 "Reload all org lisp files.
16074 With prefix arg UNCOMPILED, load the uncompiled versions."
16075 (interactive "P")
16076 (require 'find-func)
16077 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16078 (dir-org (file-name-directory (org-find-library-name "org")))
16079 (dir-org-contrib (ignore-errors
16080 (file-name-directory
16081 (org-find-library-name "org-contribdir"))))
16082 (files
16083 (append (directory-files dir-org t file-re)
16084 (and dir-org-contrib
16085 (directory-files dir-org-contrib t file-re))))
16086 (remove-re (concat (if (featurep 'xemacs)
16087 "org-colview" "org-colview-xemacs")
16088 "\\'")))
16089 (setq files (mapcar 'file-name-sans-extension files))
16090 (setq files (mapcar
16091 (lambda (x) (if (string-match remove-re x) nil x))
16092 files))
16093 (setq files (delq nil files))
16094 (mapc
16095 (lambda (f)
16096 (when (featurep (intern (file-name-nondirectory f)))
16097 (if (and (not uncompiled)
16098 (file-exists-p (concat f ".elc")))
16099 (load (concat f ".elc") nil nil t)
16100 (load (concat f ".el") nil nil t))))
16101 files))
16102 (org-version))
16104 ;;;###autoload
16105 (defun org-customize ()
16106 "Call the customize function with org as argument."
16107 (interactive)
16108 (org-load-modules-maybe)
16109 (org-require-autoloaded-modules)
16110 (customize-browse 'org))
16112 (defun org-create-customize-menu ()
16113 "Create a full customization menu for Org-mode, insert it into the menu."
16114 (interactive)
16115 (org-load-modules-maybe)
16116 (org-require-autoloaded-modules)
16117 (if (fboundp 'customize-menu-create)
16118 (progn
16119 (easy-menu-change
16120 '("Org") "Customize"
16121 `(["Browse Org group" org-customize t]
16122 "--"
16123 ,(customize-menu-create 'org)
16124 ["Set" Custom-set t]
16125 ["Save" Custom-save t]
16126 ["Reset to Current" Custom-reset-current t]
16127 ["Reset to Saved" Custom-reset-saved t]
16128 ["Reset to Standard Settings" Custom-reset-standard t]))
16129 (message "\"Org\"-menu now contains full customization menu"))
16130 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16132 ;;;; Miscellaneous stuff
16134 ;;; Generally useful functions
16136 (defun org-get-at-bol (property)
16137 "Get text property PROPERTY at beginning of line."
16138 (get-text-property (point-at-bol) property))
16140 (defun org-find-text-property-in-string (prop s)
16141 "Return the first non-nil value of property PROP in string S."
16142 (or (get-text-property 0 prop s)
16143 (get-text-property (or (next-single-property-change 0 prop s) 0)
16144 prop s)))
16146 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16147 "Display the given MESSAGE as a warning."
16148 (if (fboundp 'display-warning)
16149 (display-warning 'org message
16150 (if (featurep 'xemacs)
16151 'warning
16152 :warning))
16153 (let ((buf (get-buffer-create "*Org warnings*")))
16154 (with-current-buffer buf
16155 (goto-char (point-max))
16156 (insert "Warning (Org): " message)
16157 (unless (bolp)
16158 (newline)))
16159 (display-buffer buf)
16160 (sit-for 0))))
16162 (defun org-in-commented-line ()
16163 "Is point in a line starting with `#'?"
16164 (equal (char-after (point-at-bol)) ?#))
16166 (defun org-in-verbatim-emphasis ()
16167 (save-match-data
16168 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16170 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16171 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16172 (if (and marker (marker-buffer marker)
16173 (buffer-live-p (marker-buffer marker)))
16174 (progn
16175 (switch-to-buffer (marker-buffer marker))
16176 (if (or (> marker (point-max)) (< marker (point-min)))
16177 (widen))
16178 (goto-char marker)
16179 (org-show-context 'org-goto))
16180 (if bookmark
16181 (bookmark-jump bookmark)
16182 (error "Cannot find location"))))
16184 (defun org-quote-csv-field (s)
16185 "Quote field for inclusion in CSV material."
16186 (if (string-match "[\",]" s)
16187 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16190 (defun org-plist-delete (plist property)
16191 "Delete PROPERTY from PLIST.
16192 This is in contrast to merely setting it to 0."
16193 (let (p)
16194 (while plist
16195 (if (not (eq property (car plist)))
16196 (setq p (plist-put p (car plist) (nth 1 plist))))
16197 (setq plist (cddr plist)))
16200 (defun org-force-self-insert (N)
16201 "Needed to enforce self-insert under remapping."
16202 (interactive "p")
16203 (self-insert-command N))
16205 (defun org-string-width (s)
16206 "Compute width of string, ignoring invisible characters.
16207 This ignores character with invisibility property `org-link', and also
16208 characters with property `org-cwidth', because these will become invisible
16209 upon the next fontification round."
16210 (let (b l)
16211 (when (or (eq t buffer-invisibility-spec)
16212 (assq 'org-link buffer-invisibility-spec))
16213 (while (setq b (text-property-any 0 (length s)
16214 'invisible 'org-link s))
16215 (setq s (concat (substring s 0 b)
16216 (substring s (or (next-single-property-change
16217 b 'invisible s) (length s)))))))
16218 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16219 (setq s (concat (substring s 0 b)
16220 (substring s (or (next-single-property-change
16221 b 'org-cwidth s) (length s))))))
16222 (setq l (string-width s) b -1)
16223 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16224 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16227 (defun org-get-indentation (&optional line)
16228 "Get the indentation of the current line, interpreting tabs.
16229 When LINE is given, assume it represents a line and compute its indentation."
16230 (if line
16231 (if (string-match "^ *" (org-remove-tabs line))
16232 (match-end 0))
16233 (save-excursion
16234 (beginning-of-line 1)
16235 (skip-chars-forward " \t")
16236 (current-column))))
16238 (defun org-remove-tabs (s &optional width)
16239 "Replace tabulators in S with spaces.
16240 Assumes that s is a single line, starting in column 0."
16241 (setq width (or width tab-width))
16242 (while (string-match "\t" s)
16243 (setq s (replace-match
16244 (make-string
16245 (- (* width (/ (+ (match-beginning 0) width) width))
16246 (match-beginning 0)) ?\ )
16247 t t s)))
16250 (defun org-fix-indentation (line ind)
16251 "Fix indentation in LINE.
16252 IND is a cons cell with target and minimum indentation.
16253 If the current indentation in LINE is smaller than the minimum,
16254 leave it alone. If it is larger than ind, set it to the target."
16255 (let* ((l (org-remove-tabs line))
16256 (i (org-get-indentation l))
16257 (i1 (car ind)) (i2 (cdr ind)))
16258 (if (>= i i2) (setq l (substring line i2)))
16259 (if (> i1 0)
16260 (concat (make-string i1 ?\ ) l)
16261 l)))
16263 (defun org-remove-indentation (code &optional n)
16264 "Remove the maximum common indentation from the lines in CODE.
16265 N may optionally be the number of spaces to remove."
16266 (with-temp-buffer
16267 (insert code)
16268 (org-do-remove-indentation n)
16269 (buffer-string)))
16271 (defun org-do-remove-indentation (&optional n)
16272 "Remove the maximum common indentation from the buffer."
16273 (untabify (point-min) (point-max))
16274 (let ((min 10000) re)
16275 (if n
16276 (setq min n)
16277 (goto-char (point-min))
16278 (while (re-search-forward "^ *[^ \n]" nil t)
16279 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16280 (unless (or (= min 0) (= min 10000))
16281 (setq re (format "^ \\{%d\\}" min))
16282 (goto-char (point-min))
16283 (while (re-search-forward re nil t)
16284 (replace-match "")
16285 (end-of-line 1))
16286 min)))
16288 (defun org-fill-template (template alist)
16289 "Find each %key of ALIST in TEMPLATE and replace it."
16290 (let (entry key value)
16291 (setq alist (sort (copy-sequence alist)
16292 (lambda (a b) (< (length (car a)) (length (car b))))))
16293 (while (setq entry (pop alist))
16294 (setq template
16295 (replace-regexp-in-string
16296 (concat "%" (regexp-quote (car entry)))
16297 (cdr entry) template t t)))
16298 template))
16300 (defun org-base-buffer (buffer)
16301 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16302 (if (not buffer)
16303 buffer
16304 (or (buffer-base-buffer buffer)
16305 buffer)))
16307 (defun org-trim (s)
16308 "Remove whitespace at beginning and end of string."
16309 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
16310 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
16313 (defun org-wrap (string &optional width lines)
16314 "Wrap string to either a number of lines, or a width in characters.
16315 If WIDTH is non-nil, the string is wrapped to that width, however many lines
16316 that costs. If there is a word longer than WIDTH, the text is actually
16317 wrapped to the length of that word.
16318 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
16319 many lines, whatever width that takes.
16320 The return value is a list of lines, without newlines at the end."
16321 (let* ((words (org-split-string string "[ \t\n]+"))
16322 (maxword (apply 'max (mapcar 'org-string-width words)))
16323 w ll)
16324 (cond (width
16325 (org-do-wrap words (max maxword width)))
16326 (lines
16327 (setq w maxword)
16328 (setq ll (org-do-wrap words maxword))
16329 (if (<= (length ll) lines)
16331 (setq ll words)
16332 (while (> (length ll) lines)
16333 (setq w (1+ w))
16334 (setq ll (org-do-wrap words w)))
16335 ll))
16336 (t (error "Cannot wrap this")))))
16338 (defun org-do-wrap (words width)
16339 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
16340 (let (lines line)
16341 (while words
16342 (setq line (pop words))
16343 (while (and words (< (+ (length line) (length (car words))) width))
16344 (setq line (concat line " " (pop words))))
16345 (setq lines (push line lines)))
16346 (nreverse lines)))
16348 (defun org-split-string (string &optional separators)
16349 "Splits STRING into substrings at SEPARATORS.
16350 No empty strings are returned if there are matches at the beginning
16351 and end of string."
16352 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
16353 (start 0)
16354 notfirst
16355 (list nil))
16356 (while (and (string-match rexp string
16357 (if (and notfirst
16358 (= start (match-beginning 0))
16359 (< start (length string)))
16360 (1+ start) start))
16361 (< (match-beginning 0) (length string)))
16362 (setq notfirst t)
16363 (or (eq (match-beginning 0) 0)
16364 (and (eq (match-beginning 0) (match-end 0))
16365 (eq (match-beginning 0) start))
16366 (setq list
16367 (cons (substring string start (match-beginning 0))
16368 list)))
16369 (setq start (match-end 0)))
16370 (or (eq start (length string))
16371 (setq list
16372 (cons (substring string start)
16373 list)))
16374 (nreverse list)))
16376 (defun org-quote-vert (s)
16377 "Replace \"|\" with \"\\vert\"."
16378 (while (string-match "|" s)
16379 (setq s (replace-match "\\vert" t t s)))
16382 (defun org-uuidgen-p (s)
16383 "Is S an ID created by UUIDGEN?"
16384 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16386 (defun org-context ()
16387 "Return a list of contexts of the current cursor position.
16388 If several contexts apply, all are returned.
16389 Each context entry is a list with a symbol naming the context, and
16390 two positions indicating start and end of the context. Possible
16391 contexts are:
16393 :headline anywhere in a headline
16394 :headline-stars on the leading stars in a headline
16395 :todo-keyword on a TODO keyword (including DONE) in a headline
16396 :tags on the TAGS in a headline
16397 :priority on the priority cookie in a headline
16398 :item on the first line of a plain list item
16399 :item-bullet on the bullet/number of a plain list item
16400 :checkbox on the checkbox in a plain list item
16401 :table in an org-mode table
16402 :table-special on a special filed in a table
16403 :table-table in a table.el table
16404 :link on a hyperlink
16405 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16406 :target on a <<target>>
16407 :radio-target on a <<<radio-target>>>
16408 :latex-fragment on a LaTeX fragment
16409 :latex-preview on a LaTeX fragment with overlayed preview image
16411 This function expects the position to be visible because it uses font-lock
16412 faces as a help to recognize the following contexts: :table-special, :link,
16413 and :keyword."
16414 (let* ((f (get-text-property (point) 'face))
16415 (faces (if (listp f) f (list f)))
16416 (p (point)) clist o)
16417 ;; First the large context
16418 (cond
16419 ((org-on-heading-p t)
16420 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16421 (when (progn
16422 (beginning-of-line 1)
16423 (looking-at org-todo-line-tags-regexp))
16424 (push (org-point-in-group p 1 :headline-stars) clist)
16425 (push (org-point-in-group p 2 :todo-keyword) clist)
16426 (push (org-point-in-group p 4 :tags) clist))
16427 (goto-char p)
16428 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
16429 (if (looking-at "\\[#[A-Z0-9]\\]")
16430 (push (org-point-in-group p 0 :priority) clist)))
16432 ((org-at-item-p)
16433 (push (org-point-in-group p 2 :item-bullet) clist)
16434 (push (list :item (point-at-bol)
16435 (save-excursion (org-end-of-item) (point)))
16436 clist)
16437 (and (org-at-item-checkbox-p)
16438 (push (org-point-in-group p 0 :checkbox) clist)))
16440 ((org-at-table-p)
16441 (push (list :table (org-table-begin) (org-table-end)) clist)
16442 (if (memq 'org-formula faces)
16443 (push (list :table-special
16444 (previous-single-property-change p 'face)
16445 (next-single-property-change p 'face)) clist)))
16446 ((org-at-table-p 'any)
16447 (push (list :table-table) clist)))
16448 (goto-char p)
16450 ;; Now the small context
16451 (cond
16452 ((org-at-timestamp-p)
16453 (push (org-point-in-group p 0 :timestamp) clist))
16454 ((memq 'org-link faces)
16455 (push (list :link
16456 (previous-single-property-change p 'face)
16457 (next-single-property-change p 'face)) clist))
16458 ((memq 'org-special-keyword faces)
16459 (push (list :keyword
16460 (previous-single-property-change p 'face)
16461 (next-single-property-change p 'face)) clist))
16462 ((org-on-target-p)
16463 (push (org-point-in-group p 0 :target) clist)
16464 (goto-char (1- (match-beginning 0)))
16465 (if (looking-at org-radio-target-regexp)
16466 (push (org-point-in-group p 0 :radio-target) clist))
16467 (goto-char p))
16468 ((setq o (car (delq nil
16469 (mapcar
16470 (lambda (x)
16471 (if (memq x org-latex-fragment-image-overlays) x))
16472 (org-overlays-at (point))))))
16473 (push (list :latex-fragment
16474 (org-overlay-start o) (org-overlay-end o)) clist)
16475 (push (list :latex-preview
16476 (org-overlay-start o) (org-overlay-end o)) clist))
16477 ((org-inside-LaTeX-fragment-p)
16478 ;; FIXME: positions wrong.
16479 (push (list :latex-fragment (point) (point)) clist)))
16481 (setq clist (nreverse (delq nil clist)))
16482 clist))
16484 ;; FIXME: Compare with at-regexp-p Do we need both?
16485 (defun org-in-regexp (re &optional nlines visually)
16486 "Check if point is inside a match of regexp.
16487 Normally only the current line is checked, but you can include NLINES extra
16488 lines both before and after point into the search.
16489 If VISUALLY is set, require that the cursor is not after the match but
16490 really on, so that the block visually is on the match."
16491 (catch 'exit
16492 (let ((pos (point))
16493 (eol (point-at-eol (+ 1 (or nlines 0))))
16494 (inc (if visually 1 0)))
16495 (save-excursion
16496 (beginning-of-line (- 1 (or nlines 0)))
16497 (while (re-search-forward re eol t)
16498 (if (and (<= (match-beginning 0) pos)
16499 (>= (+ inc (match-end 0)) pos))
16500 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16502 (defun org-at-regexp-p (regexp)
16503 "Is point inside a match of REGEXP in the current line?"
16504 (catch 'exit
16505 (save-excursion
16506 (let ((pos (point)) (end (point-at-eol)))
16507 (beginning-of-line 1)
16508 (while (re-search-forward regexp end t)
16509 (if (and (<= (match-beginning 0) pos)
16510 (>= (match-end 0) pos))
16511 (throw 'exit t)))
16512 nil))))
16514 (defun org-occur-in-agenda-files (regexp &optional nlines)
16515 "Call `multi-occur' with buffers for all agenda files."
16516 (interactive "sOrg-files matching: \np")
16517 (let* ((files (org-agenda-files))
16518 (tnames (mapcar 'file-truename files))
16519 (extra org-agenda-text-search-extra-files)
16521 (when (eq (car extra) 'agenda-archives)
16522 (setq extra (cdr extra))
16523 (setq files (org-add-archive-files files)))
16524 (while (setq f (pop extra))
16525 (unless (member (file-truename f) tnames)
16526 (add-to-list 'files f 'append)
16527 (add-to-list 'tnames (file-truename f) 'append)))
16528 (multi-occur
16529 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
16530 regexp)))
16532 (if (boundp 'occur-mode-find-occurrence-hook)
16533 ;; Emacs 23
16534 (add-hook 'occur-mode-find-occurrence-hook
16535 (lambda ()
16536 (when (org-mode-p)
16537 (org-reveal))))
16538 ;; Emacs 22
16539 (defadvice occur-mode-goto-occurrence
16540 (after org-occur-reveal activate)
16541 (and (org-mode-p) (org-reveal)))
16542 (defadvice occur-mode-goto-occurrence-other-window
16543 (after org-occur-reveal activate)
16544 (and (org-mode-p) (org-reveal)))
16545 (defadvice occur-mode-display-occurrence
16546 (after org-occur-reveal activate)
16547 (when (org-mode-p)
16548 (let ((pos (occur-mode-find-occurrence)))
16549 (with-current-buffer (marker-buffer pos)
16550 (save-excursion
16551 (goto-char pos)
16552 (org-reveal)))))))
16554 (defun org-occur-link-in-agenda-files ()
16555 "Create a link and search for it in the agendas.
16556 The link is not stored in `org-stored-links', it is just created
16557 for the search purpose."
16558 (interactive)
16559 (let ((link (condition-case nil
16560 (org-store-link nil)
16561 (error "Unable to create a link to here"))))
16562 (org-occur-in-agenda-files (regexp-quote link))))
16564 (defun org-uniquify (list)
16565 "Remove duplicate elements from LIST."
16566 (let (res)
16567 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16568 res))
16570 (defun org-delete-all (elts list)
16571 "Remove all elements in ELTS from LIST."
16572 (while elts
16573 (setq list (delete (pop elts) list)))
16574 list)
16576 (defun org-back-over-empty-lines ()
16577 "Move backwards over whitespace, to the beginning of the first empty line.
16578 Returns the number of empty lines passed."
16579 (let ((pos (point)))
16580 (skip-chars-backward " \t\n\r")
16581 (beginning-of-line 2)
16582 (goto-char (min (point) pos))
16583 (count-lines (point) pos)))
16585 (defun org-skip-whitespace ()
16586 (skip-chars-forward " \t\n\r"))
16588 (defun org-point-in-group (point group &optional context)
16589 "Check if POINT is in match-group GROUP.
16590 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16591 match. If the match group does ot exist or point is not inside it,
16592 return nil."
16593 (and (match-beginning group)
16594 (>= point (match-beginning group))
16595 (<= point (match-end group))
16596 (if context
16597 (list context (match-beginning group) (match-end group))
16598 t)))
16600 (defun org-switch-to-buffer-other-window (&rest args)
16601 "Switch to buffer in a second window on the current frame.
16602 In particular, do not allow pop-up frames."
16603 (let (pop-up-frames special-display-buffer-names special-display-regexps
16604 special-display-function)
16605 (apply 'switch-to-buffer-other-window args)))
16607 (defun org-combine-plists (&rest plists)
16608 "Create a single property list from all plists in PLISTS.
16609 The process starts by copying the first list, and then setting properties
16610 from the other lists. Settings in the last list are the most significant
16611 ones and overrule settings in the other lists."
16612 (let ((rtn (copy-sequence (pop plists)))
16613 p v ls)
16614 (while plists
16615 (setq ls (pop plists))
16616 (while ls
16617 (setq p (pop ls) v (pop ls))
16618 (setq rtn (plist-put rtn p v))))
16619 rtn))
16621 (defun org-move-line-down (arg)
16622 "Move the current line down. With prefix argument, move it past ARG lines."
16623 (interactive "p")
16624 (let ((col (current-column))
16625 beg end pos)
16626 (beginning-of-line 1) (setq beg (point))
16627 (beginning-of-line 2) (setq end (point))
16628 (beginning-of-line (+ 1 arg))
16629 (setq pos (move-marker (make-marker) (point)))
16630 (insert (delete-and-extract-region beg end))
16631 (goto-char pos)
16632 (org-move-to-column col)))
16634 (defun org-move-line-up (arg)
16635 "Move the current line up. With prefix argument, move it past ARG lines."
16636 (interactive "p")
16637 (let ((col (current-column))
16638 beg end pos)
16639 (beginning-of-line 1) (setq beg (point))
16640 (beginning-of-line 2) (setq end (point))
16641 (beginning-of-line (- arg))
16642 (setq pos (move-marker (make-marker) (point)))
16643 (insert (delete-and-extract-region beg end))
16644 (goto-char pos)
16645 (org-move-to-column col)))
16647 (defun org-replace-escapes (string table)
16648 "Replace %-escapes in STRING with values in TABLE.
16649 TABLE is an association list with keys like \"%a\" and string values.
16650 The sequences in STRING may contain normal field width and padding information,
16651 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
16652 so values can contain further %-escapes if they are define later in TABLE."
16653 (let ((case-fold-search nil)
16654 e re rpl)
16655 (while (setq e (pop table))
16656 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
16657 (while (string-match re string)
16658 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
16659 (cdr e)))
16660 (setq string (replace-match rpl t t string))))
16661 string))
16664 (defun org-sublist (list start end)
16665 "Return a section of LIST, from START to END.
16666 Counting starts at 1."
16667 (let (rtn (c start))
16668 (setq list (nthcdr (1- start) list))
16669 (while (and list (<= c end))
16670 (push (pop list) rtn)
16671 (setq c (1+ c)))
16672 (nreverse rtn)))
16674 (defun org-find-base-buffer-visiting (file)
16675 "Like `find-buffer-visiting' but always return the base buffer and
16676 not an indirect buffer."
16677 (let ((buf (or (get-file-buffer file)
16678 (find-buffer-visiting file))))
16679 (if buf
16680 (or (buffer-base-buffer buf) buf)
16681 nil)))
16683 (defun org-image-file-name-regexp (&optional extensions)
16684 "Return regexp matching the file names of images.
16685 If EXTENSIONS is given, only match these."
16686 (if (and (not extensions) (fboundp 'image-file-name-regexp))
16687 (image-file-name-regexp)
16688 (let ((image-file-name-extensions
16689 (or extensions
16690 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16691 "xbm" "xpm" "pbm" "pgm" "ppm"))))
16692 (concat "\\."
16693 (regexp-opt (nconc (mapcar 'upcase
16694 image-file-name-extensions)
16695 image-file-name-extensions)
16697 "\\'"))))
16699 (defun org-file-image-p (file &optional extensions)
16700 "Return non-nil if FILE is an image."
16701 (save-match-data
16702 (string-match (org-image-file-name-regexp extensions) file)))
16704 (defun org-get-cursor-date ()
16705 "Return the date at cursor in as a time.
16706 This works in the calendar and in the agenda, anywhere else it just
16707 returns the current time."
16708 (let (date day defd)
16709 (cond
16710 ((eq major-mode 'calendar-mode)
16711 (setq date (calendar-cursor-to-date)
16712 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16713 ((eq major-mode 'org-agenda-mode)
16714 (setq day (get-text-property (point) 'day))
16715 (if day
16716 (setq date (calendar-gregorian-from-absolute day)
16717 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
16718 (nth 2 date))))))
16719 (or defd (current-time))))
16721 (defvar org-agenda-action-marker (make-marker)
16722 "Marker pointing to the entry for the next agenda action.")
16724 (defun org-mark-entry-for-agenda-action ()
16725 "Mark the current entry as target of an agenda action.
16726 Agenda actions are actions executed from the agenda with the key `k',
16727 which make use of the date at the cursor."
16728 (interactive)
16729 (move-marker org-agenda-action-marker
16730 (save-excursion (org-back-to-heading t) (point))
16731 (current-buffer))
16732 (message
16733 "Entry marked for action; press `k' at desired date in agenda or calendar"))
16735 ;;; Paragraph filling stuff.
16736 ;; We want this to be just right, so use the full arsenal.
16738 (defun org-indent-line-function ()
16739 "Indent line like previous, but further if previous was headline or item."
16740 (interactive)
16741 (let* ((pos (point))
16742 (itemp (org-at-item-p))
16743 (case-fold-search t)
16744 (org-drawer-regexp (or org-drawer-regexp "\000"))
16745 column bpos bcol tpos tcol bullet btype bullet-type)
16746 ;; Find the previous relevant line
16747 (beginning-of-line 1)
16748 (cond
16749 ((looking-at "#") (setq column 0))
16750 ((looking-at "\\*+ ") (setq column 0))
16751 ((and (looking-at "[ \t]*:END:")
16752 (save-excursion (re-search-backward org-drawer-regexp nil t)))
16753 (save-excursion
16754 (goto-char (1- (match-beginning 1)))
16755 (setq column (current-column))))
16756 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
16757 (save-excursion
16758 (re-search-backward
16759 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
16760 (setq column (org-get-indentation (match-string 0))))
16762 (beginning-of-line 0)
16763 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
16764 (not (looking-at "[ \t]*:END:"))
16765 (not (looking-at org-drawer-regexp)))
16766 (beginning-of-line 0))
16767 (cond
16768 ((looking-at "\\*+[ \t]+")
16769 (if (not org-adapt-indentation)
16770 (setq column 0)
16771 (goto-char (match-end 0))
16772 (setq column (current-column))))
16773 ((looking-at org-drawer-regexp)
16774 (goto-char (1- (match-beginning 1)))
16775 (setq column (current-column)))
16776 ((looking-at "\\([ \t]*\\):END:")
16777 (goto-char (match-end 1))
16778 (setq column (current-column)))
16779 ((org-in-item-p)
16780 (org-beginning-of-item)
16781 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
16782 (setq bpos (match-beginning 1) tpos (match-end 0)
16783 bcol (progn (goto-char bpos) (current-column))
16784 tcol (progn (goto-char tpos) (current-column))
16785 bullet (match-string 1)
16786 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
16787 (if (> tcol (+ bcol org-description-max-indent))
16788 (setq tcol (+ bcol 5)))
16789 (if (not itemp)
16790 (setq column tcol)
16791 (goto-char pos)
16792 (beginning-of-line 1)
16793 (if (looking-at "\\S-")
16794 (progn
16795 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
16796 (setq bullet (match-string 1)
16797 btype (if (string-match "[0-9]" bullet) "n" bullet))
16798 (setq column (if (equal btype bullet-type) bcol tcol)))
16799 (setq column (org-get-indentation)))))
16800 (t (setq column (org-get-indentation))))))
16801 (goto-char pos)
16802 (if (<= (current-column) (current-indentation))
16803 (org-indent-line-to column)
16804 (save-excursion (org-indent-line-to column)))
16805 (setq column (current-column))
16806 (beginning-of-line 1)
16807 (if (looking-at
16808 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16809 (replace-match (concat (match-string 1)
16810 (format org-property-format
16811 (match-string 2) (match-string 3)))
16812 t t))
16813 (org-move-to-column column)))
16815 (defun org-set-autofill-regexps ()
16816 (interactive)
16817 ;; In the paragraph separator we include headlines, because filling
16818 ;; text in a line directly attached to a headline would otherwise
16819 ;; fill the headline as well.
16820 (org-set-local 'comment-start-skip "^#+[ \t]*")
16821 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
16822 ;; The paragraph starter includes hand-formatted lists.
16823 (org-set-local
16824 'paragraph-start
16825 (concat
16826 "\f" "\\|"
16827 "[ ]*$" "\\|"
16828 "\\*+ " "\\|"
16829 "[ \t]*#" "\\|"
16830 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16831 "[ \t]*[:|]" "\\|"
16832 "\\$\\$" "\\|"
16833 "\\\\\\(begin\\|end\\|[][]\\)"))
16834 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16835 ;; But only if the user has not turned off tables or fixed-width regions
16836 (org-set-local
16837 'auto-fill-inhibit-regexp
16838 (concat "\\*+ \\|#\\+"
16839 "\\|[ \t]*" org-keyword-time-regexp
16840 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16841 (concat
16842 "\\|[ \t]*["
16843 (if org-enable-table-editor "|" "")
16844 (if org-enable-fixed-width-editor ":" "")
16845 "]"))))
16846 ;; We use our own fill-paragraph function, to make sure that tables
16847 ;; and fixed-width regions are not wrapped. That function will pass
16848 ;; through to `fill-paragraph' when appropriate.
16849 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16850 ; Adaptive filling: To get full control, first make sure that
16851 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16852 (org-set-local 'adaptive-fill-regexp "\000")
16853 (org-set-local 'adaptive-fill-function
16854 'org-adaptive-fill-function)
16855 (org-set-local
16856 'align-mode-rules-list
16857 '((org-in-buffer-settings
16858 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
16859 (modes . '(org-mode))))))
16861 (defun org-fill-paragraph (&optional justify)
16862 "Re-align a table, pass through to fill-paragraph if no table."
16863 (let ((table-p (org-at-table-p))
16864 (table.el-p (org-at-table.el-p)))
16865 (cond ((and (equal (char-after (point-at-bol)) ?*)
16866 (save-excursion (goto-char (point-at-bol))
16867 (looking-at outline-regexp)))
16868 t) ; skip headlines
16869 (table.el-p t) ; skip table.el tables
16870 (table-p (org-table-align) t) ; align org-mode tables
16871 (t nil)))) ; call paragraph-fill
16873 ;; For reference, this is the default value of adaptive-fill-regexp
16874 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16876 (defun org-adaptive-fill-function ()
16877 "Return a fill prefix for org-mode files.
16878 In particular, this makes sure hanging paragraphs for hand-formatted lists
16879 work correctly."
16880 (cond ((looking-at "#[ \t]+")
16881 (match-string 0))
16882 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
16883 (save-excursion
16884 (if (> (match-end 1) (+ (match-beginning 1)
16885 org-description-max-indent))
16886 (goto-char (+ (match-beginning 1) 5))
16887 (goto-char (match-end 0)))
16888 (make-string (current-column) ?\ )))
16889 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
16890 (save-excursion
16891 (goto-char (match-end 0))
16892 (make-string (current-column) ?\ )))
16893 (t nil)))
16895 ;;; Other stuff.
16897 (defun org-toggle-fixed-width-section (arg)
16898 "Toggle the fixed-width export.
16899 If there is no active region, the QUOTE keyword at the current headline is
16900 inserted or removed. When present, it causes the text between this headline
16901 and the next to be exported as fixed-width text, and unmodified.
16902 If there is an active region, this command adds or removes a colon as the
16903 first character of this line. If the first character of a line is a colon,
16904 this line is also exported in fixed-width font."
16905 (interactive "P")
16906 (let* ((cc 0)
16907 (regionp (org-region-active-p))
16908 (beg (if regionp (region-beginning) (point)))
16909 (end (if regionp (region-end)))
16910 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
16911 (case-fold-search nil)
16912 (re "[ \t]*\\(: \\)")
16913 off)
16914 (if regionp
16915 (save-excursion
16916 (goto-char beg)
16917 (setq cc (current-column))
16918 (beginning-of-line 1)
16919 (setq off (looking-at re))
16920 (while (> nlines 0)
16921 (setq nlines (1- nlines))
16922 (beginning-of-line 1)
16923 (cond
16924 (arg
16925 (org-move-to-column cc t)
16926 (insert ": \n")
16927 (forward-line -1))
16928 ((and off (looking-at re))
16929 (replace-match "" t t nil 1))
16930 ((not off) (org-move-to-column cc t) (insert ": ")))
16931 (forward-line 1)))
16932 (save-excursion
16933 (org-back-to-heading)
16934 (if (looking-at (concat outline-regexp
16935 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
16936 (replace-match "" t t nil 1)
16937 (if (looking-at outline-regexp)
16938 (progn
16939 (goto-char (match-end 0))
16940 (insert org-quote-string " "))))))))
16942 (defun org-reftex-citation ()
16943 "Use reftex-citation to insert a citation into the buffer.
16944 This looks for a line like
16946 #+BIBLIOGRAPHY: foo plain option:-d
16948 and derives from it that foo.bib is the bbliography file relevant
16949 for this document. It then installs the necessary environment for RefTeX
16950 to work in this buffer and calls `reftex-citation' to insert a citation
16951 into the buffer.
16953 Export of such citations to both LaTeX and HTML is handled by the contributed
16954 package org-exp-bibtex by Taru Karttunen."
16955 (interactive)
16956 (let ((reftex-docstruct-symbol 'rds)
16957 (reftex-cite-format "\\cite{%l}")
16958 rds bib)
16959 (save-excursion
16960 (save-restriction
16961 (widen)
16962 (let ((case-fold-search t)
16963 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
16964 (if (not (save-excursion
16965 (or (re-search-forward re nil t)
16966 (re-search-backward re nil t))))
16967 (error "No bibliography defined in file")
16968 (setq bib (concat (match-string 1) ".bib")
16969 rds (list (list 'bib bib)))))))
16970 (call-interactively 'reftex-citation)))
16972 ;;;; Functions extending outline functionality
16974 (defun org-beginning-of-line (&optional arg)
16975 "Go to the beginning of the current line. If that is invisible, continue
16976 to a visible line beginning. This makes the function of C-a more intuitive.
16977 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16978 first attempt, and only move to after the tags when the cursor is already
16979 beyond the end of the headline."
16980 (interactive "P")
16981 (let ((pos (point))
16982 (special (if (consp org-special-ctrl-a/e)
16983 (car org-special-ctrl-a/e)
16984 org-special-ctrl-a/e))
16985 refpos)
16986 (if (org-bound-and-true-p line-move-visual)
16987 (beginning-of-visual-line 1)
16988 (beginning-of-line 1))
16989 (if (and arg (fboundp 'move-beginning-of-line))
16990 (call-interactively 'move-beginning-of-line)
16991 (if (bobp)
16993 (backward-char 1)
16994 (if (org-invisible-p)
16995 (while (and (not (bobp)) (org-invisible-p))
16996 (backward-char 1)
16997 (beginning-of-line 1))
16998 (forward-char 1))))
16999 (when special
17000 (cond
17001 ((and (looking-at org-complex-heading-regexp)
17002 (= (char-after (match-end 1)) ?\ ))
17003 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17004 (point-at-eol)))
17005 (goto-char
17006 (if (eq special t)
17007 (cond ((> pos refpos) refpos)
17008 ((= pos (point)) refpos)
17009 (t (point)))
17010 (cond ((> pos (point)) (point))
17011 ((not (eq last-command this-command)) (point))
17012 (t refpos)))))
17013 ((org-at-item-p)
17014 (goto-char
17015 (if (eq special t)
17016 (cond ((> pos (match-end 4)) (match-end 4))
17017 ((= pos (point)) (match-end 4))
17018 (t (point)))
17019 (cond ((> pos (point)) (point))
17020 ((not (eq last-command this-command)) (point))
17021 (t (match-end 4))))))))
17022 (org-no-warnings
17023 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17025 (defun org-end-of-line (&optional arg)
17026 "Go to the end of the line.
17027 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17028 first attempt, and only move to after the tags when the cursor is already
17029 beyond the end of the headline."
17030 (interactive "P")
17031 (let ((special (if (consp org-special-ctrl-a/e)
17032 (cdr org-special-ctrl-a/e)
17033 org-special-ctrl-a/e)))
17034 (if (or (not special)
17035 (not (org-on-heading-p))
17036 arg)
17037 (call-interactively
17038 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17039 ((fboundp 'move-end-of-line) 'move-end-of-line)
17040 (t 'end-of-line)))
17041 (let ((pos (point)))
17042 (beginning-of-line 1)
17043 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17044 (if (eq special t)
17045 (if (or (< pos (match-beginning 1))
17046 (= pos (match-end 0)))
17047 (goto-char (match-beginning 1))
17048 (goto-char (match-end 0)))
17049 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17050 (goto-char (match-end 0))
17051 (goto-char (match-beginning 1))))
17052 (call-interactively (if (fboundp 'move-end-of-line)
17053 'move-end-of-line
17054 'end-of-line)))))
17055 (org-no-warnings
17056 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17058 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17059 (define-key org-mode-map "\C-e" 'org-end-of-line)
17060 (define-key org-mode-map [home] 'org-beginning-of-line)
17061 (define-key org-mode-map [end] 'org-end-of-line)
17063 (defun org-backward-sentence (&optional arg)
17064 "Go to beginning of sentence, or beginning of table field.
17065 This will call `backward-sentence' or `org-table-beginning-of-field',
17066 depending on context."
17067 (interactive "P")
17068 (cond
17069 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17070 (t (call-interactively 'backward-sentence))))
17072 (defun org-forward-sentence (&optional arg)
17073 "Go to end of sentence, or end of table field.
17074 This will call `forward-sentence' or `org-table-end-of-field',
17075 depending on context."
17076 (interactive "P")
17077 (cond
17078 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17079 (t (call-interactively 'forward-sentence))))
17081 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17082 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17084 (defun org-kill-line (&optional arg)
17085 "Kill line, to tags or end of line."
17086 (interactive "P")
17087 (cond
17088 ((or (not org-special-ctrl-k)
17089 (bolp)
17090 (not (org-on-heading-p)))
17091 (call-interactively 'kill-line))
17092 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17093 (kill-region (point) (match-beginning 1))
17094 (org-set-tags nil t))
17095 (t (kill-region (point) (point-at-eol)))))
17097 (define-key org-mode-map "\C-k" 'org-kill-line)
17099 (defun org-yank (&optional arg)
17100 "Yank. If the kill is a subtree, treat it specially.
17101 This command will look at the current kill and check if is a single
17102 subtree, or a series of subtrees[1]. If it passes the test, and if the
17103 cursor is at the beginning of a line or after the stars of a currently
17104 empty headline, then the yank is handled specially. How exactly depends
17105 on the value of the following variables, both set by default.
17107 org-yank-folded-subtrees
17108 When set, the subtree(s) will be folded after insertion, but only
17109 if doing so would now swallow text after the yanked text.
17111 org-yank-adjusted-subtrees
17112 When set, the subtree will be promoted or demoted in order to
17113 fit into the local outline tree structure, which means that the level
17114 will be adjusted so that it becomes the smaller one of the two
17115 *visible* surrounding headings.
17117 Any prefix to this command will cause `yank' to be called directly with
17118 no special treatment. In particular, a simple `C-u' prefix will just
17119 plainly yank the text as it is.
17121 \[1] The test checks if the first non-white line is a heading
17122 and if there are no other headings with fewer stars."
17123 (interactive "P")
17124 (org-yank-generic 'yank arg))
17126 (defun org-yank-generic (command arg)
17127 "Perform some yank-like command.
17129 This function implements the behavior described in the `org-yank'
17130 documentation. However, it has been generalized to work for any
17131 interactive command with similar behavior."
17133 ;; pretend to be command COMMAND
17134 (setq this-command command)
17136 (if arg
17137 (call-interactively command)
17139 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17140 (and (org-kill-is-subtree-p)
17141 (or (bolp)
17142 (and (looking-at "[ \t]*$")
17143 (string-match
17144 "\\`\\*+\\'"
17145 (buffer-substring (point-at-bol) (point)))))))
17146 swallowp)
17147 (cond
17148 ((and subtreep org-yank-folded-subtrees)
17149 (let ((beg (point))
17150 end)
17151 (if (and subtreep org-yank-adjusted-subtrees)
17152 (org-paste-subtree nil nil 'for-yank)
17153 (call-interactively command))
17155 (setq end (point))
17156 (goto-char beg)
17157 (when (and (bolp) subtreep
17158 (not (setq swallowp
17159 (org-yank-folding-would-swallow-text beg end))))
17160 (or (looking-at outline-regexp)
17161 (re-search-forward (concat "^" outline-regexp) end t))
17162 (while (and (< (point) end) (looking-at outline-regexp))
17163 (hide-subtree)
17164 (org-cycle-show-empty-lines 'folded)
17165 (condition-case nil
17166 (outline-forward-same-level 1)
17167 (error (goto-char end)))))
17168 (when swallowp
17169 (message
17170 "Inserted text not folded because that would swallow text"))
17172 (goto-char end)
17173 (skip-chars-forward " \t\n\r")
17174 (beginning-of-line 1)
17175 (push-mark beg 'nomsg)))
17176 ((and subtreep org-yank-adjusted-subtrees)
17177 (let ((beg (point-at-bol)))
17178 (org-paste-subtree nil nil 'for-yank)
17179 (push-mark beg 'nomsg)))
17181 (call-interactively command))))))
17183 (defun org-yank-folding-would-swallow-text (beg end)
17184 "Would hide-subtree at BEG swallow any text after END?"
17185 (let (level)
17186 (save-excursion
17187 (goto-char beg)
17188 (when (or (looking-at outline-regexp)
17189 (re-search-forward (concat "^" outline-regexp) end t))
17190 (setq level (org-outline-level)))
17191 (goto-char end)
17192 (skip-chars-forward " \t\r\n\v\f")
17193 (if (or (eobp)
17194 (and (bolp) (looking-at org-outline-regexp)
17195 (<= (org-outline-level) level)))
17196 nil ; Nothing would be swallowed
17197 t)))) ; something would swallow
17199 (define-key org-mode-map "\C-y" 'org-yank)
17201 (defun org-invisible-p ()
17202 "Check if point is at a character currently not visible."
17203 ;; Early versions of noutline don't have `outline-invisible-p'.
17204 (if (fboundp 'outline-invisible-p)
17205 (outline-invisible-p)
17206 (get-char-property (point) 'invisible)))
17208 (defun org-invisible-p2 ()
17209 "Check if point is at a character currently not visible."
17210 (save-excursion
17211 (if (and (eolp) (not (bobp))) (backward-char 1))
17212 ;; Early versions of noutline don't have `outline-invisible-p'.
17213 (if (fboundp 'outline-invisible-p)
17214 (outline-invisible-p)
17215 (get-char-property (point) 'invisible))))
17217 (defun org-back-to-heading (&optional invisible-ok)
17218 "Call `outline-back-to-heading', but provide a better error message."
17219 (condition-case nil
17220 (outline-back-to-heading invisible-ok)
17221 (error (error "Before first headline at position %d in buffer %s"
17222 (point) (current-buffer)))))
17224 (defun org-before-first-heading-p ()
17225 "Before first heading?"
17226 (save-excursion
17227 (null (re-search-backward "^\\*+ " nil t))))
17229 (defun org-on-heading-p (&optional ignored)
17230 (outline-on-heading-p t))
17231 (defun org-at-heading-p (&optional ignored)
17232 (outline-on-heading-p t))
17234 (defun org-at-heading-or-item-p ()
17235 (or (org-on-heading-p) (org-at-item-p)))
17237 (defun org-on-target-p ()
17238 (or (org-in-regexp org-radio-target-regexp)
17239 (org-in-regexp org-target-regexp)))
17241 (defun org-up-heading-all (arg)
17242 "Move to the heading line of which the present line is a subheading.
17243 This function considers both visible and invisible heading lines.
17244 With argument, move up ARG levels."
17245 (if (fboundp 'outline-up-heading-all)
17246 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17247 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17249 (defun org-up-heading-safe ()
17250 "Move to the heading line of which the present line is a subheading.
17251 This version will not throw an error. It will return the level of the
17252 headline found, or nil if no higher level is found.
17254 Also, this function will be a lot faster than `outline-up-heading',
17255 because it relies on stars being the outline starters. This can really
17256 make a significant difference in outlines with very many siblings."
17257 (let (start-level re)
17258 (org-back-to-heading t)
17259 (setq start-level (funcall outline-level))
17260 (if (equal start-level 1)
17262 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17263 (if (re-search-backward re nil t)
17264 (funcall outline-level)))))
17266 (defun org-first-sibling-p ()
17267 "Is this heading the first child of its parents?"
17268 (interactive)
17269 (let ((re (concat "^" outline-regexp))
17270 level l)
17271 (unless (org-at-heading-p t)
17272 (error "Not at a heading"))
17273 (setq level (funcall outline-level))
17274 (save-excursion
17275 (if (not (re-search-backward re nil t))
17277 (setq l (funcall outline-level))
17278 (< l level)))))
17280 (defun org-goto-sibling (&optional previous)
17281 "Goto the next sibling, even if it is invisible.
17282 When PREVIOUS is set, go to the previous sibling instead. Returns t
17283 when a sibling was found. When none is found, return nil and don't
17284 move point."
17285 (let ((fun (if previous 're-search-backward 're-search-forward))
17286 (pos (point))
17287 (re (concat "^" outline-regexp))
17288 level l)
17289 (when (condition-case nil (org-back-to-heading t) (error nil))
17290 (setq level (funcall outline-level))
17291 (catch 'exit
17292 (or previous (forward-char 1))
17293 (while (funcall fun re nil t)
17294 (setq l (funcall outline-level))
17295 (when (< l level) (goto-char pos) (throw 'exit nil))
17296 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17297 (goto-char pos)
17298 nil))))
17300 (defun org-show-siblings ()
17301 "Show all siblings of the current headline."
17302 (save-excursion
17303 (while (org-goto-sibling) (org-flag-heading nil)))
17304 (save-excursion
17305 (while (org-goto-sibling 'previous)
17306 (org-flag-heading nil))))
17308 (defun org-show-hidden-entry ()
17309 "Show an entry where even the heading is hidden."
17310 (save-excursion
17311 (org-show-entry)))
17313 (defun org-flag-heading (flag &optional entry)
17314 "Flag the current heading. FLAG non-nil means make invisible.
17315 When ENTRY is non-nil, show the entire entry."
17316 (save-excursion
17317 (org-back-to-heading t)
17318 ;; Check if we should show the entire entry
17319 (if entry
17320 (progn
17321 (org-show-entry)
17322 (save-excursion
17323 (and (outline-next-heading)
17324 (org-flag-heading nil))))
17325 (outline-flag-region (max (point-min) (1- (point)))
17326 (save-excursion (outline-end-of-heading) (point))
17327 flag))))
17329 (defun org-get-next-sibling ()
17330 "Move to next heading of the same level, and return point.
17331 If there is no such heading, return nil.
17332 This is like outline-next-sibling, but invisible headings are ok."
17333 (let ((level (funcall outline-level)))
17334 (outline-next-heading)
17335 (while (and (not (eobp)) (> (funcall outline-level) level))
17336 (outline-next-heading))
17337 (if (or (eobp) (< (funcall outline-level) level))
17339 (point))))
17341 (defun org-get-last-sibling ()
17342 "Move to previous heading of the same level, and return point.
17343 If there is no such heading, return nil."
17344 (let ((opoint (point))
17345 (level (funcall outline-level)))
17346 (outline-previous-heading)
17347 (when (and (/= (point) opoint) (outline-on-heading-p t))
17348 (while (and (> (funcall outline-level) level)
17349 (not (bobp)))
17350 (outline-previous-heading))
17351 (if (< (funcall outline-level) level)
17353 (point)))))
17355 (defun org-end-of-subtree (&optional invisible-OK to-heading)
17356 ;; This contains an exact copy of the original function, but it uses
17357 ;; `org-back-to-heading', to make it work also in invisible
17358 ;; trees. And is uses an invisible-OK argument.
17359 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17360 ;; Furthermore, when used inside Org, finding the end of a large subtree
17361 ;; with many children and grandchildren etc, this can be much faster
17362 ;; than the outline version.
17363 (org-back-to-heading invisible-OK)
17364 (let ((first t)
17365 (level (funcall outline-level)))
17366 (if (and (org-mode-p) (< level 1000))
17367 ;; A true heading (not a plain list item), in Org-mode
17368 ;; This means we can easily find the end by looking
17369 ;; only for the right number of stars. Using a regexp to do
17370 ;; this is so much faster than using a Lisp loop.
17371 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
17372 (forward-char 1)
17373 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
17374 ;; something else, do it the slow way
17375 (while (and (not (eobp))
17376 (or first (> (funcall outline-level) level)))
17377 (setq first nil)
17378 (outline-next-heading)))
17379 (unless to-heading
17380 (if (memq (preceding-char) '(?\n ?\^M))
17381 (progn
17382 ;; Go to end of line before heading
17383 (forward-char -1)
17384 (if (memq (preceding-char) '(?\n ?\^M))
17385 ;; leave blank line before heading
17386 (forward-char -1))))))
17387 (point))
17389 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
17390 "Use Org version in org-mode, for dramatic speed-up."
17391 (if (eq major-mode 'org-mode)
17392 (progn
17393 (org-end-of-subtree nil t)
17394 (unless (eobp) (backward-char 1)))
17395 ad-do-it))
17397 (defun org-forward-same-level (arg &optional invisible-ok)
17398 "Move forward to the arg'th subheading at same level as this one.
17399 Stop at the first and last subheadings of a superior heading."
17400 (interactive "p")
17401 (org-back-to-heading invisible-ok)
17402 (org-on-heading-p)
17403 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17404 (re (format "^\\*\\{1,%d\\} " level))
17406 (forward-char 1)
17407 (while (> arg 0)
17408 (while (and (re-search-forward re nil 'move)
17409 (setq l (- (match-end 0) (match-beginning 0) 1))
17410 (= l level)
17411 (not invisible-ok)
17412 (org-invisible-p))
17413 (if (< l level) (setq arg 1)))
17414 (setq arg (1- arg)))
17415 (beginning-of-line 1)))
17417 (defun org-backward-same-level (arg &optional invisible-ok)
17418 "Move backward to the arg'th subheading at same level as this one.
17419 Stop at the first and last subheadings of a superior heading."
17420 (interactive "p")
17421 (org-back-to-heading)
17422 (org-on-heading-p)
17423 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17424 (re (format "^\\*\\{1,%d\\} " level))
17426 (while (> arg 0)
17427 (while (and (re-search-backward re nil 'move)
17428 (setq l (- (match-end 0) (match-beginning 0) 1))
17429 (= l level)
17430 (not invisible-ok)
17431 (org-invisible-p))
17432 (if (< l level) (setq arg 1)))
17433 (setq arg (1- arg)))))
17435 (defun org-show-subtree ()
17436 "Show everything after this heading at deeper levels."
17437 (outline-flag-region
17438 (point)
17439 (save-excursion
17440 (org-end-of-subtree t t))
17441 nil))
17443 (defun org-show-entry ()
17444 "Show the body directly following this heading.
17445 Show the heading too, if it is currently invisible."
17446 (interactive)
17447 (save-excursion
17448 (condition-case nil
17449 (progn
17450 (org-back-to-heading t)
17451 (outline-flag-region
17452 (max (point-min) (1- (point)))
17453 (save-excursion
17454 (if (re-search-forward
17455 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17456 (match-beginning 1)
17457 (point-max)))
17458 nil)
17459 (org-cycle-hide-drawers 'children))
17460 (error nil))))
17462 (defun org-make-options-regexp (kwds &optional extra)
17463 "Make a regular expression for keyword lines."
17464 (concat
17466 "#?[ \t]*\\+\\("
17467 (mapconcat 'regexp-quote kwds "\\|")
17468 (if extra (concat "\\|" extra))
17469 "\\):[ \t]*"
17470 "\\(.*\\)"))
17472 ;; Make isearch reveal the necessary context
17473 (defun org-isearch-end ()
17474 "Reveal context after isearch exits."
17475 (when isearch-success ; only if search was successful
17476 (if (featurep 'xemacs)
17477 ;; Under XEmacs, the hook is run in the correct place,
17478 ;; we directly show the context.
17479 (org-show-context 'isearch)
17480 ;; In Emacs the hook runs *before* restoring the overlays.
17481 ;; So we have to use a one-time post-command-hook to do this.
17482 ;; (Emacs 22 has a special variable, see function `org-mode')
17483 (unless (and (boundp 'isearch-mode-end-hook-quit)
17484 isearch-mode-end-hook-quit)
17485 ;; Only when the isearch was not quitted.
17486 (org-add-hook 'post-command-hook 'org-isearch-post-command
17487 'append 'local)))))
17489 (defun org-isearch-post-command ()
17490 "Remove self from hook, and show context."
17491 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17492 (org-show-context 'isearch))
17495 ;;;; Integration with and fixes for other packages
17497 ;;; Imenu support
17499 (defvar org-imenu-markers nil
17500 "All markers currently used by Imenu.")
17501 (make-variable-buffer-local 'org-imenu-markers)
17503 (defun org-imenu-new-marker (&optional pos)
17504 "Return a new marker for use by Imenu, and remember the marker."
17505 (let ((m (make-marker)))
17506 (move-marker m (or pos (point)))
17507 (push m org-imenu-markers)
17510 (defun org-imenu-get-tree ()
17511 "Produce the index for Imenu."
17512 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17513 (setq org-imenu-markers nil)
17514 (let* ((n org-imenu-depth)
17515 (re (concat "^" outline-regexp))
17516 (subs (make-vector (1+ n) nil))
17517 (last-level 0)
17518 m level head)
17519 (save-excursion
17520 (save-restriction
17521 (widen)
17522 (goto-char (point-max))
17523 (while (re-search-backward re nil t)
17524 (setq level (org-reduced-level (funcall outline-level)))
17525 (when (<= level n)
17526 (looking-at org-complex-heading-regexp)
17527 (setq head (org-link-display-format
17528 (org-match-string-no-properties 4))
17529 m (org-imenu-new-marker))
17530 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17531 (if (>= level last-level)
17532 (push (cons head m) (aref subs level))
17533 (push (cons head (aref subs (1+ level))) (aref subs level))
17534 (loop for i from (1+ level) to n do (aset subs i nil)))
17535 (setq last-level level)))))
17536 (aref subs 1)))
17538 (eval-after-load "imenu"
17539 '(progn
17540 (add-hook 'imenu-after-jump-hook
17541 (lambda ()
17542 (if (eq major-mode 'org-mode)
17543 (org-show-context 'org-goto))))))
17545 (defun org-link-display-format (link)
17546 "Replace a link with either the description, or the link target
17547 if no description is present"
17548 (save-match-data
17549 (if (string-match org-bracket-link-analytic-regexp link)
17550 (replace-match (or (match-string 5 link)
17551 (concat (match-string 1 link)
17552 (match-string 3 link)))
17553 nil nil link)
17554 link)))
17556 ;; Speedbar support
17558 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17559 "Overlay marking the agenda restriction line in speedbar.")
17560 (org-overlay-put org-speedbar-restriction-lock-overlay
17561 'face 'org-agenda-restriction-lock)
17562 (org-overlay-put org-speedbar-restriction-lock-overlay
17563 'help-echo "Agendas are currently limited to this item.")
17564 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17566 (defun org-speedbar-set-agenda-restriction ()
17567 "Restrict future agenda commands to the location at point in speedbar.
17568 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17569 (interactive)
17570 (require 'org-agenda)
17571 (let (p m tp np dir txt)
17572 (cond
17573 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17574 'org-imenu t))
17575 (setq m (get-text-property p 'org-imenu-marker))
17576 (with-current-buffer (marker-buffer m)
17577 (goto-char m)
17578 (org-agenda-set-restriction-lock 'subtree)))
17579 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17580 'speedbar-function 'speedbar-find-file))
17581 (setq tp (previous-single-property-change
17582 (1+ p) 'speedbar-function)
17583 np (next-single-property-change
17584 tp 'speedbar-function)
17585 dir (speedbar-line-directory)
17586 txt (buffer-substring-no-properties (or tp (point-min))
17587 (or np (point-max))))
17588 (with-current-buffer (find-file-noselect
17589 (let ((default-directory dir))
17590 (expand-file-name txt)))
17591 (unless (org-mode-p)
17592 (error "Cannot restrict to non-Org-mode file"))
17593 (org-agenda-set-restriction-lock 'file)))
17594 (t (error "Don't know how to restrict Org-mode's agenda")))
17595 (org-move-overlay org-speedbar-restriction-lock-overlay
17596 (point-at-bol) (point-at-eol))
17597 (setq current-prefix-arg nil)
17598 (org-agenda-maybe-redo)))
17600 (eval-after-load "speedbar"
17601 '(progn
17602 (speedbar-add-supported-extension ".org")
17603 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
17604 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
17605 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
17606 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17607 (add-hook 'speedbar-visiting-tag-hook
17608 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
17611 ;;; Fixes and Hacks for problems with other packages
17613 ;; Make flyspell not check words in links, to not mess up our keymap
17614 (defun org-mode-flyspell-verify ()
17615 "Don't let flyspell put overlays at active buttons."
17616 (and (not (get-text-property (point) 'keymap))
17617 (not (get-text-property (point) 'org-no-flyspell))))
17619 (defun org-remove-flyspell-overlays-in (beg end)
17620 "Remove flyspell overlays in region."
17621 (and (org-bound-and-true-p flyspell-mode)
17622 (fboundp 'flyspell-delete-region-overlays)
17623 (flyspell-delete-region-overlays beg end))
17624 (add-text-properties beg end '(org-no-flyspell t)))
17626 ;; Make `bookmark-jump' shows the jump location if it was hidden.
17627 (eval-after-load "bookmark"
17628 '(if (boundp 'bookmark-after-jump-hook)
17629 ;; We can use the hook
17630 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17631 ;; Hook not available, use advice
17632 (defadvice bookmark-jump (after org-make-visible activate)
17633 "Make the position visible."
17634 (org-bookmark-jump-unhide))))
17636 ;; Make sure saveplace shows the location if it was hidden
17637 (eval-after-load "saveplace"
17638 '(defadvice save-place-find-file-hook (after org-make-visible activate)
17639 "Make the position visible."
17640 (org-bookmark-jump-unhide)))
17642 ;; Make sure ecb shows the location if it was hidden
17643 (eval-after-load "ecb"
17644 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
17645 "Make hierarchy visible when jumping into location from ECB tree buffer."
17646 (if (eq major-mode 'org-mode)
17647 (org-show-context))))
17649 (defun org-bookmark-jump-unhide ()
17650 "Unhide the current position, to show the bookmark location."
17651 (and (org-mode-p)
17652 (or (org-invisible-p)
17653 (save-excursion (goto-char (max (point-min) (1- (point))))
17654 (org-invisible-p)))
17655 (org-show-context 'bookmark-jump)))
17657 ;; Make session.el ignore our circular variable
17658 (eval-after-load "session"
17659 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17661 ;;;; Experimental code
17663 (defun org-closed-in-range ()
17664 "Sparse tree of items closed in a certain time range.
17665 Still experimental, may disappear in the future."
17666 (interactive)
17667 ;; Get the time interval from the user.
17668 (let* ((time1 (org-float-time
17669 (org-read-date nil 'to-time nil "Starting date: ")))
17670 (time2 (org-float-time
17671 (org-read-date nil 'to-time nil "End date:")))
17672 ;; callback function
17673 (callback (lambda ()
17674 (let ((time
17675 (org-float-time
17676 (apply 'encode-time
17677 (org-parse-time-string
17678 (match-string 1))))))
17679 ;; check if time in interval
17680 (and (>= time time1) (<= time time2))))))
17681 ;; make tree, check each match with the callback
17682 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
17684 ;;;; Finish up
17686 (provide 'org)
17688 (run-hooks 'org-load-hook)
17690 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17692 ;;; org.el ends here