Make `i' key in agenda and calendar add new entries to an org file
[org-mode.git] / lisp / org.el
blob803aa7fc2f72c9a849bb944c4c53b189893e3124
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 a closing 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 closing 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-note-clock-out nil
1978 "Non-nil means, record a note when clocking out of an item.
1979 This can also be configured on a per-file basis by adding one of
1980 the following lines anywhere in the buffer:
1982 #+STARTUP: lognoteclock-out
1983 #+STARTUP: nolognoteclock-out"
1984 :group 'org-todo
1985 :group 'org-progress
1986 :type 'boolean)
1988 (defcustom org-log-done-with-time t
1989 "Non-nil means, the CLOSED time stamp will contain date and time.
1990 When nil, only the date will be recorded."
1991 :group 'org-progress
1992 :type 'boolean)
1994 (defcustom org-log-note-headings
1995 '((done . "CLOSING NOTE %t")
1996 (state . "State %-12s from %-12S %t")
1997 (note . "Note taken on %t")
1998 (clock-out . ""))
1999 "Headings for notes added to entries.
2000 The value is an alist, with the car being a symbol indicating the note
2001 context, and the cdr is the heading to be used. The heading may also be the
2002 empty string.
2003 %t in the heading will be replaced by a time stamp.
2004 %s will be replaced by the new TODO state, in double quotes.
2005 %S will be replaced by the old TODO state, in double quotes.
2006 %u will be replaced by the user name.
2007 %U will be replaced by the full user name."
2008 :group 'org-todo
2009 :group 'org-progress
2010 :type '(list :greedy t
2011 (cons (const :tag "Heading when closing an item" done) string)
2012 (cons (const :tag
2013 "Heading when changing todo state (todo sequence only)"
2014 state) string)
2015 (cons (const :tag "Heading when just taking a note" note) string)
2016 (cons (const :tag "Heading when clocking out" clock-out) string)))
2018 (unless (assq 'note org-log-note-headings)
2019 (push '(note . "%t") org-log-note-headings))
2021 (defcustom org-log-into-drawer nil
2022 "Non-nil means, insert state change notes and time stamps into a drawer.
2023 When nil, state changes notes will be inserted after the headline and
2024 any scheduling and clock lines, but not inside a drawer.
2026 The value of this variable should be the name of the drawer to use.
2027 LOGBOOK is proposed at the default drawer for this purpose, you can
2028 also set this to a string to define the drawer of your choice.
2030 A value of t is also allowed, representing \"LOGBOOK\".
2032 If this variable is set, `org-log-state-notes-insert-after-drawers'
2033 will be ignored.
2035 You can set the property LOG_INTO_DRAWER to overrule this setting for
2036 a subtree."
2037 :group 'org-todo
2038 :group 'org-progress
2039 :type '(choice
2040 (const :tag "Not into a drawer" nil)
2041 (const :tag "LOGBOOK" t)
2042 (string :tag "Other")))
2044 (if (fboundp 'defvaralias)
2045 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2047 (defun org-log-into-drawer ()
2048 "Return the value of `org-log-into-drawer', but let properties overrule.
2049 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2050 used instead of the default value."
2051 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2052 (cond
2053 ((or (not p) (equal p "nil")) org-log-into-drawer)
2054 ((equal p "t") "LOGBOOK")
2055 (t p))))
2057 (defcustom org-log-state-notes-insert-after-drawers nil
2058 "Non-nil means, insert state change notes after any drawers in entry.
2059 Only the drawers that *immediately* follow the headline and the
2060 deadline/scheduled line are skipped.
2061 When nil, insert notes right after the heading and perhaps the line
2062 with deadline/scheduling if present.
2064 This variable will have no effect if `org-log-into-drawer' is
2065 set."
2066 :group 'org-todo
2067 :group 'org-progress
2068 :type 'boolean)
2070 (defcustom org-log-states-order-reversed t
2071 "Non-nil means, the latest state change note will be directly after heading.
2072 When nil, the notes will be orderer according to time."
2073 :group 'org-todo
2074 :group 'org-progress
2075 :type 'boolean)
2077 (defcustom org-log-repeat 'time
2078 "Non-nil means, record moving through the DONE state when triggering repeat.
2079 An auto-repeating task is immediately switched back to TODO when
2080 marked DONE. If you are not logging state changes (by adding \"@\"
2081 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2082 record a closing note, there will be no record of the task moving
2083 through DONE. This variable forces taking a note anyway.
2085 nil Don't force a record
2086 time Record a time stamp
2087 note Record a note
2089 This option can also be set with on a per-file-basis with
2091 #+STARTUP: logrepeat
2092 #+STARTUP: lognoterepeat
2093 #+STARTUP: nologrepeat
2095 You can have local logging settings for a subtree by setting the LOGGING
2096 property to one or more of these keywords."
2097 :group 'org-todo
2098 :group 'org-progress
2099 :type '(choice
2100 (const :tag "Don't force a record" nil)
2101 (const :tag "Force recording the DONE state" time)
2102 (const :tag "Force recording a note with the DONE state" note)))
2105 (defgroup org-priorities nil
2106 "Priorities in Org-mode."
2107 :tag "Org Priorities"
2108 :group 'org-todo)
2110 (defcustom org-enable-priority-commands t
2111 "Non-nil means, priority commands are active.
2112 When nil, these commands will be disabled, so that you never accidentally
2113 set a priority."
2114 :group 'org-priorities
2115 :type 'boolean)
2117 (defcustom org-highest-priority ?A
2118 "The highest priority of TODO items. A character like ?A, ?B etc.
2119 Must have a smaller ASCII number than `org-lowest-priority'."
2120 :group 'org-priorities
2121 :type 'character)
2123 (defcustom org-lowest-priority ?C
2124 "The lowest priority of TODO items. A character like ?A, ?B etc.
2125 Must have a larger ASCII number than `org-highest-priority'."
2126 :group 'org-priorities
2127 :type 'character)
2129 (defcustom org-default-priority ?B
2130 "The default priority of TODO items.
2131 This is the priority an item get if no explicit priority is given."
2132 :group 'org-priorities
2133 :type 'character)
2135 (defcustom org-priority-start-cycle-with-default t
2136 "Non-nil means, start with default priority when starting to cycle.
2137 When this is nil, the first step in the cycle will be (depending on the
2138 command used) one higher or lower that the default priority."
2139 :group 'org-priorities
2140 :type 'boolean)
2142 (defgroup org-time nil
2143 "Options concerning time stamps and deadlines in Org-mode."
2144 :tag "Org Time"
2145 :group 'org)
2147 (defcustom org-insert-labeled-timestamps-at-point nil
2148 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2149 When nil, these labeled time stamps are forces into the second line of an
2150 entry, just after the headline. When scheduling from the global TODO list,
2151 the time stamp will always be forced into the second line."
2152 :group 'org-time
2153 :type 'boolean)
2155 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2156 "Formats for `format-time-string' which are used for time stamps.
2157 It is not recommended to change this constant.")
2159 (defcustom org-time-stamp-rounding-minutes '(0 5)
2160 "Number of minutes to round time stamps to.
2161 These are two values, the first applies when first creating a time stamp.
2162 The second applies when changing it with the commands `S-up' and `S-down'.
2163 When changing the time stamp, this means that it will change in steps
2164 of N minutes, as given by the second value.
2166 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2167 numbers should be factors of 60, so for example 5, 10, 15.
2169 When this is larger than 1, you can still force an exact time-stamp by using
2170 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2171 and by using a prefix arg to `S-up/down' to specify the exact number
2172 of minutes to shift."
2173 :group 'org-time
2174 :get '(lambda (var) ; Make sure all entries have 5 elements
2175 (if (integerp (default-value var))
2176 (list (default-value var) 5)
2177 (default-value var)))
2178 :type '(list
2179 (integer :tag "when inserting times")
2180 (integer :tag "when modifying times")))
2182 ;; Normalize old customizations of this variable.
2183 (when (integerp org-time-stamp-rounding-minutes)
2184 (setq org-time-stamp-rounding-minutes
2185 (list org-time-stamp-rounding-minutes
2186 org-time-stamp-rounding-minutes)))
2188 (defcustom org-display-custom-times nil
2189 "Non-nil means, overlay custom formats over all time stamps.
2190 The formats are defined through the variable `org-time-stamp-custom-formats'.
2191 To turn this on on a per-file basis, insert anywhere in the file:
2192 #+STARTUP: customtime"
2193 :group 'org-time
2194 :set 'set-default
2195 :type 'sexp)
2196 (make-variable-buffer-local 'org-display-custom-times)
2198 (defcustom org-time-stamp-custom-formats
2199 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2200 "Custom formats for time stamps. See `format-time-string' for the syntax.
2201 These are overlayed over the default ISO format if the variable
2202 `org-display-custom-times' is set. Time like %H:%M should be at the
2203 end of the second format. The custom formats are also honored by export
2204 commands, if custom time display is turned on at the time of export."
2205 :group 'org-time
2206 :type 'sexp)
2208 (defun org-time-stamp-format (&optional long inactive)
2209 "Get the right format for a time string."
2210 (let ((f (if long (cdr org-time-stamp-formats)
2211 (car org-time-stamp-formats))))
2212 (if inactive
2213 (concat "[" (substring f 1 -1) "]")
2214 f)))
2216 (defcustom org-time-clocksum-format "%d:%02d"
2217 "The format string used when creating CLOCKSUM lines, or when
2218 org-mode generates a time duration."
2219 :group 'org-time
2220 :type 'string)
2222 (defcustom org-time-clocksum-use-fractional nil
2223 "If non-nil, \\[org-clock-display] uses fractional times.
2224 org-mode generates a time duration."
2225 :group 'org-time
2226 :type 'boolean)
2228 (defcustom org-time-clocksum-fractional-format "%.2f"
2229 "The format string used when creating CLOCKSUM lines, or when
2230 org-mode generates a time duration."
2231 :group 'org-time
2232 :type 'string)
2234 (defcustom org-deadline-warning-days 14
2235 "No. of days before expiration during which a deadline becomes active.
2236 This variable governs the display in sparse trees and in the agenda.
2237 When 0 or negative, it means use this number (the absolute value of it)
2238 even if a deadline has a different individual lead time specified.
2240 Custom commands can set this variable in the options section."
2241 :group 'org-time
2242 :group 'org-agenda-daily/weekly
2243 :type 'integer)
2245 (defcustom org-read-date-prefer-future t
2246 "Non-nil means, assume future for incomplete date input from user.
2247 This affects the following situations:
2248 1. The user gives a month but not a year.
2249 For example, if it is april and you enter \"feb 2\", this will be read
2250 as feb 2, *next* year. \"May 5\", however, will be this year.
2251 2. The user gives a day, but no month.
2252 For example, if today is the 15th, and you enter \"3\", Org-mode will
2253 read this as the third of *next* month. However, if you enter \"17\",
2254 it will be considered as *this* month.
2256 If you set this variable to the symbol `time', then also the following
2257 will work:
2259 3. If the user gives a time, but no day. If the time is before now,
2260 to will be interpreted as tomorrow.
2262 Currently none of this works for ISO week specifications.
2264 When this option is nil, the current day, month and year will always be
2265 used as defaults."
2266 :group 'org-time
2267 :type '(choice
2268 (const :tag "Never" nil)
2269 (const :tag "Check month and day" t)
2270 (const :tag "Check month, day, and time" time)))
2272 (defcustom org-read-date-display-live t
2273 "Non-nil means, display current interpretation of date prompt live.
2274 This display will be in an overlay, in the minibuffer."
2275 :group 'org-time
2276 :type 'boolean)
2278 (defcustom org-read-date-popup-calendar t
2279 "Non-nil means, pop up a calendar when prompting for a date.
2280 In the calendar, the date can be selected with mouse-1. However, the
2281 minibuffer will also be active, and you can simply enter the date as well.
2282 When nil, only the minibuffer will be available."
2283 :group 'org-time
2284 :type 'boolean)
2285 (if (fboundp 'defvaralias)
2286 (defvaralias 'org-popup-calendar-for-date-prompt
2287 'org-read-date-popup-calendar))
2289 (defcustom org-read-date-minibuffer-setup-hook nil
2290 "Hook to be used to set up keys for the date/time interface.
2291 Add key definitions to `minibuffer-local-map', which will be a temporary
2292 copy."
2293 :group 'org-time
2294 :type 'hook)
2296 (defcustom org-extend-today-until 0
2297 "The hour when your day really ends. Must be an integer.
2298 This has influence for the following applications:
2299 - When switching the agenda to \"today\". It it is still earlier than
2300 the time given here, the day recognized as TODAY is actually yesterday.
2301 - When a date is read from the user and it is still before the time given
2302 here, the current date and time will be assumed to be yesterday, 23:59.
2303 Also, timestamps inserted in remember templates follow this rule.
2305 IMPORTANT: This is a feature whose implementation is and likely will
2306 remain incomplete. Really, it is only here because past midnight seems to
2307 be the favorite working time of John Wiegley :-)"
2308 :group 'org-time
2309 :type 'integer)
2311 (defcustom org-edit-timestamp-down-means-later nil
2312 "Non-nil means, S-down will increase the time in a time stamp.
2313 When nil, S-up will increase."
2314 :group 'org-time
2315 :type 'boolean)
2317 (defcustom org-calendar-follow-timestamp-change t
2318 "Non-nil means, make the calendar window follow timestamp changes.
2319 When a timestamp is modified and the calendar window is visible, it will be
2320 moved to the new date."
2321 :group 'org-time
2322 :type 'boolean)
2324 (defgroup org-tags nil
2325 "Options concerning tags in Org-mode."
2326 :tag "Org Tags"
2327 :group 'org)
2329 (defcustom org-tag-alist nil
2330 "List of tags allowed in Org-mode files.
2331 When this list is nil, Org-mode will base TAG input on what is already in the
2332 buffer.
2333 The value of this variable is an alist, the car of each entry must be a
2334 keyword as a string, the cdr may be a character that is used to select
2335 that tag through the fast-tag-selection interface.
2336 See the manual for details."
2337 :group 'org-tags
2338 :type '(repeat
2339 (choice
2340 (cons (string :tag "Tag name")
2341 (character :tag "Access char"))
2342 (list :tag "Start radio group"
2343 (const :startgroup)
2344 (option (string :tag "Group description")))
2345 (list :tag "End radio group"
2346 (const :endgroup)
2347 (option (string :tag "Group description")))
2348 (const :tag "New line" (:newline)))))
2350 (defcustom org-tag-persistent-alist nil
2351 "List of tags that will always appear in all Org-mode files.
2352 This is in addition to any in buffer settings or customizations
2353 of `org-tag-alist'.
2354 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2355 The value of this variable is an alist, the car of each entry must be a
2356 keyword as a string, the cdr may be a character that is used to select
2357 that tag through the fast-tag-selection interface.
2358 See the manual for details.
2359 To disable these tags on a per-file basis, insert anywhere in the file:
2360 #+STARTUP: noptag"
2361 :group 'org-tags
2362 :type '(repeat
2363 (choice
2364 (cons (string :tag "Tag name")
2365 (character :tag "Access char"))
2366 (const :tag "Start radio group" (:startgroup))
2367 (const :tag "End radio group" (:endgroup))
2368 (const :tag "New line" (:newline)))))
2370 (defvar org-file-tags nil
2371 "List of tags that can be inherited by all entries in the file.
2372 The tags will be inherited if the variable `org-use-tag-inheritance'
2373 says they should be.
2374 This variable is populated from #+FILETAGS lines.")
2376 (defcustom org-use-fast-tag-selection 'auto
2377 "Non-nil means, use fast tag selection scheme.
2378 This is a special interface to select and deselect tags with single keys.
2379 When nil, fast selection is never used.
2380 When the symbol `auto', fast selection is used if and only if selection
2381 characters for tags have been configured, either through the variable
2382 `org-tag-alist' or through a #+TAGS line in the buffer.
2383 When t, fast selection is always used and selection keys are assigned
2384 automatically if necessary."
2385 :group 'org-tags
2386 :type '(choice
2387 (const :tag "Always" t)
2388 (const :tag "Never" nil)
2389 (const :tag "When selection characters are configured" 'auto)))
2391 (defcustom org-fast-tag-selection-single-key nil
2392 "Non-nil means, fast tag selection exits after first change.
2393 When nil, you have to press RET to exit it.
2394 During fast tag selection, you can toggle this flag with `C-c'.
2395 This variable can also have the value `expert'. In this case, the window
2396 displaying the tags menu is not even shown, until you press C-c again."
2397 :group 'org-tags
2398 :type '(choice
2399 (const :tag "No" nil)
2400 (const :tag "Yes" t)
2401 (const :tag "Expert" expert)))
2403 (defvar org-fast-tag-selection-include-todo nil
2404 "Non-nil means, fast tags selection interface will also offer TODO states.
2405 This is an undocumented feature, you should not rely on it.")
2407 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2408 "The column to which tags should be indented in a headline.
2409 If this number is positive, it specifies the column. If it is negative,
2410 it means that the tags should be flushright to that column. For example,
2411 -80 works well for a normal 80 character screen."
2412 :group 'org-tags
2413 :type 'integer)
2415 (defcustom org-auto-align-tags t
2416 "Non-nil means, realign tags after pro/demotion of TODO state change.
2417 These operations change the length of a headline and therefore shift
2418 the tags around. With this options turned on, after each such operation
2419 the tags are again aligned to `org-tags-column'."
2420 :group 'org-tags
2421 :type 'boolean)
2423 (defcustom org-use-tag-inheritance t
2424 "Non-nil means, tags in levels apply also for sublevels.
2425 When nil, only the tags directly given in a specific line apply there.
2426 This may also be a list of tags that should be inherited, or a regexp that
2427 matches tags that should be inherited. Additional control is possible
2428 with the variable `org-tags-exclude-from-inheritance' which gives an
2429 explicit list of tags to be excluded from inheritance., even if the value of
2430 `org-use-tag-inheritance' would select it for inheritance.
2432 If this option is t, a match early-on in a tree can lead to a large
2433 number of matches in the subtree when constructing the agenda or creating
2434 a sparse tree. If you only want to see the first match in a tree during
2435 a search, check out the variable `org-tags-match-list-sublevels'."
2436 :group 'org-tags
2437 :type '(choice
2438 (const :tag "Not" nil)
2439 (const :tag "Always" t)
2440 (repeat :tag "Specific tags" (string :tag "Tag"))
2441 (regexp :tag "Tags matched by regexp")))
2443 (defcustom org-tags-exclude-from-inheritance nil
2444 "List of tags that should never be inherited.
2445 This is a way to exclude a few tags from inheritance. For way to do
2446 the opposite, to actively allow inheritance for selected tags,
2447 see the variable `org-use-tag-inheritance'."
2448 :group 'org-tags
2449 :type '(repeat (string :tag "Tag")))
2451 (defun org-tag-inherit-p (tag)
2452 "Check if TAG is one that should be inherited."
2453 (cond
2454 ((member tag org-tags-exclude-from-inheritance) nil)
2455 ((eq org-use-tag-inheritance t) t)
2456 ((not org-use-tag-inheritance) nil)
2457 ((stringp org-use-tag-inheritance)
2458 (string-match org-use-tag-inheritance tag))
2459 ((listp org-use-tag-inheritance)
2460 (member tag org-use-tag-inheritance))
2461 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2463 (defcustom org-tags-match-list-sublevels t
2464 "Non-nil means list also sublevels of headlines matching a search.
2465 This variable applies to tags/property searches, and also to stuck
2466 projects because this search is based on a tags match as well.
2468 When set to the symbol `indented', sublevels are indented with
2469 leading dots.
2471 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2472 the sublevels of a headline matching a tag search often also match
2473 the same search. Listing all of them can create very long lists.
2474 Setting this variable to nil causes subtrees of a match to be skipped.
2476 This variable is semi-obsolete and probably should always be true. It
2477 is better to limit inheritance to certain tags using the variables
2478 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2479 :group 'org-tags
2480 :type '(choice
2481 (const :tag "No, don't list them" nil)
2482 (const :tag "Yes, do list them" t)
2483 (const :tag "List them, indented with leading dots" indented)))
2485 (defcustom org-tags-sort-function nil
2486 "When set, tags are sorted using this function as a comparator"
2487 :group 'org-tags
2488 :type '(choice
2489 (const :tag "No sorting" nil)
2490 (const :tag "Alphabetical" string<)
2491 (const :tag "Reverse alphabetical" string>)
2492 (function :tag "Custom function" nil)))
2494 (defvar org-tags-history nil
2495 "History of minibuffer reads for tags.")
2496 (defvar org-last-tags-completion-table nil
2497 "The last used completion table for tags.")
2498 (defvar org-after-tags-change-hook nil
2499 "Hook that is run after the tags in a line have changed.")
2501 (defgroup org-properties nil
2502 "Options concerning properties in Org-mode."
2503 :tag "Org Properties"
2504 :group 'org)
2506 (defcustom org-property-format "%-10s %s"
2507 "How property key/value pairs should be formatted by `indent-line'.
2508 When `indent-line' hits a property definition, it will format the line
2509 according to this format, mainly to make sure that the values are
2510 lined-up with respect to each other."
2511 :group 'org-properties
2512 :type 'string)
2514 (defcustom org-use-property-inheritance nil
2515 "Non-nil means, properties apply also for sublevels.
2517 This setting is chiefly used during property searches. Turning it on can
2518 cause significant overhead when doing a search, which is why it is not
2519 on by default.
2521 When nil, only the properties directly given in the current entry count.
2522 When t, every property is inherited. The value may also be a list of
2523 properties that should have inheritance, or a regular expression matching
2524 properties that should be inherited.
2526 However, note that some special properties use inheritance under special
2527 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2528 and the properties ending in \"_ALL\" when they are used as descriptor
2529 for valid values of a property.
2531 Note for programmers:
2532 When querying an entry with `org-entry-get', you can control if inheritance
2533 should be used. By default, `org-entry-get' looks only at the local
2534 properties. You can request inheritance by setting the inherit argument
2535 to t (to force inheritance) or to `selective' (to respect the setting
2536 in this variable)."
2537 :group 'org-properties
2538 :type '(choice
2539 (const :tag "Not" nil)
2540 (const :tag "Always" t)
2541 (repeat :tag "Specific properties" (string :tag "Property"))
2542 (regexp :tag "Properties matched by regexp")))
2544 (defun org-property-inherit-p (property)
2545 "Check if PROPERTY is one that should be inherited."
2546 (cond
2547 ((eq org-use-property-inheritance t) t)
2548 ((not org-use-property-inheritance) nil)
2549 ((stringp org-use-property-inheritance)
2550 (string-match org-use-property-inheritance property))
2551 ((listp org-use-property-inheritance)
2552 (member property org-use-property-inheritance))
2553 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2555 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2556 "The default column format, if no other format has been defined.
2557 This variable can be set on the per-file basis by inserting a line
2559 #+COLUMNS: %25ITEM ....."
2560 :group 'org-properties
2561 :type 'string)
2563 (defcustom org-columns-ellipses ".."
2564 "The ellipses to be used when a field in column view is truncated.
2565 When this is the empty string, as many characters as possible are shown,
2566 but then there will be no visual indication that the field has been truncated.
2567 When this is a string of length N, the last N characters of a truncated
2568 field are replaced by this string. If the column is narrower than the
2569 ellipses string, only part of the ellipses string will be shown."
2570 :group 'org-properties
2571 :type 'string)
2573 (defcustom org-columns-modify-value-for-display-function nil
2574 "Function that modifies values for display in column view.
2575 For example, it can be used to cut out a certain part from a time stamp.
2576 The function must take 2 arguments:
2578 column-title The title of the column (*not* the property name)
2579 value The value that should be modified.
2581 The function should return the value that should be displayed,
2582 or nil if the normal value should be used."
2583 :group 'org-properties
2584 :type 'function)
2586 (defcustom org-effort-property "Effort"
2587 "The property that is being used to keep track of effort estimates.
2588 Effort estimates given in this property need to have the format H:MM."
2589 :group 'org-properties
2590 :group 'org-progress
2591 :type '(string :tag "Property"))
2593 (defconst org-global-properties-fixed
2594 '(("VISIBILITY_ALL" . "folded children content all")
2595 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2596 "List of property/value pairs that can be inherited by any entry.
2598 These are fixed values, for the preset properties. The user variable
2599 that can be used to add to this list is `org-global-properties'.
2601 The entries in this list are cons cells where the car is a property
2602 name and cdr is a string with the value. If the value represents
2603 multiple items like an \"_ALL\" property, separate the items by
2604 spaces.")
2606 (defcustom org-global-properties nil
2607 "List of property/value pairs that can be inherited by any entry.
2609 This list will be combined with the constant `org-global-properties-fixed'.
2611 The entries in this list are cons cells where the car is a property
2612 name and cdr is a string with the value.
2614 You can set buffer-local values for the same purpose in the variable
2615 `org-file-properties' this by adding lines like
2617 #+PROPERTY: NAME VALUE"
2618 :group 'org-properties
2619 :type '(repeat
2620 (cons (string :tag "Property")
2621 (string :tag "Value"))))
2623 (defvar org-file-properties nil
2624 "List of property/value pairs that can be inherited by any entry.
2625 Valid for the current buffer.
2626 This variable is populated from #+PROPERTY lines.")
2627 (make-variable-buffer-local 'org-file-properties)
2629 (defgroup org-agenda nil
2630 "Options concerning agenda views in Org-mode."
2631 :tag "Org Agenda"
2632 :group 'org)
2634 (defvar org-category nil
2635 "Variable used by org files to set a category for agenda display.
2636 Such files should use a file variable to set it, for example
2638 # -*- mode: org; org-category: \"ELisp\"
2640 or contain a special line
2642 #+CATEGORY: ELisp
2644 If the file does not specify a category, then file's base name
2645 is used instead.")
2646 (make-variable-buffer-local 'org-category)
2647 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2649 (defcustom org-agenda-files nil
2650 "The files to be used for agenda display.
2651 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2652 \\[org-remove-file]. You can also use customize to edit the list.
2654 If an entry is a directory, all files in that directory that are matched by
2655 `org-agenda-file-regexp' will be part of the file list.
2657 If the value of the variable is not a list but a single file name, then
2658 the list of agenda files is actually stored and maintained in that file, one
2659 agenda file per line."
2660 :group 'org-agenda
2661 :type '(choice
2662 (repeat :tag "List of files and directories" file)
2663 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2665 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2666 "Regular expression to match files for `org-agenda-files'.
2667 If any element in the list in that variable contains a directory instead
2668 of a normal file, all files in that directory that are matched by this
2669 regular expression will be included."
2670 :group 'org-agenda
2671 :type 'regexp)
2673 (defcustom org-agenda-text-search-extra-files nil
2674 "List of extra files to be searched by text search commands.
2675 These files will be search in addition to the agenda files by the
2676 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2677 Note that these files will only be searched for text search commands,
2678 not for the other agenda views like todo lists, tag searches or the weekly
2679 agenda. This variable is intended to list notes and possibly archive files
2680 that should also be searched by these two commands.
2681 In fact, if the first element in the list is the symbol `agenda-archives',
2682 than all archive files of all agenda files will be added to the search
2683 scope."
2684 :group 'org-agenda
2685 :type '(set :greedy t
2686 (const :tag "Agenda Archives" agenda-archives)
2687 (repeat :inline t (file))))
2689 (if (fboundp 'defvaralias)
2690 (defvaralias 'org-agenda-multi-occur-extra-files
2691 'org-agenda-text-search-extra-files))
2693 (defcustom org-agenda-skip-unavailable-files nil
2694 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2695 A nil value means to remove them, after a query, from the list."
2696 :group 'org-agenda
2697 :type 'boolean)
2699 (defcustom org-calendar-to-agenda-key [?c]
2700 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2701 The command `org-calendar-goto-agenda' will be bound to this key. The
2702 default is the character `c' because then `c' can be used to switch back and
2703 forth between agenda and calendar."
2704 :group 'org-agenda
2705 :type 'sexp)
2707 (defcustom org-calendar-agenda-action-key [?k]
2708 "The key to be installed in `calendar-mode-map' for agenda-action.
2709 The command `org-agenda-action' will be bound to this key. The
2710 default is the character `k' because we use the same key in the agenda."
2711 :group 'org-agenda
2712 :type 'sexp)
2714 (defcustom org-calendar-insert-diary-entry-key [?i]
2715 "The key to be installed in `calendar-mode-map' for adding diary entries.
2716 This option is irrelevant until `org-agenda-diary-file' has been configured
2717 to point to an Org-mode file. When that is the case, the command
2718 `org-agenda-diary-entry' will be bound to the key given here, by default
2719 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2720 if you want to continue doing this, you need to change this to a defferent
2721 key."
2722 :group 'org-agenda
2723 :type 'sexp)
2725 (defcustom org-agenda-diary-file 'diary-file
2726 "File to which to add new entries with the `i' key in agenda and calendar.
2727 When this is the symbol `diary-file', the functionality in the Emacs
2728 calendar will be used to add entries to the `diary-file'. But when this
2729 points to a file, `org-agenda-diary-entry' will be used instead."
2730 :group 'org-agenda
2731 :type '(choice
2732 (const :tag "The standard Emacs diary file" diary-file)
2733 (file :tag "Special Org file diary entries")))
2735 (eval-after-load "calendar"
2736 '(progn
2737 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2738 'org-calendar-goto-agenda)
2739 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2740 'org-agenda-action)
2741 (add-hook 'calendar-mode-hook
2742 (lambda ()
2743 (unless (eq org-agenda-diary-file 'diary-file)
2744 (define-key calendar-mode-map
2745 org-calendar-insert-diary-entry-key
2746 'org-agenda-diary-entry))))))
2748 (defgroup org-latex nil
2749 "Options for embedding LaTeX code into Org-mode."
2750 :tag "Org LaTeX"
2751 :group 'org)
2753 (defcustom org-format-latex-options
2754 '(:foreground default :background default :scale 1.0
2755 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2756 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2757 "Options for creating images from LaTeX fragments.
2758 This is a property list with the following properties:
2759 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2760 `default' means use the foreground of the default face.
2761 :background the background color, or \"Transparent\".
2762 `default' means use the background of the default face.
2763 :scale a scaling factor for the size of the images.
2764 :html-foreground, :html-background, :html-scale
2765 the same numbers for HTML export.
2766 :matchers a list indicating which matchers should be used to
2767 find LaTeX fragments. Valid members of this list are:
2768 \"begin\" find environments
2769 \"$1\" find single characters surrounded by $.$
2770 \"$\" find math expressions surrounded by $...$
2771 \"$$\" find math expressions surrounded by $$....$$
2772 \"\\(\" find math expressions surrounded by \\(...\\)
2773 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2774 :group 'org-latex
2775 :type 'plist)
2777 (defcustom org-format-latex-header "\\documentclass{article}
2778 \\usepackage{amssymb}
2779 \\usepackage[usenames]{color}
2780 \\usepackage{amsmath}
2781 \\usepackage{latexsym}
2782 \\usepackage[mathscr]{eucal}
2783 \\pagestyle{empty} % do not remove
2784 % The settings below are copied from fullpage.sty
2785 \\setlength{\\textwidth}{\\paperwidth}
2786 \\addtolength{\\textwidth}{-3cm}
2787 \\setlength{\\oddsidemargin}{1.5cm}
2788 \\addtolength{\\oddsidemargin}{-2.54cm}
2789 \\setlength{\\evensidemargin}{\\oddsidemargin}
2790 \\setlength{\\textheight}{\\paperheight}
2791 \\addtolength{\\textheight}{-\\headheight}
2792 \\addtolength{\\textheight}{-\\headsep}
2793 \\addtolength{\\textheight}{-\\footskip}
2794 \\addtolength{\\textheight}{-3cm}
2795 \\setlength{\\topmargin}{1.5cm}
2796 \\addtolength{\\topmargin}{-2.54cm}"
2797 "The document header used for processing LaTeX fragments.
2798 It is imperative that this header make sure that no page number
2799 appears on the page."
2800 :group 'org-latex
2801 :type 'string)
2804 (defgroup org-font-lock nil
2805 "Font-lock settings for highlighting in Org-mode."
2806 :tag "Org Font Lock"
2807 :group 'org)
2809 (defcustom org-level-color-stars-only nil
2810 "Non-nil means fontify only the stars in each headline.
2811 When nil, the entire headline is fontified.
2812 Changing it requires restart of `font-lock-mode' to become effective
2813 also in regions already fontified."
2814 :group 'org-font-lock
2815 :type 'boolean)
2817 (defcustom org-hide-leading-stars nil
2818 "Non-nil means, hide the first N-1 stars in a headline.
2819 This works by using the face `org-hide' for these stars. This
2820 face is white for a light background, and black for a dark
2821 background. You may have to customize the face `org-hide' to
2822 make this work.
2823 Changing it requires restart of `font-lock-mode' to become effective
2824 also in regions already fontified.
2825 You may also set this on a per-file basis by adding one of the following
2826 lines to the buffer:
2828 #+STARTUP: hidestars
2829 #+STARTUP: showstars"
2830 :group 'org-font-lock
2831 :type 'boolean)
2833 (defcustom org-fontify-done-headline nil
2834 "Non-nil means, change the face of a headline if it is marked DONE.
2835 Normally, only the TODO/DONE keyword indicates the state of a headline.
2836 When this is non-nil, the headline after the keyword is set to the
2837 `org-headline-done' as an additional indication."
2838 :group 'org-font-lock
2839 :type 'boolean)
2841 (defcustom org-fontify-emphasized-text t
2842 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2843 Changing this variable requires a restart of Emacs to take effect."
2844 :group 'org-font-lock
2845 :type 'boolean)
2847 (defcustom org-fontify-whole-heading-line nil
2848 "Non-nil means fontify the whole line for headings.
2849 This is useful when setting a background color for the
2850 org-leve-* faces."
2851 :group 'org-font-lock
2852 :type 'boolean)
2854 (defcustom org-highlight-latex-fragments-and-specials nil
2855 "Non-nil means, fontify what is treated specially by the exporters."
2856 :group 'org-font-lock
2857 :type 'boolean)
2859 (defcustom org-hide-emphasis-markers nil
2860 "Non-nil mean font-lock should hide the emphasis marker characters."
2861 :group 'org-font-lock
2862 :type 'boolean)
2864 (defvar org-emph-re nil
2865 "Regular expression for matching emphasis.")
2866 (defvar org-verbatim-re nil
2867 "Regular expression for matching verbatim text.")
2868 (defvar org-emphasis-regexp-components) ; defined just below
2869 (defvar org-emphasis-alist) ; defined just below
2870 (defun org-set-emph-re (var val)
2871 "Set variable and compute the emphasis regular expression."
2872 (set var val)
2873 (when (and (boundp 'org-emphasis-alist)
2874 (boundp 'org-emphasis-regexp-components)
2875 org-emphasis-alist org-emphasis-regexp-components)
2876 (let* ((e org-emphasis-regexp-components)
2877 (pre (car e))
2878 (post (nth 1 e))
2879 (border (nth 2 e))
2880 (body (nth 3 e))
2881 (nl (nth 4 e))
2882 (body1 (concat body "*?"))
2883 (markers (mapconcat 'car org-emphasis-alist ""))
2884 (vmarkers (mapconcat
2885 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2886 org-emphasis-alist "")))
2887 ;; make sure special characters appear at the right position in the class
2888 (if (string-match "\\^" markers)
2889 (setq markers (concat (replace-match "" t t markers) "^")))
2890 (if (string-match "-" markers)
2891 (setq markers (concat (replace-match "" t t markers) "-")))
2892 (if (string-match "\\^" vmarkers)
2893 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2894 (if (string-match "-" vmarkers)
2895 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2896 (if (> nl 0)
2897 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2898 (int-to-string nl) "\\}")))
2899 ;; Make the regexp
2900 (setq org-emph-re
2901 (concat "\\([" pre "]\\|^\\)"
2902 "\\("
2903 "\\([" markers "]\\)"
2904 "\\("
2905 "[^" border "]\\|"
2906 "[^" border "]"
2907 body1
2908 "[^" border "]"
2909 "\\)"
2910 "\\3\\)"
2911 "\\([" post "]\\|$\\)"))
2912 (setq org-verbatim-re
2913 (concat "\\([" pre "]\\|^\\)"
2914 "\\("
2915 "\\([" vmarkers "]\\)"
2916 "\\("
2917 "[^" border "]\\|"
2918 "[^" border "]"
2919 body1
2920 "[^" border "]"
2921 "\\)"
2922 "\\3\\)"
2923 "\\([" post "]\\|$\\)")))))
2925 (defcustom org-emphasis-regexp-components
2926 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
2927 "Components used to build the regular expression for emphasis.
2928 This is a list with 6 entries. Terminology: In an emphasis string
2929 like \" *strong word* \", we call the initial space PREMATCH, the final
2930 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2931 and \"trong wor\" is the body. The different components in this variable
2932 specify what is allowed/forbidden in each part:
2934 pre Chars allowed as prematch. Beginning of line will be allowed too.
2935 post Chars allowed as postmatch. End of line will be allowed too.
2936 border The chars *forbidden* as border characters.
2937 body-regexp A regexp like \".\" to match a body character. Don't use
2938 non-shy groups here, and don't allow newline here.
2939 newline The maximum number of newlines allowed in an emphasis exp.
2941 Use customize to modify this, or restart Emacs after changing it."
2942 :group 'org-font-lock
2943 :set 'org-set-emph-re
2944 :type '(list
2945 (sexp :tag "Allowed chars in pre ")
2946 (sexp :tag "Allowed chars in post ")
2947 (sexp :tag "Forbidden chars in border ")
2948 (sexp :tag "Regexp for body ")
2949 (integer :tag "number of newlines allowed")
2950 (option (boolean :tag "Please ignore this button"))))
2952 (defcustom org-emphasis-alist
2953 `(("*" bold "<b>" "</b>")
2954 ("/" italic "<i>" "</i>")
2955 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2956 ("=" org-code "<code>" "</code>" verbatim)
2957 ("~" org-verbatim "<code>" "</code>" verbatim)
2958 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2959 "<del>" "</del>")
2961 "Special syntax for emphasized text.
2962 Text starting and ending with a special character will be emphasized, for
2963 example *bold*, _underlined_ and /italic/. This variable sets the marker
2964 characters, the face to be used by font-lock for highlighting in Org-mode
2965 Emacs buffers, and the HTML tags to be used for this.
2966 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2967 Use customize to modify this, or restart Emacs after changing it."
2968 :group 'org-font-lock
2969 :set 'org-set-emph-re
2970 :type '(repeat
2971 (list
2972 (string :tag "Marker character")
2973 (choice
2974 (face :tag "Font-lock-face")
2975 (plist :tag "Face property list"))
2976 (string :tag "HTML start tag")
2977 (string :tag "HTML end tag")
2978 (option (const verbatim)))))
2980 (defvar org-protecting-blocks
2981 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
2982 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
2983 This is needed for font-lock setup.")
2985 ;;; Miscellaneous options
2987 (defgroup org-completion nil
2988 "Completion in Org-mode."
2989 :tag "Org Completion"
2990 :group 'org)
2992 (defcustom org-completion-use-ido nil
2993 "Non-nil means, use ido completion wherever possible.
2994 Note that `ido-mode' must be active for this variable to be relevant.
2995 If you decide to turn this variable on, you might well want to turn off
2996 `org-outline-path-complete-in-steps'.
2997 See also `org-completion-use-iswitchb'."
2998 :group 'org-completion
2999 :type 'boolean)
3001 (defcustom org-completion-use-iswitchb nil
3002 "Non-nil means, use iswitchb completion wherever possible.
3003 Note that `iswitchb-mode' must be active for this variable to be relevant.
3004 If you decide to turn this variable on, you might well want to turn off
3005 `org-outline-path-complete-in-steps'.
3006 Note that thi variable has only an effect if `org-completion-use-ido' is nil."
3007 :group 'org-completion
3008 :type 'boolean)
3010 (defcustom org-completion-fallback-command 'hippie-expand
3011 "The expansion command called by \\[org-complete] in normal context.
3012 Normal means, no org-mode-specific context."
3013 :group 'org-completion
3014 :type 'function)
3016 ;;; Functions and variables from ther packages
3017 ;; Declared here to avoid compiler warnings
3019 ;; XEmacs only
3020 (defvar outline-mode-menu-heading)
3021 (defvar outline-mode-menu-show)
3022 (defvar outline-mode-menu-hide)
3023 (defvar zmacs-regions) ; XEmacs regions
3025 ;; Emacs only
3026 (defvar mark-active)
3028 ;; Various packages
3029 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3030 (declare-function calendar-forward-day "cal-move" (arg))
3031 (declare-function calendar-goto-date "cal-move" (date))
3032 (declare-function calendar-goto-today "cal-move" ())
3033 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3034 (defvar calc-embedded-close-formula)
3035 (defvar calc-embedded-open-formula)
3036 (declare-function cdlatex-tab "ext:cdlatex" ())
3037 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3038 (defvar font-lock-unfontify-region-function)
3039 (declare-function iswitchb-read-buffer "iswitchb"
3040 (prompt &optional default require-match start matches-set))
3041 (defvar iswitchb-temp-buflist)
3042 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3043 (defvar org-agenda-tags-todo-honor-ignore-options)
3044 (declare-function org-agenda-skip "org-agenda" ())
3045 (declare-function org-format-agenda-item "org-agenda"
3046 (extra txt &optional category tags dotime noprefix remove-re))
3047 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3048 (declare-function org-agenda-change-all-lines "org-agenda"
3049 (newhead hdmarker &optional fixface just-this))
3050 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3051 (declare-function org-agenda-maybe-redo "org-agenda" ())
3052 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3053 (beg end))
3054 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3055 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3056 "org-agenda" (&optional end))
3057 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3058 (declare-function org-indent-mode "org-indent" (&optional arg))
3059 (declare-function parse-time-string "parse-time" (string))
3060 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3061 (defvar remember-data-file)
3062 (defvar texmathp-why)
3063 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3064 (declare-function table--at-cell-p "table" (position &optional object at-column))
3066 (defvar w3m-current-url)
3067 (defvar w3m-current-title)
3069 (defvar org-latex-regexps)
3071 ;;; Autoload and prepare some org modules
3073 ;; Some table stuff that needs to be defined here, because it is used
3074 ;; by the functions setting up org-mode or checking for table context.
3076 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3077 "Detects an org-type or table-type table.")
3078 (defconst org-table-line-regexp "^[ \t]*|"
3079 "Detects an org-type table line.")
3080 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3081 "Detects an org-type table line.")
3082 (defconst org-table-hline-regexp "^[ \t]*|-"
3083 "Detects an org-type table hline.")
3084 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3085 "Detects a table-type table hline.")
3086 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3087 "Searching from within a table (any type) this finds the first line
3088 outside the table.")
3090 ;; Autoload the functions in org-table.el that are needed by functions here.
3092 (eval-and-compile
3093 (org-autoload "org-table"
3094 '(org-table-align org-table-begin org-table-blank-field
3095 org-table-convert org-table-convert-region org-table-copy-down
3096 org-table-copy-region org-table-create
3097 org-table-create-or-convert-from-region
3098 org-table-create-with-table.el org-table-current-dline
3099 org-table-cut-region org-table-delete-column org-table-edit-field
3100 org-table-edit-formulas org-table-end org-table-eval-formula
3101 org-table-export org-table-field-info
3102 org-table-get-stored-formulas org-table-goto-column
3103 org-table-hline-and-move org-table-import org-table-insert-column
3104 org-table-insert-hline org-table-insert-row org-table-iterate
3105 org-table-justify-field-maybe org-table-kill-row
3106 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3107 org-table-move-column org-table-move-column-left
3108 org-table-move-column-right org-table-move-row
3109 org-table-move-row-down org-table-move-row-up
3110 org-table-next-field org-table-next-row org-table-paste-rectangle
3111 org-table-previous-field org-table-recalculate
3112 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3113 org-table-toggle-coordinate-overlays
3114 org-table-toggle-formula-debugger org-table-wrap-region
3115 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3117 (defun org-at-table-p (&optional table-type)
3118 "Return t if the cursor is inside an org-type table.
3119 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3120 (if org-enable-table-editor
3121 (save-excursion
3122 (beginning-of-line 1)
3123 (looking-at (if table-type org-table-any-line-regexp
3124 org-table-line-regexp)))
3125 nil))
3126 (defsubst org-table-p () (org-at-table-p))
3128 (defun org-at-table.el-p ()
3129 "Return t if and only if we are at a table.el table."
3130 (and (org-at-table-p 'any)
3131 (save-excursion
3132 (goto-char (org-table-begin 'any))
3133 (looking-at org-table1-hline-regexp))))
3134 (defun org-table-recognize-table.el ()
3135 "If there is a table.el table nearby, recognize it and move into it."
3136 (if org-table-tab-recognizes-table.el
3137 (if (org-at-table.el-p)
3138 (progn
3139 (beginning-of-line 1)
3140 (if (looking-at org-table-dataline-regexp)
3142 (if (looking-at org-table1-hline-regexp)
3143 (progn
3144 (beginning-of-line 2)
3145 (if (looking-at org-table-any-border-regexp)
3146 (beginning-of-line -1)))))
3147 (if (re-search-forward "|" (org-table-end t) t)
3148 (progn
3149 (require 'table)
3150 (if (table--at-cell-p (point))
3152 (message "recognizing table.el table...")
3153 (table-recognize-table)
3154 (message "recognizing table.el table...done")))
3155 (error "This should not happen..."))
3157 nil)
3158 nil))
3160 (defun org-at-table-hline-p ()
3161 "Return t if the cursor is inside a hline in a table."
3162 (if org-enable-table-editor
3163 (save-excursion
3164 (beginning-of-line 1)
3165 (looking-at org-table-hline-regexp))
3166 nil))
3168 (defvar org-table-clean-did-remove-column nil)
3170 (defun org-table-map-tables (function)
3171 "Apply FUNCTION to the start of all tables in the buffer."
3172 (save-excursion
3173 (save-restriction
3174 (widen)
3175 (goto-char (point-min))
3176 (while (re-search-forward org-table-any-line-regexp nil t)
3177 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3178 (beginning-of-line 1)
3179 (when (looking-at org-table-line-regexp)
3180 (save-excursion (funcall function))
3181 (or (looking-at org-table-line-regexp)
3182 (forward-char 1)))
3183 (re-search-forward org-table-any-border-regexp nil 1))))
3184 (message "Mapping tables: done"))
3186 ;; Declare and autoload functions from org-exp.el & Co
3188 (declare-function org-default-export-plist "org-exp")
3189 (declare-function org-infile-export-plist "org-exp")
3190 (declare-function org-get-current-options "org-exp")
3191 (eval-and-compile
3192 (org-autoload "org-exp"
3193 '(org-export org-export-visible
3194 org-insert-export-options-template
3195 org-table-clean-before-export))
3196 (org-autoload "org-ascii"
3197 '(org-export-as-ascii org-export-ascii-preprocess
3198 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3199 org-export-region-as-ascii))
3200 (org-autoload "org-html"
3201 '(org-export-as-html-and-open
3202 org-export-as-html-batch org-export-as-html-to-buffer
3203 org-replace-region-by-html org-export-region-as-html
3204 org-export-as-html))
3205 (org-autoload "org-icalendar"
3206 '(org-export-icalendar-this-file
3207 org-export-icalendar-all-agenda-files
3208 org-export-icalendar-combine-agenda-files))
3209 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3211 ;; Declare and autoload functions from org-agenda.el
3213 (eval-and-compile
3214 (org-autoload "org-agenda"
3215 '(org-agenda org-agenda-list org-search-view
3216 org-todo-list org-tags-view org-agenda-list-stuck-projects
3217 org-diary org-agenda-to-appt
3218 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3220 ;; Autoload org-remember
3222 (eval-and-compile
3223 (org-autoload "org-remember"
3224 '(org-remember-insinuate org-remember-annotation
3225 org-remember-apply-template org-remember org-remember-handler)))
3227 ;; Autoload org-clock.el
3230 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3231 (beg end))
3232 (declare-function org-clock-update-mode-line "org-clock" ())
3233 (declare-function org-resolve-clocks "org-clock"
3234 (&optional also-non-dangling-p prompt last-valid))
3235 (defvar org-clock-start-time)
3236 (defvar org-clock-marker (make-marker)
3237 "Marker recording the last clock-in.")
3238 (defvar org-clock-hd-marker (make-marker)
3239 "Marker recording the last clock-in, but the headline position.")
3240 (defvar org-clock-heading ""
3241 "The heading of the current clock entry.")
3242 (defun org-clock-is-active ()
3243 "Return non-nil if clock is currently running.
3244 The return value is actually the clock marker."
3245 (marker-buffer org-clock-marker))
3247 (eval-and-compile
3248 (org-autoload
3249 "org-clock"
3250 '(org-clock-in org-clock-out org-clock-cancel
3251 org-clock-goto org-clock-sum org-clock-display
3252 org-clock-remove-overlays org-clock-report
3253 org-clocktable-shift org-dblock-write:clocktable
3254 org-get-clocktable org-resolve-clocks)))
3256 (defun org-clock-update-time-maybe ()
3257 "If this is a CLOCK line, update it and return t.
3258 Otherwise, return nil."
3259 (interactive)
3260 (save-excursion
3261 (beginning-of-line 1)
3262 (skip-chars-forward " \t")
3263 (when (looking-at org-clock-string)
3264 (let ((re (concat "[ \t]*" org-clock-string
3265 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3266 "\\([ \t]*=>.*\\)?\\)?"))
3267 ts te h m s neg)
3268 (cond
3269 ((not (looking-at re))
3270 nil)
3271 ((not (match-end 2))
3272 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3273 (> org-clock-marker (point))
3274 (<= org-clock-marker (point-at-eol)))
3275 ;; The clock is running here
3276 (setq org-clock-start-time
3277 (apply 'encode-time
3278 (org-parse-time-string (match-string 1))))
3279 (org-clock-update-mode-line)))
3281 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3282 (end-of-line 1)
3283 (setq ts (match-string 1)
3284 te (match-string 3))
3285 (setq s (- (org-float-time
3286 (apply 'encode-time (org-parse-time-string te)))
3287 (org-float-time
3288 (apply 'encode-time (org-parse-time-string ts))))
3289 neg (< s 0)
3290 s (abs s)
3291 h (floor (/ s 3600))
3292 s (- s (* 3600 h))
3293 m (floor (/ s 60))
3294 s (- s (* 60 s)))
3295 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3296 t))))))
3298 (defun org-check-running-clock ()
3299 "Check if the current buffer contains the running clock.
3300 If yes, offer to stop it and to save the buffer with the changes."
3301 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3302 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3303 (buffer-name))))
3304 (org-clock-out)
3305 (when (y-or-n-p "Save changed buffer?")
3306 (save-buffer))))
3308 (defun org-clocktable-try-shift (dir n)
3309 "Check if this line starts a clock table, if yes, shift the time block."
3310 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3311 (org-clocktable-shift dir n)))
3313 ;; Autoload org-timer.el
3315 (eval-and-compile
3316 (org-autoload
3317 "org-timer"
3318 '(org-timer-start org-timer org-timer-item
3319 org-timer-change-times-in-region
3320 org-timer-set-timer
3321 org-timer-reset-timers
3322 org-timer-show-remaining-time)))
3324 ;; Autoload org-feed.el
3326 (eval-and-compile
3327 (org-autoload
3328 "org-feed"
3329 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3332 ;; Autoload org-indent.el
3334 ;; Define the variable already here, to make sure we have it.
3335 (defvar org-indent-mode nil
3336 "Non-nil if Org-Indent mode is enabled.
3337 Use the command `org-indent-mode' to change this variable.")
3339 (eval-and-compile
3340 (org-autoload
3341 "org-indent"
3342 '(org-indent-mode)))
3344 ;; Autoload org-mobile.el
3346 (eval-and-compile
3347 (org-autoload
3348 "org-mobile"
3349 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3351 ;; Autoload archiving code
3352 ;; The stuff that is needed for cycling and tags has to be defined here.
3354 (defgroup org-archive nil
3355 "Options concerning archiving in Org-mode."
3356 :tag "Org Archive"
3357 :group 'org-structure)
3359 (defcustom org-archive-location "%s_archive::"
3360 "The location where subtrees should be archived.
3362 The value of this variable is a string, consisting of two parts,
3363 separated by a double-colon. The first part is a filename and
3364 the second part is a headline.
3366 When the filename is omitted, archiving happens in the same file.
3367 %s in the filename will be replaced by the current file
3368 name (without the directory part). Archiving to a different file
3369 is useful to keep archived entries from contributing to the
3370 Org-mode Agenda.
3372 The archived entries will be filed as subtrees of the specified
3373 headline. When the headline is omitted, the subtrees are simply
3374 filed away at the end of the file, as top-level entries. Also in
3375 the heading you can use %s to represent the file name, this can be
3376 useful when using the same archive for a number of different files.
3378 Here are a few examples:
3379 \"%s_archive::\"
3380 If the current file is Projects.org, archive in file
3381 Projects.org_archive, as top-level trees. This is the default.
3383 \"::* Archived Tasks\"
3384 Archive in the current file, under the top-level headline
3385 \"* Archived Tasks\".
3387 \"~/org/archive.org::\"
3388 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3390 \"~/org/archive.org::From %s\"
3391 Archive in file ~/org/archive.org (absolute path), und headlines
3392 \"From FILENAME\" where file name is the current file name.
3394 \"basement::** Finished Tasks\"
3395 Archive in file ./basement (relative path), as level 3 trees
3396 below the level 2 heading \"** Finished Tasks\".
3398 You may set this option on a per-file basis by adding to the buffer a
3399 line like
3401 #+ARCHIVE: basement::** Finished Tasks
3403 You may also define it locally for a subtree by setting an ARCHIVE property
3404 in the entry. If such a property is found in an entry, or anywhere up
3405 the hierarchy, it will be used."
3406 :group 'org-archive
3407 :type 'string)
3409 (defcustom org-archive-tag "ARCHIVE"
3410 "The tag that marks a subtree as archived.
3411 An archived subtree does not open during visibility cycling, and does
3412 not contribute to the agenda listings.
3413 After changing this, font-lock must be restarted in the relevant buffers to
3414 get the proper fontification."
3415 :group 'org-archive
3416 :group 'org-keywords
3417 :type 'string)
3419 (defcustom org-agenda-skip-archived-trees t
3420 "Non-nil means, the agenda will skip any items located in archived trees.
3421 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3422 variable is no longer recommended, you should leave it at the value t.
3423 Instead, use the key `v' to cycle the archives-mode in the agenda."
3424 :group 'org-archive
3425 :group 'org-agenda-skip
3426 :type 'boolean)
3428 (defcustom org-columns-skip-archived-trees t
3429 "Non-nil means, ignore archived trees when creating column view."
3430 :group 'org-archive
3431 :group 'org-properties
3432 :type 'boolean)
3434 (defcustom org-cycle-open-archived-trees nil
3435 "Non-nil means, `org-cycle' will open archived trees.
3436 An archived tree is a tree marked with the tag ARCHIVE.
3437 When nil, archived trees will stay folded. You can still open them with
3438 normal outline commands like `show-all', but not with the cycling commands."
3439 :group 'org-archive
3440 :group 'org-cycle
3441 :type 'boolean)
3443 (defcustom org-sparse-tree-open-archived-trees nil
3444 "Non-nil means sparse tree construction shows matches in archived trees.
3445 When nil, matches in these trees are highlighted, but the trees are kept in
3446 collapsed state."
3447 :group 'org-archive
3448 :group 'org-sparse-trees
3449 :type 'boolean)
3451 (defun org-cycle-hide-archived-subtrees (state)
3452 "Re-hide all archived subtrees after a visibility state change."
3453 (when (and (not org-cycle-open-archived-trees)
3454 (not (memq state '(overview folded))))
3455 (save-excursion
3456 (let* ((globalp (memq state '(contents all)))
3457 (beg (if globalp (point-min) (point)))
3458 (end (if globalp (point-max) (org-end-of-subtree t))))
3459 (org-hide-archived-subtrees beg end)
3460 (goto-char beg)
3461 (if (looking-at (concat ".*:" org-archive-tag ":"))
3462 (message "%s" (substitute-command-keys
3463 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3465 (defun org-force-cycle-archived ()
3466 "Cycle subtree even if it is archived."
3467 (interactive)
3468 (setq this-command 'org-cycle)
3469 (let ((org-cycle-open-archived-trees t))
3470 (call-interactively 'org-cycle)))
3472 (defun org-hide-archived-subtrees (beg end)
3473 "Re-hide all archived subtrees after a visibility state change."
3474 (save-excursion
3475 (let* ((re (concat ":" org-archive-tag ":")))
3476 (goto-char beg)
3477 (while (re-search-forward re end t)
3478 (and (org-on-heading-p) (org-flag-subtree t))
3479 (org-end-of-subtree t)))))
3481 (defun org-flag-subtree (flag)
3482 (save-excursion
3483 (org-back-to-heading t)
3484 (outline-end-of-heading)
3485 (outline-flag-region (point)
3486 (progn (org-end-of-subtree t) (point))
3487 flag)))
3489 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3491 (eval-and-compile
3492 (org-autoload "org-archive"
3493 '(org-add-archive-files org-archive-subtree
3494 org-archive-to-archive-sibling org-toggle-archive-tag)))
3496 ;; Autoload Column View Code
3498 (declare-function org-columns-number-to-string "org-colview")
3499 (declare-function org-columns-get-format-and-top-level "org-colview")
3500 (declare-function org-columns-compute "org-colview")
3502 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3503 '(org-columns-number-to-string org-columns-get-format-and-top-level
3504 org-columns-compute org-agenda-columns org-columns-remove-overlays
3505 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3507 ;; Autoload ID code
3509 (declare-function org-id-store-link "org-id")
3510 (declare-function org-id-locations-load "org-id")
3511 (declare-function org-id-locations-save "org-id")
3512 (defvar org-id-track-globally)
3513 (org-autoload "org-id"
3514 '(org-id-get-create org-id-new org-id-copy org-id-get
3515 org-id-get-with-outline-path-completion
3516 org-id-get-with-outline-drilling
3517 org-id-goto org-id-find org-id-store-link))
3519 ;; Autoload Plotting Code
3521 (org-autoload "org-plot"
3522 '(org-plot/gnuplot))
3524 ;;; Variables for pre-computed regular expressions, all buffer local
3526 (defvar org-drawer-regexp nil
3527 "Matches first line of a hidden block.")
3528 (make-variable-buffer-local 'org-drawer-regexp)
3529 (defvar org-todo-regexp nil
3530 "Matches any of the TODO state keywords.")
3531 (make-variable-buffer-local 'org-todo-regexp)
3532 (defvar org-not-done-regexp nil
3533 "Matches any of the TODO state keywords except the last one.")
3534 (make-variable-buffer-local 'org-not-done-regexp)
3535 (defvar org-not-done-heading-regexp nil
3536 "Matches a TODO headline that is not done.")
3537 (make-variable-buffer-local 'org-not-done-regexp)
3538 (defvar org-todo-line-regexp nil
3539 "Matches a headline and puts TODO state into group 2 if present.")
3540 (make-variable-buffer-local 'org-todo-line-regexp)
3541 (defvar org-complex-heading-regexp nil
3542 "Matches a headline and puts everything into groups:
3543 group 1: the stars
3544 group 2: The todo keyword, maybe
3545 group 3: Priority cookie
3546 group 4: True headline
3547 group 5: Tags")
3548 (make-variable-buffer-local 'org-complex-heading-regexp)
3549 (defvar org-complex-heading-regexp-format nil)
3550 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3551 (defvar org-todo-line-tags-regexp nil
3552 "Matches a headline and puts TODO state into group 2 if present.
3553 Also put tags into group 4 if tags are present.")
3554 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3555 (defvar org-nl-done-regexp nil
3556 "Matches newline followed by a headline with the DONE keyword.")
3557 (make-variable-buffer-local 'org-nl-done-regexp)
3558 (defvar org-looking-at-done-regexp nil
3559 "Matches the DONE keyword a point.")
3560 (make-variable-buffer-local 'org-looking-at-done-regexp)
3561 (defvar org-ds-keyword-length 12
3562 "Maximum length of the Deadline and SCHEDULED keywords.")
3563 (make-variable-buffer-local 'org-ds-keyword-length)
3564 (defvar org-deadline-regexp nil
3565 "Matches the DEADLINE keyword.")
3566 (make-variable-buffer-local 'org-deadline-regexp)
3567 (defvar org-deadline-time-regexp nil
3568 "Matches the DEADLINE keyword together with a time stamp.")
3569 (make-variable-buffer-local 'org-deadline-time-regexp)
3570 (defvar org-deadline-line-regexp nil
3571 "Matches the DEADLINE keyword and the rest of the line.")
3572 (make-variable-buffer-local 'org-deadline-line-regexp)
3573 (defvar org-scheduled-regexp nil
3574 "Matches the SCHEDULED keyword.")
3575 (make-variable-buffer-local 'org-scheduled-regexp)
3576 (defvar org-scheduled-time-regexp nil
3577 "Matches the SCHEDULED keyword together with a time stamp.")
3578 (make-variable-buffer-local 'org-scheduled-time-regexp)
3579 (defvar org-closed-time-regexp nil
3580 "Matches the CLOSED keyword together with a time stamp.")
3581 (make-variable-buffer-local 'org-closed-time-regexp)
3583 (defvar org-keyword-time-regexp nil
3584 "Matches any of the 4 keywords, together with the time stamp.")
3585 (make-variable-buffer-local 'org-keyword-time-regexp)
3586 (defvar org-keyword-time-not-clock-regexp nil
3587 "Matches any of the 3 keywords, together with the time stamp.")
3588 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3589 (defvar org-maybe-keyword-time-regexp nil
3590 "Matches a timestamp, possibly preceeded by a keyword.")
3591 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3592 (defvar org-planning-or-clock-line-re nil
3593 "Matches a line with planning or clock info.")
3594 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3596 (defconst org-plain-time-of-day-regexp
3597 (concat
3598 "\\(\\<[012]?[0-9]"
3599 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3600 "\\(--?"
3601 "\\(\\<[012]?[0-9]"
3602 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3603 "\\)?")
3604 "Regular expression to match a plain time or time range.
3605 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3606 groups carry important information:
3607 0 the full match
3608 1 the first time, range or not
3609 8 the second time, if it is a range.")
3611 (defconst org-plain-time-extension-regexp
3612 (concat
3613 "\\(\\<[012]?[0-9]"
3614 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3615 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3616 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3617 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3618 groups carry important information:
3619 0 the full match
3620 7 hours of duration
3621 9 minutes of duration")
3623 (defconst org-stamp-time-of-day-regexp
3624 (concat
3625 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3626 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3627 "\\(--?"
3628 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3629 "Regular expression to match a timestamp time or time range.
3630 After a match, the following groups carry important information:
3631 0 the full match
3632 1 date plus weekday, for backreferencing to make sure both times on same day
3633 2 the first time, range or not
3634 4 the second time, if it is a range.")
3636 (defconst org-startup-options
3637 '(("fold" org-startup-folded t)
3638 ("overview" org-startup-folded t)
3639 ("nofold" org-startup-folded nil)
3640 ("showall" org-startup-folded nil)
3641 ("showeverything" org-startup-folded showeverything)
3642 ("content" org-startup-folded content)
3643 ("indent" org-startup-indented t)
3644 ("noindent" org-startup-indented nil)
3645 ("hidestars" org-hide-leading-stars t)
3646 ("showstars" org-hide-leading-stars nil)
3647 ("odd" org-odd-levels-only t)
3648 ("oddeven" org-odd-levels-only nil)
3649 ("align" org-startup-align-all-tables t)
3650 ("noalign" org-startup-align-all-tables nil)
3651 ("customtime" org-display-custom-times t)
3652 ("logdone" org-log-done time)
3653 ("lognotedone" org-log-done note)
3654 ("nologdone" org-log-done nil)
3655 ("lognoteclock-out" org-log-note-clock-out t)
3656 ("nolognoteclock-out" org-log-note-clock-out nil)
3657 ("logrepeat" org-log-repeat state)
3658 ("lognoterepeat" org-log-repeat note)
3659 ("nologrepeat" org-log-repeat nil)
3660 ("fninline" org-footnote-define-inline t)
3661 ("nofninline" org-footnote-define-inline nil)
3662 ("fnlocal" org-footnote-section nil)
3663 ("fnauto" org-footnote-auto-label t)
3664 ("fnprompt" org-footnote-auto-label nil)
3665 ("fnconfirm" org-footnote-auto-label confirm)
3666 ("fnplain" org-footnote-auto-label plain)
3667 ("fnadjust" org-footnote-auto-adjust t)
3668 ("nofnadjust" org-footnote-auto-adjust nil)
3669 ("constcgs" constants-unit-system cgs)
3670 ("constSI" constants-unit-system SI)
3671 ("noptag" org-tag-persistent-alist nil)
3672 ("hideblocks" org-hide-block-startup t)
3673 ("nohideblocks" org-hide-block-startup nil))
3674 "Variable associated with STARTUP options for org-mode.
3675 Each element is a list of three items: The startup options as written
3676 in the #+STARTUP line, the corresponding variable, and the value to
3677 set this variable to if the option is found. An optional forth element PUSH
3678 means to push this value onto the list in the variable.")
3680 (defun org-set-regexps-and-options ()
3681 "Precompute regular expressions for current buffer."
3682 (when (org-mode-p)
3683 (org-set-local 'org-todo-kwd-alist nil)
3684 (org-set-local 'org-todo-key-alist nil)
3685 (org-set-local 'org-todo-key-trigger nil)
3686 (org-set-local 'org-todo-keywords-1 nil)
3687 (org-set-local 'org-done-keywords nil)
3688 (org-set-local 'org-todo-heads nil)
3689 (org-set-local 'org-todo-sets nil)
3690 (org-set-local 'org-todo-log-states nil)
3691 (org-set-local 'org-file-properties nil)
3692 (org-set-local 'org-file-tags nil)
3693 (let ((re (org-make-options-regexp
3694 '("CATEGORY" "TODO" "COLUMNS"
3695 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3696 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3697 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3698 (splitre "[ \t]+")
3699 kwds kws0 kwsa key log value cat arch tags const links hw dws
3700 tail sep kws1 prio props ftags drawers
3701 ext-setup-or-nil setup-contents (start 0))
3702 (save-excursion
3703 (save-restriction
3704 (widen)
3705 (goto-char (point-min))
3706 (while (or (and ext-setup-or-nil
3707 (string-match re ext-setup-or-nil start)
3708 (setq start (match-end 0)))
3709 (and (setq ext-setup-or-nil nil start 0)
3710 (re-search-forward re nil t)))
3711 (setq key (upcase (match-string 1 ext-setup-or-nil))
3712 value (org-match-string-no-properties 2 ext-setup-or-nil))
3713 (cond
3714 ((equal key "CATEGORY")
3715 (if (string-match "[ \t]+$" value)
3716 (setq value (replace-match "" t t value)))
3717 (setq cat value))
3718 ((member key '("SEQ_TODO" "TODO"))
3719 (push (cons 'sequence (org-split-string value splitre)) kwds))
3720 ((equal key "TYP_TODO")
3721 (push (cons 'type (org-split-string value splitre)) kwds))
3722 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3723 ;; general TODO-like setup
3724 (push (cons (intern (downcase (match-string 1 key)))
3725 (org-split-string value splitre)) kwds))
3726 ((equal key "TAGS")
3727 (setq tags (append tags (if tags '("\\n") nil)
3728 (org-split-string value splitre))))
3729 ((equal key "COLUMNS")
3730 (org-set-local 'org-columns-default-format value))
3731 ((equal key "LINK")
3732 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3733 (push (cons (match-string 1 value)
3734 (org-trim (match-string 2 value)))
3735 links)))
3736 ((equal key "PRIORITIES")
3737 (setq prio (org-split-string value " +")))
3738 ((equal key "PROPERTY")
3739 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3740 (push (cons (match-string 1 value) (match-string 2 value))
3741 props)))
3742 ((equal key "FILETAGS")
3743 (when (string-match "\\S-" value)
3744 (setq ftags
3745 (append
3746 ftags
3747 (apply 'append
3748 (mapcar (lambda (x) (org-split-string x ":"))
3749 (org-split-string value)))))))
3750 ((equal key "DRAWERS")
3751 (setq drawers (org-split-string value splitre)))
3752 ((equal key "CONSTANTS")
3753 (setq const (append const (org-split-string value splitre))))
3754 ((equal key "STARTUP")
3755 (let ((opts (org-split-string value splitre))
3756 l var val)
3757 (while (setq l (pop opts))
3758 (when (setq l (assoc l org-startup-options))
3759 (setq var (nth 1 l) val (nth 2 l))
3760 (if (not (nth 3 l))
3761 (set (make-local-variable var) val)
3762 (if (not (listp (symbol-value var)))
3763 (set (make-local-variable var) nil))
3764 (set (make-local-variable var) (symbol-value var))
3765 (add-to-list var val))))))
3766 ((equal key "ARCHIVE")
3767 (string-match " *$" value)
3768 (setq arch (replace-match "" t t value))
3769 (remove-text-properties 0 (length arch)
3770 '(face t fontified t) arch))
3771 ((equal key "SETUPFILE")
3772 (setq setup-contents (org-file-contents
3773 (expand-file-name
3774 (org-remove-double-quotes value))
3775 'noerror))
3776 (if (not ext-setup-or-nil)
3777 (setq ext-setup-or-nil setup-contents start 0)
3778 (setq ext-setup-or-nil
3779 (concat (substring ext-setup-or-nil 0 start)
3780 "\n" setup-contents "\n"
3781 (substring ext-setup-or-nil start)))))
3782 ))))
3783 (when cat
3784 (org-set-local 'org-category (intern cat))
3785 (push (cons "CATEGORY" cat) props))
3786 (when prio
3787 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3788 (setq prio (mapcar 'string-to-char prio))
3789 (org-set-local 'org-highest-priority (nth 0 prio))
3790 (org-set-local 'org-lowest-priority (nth 1 prio))
3791 (org-set-local 'org-default-priority (nth 2 prio)))
3792 (and props (org-set-local 'org-file-properties (nreverse props)))
3793 (and ftags (org-set-local 'org-file-tags
3794 (mapcar 'org-add-prop-inherited ftags)))
3795 (and drawers (org-set-local 'org-drawers drawers))
3796 (and arch (org-set-local 'org-archive-location arch))
3797 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3798 ;; Process the TODO keywords
3799 (unless kwds
3800 ;; Use the global values as if they had been given locally.
3801 (setq kwds (default-value 'org-todo-keywords))
3802 (if (stringp (car kwds))
3803 (setq kwds (list (cons org-todo-interpretation
3804 (default-value 'org-todo-keywords)))))
3805 (setq kwds (reverse kwds)))
3806 (setq kwds (nreverse kwds))
3807 (let (inter kws kw)
3808 (while (setq kws (pop kwds))
3809 (let ((kws (or
3810 (run-hook-with-args-until-success
3811 'org-todo-setup-filter-hook kws)
3812 kws)))
3813 (setq inter (pop kws) sep (member "|" kws)
3814 kws0 (delete "|" (copy-sequence kws))
3815 kwsa nil
3816 kws1 (mapcar
3817 (lambda (x)
3818 ;; 1 2
3819 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3820 (progn
3821 (setq kw (match-string 1 x)
3822 key (and (match-end 2) (match-string 2 x))
3823 log (org-extract-log-state-settings x))
3824 (push (cons kw (and key (string-to-char key))) kwsa)
3825 (and log (push log org-todo-log-states))
3827 (error "Invalid TODO keyword %s" x)))
3828 kws0)
3829 kwsa (if kwsa (append '((:startgroup))
3830 (nreverse kwsa)
3831 '((:endgroup))))
3832 hw (car kws1)
3833 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3834 tail (list inter hw (car dws) (org-last dws))))
3835 (add-to-list 'org-todo-heads hw 'append)
3836 (push kws1 org-todo-sets)
3837 (setq org-done-keywords (append org-done-keywords dws nil))
3838 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3839 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3840 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3841 (setq org-todo-sets (nreverse org-todo-sets)
3842 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3843 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3844 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3845 ;; Process the constants
3846 (when const
3847 (let (e cst)
3848 (while (setq e (pop const))
3849 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3850 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3851 (setq org-table-formula-constants-local cst)))
3853 ;; Process the tags.
3854 (when tags
3855 (let (e tgs)
3856 (while (setq e (pop tags))
3857 (cond
3858 ((equal e "{") (push '(:startgroup) tgs))
3859 ((equal e "}") (push '(:endgroup) tgs))
3860 ((equal e "\\n") (push '(:newline) tgs))
3861 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3862 (push (cons (match-string 1 e)
3863 (string-to-char (match-string 2 e)))
3864 tgs))
3865 (t (push (list e) tgs))))
3866 (org-set-local 'org-tag-alist nil)
3867 (while (setq e (pop tgs))
3868 (or (and (stringp (car e))
3869 (assoc (car e) org-tag-alist))
3870 (push e org-tag-alist)))))
3872 ;; Compute the regular expressions and other local variables
3873 (if (not org-done-keywords)
3874 (setq org-done-keywords (and org-todo-keywords-1
3875 (list (org-last org-todo-keywords-1)))))
3876 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3877 (length org-scheduled-string)
3878 (length org-clock-string)
3879 (length org-closed-string)))
3880 org-drawer-regexp
3881 (concat "^[ \t]*:\\("
3882 (mapconcat 'regexp-quote org-drawers "\\|")
3883 "\\):[ \t]*$")
3884 org-not-done-keywords
3885 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3886 org-todo-regexp
3887 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3888 "\\|") "\\)\\>")
3889 org-not-done-regexp
3890 (concat "\\<\\("
3891 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3892 "\\)\\>")
3893 org-not-done-heading-regexp
3894 (concat "^\\(\\*+\\)[ \t]+\\("
3895 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3896 "\\)\\>")
3897 org-todo-line-regexp
3898 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3899 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3900 "\\)\\>\\)?[ \t]*\\(.*\\)")
3901 org-complex-heading-regexp
3902 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3903 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3904 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3905 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3906 org-complex-heading-regexp-format
3907 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3908 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3909 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
3910 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3911 org-nl-done-regexp
3912 (concat "\n\\*+[ \t]+"
3913 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3914 "\\)" "\\>")
3915 org-todo-line-tags-regexp
3916 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3917 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3918 (org-re
3919 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3920 org-looking-at-done-regexp
3921 (concat "^" "\\(?:"
3922 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3923 "\\>")
3924 org-deadline-regexp (concat "\\<" org-deadline-string)
3925 org-deadline-time-regexp
3926 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3927 org-deadline-line-regexp
3928 (concat "\\<\\(" org-deadline-string "\\).*")
3929 org-scheduled-regexp
3930 (concat "\\<" org-scheduled-string)
3931 org-scheduled-time-regexp
3932 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3933 org-closed-time-regexp
3934 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3935 org-keyword-time-regexp
3936 (concat "\\<\\(" org-scheduled-string
3937 "\\|" org-deadline-string
3938 "\\|" org-closed-string
3939 "\\|" org-clock-string "\\)"
3940 " *[[<]\\([^]>]+\\)[]>]")
3941 org-keyword-time-not-clock-regexp
3942 (concat "\\<\\(" org-scheduled-string
3943 "\\|" org-deadline-string
3944 "\\|" org-closed-string
3945 "\\)"
3946 " *[[<]\\([^]>]+\\)[]>]")
3947 org-maybe-keyword-time-regexp
3948 (concat "\\(\\<\\(" org-scheduled-string
3949 "\\|" org-deadline-string
3950 "\\|" org-closed-string
3951 "\\|" org-clock-string "\\)\\)?"
3952 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3953 org-planning-or-clock-line-re
3954 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3955 "\\|" org-deadline-string
3956 "\\|" org-closed-string "\\|" org-clock-string
3957 "\\)\\>\\)")
3959 (org-compute-latex-and-specials-regexp)
3960 (org-set-font-lock-defaults))))
3962 (defun org-file-contents (file &optional noerror)
3963 "Return the contents of FILE, as a string."
3964 (if (or (not file)
3965 (not (file-readable-p file)))
3966 (if noerror
3967 (progn
3968 (message "Cannot read file %s" file)
3969 (ding) (sit-for 2)
3971 (error "Cannot read file %s" file))
3972 (with-temp-buffer
3973 (insert-file-contents file)
3974 (buffer-string))))
3976 (defun org-extract-log-state-settings (x)
3977 "Extract the log state setting from a TODO keyword string.
3978 This will extract info from a string like \"WAIT(w@/!)\"."
3979 (let (kw key log1 log2)
3980 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3981 (setq kw (match-string 1 x)
3982 key (and (match-end 2) (match-string 2 x))
3983 log1 (and (match-end 3) (match-string 3 x))
3984 log2 (and (match-end 4) (match-string 4 x)))
3985 (and (or log1 log2)
3986 (list kw
3987 (and log1 (if (equal log1 "!") 'time 'note))
3988 (and log2 (if (equal log2 "!") 'time 'note)))))))
3990 (defun org-remove-keyword-keys (list)
3991 "Remove a pair of parenthesis at the end of each string in LIST."
3992 (mapcar (lambda (x)
3993 (if (string-match "(.*)$" x)
3994 (substring x 0 (match-beginning 0))
3996 list))
3998 ;; FIXME: this could be done much better, using second characters etc.
3999 (defun org-assign-fast-keys (alist)
4000 "Assign fast keys to a keyword-key alist.
4001 Respect keys that are already there."
4002 (let (new e k c c1 c2 (char ?a))
4003 (while (setq e (pop alist))
4004 (cond
4005 ((equal e '(:startgroup)) (push e new))
4006 ((equal e '(:endgroup)) (push e new))
4007 ((equal e '(:newline)) (push e new))
4009 (setq k (car e) c2 nil)
4010 (if (cdr e)
4011 (setq c (cdr e))
4012 ;; automatically assign a character.
4013 (setq c1 (string-to-char
4014 (downcase (substring
4015 k (if (= (string-to-char k) ?@) 1 0)))))
4016 (if (or (rassoc c1 new) (rassoc c1 alist))
4017 (while (or (rassoc char new) (rassoc char alist))
4018 (setq char (1+ char)))
4019 (setq c2 c1))
4020 (setq c (or c2 char)))
4021 (push (cons k c) new))))
4022 (nreverse new)))
4024 ;;; Some variables used in various places
4026 (defvar org-window-configuration nil
4027 "Used in various places to store a window configuration.")
4028 (defvar org-selected-window nil
4029 "Used in various places to store a window configuration.")
4030 (defvar org-finish-function nil
4031 "Function to be called when `C-c C-c' is used.
4032 This is for getting out of special buffers like remember.")
4035 ;; FIXME: Occasionally check by commenting these, to make sure
4036 ;; no other functions uses these, forgetting to let-bind them.
4037 (defvar entry)
4038 (defvar last-state)
4039 (defvar date)
4041 ;; Defined somewhere in this file, but used before definition.
4042 (defvar org-html-entities)
4043 (defvar org-struct-menu)
4044 (defvar org-org-menu)
4045 (defvar org-tbl-menu)
4047 ;;;; Define the Org-mode
4049 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4050 (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."))
4053 ;; We use a before-change function to check if a table might need
4054 ;; an update.
4055 (defvar org-table-may-need-update t
4056 "Indicates that a table might need an update.
4057 This variable is set by `org-before-change-function'.
4058 `org-table-align' sets it back to nil.")
4059 (defun org-before-change-function (beg end)
4060 "Every change indicates that a table might need an update."
4061 (setq org-table-may-need-update t))
4062 (defvar org-mode-map)
4063 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4064 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4065 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4066 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4067 (defvar org-table-buffer-is-an nil)
4068 (defconst org-outline-regexp "\\*+ ")
4070 ;;;###autoload
4071 (define-derived-mode org-mode outline-mode "Org"
4072 "Outline-based notes management and organizer, alias
4073 \"Carsten's outline-mode for keeping track of everything.\"
4075 Org-mode develops organizational tasks around a NOTES file which
4076 contains information about projects as plain text. Org-mode is
4077 implemented on top of outline-mode, which is ideal to keep the content
4078 of large files well structured. It supports ToDo items, deadlines and
4079 time stamps, which magically appear in the diary listing of the Emacs
4080 calendar. Tables are easily created with a built-in table editor.
4081 Plain text URL-like links connect to websites, emails (VM), Usenet
4082 messages (Gnus), BBDB entries, and any files related to the project.
4083 For printing and sharing of notes, an Org-mode file (or a part of it)
4084 can be exported as a structured ASCII or HTML file.
4086 The following commands are available:
4088 \\{org-mode-map}"
4090 ;; Get rid of Outline menus, they are not needed
4091 ;; Need to do this here because define-derived-mode sets up
4092 ;; the keymap so late. Still, it is a waste to call this each time
4093 ;; we switch another buffer into org-mode.
4094 (if (featurep 'xemacs)
4095 (when (boundp 'outline-mode-menu-heading)
4096 ;; Assume this is Greg's port, it used easymenu
4097 (easy-menu-remove outline-mode-menu-heading)
4098 (easy-menu-remove outline-mode-menu-show)
4099 (easy-menu-remove outline-mode-menu-hide))
4100 (define-key org-mode-map [menu-bar headings] 'undefined)
4101 (define-key org-mode-map [menu-bar hide] 'undefined)
4102 (define-key org-mode-map [menu-bar show] 'undefined))
4104 (org-load-modules-maybe)
4105 (easy-menu-add org-org-menu)
4106 (easy-menu-add org-tbl-menu)
4107 (org-install-agenda-files-menu)
4108 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4109 (org-add-to-invisibility-spec '(org-cwidth))
4110 (org-add-to-invisibility-spec '(org-hide-block . t))
4111 (when (featurep 'xemacs)
4112 (org-set-local 'line-move-ignore-invisible t))
4113 (org-set-local 'outline-regexp org-outline-regexp)
4114 (org-set-local 'outline-level 'org-outline-level)
4115 (when (and org-ellipsis
4116 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4117 (fboundp 'make-glyph-code))
4118 (unless org-display-table
4119 (setq org-display-table (make-display-table)))
4120 (set-display-table-slot
4121 org-display-table 4
4122 (vconcat (mapcar
4123 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4124 org-ellipsis)))
4125 (if (stringp org-ellipsis) org-ellipsis "..."))))
4126 (setq buffer-display-table org-display-table))
4127 (org-set-regexps-and-options)
4128 (when (and org-tag-faces (not org-tags-special-faces-re))
4129 ;; tag faces set outside customize.... force initialization.
4130 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4131 ;; Calc embedded
4132 (org-set-local 'calc-embedded-open-mode "# ")
4133 (modify-syntax-entry ?# "<")
4134 (modify-syntax-entry ?@ "w")
4135 (if org-startup-truncated (setq truncate-lines t))
4136 (org-set-local 'font-lock-unfontify-region-function
4137 'org-unfontify-region)
4138 ;; Activate before-change-function
4139 (org-set-local 'org-table-may-need-update t)
4140 (org-add-hook 'before-change-functions 'org-before-change-function nil
4141 'local)
4142 ;; Check for running clock before killing a buffer
4143 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4144 ;; Paragraphs and auto-filling
4145 (org-set-autofill-regexps)
4146 (setq indent-line-function 'org-indent-line-function)
4147 (org-update-radio-target-regexp)
4148 ;; Make sure dependence stuff works reliably, even for users who set it
4149 ;; too late :-(
4150 (if org-enforce-todo-dependencies
4151 (add-hook 'org-blocker-hook
4152 'org-block-todo-from-children-or-siblings-or-parent)
4153 (remove-hook 'org-blocker-hook
4154 'org-block-todo-from-children-or-siblings-or-parent))
4155 (if org-enforce-todo-checkbox-dependencies
4156 (add-hook 'org-blocker-hook
4157 'org-block-todo-from-checkboxes)
4158 (remove-hook 'org-blocker-hook
4159 'org-block-todo-from-checkboxes))
4161 ;; Comment characters
4162 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4163 (org-set-local 'comment-padding " ")
4165 ;; Align options lines
4166 (org-set-local
4167 'align-mode-rules-list
4168 '((org-in-buffer-settings
4169 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4170 (modes . '(org-mode)))))
4172 ;; Imenu
4173 (org-set-local 'imenu-create-index-function
4174 'org-imenu-get-tree)
4176 ;; Make isearch reveal context
4177 (if (or (featurep 'xemacs)
4178 (not (boundp 'outline-isearch-open-invisible-function)))
4179 ;; Emacs 21 and XEmacs make use of the hook
4180 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4181 ;; Emacs 22 deals with this through a special variable
4182 (org-set-local 'outline-isearch-open-invisible-function
4183 (lambda (&rest ignore) (org-show-context 'isearch))))
4185 ;; If empty file that did not turn on org-mode automatically, make it to.
4186 (if (and org-insert-mode-line-in-empty-file
4187 (interactive-p)
4188 (= (point-min) (point-max)))
4189 (insert "# -*- mode: org -*-\n\n"))
4191 (unless org-inhibit-startup
4192 (when org-startup-align-all-tables
4193 (let ((bmp (buffer-modified-p)))
4194 (org-table-map-tables 'org-table-align)
4195 (set-buffer-modified-p bmp)))
4196 (when org-startup-indented
4197 (require 'org-indent)
4198 (org-indent-mode 1))
4199 (org-set-startup-visibility)))
4201 (when (fboundp 'abbrev-table-put)
4202 (abbrev-table-put org-mode-abbrev-table
4203 :parents (list text-mode-abbrev-table)))
4205 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4207 (defun org-current-time ()
4208 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4209 (if (> (car org-time-stamp-rounding-minutes) 1)
4210 (let ((r (car org-time-stamp-rounding-minutes))
4211 (time (decode-time)))
4212 (apply 'encode-time
4213 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4214 (nthcdr 2 time))))
4215 (current-time)))
4217 ;;;; Font-Lock stuff, including the activators
4219 (defvar org-mouse-map (make-sparse-keymap))
4220 (org-defkey org-mouse-map
4221 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4222 (org-defkey org-mouse-map
4223 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4224 (when org-mouse-1-follows-link
4225 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4226 (when org-tab-follows-link
4227 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4228 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4230 (require 'font-lock)
4232 (defconst org-non-link-chars "]\t\n\r<>")
4233 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4234 "shell" "elisp"))
4235 (defvar org-link-types-re nil
4236 "Matches a link that has a url-like prefix like \"http:\"")
4237 (defvar org-link-re-with-space nil
4238 "Matches a link with spaces, optional angular brackets around it.")
4239 (defvar org-link-re-with-space2 nil
4240 "Matches a link with spaces, optional angular brackets around it.")
4241 (defvar org-link-re-with-space3 nil
4242 "Matches a link with spaces, only for internal part in bracket links.")
4243 (defvar org-angle-link-re nil
4244 "Matches link with angular brackets, spaces are allowed.")
4245 (defvar org-plain-link-re nil
4246 "Matches plain link, without spaces.")
4247 (defvar org-bracket-link-regexp nil
4248 "Matches a link in double brackets.")
4249 (defvar org-bracket-link-analytic-regexp nil
4250 "Regular expression used to analyze links.
4251 Here is what the match groups contain after a match:
4252 1: http:
4253 2: http
4254 3: path
4255 4: [desc]
4256 5: desc")
4257 (defvar org-bracket-link-analytic-regexp++ nil
4258 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4259 (defvar org-any-link-re nil
4260 "Regular expression matching any link.")
4262 (defun org-make-link-regexps ()
4263 "Update the link regular expressions.
4264 This should be called after the variable `org-link-types' has changed."
4265 (setq org-link-types-re
4266 (concat
4267 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4268 org-link-re-with-space
4269 (concat
4270 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4271 "\\([^" org-non-link-chars " ]"
4272 "[^" org-non-link-chars "]*"
4273 "[^" org-non-link-chars " ]\\)>?")
4274 org-link-re-with-space2
4275 (concat
4276 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4277 "\\([^" org-non-link-chars " ]"
4278 "[^\t\n\r]*"
4279 "[^" org-non-link-chars " ]\\)>?")
4280 org-link-re-with-space3
4281 (concat
4282 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4283 "\\([^" org-non-link-chars " ]"
4284 "[^\t\n\r]*\\)")
4285 org-angle-link-re
4286 (concat
4287 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4288 "\\([^" org-non-link-chars " ]"
4289 "[^" org-non-link-chars "]*"
4290 "\\)>")
4291 org-plain-link-re
4292 (concat
4293 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4294 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4295 org-bracket-link-regexp
4296 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4297 org-bracket-link-analytic-regexp
4298 (concat
4299 "\\[\\["
4300 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4301 "\\([^]]+\\)"
4302 "\\]"
4303 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4304 "\\]")
4305 org-bracket-link-analytic-regexp++
4306 (concat
4307 "\\[\\["
4308 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4309 "\\([^]]+\\)"
4310 "\\]"
4311 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4312 "\\]")
4313 org-any-link-re
4314 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4315 org-angle-link-re "\\)\\|\\("
4316 org-plain-link-re "\\)")))
4318 (org-make-link-regexps)
4320 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4321 "Regular expression for fast time stamp matching.")
4322 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4323 "Regular expression for fast time stamp matching.")
4324 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4325 "Regular expression matching time strings for analysis.
4326 This one does not require the space after the date, so it can be used
4327 on a string that terminates immediately after the date.")
4328 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4329 "Regular expression matching time strings for analysis.")
4330 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4331 "Regular expression matching time stamps, with groups.")
4332 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4333 "Regular expression matching time stamps (also [..]), with groups.")
4334 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4335 "Regular expression matching a time stamp range.")
4336 (defconst org-tr-regexp-both
4337 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4338 "Regular expression matching a time stamp range.")
4339 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4340 org-ts-regexp "\\)?")
4341 "Regular expression matching a time stamp or time stamp range.")
4342 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4343 org-ts-regexp-both "\\)?")
4344 "Regular expression matching a time stamp or time stamp range.
4345 The time stamps may be either active or inactive.")
4347 (defvar org-emph-face nil)
4349 (defun org-do-emphasis-faces (limit)
4350 "Run through the buffer and add overlays to links."
4351 (let (rtn a)
4352 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4353 (if (not (= (char-after (match-beginning 3))
4354 (char-after (match-beginning 4))))
4355 (progn
4356 (setq rtn t)
4357 (setq a (assoc (match-string 3) org-emphasis-alist))
4358 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4359 'face
4360 (nth 1 a))
4361 (and (nth 4 a)
4362 (org-remove-flyspell-overlays-in
4363 (match-beginning 0) (match-end 0)))
4364 (add-text-properties (match-beginning 2) (match-end 2)
4365 '(font-lock-multiline t))
4366 (when org-hide-emphasis-markers
4367 (add-text-properties (match-end 4) (match-beginning 5)
4368 '(invisible org-link))
4369 (add-text-properties (match-beginning 3) (match-end 3)
4370 '(invisible org-link)))))
4371 (backward-char 1))
4372 rtn))
4374 (defun org-emphasize (&optional char)
4375 "Insert or change an emphasis, i.e. a font like bold or italic.
4376 If there is an active region, change that region to a new emphasis.
4377 If there is no region, just insert the marker characters and position
4378 the cursor between them.
4379 CHAR should be either the marker character, or the first character of the
4380 HTML tag associated with that emphasis. If CHAR is a space, the means
4381 to remove the emphasis of the selected region.
4382 If char is not given (for example in an interactive call) it
4383 will be prompted for."
4384 (interactive)
4385 (let ((eal org-emphasis-alist) e det
4386 (erc org-emphasis-regexp-components)
4387 (prompt "")
4388 (string "") beg end move tag c s)
4389 (if (org-region-active-p)
4390 (setq beg (region-beginning) end (region-end)
4391 string (buffer-substring beg end))
4392 (setq move t))
4394 (while (setq e (pop eal))
4395 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4396 c (aref tag 0))
4397 (push (cons c (string-to-char (car e))) det)
4398 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4399 (substring tag 1)))))
4400 (setq det (nreverse det))
4401 (unless char
4402 (message "%s" (concat "Emphasis marker or tag:" prompt))
4403 (setq char (read-char-exclusive)))
4404 (setq char (or (cdr (assoc char det)) char))
4405 (if (equal char ?\ )
4406 (setq s "" move nil)
4407 (unless (assoc (char-to-string char) org-emphasis-alist)
4408 (error "No such emphasis marker: \"%c\"" char))
4409 (setq s (char-to-string char)))
4410 (while (and (> (length string) 1)
4411 (equal (substring string 0 1) (substring string -1))
4412 (assoc (substring string 0 1) org-emphasis-alist))
4413 (setq string (substring string 1 -1)))
4414 (setq string (concat s string s))
4415 (if beg (delete-region beg end))
4416 (unless (or (bolp)
4417 (string-match (concat "[" (nth 0 erc) "\n]")
4418 (char-to-string (char-before (point)))))
4419 (insert " "))
4420 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4421 (char-to-string (char-after (point))))
4422 (insert " ") (backward-char 1))
4423 (insert string)
4424 (and move (backward-char 1))))
4426 (defconst org-nonsticky-props
4427 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4429 (defsubst org-rear-nonsticky-at (pos)
4430 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4432 (defun org-activate-plain-links (limit)
4433 "Run through the buffer and add overlays to links."
4434 (catch 'exit
4435 (let (f)
4436 (if (re-search-forward org-plain-link-re limit t)
4437 (progn
4438 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4439 (setq f (get-text-property (match-beginning 0) 'face))
4440 (if (or (eq f 'org-tag)
4441 (and (listp f) (memq 'org-tag f)))
4443 (add-text-properties (match-beginning 0) (match-end 0)
4444 (list 'mouse-face 'highlight
4445 'keymap org-mouse-map))
4446 (org-rear-nonsticky-at (match-end 0)))
4447 t)))))
4449 (defun org-activate-code (limit)
4450 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4451 (progn
4452 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4453 (remove-text-properties (match-beginning 0) (match-end 0)
4454 '(display t invisible t intangible t))
4455 t)))
4457 (defun org-fontify-meta-lines-and-blocks (limit)
4458 "Fontify #+ lines and blocks, in the correct ways."
4459 (let ((case-fold-search t))
4460 (if (re-search-forward
4461 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4462 limit t)
4463 (let ((beg (match-beginning 0))
4464 (beg1 (line-beginning-position 2))
4465 (dc1 (downcase (match-string 2)))
4466 (dc3 (downcase (match-string 3)))
4467 end end1 quoting)
4468 (cond
4469 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4470 ;; a single line of backend-specific content
4471 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4472 (remove-text-properties (match-beginning 0) (match-end 0)
4473 '(display t invisible t intangible t))
4474 (add-text-properties (match-beginning 1) (match-end 3)
4475 '(font-lock-fontified t face org-meta-line))
4476 (add-text-properties (match-beginning 6) (match-end 6)
4477 '(font-lock-fontified t face org-block))
4479 ((and (match-end 4) (equal dc3 "begin"))
4480 ;; Truely a block
4481 (setq quoting (member (downcase (match-string 5))
4482 org-protecting-blocks))
4483 (when (re-search-forward
4484 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4485 nil t) ;; on purpose, we look further than LIMIT
4486 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4487 (when quoting
4488 (remove-text-properties beg end
4489 '(display t invisible t intangible t)))
4490 (add-text-properties
4491 beg end
4492 '(font-lock-fontified t font-lock-multiline t))
4493 (add-text-properties beg beg1 '(face org-meta-line))
4494 (add-text-properties end1 end '(face org-meta-line))
4495 (when quoting
4496 (add-text-properties beg1 end1 '(face org-block)))
4498 ((not (member (char-after beg) '(?\ ?\t)))
4499 ;; just any other in-buffer setting, but not indented
4500 (add-text-properties
4501 beg (match-end 0)
4502 '(font-lock-fontified t face org-meta-line))
4504 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4505 "orgtbl:" "tblfm:" "tblname:"))
4506 (and (match-end 4) (equal dc3 "attr")))
4507 (add-text-properties
4508 beg (match-end 0)
4509 '(font-lock-fontified t face org-meta-line))
4511 ((member dc3 '(" " ""))
4512 (add-text-properties
4513 beg (match-end 0)
4514 '(font-lock-fontified t face font-lock-comment-face)))
4515 (t nil))))))
4517 (defun org-activate-angle-links (limit)
4518 "Run through the buffer and add overlays to links."
4519 (if (re-search-forward org-angle-link-re limit t)
4520 (progn
4521 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4522 (add-text-properties (match-beginning 0) (match-end 0)
4523 (list 'mouse-face 'highlight
4524 'keymap org-mouse-map))
4525 (org-rear-nonsticky-at (match-end 0))
4526 t)))
4528 (defun org-activate-footnote-links (limit)
4529 "Run through the buffer and add overlays to links."
4530 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4531 limit t)
4532 (progn
4533 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4534 (add-text-properties (match-beginning 2) (match-end 2)
4535 (list 'mouse-face 'highlight
4536 'keymap org-mouse-map
4537 'help-echo
4538 (if (= (point-at-bol) (match-beginning 2))
4539 "Footnote definition"
4540 "Footnote reference")
4542 (org-rear-nonsticky-at (match-end 2))
4543 t)))
4545 (defun org-activate-bracket-links (limit)
4546 "Run through the buffer and add overlays to bracketed links."
4547 (if (re-search-forward org-bracket-link-regexp limit t)
4548 (let* ((help (concat "LINK: "
4549 (org-match-string-no-properties 1)))
4550 ;; FIXME: above we should remove the escapes.
4551 ;; but that requires another match, protecting match data,
4552 ;; a lot of overhead for font-lock.
4553 (ip (org-maybe-intangible
4554 (list 'invisible 'org-link
4555 'keymap org-mouse-map 'mouse-face 'highlight
4556 'font-lock-multiline t 'help-echo help)))
4557 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4558 'font-lock-multiline t 'help-echo help)))
4559 ;; We need to remove the invisible property here. Table narrowing
4560 ;; may have made some of this invisible.
4561 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4562 (remove-text-properties (match-beginning 0) (match-end 0)
4563 '(invisible nil))
4564 (if (match-end 3)
4565 (progn
4566 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4567 (org-rear-nonsticky-at (match-beginning 3))
4568 (add-text-properties (match-beginning 3) (match-end 3) vp)
4569 (org-rear-nonsticky-at (match-end 3))
4570 (add-text-properties (match-end 3) (match-end 0) ip)
4571 (org-rear-nonsticky-at (match-end 0)))
4572 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4573 (org-rear-nonsticky-at (match-beginning 1))
4574 (add-text-properties (match-beginning 1) (match-end 1) vp)
4575 (org-rear-nonsticky-at (match-end 1))
4576 (add-text-properties (match-end 1) (match-end 0) ip)
4577 (org-rear-nonsticky-at (match-end 0)))
4578 t)))
4580 (defun org-activate-dates (limit)
4581 "Run through the buffer and add overlays to dates."
4582 (if (re-search-forward org-tsr-regexp-both limit t)
4583 (progn
4584 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4585 (add-text-properties (match-beginning 0) (match-end 0)
4586 (list 'mouse-face 'highlight
4587 'keymap org-mouse-map))
4588 (org-rear-nonsticky-at (match-end 0))
4589 (when org-display-custom-times
4590 (if (match-end 3)
4591 (org-display-custom-time (match-beginning 3) (match-end 3)))
4592 (org-display-custom-time (match-beginning 1) (match-end 1)))
4593 t)))
4595 (defvar org-target-link-regexp nil
4596 "Regular expression matching radio targets in plain text.")
4597 (make-variable-buffer-local 'org-target-link-regexp)
4598 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4599 "Regular expression matching a link target.")
4600 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4601 "Regular expression matching a radio target.")
4602 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4603 "Regular expression matching any target.")
4605 (defun org-activate-target-links (limit)
4606 "Run through the buffer and add overlays to target matches."
4607 (when org-target-link-regexp
4608 (let ((case-fold-search t))
4609 (if (re-search-forward org-target-link-regexp limit t)
4610 (progn
4611 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4612 (add-text-properties (match-beginning 0) (match-end 0)
4613 (list 'mouse-face 'highlight
4614 'keymap org-mouse-map
4615 'help-echo "Radio target link"
4616 'org-linked-text t))
4617 (org-rear-nonsticky-at (match-end 0))
4618 t)))))
4620 (defun org-update-radio-target-regexp ()
4621 "Find all radio targets in this file and update the regular expression."
4622 (interactive)
4623 (when (memq 'radio org-activate-links)
4624 (setq org-target-link-regexp
4625 (org-make-target-link-regexp (org-all-targets 'radio)))
4626 (org-restart-font-lock)))
4628 (defun org-hide-wide-columns (limit)
4629 (let (s e)
4630 (setq s (text-property-any (point) (or limit (point-max))
4631 'org-cwidth t))
4632 (when s
4633 (setq e (next-single-property-change s 'org-cwidth))
4634 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4635 (goto-char e)
4636 t)))
4638 (defvar org-latex-and-specials-regexp nil
4639 "Regular expression for highlighting export special stuff.")
4640 (defvar org-match-substring-regexp)
4641 (defvar org-match-substring-with-braces-regexp)
4643 ;; This should be with the exporter code, but we also use if for font-locking
4644 (defconst org-export-html-special-string-regexps
4645 '(("\\\\-" . "&shy;")
4646 ("---\\([^-]\\)" . "&mdash;\\1")
4647 ("--\\([^-]\\)" . "&ndash;\\1")
4648 ("\\.\\.\\." . "&hellip;"))
4649 "Regular expressions for special string conversion.")
4652 (defun org-compute-latex-and-specials-regexp ()
4653 "Compute regular expression for stuff treated specially by exporters."
4654 (if (not org-highlight-latex-fragments-and-specials)
4655 (org-set-local 'org-latex-and-specials-regexp nil)
4656 (require 'org-exp)
4657 (let*
4658 ((matchers (plist-get org-format-latex-options :matchers))
4659 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4660 org-latex-regexps)))
4661 (options (org-combine-plists (org-default-export-plist)
4662 (org-infile-export-plist)))
4663 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4664 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4665 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4666 (org-export-html-expand (plist-get options :expand-quoted-html))
4667 (org-export-with-special-strings (plist-get options :special-strings))
4668 (re-sub
4669 (cond
4670 ((equal org-export-with-sub-superscripts '{})
4671 (list org-match-substring-with-braces-regexp))
4672 (org-export-with-sub-superscripts
4673 (list org-match-substring-regexp))
4674 (t nil)))
4675 (re-latex
4676 (if org-export-with-LaTeX-fragments
4677 (mapcar (lambda (x) (nth 1 x)) latexs)))
4678 (re-macros
4679 (if org-export-with-TeX-macros
4680 (list (concat "\\\\"
4681 (regexp-opt
4682 (append (mapcar 'car org-html-entities)
4683 (if (boundp 'org-latex-entities)
4684 (mapcar (lambda (x)
4685 (or (car-safe x) x))
4686 org-latex-entities)
4687 nil))
4688 'words))) ; FIXME
4690 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4691 (re-special (if org-export-with-special-strings
4692 (mapcar (lambda (x) (car x))
4693 org-export-html-special-string-regexps)))
4694 (re-rest
4695 (delq nil
4696 (list
4697 (if org-export-html-expand "@<[^>\n]+>")
4698 ))))
4699 (org-set-local
4700 'org-latex-and-specials-regexp
4701 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4702 re-rest) "\\|")))))
4704 (defun org-do-latex-and-special-faces (limit)
4705 "Run through the buffer and add overlays to links."
4706 (when org-latex-and-specials-regexp
4707 (let (rtn d)
4708 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4709 limit t))
4710 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4711 'face))
4712 '(org-code org-verbatim underline)))
4713 (progn
4714 (setq rtn t
4715 d (cond ((member (char-after (1+ (match-beginning 0)))
4716 '(?_ ?^)) 1)
4717 (t 0)))
4718 (font-lock-prepend-text-property
4719 (+ d (match-beginning 0)) (match-end 0)
4720 'face 'org-latex-and-export-specials)
4721 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4722 '(font-lock-multiline t)))))
4723 rtn)))
4725 (defun org-restart-font-lock ()
4726 "Restart font-lock-mode, to force refontification."
4727 (when (and (boundp 'font-lock-mode) font-lock-mode)
4728 (font-lock-mode -1)
4729 (font-lock-mode 1)))
4731 (defun org-all-targets (&optional radio)
4732 "Return a list of all targets in this file.
4733 With optional argument RADIO, only find radio targets."
4734 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4735 rtn)
4736 (save-excursion
4737 (goto-char (point-min))
4738 (while (re-search-forward re nil t)
4739 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4740 rtn)))
4742 (defun org-make-target-link-regexp (targets)
4743 "Make regular expression matching all strings in TARGETS.
4744 The regular expression finds the targets also if there is a line break
4745 between words."
4746 (and targets
4747 (concat
4748 "\\<\\("
4749 (mapconcat
4750 (lambda (x)
4751 (while (string-match " +" x)
4752 (setq x (replace-match "\\s-+" t t x)))
4754 targets
4755 "\\|")
4756 "\\)\\>")))
4758 (defun org-activate-tags (limit)
4759 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4760 (progn
4761 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4762 (add-text-properties (match-beginning 1) (match-end 1)
4763 (list 'mouse-face 'highlight
4764 'keymap org-mouse-map))
4765 (org-rear-nonsticky-at (match-end 1))
4766 t)))
4768 (defun org-outline-level ()
4769 "Compute the outline level of the heading at point.
4770 This function assumes that the cursor is at the beginning of a line matched
4771 by outline-regexp. Otherwise it returns garbage.
4772 If this is called at a normal headline, the level is the number of stars.
4773 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4774 For plain list items, if they are matched by `outline-regexp', this returns
4775 1000 plus the line indentation."
4776 (save-excursion
4777 (looking-at outline-regexp)
4778 (if (match-beginning 1)
4779 (+ (org-get-string-indentation (match-string 1)) 1000)
4780 (1- (- (match-end 0) (match-beginning 0))))))
4782 (defvar org-font-lock-keywords nil)
4784 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4785 "Regular expression matching a property line.")
4787 (defvar org-font-lock-hook nil
4788 "Functions to be called for special font lock stuff.")
4790 (defun org-font-lock-hook (limit)
4791 (run-hook-with-args 'org-font-lock-hook limit))
4793 (defun org-set-font-lock-defaults ()
4794 (let* ((em org-fontify-emphasized-text)
4795 (lk org-activate-links)
4796 (org-font-lock-extra-keywords
4797 (list
4798 ;; Call the hook
4799 '(org-font-lock-hook)
4800 ;; Headlines
4801 `(,(if org-fontify-whole-heading-line
4802 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4803 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4804 (1 (org-get-level-face 1))
4805 (2 (org-get-level-face 2))
4806 (3 (org-get-level-face 3)))
4807 ;; Table lines
4808 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4809 (1 'org-table t))
4810 ;; Table internals
4811 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4812 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4813 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4814 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4815 ;; Drawers
4816 (list org-drawer-regexp '(0 'org-special-keyword t))
4817 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4818 ;; Properties
4819 (list org-property-re
4820 '(1 'org-special-keyword t)
4821 '(3 'org-property-value t))
4822 ;; Links
4823 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4824 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4825 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4826 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4827 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4828 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4829 (if (memq 'footnote lk) '(org-activate-footnote-links
4830 (2 'org-footnote t)))
4831 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4832 '(org-hide-wide-columns (0 nil append))
4833 ;; TODO lines
4834 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4835 '(1 (org-get-todo-face 1) t))
4836 ;; DONE
4837 (if org-fontify-done-headline
4838 (list (concat "^[*]+ +\\<\\("
4839 (mapconcat 'regexp-quote org-done-keywords "\\|")
4840 "\\)\\(.*\\)")
4841 '(2 'org-headline-done t))
4842 nil)
4843 ;; Priorities
4844 '(org-font-lock-add-priority-faces)
4845 ;; Tags
4846 '(org-font-lock-add-tag-faces)
4847 ;; Special keywords
4848 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4849 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4850 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4851 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4852 ;; Emphasis
4853 (if em
4854 (if (featurep 'xemacs)
4855 '(org-do-emphasis-faces (0 nil append))
4856 '(org-do-emphasis-faces)))
4857 ;; Checkboxes
4858 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4859 2 'org-checkbox prepend)
4860 (if org-provide-checkbox-statistics
4861 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4862 (0 (org-get-checkbox-statistics-face) t)))
4863 ;; Description list items
4864 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4865 2 'bold prepend)
4866 ;; ARCHIVEd headings
4867 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4868 '(1 'org-archived prepend))
4869 ;; Specials
4870 '(org-do-latex-and-special-faces)
4871 ;; Code
4872 '(org-activate-code (1 'org-code t))
4873 ;; COMMENT
4874 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4875 "\\|" org-quote-string "\\)\\>")
4876 '(1 'org-special-keyword t))
4877 '("^#.*" (0 'font-lock-comment-face t))
4878 ;; Blocks and meta lines
4879 '(org-fontify-meta-lines-and-blocks)
4881 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4882 ;; Now set the full font-lock-keywords
4883 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4884 (org-set-local 'font-lock-defaults
4885 '(org-font-lock-keywords t nil nil backward-paragraph))
4886 (kill-local-variable 'font-lock-keywords) nil))
4888 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4889 "Fontify string S like in Org-mode"
4890 (with-temp-buffer
4891 (insert s)
4892 (let ((org-odd-levels-only odd-levels))
4893 (org-mode)
4894 (font-lock-fontify-buffer)
4895 (buffer-string))))
4897 (defvar org-m nil)
4898 (defvar org-l nil)
4899 (defvar org-f nil)
4900 (defun org-get-level-face (n)
4901 "Get the right face for match N in font-lock matching of headlines."
4902 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4903 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4904 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4905 (cond
4906 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4907 ((eq n 2) org-f)
4908 (t (if org-level-color-stars-only nil org-f))))
4910 (defun org-get-todo-face (kwd)
4911 "Get the right face for a TODO keyword KWD.
4912 If KWD is a number, get the corresponding match group."
4913 (if (numberp kwd) (setq kwd (match-string kwd)))
4914 (or (cdr (assoc kwd org-todo-keyword-faces))
4915 (and (member kwd org-done-keywords) 'org-done)
4916 'org-todo))
4918 (defun org-font-lock-add-tag-faces (limit)
4919 "Add the special tag faces."
4920 (when (and org-tag-faces org-tags-special-faces-re)
4921 (while (re-search-forward org-tags-special-faces-re limit t)
4922 (add-text-properties (match-beginning 1) (match-end 1)
4923 (list 'face (org-get-tag-face 1)
4924 'font-lock-fontified t))
4925 (backward-char 1))))
4927 (defun org-font-lock-add-priority-faces (limit)
4928 "Add the special priority faces."
4929 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4930 (add-text-properties
4931 (match-beginning 0) (match-end 0)
4932 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4933 org-priority-faces))
4934 'org-special-keyword)
4935 'font-lock-fontified t))))
4937 (defun org-get-tag-face (kwd)
4938 "Get the right face for a TODO keyword KWD.
4939 If KWD is a number, get the corresponding match group."
4940 (if (numberp kwd) (setq kwd (match-string kwd)))
4941 (or (cdr (assoc kwd org-tag-faces))
4942 'org-tag))
4944 (defun org-unfontify-region (beg end &optional maybe_loudly)
4945 "Remove fontification and activation overlays from links."
4946 (font-lock-default-unfontify-region beg end)
4947 (let* ((buffer-undo-list t)
4948 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4949 (inhibit-modification-hooks t)
4950 deactivate-mark buffer-file-name buffer-file-truename)
4951 (remove-text-properties
4952 beg end
4953 (if org-indent-mode
4954 ;; also remove line-prefix and wrap-prefix properties
4955 '(mouse-face t keymap t org-linked-text t
4956 invisible t intangible t
4957 line-prefix t wrap-prefix t
4958 org-no-flyspell t)
4959 '(mouse-face t keymap t org-linked-text t
4960 invisible t intangible t
4961 org-no-flyspell t)))))
4963 ;;;; Visibility cycling, including org-goto and indirect buffer
4965 ;;; Cycling
4967 (defvar org-cycle-global-status nil)
4968 (make-variable-buffer-local 'org-cycle-global-status)
4969 (defvar org-cycle-subtree-status nil)
4970 (make-variable-buffer-local 'org-cycle-subtree-status)
4972 ;;;###autoload
4974 (defvar org-inlinetask-min-level)
4976 (defun org-cycle (&optional arg)
4977 "TAB-action and visibility cycling for Org-mode.
4979 This is the command invoked in Org-mode by the TAB key. Its main purpose
4980 is outine visibility cycling, but it also invokes other actions
4981 in special contexts.
4983 - When this function is called with a prefix argument, rotate the entire
4984 buffer through 3 states (global cycling)
4985 1. OVERVIEW: Show only top-level headlines.
4986 2. CONTENTS: Show all headlines of all levels, but no body text.
4987 3. SHOW ALL: Show everything.
4988 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4989 determined by the variable `org-startup-folded', and by any VISIBILITY
4990 properties in the buffer.
4991 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4992 including any drawers.
4994 - When inside a table, re-align the table and move to the next field.
4996 - When point is at the beginning of a headline, rotate the subtree started
4997 by this line through 3 different states (local cycling)
4998 1. FOLDED: Only the main headline is shown.
4999 2. CHILDREN: The main headline and the direct children are shown.
5000 From this state, you can move to one of the children
5001 and zoom in further.
5002 3. SUBTREE: Show the entire subtree, including body text.
5003 If there is no subtree, switch directly from CHILDREN to FOLDED.
5005 - When there is a numeric prefix, go up to a heading with level ARG, do
5006 a `show-subtree' and return to the previous cursor position. If ARG
5007 is negative, go up that many levels.
5009 - When point is not at the beginning of a headline, execute the global
5010 binding for TAB, which is re-indenting the line. See the option
5011 `org-cycle-emulate-tab' for details.
5013 - Special case: if point is at the beginning of the buffer and there is
5014 no headline in line 1, this function will act as if called with prefix arg.
5015 But only if also the variable `org-cycle-global-at-bob' is t."
5016 (interactive "P")
5017 (org-load-modules-maybe)
5018 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5019 (and org-cycle-level-after-item/entry-creation
5020 (or (org-cycle-level)
5021 (org-cycle-item-indentation))))
5022 (let* ((limit-level
5023 (or org-cycle-max-level
5024 (and (boundp 'org-inlinetask-min-level)
5025 org-inlinetask-min-level
5026 (1- org-inlinetask-min-level))))
5027 (nstars (and limit-level
5028 (if org-odd-levels-only
5029 (and limit-level (1- (* limit-level 2)))
5030 limit-level)))
5031 (outline-regexp
5032 (cond
5033 ((not (org-mode-p)) outline-regexp)
5034 ((or (eq org-cycle-include-plain-lists 'integrate)
5035 (and org-cycle-include-plain-lists (org-at-item-p)))
5036 (concat "\\(?:\\*"
5037 (if nstars (format "\\{1,%d\\}" nstars) "+")
5038 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5039 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5040 (bob-special (and org-cycle-global-at-bob (bobp)
5041 (not (looking-at outline-regexp))))
5042 (org-cycle-hook
5043 (if bob-special
5044 (delq 'org-optimize-window-after-visibility-change
5045 (copy-sequence org-cycle-hook))
5046 org-cycle-hook))
5047 (pos (point)))
5049 (if (or bob-special (equal arg '(4)))
5050 ;; special case: use global cycling
5051 (setq arg t))
5053 (cond
5055 ((equal arg '(16))
5056 (org-set-startup-visibility)
5057 (message "Startup visibility, plus VISIBILITY properties"))
5059 ((equal arg '(64))
5060 (show-all)
5061 (message "Entire buffer visible, including drawers"))
5063 ((org-at-table-p 'any)
5064 ;; Enter the table or move to the next field in the table
5065 (or (org-table-recognize-table.el)
5066 (progn
5067 (if arg (org-table-edit-field t)
5068 (org-table-justify-field-maybe)
5069 (call-interactively 'org-table-next-field)))))
5071 ((run-hook-with-args-until-success
5072 'org-tab-after-check-for-table-hook))
5074 ((eq arg t) ;; Global cycling
5075 (org-cycle-internal-global))
5077 ((and org-drawers org-drawer-regexp
5078 (save-excursion
5079 (beginning-of-line 1)
5080 (looking-at org-drawer-regexp)))
5081 ;; Toggle block visibility
5082 (org-flag-drawer
5083 (not (get-char-property (match-end 0) 'invisible))))
5085 ((integerp arg)
5086 ;; Show-subtree, ARG levels up from here.
5087 (save-excursion
5088 (org-back-to-heading)
5089 (outline-up-heading (if (< arg 0) (- arg)
5090 (- (funcall outline-level) arg)))
5091 (org-show-subtree)))
5093 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5094 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5096 (org-cycle-internal-local))
5098 ;; TAB emulation and template completion
5099 (buffer-read-only (org-back-to-heading))
5101 ((run-hook-with-args-until-success
5102 'org-tab-after-check-for-cycling-hook))
5104 ((org-try-structure-completion))
5106 ((org-try-cdlatex-tab))
5108 ((run-hook-with-args-until-success
5109 'org-tab-before-tab-emulation-hook))
5111 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5112 (or (not (bolp))
5113 (not (looking-at outline-regexp))))
5114 (call-interactively (global-key-binding "\t")))
5116 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5117 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5118 (or (and (eq org-cycle-emulate-tab 'white)
5119 (= (match-end 0) (point-at-eol)))
5120 (and (eq org-cycle-emulate-tab 'whitestart)
5121 (>= (match-end 0) pos))))
5123 (eq org-cycle-emulate-tab t))
5124 (call-interactively (global-key-binding "\t")))
5126 (t (save-excursion
5127 (org-back-to-heading)
5128 (org-cycle)))))))
5130 (defun org-cycle-internal-global ()
5131 "Do the global cycling action."
5132 (cond
5133 ((and (eq last-command this-command)
5134 (eq org-cycle-global-status 'overview))
5135 ;; We just created the overview - now do table of contents
5136 ;; This can be slow in very large buffers, so indicate action
5137 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5138 (message "CONTENTS...")
5139 (org-content)
5140 (message "CONTENTS...done")
5141 (setq org-cycle-global-status 'contents)
5142 (run-hook-with-args 'org-cycle-hook 'contents))
5144 ((and (eq last-command this-command)
5145 (eq org-cycle-global-status 'contents))
5146 ;; We just showed the table of contents - now show everything
5147 (run-hook-with-args 'org-pre-cycle-hook 'all)
5148 (show-all)
5149 (message "SHOW ALL")
5150 (setq org-cycle-global-status 'all)
5151 (run-hook-with-args 'org-cycle-hook 'all))
5154 ;; Default action: go to overview
5155 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5156 (org-overview)
5157 (message "OVERVIEW")
5158 (setq org-cycle-global-status 'overview)
5159 (run-hook-with-args 'org-cycle-hook 'overview))))
5161 (defun org-cycle-internal-local ()
5162 "Do the local cycling action."
5163 (org-back-to-heading)
5164 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5165 ;; First, some boundaries
5166 (save-excursion
5167 (org-back-to-heading)
5168 (setq level (funcall outline-level))
5169 (save-excursion
5170 (beginning-of-line 2)
5171 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5172 ; XEmacs does not have `next-single-char-property-change'
5173 ; I'm not sure about Emacs 21.
5174 (while (and (not (eobp)) ;; this is like `next-line'
5175 (get-char-property (1- (point)) 'invisible))
5176 (beginning-of-line 2))
5177 (while (and (not (eobp)) ;; this is like `next-line'
5178 (get-char-property (1- (point)) 'invisible))
5179 (goto-char (next-single-char-property-change (point) 'invisible))
5180 ;;;??? (or (bolp) (beginning-of-line 2))))
5181 (and (eolp) (beginning-of-line 2))))
5182 (setq eol (point)))
5183 (outline-end-of-heading) (setq eoh (point))
5184 (save-excursion
5185 (outline-next-heading)
5186 (setq has-children (and (org-at-heading-p t)
5187 (> (funcall outline-level) level))))
5188 (org-end-of-subtree t)
5189 (unless (eobp)
5190 (skip-chars-forward " \t\n")
5191 (beginning-of-line 1) ; in case this is an item
5193 (setq eos (if (eobp) (point) (1- (point)))))
5194 ;; Find out what to do next and set `this-command'
5195 (cond
5196 ((= eos eoh)
5197 ;; Nothing is hidden behind this heading
5198 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5199 (message "EMPTY ENTRY")
5200 (setq org-cycle-subtree-status nil)
5201 (save-excursion
5202 (goto-char eos)
5203 (outline-next-heading)
5204 (if (org-invisible-p) (org-flag-heading nil))))
5205 ((and (or (>= eol eos)
5206 (not (string-match "\\S-" (buffer-substring eol eos))))
5207 (or has-children
5208 (not (setq children-skipped
5209 org-cycle-skip-children-state-if-no-children))))
5210 ;; Entire subtree is hidden in one line: children view
5211 (run-hook-with-args 'org-pre-cycle-hook 'children)
5212 (org-show-entry)
5213 (show-children)
5214 (message "CHILDREN")
5215 (save-excursion
5216 (goto-char eos)
5217 (outline-next-heading)
5218 (if (org-invisible-p) (org-flag-heading nil)))
5219 (setq org-cycle-subtree-status 'children)
5220 (run-hook-with-args 'org-cycle-hook 'children))
5221 ((or children-skipped
5222 (and (eq last-command this-command)
5223 (eq org-cycle-subtree-status 'children)))
5224 ;; We just showed the children, or no children are there,
5225 ;; now show everything.
5226 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5227 (org-show-subtree)
5228 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5229 (setq org-cycle-subtree-status 'subtree)
5230 (run-hook-with-args 'org-cycle-hook 'subtree))
5232 ;; Default action: hide the subtree.
5233 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5234 (hide-subtree)
5235 (message "FOLDED")
5236 (setq org-cycle-subtree-status 'folded)
5237 (run-hook-with-args 'org-cycle-hook 'folded)))))
5239 ;;;###autoload
5240 (defun org-global-cycle (&optional arg)
5241 "Cycle the global visibility. For details see `org-cycle'.
5242 With C-u prefix arg, switch to startup visibility.
5243 With a numeric prefix, show all headlines up to that level."
5244 (interactive "P")
5245 (let ((org-cycle-include-plain-lists
5246 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5247 (cond
5248 ((integerp arg)
5249 (show-all)
5250 (hide-sublevels arg)
5251 (setq org-cycle-global-status 'contents))
5252 ((equal arg '(4))
5253 (org-set-startup-visibility)
5254 (message "Startup visibility, plus VISIBILITY properties."))
5256 (org-cycle '(4))))))
5258 (defun org-set-startup-visibility ()
5259 "Set the visibility required by startup options and properties."
5260 (cond
5261 ((eq org-startup-folded t)
5262 (org-cycle '(4)))
5263 ((eq org-startup-folded 'content)
5264 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5265 (org-cycle '(4)) (org-cycle '(4)))))
5266 (unless (eq org-startup-folded 'showeverything)
5267 (if org-hide-block-startup (org-hide-block-all))
5268 (org-set-visibility-according-to-property 'no-cleanup)
5269 (org-cycle-hide-archived-subtrees 'all)
5270 (org-cycle-hide-drawers 'all)
5271 (org-cycle-show-empty-lines 'all)))
5273 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5274 "Switch subtree visibilities according to :VISIBILITY: property."
5275 (interactive)
5276 (let (org-show-entry-below state)
5277 (save-excursion
5278 (goto-char (point-min))
5279 (while (re-search-forward
5280 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5281 nil t)
5282 (setq state (match-string 1))
5283 (save-excursion
5284 (org-back-to-heading t)
5285 (hide-subtree)
5286 (org-reveal)
5287 (cond
5288 ((equal state '("fold" "folded"))
5289 (hide-subtree))
5290 ((equal state "children")
5291 (org-show-hidden-entry)
5292 (show-children))
5293 ((equal state "content")
5294 (save-excursion
5295 (save-restriction
5296 (org-narrow-to-subtree)
5297 (org-content))))
5298 ((member state '("all" "showall"))
5299 (show-subtree)))))
5300 (unless no-cleanup
5301 (org-cycle-hide-archived-subtrees 'all)
5302 (org-cycle-hide-drawers 'all)
5303 (org-cycle-show-empty-lines 'all)))))
5305 (defun org-overview ()
5306 "Switch to overview mode, showing only top-level headlines.
5307 Really, this shows all headlines with level equal or greater than the level
5308 of the first headline in the buffer. This is important, because if the
5309 first headline is not level one, then (hide-sublevels 1) gives confusing
5310 results."
5311 (interactive)
5312 (let ((level (save-excursion
5313 (goto-char (point-min))
5314 (if (re-search-forward (concat "^" outline-regexp) nil t)
5315 (progn
5316 (goto-char (match-beginning 0))
5317 (funcall outline-level))))))
5318 (and level (hide-sublevels level))))
5320 (defun org-content (&optional arg)
5321 "Show all headlines in the buffer, like a table of contents.
5322 With numerical argument N, show content up to level N."
5323 (interactive "P")
5324 (save-excursion
5325 ;; Visit all headings and show their offspring
5326 (and (integerp arg) (org-overview))
5327 (goto-char (point-max))
5328 (catch 'exit
5329 (while (and (progn (condition-case nil
5330 (outline-previous-visible-heading 1)
5331 (error (goto-char (point-min))))
5333 (looking-at outline-regexp))
5334 (if (integerp arg)
5335 (show-children (1- arg))
5336 (show-branches))
5337 (if (bobp) (throw 'exit nil))))))
5340 (defun org-optimize-window-after-visibility-change (state)
5341 "Adjust the window after a change in outline visibility.
5342 This function is the default value of the hook `org-cycle-hook'."
5343 (when (get-buffer-window (current-buffer))
5344 (cond
5345 ((eq state 'content) nil)
5346 ((eq state 'all) nil)
5347 ((eq state 'folded) nil)
5348 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5349 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5351 ;; FIXME: no longer in use
5352 (defun org-compact-display-after-subtree-move ()
5353 "Show a compacter version of the tree of the entry's parent."
5354 (save-excursion
5355 (if (org-up-heading-safe)
5356 (progn
5357 (hide-subtree)
5358 (show-entry)
5359 (show-children)
5360 (org-cycle-show-empty-lines 'children)
5361 (org-cycle-hide-drawers 'children))
5362 (org-overview))))
5364 (defun org-remove-empty-overlays-at (pos)
5365 "Remove outline overlays that do not contain non-white stuff."
5366 (mapc
5367 (lambda (o)
5368 (and (eq 'outline (org-overlay-get o 'invisible))
5369 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5370 (org-overlay-end o))))
5371 (org-delete-overlay o)))
5372 (org-overlays-at pos)))
5374 (defun org-clean-visibility-after-subtree-move ()
5375 "Fix visibility issues after moving a subtree."
5376 ;; First, find a reasonable region to look at:
5377 ;; Start two siblings above, end three below
5378 (let* ((beg (save-excursion
5379 (and (org-get-last-sibling)
5380 (org-get-last-sibling))
5381 (point)))
5382 (end (save-excursion
5383 (and (org-get-next-sibling)
5384 (org-get-next-sibling)
5385 (org-get-next-sibling))
5386 (if (org-at-heading-p)
5387 (point-at-eol)
5388 (point))))
5389 (level (looking-at "\\*+"))
5390 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5391 (save-excursion
5392 (save-restriction
5393 (narrow-to-region beg end)
5394 (when re
5395 ;; Properly fold already folded siblings
5396 (goto-char (point-min))
5397 (while (re-search-forward re nil t)
5398 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5399 (hide-entry))))
5400 (org-cycle-show-empty-lines 'overview)
5401 (org-cycle-hide-drawers 'overview)))))
5403 (defun org-cycle-show-empty-lines (state)
5404 "Show empty lines above all visible headlines.
5405 The region to be covered depends on STATE when called through
5406 `org-cycle-hook'. Lisp program can use t for STATE to get the
5407 entire buffer covered. Note that an empty line is only shown if there
5408 are at least `org-cycle-separator-lines' empty lines before the headline."
5409 (when (not (= org-cycle-separator-lines 0))
5410 (save-excursion
5411 (let* ((n (abs org-cycle-separator-lines))
5412 (re (cond
5413 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5414 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5415 (t (let ((ns (number-to-string (- n 2))))
5416 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5417 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5418 beg end b e)
5419 (cond
5420 ((memq state '(overview contents t))
5421 (setq beg (point-min) end (point-max)))
5422 ((memq state '(children folded))
5423 (setq beg (point) end (progn (org-end-of-subtree t t)
5424 (beginning-of-line 2)
5425 (point)))))
5426 (when beg
5427 (goto-char beg)
5428 (while (re-search-forward re end t)
5429 (unless (get-char-property (match-end 1) 'invisible)
5430 (setq e (match-end 1))
5431 (if (< org-cycle-separator-lines 0)
5432 (setq b (save-excursion
5433 (goto-char (match-beginning 0))
5434 (org-back-over-empty-lines)
5435 (if (save-excursion
5436 (goto-char (max (point-min) (1- (point))))
5437 (org-on-heading-p))
5438 (1- (point))
5439 (point))))
5440 (setq b (match-beginning 1)))
5441 (outline-flag-region b e nil)))))))
5442 ;; Never hide empty lines at the end of the file.
5443 (save-excursion
5444 (goto-char (point-max))
5445 (outline-previous-heading)
5446 (outline-end-of-heading)
5447 (if (and (looking-at "[ \t\n]+")
5448 (= (match-end 0) (point-max)))
5449 (outline-flag-region (point) (match-end 0) nil))))
5451 (defun org-show-empty-lines-in-parent ()
5452 "Move to the parent and re-show empty lines before visible headlines."
5453 (save-excursion
5454 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5455 (org-cycle-show-empty-lines context))))
5457 (defun org-files-list ()
5458 "Return `org-agenda-files' list, plus all open org-mode files.
5459 This is useful for operations that need to scan all of a user's
5460 open and agenda-wise Org files."
5461 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5462 (dolist (buf (buffer-list))
5463 (with-current-buffer buf
5464 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5465 (let ((file (expand-file-name (buffer-file-name))))
5466 (unless (member file files)
5467 (push file files))))))
5468 files))
5470 (defsubst org-entry-beginning-position ()
5471 "Return the beginning position of the current entry."
5472 (save-excursion (outline-back-to-heading t) (point)))
5474 (defsubst org-entry-end-position ()
5475 "Return the end position of the current entry."
5476 (save-excursion (outline-next-heading) (point)))
5478 (defun org-cycle-hide-drawers (state)
5479 "Re-hide all drawers after a visibility state change."
5480 (when (and (org-mode-p)
5481 (not (memq state '(overview folded contents))))
5482 (save-excursion
5483 (let* ((globalp (memq state '(contents all)))
5484 (beg (if globalp (point-min) (point)))
5485 (end (if globalp (point-max)
5486 (if (eq state 'children)
5487 (save-excursion (outline-next-heading) (point))
5488 (org-end-of-subtree t)))))
5489 (goto-char beg)
5490 (while (re-search-forward org-drawer-regexp end t)
5491 (org-flag-drawer t))))))
5493 (defun org-flag-drawer (flag)
5494 (save-excursion
5495 (beginning-of-line 1)
5496 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5497 (let ((b (match-end 0))
5498 (outline-regexp org-outline-regexp))
5499 (if (re-search-forward
5500 "^[ \t]*:END:"
5501 (save-excursion (outline-next-heading) (point)) t)
5502 (outline-flag-region b (point-at-eol) flag)
5503 (error ":END: line missing at position %s" b))))))
5505 (defun org-subtree-end-visible-p ()
5506 "Is the end of the current subtree visible?"
5507 (pos-visible-in-window-p
5508 (save-excursion (org-end-of-subtree t) (point))))
5510 (defun org-first-headline-recenter (&optional N)
5511 "Move cursor to the first headline and recenter the headline.
5512 Optional argument N means, put the headline into the Nth line of the window."
5513 (goto-char (point-min))
5514 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5515 (beginning-of-line)
5516 (recenter (prefix-numeric-value N))))
5518 ;;; Folding of blocks
5520 (defconst org-block-regexp
5522 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5523 "Regular expression for hiding blocks.")
5525 (defvar org-hide-block-overlays nil
5526 "Overays hiding blocks.")
5527 (make-variable-buffer-local 'org-hide-block-overlays)
5529 (defun org-block-map (function &optional start end)
5530 "Call func at the head of all source blocks in the current
5531 buffer. Optional arguments START and END can be used to limit
5532 the range."
5533 (let ((start (or start (point-min)))
5534 (end (or end (point-max))))
5535 (save-excursion
5536 (goto-char start)
5537 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5538 (save-excursion
5539 (save-match-data
5540 (goto-char (match-beginning 0))
5541 (funcall function)))))))
5543 (defun org-hide-block-toggle-all ()
5544 "Toggle the visibility of all blocks in the current buffer."
5545 (org-block-map #'org-hide-block-toggle))
5547 (defun org-hide-block-all ()
5548 "Fold all blocks in the current buffer."
5549 (interactive)
5550 (org-show-block-all)
5551 (org-block-map #'org-hide-block-toggle-maybe))
5553 (defun org-show-block-all ()
5554 "Unfold all blocks in the current buffer."
5555 (mapc 'org-delete-overlay org-hide-block-overlays)
5556 (setq org-hide-block-overlays nil))
5558 (defun org-hide-block-toggle-maybe ()
5559 "Toggle visibility of block at point."
5560 (interactive)
5561 (let ((case-fold-search t))
5562 (if (save-excursion
5563 (beginning-of-line 1)
5564 (looking-at org-block-regexp))
5565 (progn (org-hide-block-toggle)
5566 t) ;; to signal that we took action
5567 nil))) ;; to signal that we did not
5569 (defun org-hide-block-toggle (&optional force)
5570 "Toggle the visibility of the current block."
5571 (interactive)
5572 (save-excursion
5573 (beginning-of-line)
5574 (if (re-search-forward org-block-regexp nil t)
5575 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5576 (end (match-end 0)) ;; end of entire body
5578 (if (memq t (mapcar (lambda (overlay)
5579 (eq (org-overlay-get overlay 'invisible)
5580 'org-hide-block))
5581 (org-overlays-at start)))
5582 (if (or (not force) (eq force 'off))
5583 (mapc (lambda (ov)
5584 (when (member ov org-hide-block-overlays)
5585 (setq org-hide-block-overlays
5586 (delq ov org-hide-block-overlays)))
5587 (when (eq (org-overlay-get ov 'invisible)
5588 'org-hide-block)
5589 (org-delete-overlay ov)))
5590 (org-overlays-at start)))
5591 (setq ov (org-make-overlay start end))
5592 (org-overlay-put ov 'invisible 'org-hide-block)
5593 ;; make the block accessible to isearch
5594 (org-overlay-put
5595 ov 'isearch-open-invisible
5596 (lambda (ov)
5597 (when (member ov org-hide-block-overlays)
5598 (setq org-hide-block-overlays
5599 (delq ov org-hide-block-overlays)))
5600 (when (eq (org-overlay-get ov 'invisible)
5601 'org-hide-block)
5602 (org-delete-overlay ov))))
5603 (push ov org-hide-block-overlays)))
5604 (error "Not looking at a source block"))))
5606 ;; org-tab-after-check-for-cycling-hook
5607 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5608 ;; Remove overlays when changing major mode
5609 (add-hook 'org-mode-hook
5610 (lambda () (org-add-hook 'change-major-mode-hook
5611 'org-show-block-all 'append 'local)))
5613 ;;; Org-goto
5615 (defvar org-goto-window-configuration nil)
5616 (defvar org-goto-marker nil)
5617 (defvar org-goto-map
5618 (let ((map (make-sparse-keymap)))
5619 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5620 (while (setq cmd (pop cmds))
5621 (substitute-key-definition cmd cmd map global-map)))
5622 (suppress-keymap map)
5623 (org-defkey map "\C-m" 'org-goto-ret)
5624 (org-defkey map [(return)] 'org-goto-ret)
5625 (org-defkey map [(left)] 'org-goto-left)
5626 (org-defkey map [(right)] 'org-goto-right)
5627 (org-defkey map [(control ?g)] 'org-goto-quit)
5628 (org-defkey map "\C-i" 'org-cycle)
5629 (org-defkey map [(tab)] 'org-cycle)
5630 (org-defkey map [(down)] 'outline-next-visible-heading)
5631 (org-defkey map [(up)] 'outline-previous-visible-heading)
5632 (if org-goto-auto-isearch
5633 (if (fboundp 'define-key-after)
5634 (define-key-after map [t] 'org-goto-local-auto-isearch)
5635 nil)
5636 (org-defkey map "q" 'org-goto-quit)
5637 (org-defkey map "n" 'outline-next-visible-heading)
5638 (org-defkey map "p" 'outline-previous-visible-heading)
5639 (org-defkey map "f" 'outline-forward-same-level)
5640 (org-defkey map "b" 'outline-backward-same-level)
5641 (org-defkey map "u" 'outline-up-heading))
5642 (org-defkey map "/" 'org-occur)
5643 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5644 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5645 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5646 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5647 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5648 map))
5650 (defconst org-goto-help
5651 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5652 RET=jump to location [Q]uit and return to previous location
5653 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5655 (defvar org-goto-start-pos) ; dynamically scoped parameter
5657 ;; FIXME: Docstring doe not mention both interfaces
5658 (defun org-goto (&optional alternative-interface)
5659 "Look up a different location in the current file, keeping current visibility.
5661 When you want look-up or go to a different location in a document, the
5662 fastest way is often to fold the entire buffer and then dive into the tree.
5663 This method has the disadvantage, that the previous location will be folded,
5664 which may not be what you want.
5666 This command works around this by showing a copy of the current buffer
5667 in an indirect buffer, in overview mode. You can dive into the tree in
5668 that copy, use org-occur and incremental search to find a location.
5669 When pressing RET or `Q', the command returns to the original buffer in
5670 which the visibility is still unchanged. After RET is will also jump to
5671 the location selected in the indirect buffer and expose the
5672 the headline hierarchy above."
5673 (interactive "P")
5674 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5675 (org-refile-use-outline-path t)
5676 (org-refile-target-verify-function nil)
5677 (interface
5678 (if (not alternative-interface)
5679 org-goto-interface
5680 (if (eq org-goto-interface 'outline)
5681 'outline-path-completion
5682 'outline)))
5683 (org-goto-start-pos (point))
5684 (selected-point
5685 (if (eq interface 'outline)
5686 (car (org-get-location (current-buffer) org-goto-help))
5687 (nth 3 (org-refile-get-location "Goto: ")))))
5688 (if selected-point
5689 (progn
5690 (org-mark-ring-push org-goto-start-pos)
5691 (goto-char selected-point)
5692 (if (or (org-invisible-p) (org-invisible-p2))
5693 (org-show-context 'org-goto)))
5694 (message "Quit"))))
5696 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5697 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5698 (defvar org-goto-local-auto-isearch-map) ; defined below
5700 (defun org-get-location (buf help)
5701 "Let the user select a location in the Org-mode buffer BUF.
5702 This function uses a recursive edit. It returns the selected position
5703 or nil."
5704 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5705 (isearch-hide-immediately nil)
5706 (isearch-search-fun-function
5707 (lambda () 'org-goto-local-search-headings))
5708 (org-goto-selected-point org-goto-exit-command))
5709 (save-excursion
5710 (save-window-excursion
5711 (delete-other-windows)
5712 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5713 (switch-to-buffer
5714 (condition-case nil
5715 (make-indirect-buffer (current-buffer) "*org-goto*")
5716 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5717 (with-output-to-temp-buffer "*Help*"
5718 (princ help))
5719 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5720 (setq buffer-read-only nil)
5721 (let ((org-startup-truncated t)
5722 (org-startup-folded nil)
5723 (org-startup-align-all-tables nil))
5724 (org-mode)
5725 (org-overview))
5726 (setq buffer-read-only t)
5727 (if (and (boundp 'org-goto-start-pos)
5728 (integer-or-marker-p org-goto-start-pos))
5729 (let ((org-show-hierarchy-above t)
5730 (org-show-siblings t)
5731 (org-show-following-heading t))
5732 (goto-char org-goto-start-pos)
5733 (and (org-invisible-p) (org-show-context)))
5734 (goto-char (point-min)))
5735 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5736 (message "Select location and press RET")
5737 (use-local-map org-goto-map)
5738 (recursive-edit)
5740 (kill-buffer "*org-goto*")
5741 (cons org-goto-selected-point org-goto-exit-command)))
5743 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5744 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5745 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5746 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5748 (defun org-goto-local-search-headings (string bound noerror)
5749 "Search and make sure that any matches are in headlines."
5750 (catch 'return
5751 (while (if isearch-forward
5752 (search-forward string bound noerror)
5753 (search-backward string bound noerror))
5754 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5755 (and (member :headline context)
5756 (not (member :tags context))))
5757 (throw 'return (point))))))
5759 (defun org-goto-local-auto-isearch ()
5760 "Start isearch."
5761 (interactive)
5762 (goto-char (point-min))
5763 (let ((keys (this-command-keys)))
5764 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5765 (isearch-mode t)
5766 (isearch-process-search-char (string-to-char keys)))))
5768 (defun org-goto-ret (&optional arg)
5769 "Finish `org-goto' by going to the new location."
5770 (interactive "P")
5771 (setq org-goto-selected-point (point)
5772 org-goto-exit-command 'return)
5773 (throw 'exit nil))
5775 (defun org-goto-left ()
5776 "Finish `org-goto' by going to the new location."
5777 (interactive)
5778 (if (org-on-heading-p)
5779 (progn
5780 (beginning-of-line 1)
5781 (setq org-goto-selected-point (point)
5782 org-goto-exit-command 'left)
5783 (throw 'exit nil))
5784 (error "Not on a heading")))
5786 (defun org-goto-right ()
5787 "Finish `org-goto' by going to the new location."
5788 (interactive)
5789 (if (org-on-heading-p)
5790 (progn
5791 (setq org-goto-selected-point (point)
5792 org-goto-exit-command 'right)
5793 (throw 'exit nil))
5794 (error "Not on a heading")))
5796 (defun org-goto-quit ()
5797 "Finish `org-goto' without cursor motion."
5798 (interactive)
5799 (setq org-goto-selected-point nil)
5800 (setq org-goto-exit-command 'quit)
5801 (throw 'exit nil))
5803 ;;; Indirect buffer display of subtrees
5805 (defvar org-indirect-dedicated-frame nil
5806 "This is the frame being used for indirect tree display.")
5807 (defvar org-last-indirect-buffer nil)
5809 (defun org-tree-to-indirect-buffer (&optional arg)
5810 "Create indirect buffer and narrow it to current subtree.
5811 With numerical prefix ARG, go up to this level and then take that tree.
5812 If ARG is negative, go up that many levels.
5813 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5814 indirect buffer previously made with this command, to avoid proliferation of
5815 indirect buffers. However, when you call the command with a `C-u' prefix, or
5816 when `org-indirect-buffer-display' is `new-frame', the last buffer
5817 is kept so that you can work with several indirect buffers at the same time.
5818 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5819 requests that a new frame be made for the new buffer, so that the dedicated
5820 frame is not changed."
5821 (interactive "P")
5822 (let ((cbuf (current-buffer))
5823 (cwin (selected-window))
5824 (pos (point))
5825 beg end level heading ibuf)
5826 (save-excursion
5827 (org-back-to-heading t)
5828 (when (numberp arg)
5829 (setq level (org-outline-level))
5830 (if (< arg 0) (setq arg (+ level arg)))
5831 (while (> (setq level (org-outline-level)) arg)
5832 (outline-up-heading 1 t)))
5833 (setq beg (point)
5834 heading (org-get-heading))
5835 (org-end-of-subtree t t) (setq end (point)))
5836 (if (and (buffer-live-p org-last-indirect-buffer)
5837 (not (eq org-indirect-buffer-display 'new-frame))
5838 (not arg))
5839 (kill-buffer org-last-indirect-buffer))
5840 (setq ibuf (org-get-indirect-buffer cbuf)
5841 org-last-indirect-buffer ibuf)
5842 (cond
5843 ((or (eq org-indirect-buffer-display 'new-frame)
5844 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5845 (select-frame (make-frame))
5846 (delete-other-windows)
5847 (switch-to-buffer ibuf)
5848 (org-set-frame-title heading))
5849 ((eq org-indirect-buffer-display 'dedicated-frame)
5850 (raise-frame
5851 (select-frame (or (and org-indirect-dedicated-frame
5852 (frame-live-p org-indirect-dedicated-frame)
5853 org-indirect-dedicated-frame)
5854 (setq org-indirect-dedicated-frame (make-frame)))))
5855 (delete-other-windows)
5856 (switch-to-buffer ibuf)
5857 (org-set-frame-title (concat "Indirect: " heading)))
5858 ((eq org-indirect-buffer-display 'current-window)
5859 (switch-to-buffer ibuf))
5860 ((eq org-indirect-buffer-display 'other-window)
5861 (pop-to-buffer ibuf))
5862 (t (error "Invalid value")))
5863 (if (featurep 'xemacs)
5864 (save-excursion (org-mode) (turn-on-font-lock)))
5865 (narrow-to-region beg end)
5866 (show-all)
5867 (goto-char pos)
5868 (and (window-live-p cwin) (select-window cwin))))
5870 (defun org-get-indirect-buffer (&optional buffer)
5871 (setq buffer (or buffer (current-buffer)))
5872 (let ((n 1) (base (buffer-name buffer)) bname)
5873 (while (buffer-live-p
5874 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5875 (setq n (1+ n)))
5876 (condition-case nil
5877 (make-indirect-buffer buffer bname 'clone)
5878 (error (make-indirect-buffer buffer bname)))))
5880 (defun org-set-frame-title (title)
5881 "Set the title of the current frame to the string TITLE."
5882 ;; FIXME: how to name a single frame in XEmacs???
5883 (unless (featurep 'xemacs)
5884 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5886 ;;;; Structure editing
5888 ;;; Inserting headlines
5890 (defun org-previous-line-empty-p ()
5891 (save-excursion
5892 (and (not (bobp))
5893 (or (beginning-of-line 0) t)
5894 (save-match-data
5895 (looking-at "[ \t]*$")))))
5897 (defun org-insert-heading (&optional force-heading)
5898 "Insert a new heading or item with same depth at point.
5899 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5900 If point is at the beginning of a headline, insert a sibling before the
5901 current headline. If point is not at the beginning, do not split the line,
5902 but create the new headline after the current line."
5903 (interactive "P")
5904 (if (= (buffer-size) 0)
5905 (insert "\n* ")
5906 (when (or force-heading (not (org-insert-item)))
5907 (let* ((empty-line-p nil)
5908 (head (save-excursion
5909 (condition-case nil
5910 (progn
5911 (org-back-to-heading)
5912 (setq empty-line-p (org-previous-line-empty-p))
5913 (match-string 0))
5914 (error "*"))))
5915 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5916 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5917 pos hide-previous previous-pos)
5918 (cond
5919 ((and (org-on-heading-p) (bolp)
5920 (or (bobp)
5921 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5922 ;; insert before the current line
5923 (open-line (if blank 2 1)))
5924 ((and (bolp)
5925 (not org-insert-heading-respect-content)
5926 (or (bobp)
5927 (save-excursion
5928 (backward-char 1) (not (org-invisible-p)))))
5929 ;; insert right here
5930 nil)
5932 ;; somewhere in the line
5933 (save-excursion
5934 (setq previous-pos (point-at-bol))
5935 (end-of-line)
5936 (setq hide-previous (org-invisible-p)))
5937 (and org-insert-heading-respect-content (org-show-subtree))
5938 (let ((split
5939 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5940 (save-excursion
5941 (let ((p (point)))
5942 (goto-char (point-at-bol))
5943 (and (looking-at org-complex-heading-regexp)
5944 (> p (match-beginning 4)))))))
5945 tags pos)
5946 (cond
5947 (org-insert-heading-respect-content
5948 (org-end-of-subtree nil t)
5949 (or (bolp) (newline))
5950 (or (org-previous-line-empty-p)
5951 (and blank (newline)))
5952 (open-line 1))
5953 ((org-on-heading-p)
5954 (when hide-previous
5955 (show-children)
5956 (org-show-entry))
5957 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5958 (setq tags (and (match-end 2) (match-string 2)))
5959 (and (match-end 1)
5960 (delete-region (match-beginning 1) (match-end 1)))
5961 (setq pos (point-at-bol))
5962 (or split (end-of-line 1))
5963 (delete-horizontal-space)
5964 (newline (if blank 2 1))
5965 (when tags
5966 (save-excursion
5967 (goto-char pos)
5968 (end-of-line 1)
5969 (insert " " tags)
5970 (org-set-tags nil 'align))))
5972 (or split (end-of-line 1))
5973 (newline (if blank 2 1)))))))
5974 (insert head) (just-one-space)
5975 (setq pos (point))
5976 (end-of-line 1)
5977 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5978 (when (and org-insert-heading-respect-content hide-previous)
5979 (save-excursion
5980 (goto-char previous-pos)
5981 (hide-subtree)))
5982 (run-hooks 'org-insert-heading-hook)))))
5984 (defun org-get-heading (&optional no-tags)
5985 "Return the heading of the current entry, without the stars."
5986 (save-excursion
5987 (org-back-to-heading t)
5988 (if (looking-at
5989 (if no-tags
5990 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5991 "\\*+[ \t]+\\([^\r\n]*\\)"))
5992 (match-string 1) "")))
5994 (defun org-heading-components ()
5995 "Return the components of the current heading.
5996 This is a list with the following elements:
5997 - the level as an integer
5998 - the reduced level, different if `org-odd-levels-only' is set.
5999 - the TODO keyword, or nil
6000 - the priority character, like ?A, or nil if no priority is given
6001 - the headline text itself, or the tags string if no headline text
6002 - the tags string, or nil."
6003 (save-excursion
6004 (org-back-to-heading t)
6005 (if (looking-at org-complex-heading-regexp)
6006 (list (length (match-string 1))
6007 (org-reduced-level (length (match-string 1)))
6008 (org-match-string-no-properties 2)
6009 (and (match-end 3) (aref (match-string 3) 2))
6010 (org-match-string-no-properties 4)
6011 (org-match-string-no-properties 5)))))
6013 (defun org-get-entry ()
6014 "Get the entry text, after heading, entire subtree."
6015 (save-excursion
6016 (org-back-to-heading t)
6017 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6019 (defun org-insert-heading-after-current ()
6020 "Insert a new heading with same level as current, after current subtree."
6021 (interactive)
6022 (org-back-to-heading)
6023 (org-insert-heading)
6024 (org-move-subtree-down)
6025 (end-of-line 1))
6027 (defun org-insert-heading-respect-content ()
6028 (interactive)
6029 (let ((org-insert-heading-respect-content t))
6030 (org-insert-heading t)))
6032 (defun org-insert-todo-heading-respect-content (&optional force-state)
6033 (interactive "P")
6034 (let ((org-insert-heading-respect-content t))
6035 (org-insert-todo-heading force-state t)))
6037 (defun org-insert-todo-heading (arg &optional force-heading)
6038 "Insert a new heading with the same level and TODO state as current heading.
6039 If the heading has no TODO state, or if the state is DONE, use the first
6040 state (TODO by default). Also with prefix arg, force first state."
6041 (interactive "P")
6042 (when (or force-heading (not (org-insert-item 'checkbox)))
6043 (org-insert-heading force-heading)
6044 (save-excursion
6045 (org-back-to-heading)
6046 (outline-previous-heading)
6047 (looking-at org-todo-line-regexp))
6048 (let*
6049 ((new-mark-x
6050 (if (or arg
6051 (not (match-beginning 2))
6052 (member (match-string 2) org-done-keywords))
6053 (car org-todo-keywords-1)
6054 (match-string 2)))
6055 (new-mark
6057 (run-hook-with-args-until-success
6058 'org-todo-get-default-hook new-mark-x nil)
6059 new-mark-x)))
6060 (beginning-of-line 1)
6061 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6062 (if org-treat-insert-todo-heading-as-state-change
6063 (org-todo new-mark)
6064 (insert new-mark " "))))
6065 (when org-provide-todo-statistics
6066 (org-update-parent-todo-statistics))))
6068 (defun org-insert-subheading (arg)
6069 "Insert a new subheading and demote it.
6070 Works for outline headings and for plain lists alike."
6071 (interactive "P")
6072 (org-insert-heading arg)
6073 (cond
6074 ((org-on-heading-p) (org-do-demote))
6075 ((org-at-item-p) (org-indent-item 1))))
6077 (defun org-insert-todo-subheading (arg)
6078 "Insert a new subheading with TODO keyword or checkbox and demote it.
6079 Works for outline headings and for plain lists alike."
6080 (interactive "P")
6081 (org-insert-todo-heading arg)
6082 (cond
6083 ((org-on-heading-p) (org-do-demote))
6084 ((org-at-item-p) (org-indent-item 1))))
6086 ;;; Promotion and Demotion
6088 (defvar org-after-demote-entry-hook nil
6089 "Hook run after an entry has been demoted.
6090 The cursor will be at the beginning of the entry.
6091 When a subtree is being demoted, the hook will be called for each node.")
6093 (defvar org-after-promote-entry-hook nil
6094 "Hook run after an entry has been promoted.
6095 The cursor will be at the beginning of the entry.
6096 When a subtree is being promoted, the hook will be called for each node.")
6098 (defun org-promote-subtree ()
6099 "Promote the entire subtree.
6100 See also `org-promote'."
6101 (interactive)
6102 (save-excursion
6103 (org-map-tree 'org-promote))
6104 (org-fix-position-after-promote))
6106 (defun org-demote-subtree ()
6107 "Demote the entire subtree. See `org-demote'.
6108 See also `org-promote'."
6109 (interactive)
6110 (save-excursion
6111 (org-map-tree 'org-demote))
6112 (org-fix-position-after-promote))
6115 (defun org-do-promote ()
6116 "Promote the current heading higher up the tree.
6117 If the region is active in `transient-mark-mode', promote all headings
6118 in the region."
6119 (interactive)
6120 (save-excursion
6121 (if (org-region-active-p)
6122 (org-map-region 'org-promote (region-beginning) (region-end))
6123 (org-promote)))
6124 (org-fix-position-after-promote))
6126 (defun org-do-demote ()
6127 "Demote the current heading lower down the tree.
6128 If the region is active in `transient-mark-mode', demote all headings
6129 in the region."
6130 (interactive)
6131 (save-excursion
6132 (if (org-region-active-p)
6133 (org-map-region 'org-demote (region-beginning) (region-end))
6134 (org-demote)))
6135 (org-fix-position-after-promote))
6137 (defun org-fix-position-after-promote ()
6138 "Make sure that after pro/demotion cursor position is right."
6139 (let ((pos (point)))
6140 (when (save-excursion
6141 (beginning-of-line 1)
6142 (looking-at org-todo-line-regexp)
6143 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6144 (cond ((eobp) (insert " "))
6145 ((eolp) (insert " "))
6146 ((equal (char-after) ?\ ) (forward-char 1))))))
6148 (defun org-current-level ()
6149 "Return the level of the current entry, or nil if before the first headline.
6150 The level is the number of stars at the beginning of the headline."
6151 (save-excursion
6152 (condition-case nil
6153 (progn
6154 (org-back-to-heading t)
6155 (funcall outline-level))
6156 (error nil))))
6158 (defun org-reduced-level (l)
6159 "Compute the effective level of a heading.
6160 This takes into account the setting of `org-odd-levels-only'."
6161 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6163 (defun org-get-valid-level (level &optional change)
6164 "Rectify a level change under the influence of `org-odd-levels-only'
6165 LEVEL is a current level, CHANGE is by how much the level should be
6166 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6167 even level numbers will become the next higher odd number."
6168 (if org-odd-levels-only
6169 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6170 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6171 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6172 (max 1 (+ level (or change 0)))))
6174 (if (boundp 'define-obsolete-function-alias)
6175 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6176 (define-obsolete-function-alias 'org-get-legal-level
6177 'org-get-valid-level)
6178 (define-obsolete-function-alias 'org-get-legal-level
6179 'org-get-valid-level "23.1")))
6181 (defun org-promote ()
6182 "Promote the current heading higher up the tree.
6183 If the region is active in `transient-mark-mode', promote all headings
6184 in the region."
6185 (org-back-to-heading t)
6186 (let* ((level (save-match-data (funcall outline-level)))
6187 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6188 (diff (abs (- level (length up-head) -1))))
6189 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6190 (replace-match up-head nil t)
6191 ;; Fixup tag positioning
6192 (and org-auto-align-tags (org-set-tags nil t))
6193 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6194 (run-hooks 'org-after-promote-entry-hook)))
6196 (defun org-demote ()
6197 "Demote the current heading lower down the tree.
6198 If the region is active in `transient-mark-mode', demote all headings
6199 in the region."
6200 (org-back-to-heading t)
6201 (let* ((level (save-match-data (funcall outline-level)))
6202 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6203 (diff (abs (- level (length down-head) -1))))
6204 (replace-match down-head nil t)
6205 ;; Fixup tag positioning
6206 (and org-auto-align-tags (org-set-tags nil t))
6207 (if org-adapt-indentation (org-fixup-indentation diff))
6208 (run-hooks 'org-after-demote-entry-hook)))
6210 (defvar org-tab-ind-state nil)
6212 (defun org-cycle-level ()
6213 (let ((org-adapt-indentation nil))
6214 (when (and (looking-at "[ \t]*$")
6215 (looking-back
6216 (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))
6217 (setq this-command 'org-cycle-level)
6218 (if (eq last-command 'org-cycle-level)
6219 (condition-case nil
6220 (progn (org-do-promote)
6221 (if (equal org-tab-ind-state (org-current-level))
6222 (org-do-promote)))
6223 (error
6224 (progn
6225 (save-excursion
6226 (beginning-of-line 1)
6227 (and (looking-at "\\*+")
6228 (replace-match
6229 (make-string org-tab-ind-state ?*))))
6230 (setq this-command 'org-cycle))))
6231 (setq org-tab-ind-state (- (match-end 1) (match-beginning 1)))
6232 (org-do-demote))
6233 t)))
6235 (defun org-map-tree (fun)
6236 "Call FUN for every heading underneath the current one."
6237 (org-back-to-heading)
6238 (let ((level (funcall outline-level)))
6239 (save-excursion
6240 (funcall fun)
6241 (while (and (progn
6242 (outline-next-heading)
6243 (> (funcall outline-level) level))
6244 (not (eobp)))
6245 (funcall fun)))))
6247 (defun org-map-region (fun beg end)
6248 "Call FUN for every heading between BEG and END."
6249 (let ((org-ignore-region t))
6250 (save-excursion
6251 (setq end (copy-marker end))
6252 (goto-char beg)
6253 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6254 (< (point) end))
6255 (funcall fun))
6256 (while (and (progn
6257 (outline-next-heading)
6258 (< (point) end))
6259 (not (eobp)))
6260 (funcall fun)))))
6262 (defun org-fixup-indentation (diff)
6263 "Change the indentation in the current entry by DIFF
6264 However, if any line in the current entry has no indentation, or if it
6265 would end up with no indentation after the change, nothing at all is done."
6266 (save-excursion
6267 (let ((end (save-excursion (outline-next-heading)
6268 (point-marker)))
6269 (prohibit (if (> diff 0)
6270 "^\\S-"
6271 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6272 col)
6273 (unless (save-excursion (end-of-line 1)
6274 (re-search-forward prohibit end t))
6275 (while (and (< (point) end)
6276 (re-search-forward "^[ \t]+" end t))
6277 (goto-char (match-end 0))
6278 (setq col (current-column))
6279 (if (< diff 0) (replace-match ""))
6280 (org-indent-to-column (+ diff col))))
6281 (move-marker end nil))))
6283 (defun org-convert-to-odd-levels ()
6284 "Convert an org-mode file with all levels allowed to one with odd levels.
6285 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6286 level 5 etc."
6287 (interactive)
6288 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6289 (let ((outline-regexp org-outline-regexp)
6290 (outline-level 'org-outline-level)
6291 (org-odd-levels-only nil) n)
6292 (save-excursion
6293 (goto-char (point-min))
6294 (while (re-search-forward "^\\*\\*+ " nil t)
6295 (setq n (- (length (match-string 0)) 2))
6296 (while (>= (setq n (1- n)) 0)
6297 (org-demote))
6298 (end-of-line 1))))))
6300 (defun org-convert-to-oddeven-levels ()
6301 "Convert an org-mode file with only odd levels to one with odd and even levels.
6302 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6303 section with an even level, conversion would destroy the structure of the file. An error
6304 is signaled in this case."
6305 (interactive)
6306 (goto-char (point-min))
6307 ;; First check if there are no even levels
6308 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6309 (org-show-context t)
6310 (error "Not all levels are odd in this file. Conversion not possible"))
6311 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6312 (let ((outline-regexp org-outline-regexp)
6313 (outline-level 'org-outline-level)
6314 (org-odd-levels-only nil) n)
6315 (save-excursion
6316 (goto-char (point-min))
6317 (while (re-search-forward "^\\*\\*+ " nil t)
6318 (setq n (/ (1- (length (match-string 0))) 2))
6319 (while (>= (setq n (1- n)) 0)
6320 (org-promote))
6321 (end-of-line 1))))))
6323 (defun org-tr-level (n)
6324 "Make N odd if required."
6325 (if org-odd-levels-only (1+ (/ n 2)) n))
6327 ;;; Vertical tree motion, cutting and pasting of subtrees
6329 (defun org-move-subtree-up (&optional arg)
6330 "Move the current subtree up past ARG headlines of the same level."
6331 (interactive "p")
6332 (org-move-subtree-down (- (prefix-numeric-value arg))))
6334 (defun org-move-subtree-down (&optional arg)
6335 "Move the current subtree down past ARG headlines of the same level."
6336 (interactive "p")
6337 (setq arg (prefix-numeric-value arg))
6338 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6339 'org-get-last-sibling))
6340 (ins-point (make-marker))
6341 (cnt (abs arg))
6342 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6343 ;; Select the tree
6344 (org-back-to-heading)
6345 (setq beg0 (point))
6346 (save-excursion
6347 (setq ne-beg (org-back-over-empty-lines))
6348 (setq beg (point)))
6349 (save-match-data
6350 (save-excursion (outline-end-of-heading)
6351 (setq folded (org-invisible-p)))
6352 (outline-end-of-subtree))
6353 (outline-next-heading)
6354 (setq ne-end (org-back-over-empty-lines))
6355 (setq end (point))
6356 (goto-char beg0)
6357 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6358 ;; include less whitespace
6359 (save-excursion
6360 (goto-char beg)
6361 (forward-line (- ne-beg ne-end))
6362 (setq beg (point))))
6363 ;; Find insertion point, with error handling
6364 (while (> cnt 0)
6365 (or (and (funcall movfunc) (looking-at outline-regexp))
6366 (progn (goto-char beg0)
6367 (error "Cannot move past superior level or buffer limit")))
6368 (setq cnt (1- cnt)))
6369 (if (> arg 0)
6370 ;; Moving forward - still need to move over subtree
6371 (progn (org-end-of-subtree t t)
6372 (save-excursion
6373 (org-back-over-empty-lines)
6374 (or (bolp) (newline)))))
6375 (setq ne-ins (org-back-over-empty-lines))
6376 (move-marker ins-point (point))
6377 (setq txt (buffer-substring beg end))
6378 (org-save-markers-in-region beg end)
6379 (delete-region beg end)
6380 (org-remove-empty-overlays-at beg)
6381 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6382 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6383 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6384 (let ((bbb (point)))
6385 (insert-before-markers txt)
6386 (org-reinstall-markers-in-region bbb)
6387 (move-marker ins-point bbb))
6388 (or (bolp) (insert "\n"))
6389 (setq ins-end (point))
6390 (goto-char ins-point)
6391 (org-skip-whitespace)
6392 (when (and (< arg 0)
6393 (org-first-sibling-p)
6394 (> ne-ins ne-beg))
6395 ;; Move whitespace back to beginning
6396 (save-excursion
6397 (goto-char ins-end)
6398 (let ((kill-whole-line t))
6399 (kill-line (- ne-ins ne-beg)) (point)))
6400 (insert (make-string (- ne-ins ne-beg) ?\n)))
6401 (move-marker ins-point nil)
6402 (if folded
6403 (hide-subtree)
6404 (org-show-entry)
6405 (show-children)
6406 (org-cycle-hide-drawers 'children))
6407 (org-clean-visibility-after-subtree-move)))
6409 (defvar org-subtree-clip ""
6410 "Clipboard for cut and paste of subtrees.
6411 This is actually only a copy of the kill, because we use the normal kill
6412 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6414 (defvar org-subtree-clip-folded nil
6415 "Was the last copied subtree folded?
6416 This is used to fold the tree back after pasting.")
6418 (defun org-cut-subtree (&optional n)
6419 "Cut the current subtree into the clipboard.
6420 With prefix arg N, cut this many sequential subtrees.
6421 This is a short-hand for marking the subtree and then cutting it."
6422 (interactive "p")
6423 (org-copy-subtree n 'cut))
6425 (defun org-copy-subtree (&optional n cut force-store-markers)
6426 "Cut the current subtree into the clipboard.
6427 With prefix arg N, cut this many sequential subtrees.
6428 This is a short-hand for marking the subtree and then copying it.
6429 If CUT is non-nil, actually cut the subtree.
6430 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6431 of some markers in the region, even if CUT is non-nil. This is
6432 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6433 (interactive "p")
6434 (let (beg end folded (beg0 (point)))
6435 (if (interactive-p)
6436 (org-back-to-heading nil) ; take what looks like a subtree
6437 (org-back-to-heading t)) ; take what is really there
6438 (org-back-over-empty-lines)
6439 (setq beg (point))
6440 (skip-chars-forward " \t\r\n")
6441 (save-match-data
6442 (save-excursion (outline-end-of-heading)
6443 (setq folded (org-invisible-p)))
6444 (condition-case nil
6445 (org-forward-same-level (1- n) t)
6446 (error nil))
6447 (org-end-of-subtree t t))
6448 (org-back-over-empty-lines)
6449 (setq end (point))
6450 (goto-char beg0)
6451 (when (> end beg)
6452 (setq org-subtree-clip-folded folded)
6453 (when (or cut force-store-markers)
6454 (org-save-markers-in-region beg end))
6455 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6456 (setq org-subtree-clip (current-kill 0))
6457 (message "%s: Subtree(s) with %d characters"
6458 (if cut "Cut" "Copied")
6459 (length org-subtree-clip)))))
6461 (defun org-paste-subtree (&optional level tree for-yank)
6462 "Paste the clipboard as a subtree, with modification of headline level.
6463 The entire subtree is promoted or demoted in order to match a new headline
6464 level.
6466 If the cursor is at the beginning of a headline, the same level as
6467 that headline is used to paste the tree
6469 If not, the new level is derived from the *visible* headings
6470 before and after the insertion point, and taken to be the inferior headline
6471 level of the two. So if the previous visible heading is level 3 and the
6472 next is level 4 (or vice versa), level 4 will be used for insertion.
6473 This makes sure that the subtree remains an independent subtree and does
6474 not swallow low level entries.
6476 You can also force a different level, either by using a numeric prefix
6477 argument, or by inserting the heading marker by hand. For example, if the
6478 cursor is after \"*****\", then the tree will be shifted to level 5.
6480 If optional TREE is given, use this text instead of the kill ring.
6482 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6483 move back over whitespace before inserting, and move point to the end of
6484 the inserted text when done."
6485 (interactive "P")
6486 (setq tree (or tree (and kill-ring (current-kill 0))))
6487 (unless (org-kill-is-subtree-p tree)
6488 (error "%s"
6489 (substitute-command-keys
6490 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6491 (let* ((visp (not (org-invisible-p)))
6492 (txt tree)
6493 (^re (concat "^\\(" outline-regexp "\\)"))
6494 (re (concat "\\(" outline-regexp "\\)"))
6495 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6497 (old-level (if (string-match ^re txt)
6498 (- (match-end 0) (match-beginning 0) 1)
6499 -1))
6500 (force-level (cond (level (prefix-numeric-value level))
6501 ((and (looking-at "[ \t]*$")
6502 (string-match
6503 ^re_ (buffer-substring
6504 (point-at-bol) (point))))
6505 (- (match-end 1) (match-beginning 1)))
6506 ((and (bolp)
6507 (looking-at org-outline-regexp))
6508 (- (match-end 0) (point) 1))
6509 (t nil)))
6510 (previous-level (save-excursion
6511 (condition-case nil
6512 (progn
6513 (outline-previous-visible-heading 1)
6514 (if (looking-at re)
6515 (- (match-end 0) (match-beginning 0) 1)
6517 (error 1))))
6518 (next-level (save-excursion
6519 (condition-case nil
6520 (progn
6521 (or (looking-at outline-regexp)
6522 (outline-next-visible-heading 1))
6523 (if (looking-at re)
6524 (- (match-end 0) (match-beginning 0) 1)
6526 (error 1))))
6527 (new-level (or force-level (max previous-level next-level)))
6528 (shift (if (or (= old-level -1)
6529 (= new-level -1)
6530 (= old-level new-level))
6532 (- new-level old-level)))
6533 (delta (if (> shift 0) -1 1))
6534 (func (if (> shift 0) 'org-demote 'org-promote))
6535 (org-odd-levels-only nil)
6536 beg end newend)
6537 ;; Remove the forced level indicator
6538 (if force-level
6539 (delete-region (point-at-bol) (point)))
6540 ;; Paste
6541 (beginning-of-line 1)
6542 (unless for-yank (org-back-over-empty-lines))
6543 (setq beg (point))
6544 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6545 (insert-before-markers txt)
6546 (unless (string-match "\n\\'" txt) (insert "\n"))
6547 (setq newend (point))
6548 (org-reinstall-markers-in-region beg)
6549 (setq end (point))
6550 (goto-char beg)
6551 (skip-chars-forward " \t\n\r")
6552 (setq beg (point))
6553 (if (and (org-invisible-p) visp)
6554 (save-excursion (outline-show-heading)))
6555 ;; Shift if necessary
6556 (unless (= shift 0)
6557 (save-restriction
6558 (narrow-to-region beg end)
6559 (while (not (= shift 0))
6560 (org-map-region func (point-min) (point-max))
6561 (setq shift (+ delta shift)))
6562 (goto-char (point-min))
6563 (setq newend (point-max))))
6564 (when (or (interactive-p) for-yank)
6565 (message "Clipboard pasted as level %d subtree" new-level))
6566 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6567 kill-ring
6568 (eq org-subtree-clip (current-kill 0))
6569 org-subtree-clip-folded)
6570 ;; The tree was folded before it was killed/copied
6571 (hide-subtree))
6572 (and for-yank (goto-char newend))))
6574 (defun org-kill-is-subtree-p (&optional txt)
6575 "Check if the current kill is an outline subtree, or a set of trees.
6576 Returns nil if kill does not start with a headline, or if the first
6577 headline level is not the largest headline level in the tree.
6578 So this will actually accept several entries of equal levels as well,
6579 which is OK for `org-paste-subtree'.
6580 If optional TXT is given, check this string instead of the current kill."
6581 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6582 (start-level (and kill
6583 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6584 org-outline-regexp "\\)")
6585 kill)
6586 (- (match-end 2) (match-beginning 2) 1)))
6587 (re (concat "^" org-outline-regexp))
6588 (start (1+ (or (match-beginning 2) -1))))
6589 (if (not start-level)
6590 (progn
6591 nil) ;; does not even start with a heading
6592 (catch 'exit
6593 (while (setq start (string-match re kill (1+ start)))
6594 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6595 (throw 'exit nil)))
6596 t))))
6598 (defvar org-markers-to-move nil
6599 "Markers that should be moved with a cut-and-paste operation.
6600 Those markers are stored together with their positions relative to
6601 the start of the region.")
6603 (defun org-save-markers-in-region (beg end)
6604 "Check markers in region.
6605 If these markers are between BEG and END, record their position relative
6606 to BEG, so that after moving the block of text, we can put the markers back
6607 into place.
6608 This function gets called just before an entry or tree gets cut from the
6609 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6610 called immediately, to move the markers with the entries."
6611 (setq org-markers-to-move nil)
6612 (when (featurep 'org-clock)
6613 (org-clock-save-markers-for-cut-and-paste beg end))
6614 (when (featurep 'org-agenda)
6615 (org-agenda-save-markers-for-cut-and-paste beg end)))
6617 (defun org-check-and-save-marker (marker beg end)
6618 "Check if MARKER is between BEG and END.
6619 If yes, remember the marker and the distance to BEG."
6620 (when (and (marker-buffer marker)
6621 (equal (marker-buffer marker) (current-buffer)))
6622 (if (and (>= marker beg) (< marker end))
6623 (push (cons marker (- marker beg)) org-markers-to-move))))
6625 (defun org-reinstall-markers-in-region (beg)
6626 "Move all remembered markers to their position relative to BEG."
6627 (mapc (lambda (x)
6628 (move-marker (car x) (+ beg (cdr x))))
6629 org-markers-to-move)
6630 (setq org-markers-to-move nil))
6632 (defun org-narrow-to-subtree ()
6633 "Narrow buffer to the current subtree."
6634 (interactive)
6635 (save-excursion
6636 (save-match-data
6637 (narrow-to-region
6638 (progn (org-back-to-heading t) (point))
6639 (progn (org-end-of-subtree t t) (point))))))
6641 (defun org-clone-subtree-with-time-shift (n &optional shift)
6642 "Clone the task (subtree) at point N times.
6643 The clones will be inserted as siblings.
6645 In interactive use, the user will be prompted for the number of clones
6646 to be produced, and for a time SHIFT, which may be a repeater as used
6647 in time stamps, for example `+3d'.
6649 When a valid repeater is given and the entry contains any time stamps,
6650 the clones will become a sequence in time, with time stamps in the
6651 subtree shifted for each clone produced. If SHIFT is nil or the
6652 empty string, time stamps will be left alone.
6654 If the original subtree did contain time stamps with a repeater,
6655 the following will happen:
6656 - the repeater will be removed in each clone
6657 - an additional clone will be produced, with the current, unshifted
6658 date(s) in the entry.
6659 - the original entry will be placed *after* all the clones, with
6660 repeater intact.
6661 - the start days in the repeater in the original entry will be shifted
6662 to past the last clone.
6663 I this way you can spell out a number of instances of a repeating task,
6664 and still retain the repeater to cover future instances of the task."
6665 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6666 (let (beg end template task
6667 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6668 (if (not (and (integerp n) (> n 0)))
6669 (error "Invalid number of replications %s" n))
6670 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6671 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6672 shift)))
6673 (error "Invalid shift specification %s" shift))
6674 (when doshift
6675 (setq shift-n (string-to-number (match-string 1 shift))
6676 shift-what (cdr (assoc (match-string 2 shift)
6677 '(("d" . day) ("w" . week)
6678 ("m" . month) ("y" . year))))))
6679 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6680 (setq nmin 1 nmax n)
6681 (org-back-to-heading t)
6682 (setq beg (point))
6683 (org-end-of-subtree t t)
6684 (setq end (point))
6685 (setq template (buffer-substring beg end))
6686 (when (and doshift
6687 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6688 (delete-region beg end)
6689 (setq end beg)
6690 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6691 (goto-char end)
6692 (loop for n from nmin to nmax do
6693 (if (not doshift)
6694 (setq task template)
6695 (with-temp-buffer
6696 (insert template)
6697 (org-mode)
6698 (goto-char (point-min))
6699 (while (re-search-forward org-ts-regexp-both nil t)
6700 (org-timestamp-change (* n shift-n) shift-what))
6701 (unless (= n n-no-remove)
6702 (goto-char (point-min))
6703 (while (re-search-forward org-ts-regexp nil t)
6704 (save-excursion
6705 (goto-char (match-beginning 0))
6706 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6707 (delete-region (match-beginning 1) (match-end 1))))))
6708 (setq task (buffer-string))))
6709 (insert task))
6710 (goto-char beg)))
6712 ;;; Outline Sorting
6714 (defun org-sort (with-case)
6715 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6716 Optional argument WITH-CASE means sort case-sensitively.
6717 With a double prefix argument, also remove duplicate entries."
6718 (interactive "P")
6719 (if (org-at-table-p)
6720 (org-call-with-arg 'org-table-sort-lines with-case)
6721 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6723 (defun org-sort-remove-invisible (s)
6724 (remove-text-properties 0 (length s) org-rm-props s)
6725 (while (string-match org-bracket-link-regexp s)
6726 (setq s (replace-match (if (match-end 2)
6727 (match-string 3 s)
6728 (match-string 1 s)) t t s)))
6731 (defvar org-priority-regexp) ; defined later in the file
6733 (defvar org-after-sorting-entries-or-items-hook nil
6734 "Hook that is run after a bunch of entries or items have been sorted.
6735 When children are sorted, the cursor is in the parent line when this
6736 hook gets called. When a region or a plain list is sorted, the cursor
6737 will be in the first entry of the sorted region/list.")
6739 (defun org-sort-entries-or-items
6740 (&optional with-case sorting-type getkey-func compare-func property)
6741 "Sort entries on a certain level of an outline tree, or plain list items.
6742 If there is an active region, the entries in the region are sorted.
6743 Else, if the cursor is before the first entry, sort the top-level items.
6744 Else, the children of the entry at point are sorted.
6745 If the cursor is at the first item in a plain list, the list items will be
6746 sorted.
6748 Sorting can be alphabetically, numerically, by date/time as given by
6749 a time stamp, by a property or by priority.
6751 The command prompts for the sorting type unless it has been given to the
6752 function through the SORTING-TYPE argument, which needs to a character,
6753 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6754 precise meaning of each character:
6756 n Numerically, by converting the beginning of the entry/item to a number.
6757 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6758 t By date/time, either the first active time stamp in the entry, or, if
6759 none exist, by the first inactive one.
6760 In items, only the first line will be chekced.
6761 s By the scheduled date/time.
6762 d By deadline date/time.
6763 c By creation time, which is assumed to be the first inactive time stamp
6764 at the beginning of a line.
6765 p By priority according to the cookie.
6766 r By the value of a property.
6768 Capital letters will reverse the sort order.
6770 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6771 called with point at the beginning of the record. It must return either
6772 a string or a number that should serve as the sorting key for that record.
6774 Comparing entries ignores case by default. However, with an optional argument
6775 WITH-CASE, the sorting considers case as well."
6776 (interactive "P")
6777 (let ((case-func (if with-case 'identity 'downcase))
6778 start beg end stars re re2
6779 txt what tmp plain-list-p)
6780 ;; Find beginning and end of region to sort
6781 (cond
6782 ((org-region-active-p)
6783 ;; we will sort the region
6784 (setq end (region-end)
6785 what "region")
6786 (goto-char (region-beginning))
6787 (if (not (org-on-heading-p)) (outline-next-heading))
6788 (setq start (point)))
6789 ((org-at-item-p)
6790 ;; we will sort this plain list
6791 (org-beginning-of-item-list) (setq start (point))
6792 (org-end-of-item-list) (setq end (point))
6793 (goto-char start)
6794 (setq plain-list-p t
6795 what "plain list"))
6796 ((or (org-on-heading-p)
6797 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6798 ;; we will sort the children of the current headline
6799 (org-back-to-heading)
6800 (setq start (point)
6801 end (progn (org-end-of-subtree t t)
6802 (org-back-over-empty-lines)
6803 (point))
6804 what "children")
6805 (goto-char start)
6806 (show-subtree)
6807 (outline-next-heading))
6809 ;; we will sort the top-level entries in this file
6810 (goto-char (point-min))
6811 (or (org-on-heading-p) (outline-next-heading))
6812 (setq start (point) end (point-max) what "top-level")
6813 (goto-char start)
6814 (show-all)))
6816 (setq beg (point))
6817 (if (>= beg end) (error "Nothing to sort"))
6819 (unless plain-list-p
6820 (looking-at "\\(\\*+\\)")
6821 (setq stars (match-string 1)
6822 re (concat "^" (regexp-quote stars) " +")
6823 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6824 txt (buffer-substring beg end))
6825 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6826 (if (and (not (equal stars "*")) (string-match re2 txt))
6827 (error "Region to sort contains a level above the first entry")))
6829 (unless sorting-type
6830 (message
6831 (if plain-list-p
6832 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6833 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6834 [t]ime [s]cheduled [d]eadline [c]reated
6835 A/N/T/S/D/C/P/O/F means reversed:")
6836 what)
6837 (setq sorting-type (read-char-exclusive))
6839 (and (= (downcase sorting-type) ?f)
6840 (setq getkey-func
6841 (org-icompleting-read "Sort using function: "
6842 obarray 'fboundp t nil nil))
6843 (setq getkey-func (intern getkey-func)))
6845 (and (= (downcase sorting-type) ?r)
6846 (setq property
6847 (org-icompleting-read "Property: "
6848 (mapcar 'list (org-buffer-property-keys t))
6849 nil t))))
6851 (message "Sorting entries...")
6853 (save-restriction
6854 (narrow-to-region start end)
6856 (let ((dcst (downcase sorting-type))
6857 (case-fold-search nil)
6858 (now (current-time)))
6859 (sort-subr
6860 (/= dcst sorting-type)
6861 ;; This function moves to the beginning character of the "record" to
6862 ;; be sorted.
6863 (if plain-list-p
6864 (lambda nil
6865 (if (org-at-item-p) t (goto-char (point-max))))
6866 (lambda nil
6867 (if (re-search-forward re nil t)
6868 (goto-char (match-beginning 0))
6869 (goto-char (point-max)))))
6870 ;; This function moves to the last character of the "record" being
6871 ;; sorted.
6872 (if plain-list-p
6873 'org-end-of-item
6874 (lambda nil
6875 (save-match-data
6876 (condition-case nil
6877 (outline-forward-same-level 1)
6878 (error
6879 (goto-char (point-max)))))))
6881 ;; This function returns the value that gets sorted against.
6882 (if plain-list-p
6883 (lambda nil
6884 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6885 (cond
6886 ((= dcst ?n)
6887 (string-to-number (buffer-substring (match-end 0)
6888 (point-at-eol))))
6889 ((= dcst ?a)
6890 (buffer-substring (match-end 0) (point-at-eol)))
6891 ((= dcst ?t)
6892 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6893 (re-search-forward org-ts-regexp-both
6894 (point-at-eol) t))
6895 (org-time-string-to-seconds (match-string 0))
6896 (org-float-time now)))
6897 ((= dcst ?f)
6898 (if getkey-func
6899 (progn
6900 (setq tmp (funcall getkey-func))
6901 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6902 tmp)
6903 (error "Invalid key function `%s'" getkey-func)))
6904 (t (error "Invalid sorting type `%c'" sorting-type)))))
6905 (lambda nil
6906 (cond
6907 ((= dcst ?n)
6908 (if (looking-at org-complex-heading-regexp)
6909 (string-to-number (match-string 4))
6910 nil))
6911 ((= dcst ?a)
6912 (if (looking-at org-complex-heading-regexp)
6913 (funcall case-func (match-string 4))
6914 nil))
6915 ((= dcst ?t)
6916 (let ((end (save-excursion (outline-next-heading) (point))))
6917 (if (or (re-search-forward org-ts-regexp end t)
6918 (re-search-forward org-ts-regexp-both end t))
6919 (org-time-string-to-seconds (match-string 0))
6920 (org-float-time now))))
6921 ((= dcst ?c)
6922 (let ((end (save-excursion (outline-next-heading) (point))))
6923 (if (re-search-forward
6924 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6925 end t)
6926 (org-time-string-to-seconds (match-string 0))
6927 (org-float-time now))))
6928 ((= dcst ?s)
6929 (let ((end (save-excursion (outline-next-heading) (point))))
6930 (if (re-search-forward org-scheduled-time-regexp end t)
6931 (org-time-string-to-seconds (match-string 1))
6932 (org-float-time now))))
6933 ((= dcst ?d)
6934 (let ((end (save-excursion (outline-next-heading) (point))))
6935 (if (re-search-forward org-deadline-time-regexp end t)
6936 (org-time-string-to-seconds (match-string 1))
6937 (org-float-time now))))
6938 ((= dcst ?p)
6939 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6940 (string-to-char (match-string 2))
6941 org-default-priority))
6942 ((= dcst ?r)
6943 (or (org-entry-get nil property) ""))
6944 ((= dcst ?o)
6945 (if (looking-at org-complex-heading-regexp)
6946 (- 9999 (length (member (match-string 2)
6947 org-todo-keywords-1)))))
6948 ((= dcst ?f)
6949 (if getkey-func
6950 (progn
6951 (setq tmp (funcall getkey-func))
6952 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6953 tmp)
6954 (error "Invalid key function `%s'" getkey-func)))
6955 (t (error "Invalid sorting type `%c'" sorting-type)))))
6957 (cond
6958 ((= dcst ?a) 'string<)
6959 ((= dcst ?f) compare-func)
6960 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6961 (t nil)))))
6962 (run-hooks 'org-after-sorting-entries-or-items-hook)
6963 (message "Sorting entries...done")))
6965 (defun org-do-sort (table what &optional with-case sorting-type)
6966 "Sort TABLE of WHAT according to SORTING-TYPE.
6967 The user will be prompted for the SORTING-TYPE if the call to this
6968 function does not specify it. WHAT is only for the prompt, to indicate
6969 what is being sorted. The sorting key will be extracted from
6970 the car of the elements of the table.
6971 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6972 (unless sorting-type
6973 (message
6974 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6975 what)
6976 (setq sorting-type (read-char-exclusive)))
6977 (let ((dcst (downcase sorting-type))
6978 extractfun comparefun)
6979 ;; Define the appropriate functions
6980 (cond
6981 ((= dcst ?n)
6982 (setq extractfun 'string-to-number
6983 comparefun (if (= dcst sorting-type) '< '>)))
6984 ((= dcst ?a)
6985 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6986 (lambda(x) (downcase (org-sort-remove-invisible x))))
6987 comparefun (if (= dcst sorting-type)
6988 'string<
6989 (lambda (a b) (and (not (string< a b))
6990 (not (string= a b)))))))
6991 ((= dcst ?t)
6992 (setq extractfun
6993 (lambda (x)
6994 (if (or (string-match org-ts-regexp x)
6995 (string-match org-ts-regexp-both x))
6996 (org-float-time
6997 (org-time-string-to-time (match-string 0 x)))
6999 comparefun (if (= dcst sorting-type) '< '>)))
7000 (t (error "Invalid sorting type `%c'" sorting-type)))
7002 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7003 table)
7004 (lambda (a b) (funcall comparefun (car a) (car b))))))
7007 ;;; The orgstruct minor mode
7009 ;; Define a minor mode which can be used in other modes in order to
7010 ;; integrate the org-mode structure editing commands.
7012 ;; This is really a hack, because the org-mode structure commands use
7013 ;; keys which normally belong to the major mode. Here is how it
7014 ;; works: The minor mode defines all the keys necessary to operate the
7015 ;; structure commands, but wraps the commands into a function which
7016 ;; tests if the cursor is currently at a headline or a plain list
7017 ;; item. If that is the case, the structure command is used,
7018 ;; temporarily setting many Org-mode variables like regular
7019 ;; expressions for filling etc. However, when any of those keys is
7020 ;; used at a different location, function uses `key-binding' to look
7021 ;; up if the key has an associated command in another currently active
7022 ;; keymap (minor modes, major mode, global), and executes that
7023 ;; command. There might be problems if any of the keys is otherwise
7024 ;; used as a prefix key.
7026 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7027 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7028 ;; addresses this by checking explicitly for both bindings.
7030 (defvar orgstruct-mode-map (make-sparse-keymap)
7031 "Keymap for the minor `orgstruct-mode'.")
7033 (defvar org-local-vars nil
7034 "List of local variables, for use by `orgstruct-mode'")
7036 ;;;###autoload
7037 (define-minor-mode orgstruct-mode
7038 "Toggle the minor more `orgstruct-mode'.
7039 This mode is for using Org-mode structure commands in other modes.
7040 The following key behave as if Org-mode was active, if the cursor
7041 is on a headline, or on a plain list item (both in the definition
7042 of Org-mode).
7044 M-up Move entry/item up
7045 M-down Move entry/item down
7046 M-left Promote
7047 M-right Demote
7048 M-S-up Move entry/item up
7049 M-S-down Move entry/item down
7050 M-S-left Promote subtree
7051 M-S-right Demote subtree
7052 M-q Fill paragraph and items like in Org-mode
7053 C-c ^ Sort entries
7054 C-c - Cycle list bullet
7055 TAB Cycle item visibility
7056 M-RET Insert new heading/item
7057 S-M-RET Insert new TODO heading / Checkbox item
7058 C-c C-c Set tags / toggle checkbox"
7059 nil " OrgStruct" nil
7060 (org-load-modules-maybe)
7061 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7063 ;;;###autoload
7064 (defun turn-on-orgstruct ()
7065 "Unconditionally turn on `orgstruct-mode'."
7066 (orgstruct-mode 1))
7068 (defun orgstruct++-mode (&optional arg)
7069 "Toggle `orgstruct-mode', the enhanced version of it.
7070 In addition to setting orgstruct-mode, this also exports all indentation
7071 and autofilling variables from org-mode into the buffer. It will also
7072 recognize item context in multiline items.
7073 Note that turning off orgstruct-mode will *not* remove the
7074 indentation/paragraph settings. This can only be done by refreshing the
7075 major mode, for example with \\[normal-mode]."
7076 (interactive "P")
7077 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7078 (if (< arg 1)
7079 (orgstruct-mode -1)
7080 (orgstruct-mode 1)
7081 (let (var val)
7082 (mapc
7083 (lambda (x)
7084 (when (string-match
7085 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7086 (symbol-name (car x)))
7087 (setq var (car x) val (nth 1 x))
7088 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7089 org-local-vars)
7090 (org-set-local 'orgstruct-is-++ t))))
7092 (defvar orgstruct-is-++ nil
7093 "Is orgstruct-mode in ++ version in the current-buffer?")
7094 (make-variable-buffer-local 'orgstruct-is-++)
7096 ;;;###autoload
7097 (defun turn-on-orgstruct++ ()
7098 "Unconditionally turn on `orgstruct++-mode'."
7099 (orgstruct++-mode 1))
7101 (defun orgstruct-error ()
7102 "Error when there is no default binding for a structure key."
7103 (interactive)
7104 (error "This key has no function outside structure elements"))
7106 (defun orgstruct-setup ()
7107 "Setup orgstruct keymaps."
7108 (let ((nfunc 0)
7109 (bindings
7110 (list
7111 '([(meta up)] org-metaup)
7112 '([(meta down)] org-metadown)
7113 '([(meta left)] org-metaleft)
7114 '([(meta right)] org-metaright)
7115 '([(meta shift up)] org-shiftmetaup)
7116 '([(meta shift down)] org-shiftmetadown)
7117 '([(meta shift left)] org-shiftmetaleft)
7118 '([(meta shift right)] org-shiftmetaright)
7119 '([?\e (up)] org-metaup)
7120 '([?\e (down)] org-metadown)
7121 '([?\e (left)] org-metaleft)
7122 '([?\e (right)] org-metaright)
7123 '([?\e (shift up)] org-shiftmetaup)
7124 '([?\e (shift down)] org-shiftmetadown)
7125 '([?\e (shift left)] org-shiftmetaleft)
7126 '([?\e (shift right)] org-shiftmetaright)
7127 '([(shift up)] org-shiftup)
7128 '([(shift down)] org-shiftdown)
7129 '([(shift left)] org-shiftleft)
7130 '([(shift right)] org-shiftright)
7131 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7132 '("\M-q" fill-paragraph)
7133 '("\C-c^" org-sort)
7134 '("\C-c-" org-cycle-list-bullet)))
7135 elt key fun cmd)
7136 (while (setq elt (pop bindings))
7137 (setq nfunc (1+ nfunc))
7138 (setq key (org-key (car elt))
7139 fun (nth 1 elt)
7140 cmd (orgstruct-make-binding fun nfunc key))
7141 (org-defkey orgstruct-mode-map key cmd))
7143 ;; Special treatment needed for TAB and RET
7144 (org-defkey orgstruct-mode-map [(tab)]
7145 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7146 (org-defkey orgstruct-mode-map "\C-i"
7147 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7149 (org-defkey orgstruct-mode-map "\M-\C-m"
7150 (orgstruct-make-binding 'org-insert-heading 105
7151 "\M-\C-m" [(meta return)]))
7152 (org-defkey orgstruct-mode-map [(meta return)]
7153 (orgstruct-make-binding 'org-insert-heading 106
7154 [(meta return)] "\M-\C-m"))
7156 (org-defkey orgstruct-mode-map [(shift meta return)]
7157 (orgstruct-make-binding 'org-insert-todo-heading 107
7158 [(meta return)] "\M-\C-m"))
7160 (org-defkey orgstruct-mode-map "\e\C-m"
7161 (orgstruct-make-binding 'org-insert-heading 108
7162 "\e\C-m" [?\e (return)]))
7163 (org-defkey orgstruct-mode-map [?\e (return)]
7164 (orgstruct-make-binding 'org-insert-heading 109
7165 [?\e (return)] "\e\C-m"))
7166 (org-defkey orgstruct-mode-map [?\e (shift return)]
7167 (orgstruct-make-binding 'org-insert-todo-heading 110
7168 [?\e (return)] "\e\C-m"))
7170 (unless org-local-vars
7171 (setq org-local-vars (org-get-local-variables)))
7175 (defun orgstruct-make-binding (fun n &rest keys)
7176 "Create a function for binding in the structure minor mode.
7177 FUN is the command to call inside a table. N is used to create a unique
7178 command name. KEYS are keys that should be checked in for a command
7179 to execute outside of tables."
7180 (eval
7181 (list 'defun
7182 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7183 '(arg)
7184 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7185 "Outside of structure, run the binding of `"
7186 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7187 "'.")
7188 '(interactive "p")
7189 (list 'if
7190 `(org-context-p 'headline 'item
7191 (and orgstruct-is-++
7192 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7193 'item-body))
7194 (list 'org-run-like-in-org-mode (list 'quote fun))
7195 (list 'let '(orgstruct-mode)
7196 (list 'call-interactively
7197 (append '(or)
7198 (mapcar (lambda (k)
7199 (list 'key-binding k))
7200 keys)
7201 '('orgstruct-error))))))))
7203 (defun org-context-p (&rest contexts)
7204 "Check if local context is any of CONTEXTS.
7205 Possible values in the list of contexts are `table', `headline', and `item'."
7206 (let ((pos (point)))
7207 (goto-char (point-at-bol))
7208 (prog1 (or (and (memq 'table contexts)
7209 (looking-at "[ \t]*|"))
7210 (and (memq 'headline contexts)
7211 ;;????????? (looking-at "\\*+"))
7212 (looking-at outline-regexp))
7213 (and (memq 'item contexts)
7214 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7215 (and (memq 'item-body contexts)
7216 (org-in-item-p)))
7217 (goto-char pos))))
7219 (defun org-get-local-variables ()
7220 "Return a list of all local variables in an org-mode buffer."
7221 (let (varlist)
7222 (with-current-buffer (get-buffer-create "*Org tmp*")
7223 (erase-buffer)
7224 (org-mode)
7225 (setq varlist (buffer-local-variables)))
7226 (kill-buffer "*Org tmp*")
7227 (delq nil
7228 (mapcar
7229 (lambda (x)
7230 (setq x
7231 (if (symbolp x)
7232 (list x)
7233 (list (car x) (list 'quote (cdr x)))))
7234 (if (string-match
7235 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7236 (symbol-name (car x)))
7237 x nil))
7238 varlist))))
7240 ;;;###autoload
7241 (defun org-run-like-in-org-mode (cmd)
7242 "Run a command, pretending that the current buffer is in Org-mode.
7243 This will temporarily bind local variables that are typically bound in
7244 Org-mode to the values they have in Org-mode, and then interactively
7245 call CMD."
7246 (org-load-modules-maybe)
7247 (unless org-local-vars
7248 (setq org-local-vars (org-get-local-variables)))
7249 (eval (list 'let org-local-vars
7250 (list 'call-interactively (list 'quote cmd)))))
7252 ;;;; Archiving
7254 (defun org-get-category (&optional pos)
7255 "Get the category applying to position POS."
7256 (get-text-property (or pos (point)) 'org-category))
7258 (defun org-refresh-category-properties ()
7259 "Refresh category text properties in the buffer."
7260 (let ((def-cat (cond
7261 ((null org-category)
7262 (if buffer-file-name
7263 (file-name-sans-extension
7264 (file-name-nondirectory buffer-file-name))
7265 "???"))
7266 ((symbolp org-category) (symbol-name org-category))
7267 (t org-category)))
7268 beg end cat pos optionp)
7269 (org-unmodified
7270 (save-excursion
7271 (save-restriction
7272 (widen)
7273 (goto-char (point-min))
7274 (put-text-property (point) (point-max) 'org-category def-cat)
7275 (while (re-search-forward
7276 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7277 (setq pos (match-end 0)
7278 optionp (equal (char-after (match-beginning 0)) ?#)
7279 cat (org-trim (match-string 2)))
7280 (if optionp
7281 (setq beg (point-at-bol) end (point-max))
7282 (org-back-to-heading t)
7283 (setq beg (point) end (org-end-of-subtree t t)))
7284 (put-text-property beg end 'org-category cat)
7285 (goto-char pos)))))))
7288 ;;;; Link Stuff
7290 ;;; Link abbreviations
7292 (defun org-link-expand-abbrev (link)
7293 "Apply replacements as defined in `org-link-abbrev-alist."
7294 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7295 (let* ((key (match-string 1 link))
7296 (as (or (assoc key org-link-abbrev-alist-local)
7297 (assoc key org-link-abbrev-alist)))
7298 (tag (and (match-end 2) (match-string 3 link)))
7299 rpl)
7300 (if (not as)
7301 link
7302 (setq rpl (cdr as))
7303 (cond
7304 ((symbolp rpl) (funcall rpl tag))
7305 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7306 ((string-match "%h" rpl)
7307 (replace-match (url-hexify-string (or tag "")) t t rpl))
7308 (t (concat rpl tag)))))
7309 link))
7311 ;;; Storing and inserting links
7313 (defvar org-insert-link-history nil
7314 "Minibuffer history for links inserted with `org-insert-link'.")
7316 (defvar org-stored-links nil
7317 "Contains the links stored with `org-store-link'.")
7319 (defvar org-store-link-plist nil
7320 "Plist with info about the most recently link created with `org-store-link'.")
7322 (defvar org-link-protocols nil
7323 "Link protocols added to Org-mode using `org-add-link-type'.")
7325 (defvar org-store-link-functions nil
7326 "List of functions that are called to create and store a link.
7327 Each function will be called in turn until one returns a non-nil
7328 value. Each function should check if it is responsible for creating
7329 this link (for example by looking at the major mode).
7330 If not, it must exit and return nil.
7331 If yes, it should return a non-nil value after a calling
7332 `org-store-link-props' with a list of properties and values.
7333 Special properties are:
7335 :type The link prefix. like \"http\". This must be given.
7336 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7337 This is obligatory as well.
7338 :description Optional default description for the second pair
7339 of brackets in an Org-mode link. The user can still change
7340 this when inserting this link into an Org-mode buffer.
7342 In addition to these, any additional properties can be specified
7343 and then used in remember templates.")
7345 (defun org-add-link-type (type &optional follow export)
7346 "Add TYPE to the list of `org-link-types'.
7347 Re-compute all regular expressions depending on `org-link-types'
7349 FOLLOW and EXPORT are two functions.
7351 FOLLOW should take the link path as the single argument and do whatever
7352 is necessary to follow the link, for example find a file or display
7353 a mail message.
7355 EXPORT should format the link path for export to one of the export formats.
7356 It should be a function accepting three arguments:
7358 path the path of the link, the text after the prefix (like \"http:\")
7359 desc the description of the link, if any, nil if there was no description
7360 format the export format, a symbol like `html' or `latex'.
7362 The function may use the FORMAT information to return different values
7363 depending on the format. The return value will be put literally into
7364 the exported file.
7365 Org-mode has a built-in default for exporting links. If you are happy with
7366 this default, there is no need to define an export function for the link
7367 type. For a simple example of an export function, see `org-bbdb.el'."
7368 (add-to-list 'org-link-types type t)
7369 (org-make-link-regexps)
7370 (if (assoc type org-link-protocols)
7371 (setcdr (assoc type org-link-protocols) (list follow export))
7372 (push (list type follow export) org-link-protocols)))
7374 (defvar org-agenda-buffer-name)
7376 ;;;###autoload
7377 (defun org-store-link (arg)
7378 "\\<org-mode-map>Store an org-link to the current location.
7379 This link is added to `org-stored-links' and can later be inserted
7380 into an org-buffer with \\[org-insert-link].
7382 For some link types, a prefix arg is interpreted:
7383 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7384 For file links, arg negates `org-context-in-file-links'."
7385 (interactive "P")
7386 (org-load-modules-maybe)
7387 (setq org-store-link-plist nil) ; reset
7388 (let ((outline-regexp (org-get-limited-outline-regexp))
7389 link cpltxt desc description search txt custom-id)
7390 (cond
7392 ((run-hook-with-args-until-success 'org-store-link-functions)
7393 (setq link (plist-get org-store-link-plist :link)
7394 desc (or (plist-get org-store-link-plist :description) link)))
7396 ((equal (buffer-name) "*Org Edit Src Example*")
7397 (let (label gc)
7398 (while (or (not label)
7399 (save-excursion
7400 (save-restriction
7401 (widen)
7402 (goto-char (point-min))
7403 (re-search-forward
7404 (regexp-quote (format org-coderef-label-format label))
7405 nil t))))
7406 (when label (message "Label exists already") (sit-for 2))
7407 (setq label (read-string "Code line label: " label)))
7408 (end-of-line 1)
7409 (setq link (format org-coderef-label-format label))
7410 (setq gc (- 79 (length link)))
7411 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7412 (insert link)
7413 (setq link (concat "(" label ")") desc nil)))
7415 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7416 ;; We are in the agenda, link to referenced location
7417 (let ((m (or (get-text-property (point) 'org-hd-marker)
7418 (get-text-property (point) 'org-marker))))
7419 (when m
7420 (org-with-point-at m
7421 (call-interactively 'org-store-link)))))
7423 ((eq major-mode 'calendar-mode)
7424 (let ((cd (calendar-cursor-to-date)))
7425 (setq link
7426 (format-time-string
7427 (car org-time-stamp-formats)
7428 (apply 'encode-time
7429 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7430 nil nil nil))))
7431 (org-store-link-props :type "calendar" :date cd)))
7433 ((eq major-mode 'w3-mode)
7434 (setq cpltxt (if (and (buffer-name)
7435 (not (string-match "Untitled" (buffer-name))))
7436 (buffer-name)
7437 (url-view-url t))
7438 link (org-make-link (url-view-url t)))
7439 (org-store-link-props :type "w3" :url (url-view-url t)))
7441 ((eq major-mode 'w3m-mode)
7442 (setq cpltxt (or w3m-current-title w3m-current-url)
7443 link (org-make-link w3m-current-url))
7444 (org-store-link-props :type "w3m" :url (url-view-url t)))
7446 ((setq search (run-hook-with-args-until-success
7447 'org-create-file-search-functions))
7448 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7449 "::" search))
7450 (setq cpltxt (or description link)))
7452 ((eq major-mode 'image-mode)
7453 (setq cpltxt (concat "file:"
7454 (abbreviate-file-name buffer-file-name))
7455 link (org-make-link cpltxt))
7456 (org-store-link-props :type "image" :file buffer-file-name))
7458 ((eq major-mode 'dired-mode)
7459 ;; link to the file in the current line
7460 (setq cpltxt (concat "file:"
7461 (abbreviate-file-name
7462 (expand-file-name
7463 (dired-get-filename nil t))))
7464 link (org-make-link cpltxt)))
7466 ((and buffer-file-name (org-mode-p))
7467 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7468 (cond
7469 ((org-in-regexp "<<\\(.*?\\)>>")
7470 (setq cpltxt
7471 (concat "file:"
7472 (abbreviate-file-name buffer-file-name)
7473 "::" (match-string 1))
7474 link (org-make-link cpltxt)))
7475 ((and (featurep 'org-id)
7476 (or (eq org-link-to-org-use-id t)
7477 (and (eq org-link-to-org-use-id 'create-if-interactive)
7478 (interactive-p))
7479 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7480 (interactive-p)
7481 (not custom-id))
7482 (and org-link-to-org-use-id
7483 (condition-case nil
7484 (org-entry-get nil "ID")
7485 (error nil)))))
7486 ;; We can make a link using the ID.
7487 (setq link (condition-case nil
7488 (prog1 (org-id-store-link)
7489 (setq desc (plist-get org-store-link-plist
7490 :description)))
7491 (error
7492 ;; probably before first headline, link to file only
7493 (concat "file:"
7494 (abbreviate-file-name buffer-file-name))))))
7496 ;; Just link to current headline
7497 (setq cpltxt (concat "file:"
7498 (abbreviate-file-name buffer-file-name)))
7499 ;; Add a context search string
7500 (when (org-xor org-context-in-file-links arg)
7501 (setq txt (cond
7502 ((org-on-heading-p) nil)
7503 ((org-region-active-p)
7504 (buffer-substring (region-beginning) (region-end)))
7505 (t nil)))
7506 (when (or (null txt) (string-match "\\S-" txt))
7507 (setq cpltxt
7508 (concat cpltxt "::"
7509 (condition-case nil
7510 (org-make-org-heading-search-string txt)
7511 (error "")))
7512 desc (or (nth 4 (ignore-errors
7513 (org-heading-components))) "NONE"))))
7514 (if (string-match "::\\'" cpltxt)
7515 (setq cpltxt (substring cpltxt 0 -2)))
7516 (setq link (org-make-link cpltxt)))))
7518 ((buffer-file-name (buffer-base-buffer))
7519 ;; Just link to this file here.
7520 (setq cpltxt (concat "file:"
7521 (abbreviate-file-name
7522 (buffer-file-name (buffer-base-buffer)))))
7523 ;; Add a context string
7524 (when (org-xor org-context-in-file-links arg)
7525 (setq txt (if (org-region-active-p)
7526 (buffer-substring (region-beginning) (region-end))
7527 (buffer-substring (point-at-bol) (point-at-eol))))
7528 ;; Only use search option if there is some text.
7529 (when (string-match "\\S-" txt)
7530 (setq cpltxt
7531 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7532 desc "NONE")))
7533 (setq link (org-make-link cpltxt)))
7535 ((interactive-p)
7536 (error "Cannot link to a buffer which is not visiting a file"))
7538 (t (setq link nil)))
7540 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7541 (setq link (or link cpltxt)
7542 desc (or desc cpltxt))
7543 (if (equal desc "NONE") (setq desc nil))
7545 (if (and (or (interactive-p) executing-kbd-macro) link)
7546 (progn
7547 (setq org-stored-links
7548 (cons (list link desc) org-stored-links))
7549 (message "Stored: %s" (or desc link))
7550 (when custom-id
7551 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7552 "::#" custom-id))
7553 (setq org-stored-links
7554 (cons (list link desc) org-stored-links))))
7555 (and link (org-make-link-string link desc)))))
7557 (defun org-store-link-props (&rest plist)
7558 "Store link properties, extract names and addresses."
7559 (let (x adr)
7560 (when (setq x (plist-get plist :from))
7561 (setq adr (mail-extract-address-components x))
7562 (setq plist (plist-put plist :fromname (car adr)))
7563 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7564 (when (setq x (plist-get plist :to))
7565 (setq adr (mail-extract-address-components x))
7566 (setq plist (plist-put plist :toname (car adr)))
7567 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7568 (let ((from (plist-get plist :from))
7569 (to (plist-get plist :to)))
7570 (when (and from to org-from-is-user-regexp)
7571 (setq plist
7572 (plist-put plist :fromto
7573 (if (string-match org-from-is-user-regexp from)
7574 (concat "to %t")
7575 (concat "from %f"))))))
7576 (setq org-store-link-plist plist))
7578 (defun org-add-link-props (&rest plist)
7579 "Add these properties to the link property list."
7580 (let (key value)
7581 (while plist
7582 (setq key (pop plist) value (pop plist))
7583 (setq org-store-link-plist
7584 (plist-put org-store-link-plist key value)))))
7586 (defun org-email-link-description (&optional fmt)
7587 "Return the description part of an email link.
7588 This takes information from `org-store-link-plist' and formats it
7589 according to FMT (default from `org-email-link-description-format')."
7590 (setq fmt (or fmt org-email-link-description-format))
7591 (let* ((p org-store-link-plist)
7592 (to (plist-get p :toaddress))
7593 (from (plist-get p :fromaddress))
7594 (table
7595 (list
7596 (cons "%c" (plist-get p :fromto))
7597 (cons "%F" (plist-get p :from))
7598 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7599 (cons "%T" (plist-get p :to))
7600 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7601 (cons "%s" (plist-get p :subject))
7602 (cons "%m" (plist-get p :message-id)))))
7603 (when (string-match "%c" fmt)
7604 ;; Check if the user wrote this message
7605 (if (and org-from-is-user-regexp from to
7606 (save-match-data (string-match org-from-is-user-regexp from)))
7607 (setq fmt (replace-match "to %t" t t fmt))
7608 (setq fmt (replace-match "from %f" t t fmt))))
7609 (org-replace-escapes fmt table)))
7611 (defun org-make-org-heading-search-string (&optional string heading)
7612 "Make search string for STRING or current headline."
7613 (interactive)
7614 (let ((s (or string (org-get-heading))))
7615 (unless (and string (not heading))
7616 ;; We are using a headline, clean up garbage in there.
7617 (if (string-match org-todo-regexp s)
7618 (setq s (replace-match "" t t s)))
7619 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7620 (setq s (replace-match "" t t s)))
7621 (setq s (org-trim s))
7622 (if (string-match (concat "^\\(" org-quote-string "\\|"
7623 org-comment-string "\\)") s)
7624 (setq s (replace-match "" t t s)))
7625 (while (string-match org-ts-regexp s)
7626 (setq s (replace-match "" t t s))))
7627 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7628 (setq s (replace-match " " t t s)))
7629 (or string (setq s (concat "*" s))) ; Add * for headlines
7630 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7632 (defun org-make-link (&rest strings)
7633 "Concatenate STRINGS."
7634 (apply 'concat strings))
7636 (defun org-make-link-string (link &optional description)
7637 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7638 (unless (string-match "\\S-" link)
7639 (error "Empty link"))
7640 (when (stringp description)
7641 ;; Remove brackets from the description, they are fatal.
7642 (while (string-match "\\[" description)
7643 (setq description (replace-match "{" t t description)))
7644 (while (string-match "\\]" description)
7645 (setq description (replace-match "}" t t description))))
7646 (when (equal (org-link-escape link) description)
7647 ;; No description needed, it is identical
7648 (setq description nil))
7649 (when (and (not description)
7650 (not (equal link (org-link-escape link))))
7651 (setq description (org-extract-attributes link)))
7652 (concat "[[" (org-link-escape link) "]"
7653 (if description (concat "[" description "]") "")
7654 "]"))
7656 (defconst org-link-escape-chars
7657 '((?\ . "%20")
7658 (?\[ . "%5B")
7659 (?\] . "%5D")
7660 (?\340 . "%E0") ; `a
7661 (?\342 . "%E2") ; ^a
7662 (?\347 . "%E7") ; ,c
7663 (?\350 . "%E8") ; `e
7664 (?\351 . "%E9") ; 'e
7665 (?\352 . "%EA") ; ^e
7666 (?\356 . "%EE") ; ^i
7667 (?\364 . "%F4") ; ^o
7668 (?\371 . "%F9") ; `u
7669 (?\373 . "%FB") ; ^u
7670 (?\; . "%3B")
7671 (?? . "%3F")
7672 (?= . "%3D")
7673 (?+ . "%2B")
7675 "Association list of escapes for some characters problematic in links.
7676 This is the list that is used for internal purposes.")
7678 (defvar org-url-encoding-use-url-hexify nil)
7680 (defconst org-link-escape-chars-browser
7681 '((?\ . "%20")) ; 32 for the SPC char
7682 "Association list of escapes for some characters problematic in links.
7683 This is the list that is used before handing over to the browser.")
7685 (defun org-link-escape (text &optional table)
7686 "Escape characters in TEXT that are problematic for links."
7687 (if org-url-encoding-use-url-hexify
7688 (url-hexify-string text)
7689 (setq table (or table org-link-escape-chars))
7690 (when text
7691 (let ((re (mapconcat (lambda (x) (regexp-quote
7692 (char-to-string (car x))))
7693 table "\\|")))
7694 (while (string-match re text)
7695 (setq text
7696 (replace-match
7697 (cdr (assoc (string-to-char (match-string 0 text))
7698 table))
7699 t t text)))
7700 text))))
7702 (defun org-link-unescape (text &optional table)
7703 "Reverse the action of `org-link-escape'."
7704 (if org-url-encoding-use-url-hexify
7705 (url-unhex-string text)
7706 (setq table (or table org-link-escape-chars))
7707 (when text
7708 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7709 table "\\|")))
7710 (while (string-match re text)
7711 (setq text
7712 (replace-match
7713 (char-to-string (car (rassoc (match-string 0 text) table)))
7714 t t text)))
7715 text))))
7717 (defun org-xor (a b)
7718 "Exclusive or."
7719 (if a (not b) b))
7721 (defun org-fixup-message-id-for-http (s)
7722 "Replace special characters in a message id, so it can be used in an http query."
7723 (while (string-match "<" s)
7724 (setq s (replace-match "%3C" t t s)))
7725 (while (string-match ">" s)
7726 (setq s (replace-match "%3E" t t s)))
7727 (while (string-match "@" s)
7728 (setq s (replace-match "%40" t t s)))
7731 ;;;###autoload
7732 (defun org-insert-link-global ()
7733 "Insert a link like Org-mode does.
7734 This command can be called in any mode to insert a link in Org-mode syntax."
7735 (interactive)
7736 (org-load-modules-maybe)
7737 (org-run-like-in-org-mode 'org-insert-link))
7739 (defun org-insert-link (&optional complete-file link-location)
7740 "Insert a link. At the prompt, enter the link.
7742 Completion can be used to insert any of the link protocol prefixes like
7743 http or ftp in use.
7745 The history can be used to select a link previously stored with
7746 `org-store-link'. When the empty string is entered (i.e. if you just
7747 press RET at the prompt), the link defaults to the most recently
7748 stored link. As SPC triggers completion in the minibuffer, you need to
7749 use M-SPC or C-q SPC to force the insertion of a space character.
7751 You will also be prompted for a description, and if one is given, it will
7752 be displayed in the buffer instead of the link.
7754 If there is already a link at point, this command will allow you to edit link
7755 and description parts.
7757 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7758 be selected using completion. The path to the file will be relative to the
7759 current directory if the file is in the current directory or a subdirectory.
7760 Otherwise, the link will be the absolute path as completed in the minibuffer
7761 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7762 option `org-link-file-path-type'.
7764 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7765 the current directory or below.
7767 With three \\[universal-argument] prefixes, negate the meaning of
7768 `org-keep-stored-link-after-insertion'.
7770 If `org-make-link-description-function' is non-nil, this function will be
7771 called with the link target, and the result will be the default
7772 link description.
7774 If the LINK-LOCATION parameter is non-nil, this value will be
7775 used as the link location instead of reading one interactively."
7776 (interactive "P")
7777 (let* ((wcf (current-window-configuration))
7778 (region (if (org-region-active-p)
7779 (buffer-substring (region-beginning) (region-end))))
7780 (remove (and region (list (region-beginning) (region-end))))
7781 (desc region)
7782 tmphist ; byte-compile incorrectly complains about this
7783 (link link-location)
7784 entry file all-prefixes)
7785 (cond
7786 (link-location) ; specified by arg, just use it.
7787 ((org-in-regexp org-bracket-link-regexp 1)
7788 ;; We do have a link at point, and we are going to edit it.
7789 (setq remove (list (match-beginning 0) (match-end 0)))
7790 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7791 (setq link (read-string "Link: "
7792 (org-link-unescape
7793 (org-match-string-no-properties 1)))))
7794 ((or (org-in-regexp org-angle-link-re)
7795 (org-in-regexp org-plain-link-re))
7796 ;; Convert to bracket link
7797 (setq remove (list (match-beginning 0) (match-end 0))
7798 link (read-string "Link: "
7799 (org-remove-angle-brackets (match-string 0)))))
7800 ((member complete-file '((4) (16)))
7801 ;; Completing read for file names.
7802 (setq link (org-file-complete-link complete-file)))
7804 ;; Read link, with completion for stored links.
7805 (with-output-to-temp-buffer "*Org Links*"
7806 (princ "Insert a link.
7807 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7808 (when org-stored-links
7809 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7810 (princ (mapconcat
7811 (lambda (x)
7812 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7813 (reverse org-stored-links) "\n"))))
7814 (let ((cw (selected-window)))
7815 (select-window (get-buffer-window "*Org Links*"))
7816 (setq truncate-lines t)
7817 (unless (pos-visible-in-window-p (point-max))
7818 (org-fit-window-to-buffer))
7819 (and (window-live-p cw) (select-window cw)))
7820 ;; Fake a link history, containing the stored links.
7821 (setq tmphist (append (mapcar 'car org-stored-links)
7822 org-insert-link-history))
7823 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7824 (mapcar 'car org-link-abbrev-alist)
7825 org-link-types))
7826 (unwind-protect
7827 (progn
7828 (setq link
7829 (let ((org-completion-use-ido nil)
7830 (org-completion-use-iswitchb nil))
7831 (org-completing-read
7832 "Link: "
7833 (append
7834 (mapcar (lambda (x) (list (concat x ":")))
7835 all-prefixes)
7836 (mapcar 'car org-stored-links))
7837 nil nil nil
7838 'tmphist
7839 (car (car org-stored-links)))))
7840 (if (or (member link all-prefixes)
7841 (and (equal ":" (substring link -1))
7842 (member (substring link 0 -1) all-prefixes)
7843 (setq link (substring link 0 -1))))
7844 (setq link (org-link-try-special-completion link))))
7845 (set-window-configuration wcf)
7846 (kill-buffer "*Org Links*"))
7847 (setq entry (assoc link org-stored-links))
7848 (or entry (push link org-insert-link-history))
7849 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7850 (not org-keep-stored-link-after-insertion))
7851 (setq org-stored-links (delq (assoc link org-stored-links)
7852 org-stored-links)))
7853 (setq desc (or desc (nth 1 entry)))))
7855 (if (string-match org-plain-link-re link)
7856 ;; URL-like link, normalize the use of angular brackets.
7857 (setq link (org-make-link (org-remove-angle-brackets link))))
7859 ;; Check if we are linking to the current file with a search option
7860 ;; If yes, simplify the link by using only the search option.
7861 (when (and buffer-file-name
7862 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7863 (let* ((path (match-string 1 link))
7864 (case-fold-search nil)
7865 (search (match-string 2 link)))
7866 (save-match-data
7867 (if (equal (file-truename buffer-file-name) (file-truename path))
7868 ;; We are linking to this same file, with a search option
7869 (setq link search)))))
7871 ;; Check if we can/should use a relative path. If yes, simplify the link
7872 (when (string-match "^file:\\(.*\\)" link)
7873 (let* ((path (match-string 1 link))
7874 (origpath path)
7875 (case-fold-search nil))
7876 (cond
7877 ((or (eq org-link-file-path-type 'absolute)
7878 (equal complete-file '(16)))
7879 (setq path (abbreviate-file-name (expand-file-name path))))
7880 ((eq org-link-file-path-type 'noabbrev)
7881 (setq path (expand-file-name path)))
7882 ((eq org-link-file-path-type 'relative)
7883 (setq path (file-relative-name path)))
7885 (save-match-data
7886 (if (string-match (concat "^" (regexp-quote
7887 (file-name-as-directory
7888 (expand-file-name "."))))
7889 (expand-file-name path))
7890 ;; We are linking a file with relative path name.
7891 (setq path (substring (expand-file-name path)
7892 (match-end 0)))
7893 (setq path (abbreviate-file-name (expand-file-name path)))))))
7894 (setq link (concat "file:" path))
7895 (if (equal desc origpath)
7896 (setq desc path))))
7898 (if org-make-link-description-function
7899 (setq desc (funcall org-make-link-description-function link desc)))
7901 (setq desc (read-string "Description: " desc))
7902 (unless (string-match "\\S-" desc) (setq desc nil))
7903 (if remove (apply 'delete-region remove))
7904 (insert (org-make-link-string link desc))))
7906 (defun org-link-try-special-completion (type)
7907 "If there is completion support for link type TYPE, offer it."
7908 (let ((fun (intern (concat "org-" type "-complete-link"))))
7909 (if (functionp fun)
7910 (funcall fun)
7911 (read-string "Link (no completion support): " (concat type ":")))))
7913 (defun org-file-complete-link (&optional arg)
7914 "Create a file link using completion."
7915 (let (file link)
7916 (setq file (read-file-name "File: "))
7917 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7918 (pwd1 (file-name-as-directory (abbreviate-file-name
7919 (expand-file-name ".")))))
7920 (cond
7921 ((equal arg '(16))
7922 (setq link (org-make-link
7923 "file:"
7924 (abbreviate-file-name (expand-file-name file)))))
7925 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7926 (setq link (org-make-link "file:" (match-string 1 file))))
7927 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7928 (expand-file-name file))
7929 (setq link (org-make-link
7930 "file:" (match-string 1 (expand-file-name file)))))
7931 (t (setq link (org-make-link "file:" file)))))
7932 link))
7934 (defun org-completing-read (&rest args)
7935 "Completing-read with SPACE being a normal character."
7936 (let ((minibuffer-local-completion-map
7937 (copy-keymap minibuffer-local-completion-map)))
7938 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7939 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7940 (apply 'org-icompleting-read args)))
7942 (defun org-completing-read-no-i (&rest args)
7943 (let (org-completion-use-ido org-completion-use-iswitchb)
7944 (apply 'org-completing-read args)))
7946 (defun org-iswitchb-completing-read (prompt choices &rest args)
7947 "Use iswitch as a completing-read replacement to choose from choices.
7948 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
7949 from."
7950 (let* ((iswitchb-use-virtual-buffers nil)
7951 (iswitchb-make-buflist-hook
7952 (lambda ()
7953 (setq iswitchb-temp-buflist choices))))
7954 (iswitchb-read-buffer prompt)))
7956 (defun org-icompleting-read (&rest args)
7957 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
7958 (org-without-partial-completion
7959 (if (and org-completion-use-ido
7960 (fboundp 'ido-completing-read)
7961 (boundp 'ido-mode) ido-mode
7962 (listp (second args)))
7963 (let ((ido-enter-matching-directory nil))
7964 (apply 'ido-completing-read (concat (car args))
7965 (if (consp (car (nth 1 args)))
7966 (mapcar (lambda (x) (car x)) (nth 1 args))
7967 (nth 1 args))
7968 (cddr args)))
7969 (if (and org-completion-use-iswitchb
7970 (boundp 'iswitchb-mode) iswitchb-mode
7971 (listp (second args)))
7972 (apply 'org-iswitchb-completing-read (concat (car args))
7973 (if (consp (car (nth 1 args)))
7974 (mapcar (lambda (x) (car x)) (nth 1 args))
7975 (nth 1 args))
7976 (cddr args))
7977 (apply 'completing-read args)))))
7979 (defun org-extract-attributes (s)
7980 "Extract the attributes cookie from a string and set as text property."
7981 (let (a attr (start 0) key value)
7982 (save-match-data
7983 (when (string-match "{{\\([^}]+\\)}}$" s)
7984 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7985 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7986 (setq key (match-string 1 a) value (match-string 2 a)
7987 start (match-end 0)
7988 attr (plist-put attr (intern key) value))))
7989 (org-add-props s nil 'org-attr attr))
7992 (defun org-extract-attributes-from-string (tag)
7993 (let (key value attr)
7994 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7995 (setq key (match-string 1 tag) value (match-string 2 tag)
7996 tag (replace-match "" t t tag)
7997 attr (plist-put attr (intern key) value)))
7998 (cons tag attr)))
8000 (defun org-attributes-to-string (plist)
8001 "Format a property list into an HTML attribute list."
8002 (let ((s "") key value)
8003 (while plist
8004 (setq key (pop plist) value (pop plist))
8005 (and value
8006 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8009 ;;; Opening/following a link
8011 (defvar org-link-search-failed nil)
8013 (defun org-next-link ()
8014 "Move forward to the next link.
8015 If the link is in hidden text, expose it."
8016 (interactive)
8017 (when (and org-link-search-failed (eq this-command last-command))
8018 (goto-char (point-min))
8019 (message "Link search wrapped back to beginning of buffer"))
8020 (setq org-link-search-failed nil)
8021 (let* ((pos (point))
8022 (ct (org-context))
8023 (a (assoc :link ct)))
8024 (if a (goto-char (nth 2 a)))
8025 (if (re-search-forward org-any-link-re nil t)
8026 (progn
8027 (goto-char (match-beginning 0))
8028 (if (org-invisible-p) (org-show-context)))
8029 (goto-char pos)
8030 (setq org-link-search-failed t)
8031 (error "No further link found"))))
8033 (defun org-previous-link ()
8034 "Move backward to the previous link.
8035 If the link is in hidden text, expose it."
8036 (interactive)
8037 (when (and org-link-search-failed (eq this-command last-command))
8038 (goto-char (point-max))
8039 (message "Link search wrapped back to end of buffer"))
8040 (setq org-link-search-failed nil)
8041 (let* ((pos (point))
8042 (ct (org-context))
8043 (a (assoc :link ct)))
8044 (if a (goto-char (nth 1 a)))
8045 (if (re-search-backward org-any-link-re nil t)
8046 (progn
8047 (goto-char (match-beginning 0))
8048 (if (org-invisible-p) (org-show-context)))
8049 (goto-char pos)
8050 (setq org-link-search-failed t)
8051 (error "No further link found"))))
8053 (defun org-translate-link (s)
8054 "Translate a link string if a translation function has been defined."
8055 (if (and org-link-translation-function
8056 (fboundp org-link-translation-function)
8057 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8058 (progn
8059 (setq s (funcall org-link-translation-function
8060 (match-string 1) (match-string 2)))
8061 (concat (car s) ":" (cdr s)))
8064 (defun org-translate-link-from-planner (type path)
8065 "Translate a link from Emacs Planner syntax so that Org can follow it.
8066 This is still an experimental function, your mileage may vary."
8067 (cond
8068 ((member type '("http" "https" "news" "ftp"))
8069 ;; standard Internet links are the same.
8070 nil)
8071 ((and (equal type "irc") (string-match "^//" path))
8072 ;; Planner has two / at the beginning of an irc link, we have 1.
8073 ;; We should have zero, actually....
8074 (setq path (substring path 1)))
8075 ((and (equal type "lisp") (string-match "^/" path))
8076 ;; Planner has a slash, we do not.
8077 (setq type "elisp" path (substring path 1)))
8078 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8079 ;; A typical message link. Planner has the id after the fina slash,
8080 ;; we separate it with a hash mark
8081 (setq path (concat (match-string 1 path) "#"
8082 (org-remove-angle-brackets (match-string 2 path)))))
8084 (cons type path))
8086 (defun org-find-file-at-mouse (ev)
8087 "Open file link or URL at mouse."
8088 (interactive "e")
8089 (mouse-set-point ev)
8090 (org-open-at-point 'in-emacs))
8092 (defun org-open-at-mouse (ev)
8093 "Open file link or URL at mouse."
8094 (interactive "e")
8095 (mouse-set-point ev)
8096 (if (eq major-mode 'org-agenda-mode)
8097 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8098 (org-open-at-point))
8100 (defvar org-window-config-before-follow-link nil
8101 "The window configuration before following a link.
8102 This is saved in case the need arises to restore it.")
8104 (defvar org-open-link-marker (make-marker)
8105 "Marker pointing to the location where `org-open-at-point; was called.")
8107 ;;;###autoload
8108 (defun org-open-at-point-global ()
8109 "Follow a link like Org-mode does.
8110 This command can be called in any mode to follow a link that has
8111 Org-mode syntax."
8112 (interactive)
8113 (org-run-like-in-org-mode 'org-open-at-point))
8115 ;;;###autoload
8116 (defun org-open-link-from-string (s &optional arg reference-buffer)
8117 "Open a link in the string S, as if it was in Org-mode."
8118 (interactive "sLink: \nP")
8119 (let ((reference-buffer (or reference-buffer (current-buffer))))
8120 (with-temp-buffer
8121 (let ((org-inhibit-startup t))
8122 (org-mode)
8123 (insert s)
8124 (goto-char (point-min))
8125 (org-open-at-point arg reference-buffer)))))
8127 (defun org-open-at-point (&optional in-emacs reference-buffer)
8128 "Open link at or after point.
8129 If there is no link at point, this function will search forward up to
8130 the end of the current line.
8131 Normally, files will be opened by an appropriate application. If the
8132 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8133 With a double prefix argument, try to open outside of Emacs, in the
8134 application the system uses for this file type."
8135 (interactive "P")
8136 (org-load-modules-maybe)
8137 (move-marker org-open-link-marker (point))
8138 (setq org-window-config-before-follow-link (current-window-configuration))
8139 (org-remove-occur-highlights nil nil t)
8140 (cond
8141 ((and (org-on-heading-p)
8142 (not (org-in-regexp
8143 (concat org-plain-link-re "\\|"
8144 org-bracket-link-regexp "\\|"
8145 org-angle-link-re "\\|"
8146 "[ \t]:[^ \t\n]+:[ \t]*$"))))
8147 (or (org-offer-links-in-entry in-emacs)
8148 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8149 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8150 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8151 (org-footnote-action))
8153 (let (type path link line search (pos (point)))
8154 (catch 'match
8155 (save-excursion
8156 (skip-chars-forward "^]\n\r")
8157 (when (org-in-regexp org-bracket-link-regexp)
8158 (setq link (org-extract-attributes
8159 (org-link-unescape (org-match-string-no-properties 1))))
8160 (while (string-match " *\n *" link)
8161 (setq link (replace-match " " t t link)))
8162 (setq link (org-link-expand-abbrev link))
8163 (cond
8164 ((or (file-name-absolute-p link)
8165 (string-match "^\\.\\.?/" link))
8166 (setq type "file" path link))
8167 ((string-match org-link-re-with-space3 link)
8168 (setq type (match-string 1 link) path (match-string 2 link)))
8169 (t (setq type "thisfile" path link)))
8170 (throw 'match t)))
8172 (when (get-text-property (point) 'org-linked-text)
8173 (setq type "thisfile"
8174 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8175 (1+ (point)) (point))
8176 path (buffer-substring
8177 (previous-single-property-change pos 'org-linked-text)
8178 (next-single-property-change pos 'org-linked-text)))
8179 (throw 'match t))
8181 (save-excursion
8182 (when (or (org-in-regexp org-angle-link-re)
8183 (org-in-regexp org-plain-link-re))
8184 (setq type (match-string 1) path (match-string 2))
8185 (throw 'match t)))
8186 (save-excursion
8187 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8188 (setq type "tags"
8189 path (match-string 1))
8190 (while (string-match ":" path)
8191 (setq path (replace-match "+" t t path)))
8192 (throw 'match t)))
8193 (when (org-in-regexp "<\\([^><\n]+\\)>")
8194 (setq type "tree-match"
8195 path (match-string 1))
8196 (throw 'match t)))
8197 (unless path
8198 (error "No link found"))
8200 ;; switch back to reference buffer
8201 ;; needed when if called in a temporary buffer through
8202 ;; org-open-link-from-string
8203 (with-current-buffer (or reference-buffer (current-buffer))
8205 ;; Remove any trailing spaces in path
8206 (if (string-match " +\\'" path)
8207 (setq path (replace-match "" t t path)))
8208 (if (and org-link-translation-function
8209 (fboundp org-link-translation-function))
8210 ;; Check if we need to translate the link
8211 (let ((tmp (funcall org-link-translation-function type path)))
8212 (setq type (car tmp) path (cdr tmp))))
8214 (cond
8216 ((assoc type org-link-protocols)
8217 (funcall (nth 1 (assoc type org-link-protocols)) path))
8219 ((equal type "mailto")
8220 (let ((cmd (car org-link-mailto-program))
8221 (args (cdr org-link-mailto-program)) args1
8222 (address path) (subject "") a)
8223 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8224 (setq address (match-string 1 path)
8225 subject (org-link-escape (match-string 2 path))))
8226 (while args
8227 (cond
8228 ((not (stringp (car args))) (push (pop args) args1))
8229 (t (setq a (pop args))
8230 (if (string-match "%a" a)
8231 (setq a (replace-match address t t a)))
8232 (if (string-match "%s" a)
8233 (setq a (replace-match subject t t a)))
8234 (push a args1))))
8235 (apply cmd (nreverse args1))))
8237 ((member type '("http" "https" "ftp" "news"))
8238 (browse-url (concat type ":" (org-link-escape
8239 path org-link-escape-chars-browser))))
8241 ((member type '("message"))
8242 (browse-url (concat type ":" path)))
8244 ((string= type "tags")
8245 (org-tags-view in-emacs path))
8246 ((string= type "thisfile")
8247 (if in-emacs
8248 (switch-to-buffer-other-window
8249 (org-get-buffer-for-internal-link (current-buffer)))
8250 (org-mark-ring-push))
8251 (let ((cmd `(org-link-search
8252 ,path
8253 ,(cond ((equal in-emacs '(4)) 'occur)
8254 ((equal in-emacs '(16)) 'org-occur)
8255 (t nil))
8256 ,pos)))
8257 (condition-case nil (eval cmd)
8258 (error (progn (widen) (eval cmd))))))
8260 ((string= type "tree-match")
8261 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8263 ((string= type "file")
8264 (if (string-match "::\\([0-9]+\\)\\'" path)
8265 (setq line (string-to-number (match-string 1 path))
8266 path (substring path 0 (match-beginning 0)))
8267 (if (string-match "::\\(.+\\)\\'" path)
8268 (setq search (match-string 1 path)
8269 path (substring path 0 (match-beginning 0)))))
8270 (if (string-match "[*?{]" (file-name-nondirectory path))
8271 (dired path)
8272 (org-open-file path in-emacs line search)))
8274 ((string= type "news")
8275 (require 'org-gnus)
8276 (org-gnus-follow-link path))
8278 ((string= type "shell")
8279 (let ((cmd path))
8280 (if (or (not org-confirm-shell-link-function)
8281 (funcall org-confirm-shell-link-function
8282 (format "Execute \"%s\" in shell? "
8283 (org-add-props cmd nil
8284 'face 'org-warning))))
8285 (progn
8286 (message "Executing %s" cmd)
8287 (shell-command cmd))
8288 (error "Abort"))))
8290 ((string= type "elisp")
8291 (let ((cmd path))
8292 (if (or (not org-confirm-elisp-link-function)
8293 (funcall org-confirm-elisp-link-function
8294 (format "Execute \"%s\" as elisp? "
8295 (org-add-props cmd nil
8296 'face 'org-warning))))
8297 (message "%s => %s" cmd
8298 (if (equal (string-to-char cmd) ?\()
8299 (eval (read cmd))
8300 (call-interactively (read cmd))))
8301 (error "Abort"))))
8304 (browse-url-at-point)))))))
8305 (move-marker org-open-link-marker nil)
8306 (run-hook-with-args 'org-follow-link-hook))
8308 (defun org-offer-links-in-entry (&optional nth zero)
8309 "Offer links in the curren entry and follow the selected link.
8310 If there is only one link, follow it immediately as well.
8311 If NTH is an integer, immediately pick the NTH link found.
8312 If ZERO is a string, check also this string for a link, and if
8313 there is one, offer it as link number zero."
8314 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8315 "\\(" org-angle-link-re "\\)\\|"
8316 "\\(" org-plain-link-re "\\)"))
8317 (cnt ?0)
8318 (in-emacs (if (integerp nth) nil nth))
8319 have-zero end links link c)
8320 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8321 (push (match-string 0 zero) links)
8322 (setq cnt (1- cnt) have-zero t))
8323 (save-excursion
8324 (org-back-to-heading t)
8325 (setq end (save-excursion (outline-next-heading) (point)))
8326 (while (re-search-forward re end t)
8327 (push (match-string 0) links))
8328 (setq links (org-uniquify (reverse links))))
8330 (cond
8331 ((null links)
8332 (message "No links"))
8333 ((equal (length links) 1)
8334 (setq link (car links)))
8335 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8336 (setq link (nth (if have-zero nth (1- nth)) links)))
8337 (t ; we have to select a link
8338 (save-excursion
8339 (save-window-excursion
8340 (delete-other-windows)
8341 (with-output-to-temp-buffer "*Select Link*"
8342 (mapc (lambda (l)
8343 (if (not (string-match org-bracket-link-regexp l))
8344 (princ (format "[%c] %s\n" (incf cnt)
8345 (org-remove-angle-brackets l)))
8346 (if (match-end 3)
8347 (princ (format "[%c] %s (%s)\n" (incf cnt)
8348 (match-string 3 l) (match-string 1 l)))
8349 (princ (format "[%c] %s\n" (incf cnt)
8350 (match-string 1 l))))))
8351 links))
8352 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8353 (message "Select link to open:")
8354 (setq c (read-char-exclusive))
8355 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8356 (when (equal c ?q) (error "Abort"))
8357 (setq nth (- c ?0))
8358 (if have-zero (setq nth (1+ nth)))
8359 (unless (and (integerp nth) (>= (length links) nth))
8360 (error "Invalid link selection"))
8361 (setq link (nth (1- nth) links))))
8362 (if link
8363 (progn (org-open-link-from-string link in-emacs (current-buffer)) t)
8364 nil)))
8366 ;;;; Time estimates
8368 (defun org-get-effort (&optional pom)
8369 "Get the effort estimate for the current entry."
8370 (org-entry-get pom org-effort-property))
8372 ;;; File search
8374 (defvar org-create-file-search-functions nil
8375 "List of functions to construct the right search string for a file link.
8376 These functions are called in turn with point at the location to
8377 which the link should point.
8379 A function in the hook should first test if it would like to
8380 handle this file type, for example by checking the major-mode or
8381 the file extension. If it decides not to handle this file, it
8382 should just return nil to give other functions a chance. If it
8383 does handle the file, it must return the search string to be used
8384 when following the link. The search string will be part of the
8385 file link, given after a double colon, and `org-open-at-point'
8386 will automatically search for it. If special measures must be
8387 taken to make the search successful, another function should be
8388 added to the companion hook `org-execute-file-search-functions',
8389 which see.
8391 A function in this hook may also use `setq' to set the variable
8392 `description' to provide a suggestion for the descriptive text to
8393 be used for this link when it gets inserted into an Org-mode
8394 buffer with \\[org-insert-link].")
8396 (defvar org-execute-file-search-functions nil
8397 "List of functions to execute a file search triggered by a link.
8399 Functions added to this hook must accept a single argument, the
8400 search string that was part of the file link, the part after the
8401 double colon. The function must first check if it would like to
8402 handle this search, for example by checking the major-mode or the
8403 file extension. If it decides not to handle this search, it
8404 should just return nil to give other functions a chance. If it
8405 does handle the search, it must return a non-nil value to keep
8406 other functions from trying.
8408 Each function can access the current prefix argument through the
8409 variable `current-prefix-argument'. Note that a single prefix is
8410 used to force opening a link in Emacs, so it may be good to only
8411 use a numeric or double prefix to guide the search function.
8413 In case this is needed, a function in this hook can also restore
8414 the window configuration before `org-open-at-point' was called using:
8416 (set-window-configuration org-window-config-before-follow-link)")
8418 (defun org-link-search (s &optional type avoid-pos)
8419 "Search for a link search option.
8420 If S is surrounded by forward slashes, it is interpreted as a
8421 regular expression. In org-mode files, this will create an `org-occur'
8422 sparse tree. In ordinary files, `occur' will be used to list matches.
8423 If the current buffer is in `dired-mode', grep will be used to search
8424 in all files. If AVOID-POS is given, ignore matches near that position."
8425 (let ((case-fold-search t)
8426 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8427 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8428 (append '(("") (" ") ("\t") ("\n"))
8429 org-emphasis-alist)
8430 "\\|") "\\)"))
8431 (pos (point))
8432 (pre nil) (post nil)
8433 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8434 (cond
8435 ;; First check if there are any special
8436 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8437 ;; Now try the builtin stuff
8438 ((and (equal (string-to-char s0) ?#)
8439 (> (length s0) 1)
8440 (save-excursion
8441 (goto-char (point-min))
8442 (and
8443 (re-search-forward
8444 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8445 (setq type 'dedicated
8446 pos (match-beginning 0))))
8447 ;; There is an exact target for this
8448 (goto-char pos)
8449 (org-back-to-heading t)))
8450 ((save-excursion
8451 (goto-char (point-min))
8452 (and
8453 (re-search-forward
8454 (concat "<<" (regexp-quote s0) ">>") nil t)
8455 (setq type 'dedicated
8456 pos (match-beginning 0))))
8457 ;; There is an exact target for this
8458 (goto-char pos))
8459 ((and (string-match "^(\\(.*\\))$" s0)
8460 (save-excursion
8461 (goto-char (point-min))
8462 (and
8463 (re-search-forward
8464 (concat "[^[]" (regexp-quote
8465 (format org-coderef-label-format
8466 (match-string 1 s0))))
8467 nil t)
8468 (setq type 'dedicated
8469 pos (1+ (match-beginning 0))))))
8470 ;; There is a coderef target for this
8471 (goto-char pos))
8472 ((string-match "^/\\(.*\\)/$" s)
8473 ;; A regular expression
8474 (cond
8475 ((org-mode-p)
8476 (org-occur (match-string 1 s)))
8477 ;;((eq major-mode 'dired-mode)
8478 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8479 (t (org-do-occur (match-string 1 s)))))
8481 ;; A normal search strings
8482 (when (equal (string-to-char s) ?*)
8483 ;; Anchor on headlines, post may include tags.
8484 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8485 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8486 s (substring s 1)))
8487 (remove-text-properties
8488 0 (length s)
8489 '(face nil mouse-face nil keymap nil fontified nil) s)
8490 ;; Make a series of regular expressions to find a match
8491 (setq words (org-split-string s "[ \n\r\t]+")
8493 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8494 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8495 "\\)" markers)
8496 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8497 re2a (concat "[ \t\r\n]" re2a_)
8498 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8499 re4 (concat "[^a-zA-Z_]" re4_)
8501 re1 (concat pre re2 post)
8502 re3 (concat pre (if pre re4_ re4) post)
8503 re5 (concat pre ".*" re4)
8504 re2 (concat pre re2)
8505 re2a (concat pre (if pre re2a_ re2a))
8506 re4 (concat pre (if pre re4_ re4))
8507 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8508 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8509 re5 "\\)"
8511 (cond
8512 ((eq type 'org-occur) (org-occur reall))
8513 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8514 (t (goto-char (point-min))
8515 (setq type 'fuzzy)
8516 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8517 (org-search-not-self 1 re1 nil t)
8518 (org-search-not-self 1 re2 nil t)
8519 (org-search-not-self 1 re2a nil t)
8520 (org-search-not-self 1 re3 nil t)
8521 (org-search-not-self 1 re4 nil t)
8522 (org-search-not-self 1 re5 nil t)
8524 (goto-char (match-beginning 1))
8525 (goto-char pos)
8526 (error "No match")))))
8528 ;; Normal string-search
8529 (goto-char (point-min))
8530 (if (search-forward s nil t)
8531 (goto-char (match-beginning 0))
8532 (error "No match"))))
8533 (and (org-mode-p) (org-show-context 'link-search))
8534 type))
8536 (defun org-search-not-self (group &rest args)
8537 "Execute `re-search-forward', but only accept matches that do not
8538 enclose the position of `org-open-link-marker'."
8539 (let ((m org-open-link-marker))
8540 (catch 'exit
8541 (while (apply 're-search-forward args)
8542 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8543 (goto-char (match-end group))
8544 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8545 (> (match-beginning 0) (marker-position m))
8546 (< (match-end 0) (marker-position m)))
8547 (save-match-data
8548 (or (not (org-in-regexp
8549 org-bracket-link-analytic-regexp 1))
8550 (not (match-end 4)) ; no description
8551 (and (<= (match-beginning 4) (point))
8552 (>= (match-end 4) (point))))))
8553 (throw 'exit (point))))))))
8555 (defun org-get-buffer-for-internal-link (buffer)
8556 "Return a buffer to be used for displaying the link target of internal links."
8557 (cond
8558 ((not org-display-internal-link-with-indirect-buffer)
8559 buffer)
8560 ((string-match "(Clone)$" (buffer-name buffer))
8561 (message "Buffer is already a clone, not making another one")
8562 ;; we also do not modify visibility in this case
8563 buffer)
8564 (t ; make a new indirect buffer for displaying the link
8565 (let* ((bn (buffer-name buffer))
8566 (ibn (concat bn "(Clone)"))
8567 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8568 (with-current-buffer ib (org-overview))
8569 ib))))
8571 (defun org-do-occur (regexp &optional cleanup)
8572 "Call the Emacs command `occur'.
8573 If CLEANUP is non-nil, remove the printout of the regular expression
8574 in the *Occur* buffer. This is useful if the regex is long and not useful
8575 to read."
8576 (occur regexp)
8577 (when cleanup
8578 (let ((cwin (selected-window)) win beg end)
8579 (when (setq win (get-buffer-window "*Occur*"))
8580 (select-window win))
8581 (goto-char (point-min))
8582 (when (re-search-forward "match[a-z]+" nil t)
8583 (setq beg (match-end 0))
8584 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8585 (setq end (1- (match-beginning 0)))))
8586 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8587 (goto-char (point-min))
8588 (select-window cwin))))
8590 ;;; The mark ring for links jumps
8592 (defvar org-mark-ring nil
8593 "Mark ring for positions before jumps in Org-mode.")
8594 (defvar org-mark-ring-last-goto nil
8595 "Last position in the mark ring used to go back.")
8596 ;; Fill and close the ring
8597 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8598 (loop for i from 1 to org-mark-ring-length do
8599 (push (make-marker) org-mark-ring))
8600 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8601 org-mark-ring)
8603 (defun org-mark-ring-push (&optional pos buffer)
8604 "Put the current position or POS into the mark ring and rotate it."
8605 (interactive)
8606 (setq pos (or pos (point)))
8607 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8608 (move-marker (car org-mark-ring)
8609 (or pos (point))
8610 (or buffer (current-buffer)))
8611 (message "%s"
8612 (substitute-command-keys
8613 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8615 (defun org-mark-ring-goto (&optional n)
8616 "Jump to the previous position in the mark ring.
8617 With prefix arg N, jump back that many stored positions. When
8618 called several times in succession, walk through the entire ring.
8619 Org-mode commands jumping to a different position in the current file,
8620 or to another Org-mode file, automatically push the old position
8621 onto the ring."
8622 (interactive "p")
8623 (let (p m)
8624 (if (eq last-command this-command)
8625 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8626 (setq p org-mark-ring))
8627 (setq org-mark-ring-last-goto p)
8628 (setq m (car p))
8629 (switch-to-buffer (marker-buffer m))
8630 (goto-char m)
8631 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8633 (defun org-remove-angle-brackets (s)
8634 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8635 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8637 (defun org-add-angle-brackets (s)
8638 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8639 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8641 (defun org-remove-double-quotes (s)
8642 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8643 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8646 ;;; Following specific links
8648 (defun org-follow-timestamp-link ()
8649 (cond
8650 ((org-at-date-range-p t)
8651 (let ((org-agenda-start-on-weekday)
8652 (t1 (match-string 1))
8653 (t2 (match-string 2)))
8654 (setq t1 (time-to-days (org-time-string-to-time t1))
8655 t2 (time-to-days (org-time-string-to-time t2)))
8656 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8657 ((org-at-timestamp-p t)
8658 (org-agenda-list nil (time-to-days (org-time-string-to-time
8659 (substring (match-string 1) 0 10)))
8661 (t (error "This should not happen"))))
8664 ;;; Following file links
8665 (defvar org-wait nil)
8666 (defun org-open-file (path &optional in-emacs line search)
8667 "Open the file at PATH.
8668 First, this expands any special file name abbreviations. Then the
8669 configuration variable `org-file-apps' is checked if it contains an
8670 entry for this file type, and if yes, the corresponding command is launched.
8672 If no application is found, Emacs simply visits the file.
8674 With optional prefix argument IN-EMACS, Emacs will visit the file.
8675 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8676 and o use an external application to visit the file.
8678 Optional LINE specifies a line to go to, optional SEARCH a string to
8679 search for. If LINE or SEARCH is given, the file will always be
8680 opened in Emacs.
8681 If the file does not exist, an error is thrown."
8682 (setq in-emacs (or in-emacs line search))
8683 (let* ((file (if (equal path "")
8684 buffer-file-name
8685 (substitute-in-file-name (expand-file-name path))))
8686 (apps (append org-file-apps (org-default-apps)))
8687 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8688 (dirp (if remp nil (file-directory-p file)))
8689 (file (if (and dirp org-open-directory-means-index-dot-org)
8690 (concat (file-name-as-directory file) "index.org")
8691 file))
8692 (a-m-a-p (assq 'auto-mode apps))
8693 (dfile (downcase file))
8694 (old-buffer (current-buffer))
8695 (old-pos (point))
8696 (old-mode major-mode)
8697 ext cmd)
8698 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8699 (setq ext (match-string 1 dfile))
8700 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8701 (setq ext (match-string 1 dfile))))
8702 (cond
8703 ((equal in-emacs '(16))
8704 (setq cmd (cdr (assoc 'system apps))))
8705 (in-emacs (setq cmd 'emacs))
8707 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8708 (and dirp (cdr (assoc 'directory apps)))
8709 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8710 'string-match)
8711 (cdr (assoc ext apps))
8712 (cdr (assoc t apps))))))
8713 (when (eq cmd 'system)
8714 (setq cmd (cdr (assoc 'system apps))))
8715 (when (eq cmd 'default)
8716 (setq cmd (cdr (assoc t apps))))
8717 (when (eq cmd 'mailcap)
8718 (require 'mailcap)
8719 (mailcap-parse-mailcaps)
8720 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8721 (command (mailcap-mime-info mime-type)))
8722 (if (stringp command)
8723 (setq cmd command)
8724 (setq cmd 'emacs))))
8725 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8726 (not (file-exists-p file))
8727 (not org-open-non-existing-files))
8728 (error "No such file: %s" file))
8729 (cond
8730 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8731 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8732 (while (string-match "['\"]%s['\"]" cmd)
8733 (setq cmd (replace-match "%s" t t cmd)))
8734 (while (string-match "%s" cmd)
8735 (setq cmd (replace-match
8736 (save-match-data
8737 (shell-quote-argument
8738 (convert-standard-filename file)))
8739 t t cmd)))
8740 (save-window-excursion
8741 (start-process-shell-command cmd nil cmd)
8742 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8744 ((or (stringp cmd)
8745 (eq cmd 'emacs))
8746 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8747 (widen)
8748 (if line (org-goto-line line)
8749 (if search (org-link-search search))))
8750 ((consp cmd)
8751 (let ((file (convert-standard-filename file)))
8752 (eval cmd)))
8753 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8754 (and (org-mode-p) (eq old-mode 'org-mode)
8755 (or (not (equal old-buffer (current-buffer)))
8756 (not (equal old-pos (point))))
8757 (org-mark-ring-push old-pos old-buffer))))
8759 (defun org-default-apps ()
8760 "Return the default applications for this operating system."
8761 (cond
8762 ((eq system-type 'darwin)
8763 org-file-apps-defaults-macosx)
8764 ((eq system-type 'windows-nt)
8765 org-file-apps-defaults-windowsnt)
8766 (t org-file-apps-defaults-gnu)))
8768 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8769 "Convert extensions to regular expressions in the cars of LIST.
8770 Also, weed out any non-string entries, because the return value is used
8771 only for regexp matching.
8772 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8773 point to the symbol `emacs', indicating that the file should
8774 be opened in Emacs."
8775 (append
8776 (delq nil
8777 (mapcar (lambda (x)
8778 (if (not (stringp (car x)))
8780 (if (string-match "\\W" (car x))
8782 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8783 list))
8784 (if add-auto-mode
8785 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8787 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8788 (defun org-file-remote-p (file)
8789 "Test whether FILE specifies a location on a remote system.
8790 Return non-nil if the location is indeed remote.
8792 For example, the filename \"/user@host:/foo\" specifies a location
8793 on the system \"/user@host:\"."
8794 (cond ((fboundp 'file-remote-p)
8795 (file-remote-p file))
8796 ((fboundp 'tramp-handle-file-remote-p)
8797 (tramp-handle-file-remote-p file))
8798 ((and (boundp 'ange-ftp-name-format)
8799 (string-match (car ange-ftp-name-format) file))
8801 (t nil)))
8804 ;;;; Refiling
8806 (defun org-get-org-file ()
8807 "Read a filename, with default directory `org-directory'."
8808 (let ((default (or org-default-notes-file remember-data-file)))
8809 (read-file-name (format "File name [%s]: " default)
8810 (file-name-as-directory org-directory)
8811 default)))
8813 (defun org-notes-order-reversed-p ()
8814 "Check if the current file should receive notes in reversed order."
8815 (cond
8816 ((not org-reverse-note-order) nil)
8817 ((eq t org-reverse-note-order) t)
8818 ((not (listp org-reverse-note-order)) nil)
8819 (t (catch 'exit
8820 (let ((all org-reverse-note-order)
8821 entry)
8822 (while (setq entry (pop all))
8823 (if (string-match (car entry) buffer-file-name)
8824 (throw 'exit (cdr entry))))
8825 nil)))))
8827 (defvar org-refile-target-table nil
8828 "The list of refile targets, created by `org-refile'.")
8830 (defvar org-agenda-new-buffers nil
8831 "Buffers created to visit agenda files.")
8833 (defun org-get-refile-targets (&optional default-buffer)
8834 "Produce a table with refile targets."
8835 (let ((case-fold-search nil)
8836 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8837 (entries (or org-refile-targets '((nil . (:level . 1)))))
8838 targets txt re files f desc descre fast-path-p level pos0)
8839 (message "Getting targets...")
8840 (with-current-buffer (or default-buffer (current-buffer))
8841 (while (setq entry (pop entries))
8842 (setq files (car entry) desc (cdr entry))
8843 (setq fast-path-p nil)
8844 (cond
8845 ((null files) (setq files (list (current-buffer))))
8846 ((eq files 'org-agenda-files)
8847 (setq files (org-agenda-files 'unrestricted)))
8848 ((and (symbolp files) (fboundp files))
8849 (setq files (funcall files)))
8850 ((and (symbolp files) (boundp files))
8851 (setq files (symbol-value files))))
8852 (if (stringp files) (setq files (list files)))
8853 (cond
8854 ((eq (car desc) :tag)
8855 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8856 ((eq (car desc) :todo)
8857 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8858 ((eq (car desc) :regexp)
8859 (setq descre (cdr desc)))
8860 ((eq (car desc) :level)
8861 (setq descre (concat "^\\*\\{" (number-to-string
8862 (if org-odd-levels-only
8863 (1- (* 2 (cdr desc)))
8864 (cdr desc)))
8865 "\\}[ \t]")))
8866 ((eq (car desc) :maxlevel)
8867 (setq fast-path-p t)
8868 (setq descre (concat "^\\*\\{1," (number-to-string
8869 (if org-odd-levels-only
8870 (1- (* 2 (cdr desc)))
8871 (cdr desc)))
8872 "\\}[ \t]")))
8873 (t (error "Bad refiling target description %s" desc)))
8874 (while (setq f (pop files))
8875 (with-current-buffer
8876 (if (bufferp f) f (org-get-agenda-file-buffer f))
8877 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8878 (setq f (expand-file-name f))
8879 (if (eq org-refile-use-outline-path 'file)
8880 (push (list (file-name-nondirectory f) f nil nil) targets))
8881 (save-excursion
8882 (save-restriction
8883 (widen)
8884 (goto-char (point-min))
8885 (while (re-search-forward descre nil t)
8886 (goto-char (setq pos0 (point-at-bol)))
8887 (catch 'next
8888 (when org-refile-target-verify-function
8889 (save-match-data
8890 (or (funcall org-refile-target-verify-function)
8891 (throw 'next t))))
8892 (when (looking-at org-complex-heading-regexp)
8893 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8894 txt (org-link-display-format (match-string 4))
8895 re (concat "^" (regexp-quote
8896 (buffer-substring (match-beginning 1)
8897 (match-end 4)))))
8898 (if (match-end 5) (setq re (concat re "[ \t]+"
8899 (regexp-quote
8900 (match-string 5)))))
8901 (setq re (concat re "[ \t]*$"))
8902 (when org-refile-use-outline-path
8903 (setq txt (mapconcat 'org-protect-slash
8904 (append
8905 (if (eq org-refile-use-outline-path 'file)
8906 (list (file-name-nondirectory
8907 (buffer-file-name (buffer-base-buffer))))
8908 (if (eq org-refile-use-outline-path 'full-file-path)
8909 (list (buffer-file-name (buffer-base-buffer)))))
8910 (org-get-outline-path fast-path-p level txt)
8911 (list txt))
8912 "/")))
8913 (push (list txt f re (point)) targets)))
8914 (when (= (point) pos0)
8915 ;; verification function has not moved point
8916 (goto-char (point-at-eol))))))))))
8917 (message "Getting targets...done")
8918 (nreverse targets)))
8920 (defun org-protect-slash (s)
8921 (while (string-match "/" s)
8922 (setq s (replace-match "\\" t t s)))
8925 (defvar org-olpa (make-vector 20 nil))
8927 (defun org-get-outline-path (&optional fastp level heading)
8928 "Return the outline path to the current entry, as a list."
8929 (if fastp
8930 (progn
8931 (if (> level 19)
8932 (error "Outline path failure, more than 19 levels."))
8933 (loop for i from level upto 19 do
8934 (aset org-olpa i nil))
8935 (prog1
8936 (delq nil (append org-olpa nil))
8937 (aset org-olpa level heading)))
8938 (let (rtn)
8939 (save-excursion
8940 (while (org-up-heading-safe)
8941 (when (looking-at org-complex-heading-regexp)
8942 (push (org-match-string-no-properties 4) rtn)))
8943 rtn))))
8945 (defvar org-refile-history nil
8946 "History for refiling operations.")
8948 (defvar org-after-refile-insert-hook nil
8949 "Hook run after `org-refile' has inserted its stuff at the new location.
8950 Note that this is still *before* the stuff will be removed from
8951 the *old* location.")
8953 (defun org-refile (&optional goto default-buffer rfloc)
8954 "Move the entry at point to another heading.
8955 The list of target headings is compiled using the information in
8956 `org-refile-targets', which see. This list is created before each use
8957 and will therefore always be up-to-date.
8959 At the target location, the entry is filed as a subitem of the target heading.
8960 Depending on `org-reverse-note-order', the new subitem will either be the
8961 first or the last subitem.
8963 If there is an active region, all entries in that region will be moved.
8964 However, the region must fulfil the requirement that the first heading
8965 is the first one sets the top-level of the moved text - at most siblings
8966 below it are allowed.
8968 With prefix arg GOTO, the command will only visit the target location,
8969 not actually move anything.
8970 With a double prefix `C-u C-u', go to the location where the last refiling
8971 operation has put the subtree.
8972 With a prefix argument of `2', refile to the running clock.
8974 RFLOC can be a refile location obtained in a different way.
8976 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8977 (interactive "P")
8978 (let* ((cbuf (current-buffer))
8979 (regionp (org-region-active-p))
8980 (region-start (and regionp (region-beginning)))
8981 (region-end (and regionp (region-end)))
8982 (region-length (and regionp (- region-end region-start)))
8983 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8984 pos it nbuf file re level reversed)
8985 (when regionp
8986 (goto-char region-start)
8987 (or (bolp) (goto-char (point-at-bol)))
8988 (setq region-start (point))
8989 (unless (org-kill-is-subtree-p
8990 (buffer-substring region-start region-end))
8991 (error "The region is not a (sequence of) subtree(s)")))
8992 (if (equal goto '(16))
8993 (org-refile-goto-last-stored)
8994 (when (or
8995 (and (equal goto 2)
8996 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
8997 (prog1
8998 (setq it (list (or org-clock-heading "running clock")
8999 (buffer-file-name
9000 (marker-buffer org-clock-hd-marker))
9002 (marker-position org-clock-hd-marker)))
9003 (setq goto nil)))
9004 (setq it (or rfloc
9005 (save-excursion
9006 (org-refile-get-location
9007 (if goto "Goto: " "Refile to: ") default-buffer
9008 org-refile-allow-creating-parent-nodes)))))
9009 (setq file (nth 1 it)
9010 re (nth 2 it)
9011 pos (nth 3 it))
9012 (if (and (not goto)
9014 (equal (buffer-file-name) file)
9015 (if regionp
9016 (and (>= pos region-start)
9017 (<= pos region-end))
9018 (and (>= pos (point))
9019 (< pos (save-excursion
9020 (org-end-of-subtree t t))))))
9021 (error "Cannot refile to position inside the tree or region"))
9023 (setq nbuf (or (find-buffer-visiting file)
9024 (find-file-noselect file)))
9025 (if goto
9026 (progn
9027 (switch-to-buffer nbuf)
9028 (goto-char pos)
9029 (org-show-context 'org-goto))
9030 (if regionp
9031 (progn
9032 (org-kill-new (buffer-substring region-start region-end))
9033 (org-save-markers-in-region region-start region-end))
9034 (org-copy-subtree 1 nil t))
9035 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9036 (find-file-noselect file)))
9037 (setq reversed (org-notes-order-reversed-p))
9038 (save-excursion
9039 (save-restriction
9040 (widen)
9041 (if pos
9042 (progn
9043 (goto-char pos)
9044 (looking-at outline-regexp)
9045 (setq level (org-get-valid-level (funcall outline-level) 1))
9046 (goto-char
9047 (if reversed
9048 (or (outline-next-heading) (point-max))
9049 (or (save-excursion (org-get-next-sibling))
9050 (org-end-of-subtree t t)
9051 (point-max)))))
9052 (setq level 1)
9053 (if (not reversed)
9054 (goto-char (point-max))
9055 (goto-char (point-min))
9056 (or (outline-next-heading) (goto-char (point-max)))))
9057 (if (not (bolp)) (newline))
9058 (bookmark-set "org-refile-last-stored")
9059 (org-paste-subtree level)
9060 (if (fboundp 'deactivate-mark) (deactivate-mark))
9061 (run-hooks 'org-after-refile-insert-hook))))
9062 (if regionp
9063 (delete-region (point) (+ (point) region-length))
9064 (org-cut-subtree))
9065 (when (featurep 'org-inlinetask)
9066 (org-inlinetask-remove-END-maybe))
9067 (setq org-markers-to-move nil)
9068 (message "Refiled to \"%s\"" (car it))))))
9069 (org-reveal))
9071 (defun org-refile-goto-last-stored ()
9072 "Go to the location where the last refile was stored."
9073 (interactive)
9074 (bookmark-jump "org-refile-last-stored")
9075 (message "This is the location of the last refile"))
9077 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9078 "Prompt the user for a refile location, using PROMPT."
9079 (let ((org-refile-targets org-refile-targets)
9080 (org-refile-use-outline-path org-refile-use-outline-path))
9081 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9082 (unless org-refile-target-table
9083 (error "No refile targets"))
9084 (let* ((cbuf (current-buffer))
9085 (partial-completion-mode nil)
9086 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9087 (cfunc (if (and org-refile-use-outline-path
9088 org-outline-path-complete-in-steps)
9089 'org-olpath-completing-read
9090 'org-icompleting-read))
9091 (extra (if org-refile-use-outline-path "/" ""))
9092 (filename (and cfn (expand-file-name cfn)))
9093 (tbl (mapcar
9094 (lambda (x)
9095 (if (and (not (member org-refile-use-outline-path
9096 '(file full-file-path)))
9097 (not (equal filename (nth 1 x))))
9098 (cons (concat (car x) extra " ("
9099 (file-name-nondirectory (nth 1 x)) ")")
9100 (cdr x))
9101 (cons (concat (car x) extra) (cdr x))))
9102 org-refile-target-table))
9103 (completion-ignore-case t)
9104 pa answ parent-target child parent old-hist)
9105 (setq old-hist org-refile-history)
9106 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9107 nil 'org-refile-history))
9108 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9109 (if pa
9110 (progn
9111 (when (or (not org-refile-history)
9112 (not (eq old-hist org-refile-history))
9113 (not (equal (car pa) (car org-refile-history))))
9114 (setq org-refile-history
9115 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9116 org-refile-history
9117 (cdr org-refile-history))))
9118 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9119 (pop org-refile-history)))
9121 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9122 (setq parent (match-string 1 answ)
9123 child (match-string 2 answ))
9124 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
9125 (when (and parent-target
9126 (or (eq new-nodes t)
9127 (and (eq new-nodes 'confirm)
9128 (y-or-n-p (format "Create new node \"%s\"? " child)))))
9129 (org-refile-new-child parent-target child))))))
9131 (defun org-refile-new-child (parent-target child)
9132 "Use refile target PARENT-TARGET to add new CHILD below it."
9133 (unless parent-target
9134 (error "Cannot find parent for new node"))
9135 (let ((file (nth 1 parent-target))
9136 (pos (nth 3 parent-target))
9137 level)
9138 (with-current-buffer (or (find-buffer-visiting file)
9139 (find-file-noselect file))
9140 (save-excursion
9141 (save-restriction
9142 (widen)
9143 (if pos
9144 (goto-char pos)
9145 (goto-char (point-max))
9146 (if (not (bolp)) (newline)))
9147 (when (looking-at outline-regexp)
9148 (setq level (funcall outline-level))
9149 (org-end-of-subtree t t))
9150 (org-back-over-empty-lines)
9151 (insert "\n" (make-string
9152 (if pos (org-get-valid-level level 1) 1) ?*)
9153 " " child "\n")
9154 (beginning-of-line 0)
9155 (list (concat (car parent-target) "/" child) file "" (point)))))))
9157 (defun org-olpath-completing-read (prompt collection &rest args)
9158 "Read an outline path like a file name."
9159 (let ((thetable collection)
9160 (org-completion-use-ido nil) ; does not work with ido.
9161 (org-completion-use-iswitchb nil)) ; or iswitchb
9162 (apply
9163 'org-icompleting-read prompt
9164 (lambda (string predicate &optional flag)
9165 (let (rtn r f (l (length string)))
9166 (cond
9167 ((eq flag nil)
9168 ;; try completion
9169 (try-completion string thetable))
9170 ((eq flag t)
9171 ;; all-completions
9172 (setq rtn (all-completions string thetable predicate))
9173 (mapcar
9174 (lambda (x)
9175 (setq r (substring x l))
9176 (if (string-match " ([^)]*)$" x)
9177 (setq f (match-string 0 x))
9178 (setq f ""))
9179 (if (string-match "/" r)
9180 (concat string (substring r 0 (match-end 0)) f)
9182 rtn))
9183 ((eq flag 'lambda)
9184 ;; exact match?
9185 (assoc string thetable)))
9187 args)))
9189 ;;;; Dynamic blocks
9191 (defun org-find-dblock (name)
9192 "Find the first dynamic block with name NAME in the buffer.
9193 If not found, stay at current position and return nil."
9194 (let (pos)
9195 (save-excursion
9196 (goto-char (point-min))
9197 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9198 nil t)
9199 (match-beginning 0))))
9200 (if pos (goto-char pos))
9201 pos))
9203 (defconst org-dblock-start-re
9204 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9205 "Matches the startline of a dynamic block, with parameters.")
9207 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9208 "Matches the end of a dynamic block.")
9210 (defun org-create-dblock (plist)
9211 "Create a dynamic block section, with parameters taken from PLIST.
9212 PLIST must contain a :name entry which is used as name of the block."
9213 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9214 (end-of-line 1)
9215 (newline))
9216 (let ((col (current-column))
9217 (name (plist-get plist :name)))
9218 (insert "#+BEGIN: " name)
9219 (while plist
9220 (if (eq (car plist) :name)
9221 (setq plist (cddr plist))
9222 (insert " " (prin1-to-string (pop plist)))))
9223 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9224 (beginning-of-line -2)))
9226 (defun org-prepare-dblock ()
9227 "Prepare dynamic block for refresh.
9228 This empties the block, puts the cursor at the insert position and returns
9229 the property list including an extra property :name with the block name."
9230 (unless (looking-at org-dblock-start-re)
9231 (error "Not at a dynamic block"))
9232 (let* ((begdel (1+ (match-end 0)))
9233 (name (org-no-properties (match-string 1)))
9234 (params (append (list :name name)
9235 (read (concat "(" (match-string 3) ")")))))
9236 (save-excursion
9237 (beginning-of-line 1)
9238 (skip-chars-forward " \t")
9239 (setq params (plist-put params :indentation-column (current-column))))
9240 (unless (re-search-forward org-dblock-end-re nil t)
9241 (error "Dynamic block not terminated"))
9242 (setq params
9243 (append params
9244 (list :content (buffer-substring
9245 begdel (match-beginning 0)))))
9246 (delete-region begdel (match-beginning 0))
9247 (goto-char begdel)
9248 (open-line 1)
9249 params))
9251 (defun org-map-dblocks (&optional command)
9252 "Apply COMMAND to all dynamic blocks in the current buffer.
9253 If COMMAND is not given, use `org-update-dblock'."
9254 (let ((cmd (or command 'org-update-dblock))
9255 pos)
9256 (save-excursion
9257 (goto-char (point-min))
9258 (while (re-search-forward org-dblock-start-re nil t)
9259 (goto-char (setq pos (match-beginning 0)))
9260 (condition-case nil
9261 (funcall cmd)
9262 (error (message "Error during update of dynamic block")))
9263 (goto-char pos)
9264 (unless (re-search-forward org-dblock-end-re nil t)
9265 (error "Dynamic block not terminated"))))))
9267 (defun org-dblock-update (&optional arg)
9268 "User command for updating dynamic blocks.
9269 Update the dynamic block at point. With prefix ARG, update all dynamic
9270 blocks in the buffer."
9271 (interactive "P")
9272 (if arg
9273 (org-update-all-dblocks)
9274 (or (looking-at org-dblock-start-re)
9275 (org-beginning-of-dblock))
9276 (org-update-dblock)))
9278 (defun org-update-dblock ()
9279 "Update the dynamic block at point
9280 This means to empty the block, parse for parameters and then call
9281 the correct writing function."
9282 (save-window-excursion
9283 (let* ((pos (point))
9284 (line (org-current-line))
9285 (params (org-prepare-dblock))
9286 (name (plist-get params :name))
9287 (indent (plist-get params :indentation-column))
9288 (cmd (intern (concat "org-dblock-write:" name))))
9289 (message "Updating dynamic block `%s' at line %d..." name line)
9290 (funcall cmd params)
9291 (message "Updating dynamic block `%s' at line %d...done" name line)
9292 (goto-char pos)
9293 (when (and indent (> indent 0))
9294 (setq indent (make-string indent ?\ ))
9295 (save-excursion
9296 (org-beginning-of-dblock)
9297 (forward-line 1)
9298 (while (not (looking-at org-dblock-end-re))
9299 (insert indent)
9300 (beginning-of-line 2))
9301 (when (looking-at org-dblock-end-re)
9302 (and (looking-at "[ \t]+")
9303 (replace-match ""))
9304 (insert indent)))))))
9306 (defun org-beginning-of-dblock ()
9307 "Find the beginning of the dynamic block at point.
9308 Error if there is no such block at point."
9309 (let ((pos (point))
9310 beg)
9311 (end-of-line 1)
9312 (if (and (re-search-backward org-dblock-start-re nil t)
9313 (setq beg (match-beginning 0))
9314 (re-search-forward org-dblock-end-re nil t)
9315 (> (match-end 0) pos))
9316 (goto-char beg)
9317 (goto-char pos)
9318 (error "Not in a dynamic block"))))
9320 (defun org-update-all-dblocks ()
9321 "Update all dynamic blocks in the buffer.
9322 This function can be used in a hook."
9323 (when (org-mode-p)
9324 (org-map-dblocks 'org-update-dblock)))
9327 ;;;; Completion
9329 (defconst org-additional-option-like-keywords
9330 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9331 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9332 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "LATEX_CLASS:" "ATTR_LaTeX"
9333 "BEGIN:" "END:"
9334 "ORGTBL" "TBLFM:" "TBLNAME:"
9335 "BEGIN_EXAMPLE" "END_EXAMPLE"
9336 "BEGIN_QUOTE" "END_QUOTE"
9337 "BEGIN_VERSE" "END_VERSE"
9338 "BEGIN_CENTER" "END_CENTER"
9339 "BEGIN_SRC" "END_SRC"
9340 "CATEGORY" "COLUMNS"
9341 "CAPTION" "LABEL"
9342 "SETUPFILE"
9343 "BIND"
9344 "MACRO"))
9346 (defcustom org-structure-template-alist
9348 ("s" "#+begin_src ?\n\n#+end_src"
9349 "<src lang=\"?\">\n\n</src>")
9350 ("e" "#+begin_example\n?\n#+end_example"
9351 "<example>\n?\n</example>")
9352 ("q" "#+begin_quote\n?\n#+end_quote"
9353 "<quote>\n?\n</quote>")
9354 ("v" "#+begin_verse\n?\n#+end_verse"
9355 "<verse>\n?\n/verse>")
9356 ("c" "#+begin_center\n?\n#+end_center"
9357 "<center>\n?\n/center>")
9358 ("l" "#+begin_latex\n?\n#+end_latex"
9359 "<literal style=\"latex\">\n?\n</literal>")
9360 ("L" "#+latex: "
9361 "<literal style=\"latex\">?</literal>")
9362 ("h" "#+begin_html\n?\n#+end_html"
9363 "<literal style=\"html\">\n?\n</literal>")
9364 ("H" "#+html: "
9365 "<literal style=\"html\">?</literal>")
9366 ("a" "#+begin_ascii\n?\n#+end_ascii")
9367 ("A" "#+ascii: ")
9368 ("i" "#+include %file ?"
9369 "<include file=%file markup=\"?\">")
9371 "Structure completion elements.
9372 This is a list of abbreviation keys and values. The value gets inserted
9373 it you type @samp{.} followed by the key and then the completion key,
9374 usually `M-TAB'. %file will be replaced by a file name after prompting
9375 for the file using completion.
9376 There are two templates for each key, the first uses the original Org syntax,
9377 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9378 the default when the /org-mtags.el/ module has been loaded. See also the
9379 variable `org-mtags-prefer-muse-templates'.
9380 This is an experimental feature, it is undecided if it is going to stay in."
9381 :group 'org-completion
9382 :type '(repeat
9383 (string :tag "Key")
9384 (string :tag "Template")
9385 (string :tag "Muse Template")))
9387 (defun org-try-structure-completion ()
9388 "Try to complete a structure template before point.
9389 This looks for strings like \"<e\" on an otherwise empty line and
9390 expands them."
9391 (let ((l (buffer-substring (point-at-bol) (point)))
9393 (when (and (looking-at "[ \t]*$")
9394 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9395 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9396 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9397 (match-beginning 1)) a)
9398 t)))
9400 (defun org-complete-expand-structure-template (start cell)
9401 "Expand a structure template."
9402 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9403 (rpl (nth (if musep 2 1) cell))
9404 (ind ""))
9405 (delete-region start (point))
9406 (when (string-match "\\`#\\+" rpl)
9407 (cond
9408 ((bolp))
9409 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9410 (setq ind (buffer-substring (point-at-bol) (point))))
9411 (t (newline))))
9412 (setq start (point))
9413 (if (string-match "%file" rpl)
9414 (setq rpl (replace-match
9415 (concat
9416 "\""
9417 (save-match-data
9418 (abbreviate-file-name (read-file-name "Include file: ")))
9419 "\"")
9420 t t rpl)))
9421 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9422 (concat "\n" ind)))
9423 (insert rpl)
9424 (if (re-search-backward "\\?" start t) (delete-char 1))))
9427 (defun org-complete (&optional arg)
9428 "Perform completion on word at point.
9429 At the beginning of a headline, this completes TODO keywords as given in
9430 `org-todo-keywords'.
9431 If the current word is preceded by a backslash, completes the TeX symbols
9432 that are supported for HTML support.
9433 If the current word is preceded by \"#+\", completes special words for
9434 setting file options.
9435 In the line after \"#+STARTUP:, complete valid keywords.\"
9436 At all other locations, this simply calls the value of
9437 `org-completion-fallback-command'."
9438 (interactive "P")
9439 (org-without-partial-completion
9440 (catch 'exit
9441 (let* ((a nil)
9442 (end (point))
9443 (beg1 (save-excursion
9444 (skip-chars-backward (org-re "[:alnum:]_@"))
9445 (point)))
9446 (beg (save-excursion
9447 (skip-chars-backward "a-zA-Z0-9_:$")
9448 (point)))
9449 (confirm (lambda (x) (stringp (car x))))
9450 (searchhead (equal (char-before beg) ?*))
9451 (struct
9452 (when (and (member (char-before beg1) '(?. ?<))
9453 (setq a (assoc (buffer-substring beg1 (point))
9454 org-structure-template-alist)))
9455 (org-complete-expand-structure-template (1- beg1) a)
9456 (throw 'exit t)))
9457 (tag (and (equal (char-before beg1) ?:)
9458 (equal (char-after (point-at-bol)) ?*)))
9459 (prop (and (equal (char-before beg1) ?:)
9460 (not (equal (char-after (point-at-bol)) ?*))))
9461 (texp (equal (char-before beg) ?\\))
9462 (link (equal (char-before beg) ?\[))
9463 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9464 beg)
9465 "#+"))
9466 (startup (string-match "^#\\+STARTUP:.*"
9467 (buffer-substring (point-at-bol) (point))))
9468 (completion-ignore-case opt)
9469 (type nil)
9470 (tbl nil)
9471 (table (cond
9472 (opt
9473 (setq type :opt)
9474 (require 'org-exp)
9475 (append
9476 (delq nil
9477 (mapcar
9478 (lambda (x)
9479 (if (string-match
9480 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9481 (cons (match-string 2 x)
9482 (match-string 1 x))))
9483 (org-split-string (org-get-current-options) "\n")))
9484 (mapcar 'list org-additional-option-like-keywords)))
9485 (startup
9486 (setq type :startup)
9487 org-startup-options)
9488 (link (append org-link-abbrev-alist-local
9489 org-link-abbrev-alist))
9490 (texp
9491 (setq type :tex)
9492 org-html-entities)
9493 ((string-match "\\`\\*+[ \t]+\\'"
9494 (buffer-substring (point-at-bol) beg))
9495 (setq type :todo)
9496 (mapcar 'list org-todo-keywords-1))
9497 (searchhead
9498 (setq type :searchhead)
9499 (save-excursion
9500 (goto-char (point-min))
9501 (while (re-search-forward org-todo-line-regexp nil t)
9502 (push (list
9503 (org-make-org-heading-search-string
9504 (match-string 3) t))
9505 tbl)))
9506 tbl)
9507 (tag (setq type :tag beg beg1)
9508 (or org-tag-alist (org-get-buffer-tags)))
9509 (prop (setq type :prop beg beg1)
9510 (mapcar 'list (org-buffer-property-keys nil t t)))
9511 (t (progn
9512 (call-interactively org-completion-fallback-command)
9513 (throw 'exit nil)))))
9514 (pattern (buffer-substring-no-properties beg end))
9515 (completion (try-completion pattern table confirm)))
9516 (cond ((eq completion t)
9517 (if (not (assoc (upcase pattern) table))
9518 (message "Already complete")
9519 (if (and (equal type :opt)
9520 (not (member (car (assoc (upcase pattern) table))
9521 org-additional-option-like-keywords)))
9522 (insert (substring (cdr (assoc (upcase pattern) table))
9523 (length pattern)))
9524 (if (memq type '(:tag :prop)) (insert ":")))))
9525 ((null completion)
9526 (message "Can't find completion for \"%s\"" pattern)
9527 (ding))
9528 ((not (string= pattern completion))
9529 (delete-region beg end)
9530 (if (string-match " +$" completion)
9531 (setq completion (replace-match "" t t completion)))
9532 (insert completion)
9533 (if (get-buffer-window "*Completions*")
9534 (delete-window (get-buffer-window "*Completions*")))
9535 (if (assoc completion table)
9536 (if (eq type :todo) (insert " ")
9537 (if (memq type '(:tag :prop)) (insert ":"))))
9538 (if (and (equal type :opt) (assoc completion table))
9539 (message "%s" (substitute-command-keys
9540 "Press \\[org-complete] again to insert example settings"))))
9542 (message "Making completion list...")
9543 (let ((list (sort (all-completions pattern table confirm)
9544 'string<)))
9545 (with-output-to-temp-buffer "*Completions*"
9546 (condition-case nil
9547 ;; Protection needed for XEmacs and emacs 21
9548 (display-completion-list list pattern)
9549 (error (display-completion-list list)))))
9550 (message "Making completion list...%s" "done")))))))
9552 ;;;; TODO, DEADLINE, Comments
9554 (defun org-toggle-comment ()
9555 "Change the COMMENT state of an entry."
9556 (interactive)
9557 (save-excursion
9558 (org-back-to-heading)
9559 (let (case-fold-search)
9560 (if (looking-at (concat outline-regexp
9561 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9562 (replace-match "" t t nil 1)
9563 (if (looking-at outline-regexp)
9564 (progn
9565 (goto-char (match-end 0))
9566 (insert org-comment-string " ")))))))
9568 (defvar org-last-todo-state-is-todo nil
9569 "This is non-nil when the last TODO state change led to a TODO state.
9570 If the last change removed the TODO tag or switched to DONE, then
9571 this is nil.")
9573 (defvar org-setting-tags nil) ; dynamically skipped
9575 (defun org-parse-local-options (string var)
9576 "Parse STRING for startup setting relevant for variable VAR."
9577 (let ((rtn (symbol-value var))
9578 e opts)
9579 (save-match-data
9580 (if (or (not string) (not (string-match "\\S-" string)))
9582 (setq opts (delq nil (mapcar (lambda (x)
9583 (setq e (assoc x org-startup-options))
9584 (if (eq (nth 1 e) var) e nil))
9585 (org-split-string string "[ \t]+"))))
9586 (if (not opts)
9588 (setq rtn nil)
9589 (while (setq e (pop opts))
9590 (if (not (nth 3 e))
9591 (setq rtn (nth 2 e))
9592 (if (not (listp rtn)) (setq rtn nil))
9593 (push (nth 2 e) rtn)))
9594 rtn)))))
9596 (defvar org-todo-setup-filter-hook nil
9597 "Hook for functions that pre-filter todo specs.
9599 Each function takes a todo spec and returns either `nil' or the spec
9600 transformed into canonical form." )
9602 (defvar org-todo-get-default-hook nil
9603 "Hook for functions that get a default item for todo.
9605 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9606 `nil' or a string to be used for the todo mark." )
9608 (defvar org-agenda-headline-snapshot-before-repeat)
9610 (defun org-todo (&optional arg)
9611 "Change the TODO state of an item.
9612 The state of an item is given by a keyword at the start of the heading,
9613 like
9614 *** TODO Write paper
9615 *** DONE Call mom
9617 The different keywords are specified in the variable `org-todo-keywords'.
9618 By default the available states are \"TODO\" and \"DONE\".
9619 So for this example: when the item starts with TODO, it is changed to DONE.
9620 When it starts with DONE, the DONE is removed. And when neither TODO nor
9621 DONE are present, add TODO at the beginning of the heading.
9623 With C-u prefix arg, use completion to determine the new state.
9624 With numeric prefix arg, switch to that state.
9625 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9626 With a tripple C-u prefix, circumvent any state blocking.
9628 For calling through lisp, arg is also interpreted in the following way:
9629 'none -> empty state
9630 \"\"(empty string) -> switch to empty state
9631 'done -> switch to DONE
9632 'nextset -> switch to the next set of keywords
9633 'previousset -> switch to the previous set of keywords
9634 \"WAITING\" -> switch to the specified keyword, but only if it
9635 really is a member of `org-todo-keywords'."
9636 (interactive "P")
9637 (if (equal arg '(16)) (setq arg 'nextset))
9638 (let ((org-blocker-hook org-blocker-hook)
9639 (case-fold-search nil))
9640 (when (equal arg '(64))
9641 (setq arg nil org-blocker-hook nil))
9642 (when (and org-blocker-hook
9643 (or org-inhibit-blocking
9644 (org-entry-get nil "NOBLOCKING")))
9645 (setq org-blocker-hook nil))
9646 (save-excursion
9647 (catch 'exit
9648 (org-back-to-heading t)
9649 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9650 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9651 (looking-at " *"))
9652 (let* ((match-data (match-data))
9653 (startpos (point-at-bol))
9654 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9655 (org-log-done org-log-done)
9656 (org-log-repeat org-log-repeat)
9657 (org-todo-log-states org-todo-log-states)
9658 (this (match-string 1))
9659 (hl-pos (match-beginning 0))
9660 (head (org-get-todo-sequence-head this))
9661 (ass (assoc head org-todo-kwd-alist))
9662 (interpret (nth 1 ass))
9663 (done-word (nth 3 ass))
9664 (final-done-word (nth 4 ass))
9665 (last-state (or this ""))
9666 (completion-ignore-case t)
9667 (member (member this org-todo-keywords-1))
9668 (tail (cdr member))
9669 (state (cond
9670 ((and org-todo-key-trigger
9671 (or (and (equal arg '(4))
9672 (eq org-use-fast-todo-selection 'prefix))
9673 (and (not arg) org-use-fast-todo-selection
9674 (not (eq org-use-fast-todo-selection
9675 'prefix)))))
9676 ;; Use fast selection
9677 (org-fast-todo-selection))
9678 ((and (equal arg '(4))
9679 (or (not org-use-fast-todo-selection)
9680 (not org-todo-key-trigger)))
9681 ;; Read a state with completion
9682 (org-icompleting-read
9683 "State: " (mapcar (lambda(x) (list x))
9684 org-todo-keywords-1)
9685 nil t))
9686 ((eq arg 'right)
9687 (if this
9688 (if tail (car tail) nil)
9689 (car org-todo-keywords-1)))
9690 ((eq arg 'left)
9691 (if (equal member org-todo-keywords-1)
9693 (if this
9694 (nth (- (length org-todo-keywords-1)
9695 (length tail) 2)
9696 org-todo-keywords-1)
9697 (org-last org-todo-keywords-1))))
9698 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9699 (setq arg nil))) ; hack to fall back to cycling
9700 (arg
9701 ;; user or caller requests a specific state
9702 (cond
9703 ((equal arg "") nil)
9704 ((eq arg 'none) nil)
9705 ((eq arg 'done) (or done-word (car org-done-keywords)))
9706 ((eq arg 'nextset)
9707 (or (car (cdr (member head org-todo-heads)))
9708 (car org-todo-heads)))
9709 ((eq arg 'previousset)
9710 (let ((org-todo-heads (reverse org-todo-heads)))
9711 (or (car (cdr (member head org-todo-heads)))
9712 (car org-todo-heads))))
9713 ((car (member arg org-todo-keywords-1)))
9714 ((stringp arg)
9715 (error "State `%s' not valid in this file" arg))
9716 ((nth (1- (prefix-numeric-value arg))
9717 org-todo-keywords-1))))
9718 ((null member) (or head (car org-todo-keywords-1)))
9719 ((equal this final-done-word) nil) ;; -> make empty
9720 ((null tail) nil) ;; -> first entry
9721 ((memq interpret '(type priority))
9722 (if (eq this-command last-command)
9723 (car tail)
9724 (if (> (length tail) 0)
9725 (or done-word (car org-done-keywords))
9726 nil)))
9728 (car tail))))
9729 (state (or
9730 (run-hook-with-args-until-success
9731 'org-todo-get-default-hook state last-state)
9732 state))
9733 (next (if state (concat " " state " ") " "))
9734 (change-plist (list :type 'todo-state-change :from this :to state
9735 :position startpos))
9736 dolog now-done-p)
9737 (when org-blocker-hook
9738 (setq org-last-todo-state-is-todo
9739 (not (member this org-done-keywords)))
9740 (unless (save-excursion
9741 (save-match-data
9742 (run-hook-with-args-until-failure
9743 'org-blocker-hook change-plist)))
9744 (if (interactive-p)
9745 (error "TODO state change from %s to %s blocked" this state)
9746 ;; fail silently
9747 (message "TODO state change from %s to %s blocked" this state)
9748 (throw 'exit nil))))
9749 (store-match-data match-data)
9750 (replace-match next t t)
9751 (unless (pos-visible-in-window-p hl-pos)
9752 (message "TODO state changed to %s" (org-trim next)))
9753 (unless head
9754 (setq head (org-get-todo-sequence-head state)
9755 ass (assoc head org-todo-kwd-alist)
9756 interpret (nth 1 ass)
9757 done-word (nth 3 ass)
9758 final-done-word (nth 4 ass)))
9759 (when (memq arg '(nextset previousset))
9760 (message "Keyword-Set %d/%d: %s"
9761 (- (length org-todo-sets) -1
9762 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9763 (length org-todo-sets)
9764 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9765 (setq org-last-todo-state-is-todo
9766 (not (member state org-done-keywords)))
9767 (setq now-done-p (and (member state org-done-keywords)
9768 (not (member this org-done-keywords))))
9769 (and logging (org-local-logging logging))
9770 (when (and (or org-todo-log-states org-log-done)
9771 (not (eq org-inhibit-logging t))
9772 (not (memq arg '(nextset previousset))))
9773 ;; we need to look at recording a time and note
9774 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9775 (nth 2 (assoc this org-todo-log-states))))
9776 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9777 (setq dolog 'time))
9778 (when (and state
9779 (member state org-not-done-keywords)
9780 (not (member this org-not-done-keywords)))
9781 ;; This is now a todo state and was not one before
9782 ;; If there was a CLOSED time stamp, get rid of it.
9783 (org-add-planning-info nil nil 'closed))
9784 (when (and now-done-p org-log-done)
9785 ;; It is now done, and it was not done before
9786 (org-add-planning-info 'closed (org-current-time))
9787 (if (and (not dolog) (eq 'note org-log-done))
9788 (org-add-log-setup 'done state this 'findpos 'note)))
9789 (when (and state dolog)
9790 ;; This is a non-nil state, and we need to log it
9791 (org-add-log-setup 'state state this 'findpos dolog)))
9792 ;; Fixup tag positioning
9793 (org-todo-trigger-tag-changes state)
9794 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9795 (when org-provide-todo-statistics
9796 (org-update-parent-todo-statistics))
9797 (run-hooks 'org-after-todo-state-change-hook)
9798 (if (and arg (not (member state org-done-keywords)))
9799 (setq head (org-get-todo-sequence-head state)))
9800 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9801 ;; Do we need to trigger a repeat?
9802 (when now-done-p
9803 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9804 ;; This is for the agenda, take a snapshot of the headline.
9805 (save-match-data
9806 (setq org-agenda-headline-snapshot-before-repeat
9807 (org-get-heading))))
9808 (org-auto-repeat-maybe state))
9809 ;; Fixup cursor location if close to the keyword
9810 (if (and (outline-on-heading-p)
9811 (not (bolp))
9812 (save-excursion (beginning-of-line 1)
9813 (looking-at org-todo-line-regexp))
9814 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9815 (progn
9816 (goto-char (or (match-end 2) (match-end 1)))
9817 (and (looking-at " ") (just-one-space))))
9818 (when org-trigger-hook
9819 (save-excursion
9820 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9822 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9823 "Block turning an entry into a TODO, using the hierarchy.
9824 This checks whether the current task should be blocked from state
9825 changes. Such blocking occurs when:
9827 1. The task has children which are not all in a completed state.
9829 2. A task has a parent with the property :ORDERED:, and there
9830 are siblings prior to the current task with incomplete
9831 status.
9833 3. The parent of the task is blocked because it has siblings that should
9834 be done first, or is child of a block grandparent TODO entry."
9836 (catch 'dont-block
9837 ;; If this is not a todo state change, or if this entry is already DONE,
9838 ;; do not block
9839 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9840 (member (plist-get change-plist :from)
9841 (cons 'done org-done-keywords))
9842 (member (plist-get change-plist :to)
9843 (cons 'todo org-not-done-keywords)))
9844 (throw 'dont-block t))
9845 ;; If this task has children, and any are undone, it's blocked
9846 (save-excursion
9847 (org-back-to-heading t)
9848 (let ((this-level (funcall outline-level)))
9849 (outline-next-heading)
9850 (let ((child-level (funcall outline-level)))
9851 (while (and (not (eobp))
9852 (> child-level this-level))
9853 ;; this todo has children, check whether they are all
9854 ;; completed
9855 (if (and (not (org-entry-is-done-p))
9856 (org-entry-is-todo-p))
9857 (throw 'dont-block nil))
9858 (outline-next-heading)
9859 (setq child-level (funcall outline-level))))))
9860 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9861 ;; any previous siblings are undone, it's blocked
9862 (save-excursion
9863 (org-back-to-heading t)
9864 (let* ((pos (point))
9865 (parent-pos (and (org-up-heading-safe) (point))))
9866 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9867 (when (and (org-entry-get (point) "ORDERED")
9868 (forward-line 1)
9869 (re-search-forward org-not-done-heading-regexp pos t))
9870 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9871 ;; Search further up the hierarchy, to see if an anchestor is blocked
9872 (while t
9873 (goto-char parent-pos)
9874 (if (not (looking-at org-not-done-heading-regexp))
9875 (throw 'dont-block t)) ; do not block, parent is not a TODO
9876 (setq pos (point))
9877 (setq parent-pos (and (org-up-heading-safe) (point)))
9878 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9879 (when (and (org-entry-get (point) "ORDERED")
9880 (forward-line 1)
9881 (re-search-forward org-not-done-heading-regexp pos t))
9882 (throw 'dont-block nil))))))) ; block, older sibling not done.
9884 (defcustom org-track-ordered-property-with-tag nil
9885 "Should the ORDERED property also be shown as a tag?
9886 The ORDERED property decides if an entry should require subtasks to be
9887 completed in sequence. Since a property is not very visible, setting
9888 this option means that toggling the ORDERED property with the command
9889 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9890 not relevant for the behavior, but it makes things more visible.
9892 Note that toggling the tag with tags commands will not change the property
9893 and therefore not influence behavior!
9895 This can be t, meaning the tag ORDERED should be used, It can also be a
9896 string to select a different tag for this task."
9897 :group 'org-todo
9898 :type '(choice
9899 (const :tag "No tracking" nil)
9900 (const :tag "Track with ORDERED tag" t)
9901 (string :tag "Use other tag")))
9903 (defun org-toggle-ordered-property ()
9904 "Toggle the ORDERED property of the current entry.
9905 For better visibility, you can track the value of this property with a tag.
9906 See variable `org-track-ordered-property-with-tag'."
9907 (interactive)
9908 (let* ((t1 org-track-ordered-property-with-tag)
9909 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9910 (save-excursion
9911 (org-back-to-heading)
9912 (if (org-entry-get nil "ORDERED")
9913 (progn
9914 (org-delete-property "ORDERED")
9915 (and tag (org-toggle-tag tag 'off))
9916 (message "Subtasks can be completed in arbitrary order"))
9917 (org-entry-put nil "ORDERED" "t")
9918 (and tag (org-toggle-tag tag 'on))
9919 (message "Subtasks must be completed in sequence")))))
9921 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9922 (defun org-block-todo-from-checkboxes (change-plist)
9923 "Block turning an entry into a TODO, using checkboxes.
9924 This checks whether the current task should be blocked from state
9925 changes because there are uncheckd boxes in this entry."
9926 (catch 'dont-block
9927 ;; If this is not a todo state change, or if this entry is already DONE,
9928 ;; do not block
9929 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9930 (member (plist-get change-plist :from)
9931 (cons 'done org-done-keywords))
9932 (member (plist-get change-plist :to)
9933 (cons 'todo org-not-done-keywords)))
9934 (throw 'dont-block t))
9935 ;; If this task has checkboxes that are not checked, it's blocked
9936 (save-excursion
9937 (org-back-to-heading t)
9938 (let ((beg (point)) end)
9939 (outline-next-heading)
9940 (setq end (point))
9941 (goto-char beg)
9942 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9943 end t)
9944 (progn
9945 (if (boundp 'org-blocked-by-checkboxes)
9946 (setq org-blocked-by-checkboxes t))
9947 (throw 'dont-block nil)))))
9948 t)) ; do not block
9950 (defun org-update-statistics-cookies (all)
9951 "Update the statistics cookie, either from TODO or from checkboxes.
9952 This should be called with the cursor in a line with a statistics cookie."
9953 (interactive "P")
9954 (if all
9955 (progn
9956 (org-update-checkbox-count 'all)
9957 (org-map-entries 'org-update-parent-todo-statistics))
9958 (if (not (org-on-heading-p))
9959 (org-update-checkbox-count)
9960 (let ((pos (move-marker (make-marker) (point)))
9961 end l1 l2)
9962 (ignore-errors (org-back-to-heading t))
9963 (if (not (org-on-heading-p))
9964 (org-update-checkbox-count)
9965 (setq l1 (org-outline-level))
9966 (setq end (save-excursion
9967 (outline-next-heading)
9968 (if (org-on-heading-p) (setq l2 (org-outline-level)))
9969 (point)))
9970 (if (and (save-excursion (re-search-forward
9971 "^[ \t]*[-+*] \\[[- X]\\]" end t))
9972 (not (save-excursion (re-search-forward
9973 ":COOKIE_DATA:.*\\<todo\\>" end t))))
9974 (org-update-checkbox-count)
9975 (if (and l2 (> l2 l1))
9976 (progn
9977 (goto-char end)
9978 (org-update-parent-todo-statistics))
9979 (error "No data for statistics cookie"))))
9980 (goto-char pos)
9981 (move-marker pos nil)))))
9983 (defvar org-entry-property-inherited-from) ;; defined below
9984 (defun org-update-parent-todo-statistics ()
9985 "Update any statistics cookie in the parent of the current headline.
9986 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9987 the entire subtree and this will travel up the hierarchy and update
9988 statistics everywhere."
9989 (interactive)
9990 (let* ((lim 0) prop
9991 (recursive (or (not org-hierarchical-todo-statistics)
9992 (string-match
9993 "\\<recursive\\>"
9994 (or (setq prop (org-entry-get
9995 nil "COOKIE_DATA" 'inherit)) ""))))
9996 (lim (or (and prop (marker-position
9997 org-entry-property-inherited-from))
9998 lim))
9999 (first t)
10000 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10001 level ltoggle l1 new ndel
10002 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10003 (catch 'exit
10004 (save-excursion
10005 (beginning-of-line 1)
10006 (if (org-at-heading-p)
10007 (setq ltoggle (funcall outline-level))
10008 (error "This should not happen"))
10009 (while (and (setq level (org-up-heading-safe))
10010 (or recursive first)
10011 (>= (point) lim))
10012 (setq first nil cookie-present nil)
10013 (unless (and level
10014 (not (string-match
10015 "\\<checkbox\\>"
10016 (downcase
10017 (or (org-entry-get
10018 nil "COOKIE_DATA")
10019 "")))))
10020 (throw 'exit nil))
10021 (while (re-search-forward box-re (point-at-eol) t)
10022 (setq cnt-all 0 cnt-done 0 cookie-present t)
10023 (setq is-percent (match-end 2))
10024 (save-match-data
10025 (unless (outline-next-heading) (throw 'exit nil))
10026 (while (and (looking-at org-complex-heading-regexp)
10027 (> (setq l1 (length (match-string 1))) level))
10028 (setq kwd (and (or recursive (= l1 ltoggle))
10029 (match-string 2)))
10030 (if (or (eq org-provide-todo-statistics 'all-headlines)
10031 (and (listp org-provide-todo-statistics)
10032 (or (member kwd org-provide-todo-statistics)
10033 (member kwd org-done-keywords))))
10034 (setq cnt-all (1+ cnt-all))
10035 (if (eq org-provide-todo-statistics t)
10036 (and kwd (setq cnt-all (1+ cnt-all)))))
10037 (and (member kwd org-done-keywords)
10038 (setq cnt-done (1+ cnt-done)))
10039 (outline-next-heading)))
10040 (setq new
10041 (if is-percent
10042 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10043 (format "[%d/%d]" cnt-done cnt-all))
10044 ndel (- (match-end 0) (match-beginning 0)))
10045 (goto-char (match-beginning 0))
10046 (insert new)
10047 (delete-region (point) (+ (point) ndel)))
10048 (when cookie-present
10049 (run-hook-with-args 'org-after-todo-statistics-hook
10050 cnt-done (- cnt-all cnt-done))))))
10051 (run-hooks 'org-todo-statistics-hook)))
10053 (defvar org-after-todo-statistics-hook nil
10054 "Hook that is called after a TODO statistics cookie has been updated.
10055 Each function is called with two arguments: the number of not-done entries
10056 and the number of done entries.
10058 For example, the following function, when added to this hook, will switch
10059 an entry to DONE when all children are done, and back to TODO when new
10060 entries are set to a TODO status. Note that this hook is only called
10061 when there is a statistics cookie in the headline!
10063 (defun org-summary-todo (n-done n-not-done)
10064 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10065 (let (org-log-done org-log-states) ; turn off logging
10066 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10069 (defvar org-todo-statistics-hook nil
10070 "Hook that is run whenever Org thinks TODO statistics should be updated.
10071 This hook runs even if there is no statisics cookie present, in which case
10072 `org-after-todo-statistics-hook' would not run.")
10074 (defun org-todo-trigger-tag-changes (state)
10075 "Apply the changes defined in `org-todo-state-tags-triggers'."
10076 (let ((l org-todo-state-tags-triggers)
10077 changes)
10078 (when (or (not state) (equal state ""))
10079 (setq changes (append changes (cdr (assoc "" l)))))
10080 (when (and (stringp state) (> (length state) 0))
10081 (setq changes (append changes (cdr (assoc state l)))))
10082 (when (member state org-not-done-keywords)
10083 (setq changes (append changes (cdr (assoc 'todo l)))))
10084 (when (member state org-done-keywords)
10085 (setq changes (append changes (cdr (assoc 'done l)))))
10086 (dolist (c changes)
10087 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10089 (defun org-local-logging (value)
10090 "Get logging settings from a property VALUE."
10091 (let* (words w a)
10092 ;; directly set the variables, they are already local.
10093 (setq org-log-done nil
10094 org-log-repeat nil
10095 org-todo-log-states nil)
10096 (setq words (org-split-string value))
10097 (while (setq w (pop words))
10098 (cond
10099 ((setq a (assoc w org-startup-options))
10100 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10101 (set (nth 1 a) (nth 2 a))))
10102 ((setq a (org-extract-log-state-settings w))
10103 (and (member (car a) org-todo-keywords-1)
10104 (push a org-todo-log-states)))))))
10106 (defun org-get-todo-sequence-head (kwd)
10107 "Return the head of the TODO sequence to which KWD belongs.
10108 If KWD is not set, check if there is a text property remembering the
10109 right sequence."
10110 (let (p)
10111 (cond
10112 ((not kwd)
10113 (or (get-text-property (point-at-bol) 'org-todo-head)
10114 (progn
10115 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10116 nil (point-at-eol)))
10117 (get-text-property p 'org-todo-head))))
10118 ((not (member kwd org-todo-keywords-1))
10119 (car org-todo-keywords-1))
10120 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10122 (defun org-fast-todo-selection ()
10123 "Fast TODO keyword selection with single keys.
10124 Returns the new TODO keyword, or nil if no state change should occur."
10125 (let* ((fulltable org-todo-key-alist)
10126 (done-keywords org-done-keywords) ;; needed for the faces.
10127 (maxlen (apply 'max (mapcar
10128 (lambda (x)
10129 (if (stringp (car x)) (string-width (car x)) 0))
10130 fulltable)))
10131 (expert nil)
10132 (fwidth (+ maxlen 3 1 3))
10133 (ncol (/ (- (window-width) 4) fwidth))
10134 tg cnt e c tbl
10135 groups ingroup)
10136 (save-excursion
10137 (save-window-excursion
10138 (if expert
10139 (set-buffer (get-buffer-create " *Org todo*"))
10140 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10141 (erase-buffer)
10142 (org-set-local 'org-done-keywords done-keywords)
10143 (setq tbl fulltable cnt 0)
10144 (while (setq e (pop tbl))
10145 (cond
10146 ((equal e '(:startgroup))
10147 (push '() groups) (setq ingroup t)
10148 (when (not (= cnt 0))
10149 (setq cnt 0)
10150 (insert "\n"))
10151 (insert "{ "))
10152 ((equal e '(:endgroup))
10153 (setq ingroup nil cnt 0)
10154 (insert "}\n"))
10155 ((equal e '(:newline))
10156 (when (not (= cnt 0))
10157 (setq cnt 0)
10158 (insert "\n")
10159 (setq e (car tbl))
10160 (while (equal (car tbl) '(:newline))
10161 (insert "\n")
10162 (setq tbl (cdr tbl)))))
10164 (setq tg (car e) c (cdr e))
10165 (if ingroup (push tg (car groups)))
10166 (setq tg (org-add-props tg nil 'face
10167 (org-get-todo-face tg)))
10168 (if (and (= cnt 0) (not ingroup)) (insert " "))
10169 (insert "[" c "] " tg (make-string
10170 (- fwidth 4 (length tg)) ?\ ))
10171 (when (= (setq cnt (1+ cnt)) ncol)
10172 (insert "\n")
10173 (if ingroup (insert " "))
10174 (setq cnt 0)))))
10175 (insert "\n")
10176 (goto-char (point-min))
10177 (if (not expert) (org-fit-window-to-buffer))
10178 (message "[a-z..]:Set [SPC]:clear")
10179 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10180 (cond
10181 ((or (= c ?\C-g)
10182 (and (= c ?q) (not (rassoc c fulltable))))
10183 (setq quit-flag t))
10184 ((= c ?\ ) nil)
10185 ((setq e (rassoc c fulltable) tg (car e))
10187 (t (setq quit-flag t)))))))
10189 (defun org-entry-is-todo-p ()
10190 (member (org-get-todo-state) org-not-done-keywords))
10192 (defun org-entry-is-done-p ()
10193 (member (org-get-todo-state) org-done-keywords))
10195 (defun org-get-todo-state ()
10196 (save-excursion
10197 (org-back-to-heading t)
10198 (and (looking-at org-todo-line-regexp)
10199 (match-end 2)
10200 (match-string 2))))
10202 (defun org-at-date-range-p (&optional inactive-ok)
10203 "Is the cursor inside a date range?"
10204 (interactive)
10205 (save-excursion
10206 (catch 'exit
10207 (let ((pos (point)))
10208 (skip-chars-backward "^[<\r\n")
10209 (skip-chars-backward "<[")
10210 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10211 (>= (match-end 0) pos)
10212 (throw 'exit t))
10213 (skip-chars-backward "^<[\r\n")
10214 (skip-chars-backward "<[")
10215 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10216 (>= (match-end 0) pos)
10217 (throw 'exit t)))
10218 nil)))
10220 (defun org-get-repeat (&optional tagline)
10221 "Check if there is a deadline/schedule with repeater in this entry."
10222 (save-match-data
10223 (save-excursion
10224 (org-back-to-heading t)
10225 (and (re-search-forward (if tagline
10226 (concat tagline "\\s-*" org-repeat-re)
10227 org-repeat-re)
10228 (org-entry-end-position) t)
10229 (match-string-no-properties 1)))))
10231 (defvar org-last-changed-timestamp)
10232 (defvar org-last-inserted-timestamp)
10233 (defvar org-log-post-message)
10234 (defvar org-log-note-purpose)
10235 (defvar org-log-note-how)
10236 (defvar org-log-note-extra)
10237 (defun org-auto-repeat-maybe (done-word)
10238 "Check if the current headline contains a repeated deadline/schedule.
10239 If yes, set TODO state back to what it was and change the base date
10240 of repeating deadline/scheduled time stamps to new date.
10241 This function is run automatically after each state change to a DONE state."
10242 ;; last-state is dynamically scoped into this function
10243 (let* ((repeat (org-get-repeat))
10244 (aa (assoc last-state org-todo-kwd-alist))
10245 (interpret (nth 1 aa))
10246 (head (nth 2 aa))
10247 (whata '(("d" . day) ("m" . month) ("y" . year)))
10248 (msg "Entry repeats: ")
10249 (org-log-done nil)
10250 (org-todo-log-states nil)
10251 (nshiftmax 10) (nshift 0)
10252 re type n what ts time)
10253 (when repeat
10254 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10255 (org-todo (if (eq interpret 'type) last-state head))
10256 (org-entry-put nil "LAST_REPEAT" (format-time-string
10257 (org-time-stamp-format t t)))
10258 (when org-log-repeat
10259 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10260 (memq 'org-add-log-note post-command-hook))
10261 ;; OK, we are already setup for some record
10262 (if (eq org-log-repeat 'note)
10263 ;; make sure we take a note, not only a time stamp
10264 (setq org-log-note-how 'note))
10265 ;; Set up for taking a record
10266 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10267 last-state
10268 'findpos org-log-repeat)))
10269 (org-back-to-heading t)
10270 (org-add-planning-info nil nil 'closed)
10271 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10272 org-deadline-time-regexp "\\)\\|\\("
10273 org-ts-regexp "\\)"))
10274 (while (re-search-forward
10275 re (save-excursion (outline-next-heading) (point)) t)
10276 (setq type (if (match-end 1) org-scheduled-string
10277 (if (match-end 3) org-deadline-string "Plain:"))
10278 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10279 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10280 (setq n (string-to-number (match-string 2 ts))
10281 what (match-string 3 ts))
10282 (if (equal what "w") (setq n (* n 7) what "d"))
10283 ;; Preparation, see if we need to modify the start date for the change
10284 (when (match-end 1)
10285 (setq time (save-match-data (org-time-string-to-time ts)))
10286 (cond
10287 ((equal (match-string 1 ts) ".")
10288 ;; Shift starting date to today
10289 (org-timestamp-change
10290 (- (time-to-days (current-time)) (time-to-days time))
10291 'day))
10292 ((equal (match-string 1 ts) "+")
10293 (while (or (= nshift 0)
10294 (<= (time-to-days time) (time-to-days (current-time))))
10295 (when (= (incf nshift) nshiftmax)
10296 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10297 (error "Abort")))
10298 (org-timestamp-change n (cdr (assoc what whata)))
10299 (org-at-timestamp-p t)
10300 (setq ts (match-string 1))
10301 (setq time (save-match-data (org-time-string-to-time ts))))
10302 (org-timestamp-change (- n) (cdr (assoc what whata)))
10303 ;; rematch, so that we have everything in place for the real shift
10304 (org-at-timestamp-p t)
10305 (setq ts (match-string 1))
10306 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10307 (org-timestamp-change n (cdr (assoc what whata)))
10308 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10309 (setq org-log-post-message msg)
10310 (message "%s" msg))))
10312 (defun org-show-todo-tree (arg)
10313 "Make a compact tree which shows all headlines marked with TODO.
10314 The tree will show the lines where the regexp matches, and all higher
10315 headlines above the match.
10316 With a \\[universal-argument] prefix, prompt for a regexp to match.
10317 With a numeric prefix N, construct a sparse tree for the Nth element
10318 of `org-todo-keywords-1'."
10319 (interactive "P")
10320 (let ((case-fold-search nil)
10321 (kwd-re
10322 (cond ((null arg) org-not-done-regexp)
10323 ((equal arg '(4))
10324 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10325 (mapcar 'list org-todo-keywords-1))))
10326 (concat "\\("
10327 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10328 "\\)\\>")))
10329 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10330 (regexp-quote (nth (1- (prefix-numeric-value arg))
10331 org-todo-keywords-1)))
10332 (t (error "Invalid prefix argument: %s" arg)))))
10333 (message "%d TODO entries found"
10334 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10336 (defun org-deadline (&optional remove time)
10337 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10338 With argument REMOVE, remove any deadline from the item.
10339 When TIME is set, it should be an internal time specification, and the
10340 scheduling will use the corresponding date."
10341 (interactive "P")
10342 (if remove
10343 (progn
10344 (org-remove-timestamp-with-keyword org-deadline-string)
10345 (message "Item no longer has a deadline."))
10346 (if (org-get-repeat)
10347 (error "Cannot change deadline on task with repeater, please do that by hand")
10348 (org-add-planning-info 'deadline time 'closed)
10349 (message "Deadline on %s" org-last-inserted-timestamp))))
10351 (defun org-schedule (&optional remove time)
10352 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10353 With argument REMOVE, remove any scheduling date from the item.
10354 When TIME is set, it should be an internal time specification, and the
10355 scheduling will use the corresponding date."
10356 (interactive "P")
10357 (if remove
10358 (progn
10359 (org-remove-timestamp-with-keyword org-scheduled-string)
10360 (message "Item is no longer scheduled."))
10361 (if (org-get-repeat)
10362 (error "Cannot reschedule task with repeater, please do that by hand")
10363 (org-add-planning-info 'scheduled time 'closed)
10364 (message "Scheduled to %s" org-last-inserted-timestamp))))
10366 (defun org-get-scheduled-time (pom &optional inherit)
10367 "Get the scheduled time as a time tuple, of a format suitable
10368 for calling org-schedule with, or if there is no scheduling,
10369 returns nil."
10370 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10371 (when time
10372 (apply 'encode-time (org-parse-time-string time)))))
10374 (defun org-get-deadline-time (pom &optional inherit)
10375 "Get the deadine as a time tuple, of a format suitable for
10376 calling org-deadlin with, or if there is no scheduling, returns
10377 nil."
10378 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10379 (when time
10380 (apply 'encode-time (org-parse-time-string time)))))
10382 (defun org-remove-timestamp-with-keyword (keyword)
10383 "Remove all time stamps with KEYWORD in the current entry."
10384 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10385 beg)
10386 (save-excursion
10387 (org-back-to-heading t)
10388 (setq beg (point))
10389 (outline-next-heading)
10390 (while (re-search-backward re beg t)
10391 (replace-match "")
10392 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10393 (equal (char-before) ?\ ))
10394 (backward-delete-char 1)
10395 (if (string-match "^[ \t]*$" (buffer-substring
10396 (point-at-bol) (point-at-eol)))
10397 (delete-region (point-at-bol)
10398 (min (point-max) (1+ (point-at-eol))))))))))
10400 (defun org-add-planning-info (what &optional time &rest remove)
10401 "Insert new timestamp with keyword in the line directly after the headline.
10402 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10403 If non is given, the user is prompted for a date.
10404 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10405 be removed."
10406 (interactive)
10407 (let (org-time-was-given org-end-time-was-given ts
10408 end default-time default-input)
10410 (catch 'exit
10411 (when (and (not time) (memq what '(scheduled deadline)))
10412 ;; Try to get a default date/time from existing timestamp
10413 (save-excursion
10414 (org-back-to-heading t)
10415 (setq end (save-excursion (outline-next-heading) (point)))
10416 (when (re-search-forward (if (eq what 'scheduled)
10417 org-scheduled-time-regexp
10418 org-deadline-time-regexp)
10419 end t)
10420 (setq ts (match-string 1)
10421 default-time
10422 (apply 'encode-time (org-parse-time-string ts))
10423 default-input (and ts (org-get-compact-tod ts))))))
10424 (when what
10425 ;; If necessary, get the time from the user
10426 (setq time (or time (org-read-date nil 'to-time nil nil
10427 default-time default-input))))
10429 (when (and org-insert-labeled-timestamps-at-point
10430 (member what '(scheduled deadline)))
10431 (insert
10432 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10433 (org-insert-time-stamp time org-time-was-given
10434 nil nil nil (list org-end-time-was-given))
10435 (setq what nil))
10436 (save-excursion
10437 (save-restriction
10438 (let (col list elt ts buffer-invisibility-spec)
10439 (org-back-to-heading t)
10440 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10441 (goto-char (match-end 1))
10442 (setq col (current-column))
10443 (goto-char (match-end 0))
10444 (if (eobp) (insert "\n") (forward-char 1))
10445 (when (and (not what)
10446 (not (looking-at
10447 (concat "[ \t]*"
10448 org-keyword-time-not-clock-regexp))))
10449 ;; Nothing to add, nothing to remove...... :-)
10450 (throw 'exit nil))
10451 (if (and (not (looking-at outline-regexp))
10452 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10453 "[^\r\n]*"))
10454 (not (equal (match-string 1) org-clock-string)))
10455 (narrow-to-region (match-beginning 0) (match-end 0))
10456 (insert-before-markers "\n")
10457 (backward-char 1)
10458 (narrow-to-region (point) (point))
10459 (and org-adapt-indentation (org-indent-to-column col)))
10460 ;; Check if we have to remove something.
10461 (setq list (cons what remove))
10462 (while list
10463 (setq elt (pop list))
10464 (goto-char (point-min))
10465 (when (or (and (eq elt 'scheduled)
10466 (re-search-forward org-scheduled-time-regexp nil t))
10467 (and (eq elt 'deadline)
10468 (re-search-forward org-deadline-time-regexp nil t))
10469 (and (eq elt 'closed)
10470 (re-search-forward org-closed-time-regexp nil t)))
10471 (replace-match "")
10472 (if (looking-at "--+<[^>]+>") (replace-match ""))
10473 (skip-chars-backward " ")
10474 (if (looking-at " +") (replace-match ""))))
10475 (goto-char (point-max))
10476 (and org-adapt-indentation (bolp) (org-indent-to-column col))
10477 (when what
10478 (insert
10479 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10480 (cond ((eq what 'scheduled) org-scheduled-string)
10481 ((eq what 'deadline) org-deadline-string)
10482 ((eq what 'closed) org-closed-string))
10483 " ")
10484 (setq ts (org-insert-time-stamp
10485 time
10486 (or org-time-was-given
10487 (and (eq what 'closed) org-log-done-with-time))
10488 (eq what 'closed)
10489 nil nil (list org-end-time-was-given)))
10490 (end-of-line 1))
10491 (goto-char (point-min))
10492 (widen)
10493 (if (and (looking-at "[ \t]+\n")
10494 (equal (char-before) ?\n))
10495 (delete-region (1- (point)) (point-at-eol)))
10496 ts))))))
10498 (defvar org-log-note-marker (make-marker))
10499 (defvar org-log-note-purpose nil)
10500 (defvar org-log-note-state nil)
10501 (defvar org-log-note-previous-state nil)
10502 (defvar org-log-note-how nil)
10503 (defvar org-log-note-extra nil)
10504 (defvar org-log-note-window-configuration nil)
10505 (defvar org-log-note-return-to (make-marker))
10506 (defvar org-log-post-message nil
10507 "Message to be displayed after a log note has been stored.
10508 The auto-repeater uses this.")
10510 (defun org-add-note ()
10511 "Add a note to the current entry.
10512 This is done in the same way as adding a state change note."
10513 (interactive)
10514 (org-add-log-setup 'note nil nil 'findpos nil))
10516 (defvar org-property-end-re)
10517 (defun org-add-log-setup (&optional purpose state prev-state
10518 findpos how &optional extra)
10519 "Set up the post command hook to take a note.
10520 If this is about to TODO state change, the new state is expected in STATE.
10521 When FINDPOS is non-nil, find the correct position for the note in
10522 the current entry. If not, assume that it can be inserted at point.
10523 HOW is an indicator what kind of note should be created.
10524 EXTRA is additional text that will be inserted into the notes buffer."
10525 (let* ((org-log-into-drawer (org-log-into-drawer))
10526 (drawer (cond ((stringp org-log-into-drawer)
10527 org-log-into-drawer)
10528 (org-log-into-drawer "LOGBOOK")
10529 (t nil))))
10530 (save-restriction
10531 (save-excursion
10532 (when findpos
10533 (org-back-to-heading t)
10534 (narrow-to-region (point) (save-excursion
10535 (outline-next-heading) (point)))
10536 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10537 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10538 "[^\r\n]*\\)?"))
10539 (goto-char (match-end 0))
10540 (cond
10541 (drawer
10542 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10543 nil t)
10544 (progn
10545 (goto-char (match-end 0))
10546 (or org-log-states-order-reversed
10547 (and (re-search-forward org-property-end-re nil t)
10548 (goto-char (1- (match-beginning 0))))))
10549 (insert "\n:" drawer ":\n:END:")
10550 (beginning-of-line 0)
10551 (org-indent-line-function)
10552 (beginning-of-line 2)
10553 (org-indent-line-function)
10554 (end-of-line 0)))
10555 ((and org-log-state-notes-insert-after-drawers
10556 (save-excursion
10557 (forward-line) (looking-at org-drawer-regexp)))
10558 (forward-line)
10559 (while (looking-at org-drawer-regexp)
10560 (goto-char (match-end 0))
10561 (re-search-forward org-property-end-re (point-max) t)
10562 (forward-line))
10563 (forward-line -1)))
10564 (unless org-log-states-order-reversed
10565 (and (= (char-after) ?\n) (forward-char 1))
10566 (org-skip-over-state-notes)
10567 (skip-chars-backward " \t\n\r")))
10568 (move-marker org-log-note-marker (point))
10569 (setq org-log-note-purpose purpose
10570 org-log-note-state state
10571 org-log-note-previous-state prev-state
10572 org-log-note-how how
10573 org-log-note-extra extra)
10574 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10576 (defun org-skip-over-state-notes ()
10577 "Skip past the list of State notes in an entry."
10578 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10579 (while (looking-at "[ \t]*- State")
10580 (condition-case nil
10581 (org-next-item)
10582 (error (org-end-of-item)))))
10584 (defun org-add-log-note (&optional purpose)
10585 "Pop up a window for taking a note, and add this note later at point."
10586 (remove-hook 'post-command-hook 'org-add-log-note)
10587 (setq org-log-note-window-configuration (current-window-configuration))
10588 (delete-other-windows)
10589 (move-marker org-log-note-return-to (point))
10590 (switch-to-buffer (marker-buffer org-log-note-marker))
10591 (goto-char org-log-note-marker)
10592 (org-switch-to-buffer-other-window "*Org Note*")
10593 (erase-buffer)
10594 (if (memq org-log-note-how '(time state))
10595 (let (current-prefix-arg) (org-store-log-note))
10596 (let ((org-inhibit-startup t)) (org-mode))
10597 (insert (format "# Insert note for %s.
10598 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10599 (cond
10600 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10601 ((eq org-log-note-purpose 'done) "closed todo item")
10602 ((eq org-log-note-purpose 'state)
10603 (format "state change from \"%s\" to \"%s\""
10604 (or org-log-note-previous-state "")
10605 (or org-log-note-state "")))
10606 ((eq org-log-note-purpose 'note)
10607 "this entry")
10608 (t (error "This should not happen")))))
10609 (if org-log-note-extra (insert org-log-note-extra))
10610 (org-set-local 'org-finish-function 'org-store-log-note)))
10612 (defvar org-note-abort nil) ; dynamically scoped
10613 (defun org-store-log-note ()
10614 "Finish taking a log note, and insert it to where it belongs."
10615 (let ((txt (buffer-string))
10616 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10617 lines ind)
10618 (kill-buffer (current-buffer))
10619 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10620 (setq txt (replace-match "" t t txt)))
10621 (if (string-match "\\s-+\\'" txt)
10622 (setq txt (replace-match "" t t txt)))
10623 (setq lines (org-split-string txt "\n"))
10624 (when (and note (string-match "\\S-" note))
10625 (setq note
10626 (org-replace-escapes
10627 note
10628 (list (cons "%u" (user-login-name))
10629 (cons "%U" user-full-name)
10630 (cons "%t" (format-time-string
10631 (org-time-stamp-format 'long 'inactive)
10632 (current-time)))
10633 (cons "%s" (if org-log-note-state
10634 (concat "\"" org-log-note-state "\"")
10635 ""))
10636 (cons "%S" (if org-log-note-previous-state
10637 (concat "\"" org-log-note-previous-state "\"")
10638 "\"\"")))))
10639 (if lines (setq note (concat note " \\\\")))
10640 (push note lines))
10641 (when (or current-prefix-arg org-note-abort)
10642 (when org-log-into-drawer
10643 (org-remove-empty-drawer-at
10644 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10645 org-log-note-marker))
10646 (setq lines nil))
10647 (when lines
10648 (with-current-buffer (marker-buffer org-log-note-marker)
10649 (save-excursion
10650 (goto-char org-log-note-marker)
10651 (move-marker org-log-note-marker nil)
10652 (end-of-line 1)
10653 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10654 (insert "- " (pop lines))
10655 (org-indent-line-function)
10656 (beginning-of-line 1)
10657 (looking-at "[ \t]*")
10658 (setq ind (concat (match-string 0) " "))
10659 (end-of-line 1)
10660 (while lines (insert "\n" ind (pop lines)))
10661 (message "Note stored")
10662 (org-back-to-heading t)
10663 (org-cycle-hide-drawers 'children)))))
10664 (set-window-configuration org-log-note-window-configuration)
10665 (with-current-buffer (marker-buffer org-log-note-return-to)
10666 (goto-char org-log-note-return-to))
10667 (move-marker org-log-note-return-to nil)
10668 (and org-log-post-message (message "%s" org-log-post-message)))
10670 (defun org-remove-empty-drawer-at (drawer pos)
10671 "Remove an emptyr DARWER drawer at position POS.
10672 POS may also be a marker."
10673 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10674 (save-excursion
10675 (save-restriction
10676 (widen)
10677 (goto-char pos)
10678 (if (org-in-regexp
10679 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10680 (replace-match ""))))))
10682 (defun org-sparse-tree (&optional arg)
10683 "Create a sparse tree, prompt for the details.
10684 This command can create sparse trees. You first need to select the type
10685 of match used to create the tree:
10687 t Show entries with a specific TODO keyword.
10688 m Show entries selected by a tags/property match.
10689 p Enter a property name and its value (both with completion on existing
10690 names/values) and show entries with that property.
10691 / Show entries matching a regular expression (`r' can be used as well)
10692 d Show deadlines due within `org-deadline-warning-days'.
10693 b Show deadlines and scheduled items before a date.
10694 a Show deadlines and scheduled items after a date."
10695 (interactive "P")
10696 (let (ans kwd value)
10697 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10698 (setq ans (read-char-exclusive))
10699 (cond
10700 ((equal ans ?d)
10701 (call-interactively 'org-check-deadlines))
10702 ((equal ans ?b)
10703 (call-interactively 'org-check-before-date))
10704 ((equal ans ?a)
10705 (call-interactively 'org-check-after-date))
10706 ((equal ans ?t)
10707 (org-show-todo-tree '(4)))
10708 ((member ans '(?T ?m))
10709 (call-interactively 'org-match-sparse-tree))
10710 ((member ans '(?p ?P))
10711 (setq kwd (org-icompleting-read "Property: "
10712 (mapcar 'list (org-buffer-property-keys))))
10713 (setq value (org-icompleting-read "Value: "
10714 (mapcar 'list (org-property-values kwd))))
10715 (unless (string-match "\\`{.*}\\'" value)
10716 (setq value (concat "\"" value "\"")))
10717 (org-match-sparse-tree arg (concat kwd "=" value)))
10718 ((member ans '(?r ?R ?/))
10719 (call-interactively 'org-occur))
10720 (t (error "No such sparse tree command \"%c\"" ans)))))
10722 (defvar org-occur-highlights nil
10723 "List of overlays used for occur matches.")
10724 (make-variable-buffer-local 'org-occur-highlights)
10725 (defvar org-occur-parameters nil
10726 "Parameters of the active org-occur calls.
10727 This is a list, each call to org-occur pushes as cons cell,
10728 containing the regular expression and the callback, onto the list.
10729 The list can contain several entries if `org-occur' has been called
10730 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10731 will only contain one set of parameters. When the highlights are
10732 removed (for example with `C-c C-c', or with the next edit (depending
10733 on `org-remove-highlights-with-change'), this variable is emptied
10734 as well.")
10735 (make-variable-buffer-local 'org-occur-parameters)
10737 (defun org-occur (regexp &optional keep-previous callback)
10738 "Make a compact tree which shows all matches of REGEXP.
10739 The tree will show the lines where the regexp matches, and all higher
10740 headlines above the match. It will also show the heading after the match,
10741 to make sure editing the matching entry is easy.
10742 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10743 call to `org-occur' will be kept, to allow stacking of calls to this
10744 command.
10745 If CALLBACK is non-nil, it is a function which is called to confirm
10746 that the match should indeed be shown."
10747 (interactive "sRegexp: \nP")
10748 (when (equal regexp "")
10749 (error "Regexp cannot be empty"))
10750 (unless keep-previous
10751 (org-remove-occur-highlights nil nil t))
10752 (push (cons regexp callback) org-occur-parameters)
10753 (let ((cnt 0))
10754 (save-excursion
10755 (goto-char (point-min))
10756 (if (or (not keep-previous) ; do not want to keep
10757 (not org-occur-highlights)) ; no previous matches
10758 ;; hide everything
10759 (org-overview))
10760 (while (re-search-forward regexp nil t)
10761 (when (or (not callback)
10762 (save-match-data (funcall callback)))
10763 (setq cnt (1+ cnt))
10764 (when org-highlight-sparse-tree-matches
10765 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10766 (org-show-context 'occur-tree))))
10767 (when org-remove-highlights-with-change
10768 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10769 nil 'local))
10770 (unless org-sparse-tree-open-archived-trees
10771 (org-hide-archived-subtrees (point-min) (point-max)))
10772 (run-hooks 'org-occur-hook)
10773 (if (interactive-p)
10774 (message "%d match(es) for regexp %s" cnt regexp))
10775 cnt))
10777 (defun org-show-context (&optional key)
10778 "Make sure point and context and visible.
10779 How much context is shown depends upon the variables
10780 `org-show-hierarchy-above', `org-show-following-heading'. and
10781 `org-show-siblings'."
10782 (let ((heading-p (org-on-heading-p t))
10783 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10784 (following-p (org-get-alist-option org-show-following-heading key))
10785 (entry-p (org-get-alist-option org-show-entry-below key))
10786 (siblings-p (org-get-alist-option org-show-siblings key)))
10787 (catch 'exit
10788 ;; Show heading or entry text
10789 (if (and heading-p (not entry-p))
10790 (org-flag-heading nil) ; only show the heading
10791 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10792 (org-show-hidden-entry))) ; show entire entry
10793 (when following-p
10794 ;; Show next sibling, or heading below text
10795 (save-excursion
10796 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10797 (org-flag-heading nil))))
10798 (when siblings-p (org-show-siblings))
10799 (when hierarchy-p
10800 ;; show all higher headings, possibly with siblings
10801 (save-excursion
10802 (while (and (condition-case nil
10803 (progn (org-up-heading-all 1) t)
10804 (error nil))
10805 (not (bobp)))
10806 (org-flag-heading nil)
10807 (when siblings-p (org-show-siblings))))))))
10809 (defun org-reveal (&optional siblings)
10810 "Show current entry, hierarchy above it, and the following headline.
10811 This can be used to show a consistent set of context around locations
10812 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10813 not t for the search context.
10815 With optional argument SIBLINGS, on each level of the hierarchy all
10816 siblings are shown. This repairs the tree structure to what it would
10817 look like when opened with hierarchical calls to `org-cycle'."
10818 (interactive "P")
10819 (let ((org-show-hierarchy-above t)
10820 (org-show-following-heading t)
10821 (org-show-siblings (if siblings t org-show-siblings)))
10822 (org-show-context nil)))
10824 (defun org-highlight-new-match (beg end)
10825 "Highlight from BEG to END and mark the highlight is an occur headline."
10826 (let ((ov (org-make-overlay beg end)))
10827 (org-overlay-put ov 'face 'secondary-selection)
10828 (push ov org-occur-highlights)))
10830 (defun org-remove-occur-highlights (&optional beg end noremove)
10831 "Remove the occur highlights from the buffer.
10832 BEG and END are ignored. If NOREMOVE is nil, remove this function
10833 from the `before-change-functions' in the current buffer."
10834 (interactive)
10835 (unless org-inhibit-highlight-removal
10836 (mapc 'org-delete-overlay org-occur-highlights)
10837 (setq org-occur-highlights nil)
10838 (setq org-occur-parameters nil)
10839 (unless noremove
10840 (remove-hook 'before-change-functions
10841 'org-remove-occur-highlights 'local))))
10843 ;;;; Priorities
10845 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10846 "Regular expression matching the priority indicator.")
10848 (defvar org-remove-priority-next-time nil)
10850 (defun org-priority-up ()
10851 "Increase the priority of the current item."
10852 (interactive)
10853 (org-priority 'up))
10855 (defun org-priority-down ()
10856 "Decrease the priority of the current item."
10857 (interactive)
10858 (org-priority 'down))
10860 (defun org-priority (&optional action)
10861 "Change the priority of an item by ARG.
10862 ACTION can be `set', `up', `down', or a character."
10863 (interactive)
10864 (unless org-enable-priority-commands
10865 (error "Priority commands are disabled"))
10866 (setq action (or action 'set))
10867 (let (current new news have remove)
10868 (save-excursion
10869 (org-back-to-heading t)
10870 (if (looking-at org-priority-regexp)
10871 (setq current (string-to-char (match-string 2))
10872 have t)
10873 (setq current org-default-priority))
10874 (cond
10875 ((eq action 'remove)
10876 (setq remove t new ?\ ))
10877 ((or (eq action 'set)
10878 (if (featurep 'xemacs) (characterp action) (integerp action)))
10879 (if (not (eq action 'set))
10880 (setq new action)
10881 (message "Priority %c-%c, SPC to remove: "
10882 org-highest-priority org-lowest-priority)
10883 (setq new (read-char-exclusive)))
10884 (if (and (= (upcase org-highest-priority) org-highest-priority)
10885 (= (upcase org-lowest-priority) org-lowest-priority))
10886 (setq new (upcase new)))
10887 (cond ((equal new ?\ ) (setq remove t))
10888 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10889 (error "Priority must be between `%c' and `%c'"
10890 org-highest-priority org-lowest-priority))))
10891 ((eq action 'up)
10892 (if (and (not have) (eq last-command this-command))
10893 (setq new org-lowest-priority)
10894 (setq new (if (and org-priority-start-cycle-with-default (not have))
10895 org-default-priority (1- current)))))
10896 ((eq action 'down)
10897 (if (and (not have) (eq last-command this-command))
10898 (setq new org-highest-priority)
10899 (setq new (if (and org-priority-start-cycle-with-default (not have))
10900 org-default-priority (1+ current)))))
10901 (t (error "Invalid action")))
10902 (if (or (< (upcase new) org-highest-priority)
10903 (> (upcase new) org-lowest-priority))
10904 (setq remove t))
10905 (setq news (format "%c" new))
10906 (if have
10907 (if remove
10908 (replace-match "" t t nil 1)
10909 (replace-match news t t nil 2))
10910 (if remove
10911 (error "No priority cookie found in line")
10912 (let ((case-fold-search nil))
10913 (looking-at org-todo-line-regexp))
10914 (if (match-end 2)
10915 (progn
10916 (goto-char (match-end 2))
10917 (insert " [#" news "]"))
10918 (goto-char (match-beginning 3))
10919 (insert "[#" news "] "))))
10920 (org-preserve-lc (org-set-tags nil 'align)))
10921 (if remove
10922 (message "Priority removed")
10923 (message "Priority of current item set to %s" news))))
10925 (defun org-get-priority (s)
10926 "Find priority cookie and return priority."
10927 (save-match-data
10928 (if (not (string-match org-priority-regexp s))
10929 (* 1000 (- org-lowest-priority org-default-priority))
10930 (* 1000 (- org-lowest-priority
10931 (string-to-char (match-string 2 s)))))))
10933 ;;;; Tags
10935 (defvar org-agenda-archives-mode)
10936 (defvar org-map-continue-from nil
10937 "Position from where mapping should continue.
10938 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10940 (defvar org-scanner-tags nil
10941 "The current tag list while the tags scanner is running.")
10942 (defvar org-trust-scanner-tags nil
10943 "Should `org-get-tags-at' use the tags fro the scanner.
10944 This is for internal dynamical scoping only.
10945 When this is non-nil, the function `org-get-tags-at' will return the value
10946 of `org-scanner-tags' instead of building the list by itself. This
10947 can lead to large speed-ups when the tags scanner is used in a file with
10948 many entries, and when the list of tags is retrieved, for example to
10949 obtain a list of properties. Building the tags list for each entry in such
10950 a file becomes an N^2 operation - but with this variable set, it scales
10951 as N.")
10953 (defun org-scan-tags (action matcher &optional todo-only)
10954 "Scan headline tags with inheritance and produce output ACTION.
10956 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10957 or `agenda' to produce an entry list for an agenda view. It can also be
10958 a Lisp form or a function that should be called at each matched headline, in
10959 this case the return value is a list of all return values from these calls.
10961 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10962 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10963 only lines with a TODO keyword are included in the output."
10964 (require 'org-agenda)
10965 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10966 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10967 (org-re
10968 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10969 (props (list 'face 'default
10970 'done-face 'org-agenda-done
10971 'undone-face 'default
10972 'mouse-face 'highlight
10973 'org-not-done-regexp org-not-done-regexp
10974 'org-todo-regexp org-todo-regexp
10975 'help-echo
10976 (format "mouse-2 or RET jump to org file %s"
10977 (abbreviate-file-name
10978 (or (buffer-file-name (buffer-base-buffer))
10979 (buffer-name (buffer-base-buffer)))))))
10980 (case-fold-search nil)
10981 (org-map-continue-from nil)
10982 lspos tags tags-list
10983 (tags-alist (list (cons 0 org-file-tags)))
10984 (llast 0) rtn rtn1 level category i txt
10985 todo marker entry priority)
10986 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10987 (setq action (list 'lambda nil action)))
10988 (save-excursion
10989 (goto-char (point-min))
10990 (when (eq action 'sparse-tree)
10991 (org-overview)
10992 (org-remove-occur-highlights))
10993 (while (re-search-forward re nil t)
10994 (catch :skip
10995 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10996 tags (if (match-end 4) (org-match-string-no-properties 4)))
10997 (goto-char (setq lspos (match-beginning 0)))
10998 (setq level (org-reduced-level (funcall outline-level))
10999 category (org-get-category))
11000 (setq i llast llast level)
11001 ;; remove tag lists from same and sublevels
11002 (while (>= i level)
11003 (when (setq entry (assoc i tags-alist))
11004 (setq tags-alist (delete entry tags-alist)))
11005 (setq i (1- i)))
11006 ;; add the next tags
11007 (when tags
11008 (setq tags (org-split-string tags ":")
11009 tags-alist
11010 (cons (cons level tags) tags-alist)))
11011 ;; compile tags for current headline
11012 (setq tags-list
11013 (if org-use-tag-inheritance
11014 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11015 tags)
11016 org-scanner-tags tags-list)
11017 (when org-use-tag-inheritance
11018 (setcdr (car tags-alist)
11019 (mapcar (lambda (x)
11020 (setq x (copy-sequence x))
11021 (org-add-prop-inherited x))
11022 (cdar tags-alist))))
11023 (when (and tags org-use-tag-inheritance
11024 (or (not (eq t org-use-tag-inheritance))
11025 org-tags-exclude-from-inheritance))
11026 ;; selective inheritance, remove uninherited ones
11027 (setcdr (car tags-alist)
11028 (org-remove-uniherited-tags (cdar tags-alist))))
11029 (when (and (or (not todo-only)
11030 (and (member todo org-not-done-keywords)
11031 (or (not org-agenda-tags-todo-honor-ignore-options)
11032 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11033 (let ((case-fold-search t)) (eval matcher))
11035 (not (member org-archive-tag tags-list))
11036 ;; we have an archive tag, should we use this anyway?
11037 (or (not org-agenda-skip-archived-trees)
11038 (and (eq action 'agenda) org-agenda-archives-mode))))
11039 (unless (eq action 'sparse-tree) (org-agenda-skip))
11041 ;; select this headline
11043 (cond
11044 ((eq action 'sparse-tree)
11045 (and org-highlight-sparse-tree-matches
11046 (org-get-heading) (match-end 0)
11047 (org-highlight-new-match
11048 (match-beginning 0) (match-beginning 1)))
11049 (org-show-context 'tags-tree))
11050 ((eq action 'agenda)
11051 (setq txt (org-format-agenda-item
11053 (concat
11054 (if (eq org-tags-match-list-sublevels 'indented)
11055 (make-string (1- level) ?.) "")
11056 (org-get-heading))
11057 category
11058 tags-list
11060 priority (org-get-priority txt))
11061 (goto-char lspos)
11062 (setq marker (org-agenda-new-marker))
11063 (org-add-props txt props
11064 'org-marker marker 'org-hd-marker marker 'org-category category
11065 'todo-state todo
11066 'priority priority 'type "tagsmatch")
11067 (push txt rtn))
11068 ((functionp action)
11069 (setq org-map-continue-from nil)
11070 (save-excursion
11071 (setq rtn1 (funcall action))
11072 (push rtn1 rtn)))
11073 (t (error "Invalid action")))
11075 ;; if we are to skip sublevels, jump to end of subtree
11076 (unless org-tags-match-list-sublevels
11077 (org-end-of-subtree t)
11078 (backward-char 1))))
11079 ;; Get the correct position from where to continue
11080 (if org-map-continue-from
11081 (goto-char org-map-continue-from)
11082 (and (= (point) lspos) (end-of-line 1)))))
11083 (when (and (eq action 'sparse-tree)
11084 (not org-sparse-tree-open-archived-trees))
11085 (org-hide-archived-subtrees (point-min) (point-max)))
11086 (nreverse rtn)))
11088 (defun org-remove-uniherited-tags (tags)
11089 "Remove all tags that are not inherited from the list TAGS."
11090 (cond
11091 ((eq org-use-tag-inheritance t)
11092 (if org-tags-exclude-from-inheritance
11093 (org-delete-all org-tags-exclude-from-inheritance tags)
11094 tags))
11095 ((not org-use-tag-inheritance) nil)
11096 ((stringp org-use-tag-inheritance)
11097 (delq nil (mapcar
11098 (lambda (x)
11099 (if (and (string-match org-use-tag-inheritance x)
11100 (not (member x org-tags-exclude-from-inheritance)))
11101 x nil))
11102 tags)))
11103 ((listp org-use-tag-inheritance)
11104 (delq nil (mapcar
11105 (lambda (x)
11106 (if (member x org-use-tag-inheritance) x nil))
11107 tags)))))
11109 (defvar todo-only) ;; dynamically scoped
11111 (defun org-match-sparse-tree (&optional todo-only match)
11112 "Create a sparse tree according to tags string MATCH.
11113 MATCH can contain positive and negative selection of tags, like
11114 \"+WORK+URGENT-WITHBOSS\".
11115 If optional argument TODO-ONLY is non-nil, only select lines that are
11116 also TODO lines."
11117 (interactive "P")
11118 (org-prepare-agenda-buffers (list (current-buffer)))
11119 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11121 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11123 (defvar org-cached-props nil)
11124 (defun org-cached-entry-get (pom property)
11125 (if (or (eq t org-use-property-inheritance)
11126 (and (stringp org-use-property-inheritance)
11127 (string-match org-use-property-inheritance property))
11128 (and (listp org-use-property-inheritance)
11129 (member property org-use-property-inheritance)))
11130 ;; Caching is not possible, check it directly
11131 (org-entry-get pom property 'inherit)
11132 ;; Get all properties, so that we can do complicated checks easily
11133 (cdr (assoc property (or org-cached-props
11134 (setq org-cached-props
11135 (org-entry-properties pom)))))))
11137 (defun org-global-tags-completion-table (&optional files)
11138 "Return the list of all tags in all agenda buffer/files."
11139 (save-excursion
11140 (org-uniquify
11141 (delq nil
11142 (apply 'append
11143 (mapcar
11144 (lambda (file)
11145 (set-buffer (find-file-noselect file))
11146 (append (org-get-buffer-tags)
11147 (mapcar (lambda (x) (if (stringp (car-safe x))
11148 (list (car-safe x)) nil))
11149 org-tag-alist)))
11150 (if (and files (car files))
11151 files
11152 (org-agenda-files))))))))
11154 (defun org-make-tags-matcher (match)
11155 "Create the TAGS//TODO matcher form for the selection string MATCH."
11156 ;; todo-only is scoped dynamically into this function, and the function
11157 ;; may change it if the matcher asks for it.
11158 (unless match
11159 ;; Get a new match request, with completion
11160 (let ((org-last-tags-completion-table
11161 (org-global-tags-completion-table)))
11162 (setq match (org-completing-read-no-i
11163 "Match: " 'org-tags-completion-function nil nil nil
11164 'org-tags-history))))
11166 ;; Parse the string and create a lisp form
11167 (let ((match0 match)
11168 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11169 minus tag mm
11170 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11171 orterms term orlist re-p str-p level-p level-op time-p
11172 prop-p pn pv po cat-p gv rest)
11173 (if (string-match "/+" match)
11174 ;; match contains also a todo-matching request
11175 (progn
11176 (setq tagsmatch (substring match 0 (match-beginning 0))
11177 todomatch (substring match (match-end 0)))
11178 (if (string-match "^!" todomatch)
11179 (setq todo-only t todomatch (substring todomatch 1)))
11180 (if (string-match "^\\s-*$" todomatch)
11181 (setq todomatch nil)))
11182 ;; only matching tags
11183 (setq tagsmatch match todomatch nil))
11185 ;; Make the tags matcher
11186 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11187 (setq tagsmatcher t)
11188 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11189 (while (setq term (pop orterms))
11190 (while (and (equal (substring term -1) "\\") orterms)
11191 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11192 (while (string-match re term)
11193 (setq rest (substring term (match-end 0))
11194 minus (and (match-end 1)
11195 (equal (match-string 1 term) "-"))
11196 tag (match-string 2 term)
11197 re-p (equal (string-to-char tag) ?{)
11198 level-p (match-end 4)
11199 prop-p (match-end 5)
11200 mm (cond
11201 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11202 (level-p
11203 (setq level-op (org-op-to-function (match-string 3 term)))
11204 `(,level-op level ,(string-to-number
11205 (match-string 4 term))))
11206 (prop-p
11207 (setq pn (match-string 5 term)
11208 po (match-string 6 term)
11209 pv (match-string 7 term)
11210 cat-p (equal pn "CATEGORY")
11211 re-p (equal (string-to-char pv) ?{)
11212 str-p (equal (string-to-char pv) ?\")
11213 time-p (save-match-data
11214 (string-match "^\"[[<].*[]>]\"$" pv))
11215 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11216 (if time-p (setq pv (org-matcher-time pv)))
11217 (setq po (org-op-to-function po (if time-p 'time str-p)))
11218 (cond
11219 ((equal pn "CATEGORY")
11220 (setq gv '(get-text-property (point) 'org-category)))
11221 ((equal pn "TODO")
11222 (setq gv 'todo))
11224 (setq gv `(org-cached-entry-get nil ,pn))))
11225 (if re-p
11226 (if (eq po 'org<>)
11227 `(not (string-match ,pv (or ,gv "")))
11228 `(string-match ,pv (or ,gv "")))
11229 (if str-p
11230 `(,po (or ,gv "") ,pv)
11231 `(,po (string-to-number (or ,gv ""))
11232 ,(string-to-number pv) ))))
11233 (t `(member ,tag tags-list)))
11234 mm (if minus (list 'not mm) mm)
11235 term rest)
11236 (push mm tagsmatcher))
11237 (push (if (> (length tagsmatcher) 1)
11238 (cons 'and tagsmatcher)
11239 (car tagsmatcher))
11240 orlist)
11241 (setq tagsmatcher nil))
11242 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11243 (setq tagsmatcher
11244 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11245 ;; Make the todo matcher
11246 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11247 (setq todomatcher t)
11248 (setq orterms (org-split-string todomatch "|") orlist nil)
11249 (while (setq term (pop orterms))
11250 (while (string-match re term)
11251 (setq minus (and (match-end 1)
11252 (equal (match-string 1 term) "-"))
11253 kwd (match-string 2 term)
11254 re-p (equal (string-to-char kwd) ?{)
11255 term (substring term (match-end 0))
11256 mm (if re-p
11257 `(string-match ,(substring kwd 1 -1) todo)
11258 (list 'equal 'todo kwd))
11259 mm (if minus (list 'not mm) mm))
11260 (push mm todomatcher))
11261 (push (if (> (length todomatcher) 1)
11262 (cons 'and todomatcher)
11263 (car todomatcher))
11264 orlist)
11265 (setq todomatcher nil))
11266 (setq todomatcher (if (> (length orlist) 1)
11267 (cons 'or orlist) (car orlist))))
11269 ;; Return the string and lisp forms of the matcher
11270 (setq matcher (if todomatcher
11271 (list 'and tagsmatcher todomatcher)
11272 tagsmatcher))
11273 (cons match0 matcher)))
11275 (defun org-op-to-function (op &optional stringp)
11276 "Turn an operator into the appropriate function."
11277 (setq op
11278 (cond
11279 ((equal op "<" ) '(< string< org-time<))
11280 ((equal op ">" ) '(> org-string> org-time>))
11281 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11282 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11283 ((member op '("=" "==")) '(= string= org-time=))
11284 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11285 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11287 (defun org<> (a b) (not (= a b)))
11288 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11289 (defun org-string>= (a b) (not (string< a b)))
11290 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11291 (defun org-string<> (a b) (not (string= a b)))
11292 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11293 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11294 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11295 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11296 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11297 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11298 (defun org-2ft (s)
11299 "Convert S to a floating point time.
11300 If S is already a number, just return it. If it is a string, parse
11301 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11302 (cond
11303 ((numberp s) s)
11304 ((stringp s)
11305 (condition-case nil
11306 (float-time (apply 'encode-time (org-parse-time-string s)))
11307 (error 0.)))
11308 (t 0.)))
11310 (defun org-time-today ()
11311 "Time in seconds today at 0:00.
11312 Returns the float number of seconds since the beginning of the
11313 epoch to the beginning of today (00:00)."
11314 (float-time (apply 'encode-time
11315 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11317 (defun org-matcher-time (s)
11318 "Interpret a time comparison value."
11319 (save-match-data
11320 (cond
11321 ((string= s "<now>") (float-time))
11322 ((string= s "<today>") (org-time-today))
11323 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11324 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11325 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11326 (+ (org-time-today)
11327 (* (string-to-number (match-string 1 s))
11328 (cdr (assoc (match-string 2 s)
11329 '(("d" . 86400.0) ("w" . 604800.0)
11330 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11331 (t (org-2ft s)))))
11333 (defun org-match-any-p (re list)
11334 "Does re match any element of list?"
11335 (setq list (mapcar (lambda (x) (string-match re x)) list))
11336 (delq nil list))
11338 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11339 (defvar org-tags-overlay (org-make-overlay 1 1))
11340 (org-detach-overlay org-tags-overlay)
11342 (defun org-get-local-tags-at (&optional pos)
11343 "Get a list of tags defined in the current headline."
11344 (org-get-tags-at pos 'local))
11346 (defun org-get-local-tags ()
11347 "Get a list of tags defined in the current headline."
11348 (org-get-tags-at nil 'local))
11350 (defun org-get-tags-at (&optional pos local)
11351 "Get a list of all headline tags applicable at POS.
11352 POS defaults to point. If tags are inherited, the list contains
11353 the targets in the same sequence as the headlines appear, i.e.
11354 the tags of the current headline come last.
11355 When LOCAL is non-nil, only return tags from the current headline,
11356 ignore inherited ones."
11357 (interactive)
11358 (if (and org-trust-scanner-tags
11359 (or (not pos) (equal pos (point)))
11360 (not local))
11361 org-scanner-tags
11362 (let (tags ltags lastpos parent)
11363 (save-excursion
11364 (save-restriction
11365 (widen)
11366 (goto-char (or pos (point)))
11367 (save-match-data
11368 (catch 'done
11369 (condition-case nil
11370 (progn
11371 (org-back-to-heading t)
11372 (while (not (equal lastpos (point)))
11373 (setq lastpos (point))
11374 (when (looking-at
11375 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11376 (setq ltags (org-split-string
11377 (org-match-string-no-properties 1) ":"))
11378 (when parent
11379 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11380 (setq tags (append
11381 (if parent
11382 (org-remove-uniherited-tags ltags)
11383 ltags)
11384 tags)))
11385 (or org-use-tag-inheritance (throw 'done t))
11386 (if local (throw 'done t))
11387 (or (org-up-heading-safe) (error nil))
11388 (setq parent t)))
11389 (error nil)))))
11390 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11392 (defun org-add-prop-inherited (s)
11393 (add-text-properties 0 (length s) '(inherited t) s)
11396 (defun org-toggle-tag (tag &optional onoff)
11397 "Toggle the tag TAG for the current line.
11398 If ONOFF is `on' or `off', don't toggle but set to this state."
11399 (let (res current)
11400 (save-excursion
11401 (org-back-to-heading t)
11402 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11403 (point-at-eol) t)
11404 (progn
11405 (setq current (match-string 1))
11406 (replace-match ""))
11407 (setq current ""))
11408 (setq current (nreverse (org-split-string current ":")))
11409 (cond
11410 ((eq onoff 'on)
11411 (setq res t)
11412 (or (member tag current) (push tag current)))
11413 ((eq onoff 'off)
11414 (or (not (member tag current)) (setq current (delete tag current))))
11415 (t (if (member tag current)
11416 (setq current (delete tag current))
11417 (setq res t)
11418 (push tag current))))
11419 (end-of-line 1)
11420 (if current
11421 (progn
11422 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11423 (org-set-tags nil t))
11424 (delete-horizontal-space))
11425 (run-hooks 'org-after-tags-change-hook))
11426 res))
11428 (defun org-align-tags-here (to-col)
11429 ;; Assumes that this is a headline
11430 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11431 (beginning-of-line 1)
11432 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11433 (< pos (match-beginning 2)))
11434 (progn
11435 (setq tags-l (- (match-end 2) (match-beginning 2)))
11436 (goto-char (match-beginning 1))
11437 (insert " ")
11438 (delete-region (point) (1+ (match-beginning 2)))
11439 (setq ncol (max (1+ (current-column))
11440 (1+ col)
11441 (if (> to-col 0)
11442 to-col
11443 (- (abs to-col) tags-l))))
11444 (setq p (point))
11445 (insert (make-string (- ncol (current-column)) ?\ ))
11446 (setq ncol (current-column))
11447 (when indent-tabs-mode (tabify p (point-at-eol)))
11448 (org-move-to-column (min ncol col) t))
11449 (goto-char pos))))
11451 (defun org-set-tags-command (&optional arg just-align)
11452 "Call the set-tags command for the current entry."
11453 (interactive "P")
11454 (if (org-on-heading-p)
11455 (org-set-tags arg just-align)
11456 (save-excursion
11457 (org-back-to-heading t)
11458 (org-set-tags arg just-align))))
11460 (defun org-set-tags-to (data)
11461 "Set the tags of the current entry to DATA, replacing the current tags.
11462 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11463 If DATA is nil or the empty string, any tags will be removed."
11464 (interactive "sTags: ")
11465 (setq data
11466 (cond
11467 ((eq data nil) "")
11468 ((equal data "") "")
11469 ((stringp data)
11470 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11471 ":"))
11472 ((listp data)
11473 (concat ":" (mapconcat 'identity data ":") ":"))
11474 (t nil)))
11475 (when data
11476 (save-excursion
11477 (org-back-to-heading t)
11478 (when (looking-at org-complex-heading-regexp)
11479 (if (match-end 5)
11480 (progn
11481 (goto-char (match-beginning 5))
11482 (insert data)
11483 (delete-region (point) (point-at-eol))
11484 (org-set-tags nil 'align))
11485 (goto-char (point-at-eol))
11486 (insert " " data)
11487 (org-set-tags nil 'align)))
11488 (beginning-of-line 1)
11489 (if (looking-at ".*?\\([ \t]+\\)$")
11490 (delete-region (match-beginning 1) (match-end 1))))))
11492 (defun org-set-tags (&optional arg just-align)
11493 "Set the tags for the current headline.
11494 With prefix ARG, realign all tags in headings in the current buffer."
11495 (interactive "P")
11496 (let* ((re (concat "^" outline-regexp))
11497 (current (org-get-tags-string))
11498 (col (current-column))
11499 (org-setting-tags t)
11500 table current-tags inherited-tags ; computed below when needed
11501 tags p0 c0 c1 rpl)
11502 (if arg
11503 (save-excursion
11504 (goto-char (point-min))
11505 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11506 (while (re-search-forward re nil t)
11507 (org-set-tags nil t)
11508 (end-of-line 1)))
11509 (message "All tags realigned to column %d" org-tags-column))
11510 (if just-align
11511 (setq tags current)
11512 ;; Get a new set of tags from the user
11513 (save-excursion
11514 (setq table (append org-tag-persistent-alist
11515 (or org-tag-alist (org-get-buffer-tags)))
11516 org-last-tags-completion-table table
11517 current-tags (org-split-string current ":")
11518 inherited-tags (nreverse
11519 (nthcdr (length current-tags)
11520 (nreverse (org-get-tags-at))))
11521 tags
11522 (if (or (eq t org-use-fast-tag-selection)
11523 (and org-use-fast-tag-selection
11524 (delq nil (mapcar 'cdr table))))
11525 (org-fast-tag-selection
11526 current-tags inherited-tags table
11527 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11528 (let ((org-add-colon-after-tag-completion t))
11529 (org-trim
11530 (org-without-partial-completion
11531 (org-icompleting-read "Tags: " 'org-tags-completion-function
11532 nil nil current 'org-tags-history)))))))
11533 (while (string-match "[-+&]+" tags)
11534 ;; No boolean logic, just a list
11535 (setq tags (replace-match ":" t t tags))))
11537 (if org-tags-sort-function
11538 (setq tags (mapconcat 'identity
11539 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11540 org-tags-sort-function) ":")))
11542 (if (string-match "\\`[\t ]*\\'" tags)
11543 (setq tags "")
11544 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11545 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11547 ;; Insert new tags at the correct column
11548 (beginning-of-line 1)
11549 (cond
11550 ((and (equal current "") (equal tags "")))
11551 ((re-search-forward
11552 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11553 (point-at-eol) t)
11554 (if (equal tags "")
11555 (setq rpl "")
11556 (goto-char (match-beginning 0))
11557 (setq c0 (current-column) p0 (point)
11558 c1 (max (1+ c0) (if (> org-tags-column 0)
11559 org-tags-column
11560 (- (- org-tags-column) (length tags))))
11561 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11562 (replace-match rpl t t)
11563 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11564 tags)
11565 (t (error "Tags alignment failed")))
11566 (org-move-to-column col)
11567 (unless just-align
11568 (run-hooks 'org-after-tags-change-hook)))))
11570 (defun org-change-tag-in-region (beg end tag off)
11571 "Add or remove TAG for each entry in the region.
11572 This works in the agenda, and also in an org-mode buffer."
11573 (interactive
11574 (list (region-beginning) (region-end)
11575 (let ((org-last-tags-completion-table
11576 (if (org-mode-p)
11577 (org-get-buffer-tags)
11578 (org-global-tags-completion-table))))
11579 (org-icompleting-read
11580 "Tag: " 'org-tags-completion-function nil nil nil
11581 'org-tags-history))
11582 (progn
11583 (message "[s]et or [r]emove? ")
11584 (equal (read-char-exclusive) ?r))))
11585 (if (fboundp 'deactivate-mark) (deactivate-mark))
11586 (let ((agendap (equal major-mode 'org-agenda-mode))
11587 l1 l2 m buf pos newhead (cnt 0))
11588 (goto-char end)
11589 (setq l2 (1- (org-current-line)))
11590 (goto-char beg)
11591 (setq l1 (org-current-line))
11592 (loop for l from l1 to l2 do
11593 (org-goto-line l)
11594 (setq m (get-text-property (point) 'org-hd-marker))
11595 (when (or (and (org-mode-p) (org-on-heading-p))
11596 (and agendap m))
11597 (setq buf (if agendap (marker-buffer m) (current-buffer))
11598 pos (if agendap m (point)))
11599 (with-current-buffer buf
11600 (save-excursion
11601 (save-restriction
11602 (goto-char pos)
11603 (setq cnt (1+ cnt))
11604 (org-toggle-tag tag (if off 'off 'on))
11605 (setq newhead (org-get-heading)))))
11606 (and agendap (org-agenda-change-all-lines newhead m))))
11607 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11609 (defun org-tags-completion-function (string predicate &optional flag)
11610 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11611 (confirm (lambda (x) (stringp (car x)))))
11612 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11613 (setq s1 (match-string 1 string)
11614 s2 (match-string 2 string))
11615 (setq s1 "" s2 string))
11616 (cond
11617 ((eq flag nil)
11618 ;; try completion
11619 (setq rtn (try-completion s2 ctable confirm))
11620 (if (stringp rtn)
11621 (setq rtn
11622 (concat s1 s2 (substring rtn (length s2))
11623 (if (and org-add-colon-after-tag-completion
11624 (assoc rtn ctable))
11625 ":" ""))))
11626 rtn)
11627 ((eq flag t)
11628 ;; all-completions
11629 (all-completions s2 ctable confirm)
11631 ((eq flag 'lambda)
11632 ;; exact match?
11633 (assoc s2 ctable)))
11636 (defun org-fast-tag-insert (kwd tags face &optional end)
11637 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11638 (insert (format "%-12s" (concat kwd ":"))
11639 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11640 (or end "")))
11642 (defun org-fast-tag-show-exit (flag)
11643 (save-excursion
11644 (org-goto-line 3)
11645 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11646 (replace-match ""))
11647 (when flag
11648 (end-of-line 1)
11649 (org-move-to-column (- (window-width) 19) t)
11650 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11652 (defun org-set-current-tags-overlay (current prefix)
11653 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11654 (if (featurep 'xemacs)
11655 (org-overlay-display org-tags-overlay (concat prefix s)
11656 'secondary-selection)
11657 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11658 (org-overlay-display org-tags-overlay (concat prefix s)))))
11660 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11661 "Fast tag selection with single keys.
11662 CURRENT is the current list of tags in the headline, INHERITED is the
11663 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11664 possibly with grouping information. TODO-TABLE is a similar table with
11665 TODO keywords, should these have keys assigned to them.
11666 If the keys are nil, a-z are automatically assigned.
11667 Returns the new tags string, or nil to not change the current settings."
11668 (let* ((fulltable (append table todo-table))
11669 (maxlen (apply 'max (mapcar
11670 (lambda (x)
11671 (if (stringp (car x)) (string-width (car x)) 0))
11672 fulltable)))
11673 (buf (current-buffer))
11674 (expert (eq org-fast-tag-selection-single-key 'expert))
11675 (buffer-tags nil)
11676 (fwidth (+ maxlen 3 1 3))
11677 (ncol (/ (- (window-width) 4) fwidth))
11678 (i-face 'org-done)
11679 (c-face 'org-todo)
11680 tg cnt e c char c1 c2 ntable tbl rtn
11681 ov-start ov-end ov-prefix
11682 (exit-after-next org-fast-tag-selection-single-key)
11683 (done-keywords org-done-keywords)
11684 groups ingroup)
11685 (save-excursion
11686 (beginning-of-line 1)
11687 (if (looking-at
11688 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11689 (setq ov-start (match-beginning 1)
11690 ov-end (match-end 1)
11691 ov-prefix "")
11692 (setq ov-start (1- (point-at-eol))
11693 ov-end (1+ ov-start))
11694 (skip-chars-forward "^\n\r")
11695 (setq ov-prefix
11696 (concat
11697 (buffer-substring (1- (point)) (point))
11698 (if (> (current-column) org-tags-column)
11700 (make-string (- org-tags-column (current-column)) ?\ ))))))
11701 (org-move-overlay org-tags-overlay ov-start ov-end)
11702 (save-window-excursion
11703 (if expert
11704 (set-buffer (get-buffer-create " *Org tags*"))
11705 (delete-other-windows)
11706 (split-window-vertically)
11707 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11708 (erase-buffer)
11709 (org-set-local 'org-done-keywords done-keywords)
11710 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11711 (org-fast-tag-insert "Current" current c-face "\n\n")
11712 (org-fast-tag-show-exit exit-after-next)
11713 (org-set-current-tags-overlay current ov-prefix)
11714 (setq tbl fulltable char ?a cnt 0)
11715 (while (setq e (pop tbl))
11716 (cond
11717 ((equal (car e) :startgroup)
11718 (push '() groups) (setq ingroup t)
11719 (when (not (= cnt 0))
11720 (setq cnt 0)
11721 (insert "\n"))
11722 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
11723 ((equal (car e) :endgroup)
11724 (setq ingroup nil cnt 0)
11725 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
11726 ((equal e '(:newline))
11727 (when (not (= cnt 0))
11728 (setq cnt 0)
11729 (insert "\n")
11730 (setq e (car tbl))
11731 (while (equal (car tbl) '(:newline))
11732 (insert "\n")
11733 (setq tbl (cdr tbl)))))
11735 (setq tg (copy-sequence (car e)) c2 nil)
11736 (if (cdr e)
11737 (setq c (cdr e))
11738 ;; automatically assign a character.
11739 (setq c1 (string-to-char
11740 (downcase (substring
11741 tg (if (= (string-to-char tg) ?@) 1 0)))))
11742 (if (or (rassoc c1 ntable) (rassoc c1 table))
11743 (while (or (rassoc char ntable) (rassoc char table))
11744 (setq char (1+ char)))
11745 (setq c2 c1))
11746 (setq c (or c2 char)))
11747 (if ingroup (push tg (car groups)))
11748 (setq tg (org-add-props tg nil 'face
11749 (cond
11750 ((not (assoc tg table))
11751 (org-get-todo-face tg))
11752 ((member tg current) c-face)
11753 ((member tg inherited) i-face)
11754 (t nil))))
11755 (if (and (= cnt 0) (not ingroup)) (insert " "))
11756 (insert "[" c "] " tg (make-string
11757 (- fwidth 4 (length tg)) ?\ ))
11758 (push (cons tg c) ntable)
11759 (when (= (setq cnt (1+ cnt)) ncol)
11760 (insert "\n")
11761 (if ingroup (insert " "))
11762 (setq cnt 0)))))
11763 (setq ntable (nreverse ntable))
11764 (insert "\n")
11765 (goto-char (point-min))
11766 (if (not expert) (org-fit-window-to-buffer))
11767 (setq rtn
11768 (catch 'exit
11769 (while t
11770 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
11771 (if (not groups) "no " "")
11772 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11773 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11774 (cond
11775 ((= c ?\r) (throw 'exit t))
11776 ((= c ?!)
11777 (setq groups (not groups))
11778 (goto-char (point-min))
11779 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11780 ((= c ?\C-c)
11781 (if (not expert)
11782 (org-fast-tag-show-exit
11783 (setq exit-after-next (not exit-after-next)))
11784 (setq expert nil)
11785 (delete-other-windows)
11786 (split-window-vertically)
11787 (org-switch-to-buffer-other-window " *Org tags*")
11788 (org-fit-window-to-buffer)))
11789 ((or (= c ?\C-g)
11790 (and (= c ?q) (not (rassoc c ntable))))
11791 (org-detach-overlay org-tags-overlay)
11792 (setq quit-flag t))
11793 ((= c ?\ )
11794 (setq current nil)
11795 (if exit-after-next (setq exit-after-next 'now)))
11796 ((= c ?\t)
11797 (condition-case nil
11798 (setq tg (org-icompleting-read
11799 "Tag: "
11800 (or buffer-tags
11801 (with-current-buffer buf
11802 (org-get-buffer-tags)))))
11803 (quit (setq tg "")))
11804 (when (string-match "\\S-" tg)
11805 (add-to-list 'buffer-tags (list tg))
11806 (if (member tg current)
11807 (setq current (delete tg current))
11808 (push tg current)))
11809 (if exit-after-next (setq exit-after-next 'now)))
11810 ((setq e (rassoc c todo-table) tg (car e))
11811 (with-current-buffer buf
11812 (save-excursion (org-todo tg)))
11813 (if exit-after-next (setq exit-after-next 'now)))
11814 ((setq e (rassoc c ntable) tg (car e))
11815 (if (member tg current)
11816 (setq current (delete tg current))
11817 (loop for g in groups do
11818 (if (member tg g)
11819 (mapc (lambda (x)
11820 (setq current (delete x current)))
11821 g)))
11822 (push tg current))
11823 (if exit-after-next (setq exit-after-next 'now))))
11825 ;; Create a sorted list
11826 (setq current
11827 (sort current
11828 (lambda (a b)
11829 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11830 (if (eq exit-after-next 'now) (throw 'exit t))
11831 (goto-char (point-min))
11832 (beginning-of-line 2)
11833 (delete-region (point) (point-at-eol))
11834 (org-fast-tag-insert "Current" current c-face)
11835 (org-set-current-tags-overlay current ov-prefix)
11836 (while (re-search-forward
11837 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11838 (setq tg (match-string 1))
11839 (add-text-properties
11840 (match-beginning 1) (match-end 1)
11841 (list 'face
11842 (cond
11843 ((member tg current) c-face)
11844 ((member tg inherited) i-face)
11845 (t (get-text-property (match-beginning 1) 'face))))))
11846 (goto-char (point-min)))))
11847 (org-detach-overlay org-tags-overlay)
11848 (if rtn
11849 (mapconcat 'identity current ":")
11850 nil))))
11852 (defun org-get-tags-string ()
11853 "Get the TAGS string in the current headline."
11854 (unless (org-on-heading-p t)
11855 (error "Not on a heading"))
11856 (save-excursion
11857 (beginning-of-line 1)
11858 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11859 (org-match-string-no-properties 1)
11860 "")))
11862 (defun org-get-tags ()
11863 "Get the list of tags specified in the current headline."
11864 (org-split-string (org-get-tags-string) ":"))
11866 (defun org-get-buffer-tags ()
11867 "Get a table of all tags used in the buffer, for completion."
11868 (let (tags)
11869 (save-excursion
11870 (goto-char (point-min))
11871 (while (re-search-forward
11872 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11873 (when (equal (char-after (point-at-bol 0)) ?*)
11874 (mapc (lambda (x) (add-to-list 'tags x))
11875 (org-split-string (org-match-string-no-properties 1) ":")))))
11876 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
11877 (mapcar 'list tags)))
11879 ;;;; The mapping API
11881 ;;;###autoload
11882 (defun org-map-entries (func &optional match scope &rest skip)
11883 "Call FUNC at each headline selected by MATCH in SCOPE.
11885 FUNC is a function or a lisp form. The function will be called without
11886 arguments, with the cursor positioned at the beginning of the headline.
11887 The return values of all calls to the function will be collected and
11888 returned as a list.
11890 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11891 does not need to preserve point. After evaluation, the cursor will be
11892 moved to the end of the line (presumably of the headline of the
11893 processed entry) and search continues from there. Under some
11894 circumstances, this may not produce the wanted results. For example,
11895 if you have removed (e.g. archived) the current (sub)tree it could
11896 mean that the next entry will be skipped entirely. In such cases, you
11897 can specify the position from where search should continue by making
11898 FUNC set the variable `org-map-continue-from' to the desired buffer
11899 position.
11901 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11902 Only headlines that are matched by this query will be considered during
11903 the iteration. When MATCH is nil or t, all headlines will be
11904 visited by the iteration.
11906 SCOPE determines the scope of this command. It can be any of:
11908 nil The current buffer, respecting the restriction if any
11909 tree The subtree started with the entry at point
11910 file The current buffer, without restriction
11911 file-with-archives
11912 The current buffer, and any archives associated with it
11913 agenda All agenda files
11914 agenda-with-archives
11915 All agenda files with any archive files associated with them
11916 \(file1 file2 ...)
11917 If this is a list, all files in the list will be scanned
11919 The remaining args are treated as settings for the skipping facilities of
11920 the scanner. The following items can be given here:
11922 archive skip trees with the archive tag.
11923 comment skip trees with the COMMENT keyword
11924 function or Emacs Lisp form:
11925 will be used as value for `org-agenda-skip-function', so whenever
11926 the function returns t, FUNC will not be called for that
11927 entry and search will continue from the point where the
11928 function leaves it.
11930 If your function needs to retrieve the tags including inherited tags
11931 at the *current* entry, you can use the value of the variable
11932 `org-scanner-tags' which will be much faster than getting the value
11933 with `org-get-tags-at'. If your function gets properties with
11934 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11935 to t around the call to `org-entry-properties' to get the same speedup.
11936 Note that if your function moves around to retrieve tags and properties at
11937 a *different* entry, you cannot use these techniques."
11938 (let* ((org-agenda-archives-mode nil) ; just to make sure
11939 (org-agenda-skip-archived-trees (memq 'archive skip))
11940 (org-agenda-skip-comment-trees (memq 'comment skip))
11941 (org-agenda-skip-function
11942 (car (org-delete-all '(comment archive) skip)))
11943 (org-tags-match-list-sublevels t)
11944 matcher file res
11945 org-todo-keywords-for-agenda
11946 org-done-keywords-for-agenda
11947 org-todo-keyword-alist-for-agenda
11948 org-drawers-for-agenda
11949 org-tag-alist-for-agenda)
11951 (cond
11952 ((eq match t) (setq matcher t))
11953 ((eq match nil) (setq matcher t))
11954 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11956 (save-excursion
11957 (save-restriction
11958 (when (eq scope 'tree)
11959 (org-back-to-heading t)
11960 (org-narrow-to-subtree)
11961 (setq scope nil))
11963 (if (not scope)
11964 (progn
11965 (org-prepare-agenda-buffers
11966 (list (buffer-file-name (current-buffer))))
11967 (setq res (org-scan-tags func matcher)))
11968 ;; Get the right scope
11969 (cond
11970 ((and scope (listp scope) (symbolp (car scope)))
11971 (setq scope (eval scope)))
11972 ((eq scope 'agenda)
11973 (setq scope (org-agenda-files t)))
11974 ((eq scope 'agenda-with-archives)
11975 (setq scope (org-agenda-files t))
11976 (setq scope (org-add-archive-files scope)))
11977 ((eq scope 'file)
11978 (setq scope (list (buffer-file-name))))
11979 ((eq scope 'file-with-archives)
11980 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11981 (org-prepare-agenda-buffers scope)
11982 (while (setq file (pop scope))
11983 (with-current-buffer (org-find-base-buffer-visiting file)
11984 (save-excursion
11985 (save-restriction
11986 (widen)
11987 (goto-char (point-min))
11988 (setq res (append res (org-scan-tags func matcher))))))))))
11989 res))
11991 ;;;; Properties
11993 ;;; Setting and retrieving properties
11995 (defconst org-special-properties
11996 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11997 "TIMESTAMP" "TIMESTAMP_IA")
11998 "The special properties valid in Org-mode.
12000 These are properties that are not defined in the property drawer,
12001 but in some other way.")
12003 (defconst org-default-properties
12004 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12005 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12006 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12007 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12008 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12009 "CLOCK_MODELINE_TOTAL" "STYLE")
12010 "Some properties that are used by Org-mode for various purposes.
12011 Being in this list makes sure that they are offered for completion.")
12013 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12014 "Regular expression matching the first line of a property drawer.")
12016 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12017 "Regular expression matching the first line of a property drawer.")
12019 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12020 "Regular expression matching the first line of a property drawer.")
12022 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12023 "Regular expression matching the first line of a property drawer.")
12025 (defconst org-property-drawer-re
12026 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12027 org-property-end-re "\\)\n?")
12028 "Matches an entire property drawer.")
12030 (defconst org-clock-drawer-re
12031 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12032 org-property-end-re "\\)\n?")
12033 "Matches an entire clock drawer.")
12035 (defun org-property-action ()
12036 "Do an action on properties."
12037 (interactive)
12038 (let (c)
12039 (org-at-property-p)
12040 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12041 (setq c (read-char-exclusive))
12042 (cond
12043 ((equal c ?s)
12044 (call-interactively 'org-set-property))
12045 ((equal c ?d)
12046 (call-interactively 'org-delete-property))
12047 ((equal c ?D)
12048 (call-interactively 'org-delete-property-globally))
12049 ((equal c ?c)
12050 (call-interactively 'org-compute-property-at-point))
12051 (t (error "No such property action %c" c)))))
12053 (defun org-set-effort (&optional value)
12054 "Set the effort property of the current entry.
12055 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12056 allowed value."
12057 (interactive "P")
12058 (if (equal value 0) (setq value 10))
12059 (let* ((completion-ignore-case t)
12060 (prop org-effort-property)
12061 (cur (org-entry-get nil prop))
12062 (allowed (org-property-get-allowed-values nil prop 'table))
12063 (existing (mapcar 'list (org-property-values prop)))
12065 (val (cond
12066 ((stringp value) value)
12067 ((and allowed (integerp value))
12068 (or (car (nth (1- value) allowed))
12069 (car (org-last allowed))))
12070 (allowed
12071 (message "Select 1-9,0, [RET%s]: %s"
12072 (if cur (concat "=" cur) "")
12073 (mapconcat 'car allowed " "))
12074 (setq rpl (read-char-exclusive))
12075 (if (equal rpl ?\r)
12077 (setq rpl (- rpl ?0))
12078 (if (equal rpl 0) (setq rpl 10))
12079 (if (and (> rpl 0) (<= rpl (length allowed)))
12080 (car (nth (1- rpl) allowed))
12081 (org-completing-read "Value: " allowed nil))))
12083 (let (org-completion-use-ido org-completion-use-iswitchb)
12084 (org-completing-read
12085 (concat "Value " (if (and cur (string-match "\\S-" cur))
12086 (concat "[" cur "]") "")
12087 ": ")
12088 existing nil nil "" nil cur))))))
12089 (unless (equal (org-entry-get nil prop) val)
12090 (org-entry-put nil prop val))
12091 (message "%s is now %s" prop val)))
12093 (defun org-at-property-p ()
12094 "Is the cursor in a property line?"
12095 ;; FIXME: Does not check if we are actually in the drawer.
12096 ;; FIXME: also returns true on any drawers.....
12097 ;; This is used by C-c C-c for property action.
12098 (save-excursion
12099 (beginning-of-line 1)
12100 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
12102 (defun org-get-property-block (&optional beg end force)
12103 "Return the (beg . end) range of the body of the property drawer.
12104 BEG and END can be beginning and end of subtree, if not given
12105 they will be found.
12106 If the drawer does not exist and FORCE is non-nil, create the drawer."
12107 (catch 'exit
12108 (save-excursion
12109 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12110 (end (or end (progn (outline-next-heading) (point)))))
12111 (goto-char beg)
12112 (if (re-search-forward org-property-start-re end t)
12113 (setq beg (1+ (match-end 0)))
12114 (if force
12115 (save-excursion
12116 (org-insert-property-drawer)
12117 (setq end (progn (outline-next-heading) (point))))
12118 (throw 'exit nil))
12119 (goto-char beg)
12120 (if (re-search-forward org-property-start-re end t)
12121 (setq beg (1+ (match-end 0)))))
12122 (if (re-search-forward org-property-end-re end t)
12123 (setq end (match-beginning 0))
12124 (or force (throw 'exit nil))
12125 (goto-char beg)
12126 (setq end beg)
12127 (org-indent-line-function)
12128 (insert ":END:\n"))
12129 (cons beg end)))))
12131 (defun org-entry-properties (&optional pom which)
12132 "Get all properties of the entry at point-or-marker POM.
12133 This includes the TODO keyword, the tags, time strings for deadline,
12134 scheduled, and clocking, and any additional properties defined in the
12135 entry. The return value is an alist, keys may occur multiple times
12136 if the property key was used several times.
12137 POM may also be nil, in which case the current entry is used.
12138 If WHICH is nil or `all', get all properties. If WHICH is
12139 `special' or `standard', only get that subclass."
12140 (setq which (or which 'all))
12141 (org-with-point-at pom
12142 (let ((clockstr (substring org-clock-string 0 -1))
12143 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
12144 beg end range props sum-props key value string clocksum)
12145 (save-excursion
12146 (when (condition-case nil
12147 (and (org-mode-p) (org-back-to-heading t))
12148 (error nil))
12149 (setq beg (point))
12150 (setq sum-props (get-text-property (point) 'org-summaries))
12151 (setq clocksum (get-text-property (point) :org-clock-minutes))
12152 (outline-next-heading)
12153 (setq end (point))
12154 (when (memq which '(all special))
12155 ;; Get the special properties, like TODO and tags
12156 (goto-char beg)
12157 (when (and (looking-at org-todo-line-regexp) (match-end 2))
12158 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12159 (when (looking-at org-priority-regexp)
12160 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12161 (when (and (setq value (org-get-tags-string))
12162 (string-match "\\S-" value))
12163 (push (cons "TAGS" value) props))
12164 (when (setq value (org-get-tags-at))
12165 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
12166 props))
12167 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12168 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12169 string (if (equal key clockstr)
12170 (org-no-properties
12171 (org-trim
12172 (buffer-substring
12173 (match-beginning 3) (goto-char (point-at-eol)))))
12174 (substring (org-match-string-no-properties 3) 1 -1)))
12175 (unless key
12176 (if (= (char-after (match-beginning 3)) ?\[)
12177 (setq key "TIMESTAMP_IA")
12178 (setq key "TIMESTAMP")))
12179 (when (or (equal key clockstr) (not (assoc key props)))
12180 (push (cons key string) props)))
12184 (when (memq which '(all standard))
12185 ;; Get the standard properties, like :PROP: ...
12186 (setq range (org-get-property-block beg end))
12187 (when range
12188 (goto-char (car range))
12189 (while (re-search-forward
12190 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12191 (cdr range) t)
12192 (setq key (org-match-string-no-properties 1)
12193 value (org-trim (or (org-match-string-no-properties 2) "")))
12194 (unless (member key excluded)
12195 (push (cons key (or value "")) props)))))
12196 (if clocksum
12197 (push (cons "CLOCKSUM"
12198 (org-columns-number-to-string (/ (float clocksum) 60.)
12199 'add_times))
12200 props))
12201 (unless (assoc "CATEGORY" props)
12202 (setq value (or (org-get-category)
12203 (progn (org-refresh-category-properties)
12204 (org-get-category))))
12205 (push (cons "CATEGORY" value) props))
12206 (append sum-props (nreverse props)))))))
12208 (defun org-entry-get (pom property &optional inherit)
12209 "Get value of PROPERTY for entry at point-or-marker POM.
12210 If INHERIT is non-nil and the entry does not have the property,
12211 then also check higher levels of the hierarchy.
12212 If INHERIT is the symbol `selective', use inheritance only if the setting
12213 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12214 If the property is present but empty, the return value is the empty string.
12215 If the property is not present at all, nil is returned."
12216 (org-with-point-at pom
12217 (if (and inherit (if (eq inherit 'selective)
12218 (org-property-inherit-p property)
12220 (org-entry-get-with-inheritance property)
12221 (if (member property org-special-properties)
12222 ;; We need a special property. Use brute force, get all properties.
12223 (cdr (assoc property (org-entry-properties nil 'special)))
12224 (let ((range (org-get-property-block)))
12225 (if (and range
12226 (goto-char (car range))
12227 (re-search-forward
12228 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12229 (cdr range) t))
12230 ;; Found the property, return it.
12231 (if (match-end 1)
12232 (org-match-string-no-properties 1)
12233 "")))))))
12235 (defun org-property-or-variable-value (var &optional inherit)
12236 "Check if there is a property fixing the value of VAR.
12237 If yes, return this value. If not, return the current value of the variable."
12238 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12239 (if (and prop (stringp prop) (string-match "\\S-" prop))
12240 (read prop)
12241 (symbol-value var))))
12243 (defun org-entry-delete (pom property)
12244 "Delete the property PROPERTY from entry at point-or-marker POM."
12245 (org-with-point-at pom
12246 (if (member property org-special-properties)
12247 nil ; cannot delete these properties.
12248 (let ((range (org-get-property-block)))
12249 (if (and range
12250 (goto-char (car range))
12251 (re-search-forward
12252 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12253 (cdr range) t))
12254 (progn
12255 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12257 nil)))))
12259 ;; Multi-values properties are properties that contain multiple values
12260 ;; These values are assumed to be single words, separated by whitespace.
12261 (defun org-entry-add-to-multivalued-property (pom property value)
12262 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12263 (let* ((old (org-entry-get pom property))
12264 (values (and old (org-split-string old "[ \t]"))))
12265 (setq value (org-entry-protect-space value))
12266 (unless (member value values)
12267 (setq values (cons value values))
12268 (org-entry-put pom property
12269 (mapconcat 'identity values " ")))))
12271 (defun org-entry-remove-from-multivalued-property (pom property value)
12272 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12273 (let* ((old (org-entry-get pom property))
12274 (values (and old (org-split-string old "[ \t]"))))
12275 (setq value (org-entry-protect-space value))
12276 (when (member value values)
12277 (setq values (delete value values))
12278 (org-entry-put pom property
12279 (mapconcat 'identity values " ")))))
12281 (defun org-entry-member-in-multivalued-property (pom property value)
12282 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12283 (let* ((old (org-entry-get pom property))
12284 (values (and old (org-split-string old "[ \t]"))))
12285 (setq value (org-entry-protect-space value))
12286 (member value values)))
12288 (defun org-entry-get-multivalued-property (pom property)
12289 "Return a list of values in a multivalued property."
12290 (let* ((value (org-entry-get pom property))
12291 (values (and value (org-split-string value "[ \t]"))))
12292 (mapcar 'org-entry-restore-space values)))
12294 (defun org-entry-put-multivalued-property (pom property &rest values)
12295 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12296 VALUES should be a list of strings. Spaces will be protected."
12297 (org-entry-put pom property
12298 (mapconcat 'org-entry-protect-space values " "))
12299 (let* ((value (org-entry-get pom property))
12300 (values (and value (org-split-string value "[ \t]"))))
12301 (mapcar 'org-entry-restore-space values)))
12303 (defun org-entry-protect-space (s)
12304 "Protect spaces and newline in string S."
12305 (while (string-match " " s)
12306 (setq s (replace-match "%20" t t s)))
12307 (while (string-match "\n" s)
12308 (setq s (replace-match "%0A" t t s)))
12311 (defun org-entry-restore-space (s)
12312 "Restore spaces and newline in string S."
12313 (while (string-match "%20" s)
12314 (setq s (replace-match " " t t s)))
12315 (while (string-match "%0A" s)
12316 (setq s (replace-match "\n" t t s)))
12319 (defvar org-entry-property-inherited-from (make-marker)
12320 "Marker pointing to the entry from where a property was inherited.
12321 Each call to `org-entry-get-with-inheritance' will set this marker to the
12322 location of the entry where the inheritance search matched. If there was
12323 no match, the marker will point nowhere.
12324 Note that also `org-entry-get' calls this function, if the INHERIT flag
12325 is set.")
12327 (defun org-entry-get-with-inheritance (property)
12328 "Get entry property, and search higher levels if not present."
12329 (move-marker org-entry-property-inherited-from nil)
12330 (let (tmp)
12331 (save-excursion
12332 (save-restriction
12333 (widen)
12334 (catch 'ex
12335 (while t
12336 (when (setq tmp (org-entry-get nil property))
12337 (org-back-to-heading t)
12338 (move-marker org-entry-property-inherited-from (point))
12339 (throw 'ex tmp))
12340 (or (org-up-heading-safe) (throw 'ex nil)))))
12341 (or tmp
12342 (cdr (assoc property org-file-properties))
12343 (cdr (assoc property org-global-properties))
12344 (cdr (assoc property org-global-properties-fixed))))))
12346 (defun org-entry-put (pom property value)
12347 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12348 (org-with-point-at pom
12349 (org-back-to-heading t)
12350 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12351 range)
12352 (cond
12353 ((equal property "TODO")
12354 (when (and (stringp value) (string-match "\\S-" value)
12355 (not (member value org-todo-keywords-1)))
12356 (error "\"%s\" is not a valid TODO state" value))
12357 (if (or (not value)
12358 (not (string-match "\\S-" value)))
12359 (setq value 'none))
12360 (org-todo value)
12361 (org-set-tags nil 'align))
12362 ((equal property "PRIORITY")
12363 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12364 (string-to-char value) ?\ ))
12365 (org-set-tags nil 'align))
12366 ((equal property "SCHEDULED")
12367 (if (re-search-forward org-scheduled-time-regexp end t)
12368 (cond
12369 ((eq value 'earlier) (org-timestamp-change -1 'day))
12370 ((eq value 'later) (org-timestamp-change 1 'day))
12371 (t (call-interactively 'org-schedule)))
12372 (call-interactively 'org-schedule)))
12373 ((equal property "DEADLINE")
12374 (if (re-search-forward org-deadline-time-regexp end t)
12375 (cond
12376 ((eq value 'earlier) (org-timestamp-change -1 'day))
12377 ((eq value 'later) (org-timestamp-change 1 'day))
12378 (t (call-interactively 'org-deadline)))
12379 (call-interactively 'org-deadline)))
12380 ((member property org-special-properties)
12381 (error "The %s property can not yet be set with `org-entry-put'"
12382 property))
12383 (t ; a non-special property
12384 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12385 (setq range (org-get-property-block beg end 'force))
12386 (goto-char (car range))
12387 (if (re-search-forward
12388 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12389 (progn
12390 (delete-region (match-beginning 1) (match-end 1))
12391 (goto-char (match-beginning 1)))
12392 (goto-char (cdr range))
12393 (insert "\n")
12394 (backward-char 1)
12395 (org-indent-line-function)
12396 (insert ":" property ":"))
12397 (and value (insert " " value))
12398 (org-indent-line-function)))))))
12400 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12401 "Get all property keys in the current buffer.
12402 With INCLUDE-SPECIALS, also list the special properties that reflect things
12403 like tags and TODO state.
12404 With INCLUDE-DEFAULTS, also include properties that has special meaning
12405 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12406 With INCLUDE-COLUMNS, also include property names given in COLUMN
12407 formats in the current buffer."
12408 (let (rtn range cfmt s p)
12409 (save-excursion
12410 (save-restriction
12411 (widen)
12412 (goto-char (point-min))
12413 (while (re-search-forward org-property-start-re nil t)
12414 (setq range (org-get-property-block))
12415 (goto-char (car range))
12416 (while (re-search-forward
12417 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12418 (cdr range) t)
12419 (add-to-list 'rtn (org-match-string-no-properties 1)))
12420 (outline-next-heading))))
12422 (when include-specials
12423 (setq rtn (append org-special-properties rtn)))
12425 (when include-defaults
12426 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12427 (add-to-list 'rtn org-effort-property))
12429 (when include-columns
12430 (save-excursion
12431 (save-restriction
12432 (widen)
12433 (goto-char (point-min))
12434 (while (re-search-forward
12435 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12436 nil t)
12437 (setq cfmt (match-string 2) s 0)
12438 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12439 cfmt s)
12440 (setq s (match-end 0)
12441 p (match-string 1 cfmt))
12442 (unless (or (equal p "ITEM")
12443 (member p org-special-properties))
12444 (add-to-list 'rtn (match-string 1 cfmt))))))))
12446 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12448 (defun org-property-values (key)
12449 "Return a list of all values of property KEY."
12450 (save-excursion
12451 (save-restriction
12452 (widen)
12453 (goto-char (point-min))
12454 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12455 values)
12456 (while (re-search-forward re nil t)
12457 (add-to-list 'values (org-trim (match-string 1))))
12458 (delete "" values)))))
12460 (defun org-insert-property-drawer ()
12461 "Insert a property drawer into the current entry."
12462 (interactive)
12463 (org-back-to-heading t)
12464 (looking-at outline-regexp)
12465 (let ((indent (if org-adapt-indentation
12466 (- (match-end 0)(match-beginning 0))
12468 (beg (point))
12469 (re (concat "^[ \t]*" org-keyword-time-regexp))
12470 end hiddenp)
12471 (outline-next-heading)
12472 (setq end (point))
12473 (goto-char beg)
12474 (while (re-search-forward re end t))
12475 (setq hiddenp (org-invisible-p))
12476 (end-of-line 1)
12477 (and (equal (char-after) ?\n) (forward-char 1))
12478 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12479 (if (member (match-string 1) '("CLOCK:" ":END:"))
12480 ;; just skip this line
12481 (beginning-of-line 2)
12482 ;; Drawer start, find the end
12483 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12484 (beginning-of-line 1)))
12485 (org-skip-over-state-notes)
12486 (skip-chars-backward " \t\n\r")
12487 (if (eq (char-before) ?*) (forward-char 1))
12488 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12489 (beginning-of-line 0)
12490 (org-indent-to-column indent)
12491 (beginning-of-line 2)
12492 (org-indent-to-column indent)
12493 (beginning-of-line 0)
12494 (if hiddenp
12495 (save-excursion
12496 (org-back-to-heading t)
12497 (hide-entry))
12498 (org-flag-drawer t))))
12500 (defun org-set-property (property value)
12501 "In the current entry, set PROPERTY to VALUE.
12502 When called interactively, this will prompt for a property name, offering
12503 completion on existing and default properties. And then it will prompt
12504 for a value, offering completion either on allowed values (via an inherited
12505 xxx_ALL property) or on existing values in other instances of this property
12506 in the current file."
12507 (interactive
12508 (let* ((completion-ignore-case t)
12509 (keys (org-buffer-property-keys nil t t))
12510 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12511 (prop (if (member prop0 keys)
12512 prop0
12513 (or (cdr (assoc (downcase prop0)
12514 (mapcar (lambda (x) (cons (downcase x) x))
12515 keys)))
12516 prop0)))
12517 (cur (org-entry-get nil prop))
12518 (allowed (org-property-get-allowed-values nil prop 'table))
12519 (existing (mapcar 'list (org-property-values prop)))
12520 (val (if allowed
12521 (org-completing-read "Value: " allowed nil 'req-match)
12522 (let (org-completion-use-ido org-completion-use-iswitchb)
12523 (org-completing-read
12524 (concat "Value " (if (and cur (string-match "\\S-" cur))
12525 (concat "[" cur "]") "")
12526 ": ")
12527 existing nil nil "" nil cur)))))
12528 (list prop (if (equal val "") cur val))))
12529 (unless (equal (org-entry-get nil property) value)
12530 (org-entry-put nil property value)))
12532 (defun org-delete-property (property)
12533 "In the current entry, delete PROPERTY."
12534 (interactive
12535 (let* ((completion-ignore-case t)
12536 (prop (org-icompleting-read
12537 "Property: " (org-entry-properties nil 'standard))))
12538 (list prop)))
12539 (message "Property %s %s" property
12540 (if (org-entry-delete nil property)
12541 "deleted"
12542 "was not present in the entry")))
12544 (defun org-delete-property-globally (property)
12545 "Remove PROPERTY globally, from all entries."
12546 (interactive
12547 (let* ((completion-ignore-case t)
12548 (prop (org-icompleting-read
12549 "Globally remove property: "
12550 (mapcar 'list (org-buffer-property-keys)))))
12551 (list prop)))
12552 (save-excursion
12553 (save-restriction
12554 (widen)
12555 (goto-char (point-min))
12556 (let ((cnt 0))
12557 (while (re-search-forward
12558 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12559 nil t)
12560 (setq cnt (1+ cnt))
12561 (replace-match ""))
12562 (message "Property \"%s\" removed from %d entries" property cnt)))))
12564 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12566 (defun org-compute-property-at-point ()
12567 "Compute the property at point.
12568 This looks for an enclosing column format, extracts the operator and
12569 then applies it to the property in the column format's scope."
12570 (interactive)
12571 (unless (org-at-property-p)
12572 (error "Not at a property"))
12573 (let ((prop (org-match-string-no-properties 2)))
12574 (org-columns-get-format-and-top-level)
12575 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12576 (error "No operator defined for property %s" prop))
12577 (org-columns-compute prop)))
12579 (defun org-property-get-allowed-values (pom property &optional table)
12580 "Get allowed values for the property PROPERTY.
12581 When TABLE is non-nil, return an alist that can directly be used for
12582 completion."
12583 (let (vals)
12584 (cond
12585 ((equal property "TODO")
12586 (setq vals (org-with-point-at pom
12587 (append org-todo-keywords-1 '("")))))
12588 ((equal property "PRIORITY")
12589 (let ((n org-lowest-priority))
12590 (while (>= n org-highest-priority)
12591 (push (char-to-string n) vals)
12592 (setq n (1- n)))))
12593 ((member property org-special-properties))
12595 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12597 (when (and vals (string-match "\\S-" vals))
12598 (setq vals (car (read-from-string (concat "(" vals ")"))))
12599 (setq vals (mapcar (lambda (x)
12600 (cond ((stringp x) x)
12601 ((numberp x) (number-to-string x))
12602 ((symbolp x) (symbol-name x))
12603 (t "???")))
12604 vals)))))
12605 (if table (mapcar 'list vals) vals)))
12607 (defun org-property-previous-allowed-value (&optional previous)
12608 "Switch to the next allowed value for this property."
12609 (interactive)
12610 (org-property-next-allowed-value t))
12612 (defun org-property-next-allowed-value (&optional previous)
12613 "Switch to the next allowed value for this property."
12614 (interactive)
12615 (unless (org-at-property-p)
12616 (error "Not at a property"))
12617 (let* ((key (match-string 2))
12618 (value (match-string 3))
12619 (allowed (or (org-property-get-allowed-values (point) key)
12620 (and (member value '("[ ]" "[-]" "[X]"))
12621 '("[ ]" "[X]"))))
12622 nval)
12623 (unless allowed
12624 (error "Allowed values for this property have not been defined"))
12625 (if previous (setq allowed (reverse allowed)))
12626 (if (member value allowed)
12627 (setq nval (car (cdr (member value allowed)))))
12628 (setq nval (or nval (car allowed)))
12629 (if (equal nval value)
12630 (error "Only one allowed value for this property"))
12631 (org-at-property-p)
12632 (replace-match (concat " :" key ": " nval) t t)
12633 (org-indent-line-function)
12634 (beginning-of-line 1)
12635 (skip-chars-forward " \t")))
12637 (defun org-find-entry-with-id (ident)
12638 "Locate the entry that contains the ID property with exact value IDENT.
12639 IDENT can be a string, a symbol or a number, this function will search for
12640 the string representation of it.
12641 Return the position where this entry starts, or nil if there is no such entry."
12642 (interactive "sID: ")
12643 (let ((id (cond
12644 ((stringp ident) ident)
12645 ((symbol-name ident) (symbol-name ident))
12646 ((numberp ident) (number-to-string ident))
12647 (t (error "IDENT %s must be a string, symbol or number" ident))))
12648 (case-fold-search nil))
12649 (save-excursion
12650 (save-restriction
12651 (widen)
12652 (goto-char (point-min))
12653 (when (re-search-forward
12654 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12655 nil t)
12656 (org-back-to-heading t)
12657 (point))))))
12659 ;;;; Timestamps
12661 (defvar org-last-changed-timestamp nil)
12662 (defvar org-last-inserted-timestamp nil
12663 "The last time stamp inserted with `org-insert-time-stamp'.")
12664 (defvar org-time-was-given) ; dynamically scoped parameter
12665 (defvar org-end-time-was-given) ; dynamically scoped parameter
12666 (defvar org-ts-what) ; dynamically scoped parameter
12668 (defun org-time-stamp (arg &optional inactive)
12669 "Prompt for a date/time and insert a time stamp.
12670 If the user specifies a time like HH:MM, or if this command is called
12671 with a prefix argument, the time stamp will contain date and time.
12672 Otherwise, only the date will be included. All parts of a date not
12673 specified by the user will be filled in from the current date/time.
12674 So if you press just return without typing anything, the time stamp
12675 will represent the current date/time. If there is already a timestamp
12676 at the cursor, it will be modified."
12677 (interactive "P")
12678 (let* ((ts nil)
12679 (default-time
12680 ;; Default time is either today, or, when entering a range,
12681 ;; the range start.
12682 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12683 (save-excursion
12684 (re-search-backward
12685 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12686 (- (point) 20) t)))
12687 (apply 'encode-time (org-parse-time-string (match-string 1)))
12688 (current-time)))
12689 (default-input (and ts (org-get-compact-tod ts)))
12690 org-time-was-given org-end-time-was-given time)
12691 (cond
12692 ((and (org-at-timestamp-p t)
12693 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12694 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12695 (insert "--")
12696 (setq time (let ((this-command this-command))
12697 (org-read-date arg 'totime nil nil
12698 default-time default-input)))
12699 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12700 ((org-at-timestamp-p t)
12701 (setq time (let ((this-command this-command))
12702 (org-read-date arg 'totime nil nil default-time default-input)))
12703 (when (org-at-timestamp-p t) ; just to get the match data
12704 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12705 (replace-match "")
12706 (setq org-last-changed-timestamp
12707 (org-insert-time-stamp
12708 time (or org-time-was-given arg)
12709 inactive nil nil (list org-end-time-was-given))))
12710 (message "Timestamp updated"))
12712 (setq time (let ((this-command this-command))
12713 (org-read-date arg 'totime nil nil default-time default-input)))
12714 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12715 nil nil (list org-end-time-was-given))))))
12717 ;; FIXME: can we use this for something else, like computing time differences?
12718 (defun org-get-compact-tod (s)
12719 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12720 (let* ((t1 (match-string 1 s))
12721 (h1 (string-to-number (match-string 2 s)))
12722 (m1 (string-to-number (match-string 3 s)))
12723 (t2 (and (match-end 4) (match-string 5 s)))
12724 (h2 (and t2 (string-to-number (match-string 6 s))))
12725 (m2 (and t2 (string-to-number (match-string 7 s))))
12726 dh dm)
12727 (if (not t2)
12729 (setq dh (- h2 h1) dm (- m2 m1))
12730 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12731 (concat t1 "+" (number-to-string dh)
12732 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12734 (defun org-time-stamp-inactive (&optional arg)
12735 "Insert an inactive time stamp.
12736 An inactive time stamp is enclosed in square brackets instead of angle
12737 brackets. It is inactive in the sense that it does not trigger agenda entries,
12738 does not link to the calendar and cannot be changed with the S-cursor keys.
12739 So these are more for recording a certain time/date."
12740 (interactive "P")
12741 (org-time-stamp arg 'inactive))
12743 (defvar org-date-ovl (org-make-overlay 1 1))
12744 (org-overlay-put org-date-ovl 'face 'org-warning)
12745 (org-detach-overlay org-date-ovl)
12747 (defvar org-ans1) ; dynamically scoped parameter
12748 (defvar org-ans2) ; dynamically scoped parameter
12750 (defvar org-plain-time-of-day-regexp) ; defined below
12752 (defvar org-overriding-default-time nil) ; dynamically scoped
12753 (defvar org-read-date-overlay nil)
12754 (defvar org-dcst nil) ; dynamically scoped
12755 (defvar org-read-date-history nil)
12756 (defvar org-read-date-final-answer nil)
12758 (defun org-read-date (&optional with-time to-time from-string prompt
12759 default-time default-input)
12760 "Read a date, possibly a time, and make things smooth for the user.
12761 The prompt will suggest to enter an ISO date, but you can also enter anything
12762 which will at least partially be understood by `parse-time-string'.
12763 Unrecognized parts of the date will default to the current day, month, year,
12764 hour and minute. If this command is called to replace a timestamp at point,
12765 of to enter the second timestamp of a range, the default time is taken from the
12766 existing stamp. For example,
12767 3-2-5 --> 2003-02-05
12768 feb 15 --> currentyear-02-15
12769 sep 12 9 --> 2009-09-12
12770 12:45 --> today 12:45
12771 22 sept 0:34 --> currentyear-09-22 0:34
12772 12 --> currentyear-currentmonth-12
12773 Fri --> nearest Friday (today or later)
12774 etc.
12776 Furthermore you can specify a relative date by giving, as the *first* thing
12777 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12778 change in days weeks, months, years.
12779 With a single plus or minus, the date is relative to today. With a double
12780 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12781 +4d --> four days from today
12782 +4 --> same as above
12783 +2w --> two weeks from today
12784 ++5 --> five days from default date
12786 The function understands only English month and weekday abbreviations,
12787 but this can be configured with the variables `parse-time-months' and
12788 `parse-time-weekdays'.
12790 While prompting, a calendar is popped up - you can also select the
12791 date with the mouse (button 1). The calendar shows a period of three
12792 months. To scroll it to other months, use the keys `>' and `<'.
12793 If you don't like the calendar, turn it off with
12794 \(setq org-read-date-popup-calendar nil)
12796 With optional argument TO-TIME, the date will immediately be converted
12797 to an internal time.
12798 With an optional argument WITH-TIME, the prompt will suggest to also
12799 insert a time. Note that when WITH-TIME is not set, you can still
12800 enter a time, and this function will inform the calling routine about
12801 this change. The calling routine may then choose to change the format
12802 used to insert the time stamp into the buffer to include the time.
12803 With optional argument FROM-STRING, read from this string instead from
12804 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12805 the time/date that is used for everything that is not specified by the
12806 user."
12807 (require 'parse-time)
12808 (let* ((org-time-stamp-rounding-minutes
12809 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12810 (org-dcst org-display-custom-times)
12811 (ct (org-current-time))
12812 (def (or org-overriding-default-time default-time ct))
12813 (defdecode (decode-time def))
12814 (dummy (progn
12815 (when (< (nth 2 defdecode) org-extend-today-until)
12816 (setcar (nthcdr 2 defdecode) -1)
12817 (setcar (nthcdr 1 defdecode) 59)
12818 (setq def (apply 'encode-time defdecode)
12819 defdecode (decode-time def)))))
12820 (calendar-frame-setup nil)
12821 (calendar-move-hook nil)
12822 (calendar-view-diary-initially-flag nil)
12823 (view-diary-entries-initially nil)
12824 (calendar-view-holidays-initially-flag nil)
12825 (view-calendar-holidays-initially nil)
12826 (timestr (format-time-string
12827 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12828 (prompt (concat (if prompt (concat prompt " ") "")
12829 (format "Date+time [%s]: " timestr)))
12830 ans (org-ans0 "") org-ans1 org-ans2 final)
12832 (cond
12833 (from-string (setq ans from-string))
12834 (org-read-date-popup-calendar
12835 (save-excursion
12836 (save-window-excursion
12837 (calendar)
12838 (calendar-forward-day (- (time-to-days def)
12839 (calendar-absolute-from-gregorian
12840 (calendar-current-date))))
12841 (org-eval-in-calendar nil t)
12842 (let* ((old-map (current-local-map))
12843 (map (copy-keymap calendar-mode-map))
12844 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12845 (org-defkey map (kbd "RET") 'org-calendar-select)
12846 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12847 'org-calendar-select-mouse)
12848 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12849 'org-calendar-select-mouse)
12850 (org-defkey minibuffer-local-map [(meta shift left)]
12851 (lambda () (interactive)
12852 (org-eval-in-calendar '(calendar-backward-month 1))))
12853 (org-defkey minibuffer-local-map [(meta shift right)]
12854 (lambda () (interactive)
12855 (org-eval-in-calendar '(calendar-forward-month 1))))
12856 (org-defkey minibuffer-local-map [(meta shift up)]
12857 (lambda () (interactive)
12858 (org-eval-in-calendar '(calendar-backward-year 1))))
12859 (org-defkey minibuffer-local-map [(meta shift down)]
12860 (lambda () (interactive)
12861 (org-eval-in-calendar '(calendar-forward-year 1))))
12862 (org-defkey minibuffer-local-map [?\e (shift left)]
12863 (lambda () (interactive)
12864 (org-eval-in-calendar '(calendar-backward-month 1))))
12865 (org-defkey minibuffer-local-map [?\e (shift right)]
12866 (lambda () (interactive)
12867 (org-eval-in-calendar '(calendar-forward-month 1))))
12868 (org-defkey minibuffer-local-map [?\e (shift up)]
12869 (lambda () (interactive)
12870 (org-eval-in-calendar '(calendar-backward-year 1))))
12871 (org-defkey minibuffer-local-map [?\e (shift down)]
12872 (lambda () (interactive)
12873 (org-eval-in-calendar '(calendar-forward-year 1))))
12874 (org-defkey minibuffer-local-map [(shift up)]
12875 (lambda () (interactive)
12876 (org-eval-in-calendar '(calendar-backward-week 1))))
12877 (org-defkey minibuffer-local-map [(shift down)]
12878 (lambda () (interactive)
12879 (org-eval-in-calendar '(calendar-forward-week 1))))
12880 (org-defkey minibuffer-local-map [(shift left)]
12881 (lambda () (interactive)
12882 (org-eval-in-calendar '(calendar-backward-day 1))))
12883 (org-defkey minibuffer-local-map [(shift right)]
12884 (lambda () (interactive)
12885 (org-eval-in-calendar '(calendar-forward-day 1))))
12886 (org-defkey minibuffer-local-map ">"
12887 (lambda () (interactive)
12888 (org-eval-in-calendar '(scroll-calendar-left 1))))
12889 (org-defkey minibuffer-local-map "<"
12890 (lambda () (interactive)
12891 (org-eval-in-calendar '(scroll-calendar-right 1))))
12892 (run-hooks 'org-read-date-minibuffer-setup-hook)
12893 (unwind-protect
12894 (progn
12895 (use-local-map map)
12896 (add-hook 'post-command-hook 'org-read-date-display)
12897 (setq org-ans0 (read-string prompt default-input
12898 'org-read-date-history nil))
12899 ;; org-ans0: from prompt
12900 ;; org-ans1: from mouse click
12901 ;; org-ans2: from calendar motion
12902 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12903 (remove-hook 'post-command-hook 'org-read-date-display)
12904 (use-local-map old-map)
12905 (when org-read-date-overlay
12906 (org-delete-overlay org-read-date-overlay)
12907 (setq org-read-date-overlay nil)))))))
12909 (t ; Naked prompt only
12910 (unwind-protect
12911 (setq ans (read-string prompt default-input
12912 'org-read-date-history timestr))
12913 (when org-read-date-overlay
12914 (org-delete-overlay org-read-date-overlay)
12915 (setq org-read-date-overlay nil)))))
12917 (setq final (org-read-date-analyze ans def defdecode))
12918 (setq org-read-date-final-answer ans)
12920 (if to-time
12921 (apply 'encode-time final)
12922 (if (and (boundp 'org-time-was-given) org-time-was-given)
12923 (format "%04d-%02d-%02d %02d:%02d"
12924 (nth 5 final) (nth 4 final) (nth 3 final)
12925 (nth 2 final) (nth 1 final))
12926 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12928 (defvar def)
12929 (defvar defdecode)
12930 (defvar with-time)
12931 (defvar org-read-date-analyze-futurep nil)
12932 (defun org-read-date-display ()
12933 "Display the current date prompt interpretation in the minibuffer."
12934 (when org-read-date-display-live
12935 (when org-read-date-overlay
12936 (org-delete-overlay org-read-date-overlay))
12937 (let ((p (point)))
12938 (end-of-line 1)
12939 (while (not (equal (buffer-substring
12940 (max (point-min) (- (point) 4)) (point))
12941 " "))
12942 (insert " "))
12943 (goto-char p))
12944 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12945 " " (or org-ans1 org-ans2)))
12946 (org-end-time-was-given nil)
12947 (f (org-read-date-analyze ans def defdecode))
12948 (fmts (if org-dcst
12949 org-time-stamp-custom-formats
12950 org-time-stamp-formats))
12951 (fmt (if (or with-time
12952 (and (boundp 'org-time-was-given) org-time-was-given))
12953 (cdr fmts)
12954 (car fmts)))
12955 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12956 (when (and org-end-time-was-given
12957 (string-match org-plain-time-of-day-regexp txt))
12958 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12959 org-end-time-was-given
12960 (substring txt (match-end 0)))))
12961 (when org-read-date-analyze-futurep
12962 (setq txt (concat txt " (=>F)")))
12963 (setq org-read-date-overlay
12964 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12965 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12967 (defun org-read-date-analyze (ans def defdecode)
12968 "Analyse the combined answer of the date prompt."
12969 ;; FIXME: cleanup and comment
12970 (let (delta deltan deltaw deltadef year month day
12971 hour minute second wday pm h2 m2 tl wday1
12972 iso-year iso-weekday iso-week iso-year iso-date futurep)
12973 (setq org-read-date-analyze-futurep nil)
12974 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12975 (setq ans "+0"))
12977 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12978 (setq ans (replace-match "" t t ans)
12979 deltan (car delta)
12980 deltaw (nth 1 delta)
12981 deltadef (nth 2 delta)))
12983 ;; Check if there is an iso week date in there
12984 ;; If yes, sore the info and postpone interpreting it until the rest
12985 ;; of the parsing is done
12986 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12987 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12988 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12989 iso-week (string-to-number (match-string 2 ans)))
12990 (setq ans (replace-match "" t t ans)))
12992 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12993 (when (string-match
12994 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12995 (setq year (if (match-end 2)
12996 (string-to-number (match-string 2 ans))
12997 (string-to-number (format-time-string "%Y")))
12998 month (string-to-number (match-string 3 ans))
12999 day (string-to-number (match-string 4 ans)))
13000 (if (< year 100) (setq year (+ 2000 year)))
13001 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13002 t nil ans)))
13003 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13004 ;; If there is a time with am/pm, and *no* time without it, we convert
13005 ;; so that matching will be successful.
13006 (loop for i from 1 to 2 do ; twice, for end time as well
13007 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13008 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13009 (setq hour (string-to-number (match-string 1 ans))
13010 minute (if (match-end 3)
13011 (string-to-number (match-string 3 ans))
13013 pm (equal ?p
13014 (string-to-char (downcase (match-string 4 ans)))))
13015 (if (and (= hour 12) (not pm))
13016 (setq hour 0)
13017 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13018 (setq ans (replace-match (format "%02d:%02d" hour minute)
13019 t t ans))))
13021 ;; Check if a time range is given as a duration
13022 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13023 (setq hour (string-to-number (match-string 1 ans))
13024 h2 (+ hour (string-to-number (match-string 3 ans)))
13025 minute (string-to-number (match-string 2 ans))
13026 m2 (+ minute (if (match-end 5) (string-to-number
13027 (match-string 5 ans))0)))
13028 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13029 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13030 t t ans)))
13032 ;; Check if there is a time range
13033 (when (boundp 'org-end-time-was-given)
13034 (setq org-time-was-given nil)
13035 (when (and (string-match org-plain-time-of-day-regexp ans)
13036 (match-end 8))
13037 (setq org-end-time-was-given (match-string 8 ans))
13038 (setq ans (concat (substring ans 0 (match-beginning 7))
13039 (substring ans (match-end 7))))))
13041 (setq tl (parse-time-string ans)
13042 day (or (nth 3 tl) (nth 3 defdecode))
13043 month (or (nth 4 tl)
13044 (if (and org-read-date-prefer-future
13045 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
13046 (prog1 (1+ (nth 4 defdecode)) (setq futurep t))
13047 (nth 4 defdecode)))
13048 year (or (nth 5 tl)
13049 (if (and org-read-date-prefer-future
13050 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
13051 (prog1 (1+ (nth 5 defdecode)) (setq futurep t))
13052 (nth 5 defdecode)))
13053 hour (or (nth 2 tl) (nth 2 defdecode))
13054 minute (or (nth 1 tl) (nth 1 defdecode))
13055 second (or (nth 0 tl) 0)
13056 wday (nth 6 tl))
13058 (when (and (eq org-read-date-prefer-future 'time)
13059 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13060 (equal day (nth 3 defdecode))
13061 (equal month (nth 4 defdecode))
13062 (equal year (nth 5 defdecode))
13063 (nth 2 tl)
13064 (or (< (nth 2 tl) (nth 2 defdecode))
13065 (and (= (nth 2 tl) (nth 2 defdecode))
13066 (nth 1 tl)
13067 (< (nth 1 tl) (nth 1 defdecode)))))
13068 (setq day (1+ day)
13069 futurep t))
13071 ;; Special date definitions below
13072 (cond
13073 (iso-week
13074 ;; There was an iso week
13075 (setq futurep nil)
13076 (setq year (or iso-year year)
13077 day (or iso-weekday wday 1)
13078 wday nil ; to make sure that the trigger below does not match
13079 iso-date (calendar-gregorian-from-absolute
13080 (calendar-absolute-from-iso
13081 (list iso-week day year))))
13082 ; FIXME: Should we also push ISO weeks into the future?
13083 ; (when (and org-read-date-prefer-future
13084 ; (not iso-year)
13085 ; (< (calendar-absolute-from-gregorian iso-date)
13086 ; (time-to-days (current-time))))
13087 ; (setq year (1+ year)
13088 ; iso-date (calendar-gregorian-from-absolute
13089 ; (calendar-absolute-from-iso
13090 ; (list iso-week day year)))))
13091 (setq month (car iso-date)
13092 year (nth 2 iso-date)
13093 day (nth 1 iso-date)))
13094 (deltan
13095 (setq futurep nil)
13096 (unless deltadef
13097 (let ((now (decode-time (current-time))))
13098 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13099 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13100 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13101 ((equal deltaw "m") (setq month (+ month deltan)))
13102 ((equal deltaw "y") (setq year (+ year deltan)))))
13103 ((and wday (not (nth 3 tl)))
13104 (setq futurep nil)
13105 ;; Weekday was given, but no day, so pick that day in the week
13106 ;; on or after the derived date.
13107 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13108 (unless (equal wday wday1)
13109 (setq day (+ day (% (- wday wday1 -7) 7))))))
13110 (if (and (boundp 'org-time-was-given)
13111 (nth 2 tl))
13112 (setq org-time-was-given t))
13113 (if (< year 100) (setq year (+ 2000 year)))
13114 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13115 (setq org-read-date-analyze-futurep futurep)
13116 (list second minute hour day month year)))
13118 (defvar parse-time-weekdays)
13120 (defun org-read-date-get-relative (s today default)
13121 "Check string S for special relative date string.
13122 TODAY and DEFAULT are internal times, for today and for a default.
13123 Return shift list (N what def-flag)
13124 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13125 N is the number of WHATs to shift.
13126 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13127 the DEFAULT date rather than TODAY."
13128 (when (and
13129 (string-match
13130 (concat
13131 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13132 "\\([0-9]+\\)?"
13133 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13134 "\\([ \t]\\|$\\)") s)
13135 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13136 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13137 (string-to-char (substring (match-string 1 s) -1))
13138 ?+))
13139 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13140 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13141 (what (if (match-end 3) (match-string 3 s) "d"))
13142 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13143 (date (if rel default today))
13144 (wday (nth 6 (decode-time date)))
13145 delta)
13146 (if wday1
13147 (progn
13148 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13149 (if (= dir ?-) (setq delta (- delta 7)))
13150 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13151 (list delta "d" rel))
13152 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13154 (defun org-eval-in-calendar (form &optional keepdate)
13155 "Eval FORM in the calendar window and return to current window.
13156 Also, store the cursor date in variable org-ans2."
13157 (let ((sf (selected-frame))
13158 (sw (selected-window)))
13159 (select-window (get-buffer-window "*Calendar*" t))
13160 (eval form)
13161 (when (and (not keepdate) (calendar-cursor-to-date))
13162 (let* ((date (calendar-cursor-to-date))
13163 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13164 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13165 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13166 (select-window sw)
13167 (org-select-frame-set-input-focus sf)))
13169 (defun org-calendar-select ()
13170 "Return to `org-read-date' with the date currently selected.
13171 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13172 (interactive)
13173 (when (calendar-cursor-to-date)
13174 (let* ((date (calendar-cursor-to-date))
13175 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13176 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13177 (if (active-minibuffer-window) (exit-minibuffer))))
13179 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13180 "Insert a date stamp for the date given by the internal TIME.
13181 WITH-HM means, use the stamp format that includes the time of the day.
13182 INACTIVE means use square brackets instead of angular ones, so that the
13183 stamp will not contribute to the agenda.
13184 PRE and POST are optional strings to be inserted before and after the
13185 stamp.
13186 The command returns the inserted time stamp."
13187 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13188 stamp)
13189 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13190 (insert-before-markers (or pre ""))
13191 (insert-before-markers (setq stamp (format-time-string fmt time)))
13192 (when (listp extra)
13193 (setq extra (car extra))
13194 (if (and (stringp extra)
13195 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13196 (setq extra (format "-%02d:%02d"
13197 (string-to-number (match-string 1 extra))
13198 (string-to-number (match-string 2 extra))))
13199 (setq extra nil)))
13200 (when extra
13201 (backward-char 1)
13202 (insert-before-markers extra)
13203 (forward-char 1))
13204 (insert-before-markers (or post ""))
13205 (setq org-last-inserted-timestamp stamp)))
13207 (defun org-toggle-time-stamp-overlays ()
13208 "Toggle the use of custom time stamp formats."
13209 (interactive)
13210 (setq org-display-custom-times (not org-display-custom-times))
13211 (unless org-display-custom-times
13212 (let ((p (point-min)) (bmp (buffer-modified-p)))
13213 (while (setq p (next-single-property-change p 'display))
13214 (if (and (get-text-property p 'display)
13215 (eq (get-text-property p 'face) 'org-date))
13216 (remove-text-properties
13217 p (setq p (next-single-property-change p 'display))
13218 '(display t))))
13219 (set-buffer-modified-p bmp)))
13220 (if (featurep 'xemacs)
13221 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13222 (org-restart-font-lock)
13223 (setq org-table-may-need-update t)
13224 (if org-display-custom-times
13225 (message "Time stamps are overlayed with custom format")
13226 (message "Time stamp overlays removed")))
13228 (defun org-display-custom-time (beg end)
13229 "Overlay modified time stamp format over timestamp between BEG and END."
13230 (let* ((ts (buffer-substring beg end))
13231 t1 w1 with-hm tf time str w2 (off 0))
13232 (save-match-data
13233 (setq t1 (org-parse-time-string ts t))
13234 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13235 (setq off (- (match-end 0) (match-beginning 0)))))
13236 (setq end (- end off))
13237 (setq w1 (- end beg)
13238 with-hm (and (nth 1 t1) (nth 2 t1))
13239 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13240 time (org-fix-decoded-time t1)
13241 str (org-add-props
13242 (format-time-string
13243 (substring tf 1 -1) (apply 'encode-time time))
13244 nil 'mouse-face 'highlight)
13245 w2 (length str))
13246 (if (not (= w2 w1))
13247 (add-text-properties (1+ beg) (+ 2 beg)
13248 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13249 (if (featurep 'xemacs)
13250 (progn
13251 (put-text-property beg end 'invisible t)
13252 (put-text-property beg end 'end-glyph (make-glyph str)))
13253 (put-text-property beg end 'display str))))
13255 (defun org-translate-time (string)
13256 "Translate all timestamps in STRING to custom format.
13257 But do this only if the variable `org-display-custom-times' is set."
13258 (when org-display-custom-times
13259 (save-match-data
13260 (let* ((start 0)
13261 (re org-ts-regexp-both)
13262 t1 with-hm inactive tf time str beg end)
13263 (while (setq start (string-match re string start))
13264 (setq beg (match-beginning 0)
13265 end (match-end 0)
13266 t1 (save-match-data
13267 (org-parse-time-string (substring string beg end) t))
13268 with-hm (and (nth 1 t1) (nth 2 t1))
13269 inactive (equal (substring string beg (1+ beg)) "[")
13270 tf (funcall (if with-hm 'cdr 'car)
13271 org-time-stamp-custom-formats)
13272 time (org-fix-decoded-time t1)
13273 str (format-time-string
13274 (concat
13275 (if inactive "[" "<") (substring tf 1 -1)
13276 (if inactive "]" ">"))
13277 (apply 'encode-time time))
13278 string (replace-match str t t string)
13279 start (+ start (length str)))))))
13280 string)
13282 (defun org-fix-decoded-time (time)
13283 "Set 0 instead of nil for the first 6 elements of time.
13284 Don't touch the rest."
13285 (let ((n 0))
13286 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13288 (defun org-days-to-time (timestamp-string)
13289 "Difference between TIMESTAMP-STRING and now in days."
13290 (- (time-to-days (org-time-string-to-time timestamp-string))
13291 (time-to-days (current-time))))
13293 (defun org-deadline-close (timestamp-string &optional ndays)
13294 "Is the time in TIMESTAMP-STRING close to the current date?"
13295 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13296 (and (< (org-days-to-time timestamp-string) ndays)
13297 (not (org-entry-is-done-p))))
13299 (defun org-get-wdays (ts)
13300 "Get the deadline lead time appropriate for timestring TS."
13301 (cond
13302 ((<= org-deadline-warning-days 0)
13303 ;; 0 or negative, enforce this value no matter what
13304 (- org-deadline-warning-days))
13305 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13306 ;; lead time is specified.
13307 (floor (* (string-to-number (match-string 1 ts))
13308 (cdr (assoc (match-string 2 ts)
13309 '(("d" . 1) ("w" . 7)
13310 ("m" . 30.4) ("y" . 365.25)))))))
13311 ;; go for the default.
13312 (t org-deadline-warning-days)))
13314 (defun org-calendar-select-mouse (ev)
13315 "Return to `org-read-date' with the date currently selected.
13316 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13317 (interactive "e")
13318 (mouse-set-point ev)
13319 (when (calendar-cursor-to-date)
13320 (let* ((date (calendar-cursor-to-date))
13321 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13322 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13323 (if (active-minibuffer-window) (exit-minibuffer))))
13325 (defun org-check-deadlines (ndays)
13326 "Check if there are any deadlines due or past due.
13327 A deadline is considered due if it happens within `org-deadline-warning-days'
13328 days from today's date. If the deadline appears in an entry marked DONE,
13329 it is not shown. The prefix arg NDAYS can be used to test that many
13330 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13331 (interactive "P")
13332 (let* ((org-warn-days
13333 (cond
13334 ((equal ndays '(4)) 100000)
13335 (ndays (prefix-numeric-value ndays))
13336 (t (abs org-deadline-warning-days))))
13337 (case-fold-search nil)
13338 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13339 (callback
13340 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13342 (message "%d deadlines past-due or due within %d days"
13343 (org-occur regexp nil callback)
13344 org-warn-days)))
13346 (defun org-check-before-date (date)
13347 "Check if there are deadlines or scheduled entries before DATE."
13348 (interactive (list (org-read-date)))
13349 (let ((case-fold-search nil)
13350 (regexp (concat "\\<\\(" org-deadline-string
13351 "\\|" org-scheduled-string
13352 "\\) *<\\([^>]+\\)>"))
13353 (callback
13354 (lambda () (time-less-p
13355 (org-time-string-to-time (match-string 2))
13356 (org-time-string-to-time date)))))
13357 (message "%d entries before %s"
13358 (org-occur regexp nil callback) date)))
13360 (defun org-check-after-date (date)
13361 "Check if there are deadlines or scheduled entries after DATE."
13362 (interactive (list (org-read-date)))
13363 (let ((case-fold-search nil)
13364 (regexp (concat "\\<\\(" org-deadline-string
13365 "\\|" org-scheduled-string
13366 "\\) *<\\([^>]+\\)>"))
13367 (callback
13368 (lambda () (not
13369 (time-less-p
13370 (org-time-string-to-time (match-string 2))
13371 (org-time-string-to-time date))))))
13372 (message "%d entries after %s"
13373 (org-occur regexp nil callback) date)))
13375 (defun org-evaluate-time-range (&optional to-buffer)
13376 "Evaluate a time range by computing the difference between start and end.
13377 Normally the result is just printed in the echo area, but with prefix arg
13378 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13379 If the time range is actually in a table, the result is inserted into the
13380 next column.
13381 For time difference computation, a year is assumed to be exactly 365
13382 days in order to avoid rounding problems."
13383 (interactive "P")
13385 (org-clock-update-time-maybe)
13386 (save-excursion
13387 (unless (org-at-date-range-p t)
13388 (goto-char (point-at-bol))
13389 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13390 (if (not (org-at-date-range-p t))
13391 (error "Not at a time-stamp range, and none found in current line")))
13392 (let* ((ts1 (match-string 1))
13393 (ts2 (match-string 2))
13394 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13395 (match-end (match-end 0))
13396 (time1 (org-time-string-to-time ts1))
13397 (time2 (org-time-string-to-time ts2))
13398 (t1 (org-float-time time1))
13399 (t2 (org-float-time time2))
13400 (diff (abs (- t2 t1)))
13401 (negative (< (- t2 t1) 0))
13402 ;; (ys (floor (* 365 24 60 60)))
13403 (ds (* 24 60 60))
13404 (hs (* 60 60))
13405 (fy "%dy %dd %02d:%02d")
13406 (fy1 "%dy %dd")
13407 (fd "%dd %02d:%02d")
13408 (fd1 "%dd")
13409 (fh "%02d:%02d")
13410 y d h m align)
13411 (if havetime
13412 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13414 d (floor (/ diff ds)) diff (mod diff ds)
13415 h (floor (/ diff hs)) diff (mod diff hs)
13416 m (floor (/ diff 60)))
13417 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13419 d (floor (+ (/ diff ds) 0.5))
13420 h 0 m 0))
13421 (if (not to-buffer)
13422 (message "%s" (org-make-tdiff-string y d h m))
13423 (if (org-at-table-p)
13424 (progn
13425 (goto-char match-end)
13426 (setq align t)
13427 (and (looking-at " *|") (goto-char (match-end 0))))
13428 (goto-char match-end))
13429 (if (looking-at
13430 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13431 (replace-match ""))
13432 (if negative (insert " -"))
13433 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13434 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13435 (insert " " (format fh h m))))
13436 (if align (org-table-align))
13437 (message "Time difference inserted")))))
13439 (defun org-make-tdiff-string (y d h m)
13440 (let ((fmt "")
13441 (l nil))
13442 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13443 l (push y l)))
13444 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13445 l (push d l)))
13446 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13447 l (push h l)))
13448 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13449 l (push m l)))
13450 (apply 'format fmt (nreverse l))))
13452 (defun org-time-string-to-time (s)
13453 (apply 'encode-time (org-parse-time-string s)))
13454 (defun org-time-string-to-seconds (s)
13455 (org-float-time (org-time-string-to-time s)))
13457 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13458 "Convert a time stamp to an absolute day number.
13459 If there is a specifyer for a cyclic time stamp, get the closest date to
13460 DAYNR.
13461 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13462 the variable date is bound by the calendar when this is called."
13463 (cond
13464 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13465 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13466 daynr
13467 (+ daynr 1000)))
13468 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13469 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13470 (time-to-days (current-time))) (match-string 0 s)
13471 prefer show-all))
13472 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13474 (defun org-days-to-iso-week (days)
13475 "Return the iso week number."
13476 (require 'cal-iso)
13477 (car (calendar-iso-from-absolute days)))
13479 (defun org-small-year-to-year (year)
13480 "Convert 2-digit years into 4-digit years.
13481 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13482 The year 2000 cannot be abbreviated. Any year larger than 99
13483 is returned unchanged."
13484 (if (< year 38)
13485 (setq year (+ 2000 year))
13486 (if (< year 100)
13487 (setq year (+ 1900 year))))
13488 year)
13490 (defun org-time-from-absolute (d)
13491 "Return the time corresponding to date D.
13492 D may be an absolute day number, or a calendar-type list (month day year)."
13493 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13494 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13496 (defun org-calendar-holiday ()
13497 "List of holidays, for Diary display in Org-mode."
13498 (require 'holidays)
13499 (let ((hl (funcall
13500 (if (fboundp 'calendar-check-holidays)
13501 'calendar-check-holidays 'check-calendar-holidays) date)))
13502 (if hl (mapconcat 'identity hl "; "))))
13504 (defun org-diary-sexp-entry (sexp entry date)
13505 "Process a SEXP diary ENTRY for DATE."
13506 (require 'diary-lib)
13507 (let ((result (if calendar-debug-sexp
13508 (let ((stack-trace-on-error t))
13509 (eval (car (read-from-string sexp))))
13510 (condition-case nil
13511 (eval (car (read-from-string sexp)))
13512 (error
13513 (beep)
13514 (message "Bad sexp at line %d in %s: %s"
13515 (org-current-line)
13516 (buffer-file-name) sexp)
13517 (sleep-for 2))))))
13518 (cond ((stringp result) result)
13519 ((and (consp result)
13520 (stringp (cdr result))) (cdr result))
13521 (result entry)
13522 (t nil))))
13524 (defun org-diary-to-ical-string (frombuf)
13525 "Get iCalendar entries from diary entries in buffer FROMBUF.
13526 This uses the icalendar.el library."
13527 (let* ((tmpdir (if (featurep 'xemacs)
13528 (temp-directory)
13529 temporary-file-directory))
13530 (tmpfile (make-temp-name
13531 (expand-file-name "orgics" tmpdir)))
13532 buf rtn b e)
13533 (with-current-buffer frombuf
13534 (icalendar-export-region (point-min) (point-max) tmpfile)
13535 (setq buf (find-buffer-visiting tmpfile))
13536 (set-buffer buf)
13537 (goto-char (point-min))
13538 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13539 (setq b (match-beginning 0)))
13540 (goto-char (point-max))
13541 (if (re-search-backward "^END:VEVENT" nil t)
13542 (setq e (match-end 0)))
13543 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13544 (kill-buffer buf)
13545 (delete-file tmpfile)
13546 rtn))
13548 (defun org-closest-date (start current change prefer show-all)
13549 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13550 When PREFER is `past' return a date that is either CURRENT or past.
13551 When PREFER is `future', return a date that is either CURRENT or future.
13552 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13553 ;; Make the proper lists from the dates
13554 (catch 'exit
13555 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13556 dn dw sday cday n1 n2 n0
13557 d m y y1 y2 date1 date2 nmonths nm ny m2)
13559 (setq start (org-date-to-gregorian start)
13560 current (org-date-to-gregorian
13561 (if show-all
13562 current
13563 (time-to-days (current-time))))
13564 sday (calendar-absolute-from-gregorian start)
13565 cday (calendar-absolute-from-gregorian current))
13567 (if (<= cday sday) (throw 'exit sday))
13569 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13570 (setq dn (string-to-number (match-string 1 change))
13571 dw (cdr (assoc (match-string 2 change) a1)))
13572 (error "Invalid change specifyer: %s" change))
13573 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13574 (cond
13575 ((eq dw 'day)
13576 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13577 n2 (+ n1 dn)))
13578 ((eq dw 'year)
13579 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13580 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13581 (setq date1 (list m d y1)
13582 n1 (calendar-absolute-from-gregorian date1)
13583 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13584 n2 (calendar-absolute-from-gregorian date2)))
13585 ((eq dw 'month)
13586 ;; approx number of month between the two dates
13587 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13588 ;; How often does dn fit in there?
13589 (setq d (nth 1 start) m (car start) y (nth 2 start)
13590 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13591 m (+ m nm)
13592 ny (floor (/ m 12))
13593 y (+ y ny)
13594 m (- m (* ny 12)))
13595 (while (> m 12) (setq m (- m 12) y (1+ y)))
13596 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13597 (setq m2 (+ m dn) y2 y)
13598 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13599 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13600 (while (<= n2 cday)
13601 (setq n1 n2 m m2 y y2)
13602 (setq m2 (+ m dn) y2 y)
13603 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13604 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13605 ;; Make sure n1 is the earlier date
13606 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13607 (if show-all
13608 (cond
13609 ((eq prefer 'past) (if (= cday n2) n2 n1))
13610 ((eq prefer 'future) (if (= cday n1) n1 n2))
13611 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13612 (cond
13613 ((eq prefer 'past) (if (= cday n2) n2 n1))
13614 ((eq prefer 'future) (if (= cday n1) n1 n2))
13615 (t (if (= cday n1) n1 n2)))))))
13617 (defun org-date-to-gregorian (date)
13618 "Turn any specification of DATE into a gregorian date for the calendar."
13619 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13620 ((and (listp date) (= (length date) 3)) date)
13621 ((stringp date)
13622 (setq date (org-parse-time-string date))
13623 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13624 ((listp date)
13625 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13627 (defun org-parse-time-string (s &optional nodefault)
13628 "Parse the standard Org-mode time string.
13629 This should be a lot faster than the normal `parse-time-string'.
13630 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13631 hour and minute fields will be nil if not given."
13632 (if (string-match org-ts-regexp0 s)
13633 (list 0
13634 (if (or (match-beginning 8) (not nodefault))
13635 (string-to-number (or (match-string 8 s) "0")))
13636 (if (or (match-beginning 7) (not nodefault))
13637 (string-to-number (or (match-string 7 s) "0")))
13638 (string-to-number (match-string 4 s))
13639 (string-to-number (match-string 3 s))
13640 (string-to-number (match-string 2 s))
13641 nil nil nil)
13642 (error "Not a standard Org-mode time string: %s" s)))
13644 (defun org-timestamp-up (&optional arg)
13645 "Increase the date item at the cursor by one.
13646 If the cursor is on the year, change the year. If it is on the month or
13647 the day, change that.
13648 With prefix ARG, change by that many units."
13649 (interactive "p")
13650 (org-timestamp-change (prefix-numeric-value arg)))
13652 (defun org-timestamp-down (&optional arg)
13653 "Decrease the date item at the cursor by one.
13654 If the cursor is on the year, change the year. If it is on the month or
13655 the day, change that.
13656 With prefix ARG, change by that many units."
13657 (interactive "p")
13658 (org-timestamp-change (- (prefix-numeric-value arg))))
13660 (defun org-timestamp-up-day (&optional arg)
13661 "Increase the date in the time stamp by one day.
13662 With prefix ARG, change that many days."
13663 (interactive "p")
13664 (if (and (not (org-at-timestamp-p t))
13665 (org-on-heading-p))
13666 (org-todo 'up)
13667 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13669 (defun org-timestamp-down-day (&optional arg)
13670 "Decrease the date in the time stamp by one day.
13671 With prefix ARG, change that many days."
13672 (interactive "p")
13673 (if (and (not (org-at-timestamp-p t))
13674 (org-on-heading-p))
13675 (org-todo 'down)
13676 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13678 (defun org-at-timestamp-p (&optional inactive-ok)
13679 "Determine if the cursor is in or at a timestamp."
13680 (interactive)
13681 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13682 (pos (point))
13683 (ans (or (looking-at tsr)
13684 (save-excursion
13685 (skip-chars-backward "^[<\n\r\t")
13686 (if (> (point) (point-min)) (backward-char 1))
13687 (and (looking-at tsr)
13688 (> (- (match-end 0) pos) -1))))))
13689 (and ans
13690 (boundp 'org-ts-what)
13691 (setq org-ts-what
13692 (cond
13693 ((= pos (match-beginning 0)) 'bracket)
13694 ((= pos (1- (match-end 0))) 'bracket)
13695 ((org-pos-in-match-range pos 2) 'year)
13696 ((org-pos-in-match-range pos 3) 'month)
13697 ((org-pos-in-match-range pos 7) 'hour)
13698 ((org-pos-in-match-range pos 8) 'minute)
13699 ((or (org-pos-in-match-range pos 4)
13700 (org-pos-in-match-range pos 5)) 'day)
13701 ((and (> pos (or (match-end 8) (match-end 5)))
13702 (< pos (match-end 0)))
13703 (- pos (or (match-end 8) (match-end 5))))
13704 (t 'day))))
13705 ans))
13707 (defun org-toggle-timestamp-type ()
13708 "Toggle the type (<active> or [inactive]) of a time stamp."
13709 (interactive)
13710 (when (org-at-timestamp-p t)
13711 (let ((beg (match-beginning 0)) (end (match-end 0))
13712 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13713 (save-excursion
13714 (goto-char beg)
13715 (while (re-search-forward "[][<>]" end t)
13716 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13717 t t)))
13718 (message "Timestamp is now %sactive"
13719 (if (equal (char-after beg) ?<) "" "in")))))
13721 (defun org-timestamp-change (n &optional what)
13722 "Change the date in the time stamp at point.
13723 The date will be changed by N times WHAT. WHAT can be `day', `month',
13724 `year', `minute', `second'. If WHAT is not given, the cursor position
13725 in the timestamp determines what will be changed."
13726 (let ((pos (point))
13727 with-hm inactive
13728 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13729 org-ts-what
13730 extra rem
13731 ts time time0)
13732 (if (not (org-at-timestamp-p t))
13733 (error "Not at a timestamp"))
13734 (if (and (not what) (eq org-ts-what 'bracket))
13735 (org-toggle-timestamp-type)
13736 (if (and (not what) (not (eq org-ts-what 'day))
13737 org-display-custom-times
13738 (get-text-property (point) 'display)
13739 (not (get-text-property (1- (point)) 'display)))
13740 (setq org-ts-what 'day))
13741 (setq org-ts-what (or what org-ts-what)
13742 inactive (= (char-after (match-beginning 0)) ?\[)
13743 ts (match-string 0))
13744 (replace-match "")
13745 (if (string-match
13746 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
13748 (setq extra (match-string 1 ts)))
13749 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13750 (setq with-hm t))
13751 (setq time0 (org-parse-time-string ts))
13752 (when (and (eq org-ts-what 'minute)
13753 (eq current-prefix-arg nil))
13754 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13755 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13756 (setcar (cdr time0) (+ (nth 1 time0)
13757 (if (> n 0) (- rem) (- dm rem))))))
13758 (setq time
13759 (encode-time (or (car time0) 0)
13760 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13761 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13762 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13763 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13764 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13765 (nthcdr 6 time0)))
13766 (when (and (member org-ts-what '(hour minute))
13767 extra
13768 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13769 (setq extra (org-modify-ts-extra
13770 extra
13771 (if (eq org-ts-what 'hour) 2 5)
13772 n dm)))
13773 (when (integerp org-ts-what)
13774 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13775 (if (eq what 'calendar)
13776 (let ((cal-date (org-get-date-from-calendar)))
13777 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13778 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13779 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13780 (setcar time0 (or (car time0) 0))
13781 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13782 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13783 (setq time (apply 'encode-time time0))))
13784 (setq org-last-changed-timestamp
13785 (org-insert-time-stamp time with-hm inactive nil nil extra))
13786 (org-clock-update-time-maybe)
13787 (goto-char pos)
13788 ;; Try to recenter the calendar window, if any
13789 (if (and org-calendar-follow-timestamp-change
13790 (get-buffer-window "*Calendar*" t)
13791 (memq org-ts-what '(day month year)))
13792 (org-recenter-calendar (time-to-days time))))))
13794 (defun org-modify-ts-extra (s pos n dm)
13795 "Change the different parts of the lead-time and repeat fields in timestamp."
13796 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13797 ng h m new rem)
13798 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13799 (cond
13800 ((or (org-pos-in-match-range pos 2)
13801 (org-pos-in-match-range pos 3))
13802 (setq m (string-to-number (match-string 3 s))
13803 h (string-to-number (match-string 2 s)))
13804 (if (org-pos-in-match-range pos 2)
13805 (setq h (+ h n))
13806 (setq n (* dm (org-no-warnings (signum n))))
13807 (when (not (= 0 (setq rem (% m dm))))
13808 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13809 (setq m (+ m n)))
13810 (if (< m 0) (setq m (+ m 60) h (1- h)))
13811 (if (> m 59) (setq m (- m 60) h (1+ h)))
13812 (setq h (min 24 (max 0 h)))
13813 (setq ng 1 new (format "-%02d:%02d" h m)))
13814 ((org-pos-in-match-range pos 6)
13815 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13816 ((org-pos-in-match-range pos 5)
13817 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13819 ((org-pos-in-match-range pos 9)
13820 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13821 ((org-pos-in-match-range pos 8)
13822 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13824 (when ng
13825 (setq s (concat
13826 (substring s 0 (match-beginning ng))
13828 (substring s (match-end ng))))))
13831 (defun org-recenter-calendar (date)
13832 "If the calendar is visible, recenter it to DATE."
13833 (let* ((win (selected-window))
13834 (cwin (get-buffer-window "*Calendar*" t))
13835 (calendar-move-hook nil))
13836 (when cwin
13837 (select-window cwin)
13838 (calendar-goto-date (if (listp date) date
13839 (calendar-gregorian-from-absolute date)))
13840 (select-window win))))
13842 (defun org-goto-calendar (&optional arg)
13843 "Go to the Emacs calendar at the current date.
13844 If there is a time stamp in the current line, go to that date.
13845 A prefix ARG can be used to force the current date."
13846 (interactive "P")
13847 (let ((tsr org-ts-regexp) diff
13848 (calendar-move-hook nil)
13849 (calendar-view-holidays-initially-flag nil)
13850 (view-calendar-holidays-initially nil)
13851 (calendar-view-diary-initially-flag nil)
13852 (view-diary-entries-initially nil))
13853 (if (or (org-at-timestamp-p)
13854 (save-excursion
13855 (beginning-of-line 1)
13856 (looking-at (concat ".*" tsr))))
13857 (let ((d1 (time-to-days (current-time)))
13858 (d2 (time-to-days
13859 (org-time-string-to-time (match-string 1)))))
13860 (setq diff (- d2 d1))))
13861 (calendar)
13862 (calendar-goto-today)
13863 (if (and diff (not arg)) (calendar-forward-day diff))))
13865 (defun org-get-date-from-calendar ()
13866 "Return a list (month day year) of date at point in calendar."
13867 (with-current-buffer "*Calendar*"
13868 (save-match-data
13869 (calendar-cursor-to-date))))
13871 (defun org-date-from-calendar ()
13872 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13873 If there is already a time stamp at the cursor position, update it."
13874 (interactive)
13875 (if (org-at-timestamp-p t)
13876 (org-timestamp-change 0 'calendar)
13877 (let ((cal-date (org-get-date-from-calendar)))
13878 (org-insert-time-stamp
13879 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13881 (defun org-minutes-to-hh:mm-string (m)
13882 "Compute H:MM from a number of minutes."
13883 (let ((h (/ m 60)))
13884 (setq m (- m (* 60 h)))
13885 (format org-time-clocksum-format h m)))
13887 (defun org-hh:mm-string-to-minutes (s)
13888 "Convert a string H:MM to a number of minutes.
13889 If the string is just a number, interprete it as minutes.
13890 In fact, the first hh:mm or number in the string will be taken,
13891 there can be extra stuff in the string.
13892 If no number is found, the return value is 0."
13893 (cond
13894 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13895 (+ (* (string-to-number (match-string 1 s)) 60)
13896 (string-to-number (match-string 2 s))))
13897 ((string-match "\\([0-9]+\\)" s)
13898 (string-to-number (match-string 1 s)))
13899 (t 0)))
13901 ;;;; Files
13903 (defun org-save-all-org-buffers ()
13904 "Save all Org-mode buffers without user confirmation."
13905 (interactive)
13906 (message "Saving all Org-mode buffers...")
13907 (save-some-buffers t 'org-mode-p)
13908 (when (featurep 'org-id) (org-id-locations-save))
13909 (message "Saving all Org-mode buffers... done"))
13911 (defun org-revert-all-org-buffers ()
13912 "Revert all Org-mode buffers.
13913 Prompt for confirmation when there are unsaved changes.
13914 Be sure you know what you are doing before letting this function
13915 overwrite your changes.
13917 This function is useful in a setup where one tracks org files
13918 with a version control system, to revert on one machine after pulling
13919 changes from another. I believe the procedure must be like this:
13921 1. M-x org-save-all-org-buffers
13922 2. Pull changes from the other machine, resolve conflicts
13923 3. M-x org-revert-all-org-buffers"
13924 (interactive)
13925 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13926 (error "Abort"))
13927 (save-excursion
13928 (save-window-excursion
13929 (mapc
13930 (lambda (b)
13931 (when (and (with-current-buffer b (org-mode-p))
13932 (with-current-buffer b buffer-file-name))
13933 (switch-to-buffer b)
13934 (revert-buffer t 'no-confirm)))
13935 (buffer-list))
13936 (when (and (featurep 'org-id) org-id-track-globally)
13937 (org-id-locations-load)))))
13939 ;;;; Agenda files
13941 ;;;###autoload
13942 (defun org-iswitchb (&optional arg)
13943 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
13944 With a prefix argument, restrict available to files.
13945 With two prefix arguments, restrict available buffers to agenda files."
13946 (interactive "P")
13947 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13948 ((equal arg '(16)) (org-buffer-list 'agenda))
13949 (t (org-buffer-list)))))
13950 (switch-to-buffer
13951 (org-icompleting-read "Org buffer: "
13952 (mapcar 'list (mapcar 'buffer-name blist))
13953 nil t))))
13955 ;;;###autoload
13956 (defalias 'org-ido-switchb 'org-iswitchb)
13958 (defun org-buffer-list (&optional predicate exclude-tmp)
13959 "Return a list of Org buffers.
13960 PREDICATE can be `export', `files' or `agenda'.
13962 export restrict the list to Export buffers.
13963 files restrict the list to buffers visiting Org files.
13964 agenda restrict the list to buffers visiting agenda files.
13966 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13967 (let* ((bfn nil)
13968 (agenda-files (and (eq predicate 'agenda)
13969 (mapcar 'file-truename (org-agenda-files t))))
13970 (filter
13971 (cond
13972 ((eq predicate 'files)
13973 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13974 ((eq predicate 'export)
13975 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13976 ((eq predicate 'agenda)
13977 (lambda (b)
13978 (with-current-buffer b
13979 (and (eq major-mode 'org-mode)
13980 (setq bfn (buffer-file-name b))
13981 (member (file-truename bfn) agenda-files)))))
13982 (t (lambda (b) (with-current-buffer b
13983 (or (eq major-mode 'org-mode)
13984 (string-match "\*Org .*Export"
13985 (buffer-name b)))))))))
13986 (delq nil
13987 (mapcar
13988 (lambda(b)
13989 (if (and (funcall filter b)
13990 (or (not exclude-tmp)
13991 (not (string-match "tmp" (buffer-name b)))))
13993 nil))
13994 (buffer-list)))))
13996 (defun org-agenda-files (&optional unrestricted archives)
13997 "Get the list of agenda files.
13998 Optional UNRESTRICTED means return the full list even if a restriction
13999 is currently in place.
14000 When ARCHIVES is t, include all archive files hat are really being
14001 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14002 `org-agenda-archives-mode' is t."
14003 (let ((files
14004 (cond
14005 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14006 ((stringp org-agenda-files) (org-read-agenda-file-list))
14007 ((listp org-agenda-files) org-agenda-files)
14008 (t (error "Invalid value of `org-agenda-files'")))))
14009 (setq files (apply 'append
14010 (mapcar (lambda (f)
14011 (if (file-directory-p f)
14012 (directory-files
14013 f t org-agenda-file-regexp)
14014 (list f)))
14015 files)))
14016 (when org-agenda-skip-unavailable-files
14017 (setq files (delq nil
14018 (mapcar (function
14019 (lambda (file)
14020 (and (file-readable-p file) file)))
14021 files))))
14022 (when (or (eq archives t)
14023 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14024 (setq files (org-add-archive-files files)))
14025 files))
14027 (defun org-edit-agenda-file-list ()
14028 "Edit the list of agenda files.
14029 Depending on setup, this either uses customize to edit the variable
14030 `org-agenda-files', or it visits the file that is holding the list. In the
14031 latter case, the buffer is set up in a way that saving it automatically kills
14032 the buffer and restores the previous window configuration."
14033 (interactive)
14034 (if (stringp org-agenda-files)
14035 (let ((cw (current-window-configuration)))
14036 (find-file org-agenda-files)
14037 (org-set-local 'org-window-configuration cw)
14038 (org-add-hook 'after-save-hook
14039 (lambda ()
14040 (set-window-configuration
14041 (prog1 org-window-configuration
14042 (kill-buffer (current-buffer))))
14043 (org-install-agenda-files-menu)
14044 (message "New agenda file list installed"))
14045 nil 'local)
14046 (message "%s" (substitute-command-keys
14047 "Edit list and finish with \\[save-buffer]")))
14048 (customize-variable 'org-agenda-files)))
14050 (defun org-store-new-agenda-file-list (list)
14051 "Set new value for the agenda file list and save it correctly."
14052 (if (stringp org-agenda-files)
14053 (let ((f org-agenda-files) b)
14054 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14055 (with-temp-file f
14056 (insert (mapconcat 'identity list "\n") "\n")))
14057 (let ((org-mode-hook nil) (org-inhibit-startup t)
14058 (org-insert-mode-line-in-empty-file nil))
14059 (setq org-agenda-files list)
14060 (customize-save-variable 'org-agenda-files org-agenda-files))))
14062 (defun org-read-agenda-file-list ()
14063 "Read the list of agenda files from a file."
14064 (when (file-directory-p org-agenda-files)
14065 (error "`org-agenda-files' cannot be a single directory"))
14066 (when (stringp org-agenda-files)
14067 (with-temp-buffer
14068 (insert-file-contents org-agenda-files)
14069 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14072 ;;;###autoload
14073 (defun org-cycle-agenda-files ()
14074 "Cycle through the files in `org-agenda-files'.
14075 If the current buffer visits an agenda file, find the next one in the list.
14076 If the current buffer does not, find the first agenda file."
14077 (interactive)
14078 (let* ((fs (org-agenda-files t))
14079 (files (append fs (list (car fs))))
14080 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14081 file)
14082 (unless files (error "No agenda files"))
14083 (catch 'exit
14084 (while (setq file (pop files))
14085 (if (equal (file-truename file) tcf)
14086 (when (car files)
14087 (find-file (car files))
14088 (throw 'exit t))))
14089 (find-file (car fs)))
14090 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14092 (defun org-agenda-file-to-front (&optional to-end)
14093 "Move/add the current file to the top of the agenda file list.
14094 If the file is not present in the list, it is added to the front. If it is
14095 present, it is moved there. With optional argument TO-END, add/move to the
14096 end of the list."
14097 (interactive "P")
14098 (let ((org-agenda-skip-unavailable-files nil)
14099 (file-alist (mapcar (lambda (x)
14100 (cons (file-truename x) x))
14101 (org-agenda-files t)))
14102 (ctf (file-truename buffer-file-name))
14103 x had)
14104 (setq x (assoc ctf file-alist) had x)
14106 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14107 (if to-end
14108 (setq file-alist (append (delq x file-alist) (list x)))
14109 (setq file-alist (cons x (delq x file-alist))))
14110 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14111 (org-install-agenda-files-menu)
14112 (message "File %s to %s of agenda file list"
14113 (if had "moved" "added") (if to-end "end" "front"))))
14115 (defun org-remove-file (&optional file)
14116 "Remove current file from the list of files in variable `org-agenda-files'.
14117 These are the files which are being checked for agenda entries.
14118 Optional argument FILE means, use this file instead of the current."
14119 (interactive)
14120 (let* ((org-agenda-skip-unavailable-files nil)
14121 (file (or file buffer-file-name))
14122 (true-file (file-truename file))
14123 (afile (abbreviate-file-name file))
14124 (files (delq nil (mapcar
14125 (lambda (x)
14126 (if (equal true-file
14127 (file-truename x))
14128 nil x))
14129 (org-agenda-files t)))))
14130 (if (not (= (length files) (length (org-agenda-files t))))
14131 (progn
14132 (org-store-new-agenda-file-list files)
14133 (org-install-agenda-files-menu)
14134 (message "Removed file: %s" afile))
14135 (message "File was not in list: %s (not removed)" afile))))
14137 (defun org-file-menu-entry (file)
14138 (vector file (list 'find-file file) t))
14140 (defun org-check-agenda-file (file)
14141 "Make sure FILE exists. If not, ask user what to do."
14142 (when (not (file-exists-p file))
14143 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14144 (abbreviate-file-name file))
14145 (let ((r (downcase (read-char-exclusive))))
14146 (cond
14147 ((equal r ?r)
14148 (org-remove-file file)
14149 (throw 'nextfile t))
14150 (t (error "Abort"))))))
14152 (defun org-get-agenda-file-buffer (file)
14153 "Get a buffer visiting FILE. If the buffer needs to be created, add
14154 it to the list of buffers which might be released later."
14155 (let ((buf (org-find-base-buffer-visiting file)))
14156 (if buf
14157 buf ; just return it
14158 ;; Make a new buffer and remember it
14159 (setq buf (find-file-noselect file))
14160 (if buf (push buf org-agenda-new-buffers))
14161 buf)))
14163 (defun org-release-buffers (blist)
14164 "Release all buffers in list, asking the user for confirmation when needed.
14165 When a buffer is unmodified, it is just killed. When modified, it is saved
14166 \(if the user agrees) and then killed."
14167 (let (buf file)
14168 (while (setq buf (pop blist))
14169 (setq file (buffer-file-name buf))
14170 (when (and (buffer-modified-p buf)
14171 file
14172 (y-or-n-p (format "Save file %s? " file)))
14173 (with-current-buffer buf (save-buffer)))
14174 (kill-buffer buf))))
14176 (defun org-prepare-agenda-buffers (files)
14177 "Create buffers for all agenda files, protect archived trees and comments."
14178 (interactive)
14179 (let ((pa '(:org-archived t))
14180 (pc '(:org-comment t))
14181 (pall '(:org-archived t :org-comment t))
14182 (inhibit-read-only t)
14183 (rea (concat ":" org-archive-tag ":"))
14184 bmp file re)
14185 (save-excursion
14186 (save-restriction
14187 (while (setq file (pop files))
14188 (catch 'nextfile
14189 (if (bufferp file)
14190 (set-buffer file)
14191 (org-check-agenda-file file)
14192 (set-buffer (org-get-agenda-file-buffer file)))
14193 (widen)
14194 (setq bmp (buffer-modified-p))
14195 (org-refresh-category-properties)
14196 (setq org-todo-keywords-for-agenda
14197 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14198 (setq org-done-keywords-for-agenda
14199 (append org-done-keywords-for-agenda org-done-keywords))
14200 (setq org-todo-keyword-alist-for-agenda
14201 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14202 (setq org-drawers-for-agenda
14203 (append org-drawers-for-agenda org-drawers))
14204 (setq org-tag-alist-for-agenda
14205 (append org-tag-alist-for-agenda org-tag-alist))
14207 (save-excursion
14208 (remove-text-properties (point-min) (point-max) pall)
14209 (when org-agenda-skip-archived-trees
14210 (goto-char (point-min))
14211 (while (re-search-forward rea nil t)
14212 (if (org-on-heading-p t)
14213 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14214 (goto-char (point-min))
14215 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14216 (while (re-search-forward re nil t)
14217 (add-text-properties
14218 (match-beginning 0) (org-end-of-subtree t) pc)))
14219 (set-buffer-modified-p bmp)))))
14220 (setq org-todo-keyword-alist-for-agenda
14221 (org-uniquify org-todo-keyword-alist-for-agenda)
14222 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14224 ;;;; Embedded LaTeX
14226 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14227 "Keymap for the minor `org-cdlatex-mode'.")
14229 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14230 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14231 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14232 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14233 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14235 (defvar org-cdlatex-texmathp-advice-is-done nil
14236 "Flag remembering if we have applied the advice to texmathp already.")
14238 (define-minor-mode org-cdlatex-mode
14239 "Toggle the minor `org-cdlatex-mode'.
14240 This mode supports entering LaTeX environment and math in LaTeX fragments
14241 in Org-mode.
14242 \\{org-cdlatex-mode-map}"
14243 nil " OCDL" nil
14244 (when org-cdlatex-mode (require 'cdlatex))
14245 (unless org-cdlatex-texmathp-advice-is-done
14246 (setq org-cdlatex-texmathp-advice-is-done t)
14247 (defadvice texmathp (around org-math-always-on activate)
14248 "Always return t in org-mode buffers.
14249 This is because we want to insert math symbols without dollars even outside
14250 the LaTeX math segments. If Orgmode thinks that point is actually inside
14251 an embedded LaTeX fragment, let texmathp do its job.
14252 \\[org-cdlatex-mode-map]"
14253 (interactive)
14254 (let (p)
14255 (cond
14256 ((not (org-mode-p)) ad-do-it)
14257 ((eq this-command 'cdlatex-math-symbol)
14258 (setq ad-return-value t
14259 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14261 (let ((p (org-inside-LaTeX-fragment-p)))
14262 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14263 (setq ad-return-value t
14264 texmathp-why '("Org-mode embedded math" . 0))
14265 (if p ad-do-it)))))))))
14267 (defun turn-on-org-cdlatex ()
14268 "Unconditionally turn on `org-cdlatex-mode'."
14269 (org-cdlatex-mode 1))
14271 (defun org-inside-LaTeX-fragment-p ()
14272 "Test if point is inside a LaTeX fragment.
14273 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14274 sequence appearing also before point.
14275 Even though the matchers for math are configurable, this function assumes
14276 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14277 delimiters are skipped when they have been removed by customization.
14278 The return value is nil, or a cons cell with the delimiter and
14279 and the position of this delimiter.
14281 This function does a reasonably good job, but can locally be fooled by
14282 for example currency specifications. For example it will assume being in
14283 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14284 fragments that are properly closed, but during editing, we have to live
14285 with the uncertainty caused by missing closing delimiters. This function
14286 looks only before point, not after."
14287 (catch 'exit
14288 (let ((pos (point))
14289 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14290 (lim (progn
14291 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14292 (point)))
14293 dd-on str (start 0) m re)
14294 (goto-char pos)
14295 (when dodollar
14296 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14297 re (nth 1 (assoc "$" org-latex-regexps)))
14298 (while (string-match re str start)
14299 (cond
14300 ((= (match-end 0) (length str))
14301 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14302 ((= (match-end 0) (- (length str) 5))
14303 (throw 'exit nil))
14304 (t (setq start (match-end 0))))))
14305 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14306 (goto-char pos)
14307 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14308 (and (match-beginning 2) (throw 'exit nil))
14309 ;; count $$
14310 (while (re-search-backward "\\$\\$" lim t)
14311 (setq dd-on (not dd-on)))
14312 (goto-char pos)
14313 (if dd-on (cons "$$" m))))))
14316 (defun org-try-cdlatex-tab ()
14317 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14318 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14319 - inside a LaTeX fragment, or
14320 - after the first word in a line, where an abbreviation expansion could
14321 insert a LaTeX environment."
14322 (when org-cdlatex-mode
14323 (cond
14324 ((save-excursion
14325 (skip-chars-backward "a-zA-Z0-9*")
14326 (skip-chars-backward " \t")
14327 (bolp))
14328 (cdlatex-tab) t)
14329 ((org-inside-LaTeX-fragment-p)
14330 (cdlatex-tab) t)
14331 (t nil))))
14333 (defun org-cdlatex-underscore-caret (&optional arg)
14334 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14335 Revert to the normal definition outside of these fragments."
14336 (interactive "P")
14337 (if (org-inside-LaTeX-fragment-p)
14338 (call-interactively 'cdlatex-sub-superscript)
14339 (let (org-cdlatex-mode)
14340 (call-interactively (key-binding (vector last-input-event))))))
14342 (defun org-cdlatex-math-modify (&optional arg)
14343 "Execute `cdlatex-math-modify' in LaTeX fragments.
14344 Revert to the normal definition outside of these fragments."
14345 (interactive "P")
14346 (if (org-inside-LaTeX-fragment-p)
14347 (call-interactively 'cdlatex-math-modify)
14348 (let (org-cdlatex-mode)
14349 (call-interactively (key-binding (vector last-input-event))))))
14351 (defvar org-latex-fragment-image-overlays nil
14352 "List of overlays carrying the images of latex fragments.")
14353 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14355 (defun org-remove-latex-fragment-image-overlays ()
14356 "Remove all overlays with LaTeX fragment images in current buffer."
14357 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14358 (setq org-latex-fragment-image-overlays nil))
14360 (defun org-preview-latex-fragment (&optional subtree)
14361 "Preview the LaTeX fragment at point, or all locally or globally.
14362 If the cursor is in a LaTeX fragment, create the image and overlay
14363 it over the source code. If there is no fragment at point, display
14364 all fragments in the current text, from one headline to the next. With
14365 prefix SUBTREE, display all fragments in the current subtree. With a
14366 double prefix `C-u C-u', or when the cursor is before the first headline,
14367 display all fragments in the buffer.
14368 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14369 (interactive "P")
14370 (org-remove-latex-fragment-image-overlays)
14371 (save-excursion
14372 (save-restriction
14373 (let (beg end at msg)
14374 (cond
14375 ((or (equal subtree '(16))
14376 (not (save-excursion
14377 (re-search-backward (concat "^" outline-regexp) nil t))))
14378 (setq beg (point-min) end (point-max)
14379 msg "Creating images for buffer...%s"))
14380 ((equal subtree '(4))
14381 (org-back-to-heading)
14382 (setq beg (point) end (org-end-of-subtree t)
14383 msg "Creating images for subtree...%s"))
14385 (if (setq at (org-inside-LaTeX-fragment-p))
14386 (goto-char (max (point-min) (- (cdr at) 2)))
14387 (org-back-to-heading))
14388 (setq beg (point) end (progn (outline-next-heading) (point))
14389 msg (if at "Creating image...%s"
14390 "Creating images for entry...%s"))))
14391 (message msg "")
14392 (narrow-to-region beg end)
14393 (goto-char beg)
14394 (org-format-latex
14395 (concat "ltxpng/" (file-name-sans-extension
14396 (file-name-nondirectory
14397 buffer-file-name)))
14398 default-directory 'overlays msg at 'forbuffer)
14399 (message msg "done. Use `C-c C-c' to remove images.")))))
14401 (defvar org-latex-regexps
14402 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14403 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14404 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14405 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14406 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14407 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14408 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14409 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14410 "Regular expressions for matching embedded LaTeX.")
14412 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14413 "Replace LaTeX fragments with links to an image, and produce images.
14414 Some of the options can be changed using the variable
14415 `org-format-latex-options'."
14416 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14417 (let* ((prefixnodir (file-name-nondirectory prefix))
14418 (absprefix (expand-file-name prefix dir))
14419 (todir (file-name-directory absprefix))
14420 (opt org-format-latex-options)
14421 (matchers (plist-get opt :matchers))
14422 (re-list org-latex-regexps)
14423 (cnt 0) txt link beg end re e checkdir
14424 executables-checked
14425 m n block linkfile movefile ov)
14426 ;; Check if there are old images files with this prefix, and remove them
14427 (when (file-directory-p todir)
14428 (mapc 'delete-file
14429 (directory-files
14430 todir 'full
14431 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
14432 ;; Check the different regular expressions
14433 (while (setq e (pop re-list))
14434 (setq m (car e) re (nth 1 e) n (nth 2 e)
14435 block (if (nth 3 e) "\n\n" ""))
14436 (when (member m matchers)
14437 (goto-char (point-min))
14438 (while (re-search-forward re nil t)
14439 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14440 (not (get-text-property (match-beginning n)
14441 'org-protected))
14442 (or (not overlays)
14443 (not (eq (get-char-property (match-beginning n)
14444 'org-overlay-type)
14445 'org-latex-overlay))))
14446 (setq txt (match-string n)
14447 beg (match-beginning n) end (match-end n)
14448 cnt (1+ cnt)
14449 linkfile (format "%s_%04d.png" prefix cnt)
14450 movefile (format "%s_%04d.png" absprefix cnt)
14451 link (concat block "[[file:" linkfile "]]" block))
14452 (if msg (message msg cnt))
14453 (goto-char beg)
14454 (unless checkdir ; make sure the directory exists
14455 (setq checkdir t)
14456 (or (file-directory-p todir) (make-directory todir)))
14458 (unless executables-checked
14459 (org-check-external-command
14460 "latex" "needed to convert LaTeX fragments to images")
14461 (org-check-external-command
14462 "dvipng" "needed to convert LaTeX fragments to images")
14463 (setq executables-checked t))
14465 (org-create-formula-image
14466 txt movefile opt forbuffer)
14467 (if overlays
14468 (progn
14469 (mapc (lambda (o)
14470 (if (eq (org-overlay-get o 'org-overlay-type)
14471 'org-latex-overlay)
14472 (org-delete-overlay o)))
14473 (org-overlays-in beg end))
14474 (setq ov (org-make-overlay beg end))
14475 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14476 (if (featurep 'xemacs)
14477 (progn
14478 (org-overlay-put ov 'invisible t)
14479 (org-overlay-put
14480 ov 'end-glyph
14481 (make-glyph (vector 'png :file movefile))))
14482 (org-overlay-put
14483 ov 'display
14484 (list 'image :type 'png :file movefile :ascent 'center)))
14485 (push ov org-latex-fragment-image-overlays)
14486 (goto-char end))
14487 (delete-region beg end)
14488 (insert link))))))))
14490 (defvar org-export-latex-packages-alist) ;; defined in org-latex.el
14491 ;; This function borrows from Ganesh Swami's latex2png.el
14492 (defun org-create-formula-image (string tofile options buffer)
14493 "This calls dvipng."
14494 (require 'org-latex)
14495 (let* ((tmpdir (if (featurep 'xemacs)
14496 (temp-directory)
14497 temporary-file-directory))
14498 (texfilebase (make-temp-name
14499 (expand-file-name "orgtex" tmpdir)))
14500 (texfile (concat texfilebase ".tex"))
14501 (dvifile (concat texfilebase ".dvi"))
14502 (pngfile (concat texfilebase ".png"))
14503 (fnh (if (featurep 'xemacs)
14504 (font-height (get-face-font 'default))
14505 (face-attribute 'default :height nil)))
14506 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14507 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14508 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14509 "Black"))
14510 (bg (or (plist-get options (if buffer :background :html-background))
14511 "Transparent")))
14512 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14513 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14514 (with-temp-file texfile
14515 (insert org-format-latex-header
14516 (if org-export-latex-packages-alist
14517 (concat "\n"
14518 (mapconcat (lambda(p)
14519 (if (equal "" (car p))
14520 (format "\\usepackage{%s}" (cadr p))
14521 (format "\\usepackage[%s]{%s}"
14522 (car p) (cadr p))))
14523 org-export-latex-packages-alist "\n"))
14525 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14526 (let ((dir default-directory))
14527 (condition-case nil
14528 (progn
14529 (cd tmpdir)
14530 (call-process "latex" nil nil nil texfile))
14531 (error nil))
14532 (cd dir))
14533 (if (not (file-exists-p dvifile))
14534 (progn (message "Failed to create dvi file from %s" texfile) nil)
14535 (condition-case nil
14536 (call-process "dvipng" nil nil nil
14537 "-fg" fg "-bg" bg
14538 "-D" dpi
14539 ;;"-x" scale "-y" scale
14540 "-T" "tight"
14541 "-o" pngfile
14542 dvifile)
14543 (error nil))
14544 (if (not (file-exists-p pngfile))
14545 (progn (message "Failed to create png file from %s" texfile) nil)
14546 ;; Use the requested file name and clean up
14547 (copy-file pngfile tofile 'replace)
14548 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14549 (delete-file (concat texfilebase e)))
14550 pngfile))))
14552 (defun org-dvipng-color (attr)
14553 "Return an rgb color specification for dvipng."
14554 (apply 'format "rgb %s %s %s"
14555 (mapcar 'org-normalize-color
14556 (color-values (face-attribute 'default attr nil)))))
14558 (defun org-normalize-color (value)
14559 "Return string to be used as color value for an RGB component."
14560 (format "%g" (/ value 65535.0)))
14562 ;;;; Key bindings
14564 ;; Make `C-c C-x' a prefix key
14565 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14567 ;; TAB key with modifiers
14568 (org-defkey org-mode-map "\C-i" 'org-cycle)
14569 (org-defkey org-mode-map [(tab)] 'org-cycle)
14570 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14571 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14572 (org-defkey org-mode-map "\M-\t" 'org-complete)
14573 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14574 ;; The following line is necessary under Suse GNU/Linux
14575 (unless (featurep 'xemacs)
14576 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14577 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14578 (define-key org-mode-map [backtab] 'org-shifttab)
14580 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14581 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14582 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14584 ;; Cursor keys with modifiers
14585 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14586 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14587 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14588 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14590 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14591 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14592 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14593 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14595 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14596 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14597 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14598 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14600 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14601 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14603 ;;; Extra keys for tty access.
14604 ;; We only set them when really needed because otherwise the
14605 ;; menus don't show the simple keys
14607 (when (or org-use-extra-keys
14608 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14609 (not window-system))
14610 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14611 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14612 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14613 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14614 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14615 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14616 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14617 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14618 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14619 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14620 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14621 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14622 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14623 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14624 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14625 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14626 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14627 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14628 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14629 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14630 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14631 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14632 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14633 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14634 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14635 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14636 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14637 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14639 ;; All the other keys
14641 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14642 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14643 (if (boundp 'narrow-map)
14644 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14645 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14646 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14647 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14648 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14649 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14650 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
14651 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14652 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14653 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14654 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14655 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14656 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14657 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14658 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14659 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14660 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14661 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14662 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14663 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14664 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14665 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14666 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14667 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14668 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14669 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14670 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14671 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14672 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14673 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14674 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14675 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14676 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14677 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14678 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14679 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14680 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14681 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14682 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14683 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14684 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14685 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14686 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14687 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14688 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14689 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14690 (org-defkey org-mode-map "\C-c^" 'org-sort)
14691 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14692 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14693 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
14694 (org-defkey org-mode-map "\C-m" 'org-return)
14695 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14696 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14697 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14698 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14699 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14700 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14701 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14702 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14703 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14704 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14705 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14706 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14707 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14708 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14709 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14710 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14711 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14712 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
14713 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
14714 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14715 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14717 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14718 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14719 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14720 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14722 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14723 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14724 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14725 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14726 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14727 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14728 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14729 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14730 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14731 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14732 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14733 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
14734 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14735 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14736 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14738 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14739 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14740 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14741 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14743 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14745 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14747 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14748 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14750 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14753 (when (featurep 'xemacs)
14754 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14757 (defconst org-speed-commands-default
14759 ("a" . org-agenda)
14760 ("/" . org-sparse-tree)
14761 (";" . org-set-tags-command)
14762 ("I" . org-clock-in)
14763 ("O" . org-clock-out)
14764 ("c" . org-cycle)
14765 ("C" . org-shifttab)
14766 ("n" . outline-next-visible-heading)
14767 ("p" . outline-previous-visible-heading)
14768 ("f" . org-forward-same-level)
14769 ("b" . org-backward-same-level)
14770 ("u" . outline-up-heading)
14771 ("U" . org-shiftmetaup)
14772 ("D" . org-shiftmetadown)
14773 ("r" . org-metaright)
14774 ("l" . org-metaleft)
14775 ("R" . org-shiftmetaright)
14776 ("L" . org-shiftmetaleft)
14777 ("i" . (progn (forward-char 1) (call-interactively
14778 'org-insert-heading-respect-content)))
14779 ("o" . org-open-at-point)
14780 ("t" . org-todo)
14781 ("j" . org-goto)
14782 ("g" . (org-refile t))
14783 ("e" . org-set-effort)
14784 ("0" . (org-priority ?\ ))
14785 ("1" . (org-priority ?A))
14786 ("2" . (org-priority ?B))
14787 ("3" . (org-priority ?C))
14788 ("." . outline-mark-subtree)
14789 ("^" . org-sort)
14790 ("w" . org-refile)
14791 ("a" . org-archive-subtree-default-with-confirmation)
14792 ("/" . org-sparse-tree)
14793 ("?" . org-speed-command-help)
14795 "The default speed commands.")
14797 (defun org-print-speed-command (e)
14798 (princ (car e))
14799 (princ " ")
14800 (if (symbolp (cdr e))
14801 (princ (symbol-name (cdr e)))
14802 (prin1 (cdr e)))
14803 (princ "\n"))
14805 (defun org-speed-command-help ()
14806 "Show the available speed commands."
14807 (interactive)
14808 (if (not org-use-speed-commands)
14809 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
14810 (with-output-to-temp-buffer "*Help*"
14811 (princ "Speed commands\n==============\n")
14812 (mapc 'org-print-speed-command org-speed-commands-user)
14813 (princ "\n")
14814 (mapc 'org-print-speed-command org-speed-commands-default))))
14816 (defvar org-self-insert-command-undo-counter 0)
14818 (defvar org-table-auto-blank-field) ; defined in org-table.el
14819 (defvar org-speed-command nil)
14820 (defun org-self-insert-command (N)
14821 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14822 If the cursor is in a table looking at whitespace, the whitespace is
14823 overwritten, and the table is not marked as requiring realignment."
14824 (interactive "p")
14825 (cond
14826 ((and org-use-speed-commands
14827 (bolp)
14828 (looking-at outline-regexp)
14829 (setq
14830 org-speed-command
14831 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
14832 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
14833 (cond
14834 ((commandp org-speed-command)
14835 (setq this-command org-speed-command)
14836 (call-interactively org-speed-command))
14837 ((functionp org-speed-command)
14838 (funcall org-speed-command))
14839 ((and org-speed-command (listp org-speed-command))
14840 (eval org-speed-command))
14841 (t (let (org-use-speed-commands)
14842 (call-interactively 'org-self-insert-command)))))
14843 ((and
14844 (org-table-p)
14845 (progn
14846 ;; check if we blank the field, and if that triggers align
14847 (and (featurep 'org-table) org-table-auto-blank-field
14848 (member last-command
14849 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
14850 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14851 ;; got extra space, this field does not determine column width
14852 (let (org-table-may-need-update) (org-table-blank-field))
14853 ;; no extra space, this field may determine column width
14854 (org-table-blank-field)))
14856 (eq N 1)
14857 (looking-at "[^|\n]* |"))
14858 (let (org-table-may-need-update)
14859 (goto-char (1- (match-end 0)))
14860 (delete-backward-char 1)
14861 (goto-char (match-beginning 0))
14862 (self-insert-command N)))
14864 (setq org-table-may-need-update t)
14865 (self-insert-command N)
14866 (org-fix-tags-on-the-fly)
14867 (if org-self-insert-cluster-for-undo
14868 (if (not (eq last-command 'org-self-insert-command))
14869 (setq org-self-insert-command-undo-counter 1)
14870 (if (>= org-self-insert-command-undo-counter 20)
14871 (setq org-self-insert-command-undo-counter 1)
14872 (and (> org-self-insert-command-undo-counter 0)
14873 buffer-undo-list
14874 (not (cadr buffer-undo-list)) ; remove nil entry
14875 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14876 (setq org-self-insert-command-undo-counter
14877 (1+ org-self-insert-command-undo-counter))))))))
14879 (defun org-fix-tags-on-the-fly ()
14880 (when (and (equal (char-after (point-at-bol)) ?*)
14881 (org-on-heading-p))
14882 (org-align-tags-here org-tags-column)))
14884 (defun org-delete-backward-char (N)
14885 "Like `delete-backward-char', insert whitespace at field end in tables.
14886 When deleting backwards, in tables this function will insert whitespace in
14887 front of the next \"|\" separator, to keep the table aligned. The table will
14888 still be marked for re-alignment if the field did fill the entire column,
14889 because, in this case the deletion might narrow the column."
14890 (interactive "p")
14891 (if (and (org-table-p)
14892 (eq N 1)
14893 (string-match "|" (buffer-substring (point-at-bol) (point)))
14894 (looking-at ".*?|"))
14895 (let ((pos (point))
14896 (noalign (looking-at "[^|\n\r]* |"))
14897 (c org-table-may-need-update))
14898 (backward-delete-char N)
14899 (skip-chars-forward "^|")
14900 (insert " ")
14901 (goto-char (1- pos))
14902 ;; noalign: if there were two spaces at the end, this field
14903 ;; does not determine the width of the column.
14904 (if noalign (setq org-table-may-need-update c)))
14905 (backward-delete-char N)
14906 (org-fix-tags-on-the-fly)))
14908 (defun org-delete-char (N)
14909 "Like `delete-char', but insert whitespace at field end in tables.
14910 When deleting characters, in tables this function will insert whitespace in
14911 front of the next \"|\" separator, to keep the table aligned. The table will
14912 still be marked for re-alignment if the field did fill the entire column,
14913 because, in this case the deletion might narrow the column."
14914 (interactive "p")
14915 (if (and (org-table-p)
14916 (not (bolp))
14917 (not (= (char-after) ?|))
14918 (eq N 1))
14919 (if (looking-at ".*?|")
14920 (let ((pos (point))
14921 (noalign (looking-at "[^|\n\r]* |"))
14922 (c org-table-may-need-update))
14923 (replace-match (concat
14924 (substring (match-string 0) 1 -1)
14925 " |"))
14926 (goto-char pos)
14927 ;; noalign: if there were two spaces at the end, this field
14928 ;; does not determine the width of the column.
14929 (if noalign (setq org-table-may-need-update c)))
14930 (delete-char N))
14931 (delete-char N)
14932 (org-fix-tags-on-the-fly)))
14934 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14935 (put 'org-self-insert-command 'delete-selection t)
14936 (put 'orgtbl-self-insert-command 'delete-selection t)
14937 (put 'org-delete-char 'delete-selection 'supersede)
14938 (put 'org-delete-backward-char 'delete-selection 'supersede)
14939 (put 'org-yank 'delete-selection 'yank)
14941 ;; Make `flyspell-mode' delay after some commands
14942 (put 'org-self-insert-command 'flyspell-delayed t)
14943 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14944 (put 'org-delete-char 'flyspell-delayed t)
14945 (put 'org-delete-backward-char 'flyspell-delayed t)
14947 ;; Make pabbrev-mode expand after org-mode commands
14948 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14949 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14951 ;; How to do this: Measure non-white length of current string
14952 ;; If equal to column width, we should realign.
14954 (defun org-remap (map &rest commands)
14955 "In MAP, remap the functions given in COMMANDS.
14956 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14957 (let (new old)
14958 (while commands
14959 (setq old (pop commands) new (pop commands))
14960 (if (fboundp 'command-remapping)
14961 (org-defkey map (vector 'remap old) new)
14962 (substitute-key-definition old new map global-map)))))
14964 (when (eq org-enable-table-editor 'optimized)
14965 ;; If the user wants maximum table support, we need to hijack
14966 ;; some standard editing functions
14967 (org-remap org-mode-map
14968 'self-insert-command 'org-self-insert-command
14969 'delete-char 'org-delete-char
14970 'delete-backward-char 'org-delete-backward-char)
14971 (org-defkey org-mode-map "|" 'org-force-self-insert))
14973 (defvar org-ctrl-c-ctrl-c-hook nil
14974 "Hook for functions attaching themselves to `C-c C-c'.
14975 This can be used to add additional functionality to the C-c C-c key which
14976 executes context-dependent commands.
14977 Each function will be called with no arguments. The function must check
14978 if the context is appropriate for it to act. If yes, it should do its
14979 thing and then return a non-nil value. If the context is wrong,
14980 just do nothing and return nil.")
14982 (defvar org-tab-first-hook nil
14983 "Hook for functions to attach themselves to TAB.
14984 See `org-ctrl-c-ctrl-c-hook' for more information.
14985 This hook runs as the first action when TAB is pressed, even before
14986 `org-cycle' messes around with the `outline-regexp' to cater for
14987 inline tasks and plain list item folding.
14988 If any function in this hook returns t, not other actions like table
14989 field motion visibility cycling will be done.")
14991 (defvar org-tab-after-check-for-table-hook nil
14992 "Hook for functions to attach themselves to TAB.
14993 See `org-ctrl-c-ctrl-c-hook' for more information.
14994 This hook runs after it has been established that the cursor is not in a
14995 table, but before checking if the cursor is in a headline or if global cycling
14996 should be done.
14997 If any function in this hook returns t, not other actions like visibility
14998 cycling will be done.")
15000 (defvar org-tab-after-check-for-cycling-hook nil
15001 "Hook for functions to attach themselves to TAB.
15002 See `org-ctrl-c-ctrl-c-hook' for more information.
15003 This hook runs after it has been established that not table field motion and
15004 not visibility should be done because of current context. This is probably
15005 the place where a package like yasnippets can hook in.")
15007 (defvar org-tab-before-tab-emulation-hook nil
15008 "Hook for functions to attach themselves to TAB.
15009 See `org-ctrl-c-ctrl-c-hook' for more information.
15010 This hook runs after every other options for TAB have been exhausted, but
15011 before indentation and \t insertion takes place.")
15013 (defvar org-metaleft-hook nil
15014 "Hook for functions attaching themselves to `M-left'.
15015 See `org-ctrl-c-ctrl-c-hook' for more information.")
15016 (defvar org-metaright-hook nil
15017 "Hook for functions attaching themselves to `M-right'.
15018 See `org-ctrl-c-ctrl-c-hook' for more information.")
15019 (defvar org-metaup-hook nil
15020 "Hook for functions attaching themselves to `M-up'.
15021 See `org-ctrl-c-ctrl-c-hook' for more information.")
15022 (defvar org-metadown-hook nil
15023 "Hook for functions attaching themselves to `M-down'.
15024 See `org-ctrl-c-ctrl-c-hook' for more information.")
15025 (defvar org-shiftmetaleft-hook nil
15026 "Hook for functions attaching themselves to `M-S-left'.
15027 See `org-ctrl-c-ctrl-c-hook' for more information.")
15028 (defvar org-shiftmetaright-hook nil
15029 "Hook for functions attaching themselves to `M-S-right'.
15030 See `org-ctrl-c-ctrl-c-hook' for more information.")
15031 (defvar org-shiftmetaup-hook nil
15032 "Hook for functions attaching themselves to `M-S-up'.
15033 See `org-ctrl-c-ctrl-c-hook' for more information.")
15034 (defvar org-shiftmetadown-hook nil
15035 "Hook for functions attaching themselves to `M-S-down'.
15036 See `org-ctrl-c-ctrl-c-hook' for more information.")
15037 (defvar org-metareturn-hook nil
15038 "Hook for functions attaching themselves to `M-RET'.
15039 See `org-ctrl-c-ctrl-c-hook' for more information.")
15041 (defun org-modifier-cursor-error ()
15042 "Throw an error, a modified cursor command was applied in wrong context."
15043 (error "This command is active in special context like tables, headlines or items"))
15045 (defun org-shiftselect-error ()
15046 "Throw an error because Shift-Cursor command was applied in wrong context."
15047 (if (and (boundp 'shift-select-mode) shift-select-mode)
15048 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15049 (error "This command works only in special context like headlines or timestamps")))
15051 (defun org-call-for-shift-select (cmd)
15052 (let ((this-command-keys-shift-translated t))
15053 (call-interactively cmd)))
15055 (defun org-shifttab (&optional arg)
15056 "Global visibility cycling or move to previous table field.
15057 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15058 on context.
15059 See the individual commands for more information."
15060 (interactive "P")
15061 (cond
15062 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15063 ((integerp arg)
15064 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15065 (message "Content view to level: %d" arg)
15066 (org-content (prefix-numeric-value arg2))
15067 (setq org-cycle-global-status 'overview)))
15068 (t (call-interactively 'org-global-cycle))))
15070 (defun org-shiftmetaleft ()
15071 "Promote subtree or delete table column.
15072 Calls `org-promote-subtree', `org-outdent-item',
15073 or `org-table-delete-column', depending on context.
15074 See the individual commands for more information."
15075 (interactive)
15076 (cond
15077 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15078 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15079 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15080 ((org-at-item-p) (call-interactively 'org-outdent-item))
15081 (t (org-modifier-cursor-error))))
15083 (defun org-shiftmetaright ()
15084 "Demote subtree or insert table column.
15085 Calls `org-demote-subtree', `org-indent-item',
15086 or `org-table-insert-column', depending on context.
15087 See the individual commands for more information."
15088 (interactive)
15089 (cond
15090 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15091 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15092 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15093 ((org-at-item-p) (call-interactively 'org-indent-item))
15094 (t (org-modifier-cursor-error))))
15096 (defun org-shiftmetaup (&optional arg)
15097 "Move subtree up or kill table row.
15098 Calls `org-move-subtree-up' or `org-table-kill-row' or
15099 `org-move-item-up' depending on context. See the individual commands
15100 for more information."
15101 (interactive "P")
15102 (cond
15103 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15104 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15105 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15106 ((org-at-item-p) (call-interactively 'org-move-item-up))
15107 (t (org-modifier-cursor-error))))
15109 (defun org-shiftmetadown (&optional arg)
15110 "Move subtree down or insert table row.
15111 Calls `org-move-subtree-down' or `org-table-insert-row' or
15112 `org-move-item-down', depending on context. See the individual
15113 commands for more information."
15114 (interactive "P")
15115 (cond
15116 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15117 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15118 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15119 ((org-at-item-p) (call-interactively 'org-move-item-down))
15120 (t (org-modifier-cursor-error))))
15122 (defun org-metaleft (&optional arg)
15123 "Promote heading or move table column to left.
15124 Calls `org-do-promote' or `org-table-move-column', depending on context.
15125 With no specific context, calls the Emacs default `backward-word'.
15126 See the individual commands for more information."
15127 (interactive "P")
15128 (cond
15129 ((run-hook-with-args-until-success 'org-metaleft-hook))
15130 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15131 ((or (org-on-heading-p)
15132 (and (org-region-active-p)
15133 (save-excursion
15134 (goto-char (region-beginning))
15135 (org-on-heading-p))))
15136 (call-interactively 'org-do-promote))
15137 ((or (org-at-item-p)
15138 (and (org-region-active-p)
15139 (save-excursion
15140 (goto-char (region-beginning))
15141 (org-at-item-p))))
15142 (call-interactively 'org-outdent-item))
15143 (t (call-interactively 'backward-word))))
15145 (defun org-metaright (&optional arg)
15146 "Demote subtree or move table column to right.
15147 Calls `org-do-demote' or `org-table-move-column', depending on context.
15148 With no specific context, calls the Emacs default `forward-word'.
15149 See the individual commands for more information."
15150 (interactive "P")
15151 (cond
15152 ((run-hook-with-args-until-success 'org-metaright-hook))
15153 ((org-at-table-p) (call-interactively 'org-table-move-column))
15154 ((or (org-on-heading-p)
15155 (and (org-region-active-p)
15156 (save-excursion
15157 (goto-char (region-beginning))
15158 (org-on-heading-p))))
15159 (call-interactively 'org-do-demote))
15160 ((or (org-at-item-p)
15161 (and (org-region-active-p)
15162 (save-excursion
15163 (goto-char (region-beginning))
15164 (org-at-item-p))))
15165 (call-interactively 'org-indent-item))
15166 (t (call-interactively 'forward-word))))
15168 (defun org-metaup (&optional arg)
15169 "Move subtree up or move table row up.
15170 Calls `org-move-subtree-up' or `org-table-move-row' or
15171 `org-move-item-up', depending on context. See the individual commands
15172 for more information."
15173 (interactive "P")
15174 (cond
15175 ((run-hook-with-args-until-success 'org-metaup-hook))
15176 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15177 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15178 ((org-at-item-p) (call-interactively 'org-move-item-up))
15179 (t (transpose-lines 1) (beginning-of-line -1))))
15181 (defun org-metadown (&optional arg)
15182 "Move subtree down or move table row down.
15183 Calls `org-move-subtree-down' or `org-table-move-row' or
15184 `org-move-item-down', depending on context. See the individual
15185 commands for more information."
15186 (interactive "P")
15187 (cond
15188 ((run-hook-with-args-until-success 'org-metadown-hook))
15189 ((org-at-table-p) (call-interactively 'org-table-move-row))
15190 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15191 ((org-at-item-p) (call-interactively 'org-move-item-down))
15192 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15194 (defun org-shiftup (&optional arg)
15195 "Increase item in timestamp or increase priority of current headline.
15196 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15197 depending on context. See the individual commands for more information."
15198 (interactive "P")
15199 (cond
15200 ((and org-support-shift-select (org-region-active-p))
15201 (org-call-for-shift-select 'previous-line))
15202 ((org-at-timestamp-p t)
15203 (call-interactively (if org-edit-timestamp-down-means-later
15204 'org-timestamp-down 'org-timestamp-up)))
15205 ((and (not (eq org-support-shift-select 'always))
15206 org-enable-priority-commands
15207 (org-on-heading-p))
15208 (call-interactively 'org-priority-up))
15209 ((and (not org-support-shift-select) (org-at-item-p))
15210 (call-interactively 'org-previous-item))
15211 ((org-clocktable-try-shift 'up arg))
15212 (org-support-shift-select
15213 (org-call-for-shift-select 'previous-line))
15214 (t (org-shiftselect-error))))
15216 (defun org-shiftdown (&optional arg)
15217 "Decrease item in timestamp or decrease priority of current headline.
15218 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15219 depending on context. See the individual commands for more information."
15220 (interactive "P")
15221 (cond
15222 ((and org-support-shift-select (org-region-active-p))
15223 (org-call-for-shift-select 'next-line))
15224 ((org-at-timestamp-p t)
15225 (call-interactively (if org-edit-timestamp-down-means-later
15226 'org-timestamp-up 'org-timestamp-down)))
15227 ((and (not (eq org-support-shift-select 'always))
15228 org-enable-priority-commands
15229 (org-on-heading-p))
15230 (call-interactively 'org-priority-down))
15231 ((and (not org-support-shift-select) (org-at-item-p))
15232 (call-interactively 'org-next-item))
15233 ((org-clocktable-try-shift 'down arg))
15234 (org-support-shift-select
15235 (org-call-for-shift-select 'next-line))
15236 (t (org-shiftselect-error))))
15238 (defun org-shiftright (&optional arg)
15239 "Cycle the thing at point or in the current line, depending on context.
15240 Depending on context, this does one of the following:
15242 - switch a timestamp at point one day into the future
15243 - on a headline, switch to the next TODO keyword.
15244 - on an item, switch entire list to the next bullet type
15245 - on a property line, switch to the next allowed value
15246 - on a clocktable definition line, move time block into the future"
15247 (interactive "P")
15248 (cond
15249 ((and org-support-shift-select (org-region-active-p))
15250 (org-call-for-shift-select 'forward-char))
15251 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15252 ((and (not (eq org-support-shift-select 'always))
15253 (org-on-heading-p))
15254 (let ((org-inhibit-logging
15255 (not org-treat-S-cursor-todo-selection-as-state-change))
15256 (org-inhibit-blocking
15257 (not org-treat-S-cursor-todo-selection-as-state-change)))
15258 (org-call-with-arg 'org-todo 'right)))
15259 ((or (and org-support-shift-select
15260 (not (eq org-support-shift-select 'always))
15261 (org-at-item-bullet-p))
15262 (and (not org-support-shift-select) (org-at-item-p)))
15263 (org-call-with-arg 'org-cycle-list-bullet nil))
15264 ((and (not (eq org-support-shift-select 'always))
15265 (org-at-property-p))
15266 (call-interactively 'org-property-next-allowed-value))
15267 ((org-clocktable-try-shift 'right arg))
15268 (org-support-shift-select
15269 (org-call-for-shift-select 'forward-char))
15270 (t (org-shiftselect-error))))
15272 (defun org-shiftleft (&optional arg)
15273 "Cycle the thing at point or in the current line, depending on context.
15274 Depending on context, this does one of the following:
15276 - switch a timestamp at point one day into the past
15277 - on a headline, switch to the previous TODO keyword.
15278 - on an item, switch entire list to the previous bullet type
15279 - on a property line, switch to the previous allowed value
15280 - on a clocktable definition line, move time block into the past"
15281 (interactive "P")
15282 (cond
15283 ((and org-support-shift-select (org-region-active-p))
15284 (org-call-for-shift-select 'backward-char))
15285 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15286 ((and (not (eq org-support-shift-select 'always))
15287 (org-on-heading-p))
15288 (let ((org-inhibit-logging
15289 (not org-treat-S-cursor-todo-selection-as-state-change))
15290 (org-inhibit-blocking
15291 (not org-treat-S-cursor-todo-selection-as-state-change)))
15292 (org-call-with-arg 'org-todo 'left)))
15293 ((or (and org-support-shift-select
15294 (not (eq org-support-shift-select 'always))
15295 (org-at-item-bullet-p))
15296 (and (not org-support-shift-select) (org-at-item-p)))
15297 (org-call-with-arg 'org-cycle-list-bullet 'previous))
15298 ((and (not (eq org-support-shift-select 'always))
15299 (org-at-property-p))
15300 (call-interactively 'org-property-previous-allowed-value))
15301 ((org-clocktable-try-shift 'left arg))
15302 (org-support-shift-select
15303 (org-call-for-shift-select 'backward-char))
15304 (t (org-shiftselect-error))))
15306 (defun org-shiftcontrolright ()
15307 "Switch to next TODO set."
15308 (interactive)
15309 (cond
15310 ((and org-support-shift-select (org-region-active-p))
15311 (org-call-for-shift-select 'forward-word))
15312 ((and (not (eq org-support-shift-select 'always))
15313 (org-on-heading-p))
15314 (org-call-with-arg 'org-todo 'nextset))
15315 (org-support-shift-select
15316 (org-call-for-shift-select 'forward-word))
15317 (t (org-shiftselect-error))))
15319 (defun org-shiftcontrolleft ()
15320 "Switch to previous TODO set."
15321 (interactive)
15322 (cond
15323 ((and org-support-shift-select (org-region-active-p))
15324 (org-call-for-shift-select 'backward-word))
15325 ((and (not (eq org-support-shift-select 'always))
15326 (org-on-heading-p))
15327 (org-call-with-arg 'org-todo 'previousset))
15328 (org-support-shift-select
15329 (org-call-for-shift-select 'backward-word))
15330 (t (org-shiftselect-error))))
15332 (defun org-ctrl-c-ret ()
15333 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15334 (interactive)
15335 (cond
15336 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15337 (t (call-interactively 'org-insert-heading))))
15339 (defun org-copy-special ()
15340 "Copy region in table or copy current subtree.
15341 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15342 See the individual commands for more information."
15343 (interactive)
15344 (call-interactively
15345 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15347 (defun org-cut-special ()
15348 "Cut region in table or cut current subtree.
15349 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15350 See the individual commands for more information."
15351 (interactive)
15352 (call-interactively
15353 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15355 (defun org-paste-special (arg)
15356 "Paste rectangular region into table, or past subtree relative to level.
15357 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15358 See the individual commands for more information."
15359 (interactive "P")
15360 (if (org-at-table-p)
15361 (org-table-paste-rectangle)
15362 (org-paste-subtree arg)))
15364 (defun org-edit-special ()
15365 "Call a special editor for the stuff at point.
15366 When at a table, call the formula editor with `org-table-edit-formulas'.
15367 When at the first line of an src example, call `org-edit-src-code'.
15368 When in an #+include line, visit the include file. Otherwise call
15369 `ffap' to visit the file at point."
15370 (interactive)
15371 (cond
15372 ((org-at-table-p)
15373 (call-interactively 'org-table-edit-formulas))
15374 ((save-excursion
15375 (beginning-of-line 1)
15376 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
15377 (find-file (org-trim (match-string 1))))
15378 ((org-edit-src-code))
15379 ((org-edit-fixed-width-region))
15380 (t (call-interactively 'ffap))))
15383 (defun org-ctrl-c-ctrl-c (&optional arg)
15384 "Set tags in headline, or update according to changed information at point.
15386 This command does many different things, depending on context:
15388 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15389 this is what we do.
15391 - If the cursor is on a statistics cookie, update it.
15393 - If the cursor is in a headline, prompt for tags and insert them
15394 into the current line, aligned to `org-tags-column'. When called
15395 with prefix arg, realign all tags in the current buffer.
15397 - If the cursor is in one of the special #+KEYWORD lines, this
15398 triggers scanning the buffer for these lines and updating the
15399 information.
15401 - If the cursor is inside a table, realign the table. This command
15402 works even if the automatic table editor has been turned off.
15404 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15405 the entire table.
15407 - If the cursor is at a footnote reference or definition, jump to
15408 the corresponding definition or references, respectively.
15410 - If the cursor is a the beginning of a dynamic block, update it.
15412 - If the cursor is inside a table created by the table.el package,
15413 activate that table.
15415 - If the current buffer is a remember buffer, close note and file
15416 it. A prefix argument of 1 files to the default location
15417 without further interaction. A prefix argument of 2 files to
15418 the currently clocking task.
15420 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15421 links in this buffer.
15423 - If the cursor is on a numbered item in a plain list, renumber the
15424 ordered list.
15426 - If the cursor is on a checkbox, toggle it."
15427 (interactive "P")
15428 (let ((org-enable-table-editor t))
15429 (cond
15430 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15431 org-occur-highlights
15432 org-latex-fragment-image-overlays)
15433 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15434 (org-remove-occur-highlights)
15435 (org-remove-latex-fragment-image-overlays)
15436 (message "Temporary highlights/overlays removed from current buffer"))
15437 ((and (local-variable-p 'org-finish-function (current-buffer))
15438 (fboundp org-finish-function))
15439 (funcall org-finish-function))
15440 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15441 ((org-at-property-p)
15442 (call-interactively 'org-property-action))
15443 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15444 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15445 (or (org-on-heading-p) (org-at-item-p)))
15446 (call-interactively 'org-update-statistics-cookies))
15447 ((org-on-heading-p) (call-interactively 'org-set-tags))
15448 ((org-at-table.el-p)
15449 (require 'table)
15450 (beginning-of-line 1)
15451 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15452 (call-interactively 'table-recognize-table))
15453 ((org-at-table-p)
15454 (org-table-maybe-eval-formula)
15455 (if arg
15456 (call-interactively 'org-table-recalculate)
15457 (org-table-maybe-recalculate-line))
15458 (call-interactively 'org-table-align))
15459 ((or (org-footnote-at-reference-p)
15460 (org-footnote-at-definition-p))
15461 (call-interactively 'org-footnote-action))
15462 ((org-at-item-checkbox-p)
15463 (call-interactively 'org-toggle-checkbox))
15464 ((org-at-item-p)
15465 (if arg
15466 (call-interactively 'org-toggle-checkbox)
15467 (call-interactively 'org-maybe-renumber-ordered-list)))
15468 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15469 ;; Dynamic block
15470 (beginning-of-line 1)
15471 (save-excursion (org-update-dblock)))
15472 ((save-excursion
15473 (beginning-of-line 1)
15474 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15475 (cond
15476 ((equal (match-string 1) "TBLFM")
15477 ;; Recalculate the table before this line
15478 (save-excursion
15479 (beginning-of-line 1)
15480 (skip-chars-backward " \r\n\t")
15481 (if (org-at-table-p)
15482 (org-call-with-arg 'org-table-recalculate (or arg t)))))
15484 ; (org-set-regexps-and-options)
15485 ; (org-restart-font-lock)
15486 (let ((org-inhibit-startup t)) (org-mode-restart))
15487 (message "Local setup has been refreshed"))))
15488 ((org-clock-update-time-maybe))
15489 (t (error "C-c C-c can do nothing useful at this location")))))
15491 (defun org-mode-restart ()
15492 "Restart Org-mode, to scan again for special lines.
15493 Also updates the keyword regular expressions."
15494 (interactive)
15495 (org-mode)
15496 (message "Org-mode restarted"))
15498 (defun org-kill-note-or-show-branches ()
15499 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15500 (interactive)
15501 (if (not org-finish-function)
15502 (call-interactively 'show-branches)
15503 (let ((org-note-abort t))
15504 (funcall org-finish-function))))
15506 (defun org-return (&optional indent)
15507 "Goto next table row or insert a newline.
15508 Calls `org-table-next-row' or `newline', depending on context.
15509 See the individual commands for more information."
15510 (interactive)
15511 (cond
15512 ((bobp) (if indent (newline-and-indent) (newline)))
15513 ((org-at-table-p)
15514 (org-table-justify-field-maybe)
15515 (call-interactively 'org-table-next-row))
15516 ((and org-return-follows-link
15517 (eq (get-text-property (point) 'face) 'org-link))
15518 (call-interactively 'org-open-at-point))
15519 ((and (org-at-heading-p)
15520 (looking-at
15521 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15522 (org-show-entry)
15523 (end-of-line 1)
15524 (newline))
15525 (t (if indent (newline-and-indent) (newline)))))
15527 (defun org-return-indent ()
15528 "Goto next table row or insert a newline and indent.
15529 Calls `org-table-next-row' or `newline-and-indent', depending on
15530 context. See the individual commands for more information."
15531 (interactive)
15532 (org-return t))
15534 (defun org-ctrl-c-star ()
15535 "Compute table, or change heading status of lines.
15536 Calls `org-table-recalculate' or `org-toggle-heading',
15537 depending on context."
15538 (interactive)
15539 (cond
15540 ((org-at-table-p)
15541 (call-interactively 'org-table-recalculate))
15543 ;; Convert all lines in region to list items
15544 (call-interactively 'org-toggle-heading))))
15546 (defun org-ctrl-c-minus ()
15547 "Insert separator line in table or modify bullet status of line.
15548 Also turns a plain line or a region of lines into list items.
15549 Calls `org-table-insert-hline', `org-toggle-item', or
15550 `org-cycle-list-bullet', depending on context."
15551 (interactive)
15552 (cond
15553 ((org-at-table-p)
15554 (call-interactively 'org-table-insert-hline))
15555 ((org-region-active-p)
15556 (call-interactively 'org-toggle-item))
15557 ((org-in-item-p)
15558 (call-interactively 'org-cycle-list-bullet))
15560 (call-interactively 'org-toggle-item))))
15562 (defun org-toggle-item ()
15563 "Convert headings or normal lines to items, items to normal lines.
15564 If there is no active region, only the current line is considered.
15566 If the first line in the region is a headline, convert all headlines to items.
15568 If the first line in the region is an item, convert all items to normal lines.
15570 If the first line is normal text, add an item bullet to each line."
15571 (interactive)
15572 (let (l2 l beg end)
15573 (if (org-region-active-p)
15574 (setq beg (region-beginning) end (region-end))
15575 (setq beg (point-at-bol)
15576 end (min (1+ (point-at-eol)) (point-max))))
15577 (save-excursion
15578 (goto-char end)
15579 (setq l2 (org-current-line))
15580 (goto-char beg)
15581 (beginning-of-line 1)
15582 (setq l (1- (org-current-line)))
15583 (if (org-at-item-p)
15584 ;; We already have items, de-itemize
15585 (while (< (setq l (1+ l)) l2)
15586 (when (org-at-item-p)
15587 (goto-char (match-beginning 2))
15588 (delete-region (match-beginning 2) (match-end 2))
15589 (and (looking-at "[ \t]+") (replace-match "")))
15590 (beginning-of-line 2))
15591 (if (org-on-heading-p)
15592 ;; Headings, convert to items
15593 (while (< (setq l (1+ l)) l2)
15594 (if (looking-at org-outline-regexp)
15595 (replace-match "- " t t))
15596 (beginning-of-line 2))
15597 ;; normal lines, turn them into items
15598 (while (< (setq l (1+ l)) l2)
15599 (unless (org-at-item-p)
15600 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15601 (replace-match "\\1- \\2")))
15602 (beginning-of-line 2)))))))
15604 (defun org-toggle-heading (&optional nstars)
15605 "Convert headings to normal text, or items or text to headings.
15606 If there is no active region, only the current line is considered.
15608 If the first line is a heading, remove the stars from all headlines
15609 in the region.
15611 If the first line is a plain list item, turn all plain list items
15612 into headings.
15614 If the first line is a normal line, turn each and every line in the
15615 region into a heading.
15617 When converting a line into a heading, the number of stars is chosen
15618 such that the lines become children of the current entry. However,
15619 when a prefix argument is given, its value determines the number of
15620 stars to add."
15621 (interactive "P")
15622 (let (l2 l itemp beg end)
15623 (if (org-region-active-p)
15624 (setq beg (region-beginning) end (region-end))
15625 (setq beg (point-at-bol)
15626 end (min (1+ (point-at-eol)) (point-max))))
15627 (save-excursion
15628 (goto-char end)
15629 (setq l2 (org-current-line))
15630 (goto-char beg)
15631 (beginning-of-line 1)
15632 (setq l (1- (org-current-line)))
15633 (if (org-on-heading-p)
15634 ;; We already have headlines, de-star them
15635 (while (< (setq l (1+ l)) l2)
15636 (when (org-on-heading-p t)
15637 (and (looking-at outline-regexp) (replace-match "")))
15638 (beginning-of-line 2))
15639 (setq itemp (org-at-item-p))
15640 (let* ((stars
15641 (if nstars
15642 (make-string (prefix-numeric-value current-prefix-arg)
15644 (save-excursion
15645 (if (re-search-backward org-complex-heading-regexp nil t)
15646 (match-string 1) ""))))
15647 (add-stars (cond (nstars "")
15648 ((equal stars "") "*")
15649 (org-odd-levels-only "**")
15650 (t "*")))
15651 (rpl (concat stars add-stars " ")))
15652 (while (< (setq l (1+ l)) l2)
15653 (if itemp
15654 (and (org-at-item-p) (replace-match rpl t t))
15655 (unless (org-on-heading-p)
15656 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15657 (replace-match (concat rpl (match-string 2))))))
15658 (beginning-of-line 2)))))))
15660 (defun org-meta-return (&optional arg)
15661 "Insert a new heading or wrap a region in a table.
15662 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15663 See the individual commands for more information."
15664 (interactive "P")
15665 (cond
15666 ((run-hook-with-args-until-success 'org-metareturn-hook))
15667 ((org-at-table-p)
15668 (call-interactively 'org-table-wrap-region))
15669 (t (call-interactively 'org-insert-heading))))
15671 ;;; Menu entries
15673 ;; Define the Org-mode menus
15674 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15675 '("Tbl"
15676 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15677 ["Next Field" org-cycle (org-at-table-p)]
15678 ["Previous Field" org-shifttab (org-at-table-p)]
15679 ["Next Row" org-return (org-at-table-p)]
15680 "--"
15681 ["Blank Field" org-table-blank-field (org-at-table-p)]
15682 ["Edit Field" org-table-edit-field (org-at-table-p)]
15683 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15684 "--"
15685 ("Column"
15686 ["Move Column Left" org-metaleft (org-at-table-p)]
15687 ["Move Column Right" org-metaright (org-at-table-p)]
15688 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15689 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15690 ("Row"
15691 ["Move Row Up" org-metaup (org-at-table-p)]
15692 ["Move Row Down" org-metadown (org-at-table-p)]
15693 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15694 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15695 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15696 "--"
15697 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15698 ("Rectangle"
15699 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15700 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15701 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15702 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15703 "--"
15704 ("Calculate"
15705 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15706 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15707 ["Edit Formulas" org-edit-special (org-at-table-p)]
15708 "--"
15709 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15710 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15711 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15712 "--"
15713 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15714 "--"
15715 ["Sum Column/Rectangle" org-table-sum
15716 (or (org-at-table-p) (org-region-active-p))]
15717 ["Which Column?" org-table-current-column (org-at-table-p)])
15718 ["Debug Formulas"
15719 org-table-toggle-formula-debugger
15720 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15721 ["Show Col/Row Numbers"
15722 org-table-toggle-coordinate-overlays
15723 :style toggle
15724 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15725 "--"
15726 ["Create" org-table-create (and (not (org-at-table-p))
15727 org-enable-table-editor)]
15728 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15729 ["Import from File" org-table-import (not (org-at-table-p))]
15730 ["Export to File" org-table-export (org-at-table-p)]
15731 "--"
15732 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15734 (easy-menu-define org-org-menu org-mode-map "Org menu"
15735 '("Org"
15736 ("Show/Hide"
15737 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15738 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15739 ["Sparse Tree..." org-sparse-tree t]
15740 ["Reveal Context" org-reveal t]
15741 ["Show All" show-all t]
15742 "--"
15743 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15744 "--"
15745 ["New Heading" org-insert-heading t]
15746 ("Navigate Headings"
15747 ["Up" outline-up-heading t]
15748 ["Next" outline-next-visible-heading t]
15749 ["Previous" outline-previous-visible-heading t]
15750 ["Next Same Level" outline-forward-same-level t]
15751 ["Previous Same Level" outline-backward-same-level t]
15752 "--"
15753 ["Jump" org-goto t])
15754 ("Edit Structure"
15755 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15756 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15757 "--"
15758 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15759 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15760 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15761 "--"
15762 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15763 "--"
15764 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15765 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15766 ["Demote Heading" org-metaright (not (org-at-table-p))]
15767 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15768 "--"
15769 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15770 "--"
15771 ["Convert to odd levels" org-convert-to-odd-levels t]
15772 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15773 ("Editing"
15774 ["Emphasis..." org-emphasize t]
15775 ["Edit Source Example" org-edit-special t]
15776 "--"
15777 ["Footnote new/jump" org-footnote-action t]
15778 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15779 ("Archive"
15780 ["Archive (default method)" org-archive-subtree-default t]
15781 "--"
15782 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
15783 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15784 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
15786 "--"
15787 ("Hyperlinks"
15788 ["Store Link (Global)" org-store-link t]
15789 ["Find existing link to here" org-occur-link-in-agenda-files t]
15790 ["Insert Link" org-insert-link t]
15791 ["Follow Link" org-open-at-point t]
15792 "--"
15793 ["Next link" org-next-link t]
15794 ["Previous link" org-previous-link t]
15795 "--"
15796 ["Descriptive Links"
15797 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15798 :style radio
15799 :selected (member '(org-link) buffer-invisibility-spec)]
15800 ["Literal Links"
15801 (progn
15802 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15803 :style radio
15804 :selected (not (member '(org-link) buffer-invisibility-spec))])
15805 "--"
15806 ("TODO Lists"
15807 ["TODO/DONE/-" org-todo t]
15808 ("Select keyword"
15809 ["Next keyword" org-shiftright (org-on-heading-p)]
15810 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15811 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15812 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15813 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15814 ["Show TODO Tree" org-show-todo-tree t]
15815 ["Global TODO list" org-todo-list t]
15816 "--"
15817 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15818 :selected org-enforce-todo-dependencies :style toggle :active t]
15819 "Settings for tree at point"
15820 ["Do Children sequentially" org-toggle-ordered-property :style radio
15821 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15822 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15823 ["Do Children parallel" org-toggle-ordered-property :style radio
15824 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15825 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15826 "--"
15827 ["Set Priority" org-priority t]
15828 ["Priority Up" org-shiftup t]
15829 ["Priority Down" org-shiftdown t]
15830 "--"
15831 ["Get news from all feeds" org-feed-update-all t]
15832 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15833 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15834 ("TAGS and Properties"
15835 ["Set Tags" org-set-tags-command t]
15836 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15837 "--"
15838 ["Set property" org-set-property t]
15839 ["Column view of properties" org-columns t]
15840 ["Insert Column View DBlock" org-insert-columns-dblock t])
15841 ("Dates and Scheduling"
15842 ["Timestamp" org-time-stamp t]
15843 ["Timestamp (inactive)" org-time-stamp-inactive t]
15844 ("Change Date"
15845 ["1 Day Later" org-shiftright t]
15846 ["1 Day Earlier" org-shiftleft t]
15847 ["1 ... Later" org-shiftup t]
15848 ["1 ... Earlier" org-shiftdown t])
15849 ["Compute Time Range" org-evaluate-time-range t]
15850 ["Schedule Item" org-schedule t]
15851 ["Deadline" org-deadline t]
15852 "--"
15853 ["Custom time format" org-toggle-time-stamp-overlays
15854 :style radio :selected org-display-custom-times]
15855 "--"
15856 ["Goto Calendar" org-goto-calendar t]
15857 ["Date from Calendar" org-date-from-calendar t]
15858 "--"
15859 ["Start/Restart Timer" org-timer-start t]
15860 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15861 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15862 ["Insert Timer String" org-timer t]
15863 ["Insert Timer Item" org-timer-item t])
15864 ("Logging work"
15865 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
15866 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
15867 ["Clock out" org-clock-out t]
15868 ["Clock cancel" org-clock-cancel t]
15869 "--"
15870 ["Mark as default task" org-clock-mark-default-task t]
15871 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
15872 ["Goto running clock" org-clock-goto t]
15873 "--"
15874 ["Display times" org-clock-display t]
15875 ["Create clock table" org-clock-report t]
15876 "--"
15877 ["Record DONE time"
15878 (progn (setq org-log-done (not org-log-done))
15879 (message "Switching to %s will %s record a timestamp"
15880 (car org-done-keywords)
15881 (if org-log-done "automatically" "not")))
15882 :style toggle :selected org-log-done])
15883 "--"
15884 ["Agenda Command..." org-agenda t]
15885 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15886 ("File List for Agenda")
15887 ("Special views current file"
15888 ["TODO Tree" org-show-todo-tree t]
15889 ["Check Deadlines" org-check-deadlines t]
15890 ["Timeline" org-timeline t]
15891 ["Tags/Property tree" org-match-sparse-tree t])
15892 "--"
15893 ["Export/Publish..." org-export t]
15894 ("LaTeX"
15895 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15896 :selected org-cdlatex-mode]
15897 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15898 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15899 ["Modify math symbol" org-cdlatex-math-modify
15900 (org-inside-LaTeX-fragment-p)]
15901 ["Insert citation" org-reftex-citation t]
15902 "--"
15903 ["Export LaTeX fragments as images"
15904 (if (featurep 'org-exp)
15905 (setq org-export-with-LaTeX-fragments
15906 (not org-export-with-LaTeX-fragments))
15907 (require 'org-exp))
15908 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15909 org-export-with-LaTeX-fragments)])
15910 "--"
15911 ("MobileOrg"
15912 ["Push Files and Views" org-mobile-push t]
15913 ["Get Captured and Flagged" org-mobile-pull t]
15914 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
15915 "--"
15916 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
15917 "--"
15918 ("Documentation"
15919 ["Show Version" org-version t]
15920 ["Info Documentation" org-info t])
15921 ("Customize"
15922 ["Browse Org Group" org-customize t]
15923 "--"
15924 ["Expand This Menu" org-create-customize-menu
15925 (fboundp 'customize-menu-create)])
15926 ["Send bug report" org-submit-bug-report t]
15927 "--"
15928 ("Refresh/Reload"
15929 ["Refresh setup current buffer" org-mode-restart t]
15930 ["Reload Org (after update)" org-reload t]
15931 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15934 (defun org-info (&optional node)
15935 "Read documentation for Org-mode in the info system.
15936 With optional NODE, go directly to that node."
15937 (interactive)
15938 (info (format "(org)%s" (or node ""))))
15940 ;;;###autoload
15941 (defun org-submit-bug-report ()
15942 "Submit a bug report on Org-mode via mail.
15944 Don't hesitate to report any problems or inaccurate documentation.
15946 If you don't have setup sending mail from (X)Emacs, please copy the
15947 output buffer into your mail program, as it gives us important
15948 information about your Org-mode version and configuration."
15949 (interactive)
15950 (require 'reporter)
15951 (org-load-modules-maybe)
15952 (org-require-autoloaded-modules)
15953 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
15954 (reporter-submit-bug-report
15955 "emacs-orgmode@gnu.org"
15956 (org-version)
15957 (let (list)
15958 (save-window-excursion
15959 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
15960 (delete-other-windows)
15961 (erase-buffer)
15962 (insert "You are about to submit a bug report to the Org-mode mailing list.
15964 We would like to add your full Org-mode and Outline configuration to the
15965 bug report. This greatly simplifies the work of the maintainer and
15966 other experts on the mailing list.
15968 HOWEVER, some variables you have customized may contain private
15969 information. The names of customers, colleagues, or friends, might
15970 appear in the form of file names, tags, todo states, or search strings.
15971 If you answer yes to the prompt, you might want to check and remove
15972 such private information before sending the email.")
15973 (add-text-properties (point-min) (point-max) '(face org-warning))
15974 (when (yes-or-no-p "Include your Org-mode configuration ")
15975 (mapatoms
15976 (lambda (v)
15977 (and (boundp v)
15978 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
15979 (or (and (symbol-value v)
15980 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
15981 (and
15982 (get v 'custom-type) (get v 'standard-value)
15983 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
15984 (push v list)))))
15985 (kill-buffer (get-buffer "*Warn about privacy*"))
15986 list))
15987 nil nil
15988 "Remember to cover the basics, that is, what you expected to happen and
15989 what in fact did happen. You don't know how to make a good report? See
15991 http://orgmode.org/manual/Feedback.html#Feedback
15993 Your bug report will be posted to the Org-mode mailing list.
15994 ------------------------------------------------------------------------")))
15996 (defun org-install-agenda-files-menu ()
15997 (let ((bl (buffer-list)))
15998 (save-excursion
15999 (while bl
16000 (set-buffer (pop bl))
16001 (if (org-mode-p) (setq bl nil)))
16002 (when (org-mode-p)
16003 (easy-menu-change
16004 '("Org") "File List for Agenda"
16005 (append
16006 (list
16007 ["Edit File List" (org-edit-agenda-file-list) t]
16008 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16009 ["Remove Current File from List" org-remove-file t]
16010 ["Cycle through agenda files" org-cycle-agenda-files t]
16011 ["Occur in all agenda files" org-occur-in-agenda-files t]
16012 "--")
16013 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16015 ;;;; Documentation
16017 ;;;###autoload
16018 (defun org-require-autoloaded-modules ()
16019 (interactive)
16020 (mapc 'require
16021 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16022 org-docbook org-exp org-html org-icalendar
16023 org-id org-latex
16024 org-publish org-remember org-table
16025 org-timer org-xoxo)))
16027 ;;;###autoload
16028 (defun org-reload (&optional uncompiled)
16029 "Reload all org lisp files.
16030 With prefix arg UNCOMPILED, load the uncompiled versions."
16031 (interactive "P")
16032 (require 'find-func)
16033 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16034 (dir-org (file-name-directory (org-find-library-name "org")))
16035 (dir-org-contrib (ignore-errors
16036 (file-name-directory
16037 (org-find-library-name "org-contribdir"))))
16038 (files
16039 (append (directory-files dir-org t file-re)
16040 (and dir-org-contrib
16041 (directory-files dir-org-contrib t file-re))))
16042 (remove-re (concat (if (featurep 'xemacs)
16043 "org-colview" "org-colview-xemacs")
16044 "\\'")))
16045 (setq files (mapcar 'file-name-sans-extension files))
16046 (setq files (mapcar
16047 (lambda (x) (if (string-match remove-re x) nil x))
16048 files))
16049 (setq files (delq nil files))
16050 (mapc
16051 (lambda (f)
16052 (when (featurep (intern (file-name-nondirectory f)))
16053 (if (and (not uncompiled)
16054 (file-exists-p (concat f ".elc")))
16055 (load (concat f ".elc") nil nil t)
16056 (load (concat f ".el") nil nil t))))
16057 files))
16058 (org-version))
16060 ;;;###autoload
16061 (defun org-customize ()
16062 "Call the customize function with org as argument."
16063 (interactive)
16064 (org-load-modules-maybe)
16065 (org-require-autoloaded-modules)
16066 (customize-browse 'org))
16068 (defun org-create-customize-menu ()
16069 "Create a full customization menu for Org-mode, insert it into the menu."
16070 (interactive)
16071 (org-load-modules-maybe)
16072 (org-require-autoloaded-modules)
16073 (if (fboundp 'customize-menu-create)
16074 (progn
16075 (easy-menu-change
16076 '("Org") "Customize"
16077 `(["Browse Org group" org-customize t]
16078 "--"
16079 ,(customize-menu-create 'org)
16080 ["Set" Custom-set t]
16081 ["Save" Custom-save t]
16082 ["Reset to Current" Custom-reset-current t]
16083 ["Reset to Saved" Custom-reset-saved t]
16084 ["Reset to Standard Settings" Custom-reset-standard t]))
16085 (message "\"Org\"-menu now contains full customization menu"))
16086 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16088 ;;;; Miscellaneous stuff
16090 ;;; Generally useful functions
16092 (defun org-get-at-bol (property)
16093 "Get text property PROPERTY at beginning of line."
16094 (get-text-property (point-at-bol) property))
16096 (defun org-find-text-property-in-string (prop s)
16097 "Return the first non-nil value of property PROP in string S."
16098 (or (get-text-property 0 prop s)
16099 (get-text-property (or (next-single-property-change 0 prop s) 0)
16100 prop s)))
16102 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16103 "Display the given MESSAGE as a warning."
16104 (if (fboundp 'display-warning)
16105 (display-warning 'org message
16106 (if (featurep 'xemacs)
16107 'warning
16108 :warning))
16109 (let ((buf (get-buffer-create "*Org warnings*")))
16110 (with-current-buffer buf
16111 (goto-char (point-max))
16112 (insert "Warning (Org): " message)
16113 (unless (bolp)
16114 (newline)))
16115 (display-buffer buf)
16116 (sit-for 0))))
16118 (defun org-in-commented-line ()
16119 "Is point in a line starting with `#'?"
16120 (equal (char-after (point-at-bol)) ?#))
16122 (defun org-in-verbatim-emphasis ()
16123 (save-match-data
16124 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16126 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16127 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16128 (if (and marker (marker-buffer marker)
16129 (buffer-live-p (marker-buffer marker)))
16130 (progn
16131 (switch-to-buffer (marker-buffer marker))
16132 (if (or (> marker (point-max)) (< marker (point-min)))
16133 (widen))
16134 (goto-char marker)
16135 (org-show-context 'org-goto))
16136 (if bookmark
16137 (bookmark-jump bookmark)
16138 (error "Cannot find location"))))
16140 (defun org-quote-csv-field (s)
16141 "Quote field for inclusion in CSV material."
16142 (if (string-match "[\",]" s)
16143 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16146 (defun org-plist-delete (plist property)
16147 "Delete PROPERTY from PLIST.
16148 This is in contrast to merely setting it to 0."
16149 (let (p)
16150 (while plist
16151 (if (not (eq property (car plist)))
16152 (setq p (plist-put p (car plist) (nth 1 plist))))
16153 (setq plist (cddr plist)))
16156 (defun org-force-self-insert (N)
16157 "Needed to enforce self-insert under remapping."
16158 (interactive "p")
16159 (self-insert-command N))
16161 (defun org-string-width (s)
16162 "Compute width of string, ignoring invisible characters.
16163 This ignores character with invisibility property `org-link', and also
16164 characters with property `org-cwidth', because these will become invisible
16165 upon the next fontification round."
16166 (let (b l)
16167 (when (or (eq t buffer-invisibility-spec)
16168 (assq 'org-link buffer-invisibility-spec))
16169 (while (setq b (text-property-any 0 (length s)
16170 'invisible 'org-link s))
16171 (setq s (concat (substring s 0 b)
16172 (substring s (or (next-single-property-change
16173 b 'invisible s) (length s)))))))
16174 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16175 (setq s (concat (substring s 0 b)
16176 (substring s (or (next-single-property-change
16177 b 'org-cwidth s) (length s))))))
16178 (setq l (string-width s) b -1)
16179 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16180 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16183 (defun org-get-indentation (&optional line)
16184 "Get the indentation of the current line, interpreting tabs.
16185 When LINE is given, assume it represents a line and compute its indentation."
16186 (if line
16187 (if (string-match "^ *" (org-remove-tabs line))
16188 (match-end 0))
16189 (save-excursion
16190 (beginning-of-line 1)
16191 (skip-chars-forward " \t")
16192 (current-column))))
16194 (defun org-remove-tabs (s &optional width)
16195 "Replace tabulators in S with spaces.
16196 Assumes that s is a single line, starting in column 0."
16197 (setq width (or width tab-width))
16198 (while (string-match "\t" s)
16199 (setq s (replace-match
16200 (make-string
16201 (- (* width (/ (+ (match-beginning 0) width) width))
16202 (match-beginning 0)) ?\ )
16203 t t s)))
16206 (defun org-fix-indentation (line ind)
16207 "Fix indentation in LINE.
16208 IND is a cons cell with target and minimum indentation.
16209 If the current indentation in LINE is smaller than the minimum,
16210 leave it alone. If it is larger than ind, set it to the target."
16211 (let* ((l (org-remove-tabs line))
16212 (i (org-get-indentation l))
16213 (i1 (car ind)) (i2 (cdr ind)))
16214 (if (>= i i2) (setq l (substring line i2)))
16215 (if (> i1 0)
16216 (concat (make-string i1 ?\ ) l)
16217 l)))
16219 (defun org-remove-indentation (code &optional n)
16220 "Remove the maximum common indentation from the lines in CODE.
16221 N may optionally be the number of spaces to remove."
16222 (with-temp-buffer
16223 (insert code)
16224 (org-do-remove-indentation n)
16225 (buffer-string)))
16227 (defun org-do-remove-indentation (&optional n)
16228 "Remove the maximum common indentation from the buffer."
16229 (untabify (point-min) (point-max))
16230 (let ((min 10000) re)
16231 (if n
16232 (setq min n)
16233 (goto-char (point-min))
16234 (while (re-search-forward "^ *[^ \n]" nil t)
16235 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16236 (unless (or (= min 0) (= min 10000))
16237 (setq re (format "^ \\{%d\\}" min))
16238 (goto-char (point-min))
16239 (while (re-search-forward re nil t)
16240 (replace-match "")
16241 (end-of-line 1))
16242 min)))
16244 (defun org-fill-template (template alist)
16245 "Find each %key of ALIST in TEMPLATE and replace it."
16246 (let (entry key value)
16247 (setq alist (sort (copy-sequence alist)
16248 (lambda (a b) (< (length (car a)) (length (car b))))))
16249 (while (setq entry (pop alist))
16250 (setq template
16251 (replace-regexp-in-string
16252 (concat "%" (regexp-quote (car entry)))
16253 (cdr entry) template t t)))
16254 template))
16256 (defun org-base-buffer (buffer)
16257 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16258 (if (not buffer)
16259 buffer
16260 (or (buffer-base-buffer buffer)
16261 buffer)))
16263 (defun org-trim (s)
16264 "Remove whitespace at beginning and end of string."
16265 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
16266 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
16269 (defun org-wrap (string &optional width lines)
16270 "Wrap string to either a number of lines, or a width in characters.
16271 If WIDTH is non-nil, the string is wrapped to that width, however many lines
16272 that costs. If there is a word longer than WIDTH, the text is actually
16273 wrapped to the length of that word.
16274 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
16275 many lines, whatever width that takes.
16276 The return value is a list of lines, without newlines at the end."
16277 (let* ((words (org-split-string string "[ \t\n]+"))
16278 (maxword (apply 'max (mapcar 'org-string-width words)))
16279 w ll)
16280 (cond (width
16281 (org-do-wrap words (max maxword width)))
16282 (lines
16283 (setq w maxword)
16284 (setq ll (org-do-wrap words maxword))
16285 (if (<= (length ll) lines)
16287 (setq ll words)
16288 (while (> (length ll) lines)
16289 (setq w (1+ w))
16290 (setq ll (org-do-wrap words w)))
16291 ll))
16292 (t (error "Cannot wrap this")))))
16294 (defun org-do-wrap (words width)
16295 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
16296 (let (lines line)
16297 (while words
16298 (setq line (pop words))
16299 (while (and words (< (+ (length line) (length (car words))) width))
16300 (setq line (concat line " " (pop words))))
16301 (setq lines (push line lines)))
16302 (nreverse lines)))
16304 (defun org-split-string (string &optional separators)
16305 "Splits STRING into substrings at SEPARATORS.
16306 No empty strings are returned if there are matches at the beginning
16307 and end of string."
16308 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
16309 (start 0)
16310 notfirst
16311 (list nil))
16312 (while (and (string-match rexp string
16313 (if (and notfirst
16314 (= start (match-beginning 0))
16315 (< start (length string)))
16316 (1+ start) start))
16317 (< (match-beginning 0) (length string)))
16318 (setq notfirst t)
16319 (or (eq (match-beginning 0) 0)
16320 (and (eq (match-beginning 0) (match-end 0))
16321 (eq (match-beginning 0) start))
16322 (setq list
16323 (cons (substring string start (match-beginning 0))
16324 list)))
16325 (setq start (match-end 0)))
16326 (or (eq start (length string))
16327 (setq list
16328 (cons (substring string start)
16329 list)))
16330 (nreverse list)))
16332 (defun org-quote-vert (s)
16333 "Replace \"|\" with \"\\vert\"."
16334 (while (string-match "|" s)
16335 (setq s (replace-match "\\vert" t t s)))
16338 (defun org-uuidgen-p (s)
16339 "Is S an ID created by UUIDGEN?"
16340 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16342 (defun org-context ()
16343 "Return a list of contexts of the current cursor position.
16344 If several contexts apply, all are returned.
16345 Each context entry is a list with a symbol naming the context, and
16346 two positions indicating start and end of the context. Possible
16347 contexts are:
16349 :headline anywhere in a headline
16350 :headline-stars on the leading stars in a headline
16351 :todo-keyword on a TODO keyword (including DONE) in a headline
16352 :tags on the TAGS in a headline
16353 :priority on the priority cookie in a headline
16354 :item on the first line of a plain list item
16355 :item-bullet on the bullet/number of a plain list item
16356 :checkbox on the checkbox in a plain list item
16357 :table in an org-mode table
16358 :table-special on a special filed in a table
16359 :table-table in a table.el table
16360 :link on a hyperlink
16361 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16362 :target on a <<target>>
16363 :radio-target on a <<<radio-target>>>
16364 :latex-fragment on a LaTeX fragment
16365 :latex-preview on a LaTeX fragment with overlayed preview image
16367 This function expects the position to be visible because it uses font-lock
16368 faces as a help to recognize the following contexts: :table-special, :link,
16369 and :keyword."
16370 (let* ((f (get-text-property (point) 'face))
16371 (faces (if (listp f) f (list f)))
16372 (p (point)) clist o)
16373 ;; First the large context
16374 (cond
16375 ((org-on-heading-p t)
16376 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16377 (when (progn
16378 (beginning-of-line 1)
16379 (looking-at org-todo-line-tags-regexp))
16380 (push (org-point-in-group p 1 :headline-stars) clist)
16381 (push (org-point-in-group p 2 :todo-keyword) clist)
16382 (push (org-point-in-group p 4 :tags) clist))
16383 (goto-char p)
16384 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
16385 (if (looking-at "\\[#[A-Z0-9]\\]")
16386 (push (org-point-in-group p 0 :priority) clist)))
16388 ((org-at-item-p)
16389 (push (org-point-in-group p 2 :item-bullet) clist)
16390 (push (list :item (point-at-bol)
16391 (save-excursion (org-end-of-item) (point)))
16392 clist)
16393 (and (org-at-item-checkbox-p)
16394 (push (org-point-in-group p 0 :checkbox) clist)))
16396 ((org-at-table-p)
16397 (push (list :table (org-table-begin) (org-table-end)) clist)
16398 (if (memq 'org-formula faces)
16399 (push (list :table-special
16400 (previous-single-property-change p 'face)
16401 (next-single-property-change p 'face)) clist)))
16402 ((org-at-table-p 'any)
16403 (push (list :table-table) clist)))
16404 (goto-char p)
16406 ;; Now the small context
16407 (cond
16408 ((org-at-timestamp-p)
16409 (push (org-point-in-group p 0 :timestamp) clist))
16410 ((memq 'org-link faces)
16411 (push (list :link
16412 (previous-single-property-change p 'face)
16413 (next-single-property-change p 'face)) clist))
16414 ((memq 'org-special-keyword faces)
16415 (push (list :keyword
16416 (previous-single-property-change p 'face)
16417 (next-single-property-change p 'face)) clist))
16418 ((org-on-target-p)
16419 (push (org-point-in-group p 0 :target) clist)
16420 (goto-char (1- (match-beginning 0)))
16421 (if (looking-at org-radio-target-regexp)
16422 (push (org-point-in-group p 0 :radio-target) clist))
16423 (goto-char p))
16424 ((setq o (car (delq nil
16425 (mapcar
16426 (lambda (x)
16427 (if (memq x org-latex-fragment-image-overlays) x))
16428 (org-overlays-at (point))))))
16429 (push (list :latex-fragment
16430 (org-overlay-start o) (org-overlay-end o)) clist)
16431 (push (list :latex-preview
16432 (org-overlay-start o) (org-overlay-end o)) clist))
16433 ((org-inside-LaTeX-fragment-p)
16434 ;; FIXME: positions wrong.
16435 (push (list :latex-fragment (point) (point)) clist)))
16437 (setq clist (nreverse (delq nil clist)))
16438 clist))
16440 ;; FIXME: Compare with at-regexp-p Do we need both?
16441 (defun org-in-regexp (re &optional nlines visually)
16442 "Check if point is inside a match of regexp.
16443 Normally only the current line is checked, but you can include NLINES extra
16444 lines both before and after point into the search.
16445 If VISUALLY is set, require that the cursor is not after the match but
16446 really on, so that the block visually is on the match."
16447 (catch 'exit
16448 (let ((pos (point))
16449 (eol (point-at-eol (+ 1 (or nlines 0))))
16450 (inc (if visually 1 0)))
16451 (save-excursion
16452 (beginning-of-line (- 1 (or nlines 0)))
16453 (while (re-search-forward re eol t)
16454 (if (and (<= (match-beginning 0) pos)
16455 (>= (+ inc (match-end 0)) pos))
16456 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16458 (defun org-at-regexp-p (regexp)
16459 "Is point inside a match of REGEXP in the current line?"
16460 (catch 'exit
16461 (save-excursion
16462 (let ((pos (point)) (end (point-at-eol)))
16463 (beginning-of-line 1)
16464 (while (re-search-forward regexp end t)
16465 (if (and (<= (match-beginning 0) pos)
16466 (>= (match-end 0) pos))
16467 (throw 'exit t)))
16468 nil))))
16470 (defun org-occur-in-agenda-files (regexp &optional nlines)
16471 "Call `multi-occur' with buffers for all agenda files."
16472 (interactive "sOrg-files matching: \np")
16473 (let* ((files (org-agenda-files))
16474 (tnames (mapcar 'file-truename files))
16475 (extra org-agenda-text-search-extra-files)
16477 (when (eq (car extra) 'agenda-archives)
16478 (setq extra (cdr extra))
16479 (setq files (org-add-archive-files files)))
16480 (while (setq f (pop extra))
16481 (unless (member (file-truename f) tnames)
16482 (add-to-list 'files f 'append)
16483 (add-to-list 'tnames (file-truename f) 'append)))
16484 (multi-occur
16485 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
16486 regexp)))
16488 (if (boundp 'occur-mode-find-occurrence-hook)
16489 ;; Emacs 23
16490 (add-hook 'occur-mode-find-occurrence-hook
16491 (lambda ()
16492 (when (org-mode-p)
16493 (org-reveal))))
16494 ;; Emacs 22
16495 (defadvice occur-mode-goto-occurrence
16496 (after org-occur-reveal activate)
16497 (and (org-mode-p) (org-reveal)))
16498 (defadvice occur-mode-goto-occurrence-other-window
16499 (after org-occur-reveal activate)
16500 (and (org-mode-p) (org-reveal)))
16501 (defadvice occur-mode-display-occurrence
16502 (after org-occur-reveal activate)
16503 (when (org-mode-p)
16504 (let ((pos (occur-mode-find-occurrence)))
16505 (with-current-buffer (marker-buffer pos)
16506 (save-excursion
16507 (goto-char pos)
16508 (org-reveal)))))))
16510 (defun org-occur-link-in-agenda-files ()
16511 "Create a link and search for it in the agendas.
16512 The link is not stored in `org-stored-links', it is just created
16513 for the search purpose."
16514 (interactive)
16515 (let ((link (condition-case nil
16516 (org-store-link nil)
16517 (error "Unable to create a link to here"))))
16518 (org-occur-in-agenda-files (regexp-quote link))))
16520 (defun org-uniquify (list)
16521 "Remove duplicate elements from LIST."
16522 (let (res)
16523 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16524 res))
16526 (defun org-delete-all (elts list)
16527 "Remove all elements in ELTS from LIST."
16528 (while elts
16529 (setq list (delete (pop elts) list)))
16530 list)
16532 (defun org-back-over-empty-lines ()
16533 "Move backwards over whitespace, to the beginning of the first empty line.
16534 Returns the number of empty lines passed."
16535 (let ((pos (point)))
16536 (skip-chars-backward " \t\n\r")
16537 (beginning-of-line 2)
16538 (goto-char (min (point) pos))
16539 (count-lines (point) pos)))
16541 (defun org-skip-whitespace ()
16542 (skip-chars-forward " \t\n\r"))
16544 (defun org-point-in-group (point group &optional context)
16545 "Check if POINT is in match-group GROUP.
16546 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16547 match. If the match group does ot exist or point is not inside it,
16548 return nil."
16549 (and (match-beginning group)
16550 (>= point (match-beginning group))
16551 (<= point (match-end group))
16552 (if context
16553 (list context (match-beginning group) (match-end group))
16554 t)))
16556 (defun org-switch-to-buffer-other-window (&rest args)
16557 "Switch to buffer in a second window on the current frame.
16558 In particular, do not allow pop-up frames."
16559 (let (pop-up-frames special-display-buffer-names special-display-regexps
16560 special-display-function)
16561 (apply 'switch-to-buffer-other-window args)))
16563 (defun org-combine-plists (&rest plists)
16564 "Create a single property list from all plists in PLISTS.
16565 The process starts by copying the first list, and then setting properties
16566 from the other lists. Settings in the last list are the most significant
16567 ones and overrule settings in the other lists."
16568 (let ((rtn (copy-sequence (pop plists)))
16569 p v ls)
16570 (while plists
16571 (setq ls (pop plists))
16572 (while ls
16573 (setq p (pop ls) v (pop ls))
16574 (setq rtn (plist-put rtn p v))))
16575 rtn))
16577 (defun org-move-line-down (arg)
16578 "Move the current line down. With prefix argument, move it past ARG lines."
16579 (interactive "p")
16580 (let ((col (current-column))
16581 beg end pos)
16582 (beginning-of-line 1) (setq beg (point))
16583 (beginning-of-line 2) (setq end (point))
16584 (beginning-of-line (+ 1 arg))
16585 (setq pos (move-marker (make-marker) (point)))
16586 (insert (delete-and-extract-region beg end))
16587 (goto-char pos)
16588 (org-move-to-column col)))
16590 (defun org-move-line-up (arg)
16591 "Move the current line up. With prefix argument, move it past ARG lines."
16592 (interactive "p")
16593 (let ((col (current-column))
16594 beg end pos)
16595 (beginning-of-line 1) (setq beg (point))
16596 (beginning-of-line 2) (setq end (point))
16597 (beginning-of-line (- arg))
16598 (setq pos (move-marker (make-marker) (point)))
16599 (insert (delete-and-extract-region beg end))
16600 (goto-char pos)
16601 (org-move-to-column col)))
16603 (defun org-replace-escapes (string table)
16604 "Replace %-escapes in STRING with values in TABLE.
16605 TABLE is an association list with keys like \"%a\" and string values.
16606 The sequences in STRING may contain normal field width and padding information,
16607 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
16608 so values can contain further %-escapes if they are define later in TABLE."
16609 (let ((case-fold-search nil)
16610 e re rpl)
16611 (while (setq e (pop table))
16612 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
16613 (while (string-match re string)
16614 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
16615 (cdr e)))
16616 (setq string (replace-match rpl t t string))))
16617 string))
16620 (defun org-sublist (list start end)
16621 "Return a section of LIST, from START to END.
16622 Counting starts at 1."
16623 (let (rtn (c start))
16624 (setq list (nthcdr (1- start) list))
16625 (while (and list (<= c end))
16626 (push (pop list) rtn)
16627 (setq c (1+ c)))
16628 (nreverse rtn)))
16630 (defun org-find-base-buffer-visiting (file)
16631 "Like `find-buffer-visiting' but always return the base buffer and
16632 not an indirect buffer."
16633 (let ((buf (or (get-file-buffer file)
16634 (find-buffer-visiting file))))
16635 (if buf
16636 (or (buffer-base-buffer buf) buf)
16637 nil)))
16639 (defun org-image-file-name-regexp (&optional extensions)
16640 "Return regexp matching the file names of images.
16641 If EXTENSIONS is given, only match these."
16642 (if (and (not extensions) (fboundp 'image-file-name-regexp))
16643 (image-file-name-regexp)
16644 (let ((image-file-name-extensions
16645 (or extensions
16646 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16647 "xbm" "xpm" "pbm" "pgm" "ppm"))))
16648 (concat "\\."
16649 (regexp-opt (nconc (mapcar 'upcase
16650 image-file-name-extensions)
16651 image-file-name-extensions)
16653 "\\'"))))
16655 (defun org-file-image-p (file &optional extensions)
16656 "Return non-nil if FILE is an image."
16657 (save-match-data
16658 (string-match (org-image-file-name-regexp extensions) file)))
16660 (defun org-get-cursor-date ()
16661 "Return the date at cursor in as a time.
16662 This works in the calendar and in the agenda, anywhere else it just
16663 returns the current time."
16664 (let (date day defd)
16665 (cond
16666 ((eq major-mode 'calendar-mode)
16667 (setq date (calendar-cursor-to-date)
16668 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16669 ((eq major-mode 'org-agenda-mode)
16670 (setq day (get-text-property (point) 'day))
16671 (if day
16672 (setq date (calendar-gregorian-from-absolute day)
16673 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
16674 (nth 2 date))))))
16675 (or defd (current-time))))
16677 (defvar org-agenda-action-marker (make-marker)
16678 "Marker pointing to the entry for the next agenda action.")
16680 (defun org-mark-entry-for-agenda-action ()
16681 "Mark the current entry as target of an agenda action.
16682 Agenda actions are actions executed from the agenda with the key `k',
16683 which make use of the date at the cursor."
16684 (interactive)
16685 (move-marker org-agenda-action-marker
16686 (save-excursion (org-back-to-heading t) (point))
16687 (current-buffer))
16688 (message
16689 "Entry marked for action; press `k' at desired date in agenda or calendar"))
16691 ;;; Paragraph filling stuff.
16692 ;; We want this to be just right, so use the full arsenal.
16694 (defun org-indent-line-function ()
16695 "Indent line like previous, but further if previous was headline or item."
16696 (interactive)
16697 (let* ((pos (point))
16698 (itemp (org-at-item-p))
16699 (case-fold-search t)
16700 (org-drawer-regexp (or org-drawer-regexp "\000"))
16701 column bpos bcol tpos tcol bullet btype bullet-type)
16702 ;; Find the previous relevant line
16703 (beginning-of-line 1)
16704 (cond
16705 ((looking-at "#") (setq column 0))
16706 ((looking-at "\\*+ ") (setq column 0))
16707 ((and (looking-at "[ \t]*:END:")
16708 (save-excursion (re-search-backward org-drawer-regexp nil t)))
16709 (save-excursion
16710 (goto-char (1- (match-beginning 1)))
16711 (setq column (current-column))))
16712 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
16713 (save-excursion
16714 (re-search-backward
16715 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
16716 (setq column (org-get-indentation (match-string 0))))
16718 (beginning-of-line 0)
16719 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
16720 (not (looking-at "[ \t]*:END:"))
16721 (not (looking-at org-drawer-regexp)))
16722 (beginning-of-line 0))
16723 (cond
16724 ((looking-at "\\*+[ \t]+")
16725 (if (not org-adapt-indentation)
16726 (setq column 0)
16727 (goto-char (match-end 0))
16728 (setq column (current-column))))
16729 ((looking-at org-drawer-regexp)
16730 (goto-char (1- (match-beginning 1)))
16731 (setq column (current-column)))
16732 ((looking-at "\\([ \t]*\\):END:")
16733 (goto-char (match-end 1))
16734 (setq column (current-column)))
16735 ((org-in-item-p)
16736 (org-beginning-of-item)
16737 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
16738 (setq bpos (match-beginning 1) tpos (match-end 0)
16739 bcol (progn (goto-char bpos) (current-column))
16740 tcol (progn (goto-char tpos) (current-column))
16741 bullet (match-string 1)
16742 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
16743 (if (> tcol (+ bcol org-description-max-indent))
16744 (setq tcol (+ bcol 5)))
16745 (if (not itemp)
16746 (setq column tcol)
16747 (goto-char pos)
16748 (beginning-of-line 1)
16749 (if (looking-at "\\S-")
16750 (progn
16751 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
16752 (setq bullet (match-string 1)
16753 btype (if (string-match "[0-9]" bullet) "n" bullet))
16754 (setq column (if (equal btype bullet-type) bcol tcol)))
16755 (setq column (org-get-indentation)))))
16756 (t (setq column (org-get-indentation))))))
16757 (goto-char pos)
16758 (if (<= (current-column) (current-indentation))
16759 (org-indent-line-to column)
16760 (save-excursion (org-indent-line-to column)))
16761 (setq column (current-column))
16762 (beginning-of-line 1)
16763 (if (looking-at
16764 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16765 (replace-match (concat (match-string 1)
16766 (format org-property-format
16767 (match-string 2) (match-string 3)))
16768 t t))
16769 (org-move-to-column column)))
16771 (defun org-set-autofill-regexps ()
16772 (interactive)
16773 ;; In the paragraph separator we include headlines, because filling
16774 ;; text in a line directly attached to a headline would otherwise
16775 ;; fill the headline as well.
16776 (org-set-local 'comment-start-skip "^#+[ \t]*")
16777 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
16778 ;; The paragraph starter includes hand-formatted lists.
16779 (org-set-local
16780 'paragraph-start
16781 (concat
16782 "\f" "\\|"
16783 "[ ]*$" "\\|"
16784 "\\*+ " "\\|"
16785 "[ \t]*#" "\\|"
16786 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16787 "[ \t]*[:|]" "\\|"
16788 "\\$\\$" "\\|"
16789 "\\\\\\(begin\\|end\\|[][]\\)"))
16790 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16791 ;; But only if the user has not turned off tables or fixed-width regions
16792 (org-set-local
16793 'auto-fill-inhibit-regexp
16794 (concat "\\*+ \\|#\\+"
16795 "\\|[ \t]*" org-keyword-time-regexp
16796 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16797 (concat
16798 "\\|[ \t]*["
16799 (if org-enable-table-editor "|" "")
16800 (if org-enable-fixed-width-editor ":" "")
16801 "]"))))
16802 ;; We use our own fill-paragraph function, to make sure that tables
16803 ;; and fixed-width regions are not wrapped. That function will pass
16804 ;; through to `fill-paragraph' when appropriate.
16805 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16806 ; Adaptive filling: To get full control, first make sure that
16807 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16808 (org-set-local 'adaptive-fill-regexp "\000")
16809 (org-set-local 'adaptive-fill-function
16810 'org-adaptive-fill-function)
16811 (org-set-local
16812 'align-mode-rules-list
16813 '((org-in-buffer-settings
16814 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
16815 (modes . '(org-mode))))))
16817 (defun org-fill-paragraph (&optional justify)
16818 "Re-align a table, pass through to fill-paragraph if no table."
16819 (let ((table-p (org-at-table-p))
16820 (table.el-p (org-at-table.el-p)))
16821 (cond ((and (equal (char-after (point-at-bol)) ?*)
16822 (save-excursion (goto-char (point-at-bol))
16823 (looking-at outline-regexp)))
16824 t) ; skip headlines
16825 (table.el-p t) ; skip table.el tables
16826 (table-p (org-table-align) t) ; align org-mode tables
16827 (t nil)))) ; call paragraph-fill
16829 ;; For reference, this is the default value of adaptive-fill-regexp
16830 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16832 (defun org-adaptive-fill-function ()
16833 "Return a fill prefix for org-mode files.
16834 In particular, this makes sure hanging paragraphs for hand-formatted lists
16835 work correctly."
16836 (cond ((looking-at "#[ \t]+")
16837 (match-string 0))
16838 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
16839 (save-excursion
16840 (if (> (match-end 1) (+ (match-beginning 1)
16841 org-description-max-indent))
16842 (goto-char (+ (match-beginning 1) 5))
16843 (goto-char (match-end 0)))
16844 (make-string (current-column) ?\ )))
16845 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
16846 (save-excursion
16847 (goto-char (match-end 0))
16848 (make-string (current-column) ?\ )))
16849 (t nil)))
16851 ;;; Other stuff.
16853 (defun org-toggle-fixed-width-section (arg)
16854 "Toggle the fixed-width export.
16855 If there is no active region, the QUOTE keyword at the current headline is
16856 inserted or removed. When present, it causes the text between this headline
16857 and the next to be exported as fixed-width text, and unmodified.
16858 If there is an active region, this command adds or removes a colon as the
16859 first character of this line. If the first character of a line is a colon,
16860 this line is also exported in fixed-width font."
16861 (interactive "P")
16862 (let* ((cc 0)
16863 (regionp (org-region-active-p))
16864 (beg (if regionp (region-beginning) (point)))
16865 (end (if regionp (region-end)))
16866 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
16867 (case-fold-search nil)
16868 (re "[ \t]*\\(: \\)")
16869 off)
16870 (if regionp
16871 (save-excursion
16872 (goto-char beg)
16873 (setq cc (current-column))
16874 (beginning-of-line 1)
16875 (setq off (looking-at re))
16876 (while (> nlines 0)
16877 (setq nlines (1- nlines))
16878 (beginning-of-line 1)
16879 (cond
16880 (arg
16881 (org-move-to-column cc t)
16882 (insert ": \n")
16883 (forward-line -1))
16884 ((and off (looking-at re))
16885 (replace-match "" t t nil 1))
16886 ((not off) (org-move-to-column cc t) (insert ": ")))
16887 (forward-line 1)))
16888 (save-excursion
16889 (org-back-to-heading)
16890 (if (looking-at (concat outline-regexp
16891 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
16892 (replace-match "" t t nil 1)
16893 (if (looking-at outline-regexp)
16894 (progn
16895 (goto-char (match-end 0))
16896 (insert org-quote-string " "))))))))
16898 (defun org-reftex-citation ()
16899 "Use reftex-citation to insert a citation into the buffer.
16900 This looks for a line like
16902 #+BIBLIOGRAPHY: foo plain option:-d
16904 and derives from it that foo.bib is the bbliography file relevant
16905 for this document. It then installs the necessary environment for RefTeX
16906 to work in this buffer and calls `reftex-citation' to insert a citation
16907 into the buffer.
16909 Export of such citations to both LaTeX and HTML is handled by the contributed
16910 package org-exp-bibtex by Taru Karttunen."
16911 (interactive)
16912 (let ((reftex-docstruct-symbol 'rds)
16913 (reftex-cite-format "\\cite{%l}")
16914 rds bib)
16915 (save-excursion
16916 (save-restriction
16917 (widen)
16918 (let ((case-fold-search t)
16919 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
16920 (if (not (save-excursion
16921 (or (re-search-forward re nil t)
16922 (re-search-backward re nil t))))
16923 (error "No bibliography defined in file")
16924 (setq bib (concat (match-string 1) ".bib")
16925 rds (list (list 'bib bib)))))))
16926 (call-interactively 'reftex-citation)))
16928 ;;;; Functions extending outline functionality
16930 (defun org-beginning-of-line (&optional arg)
16931 "Go to the beginning of the current line. If that is invisible, continue
16932 to a visible line beginning. This makes the function of C-a more intuitive.
16933 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16934 first attempt, and only move to after the tags when the cursor is already
16935 beyond the end of the headline."
16936 (interactive "P")
16937 (let ((pos (point))
16938 (special (if (consp org-special-ctrl-a/e)
16939 (car org-special-ctrl-a/e)
16940 org-special-ctrl-a/e))
16941 refpos)
16942 (if (org-bound-and-true-p line-move-visual)
16943 (beginning-of-visual-line 1)
16944 (beginning-of-line 1))
16945 (if (and arg (fboundp 'move-beginning-of-line))
16946 (call-interactively 'move-beginning-of-line)
16947 (if (bobp)
16949 (backward-char 1)
16950 (if (org-invisible-p)
16951 (while (and (not (bobp)) (org-invisible-p))
16952 (backward-char 1)
16953 (beginning-of-line 1))
16954 (forward-char 1))))
16955 (when special
16956 (cond
16957 ((and (looking-at org-complex-heading-regexp)
16958 (= (char-after (match-end 1)) ?\ ))
16959 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
16960 (point-at-eol)))
16961 (goto-char
16962 (if (eq special t)
16963 (cond ((> pos refpos) refpos)
16964 ((= pos (point)) refpos)
16965 (t (point)))
16966 (cond ((> pos (point)) (point))
16967 ((not (eq last-command this-command)) (point))
16968 (t refpos)))))
16969 ((org-at-item-p)
16970 (goto-char
16971 (if (eq special t)
16972 (cond ((> pos (match-end 4)) (match-end 4))
16973 ((= pos (point)) (match-end 4))
16974 (t (point)))
16975 (cond ((> pos (point)) (point))
16976 ((not (eq last-command this-command)) (point))
16977 (t (match-end 4))))))))
16978 (org-no-warnings
16979 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16981 (defun org-end-of-line (&optional arg)
16982 "Go to the end of the line.
16983 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16984 first attempt, and only move to after the tags when the cursor is already
16985 beyond the end of the headline."
16986 (interactive "P")
16987 (let ((special (if (consp org-special-ctrl-a/e)
16988 (cdr org-special-ctrl-a/e)
16989 org-special-ctrl-a/e)))
16990 (if (or (not special)
16991 (not (org-on-heading-p))
16992 arg)
16993 (call-interactively
16994 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
16995 ((fboundp 'move-end-of-line) 'move-end-of-line)
16996 (t 'end-of-line)))
16997 (let ((pos (point)))
16998 (beginning-of-line 1)
16999 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17000 (if (eq special t)
17001 (if (or (< pos (match-beginning 1))
17002 (= pos (match-end 0)))
17003 (goto-char (match-beginning 1))
17004 (goto-char (match-end 0)))
17005 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17006 (goto-char (match-end 0))
17007 (goto-char (match-beginning 1))))
17008 (call-interactively (if (fboundp 'move-end-of-line)
17009 'move-end-of-line
17010 'end-of-line)))))
17011 (org-no-warnings
17012 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17014 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17015 (define-key org-mode-map "\C-e" 'org-end-of-line)
17016 (define-key org-mode-map [home] 'org-beginning-of-line)
17017 (define-key org-mode-map [end] 'org-end-of-line)
17019 (defun org-backward-sentence (&optional arg)
17020 "Go to beginning of sentence, or beginning of table field.
17021 This will call `backward-sentence' or `org-table-beginning-of-field',
17022 depending on context."
17023 (interactive "P")
17024 (cond
17025 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17026 (t (call-interactively 'backward-sentence))))
17028 (defun org-forward-sentence (&optional arg)
17029 "Go to end of sentence, or end of table field.
17030 This will call `forward-sentence' or `org-table-end-of-field',
17031 depending on context."
17032 (interactive "P")
17033 (cond
17034 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17035 (t (call-interactively 'forward-sentence))))
17037 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17038 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17040 (defun org-kill-line (&optional arg)
17041 "Kill line, to tags or end of line."
17042 (interactive "P")
17043 (cond
17044 ((or (not org-special-ctrl-k)
17045 (bolp)
17046 (not (org-on-heading-p)))
17047 (call-interactively 'kill-line))
17048 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17049 (kill-region (point) (match-beginning 1))
17050 (org-set-tags nil t))
17051 (t (kill-region (point) (point-at-eol)))))
17053 (define-key org-mode-map "\C-k" 'org-kill-line)
17055 (defun org-yank (&optional arg)
17056 "Yank. If the kill is a subtree, treat it specially.
17057 This command will look at the current kill and check if is a single
17058 subtree, or a series of subtrees[1]. If it passes the test, and if the
17059 cursor is at the beginning of a line or after the stars of a currently
17060 empty headline, then the yank is handled specially. How exactly depends
17061 on the value of the following variables, both set by default.
17063 org-yank-folded-subtrees
17064 When set, the subtree(s) will be folded after insertion, but only
17065 if doing so would now swallow text after the yanked text.
17067 org-yank-adjusted-subtrees
17068 When set, the subtree will be promoted or demoted in order to
17069 fit into the local outline tree structure, which means that the level
17070 will be adjusted so that it becomes the smaller one of the two
17071 *visible* surrounding headings.
17073 Any prefix to this command will cause `yank' to be called directly with
17074 no special treatment. In particular, a simple `C-u' prefix will just
17075 plainly yank the text as it is.
17077 \[1] The test checks if the first non-white line is a heading
17078 and if there are no other headings with fewer stars."
17079 (interactive "P")
17080 (org-yank-generic 'yank arg))
17082 (defun org-yank-generic (command arg)
17083 "Perform some yank-like command.
17085 This function implements the behavior described in the `org-yank'
17086 documentation. However, it has been generalized to work for any
17087 interactive command with similar behavior."
17089 ;; pretend to be command COMMAND
17090 (setq this-command command)
17092 (if arg
17093 (call-interactively command)
17095 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17096 (and (org-kill-is-subtree-p)
17097 (or (bolp)
17098 (and (looking-at "[ \t]*$")
17099 (string-match
17100 "\\`\\*+\\'"
17101 (buffer-substring (point-at-bol) (point)))))))
17102 swallowp)
17103 (cond
17104 ((and subtreep org-yank-folded-subtrees)
17105 (let ((beg (point))
17106 end)
17107 (if (and subtreep org-yank-adjusted-subtrees)
17108 (org-paste-subtree nil nil 'for-yank)
17109 (call-interactively command))
17111 (setq end (point))
17112 (goto-char beg)
17113 (when (and (bolp) subtreep
17114 (not (setq swallowp
17115 (org-yank-folding-would-swallow-text beg end))))
17116 (or (looking-at outline-regexp)
17117 (re-search-forward (concat "^" outline-regexp) end t))
17118 (while (and (< (point) end) (looking-at outline-regexp))
17119 (hide-subtree)
17120 (org-cycle-show-empty-lines 'folded)
17121 (condition-case nil
17122 (outline-forward-same-level 1)
17123 (error (goto-char end)))))
17124 (when swallowp
17125 (message
17126 "Inserted text not folded because that would swallow text"))
17128 (goto-char end)
17129 (skip-chars-forward " \t\n\r")
17130 (beginning-of-line 1)
17131 (push-mark beg 'nomsg)))
17132 ((and subtreep org-yank-adjusted-subtrees)
17133 (let ((beg (point-at-bol)))
17134 (org-paste-subtree nil nil 'for-yank)
17135 (push-mark beg 'nomsg)))
17137 (call-interactively command))))))
17139 (defun org-yank-folding-would-swallow-text (beg end)
17140 "Would hide-subtree at BEG swallow any text after END?"
17141 (let (level)
17142 (save-excursion
17143 (goto-char beg)
17144 (when (or (looking-at outline-regexp)
17145 (re-search-forward (concat "^" outline-regexp) end t))
17146 (setq level (org-outline-level)))
17147 (goto-char end)
17148 (skip-chars-forward " \t\r\n\v\f")
17149 (if (or (eobp)
17150 (and (bolp) (looking-at org-outline-regexp)
17151 (<= (org-outline-level) level)))
17152 nil ; Nothing would be swallowed
17153 t)))) ; something would swallow
17155 (define-key org-mode-map "\C-y" 'org-yank)
17157 (defun org-invisible-p ()
17158 "Check if point is at a character currently not visible."
17159 ;; Early versions of noutline don't have `outline-invisible-p'.
17160 (if (fboundp 'outline-invisible-p)
17161 (outline-invisible-p)
17162 (get-char-property (point) 'invisible)))
17164 (defun org-invisible-p2 ()
17165 "Check if point is at a character currently not visible."
17166 (save-excursion
17167 (if (and (eolp) (not (bobp))) (backward-char 1))
17168 ;; Early versions of noutline don't have `outline-invisible-p'.
17169 (if (fboundp 'outline-invisible-p)
17170 (outline-invisible-p)
17171 (get-char-property (point) 'invisible))))
17173 (defun org-back-to-heading (&optional invisible-ok)
17174 "Call `outline-back-to-heading', but provide a better error message."
17175 (condition-case nil
17176 (outline-back-to-heading invisible-ok)
17177 (error (error "Before first headline at position %d in buffer %s"
17178 (point) (current-buffer)))))
17180 (defun org-before-first-heading-p ()
17181 "Before first heading?"
17182 (save-excursion
17183 (null (re-search-backward "^\\*+ " nil t))))
17185 (defun org-on-heading-p (&optional ignored)
17186 (outline-on-heading-p t))
17187 (defun org-at-heading-p (&optional ignored)
17188 (outline-on-heading-p t))
17190 (defun org-at-heading-or-item-p ()
17191 (or (org-on-heading-p) (org-at-item-p)))
17193 (defun org-on-target-p ()
17194 (or (org-in-regexp org-radio-target-regexp)
17195 (org-in-regexp org-target-regexp)))
17197 (defun org-up-heading-all (arg)
17198 "Move to the heading line of which the present line is a subheading.
17199 This function considers both visible and invisible heading lines.
17200 With argument, move up ARG levels."
17201 (if (fboundp 'outline-up-heading-all)
17202 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17203 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17205 (defun org-up-heading-safe ()
17206 "Move to the heading line of which the present line is a subheading.
17207 This version will not throw an error. It will return the level of the
17208 headline found, or nil if no higher level is found.
17210 Also, this function will be a lot faster than `outline-up-heading',
17211 because it relies on stars being the outline starters. This can really
17212 make a significant difference in outlines with very many siblings."
17213 (let (start-level re)
17214 (org-back-to-heading t)
17215 (setq start-level (funcall outline-level))
17216 (if (equal start-level 1)
17218 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17219 (if (re-search-backward re nil t)
17220 (funcall outline-level)))))
17222 (defun org-first-sibling-p ()
17223 "Is this heading the first child of its parents?"
17224 (interactive)
17225 (let ((re (concat "^" outline-regexp))
17226 level l)
17227 (unless (org-at-heading-p t)
17228 (error "Not at a heading"))
17229 (setq level (funcall outline-level))
17230 (save-excursion
17231 (if (not (re-search-backward re nil t))
17233 (setq l (funcall outline-level))
17234 (< l level)))))
17236 (defun org-goto-sibling (&optional previous)
17237 "Goto the next sibling, even if it is invisible.
17238 When PREVIOUS is set, go to the previous sibling instead. Returns t
17239 when a sibling was found. When none is found, return nil and don't
17240 move point."
17241 (let ((fun (if previous 're-search-backward 're-search-forward))
17242 (pos (point))
17243 (re (concat "^" outline-regexp))
17244 level l)
17245 (when (condition-case nil (org-back-to-heading t) (error nil))
17246 (setq level (funcall outline-level))
17247 (catch 'exit
17248 (or previous (forward-char 1))
17249 (while (funcall fun re nil t)
17250 (setq l (funcall outline-level))
17251 (when (< l level) (goto-char pos) (throw 'exit nil))
17252 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17253 (goto-char pos)
17254 nil))))
17256 (defun org-show-siblings ()
17257 "Show all siblings of the current headline."
17258 (save-excursion
17259 (while (org-goto-sibling) (org-flag-heading nil)))
17260 (save-excursion
17261 (while (org-goto-sibling 'previous)
17262 (org-flag-heading nil))))
17264 (defun org-show-hidden-entry ()
17265 "Show an entry where even the heading is hidden."
17266 (save-excursion
17267 (org-show-entry)))
17269 (defun org-flag-heading (flag &optional entry)
17270 "Flag the current heading. FLAG non-nil means make invisible.
17271 When ENTRY is non-nil, show the entire entry."
17272 (save-excursion
17273 (org-back-to-heading t)
17274 ;; Check if we should show the entire entry
17275 (if entry
17276 (progn
17277 (org-show-entry)
17278 (save-excursion
17279 (and (outline-next-heading)
17280 (org-flag-heading nil))))
17281 (outline-flag-region (max (point-min) (1- (point)))
17282 (save-excursion (outline-end-of-heading) (point))
17283 flag))))
17285 (defun org-get-next-sibling ()
17286 "Move to next heading of the same level, and return point.
17287 If there is no such heading, return nil.
17288 This is like outline-next-sibling, but invisible headings are ok."
17289 (let ((level (funcall outline-level)))
17290 (outline-next-heading)
17291 (while (and (not (eobp)) (> (funcall outline-level) level))
17292 (outline-next-heading))
17293 (if (or (eobp) (< (funcall outline-level) level))
17295 (point))))
17297 (defun org-get-last-sibling ()
17298 "Move to previous heading of the same level, and return point.
17299 If there is no such heading, return nil."
17300 (let ((opoint (point))
17301 (level (funcall outline-level)))
17302 (outline-previous-heading)
17303 (when (and (/= (point) opoint) (outline-on-heading-p t))
17304 (while (and (> (funcall outline-level) level)
17305 (not (bobp)))
17306 (outline-previous-heading))
17307 (if (< (funcall outline-level) level)
17309 (point)))))
17311 (defun org-end-of-subtree (&optional invisible-OK to-heading)
17312 ;; This contains an exact copy of the original function, but it uses
17313 ;; `org-back-to-heading', to make it work also in invisible
17314 ;; trees. And is uses an invisible-OK argument.
17315 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17316 ;; Furthermore, when used inside Org, finding the end of a large subtree
17317 ;; with many children and grandchildren etc, this can be much faster
17318 ;; than the outline version.
17319 (org-back-to-heading invisible-OK)
17320 (let ((first t)
17321 (level (funcall outline-level)))
17322 (if (and (org-mode-p) (< level 1000))
17323 ;; A true heading (not a plain list item), in Org-mode
17324 ;; This means we can easily find the end by looking
17325 ;; only for the right number of stars. Using a regexp to do
17326 ;; this is so much faster than using a Lisp loop.
17327 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
17328 (forward-char 1)
17329 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
17330 ;; something else, do it the slow way
17331 (while (and (not (eobp))
17332 (or first (> (funcall outline-level) level)))
17333 (setq first nil)
17334 (outline-next-heading)))
17335 (unless to-heading
17336 (if (memq (preceding-char) '(?\n ?\^M))
17337 (progn
17338 ;; Go to end of line before heading
17339 (forward-char -1)
17340 (if (memq (preceding-char) '(?\n ?\^M))
17341 ;; leave blank line before heading
17342 (forward-char -1))))))
17343 (point))
17345 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
17346 "Use Org version in org-mode, for dramatic speed-up."
17347 (if (eq major-mode 'org-mode)
17348 (progn
17349 (org-end-of-subtree nil t)
17350 (unless (eobp) (backward-char 1)))
17351 ad-do-it))
17353 (defun org-forward-same-level (arg &optional invisible-ok)
17354 "Move forward to the arg'th subheading at same level as this one.
17355 Stop at the first and last subheadings of a superior heading."
17356 (interactive "p")
17357 (org-back-to-heading invisible-ok)
17358 (org-on-heading-p)
17359 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17360 (re (format "^\\*\\{1,%d\\} " level))
17362 (forward-char 1)
17363 (while (> arg 0)
17364 (while (and (re-search-forward re nil 'move)
17365 (setq l (- (match-end 0) (match-beginning 0) 1))
17366 (= l level)
17367 (not invisible-ok)
17368 (org-invisible-p))
17369 (if (< l level) (setq arg 1)))
17370 (setq arg (1- arg)))
17371 (beginning-of-line 1)))
17373 (defun org-backward-same-level (arg &optional invisible-ok)
17374 "Move backward to the arg'th subheading at same level as this one.
17375 Stop at the first and last subheadings of a superior heading."
17376 (interactive "p")
17377 (org-back-to-heading)
17378 (org-on-heading-p)
17379 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17380 (re (format "^\\*\\{1,%d\\} " level))
17382 (while (> arg 0)
17383 (while (and (re-search-backward re nil 'move)
17384 (setq l (- (match-end 0) (match-beginning 0) 1))
17385 (= l level)
17386 (not invisible-ok)
17387 (org-invisible-p))
17388 (if (< l level) (setq arg 1)))
17389 (setq arg (1- arg)))))
17391 (defun org-show-subtree ()
17392 "Show everything after this heading at deeper levels."
17393 (outline-flag-region
17394 (point)
17395 (save-excursion
17396 (org-end-of-subtree t t))
17397 nil))
17399 (defun org-show-entry ()
17400 "Show the body directly following this heading.
17401 Show the heading too, if it is currently invisible."
17402 (interactive)
17403 (save-excursion
17404 (condition-case nil
17405 (progn
17406 (org-back-to-heading t)
17407 (outline-flag-region
17408 (max (point-min) (1- (point)))
17409 (save-excursion
17410 (if (re-search-forward
17411 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17412 (match-beginning 1)
17413 (point-max)))
17414 nil)
17415 (org-cycle-hide-drawers 'children))
17416 (error nil))))
17418 (defun org-make-options-regexp (kwds &optional extra)
17419 "Make a regular expression for keyword lines."
17420 (concat
17422 "#?[ \t]*\\+\\("
17423 (mapconcat 'regexp-quote kwds "\\|")
17424 (if extra (concat "\\|" extra))
17425 "\\):[ \t]*"
17426 "\\(.*\\)"))
17428 ;; Make isearch reveal the necessary context
17429 (defun org-isearch-end ()
17430 "Reveal context after isearch exits."
17431 (when isearch-success ; only if search was successful
17432 (if (featurep 'xemacs)
17433 ;; Under XEmacs, the hook is run in the correct place,
17434 ;; we directly show the context.
17435 (org-show-context 'isearch)
17436 ;; In Emacs the hook runs *before* restoring the overlays.
17437 ;; So we have to use a one-time post-command-hook to do this.
17438 ;; (Emacs 22 has a special variable, see function `org-mode')
17439 (unless (and (boundp 'isearch-mode-end-hook-quit)
17440 isearch-mode-end-hook-quit)
17441 ;; Only when the isearch was not quitted.
17442 (org-add-hook 'post-command-hook 'org-isearch-post-command
17443 'append 'local)))))
17445 (defun org-isearch-post-command ()
17446 "Remove self from hook, and show context."
17447 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17448 (org-show-context 'isearch))
17451 ;;;; Integration with and fixes for other packages
17453 ;;; Imenu support
17455 (defvar org-imenu-markers nil
17456 "All markers currently used by Imenu.")
17457 (make-variable-buffer-local 'org-imenu-markers)
17459 (defun org-imenu-new-marker (&optional pos)
17460 "Return a new marker for use by Imenu, and remember the marker."
17461 (let ((m (make-marker)))
17462 (move-marker m (or pos (point)))
17463 (push m org-imenu-markers)
17466 (defun org-imenu-get-tree ()
17467 "Produce the index for Imenu."
17468 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17469 (setq org-imenu-markers nil)
17470 (let* ((n org-imenu-depth)
17471 (re (concat "^" outline-regexp))
17472 (subs (make-vector (1+ n) nil))
17473 (last-level 0)
17474 m level head)
17475 (save-excursion
17476 (save-restriction
17477 (widen)
17478 (goto-char (point-max))
17479 (while (re-search-backward re nil t)
17480 (setq level (org-reduced-level (funcall outline-level)))
17481 (when (<= level n)
17482 (looking-at org-complex-heading-regexp)
17483 (setq head (org-link-display-format
17484 (org-match-string-no-properties 4))
17485 m (org-imenu-new-marker))
17486 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17487 (if (>= level last-level)
17488 (push (cons head m) (aref subs level))
17489 (push (cons head (aref subs (1+ level))) (aref subs level))
17490 (loop for i from (1+ level) to n do (aset subs i nil)))
17491 (setq last-level level)))))
17492 (aref subs 1)))
17494 (eval-after-load "imenu"
17495 '(progn
17496 (add-hook 'imenu-after-jump-hook
17497 (lambda ()
17498 (if (eq major-mode 'org-mode)
17499 (org-show-context 'org-goto))))))
17501 (defun org-link-display-format (link)
17502 "Replace a link with either the description, or the link target
17503 if no description is present"
17504 (save-match-data
17505 (if (string-match org-bracket-link-analytic-regexp link)
17506 (replace-match (or (match-string 5 link)
17507 (concat (match-string 1 link)
17508 (match-string 3 link)))
17509 nil nil link)
17510 link)))
17512 ;; Speedbar support
17514 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17515 "Overlay marking the agenda restriction line in speedbar.")
17516 (org-overlay-put org-speedbar-restriction-lock-overlay
17517 'face 'org-agenda-restriction-lock)
17518 (org-overlay-put org-speedbar-restriction-lock-overlay
17519 'help-echo "Agendas are currently limited to this item.")
17520 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17522 (defun org-speedbar-set-agenda-restriction ()
17523 "Restrict future agenda commands to the location at point in speedbar.
17524 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17525 (interactive)
17526 (require 'org-agenda)
17527 (let (p m tp np dir txt)
17528 (cond
17529 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17530 'org-imenu t))
17531 (setq m (get-text-property p 'org-imenu-marker))
17532 (with-current-buffer (marker-buffer m)
17533 (goto-char m)
17534 (org-agenda-set-restriction-lock 'subtree)))
17535 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17536 'speedbar-function 'speedbar-find-file))
17537 (setq tp (previous-single-property-change
17538 (1+ p) 'speedbar-function)
17539 np (next-single-property-change
17540 tp 'speedbar-function)
17541 dir (speedbar-line-directory)
17542 txt (buffer-substring-no-properties (or tp (point-min))
17543 (or np (point-max))))
17544 (with-current-buffer (find-file-noselect
17545 (let ((default-directory dir))
17546 (expand-file-name txt)))
17547 (unless (org-mode-p)
17548 (error "Cannot restrict to non-Org-mode file"))
17549 (org-agenda-set-restriction-lock 'file)))
17550 (t (error "Don't know how to restrict Org-mode's agenda")))
17551 (org-move-overlay org-speedbar-restriction-lock-overlay
17552 (point-at-bol) (point-at-eol))
17553 (setq current-prefix-arg nil)
17554 (org-agenda-maybe-redo)))
17556 (eval-after-load "speedbar"
17557 '(progn
17558 (speedbar-add-supported-extension ".org")
17559 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
17560 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
17561 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
17562 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17563 (add-hook 'speedbar-visiting-tag-hook
17564 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
17567 ;;; Fixes and Hacks for problems with other packages
17569 ;; Make flyspell not check words in links, to not mess up our keymap
17570 (defun org-mode-flyspell-verify ()
17571 "Don't let flyspell put overlays at active buttons."
17572 (and (not (get-text-property (point) 'keymap))
17573 (not (get-text-property (point) 'org-no-flyspell))))
17575 (defun org-remove-flyspell-overlays-in (beg end)
17576 "Remove flyspell overlays in region."
17577 (and (org-bound-and-true-p flyspell-mode)
17578 (fboundp 'flyspell-delete-region-overlays)
17579 (flyspell-delete-region-overlays beg end))
17580 (add-text-properties beg end '(org-no-flyspell t)))
17582 ;; Make `bookmark-jump' shows the jump location if it was hidden.
17583 (eval-after-load "bookmark"
17584 '(if (boundp 'bookmark-after-jump-hook)
17585 ;; We can use the hook
17586 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17587 ;; Hook not available, use advice
17588 (defadvice bookmark-jump (after org-make-visible activate)
17589 "Make the position visible."
17590 (org-bookmark-jump-unhide))))
17592 ;; Make sure saveplace shows the location if it was hidden
17593 (eval-after-load "saveplace"
17594 '(defadvice save-place-find-file-hook (after org-make-visible activate)
17595 "Make the position visible."
17596 (org-bookmark-jump-unhide)))
17598 ;; Make sure ecb shows the location if it was hidden
17599 (eval-after-load "ecb"
17600 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
17601 "Make hierarchy visible when jumping into location from ECB tree buffer."
17602 (if (eq major-mode 'org-mode)
17603 (org-show-context))))
17605 (defun org-bookmark-jump-unhide ()
17606 "Unhide the current position, to show the bookmark location."
17607 (and (org-mode-p)
17608 (or (org-invisible-p)
17609 (save-excursion (goto-char (max (point-min) (1- (point))))
17610 (org-invisible-p)))
17611 (org-show-context 'bookmark-jump)))
17613 ;; Make session.el ignore our circular variable
17614 (eval-after-load "session"
17615 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17617 ;;;; Experimental code
17619 (defun org-closed-in-range ()
17620 "Sparse tree of items closed in a certain time range.
17621 Still experimental, may disappear in the future."
17622 (interactive)
17623 ;; Get the time interval from the user.
17624 (let* ((time1 (org-float-time
17625 (org-read-date nil 'to-time nil "Starting date: ")))
17626 (time2 (org-float-time
17627 (org-read-date nil 'to-time nil "End date:")))
17628 ;; callback function
17629 (callback (lambda ()
17630 (let ((time
17631 (org-float-time
17632 (apply 'encode-time
17633 (org-parse-time-string
17634 (match-string 1))))))
17635 ;; check if time in interval
17636 (and (>= time time1) (<= time time2))))))
17637 ;; make tree, check each match with the callback
17638 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
17640 ;;;; Finish up
17642 (provide 'org)
17644 (run-hooks 'org-load-hook)
17646 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17648 ;;; org.el ends here