org-babel: store noweb-expanded code body in 'info' data structure
[rgr-org-mode.git] / lisp / org.el
blobb3b8909b29d3248ff48b410aef2f5d4c2fe1f57d
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 (eval-after-load "calendar"
2715 '(progn
2716 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2717 'org-calendar-goto-agenda)
2718 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2719 'org-agenda-action)))
2721 (defgroup org-latex nil
2722 "Options for embedding LaTeX code into Org-mode."
2723 :tag "Org LaTeX"
2724 :group 'org)
2726 (defcustom org-format-latex-options
2727 '(:foreground default :background default :scale 1.0
2728 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2729 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2730 "Options for creating images from LaTeX fragments.
2731 This is a property list with the following properties:
2732 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2733 `default' means use the foreground of the default face.
2734 :background the background color, or \"Transparent\".
2735 `default' means use the background of the default face.
2736 :scale a scaling factor for the size of the images.
2737 :html-foreground, :html-background, :html-scale
2738 the same numbers for HTML export.
2739 :matchers a list indicating which matchers should be used to
2740 find LaTeX fragments. Valid members of this list are:
2741 \"begin\" find environments
2742 \"$1\" find single characters surrounded by $.$
2743 \"$\" find math expressions surrounded by $...$
2744 \"$$\" find math expressions surrounded by $$....$$
2745 \"\\(\" find math expressions surrounded by \\(...\\)
2746 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2747 :group 'org-latex
2748 :type 'plist)
2750 (defcustom org-format-latex-header "\\documentclass{article}
2751 \\usepackage{amssymb}
2752 \\usepackage[usenames]{color}
2753 \\usepackage{amsmath}
2754 \\usepackage{latexsym}
2755 \\usepackage[mathscr]{eucal}
2756 \\pagestyle{empty} % do not remove
2757 % The settings below are copied from fullpage.sty
2758 \\setlength{\\textwidth}{\\paperwidth}
2759 \\addtolength{\\textwidth}{-3cm}
2760 \\setlength{\\oddsidemargin}{1.5cm}
2761 \\addtolength{\\oddsidemargin}{-2.54cm}
2762 \\setlength{\\evensidemargin}{\\oddsidemargin}
2763 \\setlength{\\textheight}{\\paperheight}
2764 \\addtolength{\\textheight}{-\\headheight}
2765 \\addtolength{\\textheight}{-\\headsep}
2766 \\addtolength{\\textheight}{-\\footskip}
2767 \\addtolength{\\textheight}{-3cm}
2768 \\setlength{\\topmargin}{1.5cm}
2769 \\addtolength{\\topmargin}{-2.54cm}"
2770 "The document header used for processing LaTeX fragments.
2771 It is imperative that this header make sure that no page number
2772 appears on the page."
2773 :group 'org-latex
2774 :type 'string)
2777 (defgroup org-font-lock nil
2778 "Font-lock settings for highlighting in Org-mode."
2779 :tag "Org Font Lock"
2780 :group 'org)
2782 (defcustom org-level-color-stars-only nil
2783 "Non-nil means fontify only the stars in each headline.
2784 When nil, the entire headline is fontified.
2785 Changing it requires restart of `font-lock-mode' to become effective
2786 also in regions already fontified."
2787 :group 'org-font-lock
2788 :type 'boolean)
2790 (defcustom org-hide-leading-stars nil
2791 "Non-nil means, hide the first N-1 stars in a headline.
2792 This works by using the face `org-hide' for these stars. This
2793 face is white for a light background, and black for a dark
2794 background. You may have to customize the face `org-hide' to
2795 make this work.
2796 Changing it requires restart of `font-lock-mode' to become effective
2797 also in regions already fontified.
2798 You may also set this on a per-file basis by adding one of the following
2799 lines to the buffer:
2801 #+STARTUP: hidestars
2802 #+STARTUP: showstars"
2803 :group 'org-font-lock
2804 :type 'boolean)
2806 (defcustom org-fontify-done-headline nil
2807 "Non-nil means, change the face of a headline if it is marked DONE.
2808 Normally, only the TODO/DONE keyword indicates the state of a headline.
2809 When this is non-nil, the headline after the keyword is set to the
2810 `org-headline-done' as an additional indication."
2811 :group 'org-font-lock
2812 :type 'boolean)
2814 (defcustom org-fontify-emphasized-text t
2815 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2816 Changing this variable requires a restart of Emacs to take effect."
2817 :group 'org-font-lock
2818 :type 'boolean)
2820 (defcustom org-fontify-whole-heading-line nil
2821 "Non-nil means fontify the whole line for headings.
2822 This is useful when setting a background color for the
2823 org-leve-* faces."
2824 :group 'org-font-lock
2825 :type 'boolean)
2827 (defcustom org-highlight-latex-fragments-and-specials nil
2828 "Non-nil means, fontify what is treated specially by the exporters."
2829 :group 'org-font-lock
2830 :type 'boolean)
2832 (defcustom org-hide-emphasis-markers nil
2833 "Non-nil mean font-lock should hide the emphasis marker characters."
2834 :group 'org-font-lock
2835 :type 'boolean)
2837 (defvar org-emph-re nil
2838 "Regular expression for matching emphasis.")
2839 (defvar org-verbatim-re nil
2840 "Regular expression for matching verbatim text.")
2841 (defvar org-emphasis-regexp-components) ; defined just below
2842 (defvar org-emphasis-alist) ; defined just below
2843 (defun org-set-emph-re (var val)
2844 "Set variable and compute the emphasis regular expression."
2845 (set var val)
2846 (when (and (boundp 'org-emphasis-alist)
2847 (boundp 'org-emphasis-regexp-components)
2848 org-emphasis-alist org-emphasis-regexp-components)
2849 (let* ((e org-emphasis-regexp-components)
2850 (pre (car e))
2851 (post (nth 1 e))
2852 (border (nth 2 e))
2853 (body (nth 3 e))
2854 (nl (nth 4 e))
2855 (body1 (concat body "*?"))
2856 (markers (mapconcat 'car org-emphasis-alist ""))
2857 (vmarkers (mapconcat
2858 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2859 org-emphasis-alist "")))
2860 ;; make sure special characters appear at the right position in the class
2861 (if (string-match "\\^" markers)
2862 (setq markers (concat (replace-match "" t t markers) "^")))
2863 (if (string-match "-" markers)
2864 (setq markers (concat (replace-match "" t t markers) "-")))
2865 (if (string-match "\\^" vmarkers)
2866 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2867 (if (string-match "-" vmarkers)
2868 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2869 (if (> nl 0)
2870 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2871 (int-to-string nl) "\\}")))
2872 ;; Make the regexp
2873 (setq org-emph-re
2874 (concat "\\([" pre "]\\|^\\)"
2875 "\\("
2876 "\\([" markers "]\\)"
2877 "\\("
2878 "[^" border "]\\|"
2879 "[^" border "]"
2880 body1
2881 "[^" border "]"
2882 "\\)"
2883 "\\3\\)"
2884 "\\([" post "]\\|$\\)"))
2885 (setq org-verbatim-re
2886 (concat "\\([" pre "]\\|^\\)"
2887 "\\("
2888 "\\([" vmarkers "]\\)"
2889 "\\("
2890 "[^" border "]\\|"
2891 "[^" border "]"
2892 body1
2893 "[^" border "]"
2894 "\\)"
2895 "\\3\\)"
2896 "\\([" post "]\\|$\\)")))))
2898 (defcustom org-emphasis-regexp-components
2899 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
2900 "Components used to build the regular expression for emphasis.
2901 This is a list with 6 entries. Terminology: In an emphasis string
2902 like \" *strong word* \", we call the initial space PREMATCH, the final
2903 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2904 and \"trong wor\" is the body. The different components in this variable
2905 specify what is allowed/forbidden in each part:
2907 pre Chars allowed as prematch. Beginning of line will be allowed too.
2908 post Chars allowed as postmatch. End of line will be allowed too.
2909 border The chars *forbidden* as border characters.
2910 body-regexp A regexp like \".\" to match a body character. Don't use
2911 non-shy groups here, and don't allow newline here.
2912 newline The maximum number of newlines allowed in an emphasis exp.
2914 Use customize to modify this, or restart Emacs after changing it."
2915 :group 'org-font-lock
2916 :set 'org-set-emph-re
2917 :type '(list
2918 (sexp :tag "Allowed chars in pre ")
2919 (sexp :tag "Allowed chars in post ")
2920 (sexp :tag "Forbidden chars in border ")
2921 (sexp :tag "Regexp for body ")
2922 (integer :tag "number of newlines allowed")
2923 (option (boolean :tag "Please ignore this button"))))
2925 (defcustom org-emphasis-alist
2926 `(("*" bold "<b>" "</b>")
2927 ("/" italic "<i>" "</i>")
2928 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2929 ("=" org-code "<code>" "</code>" verbatim)
2930 ("~" org-verbatim "<code>" "</code>" verbatim)
2931 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2932 "<del>" "</del>")
2934 "Special syntax for emphasized text.
2935 Text starting and ending with a special character will be emphasized, for
2936 example *bold*, _underlined_ and /italic/. This variable sets the marker
2937 characters, the face to be used by font-lock for highlighting in Org-mode
2938 Emacs buffers, and the HTML tags to be used for this.
2939 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2940 Use customize to modify this, or restart Emacs after changing it."
2941 :group 'org-font-lock
2942 :set 'org-set-emph-re
2943 :type '(repeat
2944 (list
2945 (string :tag "Marker character")
2946 (choice
2947 (face :tag "Font-lock-face")
2948 (plist :tag "Face property list"))
2949 (string :tag "HTML start tag")
2950 (string :tag "HTML end tag")
2951 (option (const verbatim)))))
2953 (defvar org-protecting-blocks
2954 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
2955 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
2956 This is needed for font-lock setup.")
2958 ;;; Miscellaneous options
2960 (defgroup org-completion nil
2961 "Completion in Org-mode."
2962 :tag "Org Completion"
2963 :group 'org)
2965 (defcustom org-completion-use-ido nil
2966 "Non-nil means, use ido completion wherever possible.
2967 Note that `ido-mode' must be active for this variable to be relevant.
2968 If you decide to turn this variable on, you might well want to turn off
2969 `org-outline-path-complete-in-steps'.
2970 See also `org-completion-use-iswitchb'."
2971 :group 'org-completion
2972 :type 'boolean)
2974 (defcustom org-completion-use-iswitchb nil
2975 "Non-nil means, use iswitchb completion wherever possible.
2976 Note that `iswitchb-mode' must be active for this variable to be relevant.
2977 If you decide to turn this variable on, you might well want to turn off
2978 `org-outline-path-complete-in-steps'.
2979 Note that thi variable has only an effect if `org-completion-use-ido' is nil."
2980 :group 'org-completion
2981 :type 'boolean)
2983 (defcustom org-completion-fallback-command 'hippie-expand
2984 "The expansion command called by \\[org-complete] in normal context.
2985 Normal means, no org-mode-specific context."
2986 :group 'org-completion
2987 :type 'function)
2989 ;;; Functions and variables from ther packages
2990 ;; Declared here to avoid compiler warnings
2992 ;; XEmacs only
2993 (defvar outline-mode-menu-heading)
2994 (defvar outline-mode-menu-show)
2995 (defvar outline-mode-menu-hide)
2996 (defvar zmacs-regions) ; XEmacs regions
2998 ;; Emacs only
2999 (defvar mark-active)
3001 ;; Various packages
3002 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3003 (declare-function calendar-forward-day "cal-move" (arg))
3004 (declare-function calendar-goto-date "cal-move" (date))
3005 (declare-function calendar-goto-today "cal-move" ())
3006 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3007 (defvar calc-embedded-close-formula)
3008 (defvar calc-embedded-open-formula)
3009 (declare-function cdlatex-tab "ext:cdlatex" ())
3010 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3011 (defvar font-lock-unfontify-region-function)
3012 (declare-function iswitchb-read-buffer "iswitchb"
3013 (prompt &optional default require-match start matches-set))
3014 (defvar iswitchb-temp-buflist)
3015 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3016 (defvar org-agenda-tags-todo-honor-ignore-options)
3017 (declare-function org-agenda-skip "org-agenda" ())
3018 (declare-function org-format-agenda-item "org-agenda"
3019 (extra txt &optional category tags dotime noprefix remove-re))
3020 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3021 (declare-function org-agenda-change-all-lines "org-agenda"
3022 (newhead hdmarker &optional fixface just-this))
3023 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3024 (declare-function org-agenda-maybe-redo "org-agenda" ())
3025 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3026 (beg end))
3027 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3028 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3029 "org-agenda" (&optional end))
3030 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3031 (declare-function org-indent-mode "org-indent" (&optional arg))
3032 (declare-function parse-time-string "parse-time" (string))
3033 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3034 (defvar remember-data-file)
3035 (defvar texmathp-why)
3036 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3037 (declare-function table--at-cell-p "table" (position &optional object at-column))
3039 (defvar w3m-current-url)
3040 (defvar w3m-current-title)
3042 (defvar org-latex-regexps)
3044 ;;; Autoload and prepare some org modules
3046 ;; Some table stuff that needs to be defined here, because it is used
3047 ;; by the functions setting up org-mode or checking for table context.
3049 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3050 "Detects an org-type or table-type table.")
3051 (defconst org-table-line-regexp "^[ \t]*|"
3052 "Detects an org-type table line.")
3053 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3054 "Detects an org-type table line.")
3055 (defconst org-table-hline-regexp "^[ \t]*|-"
3056 "Detects an org-type table hline.")
3057 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3058 "Detects a table-type table hline.")
3059 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3060 "Searching from within a table (any type) this finds the first line
3061 outside the table.")
3063 ;; Autoload the functions in org-table.el that are needed by functions here.
3065 (eval-and-compile
3066 (org-autoload "org-table"
3067 '(org-table-align org-table-begin org-table-blank-field
3068 org-table-convert org-table-convert-region org-table-copy-down
3069 org-table-copy-region org-table-create
3070 org-table-create-or-convert-from-region
3071 org-table-create-with-table.el org-table-current-dline
3072 org-table-cut-region org-table-delete-column org-table-edit-field
3073 org-table-edit-formulas org-table-end org-table-eval-formula
3074 org-table-export org-table-field-info
3075 org-table-get-stored-formulas org-table-goto-column
3076 org-table-hline-and-move org-table-import org-table-insert-column
3077 org-table-insert-hline org-table-insert-row org-table-iterate
3078 org-table-justify-field-maybe org-table-kill-row
3079 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3080 org-table-move-column org-table-move-column-left
3081 org-table-move-column-right org-table-move-row
3082 org-table-move-row-down org-table-move-row-up
3083 org-table-next-field org-table-next-row org-table-paste-rectangle
3084 org-table-previous-field org-table-recalculate
3085 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3086 org-table-toggle-coordinate-overlays
3087 org-table-toggle-formula-debugger org-table-wrap-region
3088 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3090 (defun org-at-table-p (&optional table-type)
3091 "Return t if the cursor is inside an org-type table.
3092 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3093 (if org-enable-table-editor
3094 (save-excursion
3095 (beginning-of-line 1)
3096 (looking-at (if table-type org-table-any-line-regexp
3097 org-table-line-regexp)))
3098 nil))
3099 (defsubst org-table-p () (org-at-table-p))
3101 (defun org-at-table.el-p ()
3102 "Return t if and only if we are at a table.el table."
3103 (and (org-at-table-p 'any)
3104 (save-excursion
3105 (goto-char (org-table-begin 'any))
3106 (looking-at org-table1-hline-regexp))))
3107 (defun org-table-recognize-table.el ()
3108 "If there is a table.el table nearby, recognize it and move into it."
3109 (if org-table-tab-recognizes-table.el
3110 (if (org-at-table.el-p)
3111 (progn
3112 (beginning-of-line 1)
3113 (if (looking-at org-table-dataline-regexp)
3115 (if (looking-at org-table1-hline-regexp)
3116 (progn
3117 (beginning-of-line 2)
3118 (if (looking-at org-table-any-border-regexp)
3119 (beginning-of-line -1)))))
3120 (if (re-search-forward "|" (org-table-end t) t)
3121 (progn
3122 (require 'table)
3123 (if (table--at-cell-p (point))
3125 (message "recognizing table.el table...")
3126 (table-recognize-table)
3127 (message "recognizing table.el table...done")))
3128 (error "This should not happen..."))
3130 nil)
3131 nil))
3133 (defun org-at-table-hline-p ()
3134 "Return t if the cursor is inside a hline in a table."
3135 (if org-enable-table-editor
3136 (save-excursion
3137 (beginning-of-line 1)
3138 (looking-at org-table-hline-regexp))
3139 nil))
3141 (defvar org-table-clean-did-remove-column nil)
3143 (defun org-table-map-tables (function)
3144 "Apply FUNCTION to the start of all tables in the buffer."
3145 (save-excursion
3146 (save-restriction
3147 (widen)
3148 (goto-char (point-min))
3149 (while (re-search-forward org-table-any-line-regexp nil t)
3150 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3151 (beginning-of-line 1)
3152 (when (looking-at org-table-line-regexp)
3153 (save-excursion (funcall function))
3154 (or (looking-at org-table-line-regexp)
3155 (forward-char 1)))
3156 (re-search-forward org-table-any-border-regexp nil 1))))
3157 (message "Mapping tables: done"))
3159 ;; Declare and autoload functions from org-exp.el & Co
3161 (declare-function org-default-export-plist "org-exp")
3162 (declare-function org-infile-export-plist "org-exp")
3163 (declare-function org-get-current-options "org-exp")
3164 (eval-and-compile
3165 (org-autoload "org-exp"
3166 '(org-export org-export-visible
3167 org-insert-export-options-template
3168 org-table-clean-before-export))
3169 (org-autoload "org-ascii"
3170 '(org-export-as-ascii org-export-ascii-preprocess
3171 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3172 org-export-region-as-ascii))
3173 (org-autoload "org-html"
3174 '(org-export-as-html-and-open
3175 org-export-as-html-batch org-export-as-html-to-buffer
3176 org-replace-region-by-html org-export-region-as-html
3177 org-export-as-html))
3178 (org-autoload "org-icalendar"
3179 '(org-export-icalendar-this-file
3180 org-export-icalendar-all-agenda-files
3181 org-export-icalendar-combine-agenda-files))
3182 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3184 ;; Declare and autoload functions from org-agenda.el
3186 (eval-and-compile
3187 (org-autoload "org-agenda"
3188 '(org-agenda org-agenda-list org-search-view
3189 org-todo-list org-tags-view org-agenda-list-stuck-projects
3190 org-diary org-agenda-to-appt
3191 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3193 ;; Autoload org-remember
3195 (eval-and-compile
3196 (org-autoload "org-remember"
3197 '(org-remember-insinuate org-remember-annotation
3198 org-remember-apply-template org-remember org-remember-handler)))
3200 ;; Autoload org-clock.el
3203 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3204 (beg end))
3205 (declare-function org-clock-update-mode-line "org-clock" ())
3206 (declare-function org-resolve-clocks "org-clock"
3207 (&optional also-non-dangling-p prompt last-valid))
3208 (defvar org-clock-start-time)
3209 (defvar org-clock-marker (make-marker)
3210 "Marker recording the last clock-in.")
3211 (defvar org-clock-hd-marker (make-marker)
3212 "Marker recording the last clock-in, but the headline position.")
3213 (defvar org-clock-heading ""
3214 "The heading of the current clock entry.")
3215 (defun org-clock-is-active ()
3216 "Return non-nil if clock is currently running.
3217 The return value is actually the clock marker."
3218 (marker-buffer org-clock-marker))
3220 (eval-and-compile
3221 (org-autoload
3222 "org-clock"
3223 '(org-clock-in org-clock-out org-clock-cancel
3224 org-clock-goto org-clock-sum org-clock-display
3225 org-clock-remove-overlays org-clock-report
3226 org-clocktable-shift org-dblock-write:clocktable
3227 org-get-clocktable org-resolve-clocks)))
3229 (defun org-clock-update-time-maybe ()
3230 "If this is a CLOCK line, update it and return t.
3231 Otherwise, return nil."
3232 (interactive)
3233 (save-excursion
3234 (beginning-of-line 1)
3235 (skip-chars-forward " \t")
3236 (when (looking-at org-clock-string)
3237 (let ((re (concat "[ \t]*" org-clock-string
3238 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3239 "\\([ \t]*=>.*\\)?\\)?"))
3240 ts te h m s neg)
3241 (cond
3242 ((not (looking-at re))
3243 nil)
3244 ((not (match-end 2))
3245 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3246 (> org-clock-marker (point))
3247 (<= org-clock-marker (point-at-eol)))
3248 ;; The clock is running here
3249 (setq org-clock-start-time
3250 (apply 'encode-time
3251 (org-parse-time-string (match-string 1))))
3252 (org-clock-update-mode-line)))
3254 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3255 (end-of-line 1)
3256 (setq ts (match-string 1)
3257 te (match-string 3))
3258 (setq s (- (org-float-time
3259 (apply 'encode-time (org-parse-time-string te)))
3260 (org-float-time
3261 (apply 'encode-time (org-parse-time-string ts))))
3262 neg (< s 0)
3263 s (abs s)
3264 h (floor (/ s 3600))
3265 s (- s (* 3600 h))
3266 m (floor (/ s 60))
3267 s (- s (* 60 s)))
3268 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3269 t))))))
3271 (defun org-check-running-clock ()
3272 "Check if the current buffer contains the running clock.
3273 If yes, offer to stop it and to save the buffer with the changes."
3274 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3275 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3276 (buffer-name))))
3277 (org-clock-out)
3278 (when (y-or-n-p "Save changed buffer?")
3279 (save-buffer))))
3281 (defun org-clocktable-try-shift (dir n)
3282 "Check if this line starts a clock table, if yes, shift the time block."
3283 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3284 (org-clocktable-shift dir n)))
3286 ;; Autoload org-timer.el
3288 (eval-and-compile
3289 (org-autoload
3290 "org-timer"
3291 '(org-timer-start org-timer org-timer-item
3292 org-timer-change-times-in-region
3293 org-timer-set-timer
3294 org-timer-reset-timers
3295 org-timer-show-remaining-time)))
3297 ;; Autoload org-feed.el
3299 (eval-and-compile
3300 (org-autoload
3301 "org-feed"
3302 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3305 ;; Autoload org-indent.el
3307 ;; Define the variable already here, to make sure we have it.
3308 (defvar org-indent-mode nil
3309 "Non-nil if Org-Indent mode is enabled.
3310 Use the command `org-indent-mode' to change this variable.")
3312 (eval-and-compile
3313 (org-autoload
3314 "org-indent"
3315 '(org-indent-mode)))
3317 ;; Autoload org-mobile.el
3319 (eval-and-compile
3320 (org-autoload
3321 "org-mobile"
3322 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3324 ;; Autoload archiving code
3325 ;; The stuff that is needed for cycling and tags has to be defined here.
3327 (defgroup org-archive nil
3328 "Options concerning archiving in Org-mode."
3329 :tag "Org Archive"
3330 :group 'org-structure)
3332 (defcustom org-archive-location "%s_archive::"
3333 "The location where subtrees should be archived.
3335 The value of this variable is a string, consisting of two parts,
3336 separated by a double-colon. The first part is a filename and
3337 the second part is a headline.
3339 When the filename is omitted, archiving happens in the same file.
3340 %s in the filename will be replaced by the current file
3341 name (without the directory part). Archiving to a different file
3342 is useful to keep archived entries from contributing to the
3343 Org-mode Agenda.
3345 The archived entries will be filed as subtrees of the specified
3346 headline. When the headline is omitted, the subtrees are simply
3347 filed away at the end of the file, as top-level entries. Also in
3348 the heading you can use %s to represent the file name, this can be
3349 useful when using the same archive for a number of different files.
3351 Here are a few examples:
3352 \"%s_archive::\"
3353 If the current file is Projects.org, archive in file
3354 Projects.org_archive, as top-level trees. This is the default.
3356 \"::* Archived Tasks\"
3357 Archive in the current file, under the top-level headline
3358 \"* Archived Tasks\".
3360 \"~/org/archive.org::\"
3361 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3363 \"~/org/archive.org::From %s\"
3364 Archive in file ~/org/archive.org (absolute path), und headlines
3365 \"From FILENAME\" where file name is the current file name.
3367 \"basement::** Finished Tasks\"
3368 Archive in file ./basement (relative path), as level 3 trees
3369 below the level 2 heading \"** Finished Tasks\".
3371 You may set this option on a per-file basis by adding to the buffer a
3372 line like
3374 #+ARCHIVE: basement::** Finished Tasks
3376 You may also define it locally for a subtree by setting an ARCHIVE property
3377 in the entry. If such a property is found in an entry, or anywhere up
3378 the hierarchy, it will be used."
3379 :group 'org-archive
3380 :type 'string)
3382 (defcustom org-archive-tag "ARCHIVE"
3383 "The tag that marks a subtree as archived.
3384 An archived subtree does not open during visibility cycling, and does
3385 not contribute to the agenda listings.
3386 After changing this, font-lock must be restarted in the relevant buffers to
3387 get the proper fontification."
3388 :group 'org-archive
3389 :group 'org-keywords
3390 :type 'string)
3392 (defcustom org-agenda-skip-archived-trees t
3393 "Non-nil means, the agenda will skip any items located in archived trees.
3394 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3395 variable is no longer recommended, you should leave it at the value t.
3396 Instead, use the key `v' to cycle the archives-mode in the agenda."
3397 :group 'org-archive
3398 :group 'org-agenda-skip
3399 :type 'boolean)
3401 (defcustom org-columns-skip-archived-trees t
3402 "Non-nil means, ignore archived trees when creating column view."
3403 :group 'org-archive
3404 :group 'org-properties
3405 :type 'boolean)
3407 (defcustom org-cycle-open-archived-trees nil
3408 "Non-nil means, `org-cycle' will open archived trees.
3409 An archived tree is a tree marked with the tag ARCHIVE.
3410 When nil, archived trees will stay folded. You can still open them with
3411 normal outline commands like `show-all', but not with the cycling commands."
3412 :group 'org-archive
3413 :group 'org-cycle
3414 :type 'boolean)
3416 (defcustom org-sparse-tree-open-archived-trees nil
3417 "Non-nil means sparse tree construction shows matches in archived trees.
3418 When nil, matches in these trees are highlighted, but the trees are kept in
3419 collapsed state."
3420 :group 'org-archive
3421 :group 'org-sparse-trees
3422 :type 'boolean)
3424 (defun org-cycle-hide-archived-subtrees (state)
3425 "Re-hide all archived subtrees after a visibility state change."
3426 (when (and (not org-cycle-open-archived-trees)
3427 (not (memq state '(overview folded))))
3428 (save-excursion
3429 (let* ((globalp (memq state '(contents all)))
3430 (beg (if globalp (point-min) (point)))
3431 (end (if globalp (point-max) (org-end-of-subtree t))))
3432 (org-hide-archived-subtrees beg end)
3433 (goto-char beg)
3434 (if (looking-at (concat ".*:" org-archive-tag ":"))
3435 (message "%s" (substitute-command-keys
3436 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3438 (defun org-force-cycle-archived ()
3439 "Cycle subtree even if it is archived."
3440 (interactive)
3441 (setq this-command 'org-cycle)
3442 (let ((org-cycle-open-archived-trees t))
3443 (call-interactively 'org-cycle)))
3445 (defun org-hide-archived-subtrees (beg end)
3446 "Re-hide all archived subtrees after a visibility state change."
3447 (save-excursion
3448 (let* ((re (concat ":" org-archive-tag ":")))
3449 (goto-char beg)
3450 (while (re-search-forward re end t)
3451 (and (org-on-heading-p) (org-flag-subtree t))
3452 (org-end-of-subtree t)))))
3454 (defun org-flag-subtree (flag)
3455 (save-excursion
3456 (org-back-to-heading t)
3457 (outline-end-of-heading)
3458 (outline-flag-region (point)
3459 (progn (org-end-of-subtree t) (point))
3460 flag)))
3462 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3464 (eval-and-compile
3465 (org-autoload "org-archive"
3466 '(org-add-archive-files org-archive-subtree
3467 org-archive-to-archive-sibling org-toggle-archive-tag)))
3469 ;; Autoload Column View Code
3471 (declare-function org-columns-number-to-string "org-colview")
3472 (declare-function org-columns-get-format-and-top-level "org-colview")
3473 (declare-function org-columns-compute "org-colview")
3475 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3476 '(org-columns-number-to-string org-columns-get-format-and-top-level
3477 org-columns-compute org-agenda-columns org-columns-remove-overlays
3478 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3480 ;; Autoload ID code
3482 (declare-function org-id-store-link "org-id")
3483 (declare-function org-id-locations-load "org-id")
3484 (declare-function org-id-locations-save "org-id")
3485 (defvar org-id-track-globally)
3486 (org-autoload "org-id"
3487 '(org-id-get-create org-id-new org-id-copy org-id-get
3488 org-id-get-with-outline-path-completion
3489 org-id-get-with-outline-drilling
3490 org-id-goto org-id-find org-id-store-link))
3492 ;; Autoload Plotting Code
3494 (org-autoload "org-plot"
3495 '(org-plot/gnuplot))
3497 ;;; Variables for pre-computed regular expressions, all buffer local
3499 (defvar org-drawer-regexp nil
3500 "Matches first line of a hidden block.")
3501 (make-variable-buffer-local 'org-drawer-regexp)
3502 (defvar org-todo-regexp nil
3503 "Matches any of the TODO state keywords.")
3504 (make-variable-buffer-local 'org-todo-regexp)
3505 (defvar org-not-done-regexp nil
3506 "Matches any of the TODO state keywords except the last one.")
3507 (make-variable-buffer-local 'org-not-done-regexp)
3508 (defvar org-not-done-heading-regexp nil
3509 "Matches a TODO headline that is not done.")
3510 (make-variable-buffer-local 'org-not-done-regexp)
3511 (defvar org-todo-line-regexp nil
3512 "Matches a headline and puts TODO state into group 2 if present.")
3513 (make-variable-buffer-local 'org-todo-line-regexp)
3514 (defvar org-complex-heading-regexp nil
3515 "Matches a headline and puts everything into groups:
3516 group 1: the stars
3517 group 2: The todo keyword, maybe
3518 group 3: Priority cookie
3519 group 4: True headline
3520 group 5: Tags")
3521 (make-variable-buffer-local 'org-complex-heading-regexp)
3522 (defvar org-complex-heading-regexp-format nil)
3523 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3524 (defvar org-todo-line-tags-regexp nil
3525 "Matches a headline and puts TODO state into group 2 if present.
3526 Also put tags into group 4 if tags are present.")
3527 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3528 (defvar org-nl-done-regexp nil
3529 "Matches newline followed by a headline with the DONE keyword.")
3530 (make-variable-buffer-local 'org-nl-done-regexp)
3531 (defvar org-looking-at-done-regexp nil
3532 "Matches the DONE keyword a point.")
3533 (make-variable-buffer-local 'org-looking-at-done-regexp)
3534 (defvar org-ds-keyword-length 12
3535 "Maximum length of the Deadline and SCHEDULED keywords.")
3536 (make-variable-buffer-local 'org-ds-keyword-length)
3537 (defvar org-deadline-regexp nil
3538 "Matches the DEADLINE keyword.")
3539 (make-variable-buffer-local 'org-deadline-regexp)
3540 (defvar org-deadline-time-regexp nil
3541 "Matches the DEADLINE keyword together with a time stamp.")
3542 (make-variable-buffer-local 'org-deadline-time-regexp)
3543 (defvar org-deadline-line-regexp nil
3544 "Matches the DEADLINE keyword and the rest of the line.")
3545 (make-variable-buffer-local 'org-deadline-line-regexp)
3546 (defvar org-scheduled-regexp nil
3547 "Matches the SCHEDULED keyword.")
3548 (make-variable-buffer-local 'org-scheduled-regexp)
3549 (defvar org-scheduled-time-regexp nil
3550 "Matches the SCHEDULED keyword together with a time stamp.")
3551 (make-variable-buffer-local 'org-scheduled-time-regexp)
3552 (defvar org-closed-time-regexp nil
3553 "Matches the CLOSED keyword together with a time stamp.")
3554 (make-variable-buffer-local 'org-closed-time-regexp)
3556 (defvar org-keyword-time-regexp nil
3557 "Matches any of the 4 keywords, together with the time stamp.")
3558 (make-variable-buffer-local 'org-keyword-time-regexp)
3559 (defvar org-keyword-time-not-clock-regexp nil
3560 "Matches any of the 3 keywords, together with the time stamp.")
3561 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3562 (defvar org-maybe-keyword-time-regexp nil
3563 "Matches a timestamp, possibly preceeded by a keyword.")
3564 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3565 (defvar org-planning-or-clock-line-re nil
3566 "Matches a line with planning or clock info.")
3567 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3569 (defconst org-plain-time-of-day-regexp
3570 (concat
3571 "\\(\\<[012]?[0-9]"
3572 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3573 "\\(--?"
3574 "\\(\\<[012]?[0-9]"
3575 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3576 "\\)?")
3577 "Regular expression to match a plain time or time range.
3578 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3579 groups carry important information:
3580 0 the full match
3581 1 the first time, range or not
3582 8 the second time, if it is a range.")
3584 (defconst org-plain-time-extension-regexp
3585 (concat
3586 "\\(\\<[012]?[0-9]"
3587 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3588 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3589 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3590 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3591 groups carry important information:
3592 0 the full match
3593 7 hours of duration
3594 9 minutes of duration")
3596 (defconst org-stamp-time-of-day-regexp
3597 (concat
3598 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3599 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3600 "\\(--?"
3601 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3602 "Regular expression to match a timestamp time or time range.
3603 After a match, the following groups carry important information:
3604 0 the full match
3605 1 date plus weekday, for backreferencing to make sure both times on same day
3606 2 the first time, range or not
3607 4 the second time, if it is a range.")
3609 (defconst org-startup-options
3610 '(("fold" org-startup-folded t)
3611 ("overview" org-startup-folded t)
3612 ("nofold" org-startup-folded nil)
3613 ("showall" org-startup-folded nil)
3614 ("showeverything" org-startup-folded showeverything)
3615 ("content" org-startup-folded content)
3616 ("indent" org-startup-indented t)
3617 ("noindent" org-startup-indented nil)
3618 ("hidestars" org-hide-leading-stars t)
3619 ("showstars" org-hide-leading-stars nil)
3620 ("odd" org-odd-levels-only t)
3621 ("oddeven" org-odd-levels-only nil)
3622 ("align" org-startup-align-all-tables t)
3623 ("noalign" org-startup-align-all-tables nil)
3624 ("customtime" org-display-custom-times t)
3625 ("logdone" org-log-done time)
3626 ("lognotedone" org-log-done note)
3627 ("nologdone" org-log-done nil)
3628 ("lognoteclock-out" org-log-note-clock-out t)
3629 ("nolognoteclock-out" org-log-note-clock-out nil)
3630 ("logrepeat" org-log-repeat state)
3631 ("lognoterepeat" org-log-repeat note)
3632 ("nologrepeat" org-log-repeat nil)
3633 ("fninline" org-footnote-define-inline t)
3634 ("nofninline" org-footnote-define-inline nil)
3635 ("fnlocal" org-footnote-section nil)
3636 ("fnauto" org-footnote-auto-label t)
3637 ("fnprompt" org-footnote-auto-label nil)
3638 ("fnconfirm" org-footnote-auto-label confirm)
3639 ("fnplain" org-footnote-auto-label plain)
3640 ("fnadjust" org-footnote-auto-adjust t)
3641 ("nofnadjust" org-footnote-auto-adjust nil)
3642 ("constcgs" constants-unit-system cgs)
3643 ("constSI" constants-unit-system SI)
3644 ("noptag" org-tag-persistent-alist nil)
3645 ("hideblocks" org-hide-block-startup t)
3646 ("nohideblocks" org-hide-block-startup nil))
3647 "Variable associated with STARTUP options for org-mode.
3648 Each element is a list of three items: The startup options as written
3649 in the #+STARTUP line, the corresponding variable, and the value to
3650 set this variable to if the option is found. An optional forth element PUSH
3651 means to push this value onto the list in the variable.")
3653 (defun org-set-regexps-and-options ()
3654 "Precompute regular expressions for current buffer."
3655 (when (org-mode-p)
3656 (org-set-local 'org-todo-kwd-alist nil)
3657 (org-set-local 'org-todo-key-alist nil)
3658 (org-set-local 'org-todo-key-trigger nil)
3659 (org-set-local 'org-todo-keywords-1 nil)
3660 (org-set-local 'org-done-keywords nil)
3661 (org-set-local 'org-todo-heads nil)
3662 (org-set-local 'org-todo-sets nil)
3663 (org-set-local 'org-todo-log-states nil)
3664 (org-set-local 'org-file-properties nil)
3665 (org-set-local 'org-file-tags nil)
3666 (let ((re (org-make-options-regexp
3667 '("CATEGORY" "TODO" "COLUMNS"
3668 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3669 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3670 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3671 (splitre "[ \t]+")
3672 kwds kws0 kwsa key log value cat arch tags const links hw dws
3673 tail sep kws1 prio props ftags drawers
3674 ext-setup-or-nil setup-contents (start 0))
3675 (save-excursion
3676 (save-restriction
3677 (widen)
3678 (goto-char (point-min))
3679 (while (or (and ext-setup-or-nil
3680 (string-match re ext-setup-or-nil start)
3681 (setq start (match-end 0)))
3682 (and (setq ext-setup-or-nil nil start 0)
3683 (re-search-forward re nil t)))
3684 (setq key (upcase (match-string 1 ext-setup-or-nil))
3685 value (org-match-string-no-properties 2 ext-setup-or-nil))
3686 (cond
3687 ((equal key "CATEGORY")
3688 (if (string-match "[ \t]+$" value)
3689 (setq value (replace-match "" t t value)))
3690 (setq cat value))
3691 ((member key '("SEQ_TODO" "TODO"))
3692 (push (cons 'sequence (org-split-string value splitre)) kwds))
3693 ((equal key "TYP_TODO")
3694 (push (cons 'type (org-split-string value splitre)) kwds))
3695 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3696 ;; general TODO-like setup
3697 (push (cons (intern (downcase (match-string 1 key)))
3698 (org-split-string value splitre)) kwds))
3699 ((equal key "TAGS")
3700 (setq tags (append tags (if tags '("\\n") nil)
3701 (org-split-string value splitre))))
3702 ((equal key "COLUMNS")
3703 (org-set-local 'org-columns-default-format value))
3704 ((equal key "LINK")
3705 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3706 (push (cons (match-string 1 value)
3707 (org-trim (match-string 2 value)))
3708 links)))
3709 ((equal key "PRIORITIES")
3710 (setq prio (org-split-string value " +")))
3711 ((equal key "PROPERTY")
3712 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3713 (push (cons (match-string 1 value) (match-string 2 value))
3714 props)))
3715 ((equal key "FILETAGS")
3716 (when (string-match "\\S-" value)
3717 (setq ftags
3718 (append
3719 ftags
3720 (apply 'append
3721 (mapcar (lambda (x) (org-split-string x ":"))
3722 (org-split-string value)))))))
3723 ((equal key "DRAWERS")
3724 (setq drawers (org-split-string value splitre)))
3725 ((equal key "CONSTANTS")
3726 (setq const (append const (org-split-string value splitre))))
3727 ((equal key "STARTUP")
3728 (let ((opts (org-split-string value splitre))
3729 l var val)
3730 (while (setq l (pop opts))
3731 (when (setq l (assoc l org-startup-options))
3732 (setq var (nth 1 l) val (nth 2 l))
3733 (if (not (nth 3 l))
3734 (set (make-local-variable var) val)
3735 (if (not (listp (symbol-value var)))
3736 (set (make-local-variable var) nil))
3737 (set (make-local-variable var) (symbol-value var))
3738 (add-to-list var val))))))
3739 ((equal key "ARCHIVE")
3740 (string-match " *$" value)
3741 (setq arch (replace-match "" t t value))
3742 (remove-text-properties 0 (length arch)
3743 '(face t fontified t) arch))
3744 ((equal key "SETUPFILE")
3745 (setq setup-contents (org-file-contents
3746 (expand-file-name
3747 (org-remove-double-quotes value))
3748 'noerror))
3749 (if (not ext-setup-or-nil)
3750 (setq ext-setup-or-nil setup-contents start 0)
3751 (setq ext-setup-or-nil
3752 (concat (substring ext-setup-or-nil 0 start)
3753 "\n" setup-contents "\n"
3754 (substring ext-setup-or-nil start)))))
3755 ))))
3756 (when cat
3757 (org-set-local 'org-category (intern cat))
3758 (push (cons "CATEGORY" cat) props))
3759 (when prio
3760 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3761 (setq prio (mapcar 'string-to-char prio))
3762 (org-set-local 'org-highest-priority (nth 0 prio))
3763 (org-set-local 'org-lowest-priority (nth 1 prio))
3764 (org-set-local 'org-default-priority (nth 2 prio)))
3765 (and props (org-set-local 'org-file-properties (nreverse props)))
3766 (and ftags (org-set-local 'org-file-tags
3767 (mapcar 'org-add-prop-inherited ftags)))
3768 (and drawers (org-set-local 'org-drawers drawers))
3769 (and arch (org-set-local 'org-archive-location arch))
3770 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3771 ;; Process the TODO keywords
3772 (unless kwds
3773 ;; Use the global values as if they had been given locally.
3774 (setq kwds (default-value 'org-todo-keywords))
3775 (if (stringp (car kwds))
3776 (setq kwds (list (cons org-todo-interpretation
3777 (default-value 'org-todo-keywords)))))
3778 (setq kwds (reverse kwds)))
3779 (setq kwds (nreverse kwds))
3780 (let (inter kws kw)
3781 (while (setq kws (pop kwds))
3782 (let ((kws (or
3783 (run-hook-with-args-until-success
3784 'org-todo-setup-filter-hook kws)
3785 kws)))
3786 (setq inter (pop kws) sep (member "|" kws)
3787 kws0 (delete "|" (copy-sequence kws))
3788 kwsa nil
3789 kws1 (mapcar
3790 (lambda (x)
3791 ;; 1 2
3792 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3793 (progn
3794 (setq kw (match-string 1 x)
3795 key (and (match-end 2) (match-string 2 x))
3796 log (org-extract-log-state-settings x))
3797 (push (cons kw (and key (string-to-char key))) kwsa)
3798 (and log (push log org-todo-log-states))
3800 (error "Invalid TODO keyword %s" x)))
3801 kws0)
3802 kwsa (if kwsa (append '((:startgroup))
3803 (nreverse kwsa)
3804 '((:endgroup))))
3805 hw (car kws1)
3806 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3807 tail (list inter hw (car dws) (org-last dws))))
3808 (add-to-list 'org-todo-heads hw 'append)
3809 (push kws1 org-todo-sets)
3810 (setq org-done-keywords (append org-done-keywords dws nil))
3811 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3812 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3813 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3814 (setq org-todo-sets (nreverse org-todo-sets)
3815 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3816 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3817 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3818 ;; Process the constants
3819 (when const
3820 (let (e cst)
3821 (while (setq e (pop const))
3822 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3823 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3824 (setq org-table-formula-constants-local cst)))
3826 ;; Process the tags.
3827 (when tags
3828 (let (e tgs)
3829 (while (setq e (pop tags))
3830 (cond
3831 ((equal e "{") (push '(:startgroup) tgs))
3832 ((equal e "}") (push '(:endgroup) tgs))
3833 ((equal e "\\n") (push '(:newline) tgs))
3834 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3835 (push (cons (match-string 1 e)
3836 (string-to-char (match-string 2 e)))
3837 tgs))
3838 (t (push (list e) tgs))))
3839 (org-set-local 'org-tag-alist nil)
3840 (while (setq e (pop tgs))
3841 (or (and (stringp (car e))
3842 (assoc (car e) org-tag-alist))
3843 (push e org-tag-alist)))))
3845 ;; Compute the regular expressions and other local variables
3846 (if (not org-done-keywords)
3847 (setq org-done-keywords (and org-todo-keywords-1
3848 (list (org-last org-todo-keywords-1)))))
3849 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3850 (length org-scheduled-string)
3851 (length org-clock-string)
3852 (length org-closed-string)))
3853 org-drawer-regexp
3854 (concat "^[ \t]*:\\("
3855 (mapconcat 'regexp-quote org-drawers "\\|")
3856 "\\):[ \t]*$")
3857 org-not-done-keywords
3858 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3859 org-todo-regexp
3860 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3861 "\\|") "\\)\\>")
3862 org-not-done-regexp
3863 (concat "\\<\\("
3864 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3865 "\\)\\>")
3866 org-not-done-heading-regexp
3867 (concat "^\\(\\*+\\)[ \t]+\\("
3868 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3869 "\\)\\>")
3870 org-todo-line-regexp
3871 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3872 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3873 "\\)\\>\\)?[ \t]*\\(.*\\)")
3874 org-complex-heading-regexp
3875 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3876 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3877 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3878 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3879 org-complex-heading-regexp-format
3880 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3881 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3882 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
3883 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3884 org-nl-done-regexp
3885 (concat "\n\\*+[ \t]+"
3886 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3887 "\\)" "\\>")
3888 org-todo-line-tags-regexp
3889 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3890 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3891 (org-re
3892 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3893 org-looking-at-done-regexp
3894 (concat "^" "\\(?:"
3895 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3896 "\\>")
3897 org-deadline-regexp (concat "\\<" org-deadline-string)
3898 org-deadline-time-regexp
3899 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3900 org-deadline-line-regexp
3901 (concat "\\<\\(" org-deadline-string "\\).*")
3902 org-scheduled-regexp
3903 (concat "\\<" org-scheduled-string)
3904 org-scheduled-time-regexp
3905 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3906 org-closed-time-regexp
3907 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3908 org-keyword-time-regexp
3909 (concat "\\<\\(" org-scheduled-string
3910 "\\|" org-deadline-string
3911 "\\|" org-closed-string
3912 "\\|" org-clock-string "\\)"
3913 " *[[<]\\([^]>]+\\)[]>]")
3914 org-keyword-time-not-clock-regexp
3915 (concat "\\<\\(" org-scheduled-string
3916 "\\|" org-deadline-string
3917 "\\|" org-closed-string
3918 "\\)"
3919 " *[[<]\\([^]>]+\\)[]>]")
3920 org-maybe-keyword-time-regexp
3921 (concat "\\(\\<\\(" org-scheduled-string
3922 "\\|" org-deadline-string
3923 "\\|" org-closed-string
3924 "\\|" org-clock-string "\\)\\)?"
3925 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3926 org-planning-or-clock-line-re
3927 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3928 "\\|" org-deadline-string
3929 "\\|" org-closed-string "\\|" org-clock-string
3930 "\\)\\>\\)")
3932 (org-compute-latex-and-specials-regexp)
3933 (org-set-font-lock-defaults))))
3935 (defun org-file-contents (file &optional noerror)
3936 "Return the contents of FILE, as a string."
3937 (if (or (not file)
3938 (not (file-readable-p file)))
3939 (if noerror
3940 (progn
3941 (message "Cannot read file %s" file)
3942 (ding) (sit-for 2)
3944 (error "Cannot read file %s" file))
3945 (with-temp-buffer
3946 (insert-file-contents file)
3947 (buffer-string))))
3949 (defun org-extract-log-state-settings (x)
3950 "Extract the log state setting from a TODO keyword string.
3951 This will extract info from a string like \"WAIT(w@/!)\"."
3952 (let (kw key log1 log2)
3953 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3954 (setq kw (match-string 1 x)
3955 key (and (match-end 2) (match-string 2 x))
3956 log1 (and (match-end 3) (match-string 3 x))
3957 log2 (and (match-end 4) (match-string 4 x)))
3958 (and (or log1 log2)
3959 (list kw
3960 (and log1 (if (equal log1 "!") 'time 'note))
3961 (and log2 (if (equal log2 "!") 'time 'note)))))))
3963 (defun org-remove-keyword-keys (list)
3964 "Remove a pair of parenthesis at the end of each string in LIST."
3965 (mapcar (lambda (x)
3966 (if (string-match "(.*)$" x)
3967 (substring x 0 (match-beginning 0))
3969 list))
3971 ;; FIXME: this could be done much better, using second characters etc.
3972 (defun org-assign-fast-keys (alist)
3973 "Assign fast keys to a keyword-key alist.
3974 Respect keys that are already there."
3975 (let (new e k c c1 c2 (char ?a))
3976 (while (setq e (pop alist))
3977 (cond
3978 ((equal e '(:startgroup)) (push e new))
3979 ((equal e '(:endgroup)) (push e new))
3980 ((equal e '(:newline)) (push e new))
3982 (setq k (car e) c2 nil)
3983 (if (cdr e)
3984 (setq c (cdr e))
3985 ;; automatically assign a character.
3986 (setq c1 (string-to-char
3987 (downcase (substring
3988 k (if (= (string-to-char k) ?@) 1 0)))))
3989 (if (or (rassoc c1 new) (rassoc c1 alist))
3990 (while (or (rassoc char new) (rassoc char alist))
3991 (setq char (1+ char)))
3992 (setq c2 c1))
3993 (setq c (or c2 char)))
3994 (push (cons k c) new))))
3995 (nreverse new)))
3997 ;;; Some variables used in various places
3999 (defvar org-window-configuration nil
4000 "Used in various places to store a window configuration.")
4001 (defvar org-selected-window nil
4002 "Used in various places to store a window configuration.")
4003 (defvar org-finish-function nil
4004 "Function to be called when `C-c C-c' is used.
4005 This is for getting out of special buffers like remember.")
4008 ;; FIXME: Occasionally check by commenting these, to make sure
4009 ;; no other functions uses these, forgetting to let-bind them.
4010 (defvar entry)
4011 (defvar last-state)
4012 (defvar date)
4014 ;; Defined somewhere in this file, but used before definition.
4015 (defvar org-html-entities)
4016 (defvar org-struct-menu)
4017 (defvar org-org-menu)
4018 (defvar org-tbl-menu)
4020 ;;;; Define the Org-mode
4022 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4023 (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."))
4026 ;; We use a before-change function to check if a table might need
4027 ;; an update.
4028 (defvar org-table-may-need-update t
4029 "Indicates that a table might need an update.
4030 This variable is set by `org-before-change-function'.
4031 `org-table-align' sets it back to nil.")
4032 (defun org-before-change-function (beg end)
4033 "Every change indicates that a table might need an update."
4034 (setq org-table-may-need-update t))
4035 (defvar org-mode-map)
4036 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4037 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4038 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4039 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4040 (defvar org-table-buffer-is-an nil)
4041 (defconst org-outline-regexp "\\*+ ")
4043 ;;;###autoload
4044 (define-derived-mode org-mode outline-mode "Org"
4045 "Outline-based notes management and organizer, alias
4046 \"Carsten's outline-mode for keeping track of everything.\"
4048 Org-mode develops organizational tasks around a NOTES file which
4049 contains information about projects as plain text. Org-mode is
4050 implemented on top of outline-mode, which is ideal to keep the content
4051 of large files well structured. It supports ToDo items, deadlines and
4052 time stamps, which magically appear in the diary listing of the Emacs
4053 calendar. Tables are easily created with a built-in table editor.
4054 Plain text URL-like links connect to websites, emails (VM), Usenet
4055 messages (Gnus), BBDB entries, and any files related to the project.
4056 For printing and sharing of notes, an Org-mode file (or a part of it)
4057 can be exported as a structured ASCII or HTML file.
4059 The following commands are available:
4061 \\{org-mode-map}"
4063 ;; Get rid of Outline menus, they are not needed
4064 ;; Need to do this here because define-derived-mode sets up
4065 ;; the keymap so late. Still, it is a waste to call this each time
4066 ;; we switch another buffer into org-mode.
4067 (if (featurep 'xemacs)
4068 (when (boundp 'outline-mode-menu-heading)
4069 ;; Assume this is Greg's port, it used easymenu
4070 (easy-menu-remove outline-mode-menu-heading)
4071 (easy-menu-remove outline-mode-menu-show)
4072 (easy-menu-remove outline-mode-menu-hide))
4073 (define-key org-mode-map [menu-bar headings] 'undefined)
4074 (define-key org-mode-map [menu-bar hide] 'undefined)
4075 (define-key org-mode-map [menu-bar show] 'undefined))
4077 (org-load-modules-maybe)
4078 (easy-menu-add org-org-menu)
4079 (easy-menu-add org-tbl-menu)
4080 (org-install-agenda-files-menu)
4081 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4082 (org-add-to-invisibility-spec '(org-cwidth))
4083 (org-add-to-invisibility-spec '(org-hide-block . t))
4084 (when (featurep 'xemacs)
4085 (org-set-local 'line-move-ignore-invisible t))
4086 (org-set-local 'outline-regexp org-outline-regexp)
4087 (org-set-local 'outline-level 'org-outline-level)
4088 (when (and org-ellipsis
4089 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4090 (fboundp 'make-glyph-code))
4091 (unless org-display-table
4092 (setq org-display-table (make-display-table)))
4093 (set-display-table-slot
4094 org-display-table 4
4095 (vconcat (mapcar
4096 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4097 org-ellipsis)))
4098 (if (stringp org-ellipsis) org-ellipsis "..."))))
4099 (setq buffer-display-table org-display-table))
4100 (org-set-regexps-and-options)
4101 (when (and org-tag-faces (not org-tags-special-faces-re))
4102 ;; tag faces set outside customize.... force initialization.
4103 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4104 ;; Calc embedded
4105 (org-set-local 'calc-embedded-open-mode "# ")
4106 (modify-syntax-entry ?# "<")
4107 (modify-syntax-entry ?@ "w")
4108 (if org-startup-truncated (setq truncate-lines t))
4109 (org-set-local 'font-lock-unfontify-region-function
4110 'org-unfontify-region)
4111 ;; Activate before-change-function
4112 (org-set-local 'org-table-may-need-update t)
4113 (org-add-hook 'before-change-functions 'org-before-change-function nil
4114 'local)
4115 ;; Check for running clock before killing a buffer
4116 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4117 ;; Paragraphs and auto-filling
4118 (org-set-autofill-regexps)
4119 (setq indent-line-function 'org-indent-line-function)
4120 (org-update-radio-target-regexp)
4121 ;; Make sure dependence stuff works reliably, even for users who set it
4122 ;; too late :-(
4123 (if org-enforce-todo-dependencies
4124 (add-hook 'org-blocker-hook
4125 'org-block-todo-from-children-or-siblings-or-parent)
4126 (remove-hook 'org-blocker-hook
4127 'org-block-todo-from-children-or-siblings-or-parent))
4128 (if org-enforce-todo-checkbox-dependencies
4129 (add-hook 'org-blocker-hook
4130 'org-block-todo-from-checkboxes)
4131 (remove-hook 'org-blocker-hook
4132 'org-block-todo-from-checkboxes))
4134 ;; Comment characters
4135 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4136 (org-set-local 'comment-padding " ")
4138 ;; Align options lines
4139 (org-set-local
4140 'align-mode-rules-list
4141 '((org-in-buffer-settings
4142 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4143 (modes . '(org-mode)))))
4145 ;; Imenu
4146 (org-set-local 'imenu-create-index-function
4147 'org-imenu-get-tree)
4149 ;; Make isearch reveal context
4150 (if (or (featurep 'xemacs)
4151 (not (boundp 'outline-isearch-open-invisible-function)))
4152 ;; Emacs 21 and XEmacs make use of the hook
4153 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4154 ;; Emacs 22 deals with this through a special variable
4155 (org-set-local 'outline-isearch-open-invisible-function
4156 (lambda (&rest ignore) (org-show-context 'isearch))))
4158 ;; If empty file that did not turn on org-mode automatically, make it to.
4159 (if (and org-insert-mode-line-in-empty-file
4160 (interactive-p)
4161 (= (point-min) (point-max)))
4162 (insert "# -*- mode: org -*-\n\n"))
4164 (unless org-inhibit-startup
4165 (when org-startup-align-all-tables
4166 (let ((bmp (buffer-modified-p)))
4167 (org-table-map-tables 'org-table-align)
4168 (set-buffer-modified-p bmp)))
4169 (when org-startup-indented
4170 (require 'org-indent)
4171 (org-indent-mode 1))
4172 (org-set-startup-visibility)))
4174 (when (fboundp 'abbrev-table-put)
4175 (abbrev-table-put org-mode-abbrev-table
4176 :parents (list text-mode-abbrev-table)))
4178 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4180 (defun org-current-time ()
4181 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4182 (if (> (car org-time-stamp-rounding-minutes) 1)
4183 (let ((r (car org-time-stamp-rounding-minutes))
4184 (time (decode-time)))
4185 (apply 'encode-time
4186 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4187 (nthcdr 2 time))))
4188 (current-time)))
4190 ;;;; Font-Lock stuff, including the activators
4192 (defvar org-mouse-map (make-sparse-keymap))
4193 (org-defkey org-mouse-map
4194 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4195 (org-defkey org-mouse-map
4196 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4197 (when org-mouse-1-follows-link
4198 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4199 (when org-tab-follows-link
4200 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4201 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4203 (require 'font-lock)
4205 (defconst org-non-link-chars "]\t\n\r<>")
4206 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4207 "shell" "elisp"))
4208 (defvar org-link-types-re nil
4209 "Matches a link that has a url-like prefix like \"http:\"")
4210 (defvar org-link-re-with-space nil
4211 "Matches a link with spaces, optional angular brackets around it.")
4212 (defvar org-link-re-with-space2 nil
4213 "Matches a link with spaces, optional angular brackets around it.")
4214 (defvar org-link-re-with-space3 nil
4215 "Matches a link with spaces, only for internal part in bracket links.")
4216 (defvar org-angle-link-re nil
4217 "Matches link with angular brackets, spaces are allowed.")
4218 (defvar org-plain-link-re nil
4219 "Matches plain link, without spaces.")
4220 (defvar org-bracket-link-regexp nil
4221 "Matches a link in double brackets.")
4222 (defvar org-bracket-link-analytic-regexp nil
4223 "Regular expression used to analyze links.
4224 Here is what the match groups contain after a match:
4225 1: http:
4226 2: http
4227 3: path
4228 4: [desc]
4229 5: desc")
4230 (defvar org-bracket-link-analytic-regexp++ nil
4231 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4232 (defvar org-any-link-re nil
4233 "Regular expression matching any link.")
4235 (defun org-make-link-regexps ()
4236 "Update the link regular expressions.
4237 This should be called after the variable `org-link-types' has changed."
4238 (setq org-link-types-re
4239 (concat
4240 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4241 org-link-re-with-space
4242 (concat
4243 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4244 "\\([^" org-non-link-chars " ]"
4245 "[^" org-non-link-chars "]*"
4246 "[^" org-non-link-chars " ]\\)>?")
4247 org-link-re-with-space2
4248 (concat
4249 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4250 "\\([^" org-non-link-chars " ]"
4251 "[^\t\n\r]*"
4252 "[^" org-non-link-chars " ]\\)>?")
4253 org-link-re-with-space3
4254 (concat
4255 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4256 "\\([^" org-non-link-chars " ]"
4257 "[^\t\n\r]*\\)")
4258 org-angle-link-re
4259 (concat
4260 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4261 "\\([^" org-non-link-chars " ]"
4262 "[^" org-non-link-chars "]*"
4263 "\\)>")
4264 org-plain-link-re
4265 (concat
4266 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4267 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4268 org-bracket-link-regexp
4269 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4270 org-bracket-link-analytic-regexp
4271 (concat
4272 "\\[\\["
4273 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4274 "\\([^]]+\\)"
4275 "\\]"
4276 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4277 "\\]")
4278 org-bracket-link-analytic-regexp++
4279 (concat
4280 "\\[\\["
4281 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4282 "\\([^]]+\\)"
4283 "\\]"
4284 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4285 "\\]")
4286 org-any-link-re
4287 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4288 org-angle-link-re "\\)\\|\\("
4289 org-plain-link-re "\\)")))
4291 (org-make-link-regexps)
4293 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4294 "Regular expression for fast time stamp matching.")
4295 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4296 "Regular expression for fast time stamp matching.")
4297 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4298 "Regular expression matching time strings for analysis.
4299 This one does not require the space after the date, so it can be used
4300 on a string that terminates immediately after the date.")
4301 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4302 "Regular expression matching time strings for analysis.")
4303 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4304 "Regular expression matching time stamps, with groups.")
4305 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4306 "Regular expression matching time stamps (also [..]), with groups.")
4307 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4308 "Regular expression matching a time stamp range.")
4309 (defconst org-tr-regexp-both
4310 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4311 "Regular expression matching a time stamp range.")
4312 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4313 org-ts-regexp "\\)?")
4314 "Regular expression matching a time stamp or time stamp range.")
4315 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4316 org-ts-regexp-both "\\)?")
4317 "Regular expression matching a time stamp or time stamp range.
4318 The time stamps may be either active or inactive.")
4320 (defvar org-emph-face nil)
4322 (defun org-do-emphasis-faces (limit)
4323 "Run through the buffer and add overlays to links."
4324 (let (rtn a)
4325 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4326 (if (not (= (char-after (match-beginning 3))
4327 (char-after (match-beginning 4))))
4328 (progn
4329 (setq rtn t)
4330 (setq a (assoc (match-string 3) org-emphasis-alist))
4331 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4332 'face
4333 (nth 1 a))
4334 (and (nth 4 a)
4335 (org-remove-flyspell-overlays-in
4336 (match-beginning 0) (match-end 0)))
4337 (add-text-properties (match-beginning 2) (match-end 2)
4338 '(font-lock-multiline t))
4339 (when org-hide-emphasis-markers
4340 (add-text-properties (match-end 4) (match-beginning 5)
4341 '(invisible org-link))
4342 (add-text-properties (match-beginning 3) (match-end 3)
4343 '(invisible org-link)))))
4344 (backward-char 1))
4345 rtn))
4347 (defun org-emphasize (&optional char)
4348 "Insert or change an emphasis, i.e. a font like bold or italic.
4349 If there is an active region, change that region to a new emphasis.
4350 If there is no region, just insert the marker characters and position
4351 the cursor between them.
4352 CHAR should be either the marker character, or the first character of the
4353 HTML tag associated with that emphasis. If CHAR is a space, the means
4354 to remove the emphasis of the selected region.
4355 If char is not given (for example in an interactive call) it
4356 will be prompted for."
4357 (interactive)
4358 (let ((eal org-emphasis-alist) e det
4359 (erc org-emphasis-regexp-components)
4360 (prompt "")
4361 (string "") beg end move tag c s)
4362 (if (org-region-active-p)
4363 (setq beg (region-beginning) end (region-end)
4364 string (buffer-substring beg end))
4365 (setq move t))
4367 (while (setq e (pop eal))
4368 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4369 c (aref tag 0))
4370 (push (cons c (string-to-char (car e))) det)
4371 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4372 (substring tag 1)))))
4373 (setq det (nreverse det))
4374 (unless char
4375 (message "%s" (concat "Emphasis marker or tag:" prompt))
4376 (setq char (read-char-exclusive)))
4377 (setq char (or (cdr (assoc char det)) char))
4378 (if (equal char ?\ )
4379 (setq s "" move nil)
4380 (unless (assoc (char-to-string char) org-emphasis-alist)
4381 (error "No such emphasis marker: \"%c\"" char))
4382 (setq s (char-to-string char)))
4383 (while (and (> (length string) 1)
4384 (equal (substring string 0 1) (substring string -1))
4385 (assoc (substring string 0 1) org-emphasis-alist))
4386 (setq string (substring string 1 -1)))
4387 (setq string (concat s string s))
4388 (if beg (delete-region beg end))
4389 (unless (or (bolp)
4390 (string-match (concat "[" (nth 0 erc) "\n]")
4391 (char-to-string (char-before (point)))))
4392 (insert " "))
4393 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4394 (char-to-string (char-after (point))))
4395 (insert " ") (backward-char 1))
4396 (insert string)
4397 (and move (backward-char 1))))
4399 (defconst org-nonsticky-props
4400 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4402 (defsubst org-rear-nonsticky-at (pos)
4403 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4405 (defun org-activate-plain-links (limit)
4406 "Run through the buffer and add overlays to links."
4407 (catch 'exit
4408 (let (f)
4409 (if (re-search-forward org-plain-link-re limit t)
4410 (progn
4411 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4412 (setq f (get-text-property (match-beginning 0) 'face))
4413 (if (or (eq f 'org-tag)
4414 (and (listp f) (memq 'org-tag f)))
4416 (add-text-properties (match-beginning 0) (match-end 0)
4417 (list 'mouse-face 'highlight
4418 'keymap org-mouse-map))
4419 (org-rear-nonsticky-at (match-end 0)))
4420 t)))))
4422 (defun org-activate-code (limit)
4423 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4424 (progn
4425 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4426 (remove-text-properties (match-beginning 0) (match-end 0)
4427 '(display t invisible t intangible t))
4428 t)))
4430 (defun org-fontify-meta-lines-and-blocks (limit)
4431 "Fontify #+ lines and blocks, in the correct ways."
4432 (let ((case-fold-search t))
4433 (if (re-search-forward
4434 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4435 limit t)
4436 (let ((beg (match-beginning 0))
4437 (beg1 (line-beginning-position 2))
4438 (dc1 (downcase (match-string 2)))
4439 (dc3 (downcase (match-string 3)))
4440 end end1 quoting)
4441 (cond
4442 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4443 ;; a single line of backend-specific content
4444 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4445 (remove-text-properties (match-beginning 0) (match-end 0)
4446 '(display t invisible t intangible t))
4447 (add-text-properties (match-beginning 1) (match-end 3)
4448 '(font-lock-fontified t face org-meta-line))
4449 (add-text-properties (match-beginning 6) (match-end 6)
4450 '(font-lock-fontified t face org-block))
4452 ((and (match-end 4) (equal dc3 "begin"))
4453 ;; Truely a block
4454 (setq quoting (member (downcase (match-string 5))
4455 org-protecting-blocks))
4456 (when (re-search-forward
4457 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4458 nil t) ;; on purpose, we look further than LIMIT
4459 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4460 (when quoting
4461 (remove-text-properties beg end
4462 '(display t invisible t intangible t)))
4463 (add-text-properties
4464 beg end
4465 '(font-lock-fontified t font-lock-multiline t))
4466 (add-text-properties beg beg1 '(face org-meta-line))
4467 (add-text-properties end1 end '(face org-meta-line))
4468 (when quoting
4469 (add-text-properties beg1 end1 '(face org-block)))
4471 ((not (member (char-after beg) '(?\ ?\t)))
4472 ;; just any other in-buffer setting, but not indented
4473 (add-text-properties
4474 beg (match-end 0)
4475 '(font-lock-fontified t face org-meta-line))
4477 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4478 "orgtbl:" "tblfm:" "tblname:"))
4479 (and (match-end 4) (equal dc3 "attr")))
4480 (add-text-properties
4481 beg (match-end 0)
4482 '(font-lock-fontified t face org-meta-line))
4484 ((member dc3 '(" " ""))
4485 (add-text-properties
4486 beg (match-end 0)
4487 '(font-lock-fontified t face font-lock-comment-face)))
4488 (t nil))))))
4490 (defun org-activate-angle-links (limit)
4491 "Run through the buffer and add overlays to links."
4492 (if (re-search-forward org-angle-link-re limit t)
4493 (progn
4494 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4495 (add-text-properties (match-beginning 0) (match-end 0)
4496 (list 'mouse-face 'highlight
4497 'keymap org-mouse-map))
4498 (org-rear-nonsticky-at (match-end 0))
4499 t)))
4501 (defun org-activate-footnote-links (limit)
4502 "Run through the buffer and add overlays to links."
4503 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4504 limit t)
4505 (progn
4506 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4507 (add-text-properties (match-beginning 2) (match-end 2)
4508 (list 'mouse-face 'highlight
4509 'keymap org-mouse-map
4510 'help-echo
4511 (if (= (point-at-bol) (match-beginning 2))
4512 "Footnote definition"
4513 "Footnote reference")
4515 (org-rear-nonsticky-at (match-end 2))
4516 t)))
4518 (defun org-activate-bracket-links (limit)
4519 "Run through the buffer and add overlays to bracketed links."
4520 (if (re-search-forward org-bracket-link-regexp limit t)
4521 (let* ((help (concat "LINK: "
4522 (org-match-string-no-properties 1)))
4523 ;; FIXME: above we should remove the escapes.
4524 ;; but that requires another match, protecting match data,
4525 ;; a lot of overhead for font-lock.
4526 (ip (org-maybe-intangible
4527 (list 'invisible 'org-link
4528 'keymap org-mouse-map 'mouse-face 'highlight
4529 'font-lock-multiline t 'help-echo help)))
4530 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4531 'font-lock-multiline t 'help-echo help)))
4532 ;; We need to remove the invisible property here. Table narrowing
4533 ;; may have made some of this invisible.
4534 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4535 (remove-text-properties (match-beginning 0) (match-end 0)
4536 '(invisible nil))
4537 (if (match-end 3)
4538 (progn
4539 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4540 (org-rear-nonsticky-at (match-beginning 3))
4541 (add-text-properties (match-beginning 3) (match-end 3) vp)
4542 (org-rear-nonsticky-at (match-end 3))
4543 (add-text-properties (match-end 3) (match-end 0) ip)
4544 (org-rear-nonsticky-at (match-end 0)))
4545 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4546 (org-rear-nonsticky-at (match-beginning 1))
4547 (add-text-properties (match-beginning 1) (match-end 1) vp)
4548 (org-rear-nonsticky-at (match-end 1))
4549 (add-text-properties (match-end 1) (match-end 0) ip)
4550 (org-rear-nonsticky-at (match-end 0)))
4551 t)))
4553 (defun org-activate-dates (limit)
4554 "Run through the buffer and add overlays to dates."
4555 (if (re-search-forward org-tsr-regexp-both limit t)
4556 (progn
4557 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4558 (add-text-properties (match-beginning 0) (match-end 0)
4559 (list 'mouse-face 'highlight
4560 'keymap org-mouse-map))
4561 (org-rear-nonsticky-at (match-end 0))
4562 (when org-display-custom-times
4563 (if (match-end 3)
4564 (org-display-custom-time (match-beginning 3) (match-end 3)))
4565 (org-display-custom-time (match-beginning 1) (match-end 1)))
4566 t)))
4568 (defvar org-target-link-regexp nil
4569 "Regular expression matching radio targets in plain text.")
4570 (make-variable-buffer-local 'org-target-link-regexp)
4571 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4572 "Regular expression matching a link target.")
4573 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4574 "Regular expression matching a radio target.")
4575 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4576 "Regular expression matching any target.")
4578 (defun org-activate-target-links (limit)
4579 "Run through the buffer and add overlays to target matches."
4580 (when org-target-link-regexp
4581 (let ((case-fold-search t))
4582 (if (re-search-forward org-target-link-regexp 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 'help-echo "Radio target link"
4589 'org-linked-text t))
4590 (org-rear-nonsticky-at (match-end 0))
4591 t)))))
4593 (defun org-update-radio-target-regexp ()
4594 "Find all radio targets in this file and update the regular expression."
4595 (interactive)
4596 (when (memq 'radio org-activate-links)
4597 (setq org-target-link-regexp
4598 (org-make-target-link-regexp (org-all-targets 'radio)))
4599 (org-restart-font-lock)))
4601 (defun org-hide-wide-columns (limit)
4602 (let (s e)
4603 (setq s (text-property-any (point) (or limit (point-max))
4604 'org-cwidth t))
4605 (when s
4606 (setq e (next-single-property-change s 'org-cwidth))
4607 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4608 (goto-char e)
4609 t)))
4611 (defvar org-latex-and-specials-regexp nil
4612 "Regular expression for highlighting export special stuff.")
4613 (defvar org-match-substring-regexp)
4614 (defvar org-match-substring-with-braces-regexp)
4616 ;; This should be with the exporter code, but we also use if for font-locking
4617 (defconst org-export-html-special-string-regexps
4618 '(("\\\\-" . "&shy;")
4619 ("---\\([^-]\\)" . "&mdash;\\1")
4620 ("--\\([^-]\\)" . "&ndash;\\1")
4621 ("\\.\\.\\." . "&hellip;"))
4622 "Regular expressions for special string conversion.")
4625 (defun org-compute-latex-and-specials-regexp ()
4626 "Compute regular expression for stuff treated specially by exporters."
4627 (if (not org-highlight-latex-fragments-and-specials)
4628 (org-set-local 'org-latex-and-specials-regexp nil)
4629 (require 'org-exp)
4630 (let*
4631 ((matchers (plist-get org-format-latex-options :matchers))
4632 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4633 org-latex-regexps)))
4634 (options (org-combine-plists (org-default-export-plist)
4635 (org-infile-export-plist)))
4636 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4637 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4638 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4639 (org-export-html-expand (plist-get options :expand-quoted-html))
4640 (org-export-with-special-strings (plist-get options :special-strings))
4641 (re-sub
4642 (cond
4643 ((equal org-export-with-sub-superscripts '{})
4644 (list org-match-substring-with-braces-regexp))
4645 (org-export-with-sub-superscripts
4646 (list org-match-substring-regexp))
4647 (t nil)))
4648 (re-latex
4649 (if org-export-with-LaTeX-fragments
4650 (mapcar (lambda (x) (nth 1 x)) latexs)))
4651 (re-macros
4652 (if org-export-with-TeX-macros
4653 (list (concat "\\\\"
4654 (regexp-opt
4655 (append (mapcar 'car org-html-entities)
4656 (if (boundp 'org-latex-entities)
4657 (mapcar (lambda (x)
4658 (or (car-safe x) x))
4659 org-latex-entities)
4660 nil))
4661 'words))) ; FIXME
4663 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4664 (re-special (if org-export-with-special-strings
4665 (mapcar (lambda (x) (car x))
4666 org-export-html-special-string-regexps)))
4667 (re-rest
4668 (delq nil
4669 (list
4670 (if org-export-html-expand "@<[^>\n]+>")
4671 ))))
4672 (org-set-local
4673 'org-latex-and-specials-regexp
4674 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4675 re-rest) "\\|")))))
4677 (defun org-do-latex-and-special-faces (limit)
4678 "Run through the buffer and add overlays to links."
4679 (when org-latex-and-specials-regexp
4680 (let (rtn d)
4681 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4682 limit t))
4683 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4684 'face))
4685 '(org-code org-verbatim underline)))
4686 (progn
4687 (setq rtn t
4688 d (cond ((member (char-after (1+ (match-beginning 0)))
4689 '(?_ ?^)) 1)
4690 (t 0)))
4691 (font-lock-prepend-text-property
4692 (+ d (match-beginning 0)) (match-end 0)
4693 'face 'org-latex-and-export-specials)
4694 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4695 '(font-lock-multiline t)))))
4696 rtn)))
4698 (defun org-restart-font-lock ()
4699 "Restart font-lock-mode, to force refontification."
4700 (when (and (boundp 'font-lock-mode) font-lock-mode)
4701 (font-lock-mode -1)
4702 (font-lock-mode 1)))
4704 (defun org-all-targets (&optional radio)
4705 "Return a list of all targets in this file.
4706 With optional argument RADIO, only find radio targets."
4707 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4708 rtn)
4709 (save-excursion
4710 (goto-char (point-min))
4711 (while (re-search-forward re nil t)
4712 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4713 rtn)))
4715 (defun org-make-target-link-regexp (targets)
4716 "Make regular expression matching all strings in TARGETS.
4717 The regular expression finds the targets also if there is a line break
4718 between words."
4719 (and targets
4720 (concat
4721 "\\<\\("
4722 (mapconcat
4723 (lambda (x)
4724 (while (string-match " +" x)
4725 (setq x (replace-match "\\s-+" t t x)))
4727 targets
4728 "\\|")
4729 "\\)\\>")))
4731 (defun org-activate-tags (limit)
4732 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4733 (progn
4734 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4735 (add-text-properties (match-beginning 1) (match-end 1)
4736 (list 'mouse-face 'highlight
4737 'keymap org-mouse-map))
4738 (org-rear-nonsticky-at (match-end 1))
4739 t)))
4741 (defun org-outline-level ()
4742 "Compute the outline level of the heading at point.
4743 This function assumes that the cursor is at the beginning of a line matched
4744 by outline-regexp. Otherwise it returns garbage.
4745 If this is called at a normal headline, the level is the number of stars.
4746 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4747 For plain list items, if they are matched by `outline-regexp', this returns
4748 1000 plus the line indentation."
4749 (save-excursion
4750 (looking-at outline-regexp)
4751 (if (match-beginning 1)
4752 (+ (org-get-string-indentation (match-string 1)) 1000)
4753 (1- (- (match-end 0) (match-beginning 0))))))
4755 (defvar org-font-lock-keywords nil)
4757 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4758 "Regular expression matching a property line.")
4760 (defvar org-font-lock-hook nil
4761 "Functions to be called for special font lock stuff.")
4763 (defun org-font-lock-hook (limit)
4764 (run-hook-with-args 'org-font-lock-hook limit))
4766 (defun org-set-font-lock-defaults ()
4767 (let* ((em org-fontify-emphasized-text)
4768 (lk org-activate-links)
4769 (org-font-lock-extra-keywords
4770 (list
4771 ;; Call the hook
4772 '(org-font-lock-hook)
4773 ;; Headlines
4774 `(,(if org-fontify-whole-heading-line
4775 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4776 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4777 (1 (org-get-level-face 1))
4778 (2 (org-get-level-face 2))
4779 (3 (org-get-level-face 3)))
4780 ;; Table lines
4781 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4782 (1 'org-table t))
4783 ;; Table internals
4784 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4785 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4786 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4787 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4788 ;; Drawers
4789 (list org-drawer-regexp '(0 'org-special-keyword t))
4790 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4791 ;; Properties
4792 (list org-property-re
4793 '(1 'org-special-keyword t)
4794 '(3 'org-property-value t))
4795 ;; Links
4796 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4797 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4798 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4799 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4800 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4801 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4802 (if (memq 'footnote lk) '(org-activate-footnote-links
4803 (2 'org-footnote t)))
4804 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4805 '(org-hide-wide-columns (0 nil append))
4806 ;; TODO lines
4807 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4808 '(1 (org-get-todo-face 1) t))
4809 ;; DONE
4810 (if org-fontify-done-headline
4811 (list (concat "^[*]+ +\\<\\("
4812 (mapconcat 'regexp-quote org-done-keywords "\\|")
4813 "\\)\\(.*\\)")
4814 '(2 'org-headline-done t))
4815 nil)
4816 ;; Priorities
4817 '(org-font-lock-add-priority-faces)
4818 ;; Tags
4819 '(org-font-lock-add-tag-faces)
4820 ;; Special keywords
4821 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4822 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4823 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4824 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4825 ;; Emphasis
4826 (if em
4827 (if (featurep 'xemacs)
4828 '(org-do-emphasis-faces (0 nil append))
4829 '(org-do-emphasis-faces)))
4830 ;; Checkboxes
4831 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4832 2 'org-checkbox prepend)
4833 (if org-provide-checkbox-statistics
4834 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4835 (0 (org-get-checkbox-statistics-face) t)))
4836 ;; Description list items
4837 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4838 2 'bold prepend)
4839 ;; ARCHIVEd headings
4840 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4841 '(1 'org-archived prepend))
4842 ;; Specials
4843 '(org-do-latex-and-special-faces)
4844 ;; Code
4845 '(org-activate-code (1 'org-code t))
4846 ;; COMMENT
4847 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4848 "\\|" org-quote-string "\\)\\>")
4849 '(1 'org-special-keyword t))
4850 '("^#.*" (0 'font-lock-comment-face t))
4851 ;; Blocks and meta lines
4852 '(org-fontify-meta-lines-and-blocks)
4854 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4855 ;; Now set the full font-lock-keywords
4856 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4857 (org-set-local 'font-lock-defaults
4858 '(org-font-lock-keywords t nil nil backward-paragraph))
4859 (kill-local-variable 'font-lock-keywords) nil))
4861 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4862 "Fontify string S like in Org-mode"
4863 (with-temp-buffer
4864 (insert s)
4865 (let ((org-odd-levels-only odd-levels))
4866 (org-mode)
4867 (font-lock-fontify-buffer)
4868 (buffer-string))))
4870 (defvar org-m nil)
4871 (defvar org-l nil)
4872 (defvar org-f nil)
4873 (defun org-get-level-face (n)
4874 "Get the right face for match N in font-lock matching of headlines."
4875 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4876 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4877 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4878 (cond
4879 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4880 ((eq n 2) org-f)
4881 (t (if org-level-color-stars-only nil org-f))))
4883 (defun org-get-todo-face (kwd)
4884 "Get the right face for a TODO keyword KWD.
4885 If KWD is a number, get the corresponding match group."
4886 (if (numberp kwd) (setq kwd (match-string kwd)))
4887 (or (cdr (assoc kwd org-todo-keyword-faces))
4888 (and (member kwd org-done-keywords) 'org-done)
4889 'org-todo))
4891 (defun org-font-lock-add-tag-faces (limit)
4892 "Add the special tag faces."
4893 (when (and org-tag-faces org-tags-special-faces-re)
4894 (while (re-search-forward org-tags-special-faces-re limit t)
4895 (add-text-properties (match-beginning 1) (match-end 1)
4896 (list 'face (org-get-tag-face 1)
4897 'font-lock-fontified t))
4898 (backward-char 1))))
4900 (defun org-font-lock-add-priority-faces (limit)
4901 "Add the special priority faces."
4902 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4903 (add-text-properties
4904 (match-beginning 0) (match-end 0)
4905 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4906 org-priority-faces))
4907 'org-special-keyword)
4908 'font-lock-fontified t))))
4910 (defun org-get-tag-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-tag-faces))
4915 'org-tag))
4917 (defun org-unfontify-region (beg end &optional maybe_loudly)
4918 "Remove fontification and activation overlays from links."
4919 (font-lock-default-unfontify-region beg end)
4920 (let* ((buffer-undo-list t)
4921 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4922 (inhibit-modification-hooks t)
4923 deactivate-mark buffer-file-name buffer-file-truename)
4924 (remove-text-properties
4925 beg end
4926 (if org-indent-mode
4927 ;; also remove line-prefix and wrap-prefix properties
4928 '(mouse-face t keymap t org-linked-text t
4929 invisible t intangible t
4930 line-prefix t wrap-prefix t
4931 org-no-flyspell t)
4932 '(mouse-face t keymap t org-linked-text t
4933 invisible t intangible t
4934 org-no-flyspell t)))))
4936 ;;;; Visibility cycling, including org-goto and indirect buffer
4938 ;;; Cycling
4940 (defvar org-cycle-global-status nil)
4941 (make-variable-buffer-local 'org-cycle-global-status)
4942 (defvar org-cycle-subtree-status nil)
4943 (make-variable-buffer-local 'org-cycle-subtree-status)
4945 ;;;###autoload
4947 (defvar org-inlinetask-min-level)
4949 (defun org-cycle (&optional arg)
4950 "TAB-action and visibility cycling for Org-mode.
4952 This is the command invoked in Org-mode by the TAB key. Its main purpose
4953 is outine visibility cycling, but it also invokes other actions
4954 in special contexts.
4956 - When this function is called with a prefix argument, rotate the entire
4957 buffer through 3 states (global cycling)
4958 1. OVERVIEW: Show only top-level headlines.
4959 2. CONTENTS: Show all headlines of all levels, but no body text.
4960 3. SHOW ALL: Show everything.
4961 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4962 determined by the variable `org-startup-folded', and by any VISIBILITY
4963 properties in the buffer.
4964 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4965 including any drawers.
4967 - When inside a table, re-align the table and move to the next field.
4969 - When point is at the beginning of a headline, rotate the subtree started
4970 by this line through 3 different states (local cycling)
4971 1. FOLDED: Only the main headline is shown.
4972 2. CHILDREN: The main headline and the direct children are shown.
4973 From this state, you can move to one of the children
4974 and zoom in further.
4975 3. SUBTREE: Show the entire subtree, including body text.
4976 If there is no subtree, switch directly from CHILDREN to FOLDED.
4978 - When there is a numeric prefix, go up to a heading with level ARG, do
4979 a `show-subtree' and return to the previous cursor position. If ARG
4980 is negative, go up that many levels.
4982 - When point is not at the beginning of a headline, execute the global
4983 binding for TAB, which is re-indenting the line. See the option
4984 `org-cycle-emulate-tab' for details.
4986 - Special case: if point is at the beginning of the buffer and there is
4987 no headline in line 1, this function will act as if called with prefix arg.
4988 But only if also the variable `org-cycle-global-at-bob' is t."
4989 (interactive "P")
4990 (org-load-modules-maybe)
4991 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
4992 (and org-cycle-level-after-item/entry-creation
4993 (or (org-cycle-level)
4994 (org-cycle-item-indentation))))
4995 (let* ((limit-level
4996 (or org-cycle-max-level
4997 (and (boundp 'org-inlinetask-min-level)
4998 org-inlinetask-min-level
4999 (1- org-inlinetask-min-level))))
5000 (nstars (and limit-level
5001 (if org-odd-levels-only
5002 (and limit-level (1- (* limit-level 2)))
5003 limit-level)))
5004 (outline-regexp
5005 (cond
5006 ((not (org-mode-p)) outline-regexp)
5007 ((or (eq org-cycle-include-plain-lists 'integrate)
5008 (and org-cycle-include-plain-lists (org-at-item-p)))
5009 (concat "\\(?:\\*"
5010 (if nstars (format "\\{1,%d\\}" nstars) "+")
5011 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5012 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5013 (bob-special (and org-cycle-global-at-bob (bobp)
5014 (not (looking-at outline-regexp))))
5015 (org-cycle-hook
5016 (if bob-special
5017 (delq 'org-optimize-window-after-visibility-change
5018 (copy-sequence org-cycle-hook))
5019 org-cycle-hook))
5020 (pos (point)))
5022 (if (or bob-special (equal arg '(4)))
5023 ;; special case: use global cycling
5024 (setq arg t))
5026 (cond
5028 ((equal arg '(16))
5029 (org-set-startup-visibility)
5030 (message "Startup visibility, plus VISIBILITY properties"))
5032 ((equal arg '(64))
5033 (show-all)
5034 (message "Entire buffer visible, including drawers"))
5036 ((org-at-table-p 'any)
5037 ;; Enter the table or move to the next field in the table
5038 (or (org-table-recognize-table.el)
5039 (progn
5040 (if arg (org-table-edit-field t)
5041 (org-table-justify-field-maybe)
5042 (call-interactively 'org-table-next-field)))))
5044 ((run-hook-with-args-until-success
5045 'org-tab-after-check-for-table-hook))
5047 ((eq arg t) ;; Global cycling
5048 (org-cycle-internal-global))
5050 ((and org-drawers org-drawer-regexp
5051 (save-excursion
5052 (beginning-of-line 1)
5053 (looking-at org-drawer-regexp)))
5054 ;; Toggle block visibility
5055 (org-flag-drawer
5056 (not (get-char-property (match-end 0) 'invisible))))
5058 ((integerp arg)
5059 ;; Show-subtree, ARG levels up from here.
5060 (save-excursion
5061 (org-back-to-heading)
5062 (outline-up-heading (if (< arg 0) (- arg)
5063 (- (funcall outline-level) arg)))
5064 (org-show-subtree)))
5066 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5067 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5069 (org-cycle-internal-local))
5071 ;; TAB emulation and template completion
5072 (buffer-read-only (org-back-to-heading))
5074 ((run-hook-with-args-until-success
5075 'org-tab-after-check-for-cycling-hook))
5077 ((org-try-structure-completion))
5079 ((org-try-cdlatex-tab))
5081 ((run-hook-with-args-until-success
5082 'org-tab-before-tab-emulation-hook))
5084 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5085 (or (not (bolp))
5086 (not (looking-at outline-regexp))))
5087 (call-interactively (global-key-binding "\t")))
5089 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5090 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5091 (or (and (eq org-cycle-emulate-tab 'white)
5092 (= (match-end 0) (point-at-eol)))
5093 (and (eq org-cycle-emulate-tab 'whitestart)
5094 (>= (match-end 0) pos))))
5096 (eq org-cycle-emulate-tab t))
5097 (call-interactively (global-key-binding "\t")))
5099 (t (save-excursion
5100 (org-back-to-heading)
5101 (org-cycle)))))))
5103 (defun org-cycle-internal-global ()
5104 "Do the global cycling action."
5105 (cond
5106 ((and (eq last-command this-command)
5107 (eq org-cycle-global-status 'overview))
5108 ;; We just created the overview - now do table of contents
5109 ;; This can be slow in very large buffers, so indicate action
5110 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5111 (message "CONTENTS...")
5112 (org-content)
5113 (message "CONTENTS...done")
5114 (setq org-cycle-global-status 'contents)
5115 (run-hook-with-args 'org-cycle-hook 'contents))
5117 ((and (eq last-command this-command)
5118 (eq org-cycle-global-status 'contents))
5119 ;; We just showed the table of contents - now show everything
5120 (run-hook-with-args 'org-pre-cycle-hook 'all)
5121 (show-all)
5122 (message "SHOW ALL")
5123 (setq org-cycle-global-status 'all)
5124 (run-hook-with-args 'org-cycle-hook 'all))
5127 ;; Default action: go to overview
5128 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5129 (org-overview)
5130 (message "OVERVIEW")
5131 (setq org-cycle-global-status 'overview)
5132 (run-hook-with-args 'org-cycle-hook 'overview))))
5134 (defun org-cycle-internal-local ()
5135 "Do the local cycling action."
5136 (org-back-to-heading)
5137 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5138 ;; First, some boundaries
5139 (save-excursion
5140 (org-back-to-heading)
5141 (setq level (funcall outline-level))
5142 (save-excursion
5143 (beginning-of-line 2)
5144 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5145 ; XEmacs does not have `next-single-char-property-change'
5146 ; I'm not sure about Emacs 21.
5147 (while (and (not (eobp)) ;; this is like `next-line'
5148 (get-char-property (1- (point)) 'invisible))
5149 (beginning-of-line 2))
5150 (while (and (not (eobp)) ;; this is like `next-line'
5151 (get-char-property (1- (point)) 'invisible))
5152 (goto-char (next-single-char-property-change (point) 'invisible))
5153 ;;;??? (or (bolp) (beginning-of-line 2))))
5154 (and (eolp) (beginning-of-line 2))))
5155 (setq eol (point)))
5156 (outline-end-of-heading) (setq eoh (point))
5157 (save-excursion
5158 (outline-next-heading)
5159 (setq has-children (and (org-at-heading-p t)
5160 (> (funcall outline-level) level))))
5161 (org-end-of-subtree t)
5162 (unless (eobp)
5163 (skip-chars-forward " \t\n")
5164 (beginning-of-line 1) ; in case this is an item
5166 (setq eos (if (eobp) (point) (1- (point)))))
5167 ;; Find out what to do next and set `this-command'
5168 (cond
5169 ((= eos eoh)
5170 ;; Nothing is hidden behind this heading
5171 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5172 (message "EMPTY ENTRY")
5173 (setq org-cycle-subtree-status nil)
5174 (save-excursion
5175 (goto-char eos)
5176 (outline-next-heading)
5177 (if (org-invisible-p) (org-flag-heading nil))))
5178 ((and (or (>= eol eos)
5179 (not (string-match "\\S-" (buffer-substring eol eos))))
5180 (or has-children
5181 (not (setq children-skipped
5182 org-cycle-skip-children-state-if-no-children))))
5183 ;; Entire subtree is hidden in one line: children view
5184 (run-hook-with-args 'org-pre-cycle-hook 'children)
5185 (org-show-entry)
5186 (show-children)
5187 (message "CHILDREN")
5188 (save-excursion
5189 (goto-char eos)
5190 (outline-next-heading)
5191 (if (org-invisible-p) (org-flag-heading nil)))
5192 (setq org-cycle-subtree-status 'children)
5193 (run-hook-with-args 'org-cycle-hook 'children))
5194 ((or children-skipped
5195 (and (eq last-command this-command)
5196 (eq org-cycle-subtree-status 'children)))
5197 ;; We just showed the children, or no children are there,
5198 ;; now show everything.
5199 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5200 (org-show-subtree)
5201 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5202 (setq org-cycle-subtree-status 'subtree)
5203 (run-hook-with-args 'org-cycle-hook 'subtree))
5205 ;; Default action: hide the subtree.
5206 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5207 (hide-subtree)
5208 (message "FOLDED")
5209 (setq org-cycle-subtree-status 'folded)
5210 (run-hook-with-args 'org-cycle-hook 'folded)))))
5212 ;;;###autoload
5213 (defun org-global-cycle (&optional arg)
5214 "Cycle the global visibility. For details see `org-cycle'.
5215 With C-u prefix arg, switch to startup visibility.
5216 With a numeric prefix, show all headlines up to that level."
5217 (interactive "P")
5218 (let ((org-cycle-include-plain-lists
5219 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5220 (cond
5221 ((integerp arg)
5222 (show-all)
5223 (hide-sublevels arg)
5224 (setq org-cycle-global-status 'contents))
5225 ((equal arg '(4))
5226 (org-set-startup-visibility)
5227 (message "Startup visibility, plus VISIBILITY properties."))
5229 (org-cycle '(4))))))
5231 (defun org-set-startup-visibility ()
5232 "Set the visibility required by startup options and properties."
5233 (cond
5234 ((eq org-startup-folded t)
5235 (org-cycle '(4)))
5236 ((eq org-startup-folded 'content)
5237 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5238 (org-cycle '(4)) (org-cycle '(4)))))
5239 (unless (eq org-startup-folded 'showeverything)
5240 (if org-hide-block-startup (org-hide-block-all))
5241 (org-set-visibility-according-to-property 'no-cleanup)
5242 (org-cycle-hide-archived-subtrees 'all)
5243 (org-cycle-hide-drawers 'all)
5244 (org-cycle-show-empty-lines 'all)))
5246 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5247 "Switch subtree visibilities according to :VISIBILITY: property."
5248 (interactive)
5249 (let (org-show-entry-below state)
5250 (save-excursion
5251 (goto-char (point-min))
5252 (while (re-search-forward
5253 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5254 nil t)
5255 (setq state (match-string 1))
5256 (save-excursion
5257 (org-back-to-heading t)
5258 (hide-subtree)
5259 (org-reveal)
5260 (cond
5261 ((equal state '("fold" "folded"))
5262 (hide-subtree))
5263 ((equal state "children")
5264 (org-show-hidden-entry)
5265 (show-children))
5266 ((equal state "content")
5267 (save-excursion
5268 (save-restriction
5269 (org-narrow-to-subtree)
5270 (org-content))))
5271 ((member state '("all" "showall"))
5272 (show-subtree)))))
5273 (unless no-cleanup
5274 (org-cycle-hide-archived-subtrees 'all)
5275 (org-cycle-hide-drawers 'all)
5276 (org-cycle-show-empty-lines 'all)))))
5278 (defun org-overview ()
5279 "Switch to overview mode, showing only top-level headlines.
5280 Really, this shows all headlines with level equal or greater than the level
5281 of the first headline in the buffer. This is important, because if the
5282 first headline is not level one, then (hide-sublevels 1) gives confusing
5283 results."
5284 (interactive)
5285 (let ((level (save-excursion
5286 (goto-char (point-min))
5287 (if (re-search-forward (concat "^" outline-regexp) nil t)
5288 (progn
5289 (goto-char (match-beginning 0))
5290 (funcall outline-level))))))
5291 (and level (hide-sublevels level))))
5293 (defun org-content (&optional arg)
5294 "Show all headlines in the buffer, like a table of contents.
5295 With numerical argument N, show content up to level N."
5296 (interactive "P")
5297 (save-excursion
5298 ;; Visit all headings and show their offspring
5299 (and (integerp arg) (org-overview))
5300 (goto-char (point-max))
5301 (catch 'exit
5302 (while (and (progn (condition-case nil
5303 (outline-previous-visible-heading 1)
5304 (error (goto-char (point-min))))
5306 (looking-at outline-regexp))
5307 (if (integerp arg)
5308 (show-children (1- arg))
5309 (show-branches))
5310 (if (bobp) (throw 'exit nil))))))
5313 (defun org-optimize-window-after-visibility-change (state)
5314 "Adjust the window after a change in outline visibility.
5315 This function is the default value of the hook `org-cycle-hook'."
5316 (when (get-buffer-window (current-buffer))
5317 (cond
5318 ((eq state 'content) nil)
5319 ((eq state 'all) nil)
5320 ((eq state 'folded) nil)
5321 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5322 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5324 ;; FIXME: no longer in use
5325 (defun org-compact-display-after-subtree-move ()
5326 "Show a compacter version of the tree of the entry's parent."
5327 (save-excursion
5328 (if (org-up-heading-safe)
5329 (progn
5330 (hide-subtree)
5331 (show-entry)
5332 (show-children)
5333 (org-cycle-show-empty-lines 'children)
5334 (org-cycle-hide-drawers 'children))
5335 (org-overview))))
5337 (defun org-remove-empty-overlays-at (pos)
5338 "Remove outline overlays that do not contain non-white stuff."
5339 (mapc
5340 (lambda (o)
5341 (and (eq 'outline (org-overlay-get o 'invisible))
5342 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5343 (org-overlay-end o))))
5344 (org-delete-overlay o)))
5345 (org-overlays-at pos)))
5347 (defun org-clean-visibility-after-subtree-move ()
5348 "Fix visibility issues after moving a subtree."
5349 ;; First, find a reasonable region to look at:
5350 ;; Start two siblings above, end three below
5351 (let* ((beg (save-excursion
5352 (and (org-get-last-sibling)
5353 (org-get-last-sibling))
5354 (point)))
5355 (end (save-excursion
5356 (and (org-get-next-sibling)
5357 (org-get-next-sibling)
5358 (org-get-next-sibling))
5359 (if (org-at-heading-p)
5360 (point-at-eol)
5361 (point))))
5362 (level (looking-at "\\*+"))
5363 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5364 (save-excursion
5365 (save-restriction
5366 (narrow-to-region beg end)
5367 (when re
5368 ;; Properly fold already folded siblings
5369 (goto-char (point-min))
5370 (while (re-search-forward re nil t)
5371 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5372 (hide-entry))))
5373 (org-cycle-show-empty-lines 'overview)
5374 (org-cycle-hide-drawers 'overview)))))
5376 (defun org-cycle-show-empty-lines (state)
5377 "Show empty lines above all visible headlines.
5378 The region to be covered depends on STATE when called through
5379 `org-cycle-hook'. Lisp program can use t for STATE to get the
5380 entire buffer covered. Note that an empty line is only shown if there
5381 are at least `org-cycle-separator-lines' empty lines before the headline."
5382 (when (not (= org-cycle-separator-lines 0))
5383 (save-excursion
5384 (let* ((n (abs org-cycle-separator-lines))
5385 (re (cond
5386 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5387 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5388 (t (let ((ns (number-to-string (- n 2))))
5389 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5390 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5391 beg end b e)
5392 (cond
5393 ((memq state '(overview contents t))
5394 (setq beg (point-min) end (point-max)))
5395 ((memq state '(children folded))
5396 (setq beg (point) end (progn (org-end-of-subtree t t)
5397 (beginning-of-line 2)
5398 (point)))))
5399 (when beg
5400 (goto-char beg)
5401 (while (re-search-forward re end t)
5402 (unless (get-char-property (match-end 1) 'invisible)
5403 (setq e (match-end 1))
5404 (if (< org-cycle-separator-lines 0)
5405 (setq b (save-excursion
5406 (goto-char (match-beginning 0))
5407 (org-back-over-empty-lines)
5408 (if (save-excursion
5409 (goto-char (max (point-min) (1- (point))))
5410 (org-on-heading-p))
5411 (1- (point))
5412 (point))))
5413 (setq b (match-beginning 1)))
5414 (outline-flag-region b e nil)))))))
5415 ;; Never hide empty lines at the end of the file.
5416 (save-excursion
5417 (goto-char (point-max))
5418 (outline-previous-heading)
5419 (outline-end-of-heading)
5420 (if (and (looking-at "[ \t\n]+")
5421 (= (match-end 0) (point-max)))
5422 (outline-flag-region (point) (match-end 0) nil))))
5424 (defun org-show-empty-lines-in-parent ()
5425 "Move to the parent and re-show empty lines before visible headlines."
5426 (save-excursion
5427 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5428 (org-cycle-show-empty-lines context))))
5430 (defun org-files-list ()
5431 "Return `org-agenda-files' list, plus all open org-mode files.
5432 This is useful for operations that need to scan all of a user's
5433 open and agenda-wise Org files."
5434 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5435 (dolist (buf (buffer-list))
5436 (with-current-buffer buf
5437 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5438 (let ((file (expand-file-name (buffer-file-name))))
5439 (unless (member file files)
5440 (push file files))))))
5441 files))
5443 (defsubst org-entry-beginning-position ()
5444 "Return the beginning position of the current entry."
5445 (save-excursion (outline-back-to-heading t) (point)))
5447 (defsubst org-entry-end-position ()
5448 "Return the end position of the current entry."
5449 (save-excursion (outline-next-heading) (point)))
5451 (defun org-cycle-hide-drawers (state)
5452 "Re-hide all drawers after a visibility state change."
5453 (when (and (org-mode-p)
5454 (not (memq state '(overview folded contents))))
5455 (save-excursion
5456 (let* ((globalp (memq state '(contents all)))
5457 (beg (if globalp (point-min) (point)))
5458 (end (if globalp (point-max)
5459 (if (eq state 'children)
5460 (save-excursion (outline-next-heading) (point))
5461 (org-end-of-subtree t)))))
5462 (goto-char beg)
5463 (while (re-search-forward org-drawer-regexp end t)
5464 (org-flag-drawer t))))))
5466 (defun org-flag-drawer (flag)
5467 (save-excursion
5468 (beginning-of-line 1)
5469 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5470 (let ((b (match-end 0))
5471 (outline-regexp org-outline-regexp))
5472 (if (re-search-forward
5473 "^[ \t]*:END:"
5474 (save-excursion (outline-next-heading) (point)) t)
5475 (outline-flag-region b (point-at-eol) flag)
5476 (error ":END: line missing at position %s" b))))))
5478 (defun org-subtree-end-visible-p ()
5479 "Is the end of the current subtree visible?"
5480 (pos-visible-in-window-p
5481 (save-excursion (org-end-of-subtree t) (point))))
5483 (defun org-first-headline-recenter (&optional N)
5484 "Move cursor to the first headline and recenter the headline.
5485 Optional argument N means, put the headline into the Nth line of the window."
5486 (goto-char (point-min))
5487 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5488 (beginning-of-line)
5489 (recenter (prefix-numeric-value N))))
5491 ;;; Folding of blocks
5493 (defconst org-block-regexp
5495 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5496 "Regular expression for hiding blocks.")
5498 (defvar org-hide-block-overlays nil
5499 "Overays hiding blocks.")
5500 (make-variable-buffer-local 'org-hide-block-overlays)
5502 (defun org-block-map (function &optional start end)
5503 "Call func at the head of all source blocks in the current
5504 buffer. Optional arguments START and END can be used to limit
5505 the range."
5506 (let ((start (or start (point-min)))
5507 (end (or end (point-max))))
5508 (save-excursion
5509 (goto-char start)
5510 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5511 (save-excursion
5512 (save-match-data
5513 (goto-char (match-beginning 0))
5514 (funcall function)))))))
5516 (defun org-hide-block-toggle-all ()
5517 "Toggle the visibility of all blocks in the current buffer."
5518 (org-block-map #'org-hide-block-toggle))
5520 (defun org-hide-block-all ()
5521 "Fold all blocks in the current buffer."
5522 (interactive)
5523 (org-show-block-all)
5524 (org-block-map #'org-hide-block-toggle-maybe))
5526 (defun org-show-block-all ()
5527 "Unfold all blocks in the current buffer."
5528 (mapc 'org-delete-overlay org-hide-block-overlays)
5529 (setq org-hide-block-overlays nil))
5531 (defun org-hide-block-toggle-maybe ()
5532 "Toggle visibility of block at point."
5533 (interactive)
5534 (let ((case-fold-search t))
5535 (if (save-excursion
5536 (beginning-of-line 1)
5537 (looking-at org-block-regexp))
5538 (progn (org-hide-block-toggle)
5539 t) ;; to signal that we took action
5540 nil))) ;; to signal that we did not
5542 (defun org-hide-block-toggle (&optional force)
5543 "Toggle the visibility of the current block."
5544 (interactive)
5545 (save-excursion
5546 (beginning-of-line)
5547 (if (re-search-forward org-block-regexp nil t)
5548 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5549 (end (match-end 0)) ;; end of entire body
5551 (if (memq t (mapcar (lambda (overlay)
5552 (eq (org-overlay-get overlay 'invisible)
5553 'org-hide-block))
5554 (org-overlays-at start)))
5555 (if (or (not force) (eq force 'off))
5556 (mapc (lambda (ov)
5557 (when (member ov org-hide-block-overlays)
5558 (setq org-hide-block-overlays
5559 (delq ov org-hide-block-overlays)))
5560 (when (eq (org-overlay-get ov 'invisible)
5561 'org-hide-block)
5562 (org-delete-overlay ov)))
5563 (org-overlays-at start)))
5564 (setq ov (org-make-overlay start end))
5565 (org-overlay-put ov 'invisible 'org-hide-block)
5566 ;; make the block accessible to isearch
5567 (org-overlay-put
5568 ov 'isearch-open-invisible
5569 (lambda (ov)
5570 (when (member ov org-hide-block-overlays)
5571 (setq org-hide-block-overlays
5572 (delq ov org-hide-block-overlays)))
5573 (when (eq (org-overlay-get ov 'invisible)
5574 'org-hide-block)
5575 (org-delete-overlay ov))))
5576 (push ov org-hide-block-overlays)))
5577 (error "Not looking at a source block"))))
5579 ;; org-tab-after-check-for-cycling-hook
5580 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5581 ;; Remove overlays when changing major mode
5582 (add-hook 'org-mode-hook
5583 (lambda () (org-add-hook 'change-major-mode-hook
5584 'org-show-block-all 'append 'local)))
5586 ;;; Org-goto
5588 (defvar org-goto-window-configuration nil)
5589 (defvar org-goto-marker nil)
5590 (defvar org-goto-map
5591 (let ((map (make-sparse-keymap)))
5592 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5593 (while (setq cmd (pop cmds))
5594 (substitute-key-definition cmd cmd map global-map)))
5595 (suppress-keymap map)
5596 (org-defkey map "\C-m" 'org-goto-ret)
5597 (org-defkey map [(return)] 'org-goto-ret)
5598 (org-defkey map [(left)] 'org-goto-left)
5599 (org-defkey map [(right)] 'org-goto-right)
5600 (org-defkey map [(control ?g)] 'org-goto-quit)
5601 (org-defkey map "\C-i" 'org-cycle)
5602 (org-defkey map [(tab)] 'org-cycle)
5603 (org-defkey map [(down)] 'outline-next-visible-heading)
5604 (org-defkey map [(up)] 'outline-previous-visible-heading)
5605 (if org-goto-auto-isearch
5606 (if (fboundp 'define-key-after)
5607 (define-key-after map [t] 'org-goto-local-auto-isearch)
5608 nil)
5609 (org-defkey map "q" 'org-goto-quit)
5610 (org-defkey map "n" 'outline-next-visible-heading)
5611 (org-defkey map "p" 'outline-previous-visible-heading)
5612 (org-defkey map "f" 'outline-forward-same-level)
5613 (org-defkey map "b" 'outline-backward-same-level)
5614 (org-defkey map "u" 'outline-up-heading))
5615 (org-defkey map "/" 'org-occur)
5616 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5617 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5618 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5619 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5620 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5621 map))
5623 (defconst org-goto-help
5624 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5625 RET=jump to location [Q]uit and return to previous location
5626 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5628 (defvar org-goto-start-pos) ; dynamically scoped parameter
5630 ;; FIXME: Docstring doe not mention both interfaces
5631 (defun org-goto (&optional alternative-interface)
5632 "Look up a different location in the current file, keeping current visibility.
5634 When you want look-up or go to a different location in a document, the
5635 fastest way is often to fold the entire buffer and then dive into the tree.
5636 This method has the disadvantage, that the previous location will be folded,
5637 which may not be what you want.
5639 This command works around this by showing a copy of the current buffer
5640 in an indirect buffer, in overview mode. You can dive into the tree in
5641 that copy, use org-occur and incremental search to find a location.
5642 When pressing RET or `Q', the command returns to the original buffer in
5643 which the visibility is still unchanged. After RET is will also jump to
5644 the location selected in the indirect buffer and expose the
5645 the headline hierarchy above."
5646 (interactive "P")
5647 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5648 (org-refile-use-outline-path t)
5649 (org-refile-target-verify-function nil)
5650 (interface
5651 (if (not alternative-interface)
5652 org-goto-interface
5653 (if (eq org-goto-interface 'outline)
5654 'outline-path-completion
5655 'outline)))
5656 (org-goto-start-pos (point))
5657 (selected-point
5658 (if (eq interface 'outline)
5659 (car (org-get-location (current-buffer) org-goto-help))
5660 (nth 3 (org-refile-get-location "Goto: ")))))
5661 (if selected-point
5662 (progn
5663 (org-mark-ring-push org-goto-start-pos)
5664 (goto-char selected-point)
5665 (if (or (org-invisible-p) (org-invisible-p2))
5666 (org-show-context 'org-goto)))
5667 (message "Quit"))))
5669 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5670 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5671 (defvar org-goto-local-auto-isearch-map) ; defined below
5673 (defun org-get-location (buf help)
5674 "Let the user select a location in the Org-mode buffer BUF.
5675 This function uses a recursive edit. It returns the selected position
5676 or nil."
5677 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5678 (isearch-hide-immediately nil)
5679 (isearch-search-fun-function
5680 (lambda () 'org-goto-local-search-headings))
5681 (org-goto-selected-point org-goto-exit-command))
5682 (save-excursion
5683 (save-window-excursion
5684 (delete-other-windows)
5685 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5686 (switch-to-buffer
5687 (condition-case nil
5688 (make-indirect-buffer (current-buffer) "*org-goto*")
5689 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5690 (with-output-to-temp-buffer "*Help*"
5691 (princ help))
5692 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5693 (setq buffer-read-only nil)
5694 (let ((org-startup-truncated t)
5695 (org-startup-folded nil)
5696 (org-startup-align-all-tables nil))
5697 (org-mode)
5698 (org-overview))
5699 (setq buffer-read-only t)
5700 (if (and (boundp 'org-goto-start-pos)
5701 (integer-or-marker-p org-goto-start-pos))
5702 (let ((org-show-hierarchy-above t)
5703 (org-show-siblings t)
5704 (org-show-following-heading t))
5705 (goto-char org-goto-start-pos)
5706 (and (org-invisible-p) (org-show-context)))
5707 (goto-char (point-min)))
5708 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5709 (message "Select location and press RET")
5710 (use-local-map org-goto-map)
5711 (recursive-edit)
5713 (kill-buffer "*org-goto*")
5714 (cons org-goto-selected-point org-goto-exit-command)))
5716 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5717 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5718 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5719 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5721 (defun org-goto-local-search-headings (string bound noerror)
5722 "Search and make sure that any matches are in headlines."
5723 (catch 'return
5724 (while (if isearch-forward
5725 (search-forward string bound noerror)
5726 (search-backward string bound noerror))
5727 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5728 (and (member :headline context)
5729 (not (member :tags context))))
5730 (throw 'return (point))))))
5732 (defun org-goto-local-auto-isearch ()
5733 "Start isearch."
5734 (interactive)
5735 (goto-char (point-min))
5736 (let ((keys (this-command-keys)))
5737 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5738 (isearch-mode t)
5739 (isearch-process-search-char (string-to-char keys)))))
5741 (defun org-goto-ret (&optional arg)
5742 "Finish `org-goto' by going to the new location."
5743 (interactive "P")
5744 (setq org-goto-selected-point (point)
5745 org-goto-exit-command 'return)
5746 (throw 'exit nil))
5748 (defun org-goto-left ()
5749 "Finish `org-goto' by going to the new location."
5750 (interactive)
5751 (if (org-on-heading-p)
5752 (progn
5753 (beginning-of-line 1)
5754 (setq org-goto-selected-point (point)
5755 org-goto-exit-command 'left)
5756 (throw 'exit nil))
5757 (error "Not on a heading")))
5759 (defun org-goto-right ()
5760 "Finish `org-goto' by going to the new location."
5761 (interactive)
5762 (if (org-on-heading-p)
5763 (progn
5764 (setq org-goto-selected-point (point)
5765 org-goto-exit-command 'right)
5766 (throw 'exit nil))
5767 (error "Not on a heading")))
5769 (defun org-goto-quit ()
5770 "Finish `org-goto' without cursor motion."
5771 (interactive)
5772 (setq org-goto-selected-point nil)
5773 (setq org-goto-exit-command 'quit)
5774 (throw 'exit nil))
5776 ;;; Indirect buffer display of subtrees
5778 (defvar org-indirect-dedicated-frame nil
5779 "This is the frame being used for indirect tree display.")
5780 (defvar org-last-indirect-buffer nil)
5782 (defun org-tree-to-indirect-buffer (&optional arg)
5783 "Create indirect buffer and narrow it to current subtree.
5784 With numerical prefix ARG, go up to this level and then take that tree.
5785 If ARG is negative, go up that many levels.
5786 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5787 indirect buffer previously made with this command, to avoid proliferation of
5788 indirect buffers. However, when you call the command with a `C-u' prefix, or
5789 when `org-indirect-buffer-display' is `new-frame', the last buffer
5790 is kept so that you can work with several indirect buffers at the same time.
5791 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5792 requests that a new frame be made for the new buffer, so that the dedicated
5793 frame is not changed."
5794 (interactive "P")
5795 (let ((cbuf (current-buffer))
5796 (cwin (selected-window))
5797 (pos (point))
5798 beg end level heading ibuf)
5799 (save-excursion
5800 (org-back-to-heading t)
5801 (when (numberp arg)
5802 (setq level (org-outline-level))
5803 (if (< arg 0) (setq arg (+ level arg)))
5804 (while (> (setq level (org-outline-level)) arg)
5805 (outline-up-heading 1 t)))
5806 (setq beg (point)
5807 heading (org-get-heading))
5808 (org-end-of-subtree t t) (setq end (point)))
5809 (if (and (buffer-live-p org-last-indirect-buffer)
5810 (not (eq org-indirect-buffer-display 'new-frame))
5811 (not arg))
5812 (kill-buffer org-last-indirect-buffer))
5813 (setq ibuf (org-get-indirect-buffer cbuf)
5814 org-last-indirect-buffer ibuf)
5815 (cond
5816 ((or (eq org-indirect-buffer-display 'new-frame)
5817 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5818 (select-frame (make-frame))
5819 (delete-other-windows)
5820 (switch-to-buffer ibuf)
5821 (org-set-frame-title heading))
5822 ((eq org-indirect-buffer-display 'dedicated-frame)
5823 (raise-frame
5824 (select-frame (or (and org-indirect-dedicated-frame
5825 (frame-live-p org-indirect-dedicated-frame)
5826 org-indirect-dedicated-frame)
5827 (setq org-indirect-dedicated-frame (make-frame)))))
5828 (delete-other-windows)
5829 (switch-to-buffer ibuf)
5830 (org-set-frame-title (concat "Indirect: " heading)))
5831 ((eq org-indirect-buffer-display 'current-window)
5832 (switch-to-buffer ibuf))
5833 ((eq org-indirect-buffer-display 'other-window)
5834 (pop-to-buffer ibuf))
5835 (t (error "Invalid value")))
5836 (if (featurep 'xemacs)
5837 (save-excursion (org-mode) (turn-on-font-lock)))
5838 (narrow-to-region beg end)
5839 (show-all)
5840 (goto-char pos)
5841 (and (window-live-p cwin) (select-window cwin))))
5843 (defun org-get-indirect-buffer (&optional buffer)
5844 (setq buffer (or buffer (current-buffer)))
5845 (let ((n 1) (base (buffer-name buffer)) bname)
5846 (while (buffer-live-p
5847 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5848 (setq n (1+ n)))
5849 (condition-case nil
5850 (make-indirect-buffer buffer bname 'clone)
5851 (error (make-indirect-buffer buffer bname)))))
5853 (defun org-set-frame-title (title)
5854 "Set the title of the current frame to the string TITLE."
5855 ;; FIXME: how to name a single frame in XEmacs???
5856 (unless (featurep 'xemacs)
5857 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5859 ;;;; Structure editing
5861 ;;; Inserting headlines
5863 (defun org-previous-line-empty-p ()
5864 (save-excursion
5865 (and (not (bobp))
5866 (or (beginning-of-line 0) t)
5867 (save-match-data
5868 (looking-at "[ \t]*$")))))
5870 (defun org-insert-heading (&optional force-heading)
5871 "Insert a new heading or item with same depth at point.
5872 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5873 If point is at the beginning of a headline, insert a sibling before the
5874 current headline. If point is not at the beginning, do not split the line,
5875 but create the new headline after the current line."
5876 (interactive "P")
5877 (if (= (buffer-size) 0)
5878 (insert "\n* ")
5879 (when (or force-heading (not (org-insert-item)))
5880 (let* ((empty-line-p nil)
5881 (head (save-excursion
5882 (condition-case nil
5883 (progn
5884 (org-back-to-heading)
5885 (setq empty-line-p (org-previous-line-empty-p))
5886 (match-string 0))
5887 (error "*"))))
5888 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5889 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5890 pos hide-previous previous-pos)
5891 (cond
5892 ((and (org-on-heading-p) (bolp)
5893 (or (bobp)
5894 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5895 ;; insert before the current line
5896 (open-line (if blank 2 1)))
5897 ((and (bolp)
5898 (not org-insert-heading-respect-content)
5899 (or (bobp)
5900 (save-excursion
5901 (backward-char 1) (not (org-invisible-p)))))
5902 ;; insert right here
5903 nil)
5905 ;; somewhere in the line
5906 (save-excursion
5907 (setq previous-pos (point-at-bol))
5908 (end-of-line)
5909 (setq hide-previous (org-invisible-p)))
5910 (and org-insert-heading-respect-content (org-show-subtree))
5911 (let ((split
5912 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5913 (save-excursion
5914 (let ((p (point)))
5915 (goto-char (point-at-bol))
5916 (and (looking-at org-complex-heading-regexp)
5917 (> p (match-beginning 4)))))))
5918 tags pos)
5919 (cond
5920 (org-insert-heading-respect-content
5921 (org-end-of-subtree nil t)
5922 (or (bolp) (newline))
5923 (or (org-previous-line-empty-p)
5924 (and blank (newline)))
5925 (open-line 1))
5926 ((org-on-heading-p)
5927 (when hide-previous
5928 (show-children)
5929 (org-show-entry))
5930 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5931 (setq tags (and (match-end 2) (match-string 2)))
5932 (and (match-end 1)
5933 (delete-region (match-beginning 1) (match-end 1)))
5934 (setq pos (point-at-bol))
5935 (or split (end-of-line 1))
5936 (delete-horizontal-space)
5937 (newline (if blank 2 1))
5938 (when tags
5939 (save-excursion
5940 (goto-char pos)
5941 (end-of-line 1)
5942 (insert " " tags)
5943 (org-set-tags nil 'align))))
5945 (or split (end-of-line 1))
5946 (newline (if blank 2 1)))))))
5947 (insert head) (just-one-space)
5948 (setq pos (point))
5949 (end-of-line 1)
5950 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5951 (when (and org-insert-heading-respect-content hide-previous)
5952 (save-excursion
5953 (goto-char previous-pos)
5954 (hide-subtree)))
5955 (run-hooks 'org-insert-heading-hook)))))
5957 (defun org-get-heading (&optional no-tags)
5958 "Return the heading of the current entry, without the stars."
5959 (save-excursion
5960 (org-back-to-heading t)
5961 (if (looking-at
5962 (if no-tags
5963 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5964 "\\*+[ \t]+\\([^\r\n]*\\)"))
5965 (match-string 1) "")))
5967 (defun org-heading-components ()
5968 "Return the components of the current heading.
5969 This is a list with the following elements:
5970 - the level as an integer
5971 - the reduced level, different if `org-odd-levels-only' is set.
5972 - the TODO keyword, or nil
5973 - the priority character, like ?A, or nil if no priority is given
5974 - the headline text itself, or the tags string if no headline text
5975 - the tags string, or nil."
5976 (save-excursion
5977 (org-back-to-heading t)
5978 (if (looking-at org-complex-heading-regexp)
5979 (list (length (match-string 1))
5980 (org-reduced-level (length (match-string 1)))
5981 (org-match-string-no-properties 2)
5982 (and (match-end 3) (aref (match-string 3) 2))
5983 (org-match-string-no-properties 4)
5984 (org-match-string-no-properties 5)))))
5986 (defun org-get-entry ()
5987 "Get the entry text, after heading, entire subtree."
5988 (save-excursion
5989 (org-back-to-heading t)
5990 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5992 (defun org-insert-heading-after-current ()
5993 "Insert a new heading with same level as current, after current subtree."
5994 (interactive)
5995 (org-back-to-heading)
5996 (org-insert-heading)
5997 (org-move-subtree-down)
5998 (end-of-line 1))
6000 (defun org-insert-heading-respect-content ()
6001 (interactive)
6002 (let ((org-insert-heading-respect-content t))
6003 (org-insert-heading t)))
6005 (defun org-insert-todo-heading-respect-content (&optional force-state)
6006 (interactive "P")
6007 (let ((org-insert-heading-respect-content t))
6008 (org-insert-todo-heading force-state t)))
6010 (defun org-insert-todo-heading (arg &optional force-heading)
6011 "Insert a new heading with the same level and TODO state as current heading.
6012 If the heading has no TODO state, or if the state is DONE, use the first
6013 state (TODO by default). Also with prefix arg, force first state."
6014 (interactive "P")
6015 (when (or force-heading (not (org-insert-item 'checkbox)))
6016 (org-insert-heading force-heading)
6017 (save-excursion
6018 (org-back-to-heading)
6019 (outline-previous-heading)
6020 (looking-at org-todo-line-regexp))
6021 (let*
6022 ((new-mark-x
6023 (if (or arg
6024 (not (match-beginning 2))
6025 (member (match-string 2) org-done-keywords))
6026 (car org-todo-keywords-1)
6027 (match-string 2)))
6028 (new-mark
6030 (run-hook-with-args-until-success
6031 'org-todo-get-default-hook new-mark-x nil)
6032 new-mark-x)))
6033 (beginning-of-line 1)
6034 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6035 (if org-treat-insert-todo-heading-as-state-change
6036 (org-todo new-mark)
6037 (insert new-mark " "))))
6038 (when org-provide-todo-statistics
6039 (org-update-parent-todo-statistics))))
6041 (defun org-insert-subheading (arg)
6042 "Insert a new subheading and demote it.
6043 Works for outline headings and for plain lists alike."
6044 (interactive "P")
6045 (org-insert-heading arg)
6046 (cond
6047 ((org-on-heading-p) (org-do-demote))
6048 ((org-at-item-p) (org-indent-item 1))))
6050 (defun org-insert-todo-subheading (arg)
6051 "Insert a new subheading with TODO keyword or checkbox and demote it.
6052 Works for outline headings and for plain lists alike."
6053 (interactive "P")
6054 (org-insert-todo-heading arg)
6055 (cond
6056 ((org-on-heading-p) (org-do-demote))
6057 ((org-at-item-p) (org-indent-item 1))))
6059 ;;; Promotion and Demotion
6061 (defvar org-after-demote-entry-hook nil
6062 "Hook run after an entry has been demoted.
6063 The cursor will be at the beginning of the entry.
6064 When a subtree is being demoted, the hook will be called for each node.")
6066 (defvar org-after-promote-entry-hook nil
6067 "Hook run after an entry has been promoted.
6068 The cursor will be at the beginning of the entry.
6069 When a subtree is being promoted, the hook will be called for each node.")
6071 (defun org-promote-subtree ()
6072 "Promote the entire subtree.
6073 See also `org-promote'."
6074 (interactive)
6075 (save-excursion
6076 (org-map-tree 'org-promote))
6077 (org-fix-position-after-promote))
6079 (defun org-demote-subtree ()
6080 "Demote the entire subtree. See `org-demote'.
6081 See also `org-promote'."
6082 (interactive)
6083 (save-excursion
6084 (org-map-tree 'org-demote))
6085 (org-fix-position-after-promote))
6088 (defun org-do-promote ()
6089 "Promote the current heading higher up the tree.
6090 If the region is active in `transient-mark-mode', promote all headings
6091 in the region."
6092 (interactive)
6093 (save-excursion
6094 (if (org-region-active-p)
6095 (org-map-region 'org-promote (region-beginning) (region-end))
6096 (org-promote)))
6097 (org-fix-position-after-promote))
6099 (defun org-do-demote ()
6100 "Demote the current heading lower down the tree.
6101 If the region is active in `transient-mark-mode', demote all headings
6102 in the region."
6103 (interactive)
6104 (save-excursion
6105 (if (org-region-active-p)
6106 (org-map-region 'org-demote (region-beginning) (region-end))
6107 (org-demote)))
6108 (org-fix-position-after-promote))
6110 (defun org-fix-position-after-promote ()
6111 "Make sure that after pro/demotion cursor position is right."
6112 (let ((pos (point)))
6113 (when (save-excursion
6114 (beginning-of-line 1)
6115 (looking-at org-todo-line-regexp)
6116 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6117 (cond ((eobp) (insert " "))
6118 ((eolp) (insert " "))
6119 ((equal (char-after) ?\ ) (forward-char 1))))))
6121 (defun org-current-level ()
6122 "Return the level of the current entry, or nil if before the first headline.
6123 The level is the number of stars at the beginning of the headline."
6124 (save-excursion
6125 (condition-case nil
6126 (progn
6127 (org-back-to-heading t)
6128 (funcall outline-level))
6129 (error nil))))
6131 (defun org-reduced-level (l)
6132 "Compute the effective level of a heading.
6133 This takes into account the setting of `org-odd-levels-only'."
6134 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6136 (defun org-get-valid-level (level &optional change)
6137 "Rectify a level change under the influence of `org-odd-levels-only'
6138 LEVEL is a current level, CHANGE is by how much the level should be
6139 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6140 even level numbers will become the next higher odd number."
6141 (if org-odd-levels-only
6142 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6143 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6144 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6145 (max 1 (+ level (or change 0)))))
6147 (if (boundp 'define-obsolete-function-alias)
6148 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6149 (define-obsolete-function-alias 'org-get-legal-level
6150 'org-get-valid-level)
6151 (define-obsolete-function-alias 'org-get-legal-level
6152 'org-get-valid-level "23.1")))
6154 (defun org-promote ()
6155 "Promote the current heading higher up the tree.
6156 If the region is active in `transient-mark-mode', promote all headings
6157 in the region."
6158 (org-back-to-heading t)
6159 (let* ((level (save-match-data (funcall outline-level)))
6160 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6161 (diff (abs (- level (length up-head) -1))))
6162 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6163 (replace-match up-head nil t)
6164 ;; Fixup tag positioning
6165 (and org-auto-align-tags (org-set-tags nil t))
6166 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6167 (run-hooks 'org-after-promote-entry-hook)))
6169 (defun org-demote ()
6170 "Demote the current heading lower down the tree.
6171 If the region is active in `transient-mark-mode', demote all headings
6172 in the region."
6173 (org-back-to-heading t)
6174 (let* ((level (save-match-data (funcall outline-level)))
6175 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6176 (diff (abs (- level (length down-head) -1))))
6177 (replace-match down-head nil t)
6178 ;; Fixup tag positioning
6179 (and org-auto-align-tags (org-set-tags nil t))
6180 (if org-adapt-indentation (org-fixup-indentation diff))
6181 (run-hooks 'org-after-demote-entry-hook)))
6183 (defvar org-tab-ind-state nil)
6185 (defun org-cycle-level ()
6186 (let ((org-adapt-indentation nil))
6187 (when (and (looking-at "[ \t]*$")
6188 (looking-back
6189 (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))
6190 (setq this-command 'org-cycle-level)
6191 (if (eq last-command 'org-cycle-level)
6192 (condition-case nil
6193 (progn (org-do-promote)
6194 (if (equal org-tab-ind-state (org-current-level))
6195 (org-do-promote)))
6196 (error
6197 (progn
6198 (save-excursion
6199 (beginning-of-line 1)
6200 (and (looking-at "\\*+")
6201 (replace-match
6202 (make-string org-tab-ind-state ?*))))
6203 (setq this-command 'org-cycle))))
6204 (setq org-tab-ind-state (- (match-end 1) (match-beginning 1)))
6205 (org-do-demote))
6206 t)))
6208 (defun org-map-tree (fun)
6209 "Call FUN for every heading underneath the current one."
6210 (org-back-to-heading)
6211 (let ((level (funcall outline-level)))
6212 (save-excursion
6213 (funcall fun)
6214 (while (and (progn
6215 (outline-next-heading)
6216 (> (funcall outline-level) level))
6217 (not (eobp)))
6218 (funcall fun)))))
6220 (defun org-map-region (fun beg end)
6221 "Call FUN for every heading between BEG and END."
6222 (let ((org-ignore-region t))
6223 (save-excursion
6224 (setq end (copy-marker end))
6225 (goto-char beg)
6226 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6227 (< (point) end))
6228 (funcall fun))
6229 (while (and (progn
6230 (outline-next-heading)
6231 (< (point) end))
6232 (not (eobp)))
6233 (funcall fun)))))
6235 (defun org-fixup-indentation (diff)
6236 "Change the indentation in the current entry by DIFF
6237 However, if any line in the current entry has no indentation, or if it
6238 would end up with no indentation after the change, nothing at all is done."
6239 (save-excursion
6240 (let ((end (save-excursion (outline-next-heading)
6241 (point-marker)))
6242 (prohibit (if (> diff 0)
6243 "^\\S-"
6244 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6245 col)
6246 (unless (save-excursion (end-of-line 1)
6247 (re-search-forward prohibit end t))
6248 (while (and (< (point) end)
6249 (re-search-forward "^[ \t]+" end t))
6250 (goto-char (match-end 0))
6251 (setq col (current-column))
6252 (if (< diff 0) (replace-match ""))
6253 (org-indent-to-column (+ diff col))))
6254 (move-marker end nil))))
6256 (defun org-convert-to-odd-levels ()
6257 "Convert an org-mode file with all levels allowed to one with odd levels.
6258 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6259 level 5 etc."
6260 (interactive)
6261 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6262 (let ((outline-regexp org-outline-regexp)
6263 (outline-level 'org-outline-level)
6264 (org-odd-levels-only nil) n)
6265 (save-excursion
6266 (goto-char (point-min))
6267 (while (re-search-forward "^\\*\\*+ " nil t)
6268 (setq n (- (length (match-string 0)) 2))
6269 (while (>= (setq n (1- n)) 0)
6270 (org-demote))
6271 (end-of-line 1))))))
6273 (defun org-convert-to-oddeven-levels ()
6274 "Convert an org-mode file with only odd levels to one with odd and even levels.
6275 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6276 section with an even level, conversion would destroy the structure of the file. An error
6277 is signaled in this case."
6278 (interactive)
6279 (goto-char (point-min))
6280 ;; First check if there are no even levels
6281 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6282 (org-show-context t)
6283 (error "Not all levels are odd in this file. Conversion not possible"))
6284 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6285 (let ((outline-regexp org-outline-regexp)
6286 (outline-level 'org-outline-level)
6287 (org-odd-levels-only nil) n)
6288 (save-excursion
6289 (goto-char (point-min))
6290 (while (re-search-forward "^\\*\\*+ " nil t)
6291 (setq n (/ (1- (length (match-string 0))) 2))
6292 (while (>= (setq n (1- n)) 0)
6293 (org-promote))
6294 (end-of-line 1))))))
6296 (defun org-tr-level (n)
6297 "Make N odd if required."
6298 (if org-odd-levels-only (1+ (/ n 2)) n))
6300 ;;; Vertical tree motion, cutting and pasting of subtrees
6302 (defun org-move-subtree-up (&optional arg)
6303 "Move the current subtree up past ARG headlines of the same level."
6304 (interactive "p")
6305 (org-move-subtree-down (- (prefix-numeric-value arg))))
6307 (defun org-move-subtree-down (&optional arg)
6308 "Move the current subtree down past ARG headlines of the same level."
6309 (interactive "p")
6310 (setq arg (prefix-numeric-value arg))
6311 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6312 'org-get-last-sibling))
6313 (ins-point (make-marker))
6314 (cnt (abs arg))
6315 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6316 ;; Select the tree
6317 (org-back-to-heading)
6318 (setq beg0 (point))
6319 (save-excursion
6320 (setq ne-beg (org-back-over-empty-lines))
6321 (setq beg (point)))
6322 (save-match-data
6323 (save-excursion (outline-end-of-heading)
6324 (setq folded (org-invisible-p)))
6325 (outline-end-of-subtree))
6326 (outline-next-heading)
6327 (setq ne-end (org-back-over-empty-lines))
6328 (setq end (point))
6329 (goto-char beg0)
6330 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6331 ;; include less whitespace
6332 (save-excursion
6333 (goto-char beg)
6334 (forward-line (- ne-beg ne-end))
6335 (setq beg (point))))
6336 ;; Find insertion point, with error handling
6337 (while (> cnt 0)
6338 (or (and (funcall movfunc) (looking-at outline-regexp))
6339 (progn (goto-char beg0)
6340 (error "Cannot move past superior level or buffer limit")))
6341 (setq cnt (1- cnt)))
6342 (if (> arg 0)
6343 ;; Moving forward - still need to move over subtree
6344 (progn (org-end-of-subtree t t)
6345 (save-excursion
6346 (org-back-over-empty-lines)
6347 (or (bolp) (newline)))))
6348 (setq ne-ins (org-back-over-empty-lines))
6349 (move-marker ins-point (point))
6350 (setq txt (buffer-substring beg end))
6351 (org-save-markers-in-region beg end)
6352 (delete-region beg end)
6353 (org-remove-empty-overlays-at beg)
6354 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6355 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6356 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6357 (let ((bbb (point)))
6358 (insert-before-markers txt)
6359 (org-reinstall-markers-in-region bbb)
6360 (move-marker ins-point bbb))
6361 (or (bolp) (insert "\n"))
6362 (setq ins-end (point))
6363 (goto-char ins-point)
6364 (org-skip-whitespace)
6365 (when (and (< arg 0)
6366 (org-first-sibling-p)
6367 (> ne-ins ne-beg))
6368 ;; Move whitespace back to beginning
6369 (save-excursion
6370 (goto-char ins-end)
6371 (let ((kill-whole-line t))
6372 (kill-line (- ne-ins ne-beg)) (point)))
6373 (insert (make-string (- ne-ins ne-beg) ?\n)))
6374 (move-marker ins-point nil)
6375 (if folded
6376 (hide-subtree)
6377 (org-show-entry)
6378 (show-children)
6379 (org-cycle-hide-drawers 'children))
6380 (org-clean-visibility-after-subtree-move)))
6382 (defvar org-subtree-clip ""
6383 "Clipboard for cut and paste of subtrees.
6384 This is actually only a copy of the kill, because we use the normal kill
6385 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6387 (defvar org-subtree-clip-folded nil
6388 "Was the last copied subtree folded?
6389 This is used to fold the tree back after pasting.")
6391 (defun org-cut-subtree (&optional n)
6392 "Cut the current subtree into the clipboard.
6393 With prefix arg N, cut this many sequential subtrees.
6394 This is a short-hand for marking the subtree and then cutting it."
6395 (interactive "p")
6396 (org-copy-subtree n 'cut))
6398 (defun org-copy-subtree (&optional n cut force-store-markers)
6399 "Cut the current subtree into the clipboard.
6400 With prefix arg N, cut this many sequential subtrees.
6401 This is a short-hand for marking the subtree and then copying it.
6402 If CUT is non-nil, actually cut the subtree.
6403 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6404 of some markers in the region, even if CUT is non-nil. This is
6405 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6406 (interactive "p")
6407 (let (beg end folded (beg0 (point)))
6408 (if (interactive-p)
6409 (org-back-to-heading nil) ; take what looks like a subtree
6410 (org-back-to-heading t)) ; take what is really there
6411 (org-back-over-empty-lines)
6412 (setq beg (point))
6413 (skip-chars-forward " \t\r\n")
6414 (save-match-data
6415 (save-excursion (outline-end-of-heading)
6416 (setq folded (org-invisible-p)))
6417 (condition-case nil
6418 (org-forward-same-level (1- n) t)
6419 (error nil))
6420 (org-end-of-subtree t t))
6421 (org-back-over-empty-lines)
6422 (setq end (point))
6423 (goto-char beg0)
6424 (when (> end beg)
6425 (setq org-subtree-clip-folded folded)
6426 (when (or cut force-store-markers)
6427 (org-save-markers-in-region beg end))
6428 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6429 (setq org-subtree-clip (current-kill 0))
6430 (message "%s: Subtree(s) with %d characters"
6431 (if cut "Cut" "Copied")
6432 (length org-subtree-clip)))))
6434 (defun org-paste-subtree (&optional level tree for-yank)
6435 "Paste the clipboard as a subtree, with modification of headline level.
6436 The entire subtree is promoted or demoted in order to match a new headline
6437 level.
6439 If the cursor is at the beginning of a headline, the same level as
6440 that headline is used to paste the tree
6442 If not, the new level is derived from the *visible* headings
6443 before and after the insertion point, and taken to be the inferior headline
6444 level of the two. So if the previous visible heading is level 3 and the
6445 next is level 4 (or vice versa), level 4 will be used for insertion.
6446 This makes sure that the subtree remains an independent subtree and does
6447 not swallow low level entries.
6449 You can also force a different level, either by using a numeric prefix
6450 argument, or by inserting the heading marker by hand. For example, if the
6451 cursor is after \"*****\", then the tree will be shifted to level 5.
6453 If optional TREE is given, use this text instead of the kill ring.
6455 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6456 move back over whitespace before inserting, and move point to the end of
6457 the inserted text when done."
6458 (interactive "P")
6459 (setq tree (or tree (and kill-ring (current-kill 0))))
6460 (unless (org-kill-is-subtree-p tree)
6461 (error "%s"
6462 (substitute-command-keys
6463 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6464 (let* ((visp (not (org-invisible-p)))
6465 (txt tree)
6466 (^re (concat "^\\(" outline-regexp "\\)"))
6467 (re (concat "\\(" outline-regexp "\\)"))
6468 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6470 (old-level (if (string-match ^re txt)
6471 (- (match-end 0) (match-beginning 0) 1)
6472 -1))
6473 (force-level (cond (level (prefix-numeric-value level))
6474 ((and (looking-at "[ \t]*$")
6475 (string-match
6476 ^re_ (buffer-substring
6477 (point-at-bol) (point))))
6478 (- (match-end 1) (match-beginning 1)))
6479 ((and (bolp)
6480 (looking-at org-outline-regexp))
6481 (- (match-end 0) (point) 1))
6482 (t nil)))
6483 (previous-level (save-excursion
6484 (condition-case nil
6485 (progn
6486 (outline-previous-visible-heading 1)
6487 (if (looking-at re)
6488 (- (match-end 0) (match-beginning 0) 1)
6490 (error 1))))
6491 (next-level (save-excursion
6492 (condition-case nil
6493 (progn
6494 (or (looking-at outline-regexp)
6495 (outline-next-visible-heading 1))
6496 (if (looking-at re)
6497 (- (match-end 0) (match-beginning 0) 1)
6499 (error 1))))
6500 (new-level (or force-level (max previous-level next-level)))
6501 (shift (if (or (= old-level -1)
6502 (= new-level -1)
6503 (= old-level new-level))
6505 (- new-level old-level)))
6506 (delta (if (> shift 0) -1 1))
6507 (func (if (> shift 0) 'org-demote 'org-promote))
6508 (org-odd-levels-only nil)
6509 beg end newend)
6510 ;; Remove the forced level indicator
6511 (if force-level
6512 (delete-region (point-at-bol) (point)))
6513 ;; Paste
6514 (beginning-of-line 1)
6515 (unless for-yank (org-back-over-empty-lines))
6516 (setq beg (point))
6517 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6518 (insert-before-markers txt)
6519 (unless (string-match "\n\\'" txt) (insert "\n"))
6520 (setq newend (point))
6521 (org-reinstall-markers-in-region beg)
6522 (setq end (point))
6523 (goto-char beg)
6524 (skip-chars-forward " \t\n\r")
6525 (setq beg (point))
6526 (if (and (org-invisible-p) visp)
6527 (save-excursion (outline-show-heading)))
6528 ;; Shift if necessary
6529 (unless (= shift 0)
6530 (save-restriction
6531 (narrow-to-region beg end)
6532 (while (not (= shift 0))
6533 (org-map-region func (point-min) (point-max))
6534 (setq shift (+ delta shift)))
6535 (goto-char (point-min))
6536 (setq newend (point-max))))
6537 (when (or (interactive-p) for-yank)
6538 (message "Clipboard pasted as level %d subtree" new-level))
6539 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6540 kill-ring
6541 (eq org-subtree-clip (current-kill 0))
6542 org-subtree-clip-folded)
6543 ;; The tree was folded before it was killed/copied
6544 (hide-subtree))
6545 (and for-yank (goto-char newend))))
6547 (defun org-kill-is-subtree-p (&optional txt)
6548 "Check if the current kill is an outline subtree, or a set of trees.
6549 Returns nil if kill does not start with a headline, or if the first
6550 headline level is not the largest headline level in the tree.
6551 So this will actually accept several entries of equal levels as well,
6552 which is OK for `org-paste-subtree'.
6553 If optional TXT is given, check this string instead of the current kill."
6554 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6555 (start-level (and kill
6556 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6557 org-outline-regexp "\\)")
6558 kill)
6559 (- (match-end 2) (match-beginning 2) 1)))
6560 (re (concat "^" org-outline-regexp))
6561 (start (1+ (or (match-beginning 2) -1))))
6562 (if (not start-level)
6563 (progn
6564 nil) ;; does not even start with a heading
6565 (catch 'exit
6566 (while (setq start (string-match re kill (1+ start)))
6567 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6568 (throw 'exit nil)))
6569 t))))
6571 (defvar org-markers-to-move nil
6572 "Markers that should be moved with a cut-and-paste operation.
6573 Those markers are stored together with their positions relative to
6574 the start of the region.")
6576 (defun org-save-markers-in-region (beg end)
6577 "Check markers in region.
6578 If these markers are between BEG and END, record their position relative
6579 to BEG, so that after moving the block of text, we can put the markers back
6580 into place.
6581 This function gets called just before an entry or tree gets cut from the
6582 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6583 called immediately, to move the markers with the entries."
6584 (setq org-markers-to-move nil)
6585 (when (featurep 'org-clock)
6586 (org-clock-save-markers-for-cut-and-paste beg end))
6587 (when (featurep 'org-agenda)
6588 (org-agenda-save-markers-for-cut-and-paste beg end)))
6590 (defun org-check-and-save-marker (marker beg end)
6591 "Check if MARKER is between BEG and END.
6592 If yes, remember the marker and the distance to BEG."
6593 (when (and (marker-buffer marker)
6594 (equal (marker-buffer marker) (current-buffer)))
6595 (if (and (>= marker beg) (< marker end))
6596 (push (cons marker (- marker beg)) org-markers-to-move))))
6598 (defun org-reinstall-markers-in-region (beg)
6599 "Move all remembered markers to their position relative to BEG."
6600 (mapc (lambda (x)
6601 (move-marker (car x) (+ beg (cdr x))))
6602 org-markers-to-move)
6603 (setq org-markers-to-move nil))
6605 (defun org-narrow-to-subtree ()
6606 "Narrow buffer to the current subtree."
6607 (interactive)
6608 (save-excursion
6609 (save-match-data
6610 (narrow-to-region
6611 (progn (org-back-to-heading t) (point))
6612 (progn (org-end-of-subtree t t) (point))))))
6614 (defun org-clone-subtree-with-time-shift (n &optional shift)
6615 "Clone the task (subtree) at point N times.
6616 The clones will be inserted as siblings.
6618 In interactive use, the user will be prompted for the number of clones
6619 to be produced, and for a time SHIFT, which may be a repeater as used
6620 in time stamps, for example `+3d'.
6622 When a valid repeater is given and the entry contains any time stamps,
6623 the clones will become a sequence in time, with time stamps in the
6624 subtree shifted for each clone produced. If SHIFT is nil or the
6625 empty string, time stamps will be left alone.
6627 If the original subtree did contain time stamps with a repeater,
6628 the following will happen:
6629 - the repeater will be removed in each clone
6630 - an additional clone will be produced, with the current, unshifted
6631 date(s) in the entry.
6632 - the original entry will be placed *after* all the clones, with
6633 repeater intact.
6634 - the start days in the repeater in the original entry will be shifted
6635 to past the last clone.
6636 I this way you can spell out a number of instances of a repeating task,
6637 and still retain the repeater to cover future instances of the task."
6638 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6639 (let (beg end template task
6640 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6641 (if (not (and (integerp n) (> n 0)))
6642 (error "Invalid number of replications %s" n))
6643 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6644 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6645 shift)))
6646 (error "Invalid shift specification %s" shift))
6647 (when doshift
6648 (setq shift-n (string-to-number (match-string 1 shift))
6649 shift-what (cdr (assoc (match-string 2 shift)
6650 '(("d" . day) ("w" . week)
6651 ("m" . month) ("y" . year))))))
6652 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6653 (setq nmin 1 nmax n)
6654 (org-back-to-heading t)
6655 (setq beg (point))
6656 (org-end-of-subtree t t)
6657 (setq end (point))
6658 (setq template (buffer-substring beg end))
6659 (when (and doshift
6660 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6661 (delete-region beg end)
6662 (setq end beg)
6663 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6664 (goto-char end)
6665 (loop for n from nmin to nmax do
6666 (if (not doshift)
6667 (setq task template)
6668 (with-temp-buffer
6669 (insert template)
6670 (org-mode)
6671 (goto-char (point-min))
6672 (while (re-search-forward org-ts-regexp-both nil t)
6673 (org-timestamp-change (* n shift-n) shift-what))
6674 (unless (= n n-no-remove)
6675 (goto-char (point-min))
6676 (while (re-search-forward org-ts-regexp nil t)
6677 (save-excursion
6678 (goto-char (match-beginning 0))
6679 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6680 (delete-region (match-beginning 1) (match-end 1))))))
6681 (setq task (buffer-string))))
6682 (insert task))
6683 (goto-char beg)))
6685 ;;; Outline Sorting
6687 (defun org-sort (with-case)
6688 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6689 Optional argument WITH-CASE means sort case-sensitively.
6690 With a double prefix argument, also remove duplicate entries."
6691 (interactive "P")
6692 (if (org-at-table-p)
6693 (org-call-with-arg 'org-table-sort-lines with-case)
6694 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6696 (defun org-sort-remove-invisible (s)
6697 (remove-text-properties 0 (length s) org-rm-props s)
6698 (while (string-match org-bracket-link-regexp s)
6699 (setq s (replace-match (if (match-end 2)
6700 (match-string 3 s)
6701 (match-string 1 s)) t t s)))
6704 (defvar org-priority-regexp) ; defined later in the file
6706 (defvar org-after-sorting-entries-or-items-hook nil
6707 "Hook that is run after a bunch of entries or items have been sorted.
6708 When children are sorted, the cursor is in the parent line when this
6709 hook gets called. When a region or a plain list is sorted, the cursor
6710 will be in the first entry of the sorted region/list.")
6712 (defun org-sort-entries-or-items
6713 (&optional with-case sorting-type getkey-func compare-func property)
6714 "Sort entries on a certain level of an outline tree, or plain list items.
6715 If there is an active region, the entries in the region are sorted.
6716 Else, if the cursor is before the first entry, sort the top-level items.
6717 Else, the children of the entry at point are sorted.
6718 If the cursor is at the first item in a plain list, the list items will be
6719 sorted.
6721 Sorting can be alphabetically, numerically, by date/time as given by
6722 a time stamp, by a property or by priority.
6724 The command prompts for the sorting type unless it has been given to the
6725 function through the SORTING-TYPE argument, which needs to a character,
6726 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6727 precise meaning of each character:
6729 n Numerically, by converting the beginning of the entry/item to a number.
6730 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6731 t By date/time, either the first active time stamp in the entry, or, if
6732 none exist, by the first inactive one.
6733 In items, only the first line will be chekced.
6734 s By the scheduled date/time.
6735 d By deadline date/time.
6736 c By creation time, which is assumed to be the first inactive time stamp
6737 at the beginning of a line.
6738 p By priority according to the cookie.
6739 r By the value of a property.
6741 Capital letters will reverse the sort order.
6743 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6744 called with point at the beginning of the record. It must return either
6745 a string or a number that should serve as the sorting key for that record.
6747 Comparing entries ignores case by default. However, with an optional argument
6748 WITH-CASE, the sorting considers case as well."
6749 (interactive "P")
6750 (let ((case-func (if with-case 'identity 'downcase))
6751 start beg end stars re re2
6752 txt what tmp plain-list-p)
6753 ;; Find beginning and end of region to sort
6754 (cond
6755 ((org-region-active-p)
6756 ;; we will sort the region
6757 (setq end (region-end)
6758 what "region")
6759 (goto-char (region-beginning))
6760 (if (not (org-on-heading-p)) (outline-next-heading))
6761 (setq start (point)))
6762 ((org-at-item-p)
6763 ;; we will sort this plain list
6764 (org-beginning-of-item-list) (setq start (point))
6765 (org-end-of-item-list) (setq end (point))
6766 (goto-char start)
6767 (setq plain-list-p t
6768 what "plain list"))
6769 ((or (org-on-heading-p)
6770 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6771 ;; we will sort the children of the current headline
6772 (org-back-to-heading)
6773 (setq start (point)
6774 end (progn (org-end-of-subtree t t)
6775 (org-back-over-empty-lines)
6776 (point))
6777 what "children")
6778 (goto-char start)
6779 (show-subtree)
6780 (outline-next-heading))
6782 ;; we will sort the top-level entries in this file
6783 (goto-char (point-min))
6784 (or (org-on-heading-p) (outline-next-heading))
6785 (setq start (point) end (point-max) what "top-level")
6786 (goto-char start)
6787 (show-all)))
6789 (setq beg (point))
6790 (if (>= beg end) (error "Nothing to sort"))
6792 (unless plain-list-p
6793 (looking-at "\\(\\*+\\)")
6794 (setq stars (match-string 1)
6795 re (concat "^" (regexp-quote stars) " +")
6796 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6797 txt (buffer-substring beg end))
6798 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6799 (if (and (not (equal stars "*")) (string-match re2 txt))
6800 (error "Region to sort contains a level above the first entry")))
6802 (unless sorting-type
6803 (message
6804 (if plain-list-p
6805 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6806 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6807 [t]ime [s]cheduled [d]eadline [c]reated
6808 A/N/T/S/D/C/P/O/F means reversed:")
6809 what)
6810 (setq sorting-type (read-char-exclusive))
6812 (and (= (downcase sorting-type) ?f)
6813 (setq getkey-func
6814 (org-icompleting-read "Sort using function: "
6815 obarray 'fboundp t nil nil))
6816 (setq getkey-func (intern getkey-func)))
6818 (and (= (downcase sorting-type) ?r)
6819 (setq property
6820 (org-icompleting-read "Property: "
6821 (mapcar 'list (org-buffer-property-keys t))
6822 nil t))))
6824 (message "Sorting entries...")
6826 (save-restriction
6827 (narrow-to-region start end)
6829 (let ((dcst (downcase sorting-type))
6830 (case-fold-search nil)
6831 (now (current-time)))
6832 (sort-subr
6833 (/= dcst sorting-type)
6834 ;; This function moves to the beginning character of the "record" to
6835 ;; be sorted.
6836 (if plain-list-p
6837 (lambda nil
6838 (if (org-at-item-p) t (goto-char (point-max))))
6839 (lambda nil
6840 (if (re-search-forward re nil t)
6841 (goto-char (match-beginning 0))
6842 (goto-char (point-max)))))
6843 ;; This function moves to the last character of the "record" being
6844 ;; sorted.
6845 (if plain-list-p
6846 'org-end-of-item
6847 (lambda nil
6848 (save-match-data
6849 (condition-case nil
6850 (outline-forward-same-level 1)
6851 (error
6852 (goto-char (point-max)))))))
6854 ;; This function returns the value that gets sorted against.
6855 (if plain-list-p
6856 (lambda nil
6857 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6858 (cond
6859 ((= dcst ?n)
6860 (string-to-number (buffer-substring (match-end 0)
6861 (point-at-eol))))
6862 ((= dcst ?a)
6863 (buffer-substring (match-end 0) (point-at-eol)))
6864 ((= dcst ?t)
6865 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6866 (re-search-forward org-ts-regexp-both
6867 (point-at-eol) t))
6868 (org-time-string-to-seconds (match-string 0))
6869 (org-float-time now)))
6870 ((= dcst ?f)
6871 (if getkey-func
6872 (progn
6873 (setq tmp (funcall getkey-func))
6874 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6875 tmp)
6876 (error "Invalid key function `%s'" getkey-func)))
6877 (t (error "Invalid sorting type `%c'" sorting-type)))))
6878 (lambda nil
6879 (cond
6880 ((= dcst ?n)
6881 (if (looking-at org-complex-heading-regexp)
6882 (string-to-number (match-string 4))
6883 nil))
6884 ((= dcst ?a)
6885 (if (looking-at org-complex-heading-regexp)
6886 (funcall case-func (match-string 4))
6887 nil))
6888 ((= dcst ?t)
6889 (let ((end (save-excursion (outline-next-heading) (point))))
6890 (if (or (re-search-forward org-ts-regexp end t)
6891 (re-search-forward org-ts-regexp-both end t))
6892 (org-time-string-to-seconds (match-string 0))
6893 (org-float-time now))))
6894 ((= dcst ?c)
6895 (let ((end (save-excursion (outline-next-heading) (point))))
6896 (if (re-search-forward
6897 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6898 end t)
6899 (org-time-string-to-seconds (match-string 0))
6900 (org-float-time now))))
6901 ((= dcst ?s)
6902 (let ((end (save-excursion (outline-next-heading) (point))))
6903 (if (re-search-forward org-scheduled-time-regexp end t)
6904 (org-time-string-to-seconds (match-string 1))
6905 (org-float-time now))))
6906 ((= dcst ?d)
6907 (let ((end (save-excursion (outline-next-heading) (point))))
6908 (if (re-search-forward org-deadline-time-regexp end t)
6909 (org-time-string-to-seconds (match-string 1))
6910 (org-float-time now))))
6911 ((= dcst ?p)
6912 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6913 (string-to-char (match-string 2))
6914 org-default-priority))
6915 ((= dcst ?r)
6916 (or (org-entry-get nil property) ""))
6917 ((= dcst ?o)
6918 (if (looking-at org-complex-heading-regexp)
6919 (- 9999 (length (member (match-string 2)
6920 org-todo-keywords-1)))))
6921 ((= dcst ?f)
6922 (if getkey-func
6923 (progn
6924 (setq tmp (funcall getkey-func))
6925 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6926 tmp)
6927 (error "Invalid key function `%s'" getkey-func)))
6928 (t (error "Invalid sorting type `%c'" sorting-type)))))
6930 (cond
6931 ((= dcst ?a) 'string<)
6932 ((= dcst ?f) compare-func)
6933 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6934 (t nil)))))
6935 (run-hooks 'org-after-sorting-entries-or-items-hook)
6936 (message "Sorting entries...done")))
6938 (defun org-do-sort (table what &optional with-case sorting-type)
6939 "Sort TABLE of WHAT according to SORTING-TYPE.
6940 The user will be prompted for the SORTING-TYPE if the call to this
6941 function does not specify it. WHAT is only for the prompt, to indicate
6942 what is being sorted. The sorting key will be extracted from
6943 the car of the elements of the table.
6944 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6945 (unless sorting-type
6946 (message
6947 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6948 what)
6949 (setq sorting-type (read-char-exclusive)))
6950 (let ((dcst (downcase sorting-type))
6951 extractfun comparefun)
6952 ;; Define the appropriate functions
6953 (cond
6954 ((= dcst ?n)
6955 (setq extractfun 'string-to-number
6956 comparefun (if (= dcst sorting-type) '< '>)))
6957 ((= dcst ?a)
6958 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6959 (lambda(x) (downcase (org-sort-remove-invisible x))))
6960 comparefun (if (= dcst sorting-type)
6961 'string<
6962 (lambda (a b) (and (not (string< a b))
6963 (not (string= a b)))))))
6964 ((= dcst ?t)
6965 (setq extractfun
6966 (lambda (x)
6967 (if (or (string-match org-ts-regexp x)
6968 (string-match org-ts-regexp-both x))
6969 (org-float-time
6970 (org-time-string-to-time (match-string 0 x)))
6972 comparefun (if (= dcst sorting-type) '< '>)))
6973 (t (error "Invalid sorting type `%c'" sorting-type)))
6975 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6976 table)
6977 (lambda (a b) (funcall comparefun (car a) (car b))))))
6980 ;;; The orgstruct minor mode
6982 ;; Define a minor mode which can be used in other modes in order to
6983 ;; integrate the org-mode structure editing commands.
6985 ;; This is really a hack, because the org-mode structure commands use
6986 ;; keys which normally belong to the major mode. Here is how it
6987 ;; works: The minor mode defines all the keys necessary to operate the
6988 ;; structure commands, but wraps the commands into a function which
6989 ;; tests if the cursor is currently at a headline or a plain list
6990 ;; item. If that is the case, the structure command is used,
6991 ;; temporarily setting many Org-mode variables like regular
6992 ;; expressions for filling etc. However, when any of those keys is
6993 ;; used at a different location, function uses `key-binding' to look
6994 ;; up if the key has an associated command in another currently active
6995 ;; keymap (minor modes, major mode, global), and executes that
6996 ;; command. There might be problems if any of the keys is otherwise
6997 ;; used as a prefix key.
6999 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7000 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7001 ;; addresses this by checking explicitly for both bindings.
7003 (defvar orgstruct-mode-map (make-sparse-keymap)
7004 "Keymap for the minor `orgstruct-mode'.")
7006 (defvar org-local-vars nil
7007 "List of local variables, for use by `orgstruct-mode'")
7009 ;;;###autoload
7010 (define-minor-mode orgstruct-mode
7011 "Toggle the minor more `orgstruct-mode'.
7012 This mode is for using Org-mode structure commands in other modes.
7013 The following key behave as if Org-mode was active, if the cursor
7014 is on a headline, or on a plain list item (both in the definition
7015 of Org-mode).
7017 M-up Move entry/item up
7018 M-down Move entry/item down
7019 M-left Promote
7020 M-right Demote
7021 M-S-up Move entry/item up
7022 M-S-down Move entry/item down
7023 M-S-left Promote subtree
7024 M-S-right Demote subtree
7025 M-q Fill paragraph and items like in Org-mode
7026 C-c ^ Sort entries
7027 C-c - Cycle list bullet
7028 TAB Cycle item visibility
7029 M-RET Insert new heading/item
7030 S-M-RET Insert new TODO heading / Checkbox item
7031 C-c C-c Set tags / toggle checkbox"
7032 nil " OrgStruct" nil
7033 (org-load-modules-maybe)
7034 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7036 ;;;###autoload
7037 (defun turn-on-orgstruct ()
7038 "Unconditionally turn on `orgstruct-mode'."
7039 (orgstruct-mode 1))
7041 (defun orgstruct++-mode (&optional arg)
7042 "Toggle `orgstruct-mode', the enhanced version of it.
7043 In addition to setting orgstruct-mode, this also exports all indentation
7044 and autofilling variables from org-mode into the buffer. It will also
7045 recognize item context in multiline items.
7046 Note that turning off orgstruct-mode will *not* remove the
7047 indentation/paragraph settings. This can only be done by refreshing the
7048 major mode, for example with \\[normal-mode]."
7049 (interactive "P")
7050 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7051 (if (< arg 1)
7052 (orgstruct-mode -1)
7053 (orgstruct-mode 1)
7054 (let (var val)
7055 (mapc
7056 (lambda (x)
7057 (when (string-match
7058 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7059 (symbol-name (car x)))
7060 (setq var (car x) val (nth 1 x))
7061 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7062 org-local-vars)
7063 (org-set-local 'orgstruct-is-++ t))))
7065 (defvar orgstruct-is-++ nil
7066 "Is orgstruct-mode in ++ version in the current-buffer?")
7067 (make-variable-buffer-local 'orgstruct-is-++)
7069 ;;;###autoload
7070 (defun turn-on-orgstruct++ ()
7071 "Unconditionally turn on `orgstruct++-mode'."
7072 (orgstruct++-mode 1))
7074 (defun orgstruct-error ()
7075 "Error when there is no default binding for a structure key."
7076 (interactive)
7077 (error "This key has no function outside structure elements"))
7079 (defun orgstruct-setup ()
7080 "Setup orgstruct keymaps."
7081 (let ((nfunc 0)
7082 (bindings
7083 (list
7084 '([(meta up)] org-metaup)
7085 '([(meta down)] org-metadown)
7086 '([(meta left)] org-metaleft)
7087 '([(meta right)] org-metaright)
7088 '([(meta shift up)] org-shiftmetaup)
7089 '([(meta shift down)] org-shiftmetadown)
7090 '([(meta shift left)] org-shiftmetaleft)
7091 '([(meta shift right)] org-shiftmetaright)
7092 '([?\e (up)] org-metaup)
7093 '([?\e (down)] org-metadown)
7094 '([?\e (left)] org-metaleft)
7095 '([?\e (right)] org-metaright)
7096 '([?\e (shift up)] org-shiftmetaup)
7097 '([?\e (shift down)] org-shiftmetadown)
7098 '([?\e (shift left)] org-shiftmetaleft)
7099 '([?\e (shift right)] org-shiftmetaright)
7100 '([(shift up)] org-shiftup)
7101 '([(shift down)] org-shiftdown)
7102 '([(shift left)] org-shiftleft)
7103 '([(shift right)] org-shiftright)
7104 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7105 '("\M-q" fill-paragraph)
7106 '("\C-c^" org-sort)
7107 '("\C-c-" org-cycle-list-bullet)))
7108 elt key fun cmd)
7109 (while (setq elt (pop bindings))
7110 (setq nfunc (1+ nfunc))
7111 (setq key (org-key (car elt))
7112 fun (nth 1 elt)
7113 cmd (orgstruct-make-binding fun nfunc key))
7114 (org-defkey orgstruct-mode-map key cmd))
7116 ;; Special treatment needed for TAB and RET
7117 (org-defkey orgstruct-mode-map [(tab)]
7118 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7119 (org-defkey orgstruct-mode-map "\C-i"
7120 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7122 (org-defkey orgstruct-mode-map "\M-\C-m"
7123 (orgstruct-make-binding 'org-insert-heading 105
7124 "\M-\C-m" [(meta return)]))
7125 (org-defkey orgstruct-mode-map [(meta return)]
7126 (orgstruct-make-binding 'org-insert-heading 106
7127 [(meta return)] "\M-\C-m"))
7129 (org-defkey orgstruct-mode-map [(shift meta return)]
7130 (orgstruct-make-binding 'org-insert-todo-heading 107
7131 [(meta return)] "\M-\C-m"))
7133 (org-defkey orgstruct-mode-map "\e\C-m"
7134 (orgstruct-make-binding 'org-insert-heading 108
7135 "\e\C-m" [?\e (return)]))
7136 (org-defkey orgstruct-mode-map [?\e (return)]
7137 (orgstruct-make-binding 'org-insert-heading 109
7138 [?\e (return)] "\e\C-m"))
7139 (org-defkey orgstruct-mode-map [?\e (shift return)]
7140 (orgstruct-make-binding 'org-insert-todo-heading 110
7141 [?\e (return)] "\e\C-m"))
7143 (unless org-local-vars
7144 (setq org-local-vars (org-get-local-variables)))
7148 (defun orgstruct-make-binding (fun n &rest keys)
7149 "Create a function for binding in the structure minor mode.
7150 FUN is the command to call inside a table. N is used to create a unique
7151 command name. KEYS are keys that should be checked in for a command
7152 to execute outside of tables."
7153 (eval
7154 (list 'defun
7155 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7156 '(arg)
7157 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7158 "Outside of structure, run the binding of `"
7159 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7160 "'.")
7161 '(interactive "p")
7162 (list 'if
7163 `(org-context-p 'headline 'item
7164 (and orgstruct-is-++
7165 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7166 'item-body))
7167 (list 'org-run-like-in-org-mode (list 'quote fun))
7168 (list 'let '(orgstruct-mode)
7169 (list 'call-interactively
7170 (append '(or)
7171 (mapcar (lambda (k)
7172 (list 'key-binding k))
7173 keys)
7174 '('orgstruct-error))))))))
7176 (defun org-context-p (&rest contexts)
7177 "Check if local context is any of CONTEXTS.
7178 Possible values in the list of contexts are `table', `headline', and `item'."
7179 (let ((pos (point)))
7180 (goto-char (point-at-bol))
7181 (prog1 (or (and (memq 'table contexts)
7182 (looking-at "[ \t]*|"))
7183 (and (memq 'headline contexts)
7184 ;;????????? (looking-at "\\*+"))
7185 (looking-at outline-regexp))
7186 (and (memq 'item contexts)
7187 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7188 (and (memq 'item-body contexts)
7189 (org-in-item-p)))
7190 (goto-char pos))))
7192 (defun org-get-local-variables ()
7193 "Return a list of all local variables in an org-mode buffer."
7194 (let (varlist)
7195 (with-current-buffer (get-buffer-create "*Org tmp*")
7196 (erase-buffer)
7197 (org-mode)
7198 (setq varlist (buffer-local-variables)))
7199 (kill-buffer "*Org tmp*")
7200 (delq nil
7201 (mapcar
7202 (lambda (x)
7203 (setq x
7204 (if (symbolp x)
7205 (list x)
7206 (list (car x) (list 'quote (cdr x)))))
7207 (if (string-match
7208 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7209 (symbol-name (car x)))
7210 x nil))
7211 varlist))))
7213 ;;;###autoload
7214 (defun org-run-like-in-org-mode (cmd)
7215 "Run a command, pretending that the current buffer is in Org-mode.
7216 This will temporarily bind local variables that are typically bound in
7217 Org-mode to the values they have in Org-mode, and then interactively
7218 call CMD."
7219 (org-load-modules-maybe)
7220 (unless org-local-vars
7221 (setq org-local-vars (org-get-local-variables)))
7222 (eval (list 'let org-local-vars
7223 (list 'call-interactively (list 'quote cmd)))))
7225 ;;;; Archiving
7227 (defun org-get-category (&optional pos)
7228 "Get the category applying to position POS."
7229 (get-text-property (or pos (point)) 'org-category))
7231 (defun org-refresh-category-properties ()
7232 "Refresh category text properties in the buffer."
7233 (let ((def-cat (cond
7234 ((null org-category)
7235 (if buffer-file-name
7236 (file-name-sans-extension
7237 (file-name-nondirectory buffer-file-name))
7238 "???"))
7239 ((symbolp org-category) (symbol-name org-category))
7240 (t org-category)))
7241 beg end cat pos optionp)
7242 (org-unmodified
7243 (save-excursion
7244 (save-restriction
7245 (widen)
7246 (goto-char (point-min))
7247 (put-text-property (point) (point-max) 'org-category def-cat)
7248 (while (re-search-forward
7249 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7250 (setq pos (match-end 0)
7251 optionp (equal (char-after (match-beginning 0)) ?#)
7252 cat (org-trim (match-string 2)))
7253 (if optionp
7254 (setq beg (point-at-bol) end (point-max))
7255 (org-back-to-heading t)
7256 (setq beg (point) end (org-end-of-subtree t t)))
7257 (put-text-property beg end 'org-category cat)
7258 (goto-char pos)))))))
7261 ;;;; Link Stuff
7263 ;;; Link abbreviations
7265 (defun org-link-expand-abbrev (link)
7266 "Apply replacements as defined in `org-link-abbrev-alist."
7267 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7268 (let* ((key (match-string 1 link))
7269 (as (or (assoc key org-link-abbrev-alist-local)
7270 (assoc key org-link-abbrev-alist)))
7271 (tag (and (match-end 2) (match-string 3 link)))
7272 rpl)
7273 (if (not as)
7274 link
7275 (setq rpl (cdr as))
7276 (cond
7277 ((symbolp rpl) (funcall rpl tag))
7278 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7279 ((string-match "%h" rpl)
7280 (replace-match (url-hexify-string (or tag "")) t t rpl))
7281 (t (concat rpl tag)))))
7282 link))
7284 ;;; Storing and inserting links
7286 (defvar org-insert-link-history nil
7287 "Minibuffer history for links inserted with `org-insert-link'.")
7289 (defvar org-stored-links nil
7290 "Contains the links stored with `org-store-link'.")
7292 (defvar org-store-link-plist nil
7293 "Plist with info about the most recently link created with `org-store-link'.")
7295 (defvar org-link-protocols nil
7296 "Link protocols added to Org-mode using `org-add-link-type'.")
7298 (defvar org-store-link-functions nil
7299 "List of functions that are called to create and store a link.
7300 Each function will be called in turn until one returns a non-nil
7301 value. Each function should check if it is responsible for creating
7302 this link (for example by looking at the major mode).
7303 If not, it must exit and return nil.
7304 If yes, it should return a non-nil value after a calling
7305 `org-store-link-props' with a list of properties and values.
7306 Special properties are:
7308 :type The link prefix. like \"http\". This must be given.
7309 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7310 This is obligatory as well.
7311 :description Optional default description for the second pair
7312 of brackets in an Org-mode link. The user can still change
7313 this when inserting this link into an Org-mode buffer.
7315 In addition to these, any additional properties can be specified
7316 and then used in remember templates.")
7318 (defun org-add-link-type (type &optional follow export)
7319 "Add TYPE to the list of `org-link-types'.
7320 Re-compute all regular expressions depending on `org-link-types'
7322 FOLLOW and EXPORT are two functions.
7324 FOLLOW should take the link path as the single argument and do whatever
7325 is necessary to follow the link, for example find a file or display
7326 a mail message.
7328 EXPORT should format the link path for export to one of the export formats.
7329 It should be a function accepting three arguments:
7331 path the path of the link, the text after the prefix (like \"http:\")
7332 desc the description of the link, if any, nil if there was no description
7333 format the export format, a symbol like `html' or `latex'.
7335 The function may use the FORMAT information to return different values
7336 depending on the format. The return value will be put literally into
7337 the exported file.
7338 Org-mode has a built-in default for exporting links. If you are happy with
7339 this default, there is no need to define an export function for the link
7340 type. For a simple example of an export function, see `org-bbdb.el'."
7341 (add-to-list 'org-link-types type t)
7342 (org-make-link-regexps)
7343 (if (assoc type org-link-protocols)
7344 (setcdr (assoc type org-link-protocols) (list follow export))
7345 (push (list type follow export) org-link-protocols)))
7347 (defvar org-agenda-buffer-name)
7349 ;;;###autoload
7350 (defun org-store-link (arg)
7351 "\\<org-mode-map>Store an org-link to the current location.
7352 This link is added to `org-stored-links' and can later be inserted
7353 into an org-buffer with \\[org-insert-link].
7355 For some link types, a prefix arg is interpreted:
7356 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7357 For file links, arg negates `org-context-in-file-links'."
7358 (interactive "P")
7359 (org-load-modules-maybe)
7360 (setq org-store-link-plist nil) ; reset
7361 (let ((outline-regexp (org-get-limited-outline-regexp))
7362 link cpltxt desc description search txt custom-id)
7363 (cond
7365 ((run-hook-with-args-until-success 'org-store-link-functions)
7366 (setq link (plist-get org-store-link-plist :link)
7367 desc (or (plist-get org-store-link-plist :description) link)))
7369 ((equal (buffer-name) "*Org Edit Src Example*")
7370 (let (label gc)
7371 (while (or (not label)
7372 (save-excursion
7373 (save-restriction
7374 (widen)
7375 (goto-char (point-min))
7376 (re-search-forward
7377 (regexp-quote (format org-coderef-label-format label))
7378 nil t))))
7379 (when label (message "Label exists already") (sit-for 2))
7380 (setq label (read-string "Code line label: " label)))
7381 (end-of-line 1)
7382 (setq link (format org-coderef-label-format label))
7383 (setq gc (- 79 (length link)))
7384 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7385 (insert link)
7386 (setq link (concat "(" label ")") desc nil)))
7388 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7389 ;; We are in the agenda, link to referenced location
7390 (let ((m (or (get-text-property (point) 'org-hd-marker)
7391 (get-text-property (point) 'org-marker))))
7392 (when m
7393 (org-with-point-at m
7394 (call-interactively 'org-store-link)))))
7396 ((eq major-mode 'calendar-mode)
7397 (let ((cd (calendar-cursor-to-date)))
7398 (setq link
7399 (format-time-string
7400 (car org-time-stamp-formats)
7401 (apply 'encode-time
7402 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7403 nil nil nil))))
7404 (org-store-link-props :type "calendar" :date cd)))
7406 ((eq major-mode 'w3-mode)
7407 (setq cpltxt (if (and (buffer-name)
7408 (not (string-match "Untitled" (buffer-name))))
7409 (buffer-name)
7410 (url-view-url t))
7411 link (org-make-link (url-view-url t)))
7412 (org-store-link-props :type "w3" :url (url-view-url t)))
7414 ((eq major-mode 'w3m-mode)
7415 (setq cpltxt (or w3m-current-title w3m-current-url)
7416 link (org-make-link w3m-current-url))
7417 (org-store-link-props :type "w3m" :url (url-view-url t)))
7419 ((setq search (run-hook-with-args-until-success
7420 'org-create-file-search-functions))
7421 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7422 "::" search))
7423 (setq cpltxt (or description link)))
7425 ((eq major-mode 'image-mode)
7426 (setq cpltxt (concat "file:"
7427 (abbreviate-file-name buffer-file-name))
7428 link (org-make-link cpltxt))
7429 (org-store-link-props :type "image" :file buffer-file-name))
7431 ((eq major-mode 'dired-mode)
7432 ;; link to the file in the current line
7433 (setq cpltxt (concat "file:"
7434 (abbreviate-file-name
7435 (expand-file-name
7436 (dired-get-filename nil t))))
7437 link (org-make-link cpltxt)))
7439 ((and buffer-file-name (org-mode-p))
7440 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7441 (cond
7442 ((org-in-regexp "<<\\(.*?\\)>>")
7443 (setq cpltxt
7444 (concat "file:"
7445 (abbreviate-file-name buffer-file-name)
7446 "::" (match-string 1))
7447 link (org-make-link cpltxt)))
7448 ((and (featurep 'org-id)
7449 (or (eq org-link-to-org-use-id t)
7450 (and (eq org-link-to-org-use-id 'create-if-interactive)
7451 (interactive-p))
7452 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7453 (interactive-p)
7454 (not custom-id))
7455 (and org-link-to-org-use-id
7456 (condition-case nil
7457 (org-entry-get nil "ID")
7458 (error nil)))))
7459 ;; We can make a link using the ID.
7460 (setq link (condition-case nil
7461 (prog1 (org-id-store-link)
7462 (setq desc (plist-get org-store-link-plist
7463 :description)))
7464 (error
7465 ;; probably before first headline, link to file only
7466 (concat "file:"
7467 (abbreviate-file-name buffer-file-name))))))
7469 ;; Just link to current headline
7470 (setq cpltxt (concat "file:"
7471 (abbreviate-file-name buffer-file-name)))
7472 ;; Add a context search string
7473 (when (org-xor org-context-in-file-links arg)
7474 (setq txt (cond
7475 ((org-on-heading-p) nil)
7476 ((org-region-active-p)
7477 (buffer-substring (region-beginning) (region-end)))
7478 (t nil)))
7479 (when (or (null txt) (string-match "\\S-" txt))
7480 (setq cpltxt
7481 (concat cpltxt "::"
7482 (condition-case nil
7483 (org-make-org-heading-search-string txt)
7484 (error "")))
7485 desc (or (nth 4 (ignore-errors
7486 (org-heading-components))) "NONE"))))
7487 (if (string-match "::\\'" cpltxt)
7488 (setq cpltxt (substring cpltxt 0 -2)))
7489 (setq link (org-make-link cpltxt)))))
7491 ((buffer-file-name (buffer-base-buffer))
7492 ;; Just link to this file here.
7493 (setq cpltxt (concat "file:"
7494 (abbreviate-file-name
7495 (buffer-file-name (buffer-base-buffer)))))
7496 ;; Add a context string
7497 (when (org-xor org-context-in-file-links arg)
7498 (setq txt (if (org-region-active-p)
7499 (buffer-substring (region-beginning) (region-end))
7500 (buffer-substring (point-at-bol) (point-at-eol))))
7501 ;; Only use search option if there is some text.
7502 (when (string-match "\\S-" txt)
7503 (setq cpltxt
7504 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7505 desc "NONE")))
7506 (setq link (org-make-link cpltxt)))
7508 ((interactive-p)
7509 (error "Cannot link to a buffer which is not visiting a file"))
7511 (t (setq link nil)))
7513 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7514 (setq link (or link cpltxt)
7515 desc (or desc cpltxt))
7516 (if (equal desc "NONE") (setq desc nil))
7518 (if (and (or (interactive-p) executing-kbd-macro) link)
7519 (progn
7520 (setq org-stored-links
7521 (cons (list link desc) org-stored-links))
7522 (message "Stored: %s" (or desc link))
7523 (when custom-id
7524 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7525 "::#" custom-id))
7526 (setq org-stored-links
7527 (cons (list link desc) org-stored-links))))
7528 (and link (org-make-link-string link desc)))))
7530 (defun org-store-link-props (&rest plist)
7531 "Store link properties, extract names and addresses."
7532 (let (x adr)
7533 (when (setq x (plist-get plist :from))
7534 (setq adr (mail-extract-address-components x))
7535 (setq plist (plist-put plist :fromname (car adr)))
7536 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7537 (when (setq x (plist-get plist :to))
7538 (setq adr (mail-extract-address-components x))
7539 (setq plist (plist-put plist :toname (car adr)))
7540 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7541 (let ((from (plist-get plist :from))
7542 (to (plist-get plist :to)))
7543 (when (and from to org-from-is-user-regexp)
7544 (setq plist
7545 (plist-put plist :fromto
7546 (if (string-match org-from-is-user-regexp from)
7547 (concat "to %t")
7548 (concat "from %f"))))))
7549 (setq org-store-link-plist plist))
7551 (defun org-add-link-props (&rest plist)
7552 "Add these properties to the link property list."
7553 (let (key value)
7554 (while plist
7555 (setq key (pop plist) value (pop plist))
7556 (setq org-store-link-plist
7557 (plist-put org-store-link-plist key value)))))
7559 (defun org-email-link-description (&optional fmt)
7560 "Return the description part of an email link.
7561 This takes information from `org-store-link-plist' and formats it
7562 according to FMT (default from `org-email-link-description-format')."
7563 (setq fmt (or fmt org-email-link-description-format))
7564 (let* ((p org-store-link-plist)
7565 (to (plist-get p :toaddress))
7566 (from (plist-get p :fromaddress))
7567 (table
7568 (list
7569 (cons "%c" (plist-get p :fromto))
7570 (cons "%F" (plist-get p :from))
7571 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7572 (cons "%T" (plist-get p :to))
7573 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7574 (cons "%s" (plist-get p :subject))
7575 (cons "%m" (plist-get p :message-id)))))
7576 (when (string-match "%c" fmt)
7577 ;; Check if the user wrote this message
7578 (if (and org-from-is-user-regexp from to
7579 (save-match-data (string-match org-from-is-user-regexp from)))
7580 (setq fmt (replace-match "to %t" t t fmt))
7581 (setq fmt (replace-match "from %f" t t fmt))))
7582 (org-replace-escapes fmt table)))
7584 (defun org-make-org-heading-search-string (&optional string heading)
7585 "Make search string for STRING or current headline."
7586 (interactive)
7587 (let ((s (or string (org-get-heading))))
7588 (unless (and string (not heading))
7589 ;; We are using a headline, clean up garbage in there.
7590 (if (string-match org-todo-regexp s)
7591 (setq s (replace-match "" t t s)))
7592 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7593 (setq s (replace-match "" t t s)))
7594 (setq s (org-trim s))
7595 (if (string-match (concat "^\\(" org-quote-string "\\|"
7596 org-comment-string "\\)") s)
7597 (setq s (replace-match "" t t s)))
7598 (while (string-match org-ts-regexp s)
7599 (setq s (replace-match "" t t s))))
7600 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7601 (setq s (replace-match " " t t s)))
7602 (or string (setq s (concat "*" s))) ; Add * for headlines
7603 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7605 (defun org-make-link (&rest strings)
7606 "Concatenate STRINGS."
7607 (apply 'concat strings))
7609 (defun org-make-link-string (link &optional description)
7610 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7611 (unless (string-match "\\S-" link)
7612 (error "Empty link"))
7613 (when (stringp description)
7614 ;; Remove brackets from the description, they are fatal.
7615 (while (string-match "\\[" description)
7616 (setq description (replace-match "{" t t description)))
7617 (while (string-match "\\]" description)
7618 (setq description (replace-match "}" t t description))))
7619 (when (equal (org-link-escape link) description)
7620 ;; No description needed, it is identical
7621 (setq description nil))
7622 (when (and (not description)
7623 (not (equal link (org-link-escape link))))
7624 (setq description (org-extract-attributes link)))
7625 (concat "[[" (org-link-escape link) "]"
7626 (if description (concat "[" description "]") "")
7627 "]"))
7629 (defconst org-link-escape-chars
7630 '((?\ . "%20")
7631 (?\[ . "%5B")
7632 (?\] . "%5D")
7633 (?\340 . "%E0") ; `a
7634 (?\342 . "%E2") ; ^a
7635 (?\347 . "%E7") ; ,c
7636 (?\350 . "%E8") ; `e
7637 (?\351 . "%E9") ; 'e
7638 (?\352 . "%EA") ; ^e
7639 (?\356 . "%EE") ; ^i
7640 (?\364 . "%F4") ; ^o
7641 (?\371 . "%F9") ; `u
7642 (?\373 . "%FB") ; ^u
7643 (?\; . "%3B")
7644 (?? . "%3F")
7645 (?= . "%3D")
7646 (?+ . "%2B")
7648 "Association list of escapes for some characters problematic in links.
7649 This is the list that is used for internal purposes.")
7651 (defvar org-url-encoding-use-url-hexify nil)
7653 (defconst org-link-escape-chars-browser
7654 '((?\ . "%20")) ; 32 for the SPC char
7655 "Association list of escapes for some characters problematic in links.
7656 This is the list that is used before handing over to the browser.")
7658 (defun org-link-escape (text &optional table)
7659 "Escape characters in TEXT that are problematic for links."
7660 (if org-url-encoding-use-url-hexify
7661 (url-hexify-string text)
7662 (setq table (or table org-link-escape-chars))
7663 (when text
7664 (let ((re (mapconcat (lambda (x) (regexp-quote
7665 (char-to-string (car x))))
7666 table "\\|")))
7667 (while (string-match re text)
7668 (setq text
7669 (replace-match
7670 (cdr (assoc (string-to-char (match-string 0 text))
7671 table))
7672 t t text)))
7673 text))))
7675 (defun org-link-unescape (text &optional table)
7676 "Reverse the action of `org-link-escape'."
7677 (if org-url-encoding-use-url-hexify
7678 (url-unhex-string text)
7679 (setq table (or table org-link-escape-chars))
7680 (when text
7681 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7682 table "\\|")))
7683 (while (string-match re text)
7684 (setq text
7685 (replace-match
7686 (char-to-string (car (rassoc (match-string 0 text) table)))
7687 t t text)))
7688 text))))
7690 (defun org-xor (a b)
7691 "Exclusive or."
7692 (if a (not b) b))
7694 (defun org-fixup-message-id-for-http (s)
7695 "Replace special characters in a message id, so it can be used in an http query."
7696 (while (string-match "<" s)
7697 (setq s (replace-match "%3C" t t s)))
7698 (while (string-match ">" s)
7699 (setq s (replace-match "%3E" t t s)))
7700 (while (string-match "@" s)
7701 (setq s (replace-match "%40" t t s)))
7704 ;;;###autoload
7705 (defun org-insert-link-global ()
7706 "Insert a link like Org-mode does.
7707 This command can be called in any mode to insert a link in Org-mode syntax."
7708 (interactive)
7709 (org-load-modules-maybe)
7710 (org-run-like-in-org-mode 'org-insert-link))
7712 (defun org-insert-link (&optional complete-file link-location)
7713 "Insert a link. At the prompt, enter the link.
7715 Completion can be used to insert any of the link protocol prefixes like
7716 http or ftp in use.
7718 The history can be used to select a link previously stored with
7719 `org-store-link'. When the empty string is entered (i.e. if you just
7720 press RET at the prompt), the link defaults to the most recently
7721 stored link. As SPC triggers completion in the minibuffer, you need to
7722 use M-SPC or C-q SPC to force the insertion of a space character.
7724 You will also be prompted for a description, and if one is given, it will
7725 be displayed in the buffer instead of the link.
7727 If there is already a link at point, this command will allow you to edit link
7728 and description parts.
7730 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7731 be selected using completion. The path to the file will be relative to the
7732 current directory if the file is in the current directory or a subdirectory.
7733 Otherwise, the link will be the absolute path as completed in the minibuffer
7734 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7735 option `org-link-file-path-type'.
7737 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7738 the current directory or below.
7740 With three \\[universal-argument] prefixes, negate the meaning of
7741 `org-keep-stored-link-after-insertion'.
7743 If `org-make-link-description-function' is non-nil, this function will be
7744 called with the link target, and the result will be the default
7745 link description.
7747 If the LINK-LOCATION parameter is non-nil, this value will be
7748 used as the link location instead of reading one interactively."
7749 (interactive "P")
7750 (let* ((wcf (current-window-configuration))
7751 (region (if (org-region-active-p)
7752 (buffer-substring (region-beginning) (region-end))))
7753 (remove (and region (list (region-beginning) (region-end))))
7754 (desc region)
7755 tmphist ; byte-compile incorrectly complains about this
7756 (link link-location)
7757 entry file all-prefixes)
7758 (cond
7759 (link-location) ; specified by arg, just use it.
7760 ((org-in-regexp org-bracket-link-regexp 1)
7761 ;; We do have a link at point, and we are going to edit it.
7762 (setq remove (list (match-beginning 0) (match-end 0)))
7763 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7764 (setq link (read-string "Link: "
7765 (org-link-unescape
7766 (org-match-string-no-properties 1)))))
7767 ((or (org-in-regexp org-angle-link-re)
7768 (org-in-regexp org-plain-link-re))
7769 ;; Convert to bracket link
7770 (setq remove (list (match-beginning 0) (match-end 0))
7771 link (read-string "Link: "
7772 (org-remove-angle-brackets (match-string 0)))))
7773 ((member complete-file '((4) (16)))
7774 ;; Completing read for file names.
7775 (setq link (org-file-complete-link complete-file)))
7777 ;; Read link, with completion for stored links.
7778 (with-output-to-temp-buffer "*Org Links*"
7779 (princ "Insert a link.
7780 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7781 (when org-stored-links
7782 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7783 (princ (mapconcat
7784 (lambda (x)
7785 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7786 (reverse org-stored-links) "\n"))))
7787 (let ((cw (selected-window)))
7788 (select-window (get-buffer-window "*Org Links*"))
7789 (setq truncate-lines t)
7790 (unless (pos-visible-in-window-p (point-max))
7791 (org-fit-window-to-buffer))
7792 (and (window-live-p cw) (select-window cw)))
7793 ;; Fake a link history, containing the stored links.
7794 (setq tmphist (append (mapcar 'car org-stored-links)
7795 org-insert-link-history))
7796 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7797 (mapcar 'car org-link-abbrev-alist)
7798 org-link-types))
7799 (unwind-protect
7800 (progn
7801 (setq link
7802 (let ((org-completion-use-ido nil)
7803 (org-completion-use-iswitchb nil))
7804 (org-completing-read
7805 "Link: "
7806 (append
7807 (mapcar (lambda (x) (list (concat x ":")))
7808 all-prefixes)
7809 (mapcar 'car org-stored-links))
7810 nil nil nil
7811 'tmphist
7812 (car (car org-stored-links)))))
7813 (if (or (member link all-prefixes)
7814 (and (equal ":" (substring link -1))
7815 (member (substring link 0 -1) all-prefixes)
7816 (setq link (substring link 0 -1))))
7817 (setq link (org-link-try-special-completion link))))
7818 (set-window-configuration wcf)
7819 (kill-buffer "*Org Links*"))
7820 (setq entry (assoc link org-stored-links))
7821 (or entry (push link org-insert-link-history))
7822 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7823 (not org-keep-stored-link-after-insertion))
7824 (setq org-stored-links (delq (assoc link org-stored-links)
7825 org-stored-links)))
7826 (setq desc (or desc (nth 1 entry)))))
7828 (if (string-match org-plain-link-re link)
7829 ;; URL-like link, normalize the use of angular brackets.
7830 (setq link (org-make-link (org-remove-angle-brackets link))))
7832 ;; Check if we are linking to the current file with a search option
7833 ;; If yes, simplify the link by using only the search option.
7834 (when (and buffer-file-name
7835 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7836 (let* ((path (match-string 1 link))
7837 (case-fold-search nil)
7838 (search (match-string 2 link)))
7839 (save-match-data
7840 (if (equal (file-truename buffer-file-name) (file-truename path))
7841 ;; We are linking to this same file, with a search option
7842 (setq link search)))))
7844 ;; Check if we can/should use a relative path. If yes, simplify the link
7845 (when (string-match "^file:\\(.*\\)" link)
7846 (let* ((path (match-string 1 link))
7847 (origpath path)
7848 (case-fold-search nil))
7849 (cond
7850 ((or (eq org-link-file-path-type 'absolute)
7851 (equal complete-file '(16)))
7852 (setq path (abbreviate-file-name (expand-file-name path))))
7853 ((eq org-link-file-path-type 'noabbrev)
7854 (setq path (expand-file-name path)))
7855 ((eq org-link-file-path-type 'relative)
7856 (setq path (file-relative-name path)))
7858 (save-match-data
7859 (if (string-match (concat "^" (regexp-quote
7860 (file-name-as-directory
7861 (expand-file-name "."))))
7862 (expand-file-name path))
7863 ;; We are linking a file with relative path name.
7864 (setq path (substring (expand-file-name path)
7865 (match-end 0)))
7866 (setq path (abbreviate-file-name (expand-file-name path)))))))
7867 (setq link (concat "file:" path))
7868 (if (equal desc origpath)
7869 (setq desc path))))
7871 (if org-make-link-description-function
7872 (setq desc (funcall org-make-link-description-function link desc)))
7874 (setq desc (read-string "Description: " desc))
7875 (unless (string-match "\\S-" desc) (setq desc nil))
7876 (if remove (apply 'delete-region remove))
7877 (insert (org-make-link-string link desc))))
7879 (defun org-link-try-special-completion (type)
7880 "If there is completion support for link type TYPE, offer it."
7881 (let ((fun (intern (concat "org-" type "-complete-link"))))
7882 (if (functionp fun)
7883 (funcall fun)
7884 (read-string "Link (no completion support): " (concat type ":")))))
7886 (defun org-file-complete-link (&optional arg)
7887 "Create a file link using completion."
7888 (let (file link)
7889 (setq file (read-file-name "File: "))
7890 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7891 (pwd1 (file-name-as-directory (abbreviate-file-name
7892 (expand-file-name ".")))))
7893 (cond
7894 ((equal arg '(16))
7895 (setq link (org-make-link
7896 "file:"
7897 (abbreviate-file-name (expand-file-name file)))))
7898 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7899 (setq link (org-make-link "file:" (match-string 1 file))))
7900 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7901 (expand-file-name file))
7902 (setq link (org-make-link
7903 "file:" (match-string 1 (expand-file-name file)))))
7904 (t (setq link (org-make-link "file:" file)))))
7905 link))
7907 (defun org-completing-read (&rest args)
7908 "Completing-read with SPACE being a normal character."
7909 (let ((minibuffer-local-completion-map
7910 (copy-keymap minibuffer-local-completion-map)))
7911 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7912 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7913 (apply 'org-icompleting-read args)))
7915 (defun org-completing-read-no-i (&rest args)
7916 (let (org-completion-use-ido org-completion-use-iswitchb)
7917 (apply 'org-completing-read args)))
7919 (defun org-iswitchb-completing-read (prompt choices &rest args)
7920 "Use iswitch as a completing-read replacement to choose from choices.
7921 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
7922 from."
7923 (let* ((iswitchb-use-virtual-buffers nil)
7924 (iswitchb-make-buflist-hook
7925 (lambda ()
7926 (setq iswitchb-temp-buflist choices))))
7927 (iswitchb-read-buffer prompt)))
7929 (defun org-icompleting-read (&rest args)
7930 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
7931 (org-without-partial-completion
7932 (if (and org-completion-use-ido
7933 (fboundp 'ido-completing-read)
7934 (boundp 'ido-mode) ido-mode
7935 (listp (second args)))
7936 (let ((ido-enter-matching-directory nil))
7937 (apply 'ido-completing-read (concat (car args))
7938 (if (consp (car (nth 1 args)))
7939 (mapcar (lambda (x) (car x)) (nth 1 args))
7940 (nth 1 args))
7941 (cddr args)))
7942 (if (and org-completion-use-iswitchb
7943 (boundp 'iswitchb-mode) iswitchb-mode
7944 (listp (second args)))
7945 (apply 'org-iswitchb-completing-read (concat (car args))
7946 (if (consp (car (nth 1 args)))
7947 (mapcar (lambda (x) (car x)) (nth 1 args))
7948 (nth 1 args))
7949 (cddr args))
7950 (apply 'completing-read args)))))
7952 (defun org-extract-attributes (s)
7953 "Extract the attributes cookie from a string and set as text property."
7954 (let (a attr (start 0) key value)
7955 (save-match-data
7956 (when (string-match "{{\\([^}]+\\)}}$" s)
7957 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7958 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7959 (setq key (match-string 1 a) value (match-string 2 a)
7960 start (match-end 0)
7961 attr (plist-put attr (intern key) value))))
7962 (org-add-props s nil 'org-attr attr))
7965 (defun org-extract-attributes-from-string (tag)
7966 (let (key value attr)
7967 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7968 (setq key (match-string 1 tag) value (match-string 2 tag)
7969 tag (replace-match "" t t tag)
7970 attr (plist-put attr (intern key) value)))
7971 (cons tag attr)))
7973 (defun org-attributes-to-string (plist)
7974 "Format a property list into an HTML attribute list."
7975 (let ((s "") key value)
7976 (while plist
7977 (setq key (pop plist) value (pop plist))
7978 (and value
7979 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7982 ;;; Opening/following a link
7984 (defvar org-link-search-failed nil)
7986 (defun org-next-link ()
7987 "Move forward to the next link.
7988 If the link is in hidden text, expose it."
7989 (interactive)
7990 (when (and org-link-search-failed (eq this-command last-command))
7991 (goto-char (point-min))
7992 (message "Link search wrapped back to beginning of buffer"))
7993 (setq org-link-search-failed nil)
7994 (let* ((pos (point))
7995 (ct (org-context))
7996 (a (assoc :link ct)))
7997 (if a (goto-char (nth 2 a)))
7998 (if (re-search-forward org-any-link-re nil t)
7999 (progn
8000 (goto-char (match-beginning 0))
8001 (if (org-invisible-p) (org-show-context)))
8002 (goto-char pos)
8003 (setq org-link-search-failed t)
8004 (error "No further link found"))))
8006 (defun org-previous-link ()
8007 "Move backward to the previous link.
8008 If the link is in hidden text, expose it."
8009 (interactive)
8010 (when (and org-link-search-failed (eq this-command last-command))
8011 (goto-char (point-max))
8012 (message "Link search wrapped back to end of buffer"))
8013 (setq org-link-search-failed nil)
8014 (let* ((pos (point))
8015 (ct (org-context))
8016 (a (assoc :link ct)))
8017 (if a (goto-char (nth 1 a)))
8018 (if (re-search-backward org-any-link-re nil t)
8019 (progn
8020 (goto-char (match-beginning 0))
8021 (if (org-invisible-p) (org-show-context)))
8022 (goto-char pos)
8023 (setq org-link-search-failed t)
8024 (error "No further link found"))))
8026 (defun org-translate-link (s)
8027 "Translate a link string if a translation function has been defined."
8028 (if (and org-link-translation-function
8029 (fboundp org-link-translation-function)
8030 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8031 (progn
8032 (setq s (funcall org-link-translation-function
8033 (match-string 1) (match-string 2)))
8034 (concat (car s) ":" (cdr s)))
8037 (defun org-translate-link-from-planner (type path)
8038 "Translate a link from Emacs Planner syntax so that Org can follow it.
8039 This is still an experimental function, your mileage may vary."
8040 (cond
8041 ((member type '("http" "https" "news" "ftp"))
8042 ;; standard Internet links are the same.
8043 nil)
8044 ((and (equal type "irc") (string-match "^//" path))
8045 ;; Planner has two / at the beginning of an irc link, we have 1.
8046 ;; We should have zero, actually....
8047 (setq path (substring path 1)))
8048 ((and (equal type "lisp") (string-match "^/" path))
8049 ;; Planner has a slash, we do not.
8050 (setq type "elisp" path (substring path 1)))
8051 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8052 ;; A typical message link. Planner has the id after the fina slash,
8053 ;; we separate it with a hash mark
8054 (setq path (concat (match-string 1 path) "#"
8055 (org-remove-angle-brackets (match-string 2 path)))))
8057 (cons type path))
8059 (defun org-find-file-at-mouse (ev)
8060 "Open file link or URL at mouse."
8061 (interactive "e")
8062 (mouse-set-point ev)
8063 (org-open-at-point 'in-emacs))
8065 (defun org-open-at-mouse (ev)
8066 "Open file link or URL at mouse."
8067 (interactive "e")
8068 (mouse-set-point ev)
8069 (if (eq major-mode 'org-agenda-mode)
8070 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8071 (org-open-at-point))
8073 (defvar org-window-config-before-follow-link nil
8074 "The window configuration before following a link.
8075 This is saved in case the need arises to restore it.")
8077 (defvar org-open-link-marker (make-marker)
8078 "Marker pointing to the location where `org-open-at-point; was called.")
8080 ;;;###autoload
8081 (defun org-open-at-point-global ()
8082 "Follow a link like Org-mode does.
8083 This command can be called in any mode to follow a link that has
8084 Org-mode syntax."
8085 (interactive)
8086 (org-run-like-in-org-mode 'org-open-at-point))
8088 ;;;###autoload
8089 (defun org-open-link-from-string (s &optional arg reference-buffer)
8090 "Open a link in the string S, as if it was in Org-mode."
8091 (interactive "sLink: \nP")
8092 (let ((reference-buffer (or reference-buffer (current-buffer))))
8093 (with-temp-buffer
8094 (let ((org-inhibit-startup t))
8095 (org-mode)
8096 (insert s)
8097 (goto-char (point-min))
8098 (org-open-at-point arg reference-buffer)))))
8100 (defun org-open-at-point (&optional in-emacs reference-buffer)
8101 "Open link at or after point.
8102 If there is no link at point, this function will search forward up to
8103 the end of the current line.
8104 Normally, files will be opened by an appropriate application. If the
8105 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8106 With a double prefix argument, try to open outside of Emacs, in the
8107 application the system uses for this file type."
8108 (interactive "P")
8109 (org-load-modules-maybe)
8110 (move-marker org-open-link-marker (point))
8111 (setq org-window-config-before-follow-link (current-window-configuration))
8112 (org-remove-occur-highlights nil nil t)
8113 (cond
8114 ((and (org-on-heading-p)
8115 (not (org-in-regexp
8116 (concat org-plain-link-re "\\|"
8117 org-bracket-link-regexp "\\|"
8118 org-angle-link-re "\\|"
8119 "[ \t]:[^ \t\n]+:[ \t]*$"))))
8120 (or (org-offer-links-in-entry in-emacs)
8121 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8122 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8123 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8124 (org-footnote-action))
8126 (let (type path link line search (pos (point)))
8127 (catch 'match
8128 (save-excursion
8129 (skip-chars-forward "^]\n\r")
8130 (when (org-in-regexp org-bracket-link-regexp)
8131 (setq link (org-extract-attributes
8132 (org-link-unescape (org-match-string-no-properties 1))))
8133 (while (string-match " *\n *" link)
8134 (setq link (replace-match " " t t link)))
8135 (setq link (org-link-expand-abbrev link))
8136 (cond
8137 ((or (file-name-absolute-p link)
8138 (string-match "^\\.\\.?/" link))
8139 (setq type "file" path link))
8140 ((string-match org-link-re-with-space3 link)
8141 (setq type (match-string 1 link) path (match-string 2 link)))
8142 (t (setq type "thisfile" path link)))
8143 (throw 'match t)))
8145 (when (get-text-property (point) 'org-linked-text)
8146 (setq type "thisfile"
8147 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8148 (1+ (point)) (point))
8149 path (buffer-substring
8150 (previous-single-property-change pos 'org-linked-text)
8151 (next-single-property-change pos 'org-linked-text)))
8152 (throw 'match t))
8154 (save-excursion
8155 (when (or (org-in-regexp org-angle-link-re)
8156 (org-in-regexp org-plain-link-re))
8157 (setq type (match-string 1) path (match-string 2))
8158 (throw 'match t)))
8159 (save-excursion
8160 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8161 (setq type "tags"
8162 path (match-string 1))
8163 (while (string-match ":" path)
8164 (setq path (replace-match "+" t t path)))
8165 (throw 'match t)))
8166 (when (org-in-regexp "<\\([^><\n]+\\)>")
8167 (setq type "tree-match"
8168 path (match-string 1))
8169 (throw 'match t)))
8170 (unless path
8171 (error "No link found"))
8173 ;; switch back to reference buffer
8174 ;; needed when if called in a temporary buffer through
8175 ;; org-open-link-from-string
8176 (with-current-buffer (or reference-buffer (current-buffer))
8178 ;; Remove any trailing spaces in path
8179 (if (string-match " +\\'" path)
8180 (setq path (replace-match "" t t path)))
8181 (if (and org-link-translation-function
8182 (fboundp org-link-translation-function))
8183 ;; Check if we need to translate the link
8184 (let ((tmp (funcall org-link-translation-function type path)))
8185 (setq type (car tmp) path (cdr tmp))))
8187 (cond
8189 ((assoc type org-link-protocols)
8190 (funcall (nth 1 (assoc type org-link-protocols)) path))
8192 ((equal type "mailto")
8193 (let ((cmd (car org-link-mailto-program))
8194 (args (cdr org-link-mailto-program)) args1
8195 (address path) (subject "") a)
8196 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8197 (setq address (match-string 1 path)
8198 subject (org-link-escape (match-string 2 path))))
8199 (while args
8200 (cond
8201 ((not (stringp (car args))) (push (pop args) args1))
8202 (t (setq a (pop args))
8203 (if (string-match "%a" a)
8204 (setq a (replace-match address t t a)))
8205 (if (string-match "%s" a)
8206 (setq a (replace-match subject t t a)))
8207 (push a args1))))
8208 (apply cmd (nreverse args1))))
8210 ((member type '("http" "https" "ftp" "news"))
8211 (browse-url (concat type ":" (org-link-escape
8212 path org-link-escape-chars-browser))))
8214 ((member type '("message"))
8215 (browse-url (concat type ":" path)))
8217 ((string= type "tags")
8218 (org-tags-view in-emacs path))
8219 ((string= type "thisfile")
8220 (if in-emacs
8221 (switch-to-buffer-other-window
8222 (org-get-buffer-for-internal-link (current-buffer)))
8223 (org-mark-ring-push))
8224 (let ((cmd `(org-link-search
8225 ,path
8226 ,(cond ((equal in-emacs '(4)) 'occur)
8227 ((equal in-emacs '(16)) 'org-occur)
8228 (t nil))
8229 ,pos)))
8230 (condition-case nil (eval cmd)
8231 (error (progn (widen) (eval cmd))))))
8233 ((string= type "tree-match")
8234 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8236 ((string= type "file")
8237 (if (string-match "::\\([0-9]+\\)\\'" path)
8238 (setq line (string-to-number (match-string 1 path))
8239 path (substring path 0 (match-beginning 0)))
8240 (if (string-match "::\\(.+\\)\\'" path)
8241 (setq search (match-string 1 path)
8242 path (substring path 0 (match-beginning 0)))))
8243 (if (string-match "[*?{]" (file-name-nondirectory path))
8244 (dired path)
8245 (org-open-file path in-emacs line search)))
8247 ((string= type "news")
8248 (require 'org-gnus)
8249 (org-gnus-follow-link path))
8251 ((string= type "shell")
8252 (let ((cmd path))
8253 (if (or (not org-confirm-shell-link-function)
8254 (funcall org-confirm-shell-link-function
8255 (format "Execute \"%s\" in shell? "
8256 (org-add-props cmd nil
8257 'face 'org-warning))))
8258 (progn
8259 (message "Executing %s" cmd)
8260 (shell-command cmd))
8261 (error "Abort"))))
8263 ((string= type "elisp")
8264 (let ((cmd path))
8265 (if (or (not org-confirm-elisp-link-function)
8266 (funcall org-confirm-elisp-link-function
8267 (format "Execute \"%s\" as elisp? "
8268 (org-add-props cmd nil
8269 'face 'org-warning))))
8270 (message "%s => %s" cmd
8271 (if (equal (string-to-char cmd) ?\()
8272 (eval (read cmd))
8273 (call-interactively (read cmd))))
8274 (error "Abort"))))
8277 (browse-url-at-point)))))))
8278 (move-marker org-open-link-marker nil)
8279 (run-hook-with-args 'org-follow-link-hook))
8281 (defun org-offer-links-in-entry (&optional nth zero)
8282 "Offer links in the curren entry and follow the selected link.
8283 If there is only one link, follow it immediately as well.
8284 If NTH is an integer, immediately pick the NTH link found.
8285 If ZERO is a string, check also this string for a link, and if
8286 there is one, offer it as link number zero."
8287 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8288 "\\(" org-angle-link-re "\\)\\|"
8289 "\\(" org-plain-link-re "\\)"))
8290 (cnt ?0)
8291 (in-emacs (if (integerp nth) nil nth))
8292 have-zero end links link c)
8293 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8294 (push (match-string 0 zero) links)
8295 (setq cnt (1- cnt) have-zero t))
8296 (save-excursion
8297 (org-back-to-heading t)
8298 (setq end (save-excursion (outline-next-heading) (point)))
8299 (while (re-search-forward re end t)
8300 (push (match-string 0) links))
8301 (setq links (org-uniquify (reverse links))))
8303 (cond
8304 ((null links)
8305 (message "No links"))
8306 ((equal (length links) 1)
8307 (setq link (car links)))
8308 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8309 (setq link (nth (if have-zero nth (1- nth)) links)))
8310 (t ; we have to select a link
8311 (save-excursion
8312 (save-window-excursion
8313 (delete-other-windows)
8314 (with-output-to-temp-buffer "*Select Link*"
8315 (mapc (lambda (l)
8316 (if (not (string-match org-bracket-link-regexp l))
8317 (princ (format "[%c] %s\n" (incf cnt)
8318 (org-remove-angle-brackets l)))
8319 (if (match-end 3)
8320 (princ (format "[%c] %s (%s)\n" (incf cnt)
8321 (match-string 3 l) (match-string 1 l)))
8322 (princ (format "[%c] %s\n" (incf cnt)
8323 (match-string 1 l))))))
8324 links))
8325 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8326 (message "Select link to open:")
8327 (setq c (read-char-exclusive))
8328 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8329 (when (equal c ?q) (error "Abort"))
8330 (setq nth (- c ?0))
8331 (if have-zero (setq nth (1+ nth)))
8332 (unless (and (integerp nth) (>= (length links) nth))
8333 (error "Invalid link selection"))
8334 (setq link (nth (1- nth) links))))
8335 (if link
8336 (progn (org-open-link-from-string link in-emacs (current-buffer)) t)
8337 nil)))
8339 ;;;; Time estimates
8341 (defun org-get-effort (&optional pom)
8342 "Get the effort estimate for the current entry."
8343 (org-entry-get pom org-effort-property))
8345 ;;; File search
8347 (defvar org-create-file-search-functions nil
8348 "List of functions to construct the right search string for a file link.
8349 These functions are called in turn with point at the location to
8350 which the link should point.
8352 A function in the hook should first test if it would like to
8353 handle this file type, for example by checking the major-mode or
8354 the file extension. If it decides not to handle this file, it
8355 should just return nil to give other functions a chance. If it
8356 does handle the file, it must return the search string to be used
8357 when following the link. The search string will be part of the
8358 file link, given after a double colon, and `org-open-at-point'
8359 will automatically search for it. If special measures must be
8360 taken to make the search successful, another function should be
8361 added to the companion hook `org-execute-file-search-functions',
8362 which see.
8364 A function in this hook may also use `setq' to set the variable
8365 `description' to provide a suggestion for the descriptive text to
8366 be used for this link when it gets inserted into an Org-mode
8367 buffer with \\[org-insert-link].")
8369 (defvar org-execute-file-search-functions nil
8370 "List of functions to execute a file search triggered by a link.
8372 Functions added to this hook must accept a single argument, the
8373 search string that was part of the file link, the part after the
8374 double colon. The function must first check if it would like to
8375 handle this search, for example by checking the major-mode or the
8376 file extension. If it decides not to handle this search, it
8377 should just return nil to give other functions a chance. If it
8378 does handle the search, it must return a non-nil value to keep
8379 other functions from trying.
8381 Each function can access the current prefix argument through the
8382 variable `current-prefix-argument'. Note that a single prefix is
8383 used to force opening a link in Emacs, so it may be good to only
8384 use a numeric or double prefix to guide the search function.
8386 In case this is needed, a function in this hook can also restore
8387 the window configuration before `org-open-at-point' was called using:
8389 (set-window-configuration org-window-config-before-follow-link)")
8391 (defun org-link-search (s &optional type avoid-pos)
8392 "Search for a link search option.
8393 If S is surrounded by forward slashes, it is interpreted as a
8394 regular expression. In org-mode files, this will create an `org-occur'
8395 sparse tree. In ordinary files, `occur' will be used to list matches.
8396 If the current buffer is in `dired-mode', grep will be used to search
8397 in all files. If AVOID-POS is given, ignore matches near that position."
8398 (let ((case-fold-search t)
8399 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8400 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8401 (append '(("") (" ") ("\t") ("\n"))
8402 org-emphasis-alist)
8403 "\\|") "\\)"))
8404 (pos (point))
8405 (pre nil) (post nil)
8406 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8407 (cond
8408 ;; First check if there are any special
8409 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8410 ;; Now try the builtin stuff
8411 ((and (equal (string-to-char s0) ?#)
8412 (> (length s0) 1)
8413 (save-excursion
8414 (goto-char (point-min))
8415 (and
8416 (re-search-forward
8417 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8418 (setq type 'dedicated
8419 pos (match-beginning 0))))
8420 ;; There is an exact target for this
8421 (goto-char pos)
8422 (org-back-to-heading t)))
8423 ((save-excursion
8424 (goto-char (point-min))
8425 (and
8426 (re-search-forward
8427 (concat "<<" (regexp-quote s0) ">>") nil t)
8428 (setq type 'dedicated
8429 pos (match-beginning 0))))
8430 ;; There is an exact target for this
8431 (goto-char pos))
8432 ((and (string-match "^(\\(.*\\))$" s0)
8433 (save-excursion
8434 (goto-char (point-min))
8435 (and
8436 (re-search-forward
8437 (concat "[^[]" (regexp-quote
8438 (format org-coderef-label-format
8439 (match-string 1 s0))))
8440 nil t)
8441 (setq type 'dedicated
8442 pos (1+ (match-beginning 0))))))
8443 ;; There is a coderef target for this
8444 (goto-char pos))
8445 ((string-match "^/\\(.*\\)/$" s)
8446 ;; A regular expression
8447 (cond
8448 ((org-mode-p)
8449 (org-occur (match-string 1 s)))
8450 ;;((eq major-mode 'dired-mode)
8451 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8452 (t (org-do-occur (match-string 1 s)))))
8454 ;; A normal search strings
8455 (when (equal (string-to-char s) ?*)
8456 ;; Anchor on headlines, post may include tags.
8457 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8458 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8459 s (substring s 1)))
8460 (remove-text-properties
8461 0 (length s)
8462 '(face nil mouse-face nil keymap nil fontified nil) s)
8463 ;; Make a series of regular expressions to find a match
8464 (setq words (org-split-string s "[ \n\r\t]+")
8466 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8467 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8468 "\\)" markers)
8469 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8470 re2a (concat "[ \t\r\n]" re2a_)
8471 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8472 re4 (concat "[^a-zA-Z_]" re4_)
8474 re1 (concat pre re2 post)
8475 re3 (concat pre (if pre re4_ re4) post)
8476 re5 (concat pre ".*" re4)
8477 re2 (concat pre re2)
8478 re2a (concat pre (if pre re2a_ re2a))
8479 re4 (concat pre (if pre re4_ re4))
8480 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8481 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8482 re5 "\\)"
8484 (cond
8485 ((eq type 'org-occur) (org-occur reall))
8486 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8487 (t (goto-char (point-min))
8488 (setq type 'fuzzy)
8489 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8490 (org-search-not-self 1 re1 nil t)
8491 (org-search-not-self 1 re2 nil t)
8492 (org-search-not-self 1 re2a nil t)
8493 (org-search-not-self 1 re3 nil t)
8494 (org-search-not-self 1 re4 nil t)
8495 (org-search-not-self 1 re5 nil t)
8497 (goto-char (match-beginning 1))
8498 (goto-char pos)
8499 (error "No match")))))
8501 ;; Normal string-search
8502 (goto-char (point-min))
8503 (if (search-forward s nil t)
8504 (goto-char (match-beginning 0))
8505 (error "No match"))))
8506 (and (org-mode-p) (org-show-context 'link-search))
8507 type))
8509 (defun org-search-not-self (group &rest args)
8510 "Execute `re-search-forward', but only accept matches that do not
8511 enclose the position of `org-open-link-marker'."
8512 (let ((m org-open-link-marker))
8513 (catch 'exit
8514 (while (apply 're-search-forward args)
8515 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8516 (goto-char (match-end group))
8517 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8518 (> (match-beginning 0) (marker-position m))
8519 (< (match-end 0) (marker-position m)))
8520 (save-match-data
8521 (or (not (org-in-regexp
8522 org-bracket-link-analytic-regexp 1))
8523 (not (match-end 4)) ; no description
8524 (and (<= (match-beginning 4) (point))
8525 (>= (match-end 4) (point))))))
8526 (throw 'exit (point))))))))
8528 (defun org-get-buffer-for-internal-link (buffer)
8529 "Return a buffer to be used for displaying the link target of internal links."
8530 (cond
8531 ((not org-display-internal-link-with-indirect-buffer)
8532 buffer)
8533 ((string-match "(Clone)$" (buffer-name buffer))
8534 (message "Buffer is already a clone, not making another one")
8535 ;; we also do not modify visibility in this case
8536 buffer)
8537 (t ; make a new indirect buffer for displaying the link
8538 (let* ((bn (buffer-name buffer))
8539 (ibn (concat bn "(Clone)"))
8540 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8541 (with-current-buffer ib (org-overview))
8542 ib))))
8544 (defun org-do-occur (regexp &optional cleanup)
8545 "Call the Emacs command `occur'.
8546 If CLEANUP is non-nil, remove the printout of the regular expression
8547 in the *Occur* buffer. This is useful if the regex is long and not useful
8548 to read."
8549 (occur regexp)
8550 (when cleanup
8551 (let ((cwin (selected-window)) win beg end)
8552 (when (setq win (get-buffer-window "*Occur*"))
8553 (select-window win))
8554 (goto-char (point-min))
8555 (when (re-search-forward "match[a-z]+" nil t)
8556 (setq beg (match-end 0))
8557 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8558 (setq end (1- (match-beginning 0)))))
8559 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8560 (goto-char (point-min))
8561 (select-window cwin))))
8563 ;;; The mark ring for links jumps
8565 (defvar org-mark-ring nil
8566 "Mark ring for positions before jumps in Org-mode.")
8567 (defvar org-mark-ring-last-goto nil
8568 "Last position in the mark ring used to go back.")
8569 ;; Fill and close the ring
8570 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8571 (loop for i from 1 to org-mark-ring-length do
8572 (push (make-marker) org-mark-ring))
8573 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8574 org-mark-ring)
8576 (defun org-mark-ring-push (&optional pos buffer)
8577 "Put the current position or POS into the mark ring and rotate it."
8578 (interactive)
8579 (setq pos (or pos (point)))
8580 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8581 (move-marker (car org-mark-ring)
8582 (or pos (point))
8583 (or buffer (current-buffer)))
8584 (message "%s"
8585 (substitute-command-keys
8586 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8588 (defun org-mark-ring-goto (&optional n)
8589 "Jump to the previous position in the mark ring.
8590 With prefix arg N, jump back that many stored positions. When
8591 called several times in succession, walk through the entire ring.
8592 Org-mode commands jumping to a different position in the current file,
8593 or to another Org-mode file, automatically push the old position
8594 onto the ring."
8595 (interactive "p")
8596 (let (p m)
8597 (if (eq last-command this-command)
8598 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8599 (setq p org-mark-ring))
8600 (setq org-mark-ring-last-goto p)
8601 (setq m (car p))
8602 (switch-to-buffer (marker-buffer m))
8603 (goto-char m)
8604 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8606 (defun org-remove-angle-brackets (s)
8607 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8608 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8610 (defun org-add-angle-brackets (s)
8611 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8612 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8614 (defun org-remove-double-quotes (s)
8615 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8616 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8619 ;;; Following specific links
8621 (defun org-follow-timestamp-link ()
8622 (cond
8623 ((org-at-date-range-p t)
8624 (let ((org-agenda-start-on-weekday)
8625 (t1 (match-string 1))
8626 (t2 (match-string 2)))
8627 (setq t1 (time-to-days (org-time-string-to-time t1))
8628 t2 (time-to-days (org-time-string-to-time t2)))
8629 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8630 ((org-at-timestamp-p t)
8631 (org-agenda-list nil (time-to-days (org-time-string-to-time
8632 (substring (match-string 1) 0 10)))
8634 (t (error "This should not happen"))))
8637 ;;; Following file links
8638 (defvar org-wait nil)
8639 (defun org-open-file (path &optional in-emacs line search)
8640 "Open the file at PATH.
8641 First, this expands any special file name abbreviations. Then the
8642 configuration variable `org-file-apps' is checked if it contains an
8643 entry for this file type, and if yes, the corresponding command is launched.
8645 If no application is found, Emacs simply visits the file.
8647 With optional prefix argument IN-EMACS, Emacs will visit the file.
8648 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8649 and o use an external application to visit the file.
8651 Optional LINE specifies a line to go to, optional SEARCH a string to
8652 search for. If LINE or SEARCH is given, the file will always be
8653 opened in Emacs.
8654 If the file does not exist, an error is thrown."
8655 (setq in-emacs (or in-emacs line search))
8656 (let* ((file (if (equal path "")
8657 buffer-file-name
8658 (substitute-in-file-name (expand-file-name path))))
8659 (apps (append org-file-apps (org-default-apps)))
8660 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8661 (dirp (if remp nil (file-directory-p file)))
8662 (file (if (and dirp org-open-directory-means-index-dot-org)
8663 (concat (file-name-as-directory file) "index.org")
8664 file))
8665 (a-m-a-p (assq 'auto-mode apps))
8666 (dfile (downcase file))
8667 (old-buffer (current-buffer))
8668 (old-pos (point))
8669 (old-mode major-mode)
8670 ext cmd)
8671 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8672 (setq ext (match-string 1 dfile))
8673 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8674 (setq ext (match-string 1 dfile))))
8675 (cond
8676 ((equal in-emacs '(16))
8677 (setq cmd (cdr (assoc 'system apps))))
8678 (in-emacs (setq cmd 'emacs))
8680 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8681 (and dirp (cdr (assoc 'directory apps)))
8682 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8683 'string-match)
8684 (cdr (assoc ext apps))
8685 (cdr (assoc t apps))))))
8686 (when (eq cmd 'system)
8687 (setq cmd (cdr (assoc 'system apps))))
8688 (when (eq cmd 'default)
8689 (setq cmd (cdr (assoc t apps))))
8690 (when (eq cmd 'mailcap)
8691 (require 'mailcap)
8692 (mailcap-parse-mailcaps)
8693 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8694 (command (mailcap-mime-info mime-type)))
8695 (if (stringp command)
8696 (setq cmd command)
8697 (setq cmd 'emacs))))
8698 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8699 (not (file-exists-p file))
8700 (not org-open-non-existing-files))
8701 (error "No such file: %s" file))
8702 (cond
8703 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8704 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8705 (while (string-match "['\"]%s['\"]" cmd)
8706 (setq cmd (replace-match "%s" t t cmd)))
8707 (while (string-match "%s" cmd)
8708 (setq cmd (replace-match
8709 (save-match-data
8710 (shell-quote-argument
8711 (convert-standard-filename file)))
8712 t t cmd)))
8713 (save-window-excursion
8714 (start-process-shell-command cmd nil cmd)
8715 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8717 ((or (stringp cmd)
8718 (eq cmd 'emacs))
8719 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8720 (widen)
8721 (if line (org-goto-line line)
8722 (if search (org-link-search search))))
8723 ((consp cmd)
8724 (let ((file (convert-standard-filename file)))
8725 (eval cmd)))
8726 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8727 (and (org-mode-p) (eq old-mode 'org-mode)
8728 (or (not (equal old-buffer (current-buffer)))
8729 (not (equal old-pos (point))))
8730 (org-mark-ring-push old-pos old-buffer))))
8732 (defun org-default-apps ()
8733 "Return the default applications for this operating system."
8734 (cond
8735 ((eq system-type 'darwin)
8736 org-file-apps-defaults-macosx)
8737 ((eq system-type 'windows-nt)
8738 org-file-apps-defaults-windowsnt)
8739 (t org-file-apps-defaults-gnu)))
8741 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8742 "Convert extensions to regular expressions in the cars of LIST.
8743 Also, weed out any non-string entries, because the return value is used
8744 only for regexp matching.
8745 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8746 point to the symbol `emacs', indicating that the file should
8747 be opened in Emacs."
8748 (append
8749 (delq nil
8750 (mapcar (lambda (x)
8751 (if (not (stringp (car x)))
8753 (if (string-match "\\W" (car x))
8755 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8756 list))
8757 (if add-auto-mode
8758 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8760 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8761 (defun org-file-remote-p (file)
8762 "Test whether FILE specifies a location on a remote system.
8763 Return non-nil if the location is indeed remote.
8765 For example, the filename \"/user@host:/foo\" specifies a location
8766 on the system \"/user@host:\"."
8767 (cond ((fboundp 'file-remote-p)
8768 (file-remote-p file))
8769 ((fboundp 'tramp-handle-file-remote-p)
8770 (tramp-handle-file-remote-p file))
8771 ((and (boundp 'ange-ftp-name-format)
8772 (string-match (car ange-ftp-name-format) file))
8774 (t nil)))
8777 ;;;; Refiling
8779 (defun org-get-org-file ()
8780 "Read a filename, with default directory `org-directory'."
8781 (let ((default (or org-default-notes-file remember-data-file)))
8782 (read-file-name (format "File name [%s]: " default)
8783 (file-name-as-directory org-directory)
8784 default)))
8786 (defun org-notes-order-reversed-p ()
8787 "Check if the current file should receive notes in reversed order."
8788 (cond
8789 ((not org-reverse-note-order) nil)
8790 ((eq t org-reverse-note-order) t)
8791 ((not (listp org-reverse-note-order)) nil)
8792 (t (catch 'exit
8793 (let ((all org-reverse-note-order)
8794 entry)
8795 (while (setq entry (pop all))
8796 (if (string-match (car entry) buffer-file-name)
8797 (throw 'exit (cdr entry))))
8798 nil)))))
8800 (defvar org-refile-target-table nil
8801 "The list of refile targets, created by `org-refile'.")
8803 (defvar org-agenda-new-buffers nil
8804 "Buffers created to visit agenda files.")
8806 (defun org-get-refile-targets (&optional default-buffer)
8807 "Produce a table with refile targets."
8808 (let ((case-fold-search nil)
8809 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8810 (entries (or org-refile-targets '((nil . (:level . 1)))))
8811 targets txt re files f desc descre fast-path-p level pos0)
8812 (message "Getting targets...")
8813 (with-current-buffer (or default-buffer (current-buffer))
8814 (while (setq entry (pop entries))
8815 (setq files (car entry) desc (cdr entry))
8816 (setq fast-path-p nil)
8817 (cond
8818 ((null files) (setq files (list (current-buffer))))
8819 ((eq files 'org-agenda-files)
8820 (setq files (org-agenda-files 'unrestricted)))
8821 ((and (symbolp files) (fboundp files))
8822 (setq files (funcall files)))
8823 ((and (symbolp files) (boundp files))
8824 (setq files (symbol-value files))))
8825 (if (stringp files) (setq files (list files)))
8826 (cond
8827 ((eq (car desc) :tag)
8828 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8829 ((eq (car desc) :todo)
8830 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8831 ((eq (car desc) :regexp)
8832 (setq descre (cdr desc)))
8833 ((eq (car desc) :level)
8834 (setq descre (concat "^\\*\\{" (number-to-string
8835 (if org-odd-levels-only
8836 (1- (* 2 (cdr desc)))
8837 (cdr desc)))
8838 "\\}[ \t]")))
8839 ((eq (car desc) :maxlevel)
8840 (setq fast-path-p t)
8841 (setq descre (concat "^\\*\\{1," (number-to-string
8842 (if org-odd-levels-only
8843 (1- (* 2 (cdr desc)))
8844 (cdr desc)))
8845 "\\}[ \t]")))
8846 (t (error "Bad refiling target description %s" desc)))
8847 (while (setq f (pop files))
8848 (with-current-buffer
8849 (if (bufferp f) f (org-get-agenda-file-buffer f))
8850 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8851 (setq f (expand-file-name f))
8852 (if (eq org-refile-use-outline-path 'file)
8853 (push (list (file-name-nondirectory f) f nil nil) targets))
8854 (save-excursion
8855 (save-restriction
8856 (widen)
8857 (goto-char (point-min))
8858 (while (re-search-forward descre nil t)
8859 (goto-char (setq pos0 (point-at-bol)))
8860 (catch 'next
8861 (when org-refile-target-verify-function
8862 (save-match-data
8863 (or (funcall org-refile-target-verify-function)
8864 (throw 'next t))))
8865 (when (looking-at org-complex-heading-regexp)
8866 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8867 txt (org-link-display-format (match-string 4))
8868 re (concat "^" (regexp-quote
8869 (buffer-substring (match-beginning 1)
8870 (match-end 4)))))
8871 (if (match-end 5) (setq re (concat re "[ \t]+"
8872 (regexp-quote
8873 (match-string 5)))))
8874 (setq re (concat re "[ \t]*$"))
8875 (when org-refile-use-outline-path
8876 (setq txt (mapconcat 'org-protect-slash
8877 (append
8878 (if (eq org-refile-use-outline-path 'file)
8879 (list (file-name-nondirectory
8880 (buffer-file-name (buffer-base-buffer))))
8881 (if (eq org-refile-use-outline-path 'full-file-path)
8882 (list (buffer-file-name (buffer-base-buffer)))))
8883 (org-get-outline-path fast-path-p level txt)
8884 (list txt))
8885 "/")))
8886 (push (list txt f re (point)) targets)))
8887 (when (= (point) pos0)
8888 ;; verification function has not moved point
8889 (goto-char (point-at-eol))))))))))
8890 (message "Getting targets...done")
8891 (nreverse targets)))
8893 (defun org-protect-slash (s)
8894 (while (string-match "/" s)
8895 (setq s (replace-match "\\" t t s)))
8898 (defvar org-olpa (make-vector 20 nil))
8900 (defun org-get-outline-path (&optional fastp level heading)
8901 "Return the outline path to the current entry, as a list."
8902 (if fastp
8903 (progn
8904 (if (> level 19)
8905 (error "Outline path failure, more than 19 levels."))
8906 (loop for i from level upto 19 do
8907 (aset org-olpa i nil))
8908 (prog1
8909 (delq nil (append org-olpa nil))
8910 (aset org-olpa level heading)))
8911 (let (rtn)
8912 (save-excursion
8913 (while (org-up-heading-safe)
8914 (when (looking-at org-complex-heading-regexp)
8915 (push (org-match-string-no-properties 4) rtn)))
8916 rtn))))
8918 (defvar org-refile-history nil
8919 "History for refiling operations.")
8921 (defvar org-after-refile-insert-hook nil
8922 "Hook run after `org-refile' has inserted its stuff at the new location.
8923 Note that this is still *before* the stuff will be removed from
8924 the *old* location.")
8926 (defun org-refile (&optional goto default-buffer rfloc)
8927 "Move the entry at point to another heading.
8928 The list of target headings is compiled using the information in
8929 `org-refile-targets', which see. This list is created before each use
8930 and will therefore always be up-to-date.
8932 At the target location, the entry is filed as a subitem of the target heading.
8933 Depending on `org-reverse-note-order', the new subitem will either be the
8934 first or the last subitem.
8936 If there is an active region, all entries in that region will be moved.
8937 However, the region must fulfil the requirement that the first heading
8938 is the first one sets the top-level of the moved text - at most siblings
8939 below it are allowed.
8941 With prefix arg GOTO, the command will only visit the target location,
8942 not actually move anything.
8943 With a double prefix `C-u C-u', go to the location where the last refiling
8944 operation has put the subtree.
8945 With a prefix argument of `2', refile to the running clock.
8947 RFLOC can be a refile location obtained in a different way.
8949 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8950 (interactive "P")
8951 (let* ((cbuf (current-buffer))
8952 (regionp (org-region-active-p))
8953 (region-start (and regionp (region-beginning)))
8954 (region-end (and regionp (region-end)))
8955 (region-length (and regionp (- region-end region-start)))
8956 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8957 pos it nbuf file re level reversed)
8958 (when regionp
8959 (goto-char region-start)
8960 (or (bolp) (goto-char (point-at-bol)))
8961 (setq region-start (point))
8962 (unless (org-kill-is-subtree-p
8963 (buffer-substring region-start region-end))
8964 (error "The region is not a (sequence of) subtree(s)")))
8965 (if (equal goto '(16))
8966 (org-refile-goto-last-stored)
8967 (when (or
8968 (and (equal goto 2)
8969 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
8970 (prog1
8971 (setq it (list (or org-clock-heading "running clock")
8972 (buffer-file-name
8973 (marker-buffer org-clock-hd-marker))
8975 (marker-position org-clock-hd-marker)))
8976 (setq goto nil)))
8977 (setq it (or rfloc
8978 (save-excursion
8979 (org-refile-get-location
8980 (if goto "Goto: " "Refile to: ") default-buffer
8981 org-refile-allow-creating-parent-nodes)))))
8982 (setq file (nth 1 it)
8983 re (nth 2 it)
8984 pos (nth 3 it))
8985 (if (and (not goto)
8987 (equal (buffer-file-name) file)
8988 (if regionp
8989 (and (>= pos region-start)
8990 (<= pos region-end))
8991 (and (>= pos (point))
8992 (< pos (save-excursion
8993 (org-end-of-subtree t t))))))
8994 (error "Cannot refile to position inside the tree or region"))
8996 (setq nbuf (or (find-buffer-visiting file)
8997 (find-file-noselect file)))
8998 (if goto
8999 (progn
9000 (switch-to-buffer nbuf)
9001 (goto-char pos)
9002 (org-show-context 'org-goto))
9003 (if regionp
9004 (progn
9005 (org-kill-new (buffer-substring region-start region-end))
9006 (org-save-markers-in-region region-start region-end))
9007 (org-copy-subtree 1 nil t))
9008 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9009 (find-file-noselect file)))
9010 (setq reversed (org-notes-order-reversed-p))
9011 (save-excursion
9012 (save-restriction
9013 (widen)
9014 (if pos
9015 (progn
9016 (goto-char pos)
9017 (looking-at outline-regexp)
9018 (setq level (org-get-valid-level (funcall outline-level) 1))
9019 (goto-char
9020 (if reversed
9021 (or (outline-next-heading) (point-max))
9022 (or (save-excursion (org-get-next-sibling))
9023 (org-end-of-subtree t t)
9024 (point-max)))))
9025 (setq level 1)
9026 (if (not reversed)
9027 (goto-char (point-max))
9028 (goto-char (point-min))
9029 (or (outline-next-heading) (goto-char (point-max)))))
9030 (if (not (bolp)) (newline))
9031 (bookmark-set "org-refile-last-stored")
9032 (org-paste-subtree level)
9033 (if (fboundp 'deactivate-mark) (deactivate-mark))
9034 (run-hooks 'org-after-refile-insert-hook))))
9035 (if regionp
9036 (delete-region (point) (+ (point) region-length))
9037 (org-cut-subtree))
9038 (when (featurep 'org-inlinetask)
9039 (org-inlinetask-remove-END-maybe))
9040 (setq org-markers-to-move nil)
9041 (message "Refiled to \"%s\"" (car it))))))
9042 (org-reveal))
9044 (defun org-refile-goto-last-stored ()
9045 "Go to the location where the last refile was stored."
9046 (interactive)
9047 (bookmark-jump "org-refile-last-stored")
9048 (message "This is the location of the last refile"))
9050 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9051 "Prompt the user for a refile location, using PROMPT."
9052 (let ((org-refile-targets org-refile-targets)
9053 (org-refile-use-outline-path org-refile-use-outline-path))
9054 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9055 (unless org-refile-target-table
9056 (error "No refile targets"))
9057 (let* ((cbuf (current-buffer))
9058 (partial-completion-mode nil)
9059 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9060 (cfunc (if (and org-refile-use-outline-path
9061 org-outline-path-complete-in-steps)
9062 'org-olpath-completing-read
9063 'org-icompleting-read))
9064 (extra (if org-refile-use-outline-path "/" ""))
9065 (filename (and cfn (expand-file-name cfn)))
9066 (tbl (mapcar
9067 (lambda (x)
9068 (if (and (not (member org-refile-use-outline-path
9069 '(file full-file-path)))
9070 (not (equal filename (nth 1 x))))
9071 (cons (concat (car x) extra " ("
9072 (file-name-nondirectory (nth 1 x)) ")")
9073 (cdr x))
9074 (cons (concat (car x) extra) (cdr x))))
9075 org-refile-target-table))
9076 (completion-ignore-case t)
9077 pa answ parent-target child parent old-hist)
9078 (setq old-hist org-refile-history)
9079 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9080 nil 'org-refile-history))
9081 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9082 (if pa
9083 (progn
9084 (when (or (not org-refile-history)
9085 (not (eq old-hist org-refile-history))
9086 (not (equal (car pa) (car org-refile-history))))
9087 (setq org-refile-history
9088 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9089 org-refile-history
9090 (cdr org-refile-history))))
9091 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9092 (pop org-refile-history)))
9094 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9095 (setq parent (match-string 1 answ)
9096 child (match-string 2 answ))
9097 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
9098 (when (and parent-target
9099 (or (eq new-nodes t)
9100 (and (eq new-nodes 'confirm)
9101 (y-or-n-p (format "Create new node \"%s\"? " child)))))
9102 (org-refile-new-child parent-target child))))))
9104 (defun org-refile-new-child (parent-target child)
9105 "Use refile target PARENT-TARGET to add new CHILD below it."
9106 (unless parent-target
9107 (error "Cannot find parent for new node"))
9108 (let ((file (nth 1 parent-target))
9109 (pos (nth 3 parent-target))
9110 level)
9111 (with-current-buffer (or (find-buffer-visiting file)
9112 (find-file-noselect file))
9113 (save-excursion
9114 (save-restriction
9115 (widen)
9116 (if pos
9117 (goto-char pos)
9118 (goto-char (point-max))
9119 (if (not (bolp)) (newline)))
9120 (when (looking-at outline-regexp)
9121 (setq level (funcall outline-level))
9122 (org-end-of-subtree t t))
9123 (org-back-over-empty-lines)
9124 (insert "\n" (make-string
9125 (if pos (org-get-valid-level level 1) 1) ?*)
9126 " " child "\n")
9127 (beginning-of-line 0)
9128 (list (concat (car parent-target) "/" child) file "" (point)))))))
9130 (defun org-olpath-completing-read (prompt collection &rest args)
9131 "Read an outline path like a file name."
9132 (let ((thetable collection)
9133 (org-completion-use-ido nil) ; does not work with ido.
9134 (org-completion-use-iswitchb nil)) ; or iswitchb
9135 (apply
9136 'org-icompleting-read prompt
9137 (lambda (string predicate &optional flag)
9138 (let (rtn r f (l (length string)))
9139 (cond
9140 ((eq flag nil)
9141 ;; try completion
9142 (try-completion string thetable))
9143 ((eq flag t)
9144 ;; all-completions
9145 (setq rtn (all-completions string thetable predicate))
9146 (mapcar
9147 (lambda (x)
9148 (setq r (substring x l))
9149 (if (string-match " ([^)]*)$" x)
9150 (setq f (match-string 0 x))
9151 (setq f ""))
9152 (if (string-match "/" r)
9153 (concat string (substring r 0 (match-end 0)) f)
9155 rtn))
9156 ((eq flag 'lambda)
9157 ;; exact match?
9158 (assoc string thetable)))
9160 args)))
9162 ;;;; Dynamic blocks
9164 (defun org-find-dblock (name)
9165 "Find the first dynamic block with name NAME in the buffer.
9166 If not found, stay at current position and return nil."
9167 (let (pos)
9168 (save-excursion
9169 (goto-char (point-min))
9170 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9171 nil t)
9172 (match-beginning 0))))
9173 (if pos (goto-char pos))
9174 pos))
9176 (defconst org-dblock-start-re
9177 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9178 "Matches the startline of a dynamic block, with parameters.")
9180 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9181 "Matches the end of a dynamic block.")
9183 (defun org-create-dblock (plist)
9184 "Create a dynamic block section, with parameters taken from PLIST.
9185 PLIST must contain a :name entry which is used as name of the block."
9186 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9187 (end-of-line 1)
9188 (newline))
9189 (let ((col (current-column))
9190 (name (plist-get plist :name)))
9191 (insert "#+BEGIN: " name)
9192 (while plist
9193 (if (eq (car plist) :name)
9194 (setq plist (cddr plist))
9195 (insert " " (prin1-to-string (pop plist)))))
9196 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9197 (beginning-of-line -2)))
9199 (defun org-prepare-dblock ()
9200 "Prepare dynamic block for refresh.
9201 This empties the block, puts the cursor at the insert position and returns
9202 the property list including an extra property :name with the block name."
9203 (unless (looking-at org-dblock-start-re)
9204 (error "Not at a dynamic block"))
9205 (let* ((begdel (1+ (match-end 0)))
9206 (name (org-no-properties (match-string 1)))
9207 (params (append (list :name name)
9208 (read (concat "(" (match-string 3) ")")))))
9209 (save-excursion
9210 (beginning-of-line 1)
9211 (skip-chars-forward " \t")
9212 (setq params (plist-put params :indentation-column (current-column))))
9213 (unless (re-search-forward org-dblock-end-re nil t)
9214 (error "Dynamic block not terminated"))
9215 (setq params
9216 (append params
9217 (list :content (buffer-substring
9218 begdel (match-beginning 0)))))
9219 (delete-region begdel (match-beginning 0))
9220 (goto-char begdel)
9221 (open-line 1)
9222 params))
9224 (defun org-map-dblocks (&optional command)
9225 "Apply COMMAND to all dynamic blocks in the current buffer.
9226 If COMMAND is not given, use `org-update-dblock'."
9227 (let ((cmd (or command 'org-update-dblock))
9228 pos)
9229 (save-excursion
9230 (goto-char (point-min))
9231 (while (re-search-forward org-dblock-start-re nil t)
9232 (goto-char (setq pos (match-beginning 0)))
9233 (condition-case nil
9234 (funcall cmd)
9235 (error (message "Error during update of dynamic block")))
9236 (goto-char pos)
9237 (unless (re-search-forward org-dblock-end-re nil t)
9238 (error "Dynamic block not terminated"))))))
9240 (defun org-dblock-update (&optional arg)
9241 "User command for updating dynamic blocks.
9242 Update the dynamic block at point. With prefix ARG, update all dynamic
9243 blocks in the buffer."
9244 (interactive "P")
9245 (if arg
9246 (org-update-all-dblocks)
9247 (or (looking-at org-dblock-start-re)
9248 (org-beginning-of-dblock))
9249 (org-update-dblock)))
9251 (defun org-update-dblock ()
9252 "Update the dynamic block at point
9253 This means to empty the block, parse for parameters and then call
9254 the correct writing function."
9255 (save-window-excursion
9256 (let* ((pos (point))
9257 (line (org-current-line))
9258 (params (org-prepare-dblock))
9259 (name (plist-get params :name))
9260 (indent (plist-get params :indentation-column))
9261 (cmd (intern (concat "org-dblock-write:" name))))
9262 (message "Updating dynamic block `%s' at line %d..." name line)
9263 (funcall cmd params)
9264 (message "Updating dynamic block `%s' at line %d...done" name line)
9265 (goto-char pos)
9266 (when (and indent (> indent 0))
9267 (setq indent (make-string indent ?\ ))
9268 (save-excursion
9269 (org-beginning-of-dblock)
9270 (forward-line 1)
9271 (while (not (looking-at org-dblock-end-re))
9272 (insert indent)
9273 (beginning-of-line 2))
9274 (when (looking-at org-dblock-end-re)
9275 (and (looking-at "[ \t]+")
9276 (replace-match ""))
9277 (insert indent)))))))
9279 (defun org-beginning-of-dblock ()
9280 "Find the beginning of the dynamic block at point.
9281 Error if there is no such block at point."
9282 (let ((pos (point))
9283 beg)
9284 (end-of-line 1)
9285 (if (and (re-search-backward org-dblock-start-re nil t)
9286 (setq beg (match-beginning 0))
9287 (re-search-forward org-dblock-end-re nil t)
9288 (> (match-end 0) pos))
9289 (goto-char beg)
9290 (goto-char pos)
9291 (error "Not in a dynamic block"))))
9293 (defun org-update-all-dblocks ()
9294 "Update all dynamic blocks in the buffer.
9295 This function can be used in a hook."
9296 (when (org-mode-p)
9297 (org-map-dblocks 'org-update-dblock)))
9300 ;;;; Completion
9302 (defconst org-additional-option-like-keywords
9303 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9304 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9305 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "LATEX_CLASS:" "ATTR_LaTeX"
9306 "BEGIN:" "END:"
9307 "ORGTBL" "TBLFM:" "TBLNAME:"
9308 "BEGIN_EXAMPLE" "END_EXAMPLE"
9309 "BEGIN_QUOTE" "END_QUOTE"
9310 "BEGIN_VERSE" "END_VERSE"
9311 "BEGIN_CENTER" "END_CENTER"
9312 "BEGIN_SRC" "END_SRC"
9313 "CATEGORY" "COLUMNS"
9314 "CAPTION" "LABEL"
9315 "SETUPFILE"
9316 "BIND"
9317 "MACRO"))
9319 (defcustom org-structure-template-alist
9321 ("s" "#+begin_src ?\n\n#+end_src"
9322 "<src lang=\"?\">\n\n</src>")
9323 ("e" "#+begin_example\n?\n#+end_example"
9324 "<example>\n?\n</example>")
9325 ("q" "#+begin_quote\n?\n#+end_quote"
9326 "<quote>\n?\n</quote>")
9327 ("v" "#+begin_verse\n?\n#+end_verse"
9328 "<verse>\n?\n/verse>")
9329 ("c" "#+begin_center\n?\n#+end_center"
9330 "<center>\n?\n/center>")
9331 ("l" "#+begin_latex\n?\n#+end_latex"
9332 "<literal style=\"latex\">\n?\n</literal>")
9333 ("L" "#+latex: "
9334 "<literal style=\"latex\">?</literal>")
9335 ("h" "#+begin_html\n?\n#+end_html"
9336 "<literal style=\"html\">\n?\n</literal>")
9337 ("H" "#+html: "
9338 "<literal style=\"html\">?</literal>")
9339 ("a" "#+begin_ascii\n?\n#+end_ascii")
9340 ("A" "#+ascii: ")
9341 ("i" "#+include %file ?"
9342 "<include file=%file markup=\"?\">")
9344 "Structure completion elements.
9345 This is a list of abbreviation keys and values. The value gets inserted
9346 it you type @samp{.} followed by the key and then the completion key,
9347 usually `M-TAB'. %file will be replaced by a file name after prompting
9348 for the file using completion.
9349 There are two templates for each key, the first uses the original Org syntax,
9350 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9351 the default when the /org-mtags.el/ module has been loaded. See also the
9352 variable `org-mtags-prefer-muse-templates'.
9353 This is an experimental feature, it is undecided if it is going to stay in."
9354 :group 'org-completion
9355 :type '(repeat
9356 (string :tag "Key")
9357 (string :tag "Template")
9358 (string :tag "Muse Template")))
9360 (defun org-try-structure-completion ()
9361 "Try to complete a structure template before point.
9362 This looks for strings like \"<e\" on an otherwise empty line and
9363 expands them."
9364 (let ((l (buffer-substring (point-at-bol) (point)))
9366 (when (and (looking-at "[ \t]*$")
9367 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9368 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9369 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9370 (match-beginning 1)) a)
9371 t)))
9373 (defun org-complete-expand-structure-template (start cell)
9374 "Expand a structure template."
9375 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9376 (rpl (nth (if musep 2 1) cell))
9377 (ind ""))
9378 (delete-region start (point))
9379 (when (string-match "\\`#\\+" rpl)
9380 (cond
9381 ((bolp))
9382 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9383 (setq ind (buffer-substring (point-at-bol) (point))))
9384 (t (newline))))
9385 (setq start (point))
9386 (if (string-match "%file" rpl)
9387 (setq rpl (replace-match
9388 (concat
9389 "\""
9390 (save-match-data
9391 (abbreviate-file-name (read-file-name "Include file: ")))
9392 "\"")
9393 t t rpl)))
9394 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9395 (concat "\n" ind)))
9396 (insert rpl)
9397 (if (re-search-backward "\\?" start t) (delete-char 1))))
9400 (defun org-complete (&optional arg)
9401 "Perform completion on word at point.
9402 At the beginning of a headline, this completes TODO keywords as given in
9403 `org-todo-keywords'.
9404 If the current word is preceded by a backslash, completes the TeX symbols
9405 that are supported for HTML support.
9406 If the current word is preceded by \"#+\", completes special words for
9407 setting file options.
9408 In the line after \"#+STARTUP:, complete valid keywords.\"
9409 At all other locations, this simply calls the value of
9410 `org-completion-fallback-command'."
9411 (interactive "P")
9412 (org-without-partial-completion
9413 (catch 'exit
9414 (let* ((a nil)
9415 (end (point))
9416 (beg1 (save-excursion
9417 (skip-chars-backward (org-re "[:alnum:]_@"))
9418 (point)))
9419 (beg (save-excursion
9420 (skip-chars-backward "a-zA-Z0-9_:$")
9421 (point)))
9422 (confirm (lambda (x) (stringp (car x))))
9423 (searchhead (equal (char-before beg) ?*))
9424 (struct
9425 (when (and (member (char-before beg1) '(?. ?<))
9426 (setq a (assoc (buffer-substring beg1 (point))
9427 org-structure-template-alist)))
9428 (org-complete-expand-structure-template (1- beg1) a)
9429 (throw 'exit t)))
9430 (tag (and (equal (char-before beg1) ?:)
9431 (equal (char-after (point-at-bol)) ?*)))
9432 (prop (and (equal (char-before beg1) ?:)
9433 (not (equal (char-after (point-at-bol)) ?*))))
9434 (texp (equal (char-before beg) ?\\))
9435 (link (equal (char-before beg) ?\[))
9436 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9437 beg)
9438 "#+"))
9439 (startup (string-match "^#\\+STARTUP:.*"
9440 (buffer-substring (point-at-bol) (point))))
9441 (completion-ignore-case opt)
9442 (type nil)
9443 (tbl nil)
9444 (table (cond
9445 (opt
9446 (setq type :opt)
9447 (require 'org-exp)
9448 (append
9449 (delq nil
9450 (mapcar
9451 (lambda (x)
9452 (if (string-match
9453 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9454 (cons (match-string 2 x)
9455 (match-string 1 x))))
9456 (org-split-string (org-get-current-options) "\n")))
9457 (mapcar 'list org-additional-option-like-keywords)))
9458 (startup
9459 (setq type :startup)
9460 org-startup-options)
9461 (link (append org-link-abbrev-alist-local
9462 org-link-abbrev-alist))
9463 (texp
9464 (setq type :tex)
9465 org-html-entities)
9466 ((string-match "\\`\\*+[ \t]+\\'"
9467 (buffer-substring (point-at-bol) beg))
9468 (setq type :todo)
9469 (mapcar 'list org-todo-keywords-1))
9470 (searchhead
9471 (setq type :searchhead)
9472 (save-excursion
9473 (goto-char (point-min))
9474 (while (re-search-forward org-todo-line-regexp nil t)
9475 (push (list
9476 (org-make-org-heading-search-string
9477 (match-string 3) t))
9478 tbl)))
9479 tbl)
9480 (tag (setq type :tag beg beg1)
9481 (or org-tag-alist (org-get-buffer-tags)))
9482 (prop (setq type :prop beg beg1)
9483 (mapcar 'list (org-buffer-property-keys nil t t)))
9484 (t (progn
9485 (call-interactively org-completion-fallback-command)
9486 (throw 'exit nil)))))
9487 (pattern (buffer-substring-no-properties beg end))
9488 (completion (try-completion pattern table confirm)))
9489 (cond ((eq completion t)
9490 (if (not (assoc (upcase pattern) table))
9491 (message "Already complete")
9492 (if (and (equal type :opt)
9493 (not (member (car (assoc (upcase pattern) table))
9494 org-additional-option-like-keywords)))
9495 (insert (substring (cdr (assoc (upcase pattern) table))
9496 (length pattern)))
9497 (if (memq type '(:tag :prop)) (insert ":")))))
9498 ((null completion)
9499 (message "Can't find completion for \"%s\"" pattern)
9500 (ding))
9501 ((not (string= pattern completion))
9502 (delete-region beg end)
9503 (if (string-match " +$" completion)
9504 (setq completion (replace-match "" t t completion)))
9505 (insert completion)
9506 (if (get-buffer-window "*Completions*")
9507 (delete-window (get-buffer-window "*Completions*")))
9508 (if (assoc completion table)
9509 (if (eq type :todo) (insert " ")
9510 (if (memq type '(:tag :prop)) (insert ":"))))
9511 (if (and (equal type :opt) (assoc completion table))
9512 (message "%s" (substitute-command-keys
9513 "Press \\[org-complete] again to insert example settings"))))
9515 (message "Making completion list...")
9516 (let ((list (sort (all-completions pattern table confirm)
9517 'string<)))
9518 (with-output-to-temp-buffer "*Completions*"
9519 (condition-case nil
9520 ;; Protection needed for XEmacs and emacs 21
9521 (display-completion-list list pattern)
9522 (error (display-completion-list list)))))
9523 (message "Making completion list...%s" "done")))))))
9525 ;;;; TODO, DEADLINE, Comments
9527 (defun org-toggle-comment ()
9528 "Change the COMMENT state of an entry."
9529 (interactive)
9530 (save-excursion
9531 (org-back-to-heading)
9532 (let (case-fold-search)
9533 (if (looking-at (concat outline-regexp
9534 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9535 (replace-match "" t t nil 1)
9536 (if (looking-at outline-regexp)
9537 (progn
9538 (goto-char (match-end 0))
9539 (insert org-comment-string " ")))))))
9541 (defvar org-last-todo-state-is-todo nil
9542 "This is non-nil when the last TODO state change led to a TODO state.
9543 If the last change removed the TODO tag or switched to DONE, then
9544 this is nil.")
9546 (defvar org-setting-tags nil) ; dynamically skipped
9548 (defun org-parse-local-options (string var)
9549 "Parse STRING for startup setting relevant for variable VAR."
9550 (let ((rtn (symbol-value var))
9551 e opts)
9552 (save-match-data
9553 (if (or (not string) (not (string-match "\\S-" string)))
9555 (setq opts (delq nil (mapcar (lambda (x)
9556 (setq e (assoc x org-startup-options))
9557 (if (eq (nth 1 e) var) e nil))
9558 (org-split-string string "[ \t]+"))))
9559 (if (not opts)
9561 (setq rtn nil)
9562 (while (setq e (pop opts))
9563 (if (not (nth 3 e))
9564 (setq rtn (nth 2 e))
9565 (if (not (listp rtn)) (setq rtn nil))
9566 (push (nth 2 e) rtn)))
9567 rtn)))))
9569 (defvar org-todo-setup-filter-hook nil
9570 "Hook for functions that pre-filter todo specs.
9572 Each function takes a todo spec and returns either `nil' or the spec
9573 transformed into canonical form." )
9575 (defvar org-todo-get-default-hook nil
9576 "Hook for functions that get a default item for todo.
9578 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9579 `nil' or a string to be used for the todo mark." )
9581 (defvar org-agenda-headline-snapshot-before-repeat)
9583 (defun org-todo (&optional arg)
9584 "Change the TODO state of an item.
9585 The state of an item is given by a keyword at the start of the heading,
9586 like
9587 *** TODO Write paper
9588 *** DONE Call mom
9590 The different keywords are specified in the variable `org-todo-keywords'.
9591 By default the available states are \"TODO\" and \"DONE\".
9592 So for this example: when the item starts with TODO, it is changed to DONE.
9593 When it starts with DONE, the DONE is removed. And when neither TODO nor
9594 DONE are present, add TODO at the beginning of the heading.
9596 With C-u prefix arg, use completion to determine the new state.
9597 With numeric prefix arg, switch to that state.
9598 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9599 With a tripple C-u prefix, circumvent any state blocking.
9601 For calling through lisp, arg is also interpreted in the following way:
9602 'none -> empty state
9603 \"\"(empty string) -> switch to empty state
9604 'done -> switch to DONE
9605 'nextset -> switch to the next set of keywords
9606 'previousset -> switch to the previous set of keywords
9607 \"WAITING\" -> switch to the specified keyword, but only if it
9608 really is a member of `org-todo-keywords'."
9609 (interactive "P")
9610 (if (equal arg '(16)) (setq arg 'nextset))
9611 (let ((org-blocker-hook org-blocker-hook)
9612 (case-fold-search nil))
9613 (when (equal arg '(64))
9614 (setq arg nil org-blocker-hook nil))
9615 (when (and org-blocker-hook
9616 (or org-inhibit-blocking
9617 (org-entry-get nil "NOBLOCKING")))
9618 (setq org-blocker-hook nil))
9619 (save-excursion
9620 (catch 'exit
9621 (org-back-to-heading t)
9622 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9623 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9624 (looking-at " *"))
9625 (let* ((match-data (match-data))
9626 (startpos (point-at-bol))
9627 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9628 (org-log-done org-log-done)
9629 (org-log-repeat org-log-repeat)
9630 (org-todo-log-states org-todo-log-states)
9631 (this (match-string 1))
9632 (hl-pos (match-beginning 0))
9633 (head (org-get-todo-sequence-head this))
9634 (ass (assoc head org-todo-kwd-alist))
9635 (interpret (nth 1 ass))
9636 (done-word (nth 3 ass))
9637 (final-done-word (nth 4 ass))
9638 (last-state (or this ""))
9639 (completion-ignore-case t)
9640 (member (member this org-todo-keywords-1))
9641 (tail (cdr member))
9642 (state (cond
9643 ((and org-todo-key-trigger
9644 (or (and (equal arg '(4))
9645 (eq org-use-fast-todo-selection 'prefix))
9646 (and (not arg) org-use-fast-todo-selection
9647 (not (eq org-use-fast-todo-selection
9648 'prefix)))))
9649 ;; Use fast selection
9650 (org-fast-todo-selection))
9651 ((and (equal arg '(4))
9652 (or (not org-use-fast-todo-selection)
9653 (not org-todo-key-trigger)))
9654 ;; Read a state with completion
9655 (org-icompleting-read
9656 "State: " (mapcar (lambda(x) (list x))
9657 org-todo-keywords-1)
9658 nil t))
9659 ((eq arg 'right)
9660 (if this
9661 (if tail (car tail) nil)
9662 (car org-todo-keywords-1)))
9663 ((eq arg 'left)
9664 (if (equal member org-todo-keywords-1)
9666 (if this
9667 (nth (- (length org-todo-keywords-1)
9668 (length tail) 2)
9669 org-todo-keywords-1)
9670 (org-last org-todo-keywords-1))))
9671 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9672 (setq arg nil))) ; hack to fall back to cycling
9673 (arg
9674 ;; user or caller requests a specific state
9675 (cond
9676 ((equal arg "") nil)
9677 ((eq arg 'none) nil)
9678 ((eq arg 'done) (or done-word (car org-done-keywords)))
9679 ((eq arg 'nextset)
9680 (or (car (cdr (member head org-todo-heads)))
9681 (car org-todo-heads)))
9682 ((eq arg 'previousset)
9683 (let ((org-todo-heads (reverse org-todo-heads)))
9684 (or (car (cdr (member head org-todo-heads)))
9685 (car org-todo-heads))))
9686 ((car (member arg org-todo-keywords-1)))
9687 ((stringp arg)
9688 (error "State `%s' not valid in this file" arg))
9689 ((nth (1- (prefix-numeric-value arg))
9690 org-todo-keywords-1))))
9691 ((null member) (or head (car org-todo-keywords-1)))
9692 ((equal this final-done-word) nil) ;; -> make empty
9693 ((null tail) nil) ;; -> first entry
9694 ((memq interpret '(type priority))
9695 (if (eq this-command last-command)
9696 (car tail)
9697 (if (> (length tail) 0)
9698 (or done-word (car org-done-keywords))
9699 nil)))
9701 (car tail))))
9702 (state (or
9703 (run-hook-with-args-until-success
9704 'org-todo-get-default-hook state last-state)
9705 state))
9706 (next (if state (concat " " state " ") " "))
9707 (change-plist (list :type 'todo-state-change :from this :to state
9708 :position startpos))
9709 dolog now-done-p)
9710 (when org-blocker-hook
9711 (setq org-last-todo-state-is-todo
9712 (not (member this org-done-keywords)))
9713 (unless (save-excursion
9714 (save-match-data
9715 (run-hook-with-args-until-failure
9716 'org-blocker-hook change-plist)))
9717 (if (interactive-p)
9718 (error "TODO state change from %s to %s blocked" this state)
9719 ;; fail silently
9720 (message "TODO state change from %s to %s blocked" this state)
9721 (throw 'exit nil))))
9722 (store-match-data match-data)
9723 (replace-match next t t)
9724 (unless (pos-visible-in-window-p hl-pos)
9725 (message "TODO state changed to %s" (org-trim next)))
9726 (unless head
9727 (setq head (org-get-todo-sequence-head state)
9728 ass (assoc head org-todo-kwd-alist)
9729 interpret (nth 1 ass)
9730 done-word (nth 3 ass)
9731 final-done-word (nth 4 ass)))
9732 (when (memq arg '(nextset previousset))
9733 (message "Keyword-Set %d/%d: %s"
9734 (- (length org-todo-sets) -1
9735 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9736 (length org-todo-sets)
9737 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9738 (setq org-last-todo-state-is-todo
9739 (not (member state org-done-keywords)))
9740 (setq now-done-p (and (member state org-done-keywords)
9741 (not (member this org-done-keywords))))
9742 (and logging (org-local-logging logging))
9743 (when (and (or org-todo-log-states org-log-done)
9744 (not (eq org-inhibit-logging t))
9745 (not (memq arg '(nextset previousset))))
9746 ;; we need to look at recording a time and note
9747 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9748 (nth 2 (assoc this org-todo-log-states))))
9749 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9750 (setq dolog 'time))
9751 (when (and state
9752 (member state org-not-done-keywords)
9753 (not (member this org-not-done-keywords)))
9754 ;; This is now a todo state and was not one before
9755 ;; If there was a CLOSED time stamp, get rid of it.
9756 (org-add-planning-info nil nil 'closed))
9757 (when (and now-done-p org-log-done)
9758 ;; It is now done, and it was not done before
9759 (org-add-planning-info 'closed (org-current-time))
9760 (if (and (not dolog) (eq 'note org-log-done))
9761 (org-add-log-setup 'done state this 'findpos 'note)))
9762 (when (and state dolog)
9763 ;; This is a non-nil state, and we need to log it
9764 (org-add-log-setup 'state state this 'findpos dolog)))
9765 ;; Fixup tag positioning
9766 (org-todo-trigger-tag-changes state)
9767 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9768 (when org-provide-todo-statistics
9769 (org-update-parent-todo-statistics))
9770 (run-hooks 'org-after-todo-state-change-hook)
9771 (if (and arg (not (member state org-done-keywords)))
9772 (setq head (org-get-todo-sequence-head state)))
9773 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9774 ;; Do we need to trigger a repeat?
9775 (when now-done-p
9776 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9777 ;; This is for the agenda, take a snapshot of the headline.
9778 (save-match-data
9779 (setq org-agenda-headline-snapshot-before-repeat
9780 (org-get-heading))))
9781 (org-auto-repeat-maybe state))
9782 ;; Fixup cursor location if close to the keyword
9783 (if (and (outline-on-heading-p)
9784 (not (bolp))
9785 (save-excursion (beginning-of-line 1)
9786 (looking-at org-todo-line-regexp))
9787 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9788 (progn
9789 (goto-char (or (match-end 2) (match-end 1)))
9790 (and (looking-at " ") (just-one-space))))
9791 (when org-trigger-hook
9792 (save-excursion
9793 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9795 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9796 "Block turning an entry into a TODO, using the hierarchy.
9797 This checks whether the current task should be blocked from state
9798 changes. Such blocking occurs when:
9800 1. The task has children which are not all in a completed state.
9802 2. A task has a parent with the property :ORDERED:, and there
9803 are siblings prior to the current task with incomplete
9804 status.
9806 3. The parent of the task is blocked because it has siblings that should
9807 be done first, or is child of a block grandparent TODO entry."
9809 (catch 'dont-block
9810 ;; If this is not a todo state change, or if this entry is already DONE,
9811 ;; do not block
9812 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9813 (member (plist-get change-plist :from)
9814 (cons 'done org-done-keywords))
9815 (member (plist-get change-plist :to)
9816 (cons 'todo org-not-done-keywords)))
9817 (throw 'dont-block t))
9818 ;; If this task has children, and any are undone, it's blocked
9819 (save-excursion
9820 (org-back-to-heading t)
9821 (let ((this-level (funcall outline-level)))
9822 (outline-next-heading)
9823 (let ((child-level (funcall outline-level)))
9824 (while (and (not (eobp))
9825 (> child-level this-level))
9826 ;; this todo has children, check whether they are all
9827 ;; completed
9828 (if (and (not (org-entry-is-done-p))
9829 (org-entry-is-todo-p))
9830 (throw 'dont-block nil))
9831 (outline-next-heading)
9832 (setq child-level (funcall outline-level))))))
9833 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9834 ;; any previous siblings are undone, it's blocked
9835 (save-excursion
9836 (org-back-to-heading t)
9837 (let* ((pos (point))
9838 (parent-pos (and (org-up-heading-safe) (point))))
9839 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9840 (when (and (org-entry-get (point) "ORDERED")
9841 (forward-line 1)
9842 (re-search-forward org-not-done-heading-regexp pos t))
9843 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9844 ;; Search further up the hierarchy, to see if an anchestor is blocked
9845 (while t
9846 (goto-char parent-pos)
9847 (if (not (looking-at org-not-done-heading-regexp))
9848 (throw 'dont-block t)) ; do not block, parent is not a TODO
9849 (setq pos (point))
9850 (setq parent-pos (and (org-up-heading-safe) (point)))
9851 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9852 (when (and (org-entry-get (point) "ORDERED")
9853 (forward-line 1)
9854 (re-search-forward org-not-done-heading-regexp pos t))
9855 (throw 'dont-block nil))))))) ; block, older sibling not done.
9857 (defcustom org-track-ordered-property-with-tag nil
9858 "Should the ORDERED property also be shown as a tag?
9859 The ORDERED property decides if an entry should require subtasks to be
9860 completed in sequence. Since a property is not very visible, setting
9861 this option means that toggling the ORDERED property with the command
9862 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9863 not relevant for the behavior, but it makes things more visible.
9865 Note that toggling the tag with tags commands will not change the property
9866 and therefore not influence behavior!
9868 This can be t, meaning the tag ORDERED should be used, It can also be a
9869 string to select a different tag for this task."
9870 :group 'org-todo
9871 :type '(choice
9872 (const :tag "No tracking" nil)
9873 (const :tag "Track with ORDERED tag" t)
9874 (string :tag "Use other tag")))
9876 (defun org-toggle-ordered-property ()
9877 "Toggle the ORDERED property of the current entry.
9878 For better visibility, you can track the value of this property with a tag.
9879 See variable `org-track-ordered-property-with-tag'."
9880 (interactive)
9881 (let* ((t1 org-track-ordered-property-with-tag)
9882 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9883 (save-excursion
9884 (org-back-to-heading)
9885 (if (org-entry-get nil "ORDERED")
9886 (progn
9887 (org-delete-property "ORDERED")
9888 (and tag (org-toggle-tag tag 'off))
9889 (message "Subtasks can be completed in arbitrary order"))
9890 (org-entry-put nil "ORDERED" "t")
9891 (and tag (org-toggle-tag tag 'on))
9892 (message "Subtasks must be completed in sequence")))))
9894 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9895 (defun org-block-todo-from-checkboxes (change-plist)
9896 "Block turning an entry into a TODO, using checkboxes.
9897 This checks whether the current task should be blocked from state
9898 changes because there are uncheckd boxes in this entry."
9899 (catch 'dont-block
9900 ;; If this is not a todo state change, or if this entry is already DONE,
9901 ;; do not block
9902 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9903 (member (plist-get change-plist :from)
9904 (cons 'done org-done-keywords))
9905 (member (plist-get change-plist :to)
9906 (cons 'todo org-not-done-keywords)))
9907 (throw 'dont-block t))
9908 ;; If this task has checkboxes that are not checked, it's blocked
9909 (save-excursion
9910 (org-back-to-heading t)
9911 (let ((beg (point)) end)
9912 (outline-next-heading)
9913 (setq end (point))
9914 (goto-char beg)
9915 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9916 end t)
9917 (progn
9918 (if (boundp 'org-blocked-by-checkboxes)
9919 (setq org-blocked-by-checkboxes t))
9920 (throw 'dont-block nil)))))
9921 t)) ; do not block
9923 (defun org-update-statistics-cookies (all)
9924 "Update the statistics cookie, either from TODO or from checkboxes.
9925 This should be called with the cursor in a line with a statistics cookie."
9926 (interactive "P")
9927 (if all
9928 (progn
9929 (org-update-checkbox-count 'all)
9930 (org-map-entries 'org-update-parent-todo-statistics))
9931 (if (not (org-on-heading-p))
9932 (org-update-checkbox-count)
9933 (let ((pos (move-marker (make-marker) (point)))
9934 end l1 l2)
9935 (ignore-errors (org-back-to-heading t))
9936 (if (not (org-on-heading-p))
9937 (org-update-checkbox-count)
9938 (setq l1 (org-outline-level))
9939 (setq end (save-excursion
9940 (outline-next-heading)
9941 (if (org-on-heading-p) (setq l2 (org-outline-level)))
9942 (point)))
9943 (if (and (save-excursion (re-search-forward
9944 "^[ \t]*[-+*] \\[[- X]\\]" end t))
9945 (not (save-excursion (re-search-forward
9946 ":COOKIE_DATA:.*\\<todo\\>" end t))))
9947 (org-update-checkbox-count)
9948 (if (and l2 (> l2 l1))
9949 (progn
9950 (goto-char end)
9951 (org-update-parent-todo-statistics))
9952 (error "No data for statistics cookie"))))
9953 (goto-char pos)
9954 (move-marker pos nil)))))
9956 (defvar org-entry-property-inherited-from) ;; defined below
9957 (defun org-update-parent-todo-statistics ()
9958 "Update any statistics cookie in the parent of the current headline.
9959 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9960 the entire subtree and this will travel up the hierarchy and update
9961 statistics everywhere."
9962 (interactive)
9963 (let* ((lim 0) prop
9964 (recursive (or (not org-hierarchical-todo-statistics)
9965 (string-match
9966 "\\<recursive\\>"
9967 (or (setq prop (org-entry-get
9968 nil "COOKIE_DATA" 'inherit)) ""))))
9969 (lim (or (and prop (marker-position
9970 org-entry-property-inherited-from))
9971 lim))
9972 (first t)
9973 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9974 level ltoggle l1 new ndel
9975 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9976 (catch 'exit
9977 (save-excursion
9978 (beginning-of-line 1)
9979 (if (org-at-heading-p)
9980 (setq ltoggle (funcall outline-level))
9981 (error "This should not happen"))
9982 (while (and (setq level (org-up-heading-safe))
9983 (or recursive first)
9984 (>= (point) lim))
9985 (setq first nil cookie-present nil)
9986 (unless (and level
9987 (not (string-match
9988 "\\<checkbox\\>"
9989 (downcase
9990 (or (org-entry-get
9991 nil "COOKIE_DATA")
9992 "")))))
9993 (throw 'exit nil))
9994 (while (re-search-forward box-re (point-at-eol) t)
9995 (setq cnt-all 0 cnt-done 0 cookie-present t)
9996 (setq is-percent (match-end 2))
9997 (save-match-data
9998 (unless (outline-next-heading) (throw 'exit nil))
9999 (while (and (looking-at org-complex-heading-regexp)
10000 (> (setq l1 (length (match-string 1))) level))
10001 (setq kwd (and (or recursive (= l1 ltoggle))
10002 (match-string 2)))
10003 (if (or (eq org-provide-todo-statistics 'all-headlines)
10004 (and (listp org-provide-todo-statistics)
10005 (or (member kwd org-provide-todo-statistics)
10006 (member kwd org-done-keywords))))
10007 (setq cnt-all (1+ cnt-all))
10008 (if (eq org-provide-todo-statistics t)
10009 (and kwd (setq cnt-all (1+ cnt-all)))))
10010 (and (member kwd org-done-keywords)
10011 (setq cnt-done (1+ cnt-done)))
10012 (outline-next-heading)))
10013 (setq new
10014 (if is-percent
10015 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10016 (format "[%d/%d]" cnt-done cnt-all))
10017 ndel (- (match-end 0) (match-beginning 0)))
10018 (goto-char (match-beginning 0))
10019 (insert new)
10020 (delete-region (point) (+ (point) ndel)))
10021 (when cookie-present
10022 (run-hook-with-args 'org-after-todo-statistics-hook
10023 cnt-done (- cnt-all cnt-done))))))
10024 (run-hooks 'org-todo-statistics-hook)))
10026 (defvar org-after-todo-statistics-hook nil
10027 "Hook that is called after a TODO statistics cookie has been updated.
10028 Each function is called with two arguments: the number of not-done entries
10029 and the number of done entries.
10031 For example, the following function, when added to this hook, will switch
10032 an entry to DONE when all children are done, and back to TODO when new
10033 entries are set to a TODO status. Note that this hook is only called
10034 when there is a statistics cookie in the headline!
10036 (defun org-summary-todo (n-done n-not-done)
10037 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10038 (let (org-log-done org-log-states) ; turn off logging
10039 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10042 (defvar org-todo-statistics-hook nil
10043 "Hook that is run whenever Org thinks TODO statistics should be updated.
10044 This hook runs even if there is no statisics cookie present, in which case
10045 `org-after-todo-statistics-hook' would not run.")
10047 (defun org-todo-trigger-tag-changes (state)
10048 "Apply the changes defined in `org-todo-state-tags-triggers'."
10049 (let ((l org-todo-state-tags-triggers)
10050 changes)
10051 (when (or (not state) (equal state ""))
10052 (setq changes (append changes (cdr (assoc "" l)))))
10053 (when (and (stringp state) (> (length state) 0))
10054 (setq changes (append changes (cdr (assoc state l)))))
10055 (when (member state org-not-done-keywords)
10056 (setq changes (append changes (cdr (assoc 'todo l)))))
10057 (when (member state org-done-keywords)
10058 (setq changes (append changes (cdr (assoc 'done l)))))
10059 (dolist (c changes)
10060 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10062 (defun org-local-logging (value)
10063 "Get logging settings from a property VALUE."
10064 (let* (words w a)
10065 ;; directly set the variables, they are already local.
10066 (setq org-log-done nil
10067 org-log-repeat nil
10068 org-todo-log-states nil)
10069 (setq words (org-split-string value))
10070 (while (setq w (pop words))
10071 (cond
10072 ((setq a (assoc w org-startup-options))
10073 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10074 (set (nth 1 a) (nth 2 a))))
10075 ((setq a (org-extract-log-state-settings w))
10076 (and (member (car a) org-todo-keywords-1)
10077 (push a org-todo-log-states)))))))
10079 (defun org-get-todo-sequence-head (kwd)
10080 "Return the head of the TODO sequence to which KWD belongs.
10081 If KWD is not set, check if there is a text property remembering the
10082 right sequence."
10083 (let (p)
10084 (cond
10085 ((not kwd)
10086 (or (get-text-property (point-at-bol) 'org-todo-head)
10087 (progn
10088 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10089 nil (point-at-eol)))
10090 (get-text-property p 'org-todo-head))))
10091 ((not (member kwd org-todo-keywords-1))
10092 (car org-todo-keywords-1))
10093 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10095 (defun org-fast-todo-selection ()
10096 "Fast TODO keyword selection with single keys.
10097 Returns the new TODO keyword, or nil if no state change should occur."
10098 (let* ((fulltable org-todo-key-alist)
10099 (done-keywords org-done-keywords) ;; needed for the faces.
10100 (maxlen (apply 'max (mapcar
10101 (lambda (x)
10102 (if (stringp (car x)) (string-width (car x)) 0))
10103 fulltable)))
10104 (expert nil)
10105 (fwidth (+ maxlen 3 1 3))
10106 (ncol (/ (- (window-width) 4) fwidth))
10107 tg cnt e c tbl
10108 groups ingroup)
10109 (save-excursion
10110 (save-window-excursion
10111 (if expert
10112 (set-buffer (get-buffer-create " *Org todo*"))
10113 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10114 (erase-buffer)
10115 (org-set-local 'org-done-keywords done-keywords)
10116 (setq tbl fulltable cnt 0)
10117 (while (setq e (pop tbl))
10118 (cond
10119 ((equal e '(:startgroup))
10120 (push '() groups) (setq ingroup t)
10121 (when (not (= cnt 0))
10122 (setq cnt 0)
10123 (insert "\n"))
10124 (insert "{ "))
10125 ((equal e '(:endgroup))
10126 (setq ingroup nil cnt 0)
10127 (insert "}\n"))
10128 ((equal e '(:newline))
10129 (when (not (= cnt 0))
10130 (setq cnt 0)
10131 (insert "\n")
10132 (setq e (car tbl))
10133 (while (equal (car tbl) '(:newline))
10134 (insert "\n")
10135 (setq tbl (cdr tbl)))))
10137 (setq tg (car e) c (cdr e))
10138 (if ingroup (push tg (car groups)))
10139 (setq tg (org-add-props tg nil 'face
10140 (org-get-todo-face tg)))
10141 (if (and (= cnt 0) (not ingroup)) (insert " "))
10142 (insert "[" c "] " tg (make-string
10143 (- fwidth 4 (length tg)) ?\ ))
10144 (when (= (setq cnt (1+ cnt)) ncol)
10145 (insert "\n")
10146 (if ingroup (insert " "))
10147 (setq cnt 0)))))
10148 (insert "\n")
10149 (goto-char (point-min))
10150 (if (not expert) (org-fit-window-to-buffer))
10151 (message "[a-z..]:Set [SPC]:clear")
10152 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10153 (cond
10154 ((or (= c ?\C-g)
10155 (and (= c ?q) (not (rassoc c fulltable))))
10156 (setq quit-flag t))
10157 ((= c ?\ ) nil)
10158 ((setq e (rassoc c fulltable) tg (car e))
10160 (t (setq quit-flag t)))))))
10162 (defun org-entry-is-todo-p ()
10163 (member (org-get-todo-state) org-not-done-keywords))
10165 (defun org-entry-is-done-p ()
10166 (member (org-get-todo-state) org-done-keywords))
10168 (defun org-get-todo-state ()
10169 (save-excursion
10170 (org-back-to-heading t)
10171 (and (looking-at org-todo-line-regexp)
10172 (match-end 2)
10173 (match-string 2))))
10175 (defun org-at-date-range-p (&optional inactive-ok)
10176 "Is the cursor inside a date range?"
10177 (interactive)
10178 (save-excursion
10179 (catch 'exit
10180 (let ((pos (point)))
10181 (skip-chars-backward "^[<\r\n")
10182 (skip-chars-backward "<[")
10183 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10184 (>= (match-end 0) pos)
10185 (throw 'exit t))
10186 (skip-chars-backward "^<[\r\n")
10187 (skip-chars-backward "<[")
10188 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10189 (>= (match-end 0) pos)
10190 (throw 'exit t)))
10191 nil)))
10193 (defun org-get-repeat (&optional tagline)
10194 "Check if there is a deadline/schedule with repeater in this entry."
10195 (save-match-data
10196 (save-excursion
10197 (org-back-to-heading t)
10198 (and (re-search-forward (if tagline
10199 (concat tagline "\\s-*" org-repeat-re)
10200 org-repeat-re)
10201 (org-entry-end-position) t)
10202 (match-string-no-properties 1)))))
10204 (defvar org-last-changed-timestamp)
10205 (defvar org-last-inserted-timestamp)
10206 (defvar org-log-post-message)
10207 (defvar org-log-note-purpose)
10208 (defvar org-log-note-how)
10209 (defvar org-log-note-extra)
10210 (defun org-auto-repeat-maybe (done-word)
10211 "Check if the current headline contains a repeated deadline/schedule.
10212 If yes, set TODO state back to what it was and change the base date
10213 of repeating deadline/scheduled time stamps to new date.
10214 This function is run automatically after each state change to a DONE state."
10215 ;; last-state is dynamically scoped into this function
10216 (let* ((repeat (org-get-repeat))
10217 (aa (assoc last-state org-todo-kwd-alist))
10218 (interpret (nth 1 aa))
10219 (head (nth 2 aa))
10220 (whata '(("d" . day) ("m" . month) ("y" . year)))
10221 (msg "Entry repeats: ")
10222 (org-log-done nil)
10223 (org-todo-log-states nil)
10224 (nshiftmax 10) (nshift 0)
10225 re type n what ts time)
10226 (when repeat
10227 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10228 (org-todo (if (eq interpret 'type) last-state head))
10229 (org-entry-put nil "LAST_REPEAT" (format-time-string
10230 (org-time-stamp-format t t)))
10231 (when org-log-repeat
10232 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10233 (memq 'org-add-log-note post-command-hook))
10234 ;; OK, we are already setup for some record
10235 (if (eq org-log-repeat 'note)
10236 ;; make sure we take a note, not only a time stamp
10237 (setq org-log-note-how 'note))
10238 ;; Set up for taking a record
10239 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10240 last-state
10241 'findpos org-log-repeat)))
10242 (org-back-to-heading t)
10243 (org-add-planning-info nil nil 'closed)
10244 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10245 org-deadline-time-regexp "\\)\\|\\("
10246 org-ts-regexp "\\)"))
10247 (while (re-search-forward
10248 re (save-excursion (outline-next-heading) (point)) t)
10249 (setq type (if (match-end 1) org-scheduled-string
10250 (if (match-end 3) org-deadline-string "Plain:"))
10251 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10252 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10253 (setq n (string-to-number (match-string 2 ts))
10254 what (match-string 3 ts))
10255 (if (equal what "w") (setq n (* n 7) what "d"))
10256 ;; Preparation, see if we need to modify the start date for the change
10257 (when (match-end 1)
10258 (setq time (save-match-data (org-time-string-to-time ts)))
10259 (cond
10260 ((equal (match-string 1 ts) ".")
10261 ;; Shift starting date to today
10262 (org-timestamp-change
10263 (- (time-to-days (current-time)) (time-to-days time))
10264 'day))
10265 ((equal (match-string 1 ts) "+")
10266 (while (or (= nshift 0)
10267 (<= (time-to-days time) (time-to-days (current-time))))
10268 (when (= (incf nshift) nshiftmax)
10269 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10270 (error "Abort")))
10271 (org-timestamp-change n (cdr (assoc what whata)))
10272 (org-at-timestamp-p t)
10273 (setq ts (match-string 1))
10274 (setq time (save-match-data (org-time-string-to-time ts))))
10275 (org-timestamp-change (- n) (cdr (assoc what whata)))
10276 ;; rematch, so that we have everything in place for the real shift
10277 (org-at-timestamp-p t)
10278 (setq ts (match-string 1))
10279 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10280 (org-timestamp-change n (cdr (assoc what whata)))
10281 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10282 (setq org-log-post-message msg)
10283 (message "%s" msg))))
10285 (defun org-show-todo-tree (arg)
10286 "Make a compact tree which shows all headlines marked with TODO.
10287 The tree will show the lines where the regexp matches, and all higher
10288 headlines above the match.
10289 With a \\[universal-argument] prefix, prompt for a regexp to match.
10290 With a numeric prefix N, construct a sparse tree for the Nth element
10291 of `org-todo-keywords-1'."
10292 (interactive "P")
10293 (let ((case-fold-search nil)
10294 (kwd-re
10295 (cond ((null arg) org-not-done-regexp)
10296 ((equal arg '(4))
10297 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10298 (mapcar 'list org-todo-keywords-1))))
10299 (concat "\\("
10300 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10301 "\\)\\>")))
10302 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10303 (regexp-quote (nth (1- (prefix-numeric-value arg))
10304 org-todo-keywords-1)))
10305 (t (error "Invalid prefix argument: %s" arg)))))
10306 (message "%d TODO entries found"
10307 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10309 (defun org-deadline (&optional remove time)
10310 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10311 With argument REMOVE, remove any deadline from the item.
10312 When TIME is set, it should be an internal time specification, and the
10313 scheduling will use the corresponding date."
10314 (interactive "P")
10315 (if remove
10316 (progn
10317 (org-remove-timestamp-with-keyword org-deadline-string)
10318 (message "Item no longer has a deadline."))
10319 (if (org-get-repeat)
10320 (error "Cannot change deadline on task with repeater, please do that by hand")
10321 (org-add-planning-info 'deadline time 'closed)
10322 (message "Deadline on %s" org-last-inserted-timestamp))))
10324 (defun org-schedule (&optional remove time)
10325 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10326 With argument REMOVE, remove any scheduling date from the item.
10327 When TIME is set, it should be an internal time specification, and the
10328 scheduling will use the corresponding date."
10329 (interactive "P")
10330 (if remove
10331 (progn
10332 (org-remove-timestamp-with-keyword org-scheduled-string)
10333 (message "Item is no longer scheduled."))
10334 (if (org-get-repeat)
10335 (error "Cannot reschedule task with repeater, please do that by hand")
10336 (org-add-planning-info 'scheduled time 'closed)
10337 (message "Scheduled to %s" org-last-inserted-timestamp))))
10339 (defun org-get-scheduled-time (pom &optional inherit)
10340 "Get the scheduled time as a time tuple, of a format suitable
10341 for calling org-schedule with, or if there is no scheduling,
10342 returns nil."
10343 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10344 (when time
10345 (apply 'encode-time (org-parse-time-string time)))))
10347 (defun org-get-deadline-time (pom &optional inherit)
10348 "Get the deadine as a time tuple, of a format suitable for
10349 calling org-deadlin with, or if there is no scheduling, returns
10350 nil."
10351 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10352 (when time
10353 (apply 'encode-time (org-parse-time-string time)))))
10355 (defun org-remove-timestamp-with-keyword (keyword)
10356 "Remove all time stamps with KEYWORD in the current entry."
10357 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10358 beg)
10359 (save-excursion
10360 (org-back-to-heading t)
10361 (setq beg (point))
10362 (outline-next-heading)
10363 (while (re-search-backward re beg t)
10364 (replace-match "")
10365 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10366 (equal (char-before) ?\ ))
10367 (backward-delete-char 1)
10368 (if (string-match "^[ \t]*$" (buffer-substring
10369 (point-at-bol) (point-at-eol)))
10370 (delete-region (point-at-bol)
10371 (min (point-max) (1+ (point-at-eol))))))))))
10373 (defun org-add-planning-info (what &optional time &rest remove)
10374 "Insert new timestamp with keyword in the line directly after the headline.
10375 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10376 If non is given, the user is prompted for a date.
10377 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10378 be removed."
10379 (interactive)
10380 (let (org-time-was-given org-end-time-was-given ts
10381 end default-time default-input)
10383 (catch 'exit
10384 (when (and (not time) (memq what '(scheduled deadline)))
10385 ;; Try to get a default date/time from existing timestamp
10386 (save-excursion
10387 (org-back-to-heading t)
10388 (setq end (save-excursion (outline-next-heading) (point)))
10389 (when (re-search-forward (if (eq what 'scheduled)
10390 org-scheduled-time-regexp
10391 org-deadline-time-regexp)
10392 end t)
10393 (setq ts (match-string 1)
10394 default-time
10395 (apply 'encode-time (org-parse-time-string ts))
10396 default-input (and ts (org-get-compact-tod ts))))))
10397 (when what
10398 ;; If necessary, get the time from the user
10399 (setq time (or time (org-read-date nil 'to-time nil nil
10400 default-time default-input))))
10402 (when (and org-insert-labeled-timestamps-at-point
10403 (member what '(scheduled deadline)))
10404 (insert
10405 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10406 (org-insert-time-stamp time org-time-was-given
10407 nil nil nil (list org-end-time-was-given))
10408 (setq what nil))
10409 (save-excursion
10410 (save-restriction
10411 (let (col list elt ts buffer-invisibility-spec)
10412 (org-back-to-heading t)
10413 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10414 (goto-char (match-end 1))
10415 (setq col (current-column))
10416 (goto-char (match-end 0))
10417 (if (eobp) (insert "\n") (forward-char 1))
10418 (when (and (not what)
10419 (not (looking-at
10420 (concat "[ \t]*"
10421 org-keyword-time-not-clock-regexp))))
10422 ;; Nothing to add, nothing to remove...... :-)
10423 (throw 'exit nil))
10424 (if (and (not (looking-at outline-regexp))
10425 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10426 "[^\r\n]*"))
10427 (not (equal (match-string 1) org-clock-string)))
10428 (narrow-to-region (match-beginning 0) (match-end 0))
10429 (insert-before-markers "\n")
10430 (backward-char 1)
10431 (narrow-to-region (point) (point))
10432 (and org-adapt-indentation (org-indent-to-column col)))
10433 ;; Check if we have to remove something.
10434 (setq list (cons what remove))
10435 (while list
10436 (setq elt (pop list))
10437 (goto-char (point-min))
10438 (when (or (and (eq elt 'scheduled)
10439 (re-search-forward org-scheduled-time-regexp nil t))
10440 (and (eq elt 'deadline)
10441 (re-search-forward org-deadline-time-regexp nil t))
10442 (and (eq elt 'closed)
10443 (re-search-forward org-closed-time-regexp nil t)))
10444 (replace-match "")
10445 (if (looking-at "--+<[^>]+>") (replace-match ""))
10446 (skip-chars-backward " ")
10447 (if (looking-at " +") (replace-match ""))))
10448 (goto-char (point-max))
10449 (and org-adapt-indentation (bolp) (org-indent-to-column col))
10450 (when what
10451 (insert
10452 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10453 (cond ((eq what 'scheduled) org-scheduled-string)
10454 ((eq what 'deadline) org-deadline-string)
10455 ((eq what 'closed) org-closed-string))
10456 " ")
10457 (setq ts (org-insert-time-stamp
10458 time
10459 (or org-time-was-given
10460 (and (eq what 'closed) org-log-done-with-time))
10461 (eq what 'closed)
10462 nil nil (list org-end-time-was-given)))
10463 (end-of-line 1))
10464 (goto-char (point-min))
10465 (widen)
10466 (if (and (looking-at "[ \t]+\n")
10467 (equal (char-before) ?\n))
10468 (delete-region (1- (point)) (point-at-eol)))
10469 ts))))))
10471 (defvar org-log-note-marker (make-marker))
10472 (defvar org-log-note-purpose nil)
10473 (defvar org-log-note-state nil)
10474 (defvar org-log-note-previous-state nil)
10475 (defvar org-log-note-how nil)
10476 (defvar org-log-note-extra nil)
10477 (defvar org-log-note-window-configuration nil)
10478 (defvar org-log-note-return-to (make-marker))
10479 (defvar org-log-post-message nil
10480 "Message to be displayed after a log note has been stored.
10481 The auto-repeater uses this.")
10483 (defun org-add-note ()
10484 "Add a note to the current entry.
10485 This is done in the same way as adding a state change note."
10486 (interactive)
10487 (org-add-log-setup 'note nil nil 'findpos nil))
10489 (defvar org-property-end-re)
10490 (defun org-add-log-setup (&optional purpose state prev-state
10491 findpos how &optional extra)
10492 "Set up the post command hook to take a note.
10493 If this is about to TODO state change, the new state is expected in STATE.
10494 When FINDPOS is non-nil, find the correct position for the note in
10495 the current entry. If not, assume that it can be inserted at point.
10496 HOW is an indicator what kind of note should be created.
10497 EXTRA is additional text that will be inserted into the notes buffer."
10498 (let* ((org-log-into-drawer (org-log-into-drawer))
10499 (drawer (cond ((stringp org-log-into-drawer)
10500 org-log-into-drawer)
10501 (org-log-into-drawer "LOGBOOK")
10502 (t nil))))
10503 (save-restriction
10504 (save-excursion
10505 (when findpos
10506 (org-back-to-heading t)
10507 (narrow-to-region (point) (save-excursion
10508 (outline-next-heading) (point)))
10509 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10510 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10511 "[^\r\n]*\\)?"))
10512 (goto-char (match-end 0))
10513 (cond
10514 (drawer
10515 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10516 nil t)
10517 (progn
10518 (goto-char (match-end 0))
10519 (or org-log-states-order-reversed
10520 (and (re-search-forward org-property-end-re nil t)
10521 (goto-char (1- (match-beginning 0))))))
10522 (insert "\n:" drawer ":\n:END:")
10523 (beginning-of-line 0)
10524 (org-indent-line-function)
10525 (beginning-of-line 2)
10526 (org-indent-line-function)
10527 (end-of-line 0)))
10528 ((and org-log-state-notes-insert-after-drawers
10529 (save-excursion
10530 (forward-line) (looking-at org-drawer-regexp)))
10531 (forward-line)
10532 (while (looking-at org-drawer-regexp)
10533 (goto-char (match-end 0))
10534 (re-search-forward org-property-end-re (point-max) t)
10535 (forward-line))
10536 (forward-line -1)))
10537 (unless org-log-states-order-reversed
10538 (and (= (char-after) ?\n) (forward-char 1))
10539 (org-skip-over-state-notes)
10540 (skip-chars-backward " \t\n\r")))
10541 (move-marker org-log-note-marker (point))
10542 (setq org-log-note-purpose purpose
10543 org-log-note-state state
10544 org-log-note-previous-state prev-state
10545 org-log-note-how how
10546 org-log-note-extra extra)
10547 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10549 (defun org-skip-over-state-notes ()
10550 "Skip past the list of State notes in an entry."
10551 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10552 (while (looking-at "[ \t]*- State")
10553 (condition-case nil
10554 (org-next-item)
10555 (error (org-end-of-item)))))
10557 (defun org-add-log-note (&optional purpose)
10558 "Pop up a window for taking a note, and add this note later at point."
10559 (remove-hook 'post-command-hook 'org-add-log-note)
10560 (setq org-log-note-window-configuration (current-window-configuration))
10561 (delete-other-windows)
10562 (move-marker org-log-note-return-to (point))
10563 (switch-to-buffer (marker-buffer org-log-note-marker))
10564 (goto-char org-log-note-marker)
10565 (org-switch-to-buffer-other-window "*Org Note*")
10566 (erase-buffer)
10567 (if (memq org-log-note-how '(time state))
10568 (let (current-prefix-arg) (org-store-log-note))
10569 (let ((org-inhibit-startup t)) (org-mode))
10570 (insert (format "# Insert note for %s.
10571 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10572 (cond
10573 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10574 ((eq org-log-note-purpose 'done) "closed todo item")
10575 ((eq org-log-note-purpose 'state)
10576 (format "state change from \"%s\" to \"%s\""
10577 (or org-log-note-previous-state "")
10578 (or org-log-note-state "")))
10579 ((eq org-log-note-purpose 'note)
10580 "this entry")
10581 (t (error "This should not happen")))))
10582 (if org-log-note-extra (insert org-log-note-extra))
10583 (org-set-local 'org-finish-function 'org-store-log-note)))
10585 (defvar org-note-abort nil) ; dynamically scoped
10586 (defun org-store-log-note ()
10587 "Finish taking a log note, and insert it to where it belongs."
10588 (let ((txt (buffer-string))
10589 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10590 lines ind)
10591 (kill-buffer (current-buffer))
10592 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10593 (setq txt (replace-match "" t t txt)))
10594 (if (string-match "\\s-+\\'" txt)
10595 (setq txt (replace-match "" t t txt)))
10596 (setq lines (org-split-string txt "\n"))
10597 (when (and note (string-match "\\S-" note))
10598 (setq note
10599 (org-replace-escapes
10600 note
10601 (list (cons "%u" (user-login-name))
10602 (cons "%U" user-full-name)
10603 (cons "%t" (format-time-string
10604 (org-time-stamp-format 'long 'inactive)
10605 (current-time)))
10606 (cons "%s" (if org-log-note-state
10607 (concat "\"" org-log-note-state "\"")
10608 ""))
10609 (cons "%S" (if org-log-note-previous-state
10610 (concat "\"" org-log-note-previous-state "\"")
10611 "\"\"")))))
10612 (if lines (setq note (concat note " \\\\")))
10613 (push note lines))
10614 (when (or current-prefix-arg org-note-abort)
10615 (when org-log-into-drawer
10616 (org-remove-empty-drawer-at
10617 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10618 org-log-note-marker))
10619 (setq lines nil))
10620 (when lines
10621 (with-current-buffer (marker-buffer org-log-note-marker)
10622 (save-excursion
10623 (goto-char org-log-note-marker)
10624 (move-marker org-log-note-marker nil)
10625 (end-of-line 1)
10626 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10627 (insert "- " (pop lines))
10628 (org-indent-line-function)
10629 (beginning-of-line 1)
10630 (looking-at "[ \t]*")
10631 (setq ind (concat (match-string 0) " "))
10632 (end-of-line 1)
10633 (while lines (insert "\n" ind (pop lines)))
10634 (message "Note stored")
10635 (org-back-to-heading t)
10636 (org-cycle-hide-drawers 'children)))))
10637 (set-window-configuration org-log-note-window-configuration)
10638 (with-current-buffer (marker-buffer org-log-note-return-to)
10639 (goto-char org-log-note-return-to))
10640 (move-marker org-log-note-return-to nil)
10641 (and org-log-post-message (message "%s" org-log-post-message)))
10643 (defun org-remove-empty-drawer-at (drawer pos)
10644 "Remove an emptyr DARWER drawer at position POS.
10645 POS may also be a marker."
10646 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10647 (save-excursion
10648 (save-restriction
10649 (widen)
10650 (goto-char pos)
10651 (if (org-in-regexp
10652 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10653 (replace-match ""))))))
10655 (defun org-sparse-tree (&optional arg)
10656 "Create a sparse tree, prompt for the details.
10657 This command can create sparse trees. You first need to select the type
10658 of match used to create the tree:
10660 t Show entries with a specific TODO keyword.
10661 m Show entries selected by a tags/property match.
10662 p Enter a property name and its value (both with completion on existing
10663 names/values) and show entries with that property.
10664 / Show entries matching a regular expression (`r' can be used as well)
10665 d Show deadlines due within `org-deadline-warning-days'.
10666 b Show deadlines and scheduled items before a date.
10667 a Show deadlines and scheduled items after a date."
10668 (interactive "P")
10669 (let (ans kwd value)
10670 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10671 (setq ans (read-char-exclusive))
10672 (cond
10673 ((equal ans ?d)
10674 (call-interactively 'org-check-deadlines))
10675 ((equal ans ?b)
10676 (call-interactively 'org-check-before-date))
10677 ((equal ans ?a)
10678 (call-interactively 'org-check-after-date))
10679 ((equal ans ?t)
10680 (org-show-todo-tree '(4)))
10681 ((member ans '(?T ?m))
10682 (call-interactively 'org-match-sparse-tree))
10683 ((member ans '(?p ?P))
10684 (setq kwd (org-icompleting-read "Property: "
10685 (mapcar 'list (org-buffer-property-keys))))
10686 (setq value (org-icompleting-read "Value: "
10687 (mapcar 'list (org-property-values kwd))))
10688 (unless (string-match "\\`{.*}\\'" value)
10689 (setq value (concat "\"" value "\"")))
10690 (org-match-sparse-tree arg (concat kwd "=" value)))
10691 ((member ans '(?r ?R ?/))
10692 (call-interactively 'org-occur))
10693 (t (error "No such sparse tree command \"%c\"" ans)))))
10695 (defvar org-occur-highlights nil
10696 "List of overlays used for occur matches.")
10697 (make-variable-buffer-local 'org-occur-highlights)
10698 (defvar org-occur-parameters nil
10699 "Parameters of the active org-occur calls.
10700 This is a list, each call to org-occur pushes as cons cell,
10701 containing the regular expression and the callback, onto the list.
10702 The list can contain several entries if `org-occur' has been called
10703 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10704 will only contain one set of parameters. When the highlights are
10705 removed (for example with `C-c C-c', or with the next edit (depending
10706 on `org-remove-highlights-with-change'), this variable is emptied
10707 as well.")
10708 (make-variable-buffer-local 'org-occur-parameters)
10710 (defun org-occur (regexp &optional keep-previous callback)
10711 "Make a compact tree which shows all matches of REGEXP.
10712 The tree will show the lines where the regexp matches, and all higher
10713 headlines above the match. It will also show the heading after the match,
10714 to make sure editing the matching entry is easy.
10715 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10716 call to `org-occur' will be kept, to allow stacking of calls to this
10717 command.
10718 If CALLBACK is non-nil, it is a function which is called to confirm
10719 that the match should indeed be shown."
10720 (interactive "sRegexp: \nP")
10721 (when (equal regexp "")
10722 (error "Regexp cannot be empty"))
10723 (unless keep-previous
10724 (org-remove-occur-highlights nil nil t))
10725 (push (cons regexp callback) org-occur-parameters)
10726 (let ((cnt 0))
10727 (save-excursion
10728 (goto-char (point-min))
10729 (if (or (not keep-previous) ; do not want to keep
10730 (not org-occur-highlights)) ; no previous matches
10731 ;; hide everything
10732 (org-overview))
10733 (while (re-search-forward regexp nil t)
10734 (when (or (not callback)
10735 (save-match-data (funcall callback)))
10736 (setq cnt (1+ cnt))
10737 (when org-highlight-sparse-tree-matches
10738 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10739 (org-show-context 'occur-tree))))
10740 (when org-remove-highlights-with-change
10741 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10742 nil 'local))
10743 (unless org-sparse-tree-open-archived-trees
10744 (org-hide-archived-subtrees (point-min) (point-max)))
10745 (run-hooks 'org-occur-hook)
10746 (if (interactive-p)
10747 (message "%d match(es) for regexp %s" cnt regexp))
10748 cnt))
10750 (defun org-show-context (&optional key)
10751 "Make sure point and context and visible.
10752 How much context is shown depends upon the variables
10753 `org-show-hierarchy-above', `org-show-following-heading'. and
10754 `org-show-siblings'."
10755 (let ((heading-p (org-on-heading-p t))
10756 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10757 (following-p (org-get-alist-option org-show-following-heading key))
10758 (entry-p (org-get-alist-option org-show-entry-below key))
10759 (siblings-p (org-get-alist-option org-show-siblings key)))
10760 (catch 'exit
10761 ;; Show heading or entry text
10762 (if (and heading-p (not entry-p))
10763 (org-flag-heading nil) ; only show the heading
10764 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10765 (org-show-hidden-entry))) ; show entire entry
10766 (when following-p
10767 ;; Show next sibling, or heading below text
10768 (save-excursion
10769 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10770 (org-flag-heading nil))))
10771 (when siblings-p (org-show-siblings))
10772 (when hierarchy-p
10773 ;; show all higher headings, possibly with siblings
10774 (save-excursion
10775 (while (and (condition-case nil
10776 (progn (org-up-heading-all 1) t)
10777 (error nil))
10778 (not (bobp)))
10779 (org-flag-heading nil)
10780 (when siblings-p (org-show-siblings))))))))
10782 (defun org-reveal (&optional siblings)
10783 "Show current entry, hierarchy above it, and the following headline.
10784 This can be used to show a consistent set of context around locations
10785 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10786 not t for the search context.
10788 With optional argument SIBLINGS, on each level of the hierarchy all
10789 siblings are shown. This repairs the tree structure to what it would
10790 look like when opened with hierarchical calls to `org-cycle'."
10791 (interactive "P")
10792 (let ((org-show-hierarchy-above t)
10793 (org-show-following-heading t)
10794 (org-show-siblings (if siblings t org-show-siblings)))
10795 (org-show-context nil)))
10797 (defun org-highlight-new-match (beg end)
10798 "Highlight from BEG to END and mark the highlight is an occur headline."
10799 (let ((ov (org-make-overlay beg end)))
10800 (org-overlay-put ov 'face 'secondary-selection)
10801 (push ov org-occur-highlights)))
10803 (defun org-remove-occur-highlights (&optional beg end noremove)
10804 "Remove the occur highlights from the buffer.
10805 BEG and END are ignored. If NOREMOVE is nil, remove this function
10806 from the `before-change-functions' in the current buffer."
10807 (interactive)
10808 (unless org-inhibit-highlight-removal
10809 (mapc 'org-delete-overlay org-occur-highlights)
10810 (setq org-occur-highlights nil)
10811 (setq org-occur-parameters nil)
10812 (unless noremove
10813 (remove-hook 'before-change-functions
10814 'org-remove-occur-highlights 'local))))
10816 ;;;; Priorities
10818 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10819 "Regular expression matching the priority indicator.")
10821 (defvar org-remove-priority-next-time nil)
10823 (defun org-priority-up ()
10824 "Increase the priority of the current item."
10825 (interactive)
10826 (org-priority 'up))
10828 (defun org-priority-down ()
10829 "Decrease the priority of the current item."
10830 (interactive)
10831 (org-priority 'down))
10833 (defun org-priority (&optional action)
10834 "Change the priority of an item by ARG.
10835 ACTION can be `set', `up', `down', or a character."
10836 (interactive)
10837 (unless org-enable-priority-commands
10838 (error "Priority commands are disabled"))
10839 (setq action (or action 'set))
10840 (let (current new news have remove)
10841 (save-excursion
10842 (org-back-to-heading t)
10843 (if (looking-at org-priority-regexp)
10844 (setq current (string-to-char (match-string 2))
10845 have t)
10846 (setq current org-default-priority))
10847 (cond
10848 ((eq action 'remove)
10849 (setq remove t new ?\ ))
10850 ((or (eq action 'set)
10851 (if (featurep 'xemacs) (characterp action) (integerp action)))
10852 (if (not (eq action 'set))
10853 (setq new action)
10854 (message "Priority %c-%c, SPC to remove: "
10855 org-highest-priority org-lowest-priority)
10856 (setq new (read-char-exclusive)))
10857 (if (and (= (upcase org-highest-priority) org-highest-priority)
10858 (= (upcase org-lowest-priority) org-lowest-priority))
10859 (setq new (upcase new)))
10860 (cond ((equal new ?\ ) (setq remove t))
10861 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10862 (error "Priority must be between `%c' and `%c'"
10863 org-highest-priority org-lowest-priority))))
10864 ((eq action 'up)
10865 (if (and (not have) (eq last-command this-command))
10866 (setq new org-lowest-priority)
10867 (setq new (if (and org-priority-start-cycle-with-default (not have))
10868 org-default-priority (1- current)))))
10869 ((eq action 'down)
10870 (if (and (not have) (eq last-command this-command))
10871 (setq new org-highest-priority)
10872 (setq new (if (and org-priority-start-cycle-with-default (not have))
10873 org-default-priority (1+ current)))))
10874 (t (error "Invalid action")))
10875 (if (or (< (upcase new) org-highest-priority)
10876 (> (upcase new) org-lowest-priority))
10877 (setq remove t))
10878 (setq news (format "%c" new))
10879 (if have
10880 (if remove
10881 (replace-match "" t t nil 1)
10882 (replace-match news t t nil 2))
10883 (if remove
10884 (error "No priority cookie found in line")
10885 (let ((case-fold-search nil))
10886 (looking-at org-todo-line-regexp))
10887 (if (match-end 2)
10888 (progn
10889 (goto-char (match-end 2))
10890 (insert " [#" news "]"))
10891 (goto-char (match-beginning 3))
10892 (insert "[#" news "] "))))
10893 (org-preserve-lc (org-set-tags nil 'align)))
10894 (if remove
10895 (message "Priority removed")
10896 (message "Priority of current item set to %s" news))))
10898 (defun org-get-priority (s)
10899 "Find priority cookie and return priority."
10900 (save-match-data
10901 (if (not (string-match org-priority-regexp s))
10902 (* 1000 (- org-lowest-priority org-default-priority))
10903 (* 1000 (- org-lowest-priority
10904 (string-to-char (match-string 2 s)))))))
10906 ;;;; Tags
10908 (defvar org-agenda-archives-mode)
10909 (defvar org-map-continue-from nil
10910 "Position from where mapping should continue.
10911 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10913 (defvar org-scanner-tags nil
10914 "The current tag list while the tags scanner is running.")
10915 (defvar org-trust-scanner-tags nil
10916 "Should `org-get-tags-at' use the tags fro the scanner.
10917 This is for internal dynamical scoping only.
10918 When this is non-nil, the function `org-get-tags-at' will return the value
10919 of `org-scanner-tags' instead of building the list by itself. This
10920 can lead to large speed-ups when the tags scanner is used in a file with
10921 many entries, and when the list of tags is retrieved, for example to
10922 obtain a list of properties. Building the tags list for each entry in such
10923 a file becomes an N^2 operation - but with this variable set, it scales
10924 as N.")
10926 (defun org-scan-tags (action matcher &optional todo-only)
10927 "Scan headline tags with inheritance and produce output ACTION.
10929 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10930 or `agenda' to produce an entry list for an agenda view. It can also be
10931 a Lisp form or a function that should be called at each matched headline, in
10932 this case the return value is a list of all return values from these calls.
10934 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10935 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10936 only lines with a TODO keyword are included in the output."
10937 (require 'org-agenda)
10938 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10939 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10940 (org-re
10941 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10942 (props (list 'face 'default
10943 'done-face 'org-agenda-done
10944 'undone-face 'default
10945 'mouse-face 'highlight
10946 'org-not-done-regexp org-not-done-regexp
10947 'org-todo-regexp org-todo-regexp
10948 'help-echo
10949 (format "mouse-2 or RET jump to org file %s"
10950 (abbreviate-file-name
10951 (or (buffer-file-name (buffer-base-buffer))
10952 (buffer-name (buffer-base-buffer)))))))
10953 (case-fold-search nil)
10954 (org-map-continue-from nil)
10955 lspos tags tags-list
10956 (tags-alist (list (cons 0 org-file-tags)))
10957 (llast 0) rtn rtn1 level category i txt
10958 todo marker entry priority)
10959 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10960 (setq action (list 'lambda nil action)))
10961 (save-excursion
10962 (goto-char (point-min))
10963 (when (eq action 'sparse-tree)
10964 (org-overview)
10965 (org-remove-occur-highlights))
10966 (while (re-search-forward re nil t)
10967 (catch :skip
10968 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10969 tags (if (match-end 4) (org-match-string-no-properties 4)))
10970 (goto-char (setq lspos (match-beginning 0)))
10971 (setq level (org-reduced-level (funcall outline-level))
10972 category (org-get-category))
10973 (setq i llast llast level)
10974 ;; remove tag lists from same and sublevels
10975 (while (>= i level)
10976 (when (setq entry (assoc i tags-alist))
10977 (setq tags-alist (delete entry tags-alist)))
10978 (setq i (1- i)))
10979 ;; add the next tags
10980 (when tags
10981 (setq tags (org-split-string tags ":")
10982 tags-alist
10983 (cons (cons level tags) tags-alist)))
10984 ;; compile tags for current headline
10985 (setq tags-list
10986 (if org-use-tag-inheritance
10987 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10988 tags)
10989 org-scanner-tags tags-list)
10990 (when org-use-tag-inheritance
10991 (setcdr (car tags-alist)
10992 (mapcar (lambda (x)
10993 (setq x (copy-sequence x))
10994 (org-add-prop-inherited x))
10995 (cdar tags-alist))))
10996 (when (and tags org-use-tag-inheritance
10997 (or (not (eq t org-use-tag-inheritance))
10998 org-tags-exclude-from-inheritance))
10999 ;; selective inheritance, remove uninherited ones
11000 (setcdr (car tags-alist)
11001 (org-remove-uniherited-tags (cdar tags-alist))))
11002 (when (and (or (not todo-only)
11003 (and (member todo org-not-done-keywords)
11004 (or (not org-agenda-tags-todo-honor-ignore-options)
11005 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11006 (let ((case-fold-search t)) (eval matcher))
11008 (not (member org-archive-tag tags-list))
11009 ;; we have an archive tag, should we use this anyway?
11010 (or (not org-agenda-skip-archived-trees)
11011 (and (eq action 'agenda) org-agenda-archives-mode))))
11012 (unless (eq action 'sparse-tree) (org-agenda-skip))
11014 ;; select this headline
11016 (cond
11017 ((eq action 'sparse-tree)
11018 (and org-highlight-sparse-tree-matches
11019 (org-get-heading) (match-end 0)
11020 (org-highlight-new-match
11021 (match-beginning 0) (match-beginning 1)))
11022 (org-show-context 'tags-tree))
11023 ((eq action 'agenda)
11024 (setq txt (org-format-agenda-item
11026 (concat
11027 (if (eq org-tags-match-list-sublevels 'indented)
11028 (make-string (1- level) ?.) "")
11029 (org-get-heading))
11030 category
11031 tags-list
11033 priority (org-get-priority txt))
11034 (goto-char lspos)
11035 (setq marker (org-agenda-new-marker))
11036 (org-add-props txt props
11037 'org-marker marker 'org-hd-marker marker 'org-category category
11038 'todo-state todo
11039 'priority priority 'type "tagsmatch")
11040 (push txt rtn))
11041 ((functionp action)
11042 (setq org-map-continue-from nil)
11043 (save-excursion
11044 (setq rtn1 (funcall action))
11045 (push rtn1 rtn)))
11046 (t (error "Invalid action")))
11048 ;; if we are to skip sublevels, jump to end of subtree
11049 (unless org-tags-match-list-sublevels
11050 (org-end-of-subtree t)
11051 (backward-char 1))))
11052 ;; Get the correct position from where to continue
11053 (if org-map-continue-from
11054 (goto-char org-map-continue-from)
11055 (and (= (point) lspos) (end-of-line 1)))))
11056 (when (and (eq action 'sparse-tree)
11057 (not org-sparse-tree-open-archived-trees))
11058 (org-hide-archived-subtrees (point-min) (point-max)))
11059 (nreverse rtn)))
11061 (defun org-remove-uniherited-tags (tags)
11062 "Remove all tags that are not inherited from the list TAGS."
11063 (cond
11064 ((eq org-use-tag-inheritance t)
11065 (if org-tags-exclude-from-inheritance
11066 (org-delete-all org-tags-exclude-from-inheritance tags)
11067 tags))
11068 ((not org-use-tag-inheritance) nil)
11069 ((stringp org-use-tag-inheritance)
11070 (delq nil (mapcar
11071 (lambda (x)
11072 (if (and (string-match org-use-tag-inheritance x)
11073 (not (member x org-tags-exclude-from-inheritance)))
11074 x nil))
11075 tags)))
11076 ((listp org-use-tag-inheritance)
11077 (delq nil (mapcar
11078 (lambda (x)
11079 (if (member x org-use-tag-inheritance) x nil))
11080 tags)))))
11082 (defvar todo-only) ;; dynamically scoped
11084 (defun org-match-sparse-tree (&optional todo-only match)
11085 "Create a sparse tree according to tags string MATCH.
11086 MATCH can contain positive and negative selection of tags, like
11087 \"+WORK+URGENT-WITHBOSS\".
11088 If optional argument TODO-ONLY is non-nil, only select lines that are
11089 also TODO lines."
11090 (interactive "P")
11091 (org-prepare-agenda-buffers (list (current-buffer)))
11092 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11094 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11096 (defvar org-cached-props nil)
11097 (defun org-cached-entry-get (pom property)
11098 (if (or (eq t org-use-property-inheritance)
11099 (and (stringp org-use-property-inheritance)
11100 (string-match org-use-property-inheritance property))
11101 (and (listp org-use-property-inheritance)
11102 (member property org-use-property-inheritance)))
11103 ;; Caching is not possible, check it directly
11104 (org-entry-get pom property 'inherit)
11105 ;; Get all properties, so that we can do complicated checks easily
11106 (cdr (assoc property (or org-cached-props
11107 (setq org-cached-props
11108 (org-entry-properties pom)))))))
11110 (defun org-global-tags-completion-table (&optional files)
11111 "Return the list of all tags in all agenda buffer/files."
11112 (save-excursion
11113 (org-uniquify
11114 (delq nil
11115 (apply 'append
11116 (mapcar
11117 (lambda (file)
11118 (set-buffer (find-file-noselect file))
11119 (append (org-get-buffer-tags)
11120 (mapcar (lambda (x) (if (stringp (car-safe x))
11121 (list (car-safe x)) nil))
11122 org-tag-alist)))
11123 (if (and files (car files))
11124 files
11125 (org-agenda-files))))))))
11127 (defun org-make-tags-matcher (match)
11128 "Create the TAGS//TODO matcher form for the selection string MATCH."
11129 ;; todo-only is scoped dynamically into this function, and the function
11130 ;; may change it if the matcher asks for it.
11131 (unless match
11132 ;; Get a new match request, with completion
11133 (let ((org-last-tags-completion-table
11134 (org-global-tags-completion-table)))
11135 (setq match (org-completing-read-no-i
11136 "Match: " 'org-tags-completion-function nil nil nil
11137 'org-tags-history))))
11139 ;; Parse the string and create a lisp form
11140 (let ((match0 match)
11141 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11142 minus tag mm
11143 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11144 orterms term orlist re-p str-p level-p level-op time-p
11145 prop-p pn pv po cat-p gv rest)
11146 (if (string-match "/+" match)
11147 ;; match contains also a todo-matching request
11148 (progn
11149 (setq tagsmatch (substring match 0 (match-beginning 0))
11150 todomatch (substring match (match-end 0)))
11151 (if (string-match "^!" todomatch)
11152 (setq todo-only t todomatch (substring todomatch 1)))
11153 (if (string-match "^\\s-*$" todomatch)
11154 (setq todomatch nil)))
11155 ;; only matching tags
11156 (setq tagsmatch match todomatch nil))
11158 ;; Make the tags matcher
11159 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11160 (setq tagsmatcher t)
11161 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11162 (while (setq term (pop orterms))
11163 (while (and (equal (substring term -1) "\\") orterms)
11164 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11165 (while (string-match re term)
11166 (setq rest (substring term (match-end 0))
11167 minus (and (match-end 1)
11168 (equal (match-string 1 term) "-"))
11169 tag (match-string 2 term)
11170 re-p (equal (string-to-char tag) ?{)
11171 level-p (match-end 4)
11172 prop-p (match-end 5)
11173 mm (cond
11174 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11175 (level-p
11176 (setq level-op (org-op-to-function (match-string 3 term)))
11177 `(,level-op level ,(string-to-number
11178 (match-string 4 term))))
11179 (prop-p
11180 (setq pn (match-string 5 term)
11181 po (match-string 6 term)
11182 pv (match-string 7 term)
11183 cat-p (equal pn "CATEGORY")
11184 re-p (equal (string-to-char pv) ?{)
11185 str-p (equal (string-to-char pv) ?\")
11186 time-p (save-match-data
11187 (string-match "^\"[[<].*[]>]\"$" pv))
11188 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11189 (if time-p (setq pv (org-matcher-time pv)))
11190 (setq po (org-op-to-function po (if time-p 'time str-p)))
11191 (cond
11192 ((equal pn "CATEGORY")
11193 (setq gv '(get-text-property (point) 'org-category)))
11194 ((equal pn "TODO")
11195 (setq gv 'todo))
11197 (setq gv `(org-cached-entry-get nil ,pn))))
11198 (if re-p
11199 (if (eq po 'org<>)
11200 `(not (string-match ,pv (or ,gv "")))
11201 `(string-match ,pv (or ,gv "")))
11202 (if str-p
11203 `(,po (or ,gv "") ,pv)
11204 `(,po (string-to-number (or ,gv ""))
11205 ,(string-to-number pv) ))))
11206 (t `(member ,tag tags-list)))
11207 mm (if minus (list 'not mm) mm)
11208 term rest)
11209 (push mm tagsmatcher))
11210 (push (if (> (length tagsmatcher) 1)
11211 (cons 'and tagsmatcher)
11212 (car tagsmatcher))
11213 orlist)
11214 (setq tagsmatcher nil))
11215 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11216 (setq tagsmatcher
11217 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11218 ;; Make the todo matcher
11219 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11220 (setq todomatcher t)
11221 (setq orterms (org-split-string todomatch "|") orlist nil)
11222 (while (setq term (pop orterms))
11223 (while (string-match re term)
11224 (setq minus (and (match-end 1)
11225 (equal (match-string 1 term) "-"))
11226 kwd (match-string 2 term)
11227 re-p (equal (string-to-char kwd) ?{)
11228 term (substring term (match-end 0))
11229 mm (if re-p
11230 `(string-match ,(substring kwd 1 -1) todo)
11231 (list 'equal 'todo kwd))
11232 mm (if minus (list 'not mm) mm))
11233 (push mm todomatcher))
11234 (push (if (> (length todomatcher) 1)
11235 (cons 'and todomatcher)
11236 (car todomatcher))
11237 orlist)
11238 (setq todomatcher nil))
11239 (setq todomatcher (if (> (length orlist) 1)
11240 (cons 'or orlist) (car orlist))))
11242 ;; Return the string and lisp forms of the matcher
11243 (setq matcher (if todomatcher
11244 (list 'and tagsmatcher todomatcher)
11245 tagsmatcher))
11246 (cons match0 matcher)))
11248 (defun org-op-to-function (op &optional stringp)
11249 "Turn an operator into the appropriate function."
11250 (setq op
11251 (cond
11252 ((equal op "<" ) '(< string< org-time<))
11253 ((equal op ">" ) '(> org-string> org-time>))
11254 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11255 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11256 ((member op '("=" "==")) '(= string= org-time=))
11257 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11258 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11260 (defun org<> (a b) (not (= a b)))
11261 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11262 (defun org-string>= (a b) (not (string< a b)))
11263 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11264 (defun org-string<> (a b) (not (string= a b)))
11265 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11266 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11267 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11268 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11269 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11270 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11271 (defun org-2ft (s)
11272 "Convert S to a floating point time.
11273 If S is already a number, just return it. If it is a string, parse
11274 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11275 (cond
11276 ((numberp s) s)
11277 ((stringp s)
11278 (condition-case nil
11279 (float-time (apply 'encode-time (org-parse-time-string s)))
11280 (error 0.)))
11281 (t 0.)))
11283 (defun org-time-today ()
11284 "Time in seconds today at 0:00.
11285 Returns the float number of seconds since the beginning of the
11286 epoch to the beginning of today (00:00)."
11287 (float-time (apply 'encode-time
11288 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11290 (defun org-matcher-time (s)
11291 "Interpret a time comparison value."
11292 (save-match-data
11293 (cond
11294 ((string= s "<now>") (float-time))
11295 ((string= s "<today>") (org-time-today))
11296 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11297 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11298 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11299 (+ (org-time-today)
11300 (* (string-to-number (match-string 1 s))
11301 (cdr (assoc (match-string 2 s)
11302 '(("d" . 86400.0) ("w" . 604800.0)
11303 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11304 (t (org-2ft s)))))
11306 (defun org-match-any-p (re list)
11307 "Does re match any element of list?"
11308 (setq list (mapcar (lambda (x) (string-match re x)) list))
11309 (delq nil list))
11311 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11312 (defvar org-tags-overlay (org-make-overlay 1 1))
11313 (org-detach-overlay org-tags-overlay)
11315 (defun org-get-local-tags-at (&optional pos)
11316 "Get a list of tags defined in the current headline."
11317 (org-get-tags-at pos 'local))
11319 (defun org-get-local-tags ()
11320 "Get a list of tags defined in the current headline."
11321 (org-get-tags-at nil 'local))
11323 (defun org-get-tags-at (&optional pos local)
11324 "Get a list of all headline tags applicable at POS.
11325 POS defaults to point. If tags are inherited, the list contains
11326 the targets in the same sequence as the headlines appear, i.e.
11327 the tags of the current headline come last.
11328 When LOCAL is non-nil, only return tags from the current headline,
11329 ignore inherited ones."
11330 (interactive)
11331 (if (and org-trust-scanner-tags
11332 (or (not pos) (equal pos (point)))
11333 (not local))
11334 org-scanner-tags
11335 (let (tags ltags lastpos parent)
11336 (save-excursion
11337 (save-restriction
11338 (widen)
11339 (goto-char (or pos (point)))
11340 (save-match-data
11341 (catch 'done
11342 (condition-case nil
11343 (progn
11344 (org-back-to-heading t)
11345 (while (not (equal lastpos (point)))
11346 (setq lastpos (point))
11347 (when (looking-at
11348 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11349 (setq ltags (org-split-string
11350 (org-match-string-no-properties 1) ":"))
11351 (when parent
11352 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11353 (setq tags (append
11354 (if parent
11355 (org-remove-uniherited-tags ltags)
11356 ltags)
11357 tags)))
11358 (or org-use-tag-inheritance (throw 'done t))
11359 (if local (throw 'done t))
11360 (or (org-up-heading-safe) (error nil))
11361 (setq parent t)))
11362 (error nil)))))
11363 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11365 (defun org-add-prop-inherited (s)
11366 (add-text-properties 0 (length s) '(inherited t) s)
11369 (defun org-toggle-tag (tag &optional onoff)
11370 "Toggle the tag TAG for the current line.
11371 If ONOFF is `on' or `off', don't toggle but set to this state."
11372 (let (res current)
11373 (save-excursion
11374 (org-back-to-heading t)
11375 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11376 (point-at-eol) t)
11377 (progn
11378 (setq current (match-string 1))
11379 (replace-match ""))
11380 (setq current ""))
11381 (setq current (nreverse (org-split-string current ":")))
11382 (cond
11383 ((eq onoff 'on)
11384 (setq res t)
11385 (or (member tag current) (push tag current)))
11386 ((eq onoff 'off)
11387 (or (not (member tag current)) (setq current (delete tag current))))
11388 (t (if (member tag current)
11389 (setq current (delete tag current))
11390 (setq res t)
11391 (push tag current))))
11392 (end-of-line 1)
11393 (if current
11394 (progn
11395 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11396 (org-set-tags nil t))
11397 (delete-horizontal-space))
11398 (run-hooks 'org-after-tags-change-hook))
11399 res))
11401 (defun org-align-tags-here (to-col)
11402 ;; Assumes that this is a headline
11403 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11404 (beginning-of-line 1)
11405 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11406 (< pos (match-beginning 2)))
11407 (progn
11408 (setq tags-l (- (match-end 2) (match-beginning 2)))
11409 (goto-char (match-beginning 1))
11410 (insert " ")
11411 (delete-region (point) (1+ (match-beginning 2)))
11412 (setq ncol (max (1+ (current-column))
11413 (1+ col)
11414 (if (> to-col 0)
11415 to-col
11416 (- (abs to-col) tags-l))))
11417 (setq p (point))
11418 (insert (make-string (- ncol (current-column)) ?\ ))
11419 (setq ncol (current-column))
11420 (when indent-tabs-mode (tabify p (point-at-eol)))
11421 (org-move-to-column (min ncol col) t))
11422 (goto-char pos))))
11424 (defun org-set-tags-command (&optional arg just-align)
11425 "Call the set-tags command for the current entry."
11426 (interactive "P")
11427 (if (org-on-heading-p)
11428 (org-set-tags arg just-align)
11429 (save-excursion
11430 (org-back-to-heading t)
11431 (org-set-tags arg just-align))))
11433 (defun org-set-tags-to (data)
11434 "Set the tags of the current entry to DATA, replacing the current tags.
11435 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11436 If DATA is nil or the empty string, any tags will be removed."
11437 (interactive "sTags: ")
11438 (setq data
11439 (cond
11440 ((eq data nil) "")
11441 ((equal data "") "")
11442 ((stringp data)
11443 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11444 ":"))
11445 ((listp data)
11446 (concat ":" (mapconcat 'identity data ":") ":"))
11447 (t nil)))
11448 (when data
11449 (save-excursion
11450 (org-back-to-heading t)
11451 (when (looking-at org-complex-heading-regexp)
11452 (if (match-end 5)
11453 (progn
11454 (goto-char (match-beginning 5))
11455 (insert data)
11456 (delete-region (point) (point-at-eol))
11457 (org-set-tags nil 'align))
11458 (goto-char (point-at-eol))
11459 (insert " " data)
11460 (org-set-tags nil 'align)))
11461 (beginning-of-line 1)
11462 (if (looking-at ".*?\\([ \t]+\\)$")
11463 (delete-region (match-beginning 1) (match-end 1))))))
11465 (defun org-set-tags (&optional arg just-align)
11466 "Set the tags for the current headline.
11467 With prefix ARG, realign all tags in headings in the current buffer."
11468 (interactive "P")
11469 (let* ((re (concat "^" outline-regexp))
11470 (current (org-get-tags-string))
11471 (col (current-column))
11472 (org-setting-tags t)
11473 table current-tags inherited-tags ; computed below when needed
11474 tags p0 c0 c1 rpl)
11475 (if arg
11476 (save-excursion
11477 (goto-char (point-min))
11478 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11479 (while (re-search-forward re nil t)
11480 (org-set-tags nil t)
11481 (end-of-line 1)))
11482 (message "All tags realigned to column %d" org-tags-column))
11483 (if just-align
11484 (setq tags current)
11485 ;; Get a new set of tags from the user
11486 (save-excursion
11487 (setq table (append org-tag-persistent-alist
11488 (or org-tag-alist (org-get-buffer-tags)))
11489 org-last-tags-completion-table table
11490 current-tags (org-split-string current ":")
11491 inherited-tags (nreverse
11492 (nthcdr (length current-tags)
11493 (nreverse (org-get-tags-at))))
11494 tags
11495 (if (or (eq t org-use-fast-tag-selection)
11496 (and org-use-fast-tag-selection
11497 (delq nil (mapcar 'cdr table))))
11498 (org-fast-tag-selection
11499 current-tags inherited-tags table
11500 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11501 (let ((org-add-colon-after-tag-completion t))
11502 (org-trim
11503 (org-without-partial-completion
11504 (org-icompleting-read "Tags: " 'org-tags-completion-function
11505 nil nil current 'org-tags-history)))))))
11506 (while (string-match "[-+&]+" tags)
11507 ;; No boolean logic, just a list
11508 (setq tags (replace-match ":" t t tags))))
11510 (if org-tags-sort-function
11511 (setq tags (mapconcat 'identity
11512 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11513 org-tags-sort-function) ":")))
11515 (if (string-match "\\`[\t ]*\\'" tags)
11516 (setq tags "")
11517 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11518 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11520 ;; Insert new tags at the correct column
11521 (beginning-of-line 1)
11522 (cond
11523 ((and (equal current "") (equal tags "")))
11524 ((re-search-forward
11525 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11526 (point-at-eol) t)
11527 (if (equal tags "")
11528 (setq rpl "")
11529 (goto-char (match-beginning 0))
11530 (setq c0 (current-column) p0 (point)
11531 c1 (max (1+ c0) (if (> org-tags-column 0)
11532 org-tags-column
11533 (- (- org-tags-column) (length tags))))
11534 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11535 (replace-match rpl t t)
11536 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11537 tags)
11538 (t (error "Tags alignment failed")))
11539 (org-move-to-column col)
11540 (unless just-align
11541 (run-hooks 'org-after-tags-change-hook)))))
11543 (defun org-change-tag-in-region (beg end tag off)
11544 "Add or remove TAG for each entry in the region.
11545 This works in the agenda, and also in an org-mode buffer."
11546 (interactive
11547 (list (region-beginning) (region-end)
11548 (let ((org-last-tags-completion-table
11549 (if (org-mode-p)
11550 (org-get-buffer-tags)
11551 (org-global-tags-completion-table))))
11552 (org-icompleting-read
11553 "Tag: " 'org-tags-completion-function nil nil nil
11554 'org-tags-history))
11555 (progn
11556 (message "[s]et or [r]emove? ")
11557 (equal (read-char-exclusive) ?r))))
11558 (if (fboundp 'deactivate-mark) (deactivate-mark))
11559 (let ((agendap (equal major-mode 'org-agenda-mode))
11560 l1 l2 m buf pos newhead (cnt 0))
11561 (goto-char end)
11562 (setq l2 (1- (org-current-line)))
11563 (goto-char beg)
11564 (setq l1 (org-current-line))
11565 (loop for l from l1 to l2 do
11566 (org-goto-line l)
11567 (setq m (get-text-property (point) 'org-hd-marker))
11568 (when (or (and (org-mode-p) (org-on-heading-p))
11569 (and agendap m))
11570 (setq buf (if agendap (marker-buffer m) (current-buffer))
11571 pos (if agendap m (point)))
11572 (with-current-buffer buf
11573 (save-excursion
11574 (save-restriction
11575 (goto-char pos)
11576 (setq cnt (1+ cnt))
11577 (org-toggle-tag tag (if off 'off 'on))
11578 (setq newhead (org-get-heading)))))
11579 (and agendap (org-agenda-change-all-lines newhead m))))
11580 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11582 (defun org-tags-completion-function (string predicate &optional flag)
11583 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11584 (confirm (lambda (x) (stringp (car x)))))
11585 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11586 (setq s1 (match-string 1 string)
11587 s2 (match-string 2 string))
11588 (setq s1 "" s2 string))
11589 (cond
11590 ((eq flag nil)
11591 ;; try completion
11592 (setq rtn (try-completion s2 ctable confirm))
11593 (if (stringp rtn)
11594 (setq rtn
11595 (concat s1 s2 (substring rtn (length s2))
11596 (if (and org-add-colon-after-tag-completion
11597 (assoc rtn ctable))
11598 ":" ""))))
11599 rtn)
11600 ((eq flag t)
11601 ;; all-completions
11602 (all-completions s2 ctable confirm)
11604 ((eq flag 'lambda)
11605 ;; exact match?
11606 (assoc s2 ctable)))
11609 (defun org-fast-tag-insert (kwd tags face &optional end)
11610 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11611 (insert (format "%-12s" (concat kwd ":"))
11612 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11613 (or end "")))
11615 (defun org-fast-tag-show-exit (flag)
11616 (save-excursion
11617 (org-goto-line 3)
11618 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11619 (replace-match ""))
11620 (when flag
11621 (end-of-line 1)
11622 (org-move-to-column (- (window-width) 19) t)
11623 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11625 (defun org-set-current-tags-overlay (current prefix)
11626 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11627 (if (featurep 'xemacs)
11628 (org-overlay-display org-tags-overlay (concat prefix s)
11629 'secondary-selection)
11630 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11631 (org-overlay-display org-tags-overlay (concat prefix s)))))
11633 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11634 "Fast tag selection with single keys.
11635 CURRENT is the current list of tags in the headline, INHERITED is the
11636 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11637 possibly with grouping information. TODO-TABLE is a similar table with
11638 TODO keywords, should these have keys assigned to them.
11639 If the keys are nil, a-z are automatically assigned.
11640 Returns the new tags string, or nil to not change the current settings."
11641 (let* ((fulltable (append table todo-table))
11642 (maxlen (apply 'max (mapcar
11643 (lambda (x)
11644 (if (stringp (car x)) (string-width (car x)) 0))
11645 fulltable)))
11646 (buf (current-buffer))
11647 (expert (eq org-fast-tag-selection-single-key 'expert))
11648 (buffer-tags nil)
11649 (fwidth (+ maxlen 3 1 3))
11650 (ncol (/ (- (window-width) 4) fwidth))
11651 (i-face 'org-done)
11652 (c-face 'org-todo)
11653 tg cnt e c char c1 c2 ntable tbl rtn
11654 ov-start ov-end ov-prefix
11655 (exit-after-next org-fast-tag-selection-single-key)
11656 (done-keywords org-done-keywords)
11657 groups ingroup)
11658 (save-excursion
11659 (beginning-of-line 1)
11660 (if (looking-at
11661 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11662 (setq ov-start (match-beginning 1)
11663 ov-end (match-end 1)
11664 ov-prefix "")
11665 (setq ov-start (1- (point-at-eol))
11666 ov-end (1+ ov-start))
11667 (skip-chars-forward "^\n\r")
11668 (setq ov-prefix
11669 (concat
11670 (buffer-substring (1- (point)) (point))
11671 (if (> (current-column) org-tags-column)
11673 (make-string (- org-tags-column (current-column)) ?\ ))))))
11674 (org-move-overlay org-tags-overlay ov-start ov-end)
11675 (save-window-excursion
11676 (if expert
11677 (set-buffer (get-buffer-create " *Org tags*"))
11678 (delete-other-windows)
11679 (split-window-vertically)
11680 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11681 (erase-buffer)
11682 (org-set-local 'org-done-keywords done-keywords)
11683 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11684 (org-fast-tag-insert "Current" current c-face "\n\n")
11685 (org-fast-tag-show-exit exit-after-next)
11686 (org-set-current-tags-overlay current ov-prefix)
11687 (setq tbl fulltable char ?a cnt 0)
11688 (while (setq e (pop tbl))
11689 (cond
11690 ((equal (car e) :startgroup)
11691 (push '() groups) (setq ingroup t)
11692 (when (not (= cnt 0))
11693 (setq cnt 0)
11694 (insert "\n"))
11695 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
11696 ((equal (car e) :endgroup)
11697 (setq ingroup nil cnt 0)
11698 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
11699 ((equal e '(:newline))
11700 (when (not (= cnt 0))
11701 (setq cnt 0)
11702 (insert "\n")
11703 (setq e (car tbl))
11704 (while (equal (car tbl) '(:newline))
11705 (insert "\n")
11706 (setq tbl (cdr tbl)))))
11708 (setq tg (copy-sequence (car e)) c2 nil)
11709 (if (cdr e)
11710 (setq c (cdr e))
11711 ;; automatically assign a character.
11712 (setq c1 (string-to-char
11713 (downcase (substring
11714 tg (if (= (string-to-char tg) ?@) 1 0)))))
11715 (if (or (rassoc c1 ntable) (rassoc c1 table))
11716 (while (or (rassoc char ntable) (rassoc char table))
11717 (setq char (1+ char)))
11718 (setq c2 c1))
11719 (setq c (or c2 char)))
11720 (if ingroup (push tg (car groups)))
11721 (setq tg (org-add-props tg nil 'face
11722 (cond
11723 ((not (assoc tg table))
11724 (org-get-todo-face tg))
11725 ((member tg current) c-face)
11726 ((member tg inherited) i-face)
11727 (t nil))))
11728 (if (and (= cnt 0) (not ingroup)) (insert " "))
11729 (insert "[" c "] " tg (make-string
11730 (- fwidth 4 (length tg)) ?\ ))
11731 (push (cons tg c) ntable)
11732 (when (= (setq cnt (1+ cnt)) ncol)
11733 (insert "\n")
11734 (if ingroup (insert " "))
11735 (setq cnt 0)))))
11736 (setq ntable (nreverse ntable))
11737 (insert "\n")
11738 (goto-char (point-min))
11739 (if (not expert) (org-fit-window-to-buffer))
11740 (setq rtn
11741 (catch 'exit
11742 (while t
11743 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
11744 (if (not groups) "no " "")
11745 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11746 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11747 (cond
11748 ((= c ?\r) (throw 'exit t))
11749 ((= c ?!)
11750 (setq groups (not groups))
11751 (goto-char (point-min))
11752 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11753 ((= c ?\C-c)
11754 (if (not expert)
11755 (org-fast-tag-show-exit
11756 (setq exit-after-next (not exit-after-next)))
11757 (setq expert nil)
11758 (delete-other-windows)
11759 (split-window-vertically)
11760 (org-switch-to-buffer-other-window " *Org tags*")
11761 (org-fit-window-to-buffer)))
11762 ((or (= c ?\C-g)
11763 (and (= c ?q) (not (rassoc c ntable))))
11764 (org-detach-overlay org-tags-overlay)
11765 (setq quit-flag t))
11766 ((= c ?\ )
11767 (setq current nil)
11768 (if exit-after-next (setq exit-after-next 'now)))
11769 ((= c ?\t)
11770 (condition-case nil
11771 (setq tg (org-icompleting-read
11772 "Tag: "
11773 (or buffer-tags
11774 (with-current-buffer buf
11775 (org-get-buffer-tags)))))
11776 (quit (setq tg "")))
11777 (when (string-match "\\S-" tg)
11778 (add-to-list 'buffer-tags (list tg))
11779 (if (member tg current)
11780 (setq current (delete tg current))
11781 (push tg current)))
11782 (if exit-after-next (setq exit-after-next 'now)))
11783 ((setq e (rassoc c todo-table) tg (car e))
11784 (with-current-buffer buf
11785 (save-excursion (org-todo tg)))
11786 (if exit-after-next (setq exit-after-next 'now)))
11787 ((setq e (rassoc c ntable) tg (car e))
11788 (if (member tg current)
11789 (setq current (delete tg current))
11790 (loop for g in groups do
11791 (if (member tg g)
11792 (mapc (lambda (x)
11793 (setq current (delete x current)))
11794 g)))
11795 (push tg current))
11796 (if exit-after-next (setq exit-after-next 'now))))
11798 ;; Create a sorted list
11799 (setq current
11800 (sort current
11801 (lambda (a b)
11802 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11803 (if (eq exit-after-next 'now) (throw 'exit t))
11804 (goto-char (point-min))
11805 (beginning-of-line 2)
11806 (delete-region (point) (point-at-eol))
11807 (org-fast-tag-insert "Current" current c-face)
11808 (org-set-current-tags-overlay current ov-prefix)
11809 (while (re-search-forward
11810 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11811 (setq tg (match-string 1))
11812 (add-text-properties
11813 (match-beginning 1) (match-end 1)
11814 (list 'face
11815 (cond
11816 ((member tg current) c-face)
11817 ((member tg inherited) i-face)
11818 (t (get-text-property (match-beginning 1) 'face))))))
11819 (goto-char (point-min)))))
11820 (org-detach-overlay org-tags-overlay)
11821 (if rtn
11822 (mapconcat 'identity current ":")
11823 nil))))
11825 (defun org-get-tags-string ()
11826 "Get the TAGS string in the current headline."
11827 (unless (org-on-heading-p t)
11828 (error "Not on a heading"))
11829 (save-excursion
11830 (beginning-of-line 1)
11831 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11832 (org-match-string-no-properties 1)
11833 "")))
11835 (defun org-get-tags ()
11836 "Get the list of tags specified in the current headline."
11837 (org-split-string (org-get-tags-string) ":"))
11839 (defun org-get-buffer-tags ()
11840 "Get a table of all tags used in the buffer, for completion."
11841 (let (tags)
11842 (save-excursion
11843 (goto-char (point-min))
11844 (while (re-search-forward
11845 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11846 (when (equal (char-after (point-at-bol 0)) ?*)
11847 (mapc (lambda (x) (add-to-list 'tags x))
11848 (org-split-string (org-match-string-no-properties 1) ":")))))
11849 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
11850 (mapcar 'list tags)))
11852 ;;;; The mapping API
11854 ;;;###autoload
11855 (defun org-map-entries (func &optional match scope &rest skip)
11856 "Call FUNC at each headline selected by MATCH in SCOPE.
11858 FUNC is a function or a lisp form. The function will be called without
11859 arguments, with the cursor positioned at the beginning of the headline.
11860 The return values of all calls to the function will be collected and
11861 returned as a list.
11863 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11864 does not need to preserve point. After evaluation, the cursor will be
11865 moved to the end of the line (presumably of the headline of the
11866 processed entry) and search continues from there. Under some
11867 circumstances, this may not produce the wanted results. For example,
11868 if you have removed (e.g. archived) the current (sub)tree it could
11869 mean that the next entry will be skipped entirely. In such cases, you
11870 can specify the position from where search should continue by making
11871 FUNC set the variable `org-map-continue-from' to the desired buffer
11872 position.
11874 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11875 Only headlines that are matched by this query will be considered during
11876 the iteration. When MATCH is nil or t, all headlines will be
11877 visited by the iteration.
11879 SCOPE determines the scope of this command. It can be any of:
11881 nil The current buffer, respecting the restriction if any
11882 tree The subtree started with the entry at point
11883 file The current buffer, without restriction
11884 file-with-archives
11885 The current buffer, and any archives associated with it
11886 agenda All agenda files
11887 agenda-with-archives
11888 All agenda files with any archive files associated with them
11889 \(file1 file2 ...)
11890 If this is a list, all files in the list will be scanned
11892 The remaining args are treated as settings for the skipping facilities of
11893 the scanner. The following items can be given here:
11895 archive skip trees with the archive tag.
11896 comment skip trees with the COMMENT keyword
11897 function or Emacs Lisp form:
11898 will be used as value for `org-agenda-skip-function', so whenever
11899 the function returns t, FUNC will not be called for that
11900 entry and search will continue from the point where the
11901 function leaves it.
11903 If your function needs to retrieve the tags including inherited tags
11904 at the *current* entry, you can use the value of the variable
11905 `org-scanner-tags' which will be much faster than getting the value
11906 with `org-get-tags-at'. If your function gets properties with
11907 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11908 to t around the call to `org-entry-properties' to get the same speedup.
11909 Note that if your function moves around to retrieve tags and properties at
11910 a *different* entry, you cannot use these techniques."
11911 (let* ((org-agenda-archives-mode nil) ; just to make sure
11912 (org-agenda-skip-archived-trees (memq 'archive skip))
11913 (org-agenda-skip-comment-trees (memq 'comment skip))
11914 (org-agenda-skip-function
11915 (car (org-delete-all '(comment archive) skip)))
11916 (org-tags-match-list-sublevels t)
11917 matcher file res
11918 org-todo-keywords-for-agenda
11919 org-done-keywords-for-agenda
11920 org-todo-keyword-alist-for-agenda
11921 org-drawers-for-agenda
11922 org-tag-alist-for-agenda)
11924 (cond
11925 ((eq match t) (setq matcher t))
11926 ((eq match nil) (setq matcher t))
11927 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11929 (save-excursion
11930 (save-restriction
11931 (when (eq scope 'tree)
11932 (org-back-to-heading t)
11933 (org-narrow-to-subtree)
11934 (setq scope nil))
11936 (if (not scope)
11937 (progn
11938 (org-prepare-agenda-buffers
11939 (list (buffer-file-name (current-buffer))))
11940 (setq res (org-scan-tags func matcher)))
11941 ;; Get the right scope
11942 (cond
11943 ((and scope (listp scope) (symbolp (car scope)))
11944 (setq scope (eval scope)))
11945 ((eq scope 'agenda)
11946 (setq scope (org-agenda-files t)))
11947 ((eq scope 'agenda-with-archives)
11948 (setq scope (org-agenda-files t))
11949 (setq scope (org-add-archive-files scope)))
11950 ((eq scope 'file)
11951 (setq scope (list (buffer-file-name))))
11952 ((eq scope 'file-with-archives)
11953 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11954 (org-prepare-agenda-buffers scope)
11955 (while (setq file (pop scope))
11956 (with-current-buffer (org-find-base-buffer-visiting file)
11957 (save-excursion
11958 (save-restriction
11959 (widen)
11960 (goto-char (point-min))
11961 (setq res (append res (org-scan-tags func matcher))))))))))
11962 res))
11964 ;;;; Properties
11966 ;;; Setting and retrieving properties
11968 (defconst org-special-properties
11969 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11970 "TIMESTAMP" "TIMESTAMP_IA")
11971 "The special properties valid in Org-mode.
11973 These are properties that are not defined in the property drawer,
11974 but in some other way.")
11976 (defconst org-default-properties
11977 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11978 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11979 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11980 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11981 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
11982 "CLOCK_MODELINE_TOTAL" "STYLE")
11983 "Some properties that are used by Org-mode for various purposes.
11984 Being in this list makes sure that they are offered for completion.")
11986 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11987 "Regular expression matching the first line of a property drawer.")
11989 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11990 "Regular expression matching the first line of a property drawer.")
11992 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11993 "Regular expression matching the first line of a property drawer.")
11995 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11996 "Regular expression matching the first line of a property drawer.")
11998 (defconst org-property-drawer-re
11999 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12000 org-property-end-re "\\)\n?")
12001 "Matches an entire property drawer.")
12003 (defconst org-clock-drawer-re
12004 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12005 org-property-end-re "\\)\n?")
12006 "Matches an entire clock drawer.")
12008 (defun org-property-action ()
12009 "Do an action on properties."
12010 (interactive)
12011 (let (c)
12012 (org-at-property-p)
12013 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12014 (setq c (read-char-exclusive))
12015 (cond
12016 ((equal c ?s)
12017 (call-interactively 'org-set-property))
12018 ((equal c ?d)
12019 (call-interactively 'org-delete-property))
12020 ((equal c ?D)
12021 (call-interactively 'org-delete-property-globally))
12022 ((equal c ?c)
12023 (call-interactively 'org-compute-property-at-point))
12024 (t (error "No such property action %c" c)))))
12026 (defun org-set-effort (&optional value)
12027 "Set the effort property of the current entry.
12028 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12029 allowed value."
12030 (interactive "P")
12031 (if (equal value 0) (setq value 10))
12032 (let* ((completion-ignore-case t)
12033 (prop org-effort-property)
12034 (cur (org-entry-get nil prop))
12035 (allowed (org-property-get-allowed-values nil prop 'table))
12036 (existing (mapcar 'list (org-property-values prop)))
12038 (val (cond
12039 ((stringp value) value)
12040 ((and allowed (integerp value))
12041 (or (car (nth (1- value) allowed))
12042 (car (org-last allowed))))
12043 (allowed
12044 (message "Select 1-9,0, [RET%s]: %s"
12045 (if cur (concat "=" cur) "")
12046 (mapconcat 'car allowed " "))
12047 (setq rpl (read-char-exclusive))
12048 (if (equal rpl ?\r)
12050 (setq rpl (- rpl ?0))
12051 (if (equal rpl 0) (setq rpl 10))
12052 (if (and (> rpl 0) (<= rpl (length allowed)))
12053 (car (nth (1- rpl) allowed))
12054 (org-completing-read "Value: " allowed nil))))
12056 (let (org-completion-use-ido org-completion-use-iswitchb)
12057 (org-completing-read
12058 (concat "Value " (if (and cur (string-match "\\S-" cur))
12059 (concat "[" cur "]") "")
12060 ": ")
12061 existing nil nil "" nil cur))))))
12062 (unless (equal (org-entry-get nil prop) val)
12063 (org-entry-put nil prop val))
12064 (message "%s is now %s" prop val)))
12066 (defun org-at-property-p ()
12067 "Is the cursor in a property line?"
12068 ;; FIXME: Does not check if we are actually in the drawer.
12069 ;; FIXME: also returns true on any drawers.....
12070 ;; This is used by C-c C-c for property action.
12071 (save-excursion
12072 (beginning-of-line 1)
12073 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
12075 (defun org-get-property-block (&optional beg end force)
12076 "Return the (beg . end) range of the body of the property drawer.
12077 BEG and END can be beginning and end of subtree, if not given
12078 they will be found.
12079 If the drawer does not exist and FORCE is non-nil, create the drawer."
12080 (catch 'exit
12081 (save-excursion
12082 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12083 (end (or end (progn (outline-next-heading) (point)))))
12084 (goto-char beg)
12085 (if (re-search-forward org-property-start-re end t)
12086 (setq beg (1+ (match-end 0)))
12087 (if force
12088 (save-excursion
12089 (org-insert-property-drawer)
12090 (setq end (progn (outline-next-heading) (point))))
12091 (throw 'exit nil))
12092 (goto-char beg)
12093 (if (re-search-forward org-property-start-re end t)
12094 (setq beg (1+ (match-end 0)))))
12095 (if (re-search-forward org-property-end-re end t)
12096 (setq end (match-beginning 0))
12097 (or force (throw 'exit nil))
12098 (goto-char beg)
12099 (setq end beg)
12100 (org-indent-line-function)
12101 (insert ":END:\n"))
12102 (cons beg end)))))
12104 (defun org-entry-properties (&optional pom which)
12105 "Get all properties of the entry at point-or-marker POM.
12106 This includes the TODO keyword, the tags, time strings for deadline,
12107 scheduled, and clocking, and any additional properties defined in the
12108 entry. The return value is an alist, keys may occur multiple times
12109 if the property key was used several times.
12110 POM may also be nil, in which case the current entry is used.
12111 If WHICH is nil or `all', get all properties. If WHICH is
12112 `special' or `standard', only get that subclass."
12113 (setq which (or which 'all))
12114 (org-with-point-at pom
12115 (let ((clockstr (substring org-clock-string 0 -1))
12116 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
12117 beg end range props sum-props key value string clocksum)
12118 (save-excursion
12119 (when (condition-case nil
12120 (and (org-mode-p) (org-back-to-heading t))
12121 (error nil))
12122 (setq beg (point))
12123 (setq sum-props (get-text-property (point) 'org-summaries))
12124 (setq clocksum (get-text-property (point) :org-clock-minutes))
12125 (outline-next-heading)
12126 (setq end (point))
12127 (when (memq which '(all special))
12128 ;; Get the special properties, like TODO and tags
12129 (goto-char beg)
12130 (when (and (looking-at org-todo-line-regexp) (match-end 2))
12131 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12132 (when (looking-at org-priority-regexp)
12133 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12134 (when (and (setq value (org-get-tags-string))
12135 (string-match "\\S-" value))
12136 (push (cons "TAGS" value) props))
12137 (when (setq value (org-get-tags-at))
12138 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
12139 props))
12140 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12141 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12142 string (if (equal key clockstr)
12143 (org-no-properties
12144 (org-trim
12145 (buffer-substring
12146 (match-beginning 3) (goto-char (point-at-eol)))))
12147 (substring (org-match-string-no-properties 3) 1 -1)))
12148 (unless key
12149 (if (= (char-after (match-beginning 3)) ?\[)
12150 (setq key "TIMESTAMP_IA")
12151 (setq key "TIMESTAMP")))
12152 (when (or (equal key clockstr) (not (assoc key props)))
12153 (push (cons key string) props)))
12157 (when (memq which '(all standard))
12158 ;; Get the standard properties, like :PROP: ...
12159 (setq range (org-get-property-block beg end))
12160 (when range
12161 (goto-char (car range))
12162 (while (re-search-forward
12163 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12164 (cdr range) t)
12165 (setq key (org-match-string-no-properties 1)
12166 value (org-trim (or (org-match-string-no-properties 2) "")))
12167 (unless (member key excluded)
12168 (push (cons key (or value "")) props)))))
12169 (if clocksum
12170 (push (cons "CLOCKSUM"
12171 (org-columns-number-to-string (/ (float clocksum) 60.)
12172 'add_times))
12173 props))
12174 (unless (assoc "CATEGORY" props)
12175 (setq value (or (org-get-category)
12176 (progn (org-refresh-category-properties)
12177 (org-get-category))))
12178 (push (cons "CATEGORY" value) props))
12179 (append sum-props (nreverse props)))))))
12181 (defun org-entry-get (pom property &optional inherit)
12182 "Get value of PROPERTY for entry at point-or-marker POM.
12183 If INHERIT is non-nil and the entry does not have the property,
12184 then also check higher levels of the hierarchy.
12185 If INHERIT is the symbol `selective', use inheritance only if the setting
12186 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12187 If the property is present but empty, the return value is the empty string.
12188 If the property is not present at all, nil is returned."
12189 (org-with-point-at pom
12190 (if (and inherit (if (eq inherit 'selective)
12191 (org-property-inherit-p property)
12193 (org-entry-get-with-inheritance property)
12194 (if (member property org-special-properties)
12195 ;; We need a special property. Use brute force, get all properties.
12196 (cdr (assoc property (org-entry-properties nil 'special)))
12197 (let ((range (org-get-property-block)))
12198 (if (and range
12199 (goto-char (car range))
12200 (re-search-forward
12201 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12202 (cdr range) t))
12203 ;; Found the property, return it.
12204 (if (match-end 1)
12205 (org-match-string-no-properties 1)
12206 "")))))))
12208 (defun org-property-or-variable-value (var &optional inherit)
12209 "Check if there is a property fixing the value of VAR.
12210 If yes, return this value. If not, return the current value of the variable."
12211 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12212 (if (and prop (stringp prop) (string-match "\\S-" prop))
12213 (read prop)
12214 (symbol-value var))))
12216 (defun org-entry-delete (pom property)
12217 "Delete the property PROPERTY from entry at point-or-marker POM."
12218 (org-with-point-at pom
12219 (if (member property org-special-properties)
12220 nil ; cannot delete these properties.
12221 (let ((range (org-get-property-block)))
12222 (if (and range
12223 (goto-char (car range))
12224 (re-search-forward
12225 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12226 (cdr range) t))
12227 (progn
12228 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12230 nil)))))
12232 ;; Multi-values properties are properties that contain multiple values
12233 ;; These values are assumed to be single words, separated by whitespace.
12234 (defun org-entry-add-to-multivalued-property (pom property value)
12235 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12236 (let* ((old (org-entry-get pom property))
12237 (values (and old (org-split-string old "[ \t]"))))
12238 (setq value (org-entry-protect-space value))
12239 (unless (member value values)
12240 (setq values (cons value values))
12241 (org-entry-put pom property
12242 (mapconcat 'identity values " ")))))
12244 (defun org-entry-remove-from-multivalued-property (pom property value)
12245 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12246 (let* ((old (org-entry-get pom property))
12247 (values (and old (org-split-string old "[ \t]"))))
12248 (setq value (org-entry-protect-space value))
12249 (when (member value values)
12250 (setq values (delete value values))
12251 (org-entry-put pom property
12252 (mapconcat 'identity values " ")))))
12254 (defun org-entry-member-in-multivalued-property (pom property value)
12255 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12256 (let* ((old (org-entry-get pom property))
12257 (values (and old (org-split-string old "[ \t]"))))
12258 (setq value (org-entry-protect-space value))
12259 (member value values)))
12261 (defun org-entry-get-multivalued-property (pom property)
12262 "Return a list of values in a multivalued property."
12263 (let* ((value (org-entry-get pom property))
12264 (values (and value (org-split-string value "[ \t]"))))
12265 (mapcar 'org-entry-restore-space values)))
12267 (defun org-entry-put-multivalued-property (pom property &rest values)
12268 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12269 VALUES should be a list of strings. Spaces will be protected."
12270 (org-entry-put pom property
12271 (mapconcat 'org-entry-protect-space values " "))
12272 (let* ((value (org-entry-get pom property))
12273 (values (and value (org-split-string value "[ \t]"))))
12274 (mapcar 'org-entry-restore-space values)))
12276 (defun org-entry-protect-space (s)
12277 "Protect spaces and newline in string S."
12278 (while (string-match " " s)
12279 (setq s (replace-match "%20" t t s)))
12280 (while (string-match "\n" s)
12281 (setq s (replace-match "%0A" t t s)))
12284 (defun org-entry-restore-space (s)
12285 "Restore spaces and newline in string S."
12286 (while (string-match "%20" s)
12287 (setq s (replace-match " " t t s)))
12288 (while (string-match "%0A" s)
12289 (setq s (replace-match "\n" t t s)))
12292 (defvar org-entry-property-inherited-from (make-marker)
12293 "Marker pointing to the entry from where a property was inherited.
12294 Each call to `org-entry-get-with-inheritance' will set this marker to the
12295 location of the entry where the inheritance search matched. If there was
12296 no match, the marker will point nowhere.
12297 Note that also `org-entry-get' calls this function, if the INHERIT flag
12298 is set.")
12300 (defun org-entry-get-with-inheritance (property)
12301 "Get entry property, and search higher levels if not present."
12302 (move-marker org-entry-property-inherited-from nil)
12303 (let (tmp)
12304 (save-excursion
12305 (save-restriction
12306 (widen)
12307 (catch 'ex
12308 (while t
12309 (when (setq tmp (org-entry-get nil property))
12310 (org-back-to-heading t)
12311 (move-marker org-entry-property-inherited-from (point))
12312 (throw 'ex tmp))
12313 (or (org-up-heading-safe) (throw 'ex nil)))))
12314 (or tmp
12315 (cdr (assoc property org-file-properties))
12316 (cdr (assoc property org-global-properties))
12317 (cdr (assoc property org-global-properties-fixed))))))
12319 (defun org-entry-put (pom property value)
12320 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12321 (org-with-point-at pom
12322 (org-back-to-heading t)
12323 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12324 range)
12325 (cond
12326 ((equal property "TODO")
12327 (when (and (stringp value) (string-match "\\S-" value)
12328 (not (member value org-todo-keywords-1)))
12329 (error "\"%s\" is not a valid TODO state" value))
12330 (if (or (not value)
12331 (not (string-match "\\S-" value)))
12332 (setq value 'none))
12333 (org-todo value)
12334 (org-set-tags nil 'align))
12335 ((equal property "PRIORITY")
12336 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12337 (string-to-char value) ?\ ))
12338 (org-set-tags nil 'align))
12339 ((equal property "SCHEDULED")
12340 (if (re-search-forward org-scheduled-time-regexp end t)
12341 (cond
12342 ((eq value 'earlier) (org-timestamp-change -1 'day))
12343 ((eq value 'later) (org-timestamp-change 1 'day))
12344 (t (call-interactively 'org-schedule)))
12345 (call-interactively 'org-schedule)))
12346 ((equal property "DEADLINE")
12347 (if (re-search-forward org-deadline-time-regexp end t)
12348 (cond
12349 ((eq value 'earlier) (org-timestamp-change -1 'day))
12350 ((eq value 'later) (org-timestamp-change 1 'day))
12351 (t (call-interactively 'org-deadline)))
12352 (call-interactively 'org-deadline)))
12353 ((member property org-special-properties)
12354 (error "The %s property can not yet be set with `org-entry-put'"
12355 property))
12356 (t ; a non-special property
12357 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12358 (setq range (org-get-property-block beg end 'force))
12359 (goto-char (car range))
12360 (if (re-search-forward
12361 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12362 (progn
12363 (delete-region (match-beginning 1) (match-end 1))
12364 (goto-char (match-beginning 1)))
12365 (goto-char (cdr range))
12366 (insert "\n")
12367 (backward-char 1)
12368 (org-indent-line-function)
12369 (insert ":" property ":"))
12370 (and value (insert " " value))
12371 (org-indent-line-function)))))))
12373 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12374 "Get all property keys in the current buffer.
12375 With INCLUDE-SPECIALS, also list the special properties that reflect things
12376 like tags and TODO state.
12377 With INCLUDE-DEFAULTS, also include properties that has special meaning
12378 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12379 With INCLUDE-COLUMNS, also include property names given in COLUMN
12380 formats in the current buffer."
12381 (let (rtn range cfmt s p)
12382 (save-excursion
12383 (save-restriction
12384 (widen)
12385 (goto-char (point-min))
12386 (while (re-search-forward org-property-start-re nil t)
12387 (setq range (org-get-property-block))
12388 (goto-char (car range))
12389 (while (re-search-forward
12390 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12391 (cdr range) t)
12392 (add-to-list 'rtn (org-match-string-no-properties 1)))
12393 (outline-next-heading))))
12395 (when include-specials
12396 (setq rtn (append org-special-properties rtn)))
12398 (when include-defaults
12399 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12400 (add-to-list 'rtn org-effort-property))
12402 (when include-columns
12403 (save-excursion
12404 (save-restriction
12405 (widen)
12406 (goto-char (point-min))
12407 (while (re-search-forward
12408 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12409 nil t)
12410 (setq cfmt (match-string 2) s 0)
12411 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12412 cfmt s)
12413 (setq s (match-end 0)
12414 p (match-string 1 cfmt))
12415 (unless (or (equal p "ITEM")
12416 (member p org-special-properties))
12417 (add-to-list 'rtn (match-string 1 cfmt))))))))
12419 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12421 (defun org-property-values (key)
12422 "Return a list of all values of property KEY."
12423 (save-excursion
12424 (save-restriction
12425 (widen)
12426 (goto-char (point-min))
12427 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12428 values)
12429 (while (re-search-forward re nil t)
12430 (add-to-list 'values (org-trim (match-string 1))))
12431 (delete "" values)))))
12433 (defun org-insert-property-drawer ()
12434 "Insert a property drawer into the current entry."
12435 (interactive)
12436 (org-back-to-heading t)
12437 (looking-at outline-regexp)
12438 (let ((indent (if org-adapt-indentation
12439 (- (match-end 0)(match-beginning 0))
12441 (beg (point))
12442 (re (concat "^[ \t]*" org-keyword-time-regexp))
12443 end hiddenp)
12444 (outline-next-heading)
12445 (setq end (point))
12446 (goto-char beg)
12447 (while (re-search-forward re end t))
12448 (setq hiddenp (org-invisible-p))
12449 (end-of-line 1)
12450 (and (equal (char-after) ?\n) (forward-char 1))
12451 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12452 (if (member (match-string 1) '("CLOCK:" ":END:"))
12453 ;; just skip this line
12454 (beginning-of-line 2)
12455 ;; Drawer start, find the end
12456 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12457 (beginning-of-line 1)))
12458 (org-skip-over-state-notes)
12459 (skip-chars-backward " \t\n\r")
12460 (if (eq (char-before) ?*) (forward-char 1))
12461 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12462 (beginning-of-line 0)
12463 (org-indent-to-column indent)
12464 (beginning-of-line 2)
12465 (org-indent-to-column indent)
12466 (beginning-of-line 0)
12467 (if hiddenp
12468 (save-excursion
12469 (org-back-to-heading t)
12470 (hide-entry))
12471 (org-flag-drawer t))))
12473 (defun org-set-property (property value)
12474 "In the current entry, set PROPERTY to VALUE.
12475 When called interactively, this will prompt for a property name, offering
12476 completion on existing and default properties. And then it will prompt
12477 for a value, offering completion either on allowed values (via an inherited
12478 xxx_ALL property) or on existing values in other instances of this property
12479 in the current file."
12480 (interactive
12481 (let* ((completion-ignore-case t)
12482 (keys (org-buffer-property-keys nil t t))
12483 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12484 (prop (if (member prop0 keys)
12485 prop0
12486 (or (cdr (assoc (downcase prop0)
12487 (mapcar (lambda (x) (cons (downcase x) x))
12488 keys)))
12489 prop0)))
12490 (cur (org-entry-get nil prop))
12491 (allowed (org-property-get-allowed-values nil prop 'table))
12492 (existing (mapcar 'list (org-property-values prop)))
12493 (val (if allowed
12494 (org-completing-read "Value: " allowed nil 'req-match)
12495 (let (org-completion-use-ido org-completion-use-iswitchb)
12496 (org-completing-read
12497 (concat "Value " (if (and cur (string-match "\\S-" cur))
12498 (concat "[" cur "]") "")
12499 ": ")
12500 existing nil nil "" nil cur)))))
12501 (list prop (if (equal val "") cur val))))
12502 (unless (equal (org-entry-get nil property) value)
12503 (org-entry-put nil property value)))
12505 (defun org-delete-property (property)
12506 "In the current entry, delete PROPERTY."
12507 (interactive
12508 (let* ((completion-ignore-case t)
12509 (prop (org-icompleting-read
12510 "Property: " (org-entry-properties nil 'standard))))
12511 (list prop)))
12512 (message "Property %s %s" property
12513 (if (org-entry-delete nil property)
12514 "deleted"
12515 "was not present in the entry")))
12517 (defun org-delete-property-globally (property)
12518 "Remove PROPERTY globally, from all entries."
12519 (interactive
12520 (let* ((completion-ignore-case t)
12521 (prop (org-icompleting-read
12522 "Globally remove property: "
12523 (mapcar 'list (org-buffer-property-keys)))))
12524 (list prop)))
12525 (save-excursion
12526 (save-restriction
12527 (widen)
12528 (goto-char (point-min))
12529 (let ((cnt 0))
12530 (while (re-search-forward
12531 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12532 nil t)
12533 (setq cnt (1+ cnt))
12534 (replace-match ""))
12535 (message "Property \"%s\" removed from %d entries" property cnt)))))
12537 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12539 (defun org-compute-property-at-point ()
12540 "Compute the property at point.
12541 This looks for an enclosing column format, extracts the operator and
12542 then applies it to the property in the column format's scope."
12543 (interactive)
12544 (unless (org-at-property-p)
12545 (error "Not at a property"))
12546 (let ((prop (org-match-string-no-properties 2)))
12547 (org-columns-get-format-and-top-level)
12548 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12549 (error "No operator defined for property %s" prop))
12550 (org-columns-compute prop)))
12552 (defun org-property-get-allowed-values (pom property &optional table)
12553 "Get allowed values for the property PROPERTY.
12554 When TABLE is non-nil, return an alist that can directly be used for
12555 completion."
12556 (let (vals)
12557 (cond
12558 ((equal property "TODO")
12559 (setq vals (org-with-point-at pom
12560 (append org-todo-keywords-1 '("")))))
12561 ((equal property "PRIORITY")
12562 (let ((n org-lowest-priority))
12563 (while (>= n org-highest-priority)
12564 (push (char-to-string n) vals)
12565 (setq n (1- n)))))
12566 ((member property org-special-properties))
12568 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12570 (when (and vals (string-match "\\S-" vals))
12571 (setq vals (car (read-from-string (concat "(" vals ")"))))
12572 (setq vals (mapcar (lambda (x)
12573 (cond ((stringp x) x)
12574 ((numberp x) (number-to-string x))
12575 ((symbolp x) (symbol-name x))
12576 (t "???")))
12577 vals)))))
12578 (if table (mapcar 'list vals) vals)))
12580 (defun org-property-previous-allowed-value (&optional previous)
12581 "Switch to the next allowed value for this property."
12582 (interactive)
12583 (org-property-next-allowed-value t))
12585 (defun org-property-next-allowed-value (&optional previous)
12586 "Switch to the next allowed value for this property."
12587 (interactive)
12588 (unless (org-at-property-p)
12589 (error "Not at a property"))
12590 (let* ((key (match-string 2))
12591 (value (match-string 3))
12592 (allowed (or (org-property-get-allowed-values (point) key)
12593 (and (member value '("[ ]" "[-]" "[X]"))
12594 '("[ ]" "[X]"))))
12595 nval)
12596 (unless allowed
12597 (error "Allowed values for this property have not been defined"))
12598 (if previous (setq allowed (reverse allowed)))
12599 (if (member value allowed)
12600 (setq nval (car (cdr (member value allowed)))))
12601 (setq nval (or nval (car allowed)))
12602 (if (equal nval value)
12603 (error "Only one allowed value for this property"))
12604 (org-at-property-p)
12605 (replace-match (concat " :" key ": " nval) t t)
12606 (org-indent-line-function)
12607 (beginning-of-line 1)
12608 (skip-chars-forward " \t")))
12610 (defun org-find-entry-with-id (ident)
12611 "Locate the entry that contains the ID property with exact value IDENT.
12612 IDENT can be a string, a symbol or a number, this function will search for
12613 the string representation of it.
12614 Return the position where this entry starts, or nil if there is no such entry."
12615 (interactive "sID: ")
12616 (let ((id (cond
12617 ((stringp ident) ident)
12618 ((symbol-name ident) (symbol-name ident))
12619 ((numberp ident) (number-to-string ident))
12620 (t (error "IDENT %s must be a string, symbol or number" ident))))
12621 (case-fold-search nil))
12622 (save-excursion
12623 (save-restriction
12624 (widen)
12625 (goto-char (point-min))
12626 (when (re-search-forward
12627 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12628 nil t)
12629 (org-back-to-heading t)
12630 (point))))))
12632 ;;;; Timestamps
12634 (defvar org-last-changed-timestamp nil)
12635 (defvar org-last-inserted-timestamp nil
12636 "The last time stamp inserted with `org-insert-time-stamp'.")
12637 (defvar org-time-was-given) ; dynamically scoped parameter
12638 (defvar org-end-time-was-given) ; dynamically scoped parameter
12639 (defvar org-ts-what) ; dynamically scoped parameter
12641 (defun org-time-stamp (arg &optional inactive)
12642 "Prompt for a date/time and insert a time stamp.
12643 If the user specifies a time like HH:MM, or if this command is called
12644 with a prefix argument, the time stamp will contain date and time.
12645 Otherwise, only the date will be included. All parts of a date not
12646 specified by the user will be filled in from the current date/time.
12647 So if you press just return without typing anything, the time stamp
12648 will represent the current date/time. If there is already a timestamp
12649 at the cursor, it will be modified."
12650 (interactive "P")
12651 (let* ((ts nil)
12652 (default-time
12653 ;; Default time is either today, or, when entering a range,
12654 ;; the range start.
12655 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12656 (save-excursion
12657 (re-search-backward
12658 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12659 (- (point) 20) t)))
12660 (apply 'encode-time (org-parse-time-string (match-string 1)))
12661 (current-time)))
12662 (default-input (and ts (org-get-compact-tod ts)))
12663 org-time-was-given org-end-time-was-given time)
12664 (cond
12665 ((and (org-at-timestamp-p t)
12666 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12667 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12668 (insert "--")
12669 (setq time (let ((this-command this-command))
12670 (org-read-date arg 'totime nil nil
12671 default-time default-input)))
12672 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12673 ((org-at-timestamp-p t)
12674 (setq time (let ((this-command this-command))
12675 (org-read-date arg 'totime nil nil default-time default-input)))
12676 (when (org-at-timestamp-p t) ; just to get the match data
12677 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12678 (replace-match "")
12679 (setq org-last-changed-timestamp
12680 (org-insert-time-stamp
12681 time (or org-time-was-given arg)
12682 inactive nil nil (list org-end-time-was-given))))
12683 (message "Timestamp updated"))
12685 (setq time (let ((this-command this-command))
12686 (org-read-date arg 'totime nil nil default-time default-input)))
12687 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12688 nil nil (list org-end-time-was-given))))))
12690 ;; FIXME: can we use this for something else, like computing time differences?
12691 (defun org-get-compact-tod (s)
12692 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12693 (let* ((t1 (match-string 1 s))
12694 (h1 (string-to-number (match-string 2 s)))
12695 (m1 (string-to-number (match-string 3 s)))
12696 (t2 (and (match-end 4) (match-string 5 s)))
12697 (h2 (and t2 (string-to-number (match-string 6 s))))
12698 (m2 (and t2 (string-to-number (match-string 7 s))))
12699 dh dm)
12700 (if (not t2)
12702 (setq dh (- h2 h1) dm (- m2 m1))
12703 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12704 (concat t1 "+" (number-to-string dh)
12705 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12707 (defun org-time-stamp-inactive (&optional arg)
12708 "Insert an inactive time stamp.
12709 An inactive time stamp is enclosed in square brackets instead of angle
12710 brackets. It is inactive in the sense that it does not trigger agenda entries,
12711 does not link to the calendar and cannot be changed with the S-cursor keys.
12712 So these are more for recording a certain time/date."
12713 (interactive "P")
12714 (org-time-stamp arg 'inactive))
12716 (defvar org-date-ovl (org-make-overlay 1 1))
12717 (org-overlay-put org-date-ovl 'face 'org-warning)
12718 (org-detach-overlay org-date-ovl)
12720 (defvar org-ans1) ; dynamically scoped parameter
12721 (defvar org-ans2) ; dynamically scoped parameter
12723 (defvar org-plain-time-of-day-regexp) ; defined below
12725 (defvar org-overriding-default-time nil) ; dynamically scoped
12726 (defvar org-read-date-overlay nil)
12727 (defvar org-dcst nil) ; dynamically scoped
12728 (defvar org-read-date-history nil)
12729 (defvar org-read-date-final-answer nil)
12731 (defun org-read-date (&optional with-time to-time from-string prompt
12732 default-time default-input)
12733 "Read a date, possibly a time, and make things smooth for the user.
12734 The prompt will suggest to enter an ISO date, but you can also enter anything
12735 which will at least partially be understood by `parse-time-string'.
12736 Unrecognized parts of the date will default to the current day, month, year,
12737 hour and minute. If this command is called to replace a timestamp at point,
12738 of to enter the second timestamp of a range, the default time is taken from the
12739 existing stamp. For example,
12740 3-2-5 --> 2003-02-05
12741 feb 15 --> currentyear-02-15
12742 sep 12 9 --> 2009-09-12
12743 12:45 --> today 12:45
12744 22 sept 0:34 --> currentyear-09-22 0:34
12745 12 --> currentyear-currentmonth-12
12746 Fri --> nearest Friday (today or later)
12747 etc.
12749 Furthermore you can specify a relative date by giving, as the *first* thing
12750 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12751 change in days weeks, months, years.
12752 With a single plus or minus, the date is relative to today. With a double
12753 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12754 +4d --> four days from today
12755 +4 --> same as above
12756 +2w --> two weeks from today
12757 ++5 --> five days from default date
12759 The function understands only English month and weekday abbreviations,
12760 but this can be configured with the variables `parse-time-months' and
12761 `parse-time-weekdays'.
12763 While prompting, a calendar is popped up - you can also select the
12764 date with the mouse (button 1). The calendar shows a period of three
12765 months. To scroll it to other months, use the keys `>' and `<'.
12766 If you don't like the calendar, turn it off with
12767 \(setq org-read-date-popup-calendar nil)
12769 With optional argument TO-TIME, the date will immediately be converted
12770 to an internal time.
12771 With an optional argument WITH-TIME, the prompt will suggest to also
12772 insert a time. Note that when WITH-TIME is not set, you can still
12773 enter a time, and this function will inform the calling routine about
12774 this change. The calling routine may then choose to change the format
12775 used to insert the time stamp into the buffer to include the time.
12776 With optional argument FROM-STRING, read from this string instead from
12777 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12778 the time/date that is used for everything that is not specified by the
12779 user."
12780 (require 'parse-time)
12781 (let* ((org-time-stamp-rounding-minutes
12782 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12783 (org-dcst org-display-custom-times)
12784 (ct (org-current-time))
12785 (def (or org-overriding-default-time default-time ct))
12786 (defdecode (decode-time def))
12787 (dummy (progn
12788 (when (< (nth 2 defdecode) org-extend-today-until)
12789 (setcar (nthcdr 2 defdecode) -1)
12790 (setcar (nthcdr 1 defdecode) 59)
12791 (setq def (apply 'encode-time defdecode)
12792 defdecode (decode-time def)))))
12793 (calendar-frame-setup nil)
12794 (calendar-move-hook nil)
12795 (calendar-view-diary-initially-flag nil)
12796 (view-diary-entries-initially nil)
12797 (calendar-view-holidays-initially-flag nil)
12798 (view-calendar-holidays-initially nil)
12799 (timestr (format-time-string
12800 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12801 (prompt (concat (if prompt (concat prompt " ") "")
12802 (format "Date+time [%s]: " timestr)))
12803 ans (org-ans0 "") org-ans1 org-ans2 final)
12805 (cond
12806 (from-string (setq ans from-string))
12807 (org-read-date-popup-calendar
12808 (save-excursion
12809 (save-window-excursion
12810 (calendar)
12811 (calendar-forward-day (- (time-to-days def)
12812 (calendar-absolute-from-gregorian
12813 (calendar-current-date))))
12814 (org-eval-in-calendar nil t)
12815 (let* ((old-map (current-local-map))
12816 (map (copy-keymap calendar-mode-map))
12817 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12818 (org-defkey map (kbd "RET") 'org-calendar-select)
12819 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12820 'org-calendar-select-mouse)
12821 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12822 'org-calendar-select-mouse)
12823 (org-defkey minibuffer-local-map [(meta shift left)]
12824 (lambda () (interactive)
12825 (org-eval-in-calendar '(calendar-backward-month 1))))
12826 (org-defkey minibuffer-local-map [(meta shift right)]
12827 (lambda () (interactive)
12828 (org-eval-in-calendar '(calendar-forward-month 1))))
12829 (org-defkey minibuffer-local-map [(meta shift up)]
12830 (lambda () (interactive)
12831 (org-eval-in-calendar '(calendar-backward-year 1))))
12832 (org-defkey minibuffer-local-map [(meta shift down)]
12833 (lambda () (interactive)
12834 (org-eval-in-calendar '(calendar-forward-year 1))))
12835 (org-defkey minibuffer-local-map [?\e (shift left)]
12836 (lambda () (interactive)
12837 (org-eval-in-calendar '(calendar-backward-month 1))))
12838 (org-defkey minibuffer-local-map [?\e (shift right)]
12839 (lambda () (interactive)
12840 (org-eval-in-calendar '(calendar-forward-month 1))))
12841 (org-defkey minibuffer-local-map [?\e (shift up)]
12842 (lambda () (interactive)
12843 (org-eval-in-calendar '(calendar-backward-year 1))))
12844 (org-defkey minibuffer-local-map [?\e (shift down)]
12845 (lambda () (interactive)
12846 (org-eval-in-calendar '(calendar-forward-year 1))))
12847 (org-defkey minibuffer-local-map [(shift up)]
12848 (lambda () (interactive)
12849 (org-eval-in-calendar '(calendar-backward-week 1))))
12850 (org-defkey minibuffer-local-map [(shift down)]
12851 (lambda () (interactive)
12852 (org-eval-in-calendar '(calendar-forward-week 1))))
12853 (org-defkey minibuffer-local-map [(shift left)]
12854 (lambda () (interactive)
12855 (org-eval-in-calendar '(calendar-backward-day 1))))
12856 (org-defkey minibuffer-local-map [(shift right)]
12857 (lambda () (interactive)
12858 (org-eval-in-calendar '(calendar-forward-day 1))))
12859 (org-defkey minibuffer-local-map ">"
12860 (lambda () (interactive)
12861 (org-eval-in-calendar '(scroll-calendar-left 1))))
12862 (org-defkey minibuffer-local-map "<"
12863 (lambda () (interactive)
12864 (org-eval-in-calendar '(scroll-calendar-right 1))))
12865 (run-hooks 'org-read-date-minibuffer-setup-hook)
12866 (unwind-protect
12867 (progn
12868 (use-local-map map)
12869 (add-hook 'post-command-hook 'org-read-date-display)
12870 (setq org-ans0 (read-string prompt default-input
12871 'org-read-date-history nil))
12872 ;; org-ans0: from prompt
12873 ;; org-ans1: from mouse click
12874 ;; org-ans2: from calendar motion
12875 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12876 (remove-hook 'post-command-hook 'org-read-date-display)
12877 (use-local-map old-map)
12878 (when org-read-date-overlay
12879 (org-delete-overlay org-read-date-overlay)
12880 (setq org-read-date-overlay nil)))))))
12882 (t ; Naked prompt only
12883 (unwind-protect
12884 (setq ans (read-string prompt default-input
12885 'org-read-date-history timestr))
12886 (when org-read-date-overlay
12887 (org-delete-overlay org-read-date-overlay)
12888 (setq org-read-date-overlay nil)))))
12890 (setq final (org-read-date-analyze ans def defdecode))
12891 (setq org-read-date-final-answer ans)
12893 (if to-time
12894 (apply 'encode-time final)
12895 (if (and (boundp 'org-time-was-given) org-time-was-given)
12896 (format "%04d-%02d-%02d %02d:%02d"
12897 (nth 5 final) (nth 4 final) (nth 3 final)
12898 (nth 2 final) (nth 1 final))
12899 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12901 (defvar def)
12902 (defvar defdecode)
12903 (defvar with-time)
12904 (defvar org-read-date-analyze-futurep nil)
12905 (defun org-read-date-display ()
12906 "Display the current date prompt interpretation in the minibuffer."
12907 (when org-read-date-display-live
12908 (when org-read-date-overlay
12909 (org-delete-overlay org-read-date-overlay))
12910 (let ((p (point)))
12911 (end-of-line 1)
12912 (while (not (equal (buffer-substring
12913 (max (point-min) (- (point) 4)) (point))
12914 " "))
12915 (insert " "))
12916 (goto-char p))
12917 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12918 " " (or org-ans1 org-ans2)))
12919 (org-end-time-was-given nil)
12920 (f (org-read-date-analyze ans def defdecode))
12921 (fmts (if org-dcst
12922 org-time-stamp-custom-formats
12923 org-time-stamp-formats))
12924 (fmt (if (or with-time
12925 (and (boundp 'org-time-was-given) org-time-was-given))
12926 (cdr fmts)
12927 (car fmts)))
12928 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12929 (when (and org-end-time-was-given
12930 (string-match org-plain-time-of-day-regexp txt))
12931 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12932 org-end-time-was-given
12933 (substring txt (match-end 0)))))
12934 (when org-read-date-analyze-futurep
12935 (setq txt (concat txt " (=>F)")))
12936 (setq org-read-date-overlay
12937 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12938 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12940 (defun org-read-date-analyze (ans def defdecode)
12941 "Analyse the combined answer of the date prompt."
12942 ;; FIXME: cleanup and comment
12943 (let (delta deltan deltaw deltadef year month day
12944 hour minute second wday pm h2 m2 tl wday1
12945 iso-year iso-weekday iso-week iso-year iso-date futurep)
12946 (setq org-read-date-analyze-futurep nil)
12947 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12948 (setq ans "+0"))
12950 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12951 (setq ans (replace-match "" t t ans)
12952 deltan (car delta)
12953 deltaw (nth 1 delta)
12954 deltadef (nth 2 delta)))
12956 ;; Check if there is an iso week date in there
12957 ;; If yes, sore the info and postpone interpreting it until the rest
12958 ;; of the parsing is done
12959 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12960 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12961 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12962 iso-week (string-to-number (match-string 2 ans)))
12963 (setq ans (replace-match "" t t ans)))
12965 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12966 (when (string-match
12967 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12968 (setq year (if (match-end 2)
12969 (string-to-number (match-string 2 ans))
12970 (string-to-number (format-time-string "%Y")))
12971 month (string-to-number (match-string 3 ans))
12972 day (string-to-number (match-string 4 ans)))
12973 (if (< year 100) (setq year (+ 2000 year)))
12974 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12975 t nil ans)))
12976 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12977 ;; If there is a time with am/pm, and *no* time without it, we convert
12978 ;; so that matching will be successful.
12979 (loop for i from 1 to 2 do ; twice, for end time as well
12980 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12981 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12982 (setq hour (string-to-number (match-string 1 ans))
12983 minute (if (match-end 3)
12984 (string-to-number (match-string 3 ans))
12986 pm (equal ?p
12987 (string-to-char (downcase (match-string 4 ans)))))
12988 (if (and (= hour 12) (not pm))
12989 (setq hour 0)
12990 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12991 (setq ans (replace-match (format "%02d:%02d" hour minute)
12992 t t ans))))
12994 ;; Check if a time range is given as a duration
12995 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12996 (setq hour (string-to-number (match-string 1 ans))
12997 h2 (+ hour (string-to-number (match-string 3 ans)))
12998 minute (string-to-number (match-string 2 ans))
12999 m2 (+ minute (if (match-end 5) (string-to-number
13000 (match-string 5 ans))0)))
13001 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13002 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13003 t t ans)))
13005 ;; Check if there is a time range
13006 (when (boundp 'org-end-time-was-given)
13007 (setq org-time-was-given nil)
13008 (when (and (string-match org-plain-time-of-day-regexp ans)
13009 (match-end 8))
13010 (setq org-end-time-was-given (match-string 8 ans))
13011 (setq ans (concat (substring ans 0 (match-beginning 7))
13012 (substring ans (match-end 7))))))
13014 (setq tl (parse-time-string ans)
13015 day (or (nth 3 tl) (nth 3 defdecode))
13016 month (or (nth 4 tl)
13017 (if (and org-read-date-prefer-future
13018 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
13019 (prog1 (1+ (nth 4 defdecode)) (setq futurep t))
13020 (nth 4 defdecode)))
13021 year (or (nth 5 tl)
13022 (if (and org-read-date-prefer-future
13023 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
13024 (prog1 (1+ (nth 5 defdecode)) (setq futurep t))
13025 (nth 5 defdecode)))
13026 hour (or (nth 2 tl) (nth 2 defdecode))
13027 minute (or (nth 1 tl) (nth 1 defdecode))
13028 second (or (nth 0 tl) 0)
13029 wday (nth 6 tl))
13031 (when (and (eq org-read-date-prefer-future 'time)
13032 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13033 (equal day (nth 3 defdecode))
13034 (equal month (nth 4 defdecode))
13035 (equal year (nth 5 defdecode))
13036 (nth 2 tl)
13037 (or (< (nth 2 tl) (nth 2 defdecode))
13038 (and (= (nth 2 tl) (nth 2 defdecode))
13039 (nth 1 tl)
13040 (< (nth 1 tl) (nth 1 defdecode)))))
13041 (setq day (1+ day)
13042 futurep t))
13044 ;; Special date definitions below
13045 (cond
13046 (iso-week
13047 ;; There was an iso week
13048 (setq futurep nil)
13049 (setq year (or iso-year year)
13050 day (or iso-weekday wday 1)
13051 wday nil ; to make sure that the trigger below does not match
13052 iso-date (calendar-gregorian-from-absolute
13053 (calendar-absolute-from-iso
13054 (list iso-week day year))))
13055 ; FIXME: Should we also push ISO weeks into the future?
13056 ; (when (and org-read-date-prefer-future
13057 ; (not iso-year)
13058 ; (< (calendar-absolute-from-gregorian iso-date)
13059 ; (time-to-days (current-time))))
13060 ; (setq year (1+ year)
13061 ; iso-date (calendar-gregorian-from-absolute
13062 ; (calendar-absolute-from-iso
13063 ; (list iso-week day year)))))
13064 (setq month (car iso-date)
13065 year (nth 2 iso-date)
13066 day (nth 1 iso-date)))
13067 (deltan
13068 (setq futurep nil)
13069 (unless deltadef
13070 (let ((now (decode-time (current-time))))
13071 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13072 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13073 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13074 ((equal deltaw "m") (setq month (+ month deltan)))
13075 ((equal deltaw "y") (setq year (+ year deltan)))))
13076 ((and wday (not (nth 3 tl)))
13077 (setq futurep nil)
13078 ;; Weekday was given, but no day, so pick that day in the week
13079 ;; on or after the derived date.
13080 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13081 (unless (equal wday wday1)
13082 (setq day (+ day (% (- wday wday1 -7) 7))))))
13083 (if (and (boundp 'org-time-was-given)
13084 (nth 2 tl))
13085 (setq org-time-was-given t))
13086 (if (< year 100) (setq year (+ 2000 year)))
13087 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13088 (setq org-read-date-analyze-futurep futurep)
13089 (list second minute hour day month year)))
13091 (defvar parse-time-weekdays)
13093 (defun org-read-date-get-relative (s today default)
13094 "Check string S for special relative date string.
13095 TODAY and DEFAULT are internal times, for today and for a default.
13096 Return shift list (N what def-flag)
13097 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13098 N is the number of WHATs to shift.
13099 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13100 the DEFAULT date rather than TODAY."
13101 (when (and
13102 (string-match
13103 (concat
13104 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13105 "\\([0-9]+\\)?"
13106 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13107 "\\([ \t]\\|$\\)") s)
13108 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13109 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13110 (string-to-char (substring (match-string 1 s) -1))
13111 ?+))
13112 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13113 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13114 (what (if (match-end 3) (match-string 3 s) "d"))
13115 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13116 (date (if rel default today))
13117 (wday (nth 6 (decode-time date)))
13118 delta)
13119 (if wday1
13120 (progn
13121 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13122 (if (= dir ?-) (setq delta (- delta 7)))
13123 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13124 (list delta "d" rel))
13125 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13127 (defun org-eval-in-calendar (form &optional keepdate)
13128 "Eval FORM in the calendar window and return to current window.
13129 Also, store the cursor date in variable org-ans2."
13130 (let ((sf (selected-frame))
13131 (sw (selected-window)))
13132 (select-window (get-buffer-window "*Calendar*" t))
13133 (eval form)
13134 (when (and (not keepdate) (calendar-cursor-to-date))
13135 (let* ((date (calendar-cursor-to-date))
13136 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13137 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13138 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13139 (select-window sw)
13140 (org-select-frame-set-input-focus sf)))
13142 (defun org-calendar-select ()
13143 "Return to `org-read-date' with the date currently selected.
13144 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13145 (interactive)
13146 (when (calendar-cursor-to-date)
13147 (let* ((date (calendar-cursor-to-date))
13148 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13149 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13150 (if (active-minibuffer-window) (exit-minibuffer))))
13152 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13153 "Insert a date stamp for the date given by the internal TIME.
13154 WITH-HM means, use the stamp format that includes the time of the day.
13155 INACTIVE means use square brackets instead of angular ones, so that the
13156 stamp will not contribute to the agenda.
13157 PRE and POST are optional strings to be inserted before and after the
13158 stamp.
13159 The command returns the inserted time stamp."
13160 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13161 stamp)
13162 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13163 (insert-before-markers (or pre ""))
13164 (insert-before-markers (setq stamp (format-time-string fmt time)))
13165 (when (listp extra)
13166 (setq extra (car extra))
13167 (if (and (stringp extra)
13168 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13169 (setq extra (format "-%02d:%02d"
13170 (string-to-number (match-string 1 extra))
13171 (string-to-number (match-string 2 extra))))
13172 (setq extra nil)))
13173 (when extra
13174 (backward-char 1)
13175 (insert-before-markers extra)
13176 (forward-char 1))
13177 (insert-before-markers (or post ""))
13178 (setq org-last-inserted-timestamp stamp)))
13180 (defun org-toggle-time-stamp-overlays ()
13181 "Toggle the use of custom time stamp formats."
13182 (interactive)
13183 (setq org-display-custom-times (not org-display-custom-times))
13184 (unless org-display-custom-times
13185 (let ((p (point-min)) (bmp (buffer-modified-p)))
13186 (while (setq p (next-single-property-change p 'display))
13187 (if (and (get-text-property p 'display)
13188 (eq (get-text-property p 'face) 'org-date))
13189 (remove-text-properties
13190 p (setq p (next-single-property-change p 'display))
13191 '(display t))))
13192 (set-buffer-modified-p bmp)))
13193 (if (featurep 'xemacs)
13194 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13195 (org-restart-font-lock)
13196 (setq org-table-may-need-update t)
13197 (if org-display-custom-times
13198 (message "Time stamps are overlayed with custom format")
13199 (message "Time stamp overlays removed")))
13201 (defun org-display-custom-time (beg end)
13202 "Overlay modified time stamp format over timestamp between BEG and END."
13203 (let* ((ts (buffer-substring beg end))
13204 t1 w1 with-hm tf time str w2 (off 0))
13205 (save-match-data
13206 (setq t1 (org-parse-time-string ts t))
13207 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13208 (setq off (- (match-end 0) (match-beginning 0)))))
13209 (setq end (- end off))
13210 (setq w1 (- end beg)
13211 with-hm (and (nth 1 t1) (nth 2 t1))
13212 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13213 time (org-fix-decoded-time t1)
13214 str (org-add-props
13215 (format-time-string
13216 (substring tf 1 -1) (apply 'encode-time time))
13217 nil 'mouse-face 'highlight)
13218 w2 (length str))
13219 (if (not (= w2 w1))
13220 (add-text-properties (1+ beg) (+ 2 beg)
13221 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13222 (if (featurep 'xemacs)
13223 (progn
13224 (put-text-property beg end 'invisible t)
13225 (put-text-property beg end 'end-glyph (make-glyph str)))
13226 (put-text-property beg end 'display str))))
13228 (defun org-translate-time (string)
13229 "Translate all timestamps in STRING to custom format.
13230 But do this only if the variable `org-display-custom-times' is set."
13231 (when org-display-custom-times
13232 (save-match-data
13233 (let* ((start 0)
13234 (re org-ts-regexp-both)
13235 t1 with-hm inactive tf time str beg end)
13236 (while (setq start (string-match re string start))
13237 (setq beg (match-beginning 0)
13238 end (match-end 0)
13239 t1 (save-match-data
13240 (org-parse-time-string (substring string beg end) t))
13241 with-hm (and (nth 1 t1) (nth 2 t1))
13242 inactive (equal (substring string beg (1+ beg)) "[")
13243 tf (funcall (if with-hm 'cdr 'car)
13244 org-time-stamp-custom-formats)
13245 time (org-fix-decoded-time t1)
13246 str (format-time-string
13247 (concat
13248 (if inactive "[" "<") (substring tf 1 -1)
13249 (if inactive "]" ">"))
13250 (apply 'encode-time time))
13251 string (replace-match str t t string)
13252 start (+ start (length str)))))))
13253 string)
13255 (defun org-fix-decoded-time (time)
13256 "Set 0 instead of nil for the first 6 elements of time.
13257 Don't touch the rest."
13258 (let ((n 0))
13259 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13261 (defun org-days-to-time (timestamp-string)
13262 "Difference between TIMESTAMP-STRING and now in days."
13263 (- (time-to-days (org-time-string-to-time timestamp-string))
13264 (time-to-days (current-time))))
13266 (defun org-deadline-close (timestamp-string &optional ndays)
13267 "Is the time in TIMESTAMP-STRING close to the current date?"
13268 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13269 (and (< (org-days-to-time timestamp-string) ndays)
13270 (not (org-entry-is-done-p))))
13272 (defun org-get-wdays (ts)
13273 "Get the deadline lead time appropriate for timestring TS."
13274 (cond
13275 ((<= org-deadline-warning-days 0)
13276 ;; 0 or negative, enforce this value no matter what
13277 (- org-deadline-warning-days))
13278 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13279 ;; lead time is specified.
13280 (floor (* (string-to-number (match-string 1 ts))
13281 (cdr (assoc (match-string 2 ts)
13282 '(("d" . 1) ("w" . 7)
13283 ("m" . 30.4) ("y" . 365.25)))))))
13284 ;; go for the default.
13285 (t org-deadline-warning-days)))
13287 (defun org-calendar-select-mouse (ev)
13288 "Return to `org-read-date' with the date currently selected.
13289 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13290 (interactive "e")
13291 (mouse-set-point ev)
13292 (when (calendar-cursor-to-date)
13293 (let* ((date (calendar-cursor-to-date))
13294 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13295 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13296 (if (active-minibuffer-window) (exit-minibuffer))))
13298 (defun org-check-deadlines (ndays)
13299 "Check if there are any deadlines due or past due.
13300 A deadline is considered due if it happens within `org-deadline-warning-days'
13301 days from today's date. If the deadline appears in an entry marked DONE,
13302 it is not shown. The prefix arg NDAYS can be used to test that many
13303 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13304 (interactive "P")
13305 (let* ((org-warn-days
13306 (cond
13307 ((equal ndays '(4)) 100000)
13308 (ndays (prefix-numeric-value ndays))
13309 (t (abs org-deadline-warning-days))))
13310 (case-fold-search nil)
13311 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13312 (callback
13313 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13315 (message "%d deadlines past-due or due within %d days"
13316 (org-occur regexp nil callback)
13317 org-warn-days)))
13319 (defun org-check-before-date (date)
13320 "Check if there are deadlines or scheduled entries before DATE."
13321 (interactive (list (org-read-date)))
13322 (let ((case-fold-search nil)
13323 (regexp (concat "\\<\\(" org-deadline-string
13324 "\\|" org-scheduled-string
13325 "\\) *<\\([^>]+\\)>"))
13326 (callback
13327 (lambda () (time-less-p
13328 (org-time-string-to-time (match-string 2))
13329 (org-time-string-to-time date)))))
13330 (message "%d entries before %s"
13331 (org-occur regexp nil callback) date)))
13333 (defun org-check-after-date (date)
13334 "Check if there are deadlines or scheduled entries after DATE."
13335 (interactive (list (org-read-date)))
13336 (let ((case-fold-search nil)
13337 (regexp (concat "\\<\\(" org-deadline-string
13338 "\\|" org-scheduled-string
13339 "\\) *<\\([^>]+\\)>"))
13340 (callback
13341 (lambda () (not
13342 (time-less-p
13343 (org-time-string-to-time (match-string 2))
13344 (org-time-string-to-time date))))))
13345 (message "%d entries after %s"
13346 (org-occur regexp nil callback) date)))
13348 (defun org-evaluate-time-range (&optional to-buffer)
13349 "Evaluate a time range by computing the difference between start and end.
13350 Normally the result is just printed in the echo area, but with prefix arg
13351 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13352 If the time range is actually in a table, the result is inserted into the
13353 next column.
13354 For time difference computation, a year is assumed to be exactly 365
13355 days in order to avoid rounding problems."
13356 (interactive "P")
13358 (org-clock-update-time-maybe)
13359 (save-excursion
13360 (unless (org-at-date-range-p t)
13361 (goto-char (point-at-bol))
13362 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13363 (if (not (org-at-date-range-p t))
13364 (error "Not at a time-stamp range, and none found in current line")))
13365 (let* ((ts1 (match-string 1))
13366 (ts2 (match-string 2))
13367 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13368 (match-end (match-end 0))
13369 (time1 (org-time-string-to-time ts1))
13370 (time2 (org-time-string-to-time ts2))
13371 (t1 (org-float-time time1))
13372 (t2 (org-float-time time2))
13373 (diff (abs (- t2 t1)))
13374 (negative (< (- t2 t1) 0))
13375 ;; (ys (floor (* 365 24 60 60)))
13376 (ds (* 24 60 60))
13377 (hs (* 60 60))
13378 (fy "%dy %dd %02d:%02d")
13379 (fy1 "%dy %dd")
13380 (fd "%dd %02d:%02d")
13381 (fd1 "%dd")
13382 (fh "%02d:%02d")
13383 y d h m align)
13384 (if havetime
13385 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13387 d (floor (/ diff ds)) diff (mod diff ds)
13388 h (floor (/ diff hs)) diff (mod diff hs)
13389 m (floor (/ diff 60)))
13390 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13392 d (floor (+ (/ diff ds) 0.5))
13393 h 0 m 0))
13394 (if (not to-buffer)
13395 (message "%s" (org-make-tdiff-string y d h m))
13396 (if (org-at-table-p)
13397 (progn
13398 (goto-char match-end)
13399 (setq align t)
13400 (and (looking-at " *|") (goto-char (match-end 0))))
13401 (goto-char match-end))
13402 (if (looking-at
13403 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13404 (replace-match ""))
13405 (if negative (insert " -"))
13406 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13407 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13408 (insert " " (format fh h m))))
13409 (if align (org-table-align))
13410 (message "Time difference inserted")))))
13412 (defun org-make-tdiff-string (y d h m)
13413 (let ((fmt "")
13414 (l nil))
13415 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13416 l (push y l)))
13417 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13418 l (push d l)))
13419 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13420 l (push h l)))
13421 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13422 l (push m l)))
13423 (apply 'format fmt (nreverse l))))
13425 (defun org-time-string-to-time (s)
13426 (apply 'encode-time (org-parse-time-string s)))
13427 (defun org-time-string-to-seconds (s)
13428 (org-float-time (org-time-string-to-time s)))
13430 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13431 "Convert a time stamp to an absolute day number.
13432 If there is a specifyer for a cyclic time stamp, get the closest date to
13433 DAYNR.
13434 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13435 the variable date is bound by the calendar when this is called."
13436 (cond
13437 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13438 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13439 daynr
13440 (+ daynr 1000)))
13441 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13442 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13443 (time-to-days (current-time))) (match-string 0 s)
13444 prefer show-all))
13445 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13447 (defun org-days-to-iso-week (days)
13448 "Return the iso week number."
13449 (require 'cal-iso)
13450 (car (calendar-iso-from-absolute days)))
13452 (defun org-small-year-to-year (year)
13453 "Convert 2-digit years into 4-digit years.
13454 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13455 The year 2000 cannot be abbreviated. Any year larger than 99
13456 is returned unchanged."
13457 (if (< year 38)
13458 (setq year (+ 2000 year))
13459 (if (< year 100)
13460 (setq year (+ 1900 year))))
13461 year)
13463 (defun org-time-from-absolute (d)
13464 "Return the time corresponding to date D.
13465 D may be an absolute day number, or a calendar-type list (month day year)."
13466 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13467 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13469 (defun org-calendar-holiday ()
13470 "List of holidays, for Diary display in Org-mode."
13471 (require 'holidays)
13472 (let ((hl (funcall
13473 (if (fboundp 'calendar-check-holidays)
13474 'calendar-check-holidays 'check-calendar-holidays) date)))
13475 (if hl (mapconcat 'identity hl "; "))))
13477 (defun org-diary-sexp-entry (sexp entry date)
13478 "Process a SEXP diary ENTRY for DATE."
13479 (require 'diary-lib)
13480 (let ((result (if calendar-debug-sexp
13481 (let ((stack-trace-on-error t))
13482 (eval (car (read-from-string sexp))))
13483 (condition-case nil
13484 (eval (car (read-from-string sexp)))
13485 (error
13486 (beep)
13487 (message "Bad sexp at line %d in %s: %s"
13488 (org-current-line)
13489 (buffer-file-name) sexp)
13490 (sleep-for 2))))))
13491 (cond ((stringp result) result)
13492 ((and (consp result)
13493 (stringp (cdr result))) (cdr result))
13494 (result entry)
13495 (t nil))))
13497 (defun org-diary-to-ical-string (frombuf)
13498 "Get iCalendar entries from diary entries in buffer FROMBUF.
13499 This uses the icalendar.el library."
13500 (let* ((tmpdir (if (featurep 'xemacs)
13501 (temp-directory)
13502 temporary-file-directory))
13503 (tmpfile (make-temp-name
13504 (expand-file-name "orgics" tmpdir)))
13505 buf rtn b e)
13506 (with-current-buffer frombuf
13507 (icalendar-export-region (point-min) (point-max) tmpfile)
13508 (setq buf (find-buffer-visiting tmpfile))
13509 (set-buffer buf)
13510 (goto-char (point-min))
13511 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13512 (setq b (match-beginning 0)))
13513 (goto-char (point-max))
13514 (if (re-search-backward "^END:VEVENT" nil t)
13515 (setq e (match-end 0)))
13516 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13517 (kill-buffer buf)
13518 (delete-file tmpfile)
13519 rtn))
13521 (defun org-closest-date (start current change prefer show-all)
13522 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13523 When PREFER is `past' return a date that is either CURRENT or past.
13524 When PREFER is `future', return a date that is either CURRENT or future.
13525 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13526 ;; Make the proper lists from the dates
13527 (catch 'exit
13528 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13529 dn dw sday cday n1 n2 n0
13530 d m y y1 y2 date1 date2 nmonths nm ny m2)
13532 (setq start (org-date-to-gregorian start)
13533 current (org-date-to-gregorian
13534 (if show-all
13535 current
13536 (time-to-days (current-time))))
13537 sday (calendar-absolute-from-gregorian start)
13538 cday (calendar-absolute-from-gregorian current))
13540 (if (<= cday sday) (throw 'exit sday))
13542 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13543 (setq dn (string-to-number (match-string 1 change))
13544 dw (cdr (assoc (match-string 2 change) a1)))
13545 (error "Invalid change specifyer: %s" change))
13546 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13547 (cond
13548 ((eq dw 'day)
13549 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13550 n2 (+ n1 dn)))
13551 ((eq dw 'year)
13552 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13553 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13554 (setq date1 (list m d y1)
13555 n1 (calendar-absolute-from-gregorian date1)
13556 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13557 n2 (calendar-absolute-from-gregorian date2)))
13558 ((eq dw 'month)
13559 ;; approx number of month between the two dates
13560 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13561 ;; How often does dn fit in there?
13562 (setq d (nth 1 start) m (car start) y (nth 2 start)
13563 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13564 m (+ m nm)
13565 ny (floor (/ m 12))
13566 y (+ y ny)
13567 m (- m (* ny 12)))
13568 (while (> m 12) (setq m (- m 12) y (1+ y)))
13569 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13570 (setq m2 (+ m dn) y2 y)
13571 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13572 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13573 (while (<= n2 cday)
13574 (setq n1 n2 m m2 y y2)
13575 (setq m2 (+ m dn) y2 y)
13576 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13577 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13578 ;; Make sure n1 is the earlier date
13579 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13580 (if show-all
13581 (cond
13582 ((eq prefer 'past) (if (= cday n2) n2 n1))
13583 ((eq prefer 'future) (if (= cday n1) n1 n2))
13584 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13585 (cond
13586 ((eq prefer 'past) (if (= cday n2) n2 n1))
13587 ((eq prefer 'future) (if (= cday n1) n1 n2))
13588 (t (if (= cday n1) n1 n2)))))))
13590 (defun org-date-to-gregorian (date)
13591 "Turn any specification of DATE into a gregorian date for the calendar."
13592 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13593 ((and (listp date) (= (length date) 3)) date)
13594 ((stringp date)
13595 (setq date (org-parse-time-string date))
13596 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13597 ((listp date)
13598 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13600 (defun org-parse-time-string (s &optional nodefault)
13601 "Parse the standard Org-mode time string.
13602 This should be a lot faster than the normal `parse-time-string'.
13603 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13604 hour and minute fields will be nil if not given."
13605 (if (string-match org-ts-regexp0 s)
13606 (list 0
13607 (if (or (match-beginning 8) (not nodefault))
13608 (string-to-number (or (match-string 8 s) "0")))
13609 (if (or (match-beginning 7) (not nodefault))
13610 (string-to-number (or (match-string 7 s) "0")))
13611 (string-to-number (match-string 4 s))
13612 (string-to-number (match-string 3 s))
13613 (string-to-number (match-string 2 s))
13614 nil nil nil)
13615 (error "Not a standard Org-mode time string: %s" s)))
13617 (defun org-timestamp-up (&optional arg)
13618 "Increase the date item at the cursor by one.
13619 If the cursor is on the year, change the year. If it is on the month or
13620 the day, change that.
13621 With prefix ARG, change by that many units."
13622 (interactive "p")
13623 (org-timestamp-change (prefix-numeric-value arg)))
13625 (defun org-timestamp-down (&optional arg)
13626 "Decrease the date item at the cursor by one.
13627 If the cursor is on the year, change the year. If it is on the month or
13628 the day, change that.
13629 With prefix ARG, change by that many units."
13630 (interactive "p")
13631 (org-timestamp-change (- (prefix-numeric-value arg))))
13633 (defun org-timestamp-up-day (&optional arg)
13634 "Increase the date in the time stamp by one day.
13635 With prefix ARG, change that many days."
13636 (interactive "p")
13637 (if (and (not (org-at-timestamp-p t))
13638 (org-on-heading-p))
13639 (org-todo 'up)
13640 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13642 (defun org-timestamp-down-day (&optional arg)
13643 "Decrease the date in the time stamp by one day.
13644 With prefix ARG, change that many days."
13645 (interactive "p")
13646 (if (and (not (org-at-timestamp-p t))
13647 (org-on-heading-p))
13648 (org-todo 'down)
13649 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13651 (defun org-at-timestamp-p (&optional inactive-ok)
13652 "Determine if the cursor is in or at a timestamp."
13653 (interactive)
13654 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13655 (pos (point))
13656 (ans (or (looking-at tsr)
13657 (save-excursion
13658 (skip-chars-backward "^[<\n\r\t")
13659 (if (> (point) (point-min)) (backward-char 1))
13660 (and (looking-at tsr)
13661 (> (- (match-end 0) pos) -1))))))
13662 (and ans
13663 (boundp 'org-ts-what)
13664 (setq org-ts-what
13665 (cond
13666 ((= pos (match-beginning 0)) 'bracket)
13667 ((= pos (1- (match-end 0))) 'bracket)
13668 ((org-pos-in-match-range pos 2) 'year)
13669 ((org-pos-in-match-range pos 3) 'month)
13670 ((org-pos-in-match-range pos 7) 'hour)
13671 ((org-pos-in-match-range pos 8) 'minute)
13672 ((or (org-pos-in-match-range pos 4)
13673 (org-pos-in-match-range pos 5)) 'day)
13674 ((and (> pos (or (match-end 8) (match-end 5)))
13675 (< pos (match-end 0)))
13676 (- pos (or (match-end 8) (match-end 5))))
13677 (t 'day))))
13678 ans))
13680 (defun org-toggle-timestamp-type ()
13681 "Toggle the type (<active> or [inactive]) of a time stamp."
13682 (interactive)
13683 (when (org-at-timestamp-p t)
13684 (let ((beg (match-beginning 0)) (end (match-end 0))
13685 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13686 (save-excursion
13687 (goto-char beg)
13688 (while (re-search-forward "[][<>]" end t)
13689 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13690 t t)))
13691 (message "Timestamp is now %sactive"
13692 (if (equal (char-after beg) ?<) "" "in")))))
13694 (defun org-timestamp-change (n &optional what)
13695 "Change the date in the time stamp at point.
13696 The date will be changed by N times WHAT. WHAT can be `day', `month',
13697 `year', `minute', `second'. If WHAT is not given, the cursor position
13698 in the timestamp determines what will be changed."
13699 (let ((pos (point))
13700 with-hm inactive
13701 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13702 org-ts-what
13703 extra rem
13704 ts time time0)
13705 (if (not (org-at-timestamp-p t))
13706 (error "Not at a timestamp"))
13707 (if (and (not what) (eq org-ts-what 'bracket))
13708 (org-toggle-timestamp-type)
13709 (if (and (not what) (not (eq org-ts-what 'day))
13710 org-display-custom-times
13711 (get-text-property (point) 'display)
13712 (not (get-text-property (1- (point)) 'display)))
13713 (setq org-ts-what 'day))
13714 (setq org-ts-what (or what org-ts-what)
13715 inactive (= (char-after (match-beginning 0)) ?\[)
13716 ts (match-string 0))
13717 (replace-match "")
13718 (if (string-match
13719 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
13721 (setq extra (match-string 1 ts)))
13722 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13723 (setq with-hm t))
13724 (setq time0 (org-parse-time-string ts))
13725 (when (and (eq org-ts-what 'minute)
13726 (eq current-prefix-arg nil))
13727 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13728 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13729 (setcar (cdr time0) (+ (nth 1 time0)
13730 (if (> n 0) (- rem) (- dm rem))))))
13731 (setq time
13732 (encode-time (or (car time0) 0)
13733 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13734 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13735 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13736 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13737 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13738 (nthcdr 6 time0)))
13739 (when (and (member org-ts-what '(hour minute))
13740 extra
13741 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13742 (setq extra (org-modify-ts-extra
13743 extra
13744 (if (eq org-ts-what 'hour) 2 5)
13745 n dm)))
13746 (when (integerp org-ts-what)
13747 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13748 (if (eq what 'calendar)
13749 (let ((cal-date (org-get-date-from-calendar)))
13750 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13751 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13752 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13753 (setcar time0 (or (car time0) 0))
13754 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13755 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13756 (setq time (apply 'encode-time time0))))
13757 (setq org-last-changed-timestamp
13758 (org-insert-time-stamp time with-hm inactive nil nil extra))
13759 (org-clock-update-time-maybe)
13760 (goto-char pos)
13761 ;; Try to recenter the calendar window, if any
13762 (if (and org-calendar-follow-timestamp-change
13763 (get-buffer-window "*Calendar*" t)
13764 (memq org-ts-what '(day month year)))
13765 (org-recenter-calendar (time-to-days time))))))
13767 (defun org-modify-ts-extra (s pos n dm)
13768 "Change the different parts of the lead-time and repeat fields in timestamp."
13769 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13770 ng h m new rem)
13771 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13772 (cond
13773 ((or (org-pos-in-match-range pos 2)
13774 (org-pos-in-match-range pos 3))
13775 (setq m (string-to-number (match-string 3 s))
13776 h (string-to-number (match-string 2 s)))
13777 (if (org-pos-in-match-range pos 2)
13778 (setq h (+ h n))
13779 (setq n (* dm (org-no-warnings (signum n))))
13780 (when (not (= 0 (setq rem (% m dm))))
13781 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13782 (setq m (+ m n)))
13783 (if (< m 0) (setq m (+ m 60) h (1- h)))
13784 (if (> m 59) (setq m (- m 60) h (1+ h)))
13785 (setq h (min 24 (max 0 h)))
13786 (setq ng 1 new (format "-%02d:%02d" h m)))
13787 ((org-pos-in-match-range pos 6)
13788 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13789 ((org-pos-in-match-range pos 5)
13790 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13792 ((org-pos-in-match-range pos 9)
13793 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13794 ((org-pos-in-match-range pos 8)
13795 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13797 (when ng
13798 (setq s (concat
13799 (substring s 0 (match-beginning ng))
13801 (substring s (match-end ng))))))
13804 (defun org-recenter-calendar (date)
13805 "If the calendar is visible, recenter it to DATE."
13806 (let* ((win (selected-window))
13807 (cwin (get-buffer-window "*Calendar*" t))
13808 (calendar-move-hook nil))
13809 (when cwin
13810 (select-window cwin)
13811 (calendar-goto-date (if (listp date) date
13812 (calendar-gregorian-from-absolute date)))
13813 (select-window win))))
13815 (defun org-goto-calendar (&optional arg)
13816 "Go to the Emacs calendar at the current date.
13817 If there is a time stamp in the current line, go to that date.
13818 A prefix ARG can be used to force the current date."
13819 (interactive "P")
13820 (let ((tsr org-ts-regexp) diff
13821 (calendar-move-hook nil)
13822 (calendar-view-holidays-initially-flag nil)
13823 (view-calendar-holidays-initially nil)
13824 (calendar-view-diary-initially-flag nil)
13825 (view-diary-entries-initially nil))
13826 (if (or (org-at-timestamp-p)
13827 (save-excursion
13828 (beginning-of-line 1)
13829 (looking-at (concat ".*" tsr))))
13830 (let ((d1 (time-to-days (current-time)))
13831 (d2 (time-to-days
13832 (org-time-string-to-time (match-string 1)))))
13833 (setq diff (- d2 d1))))
13834 (calendar)
13835 (calendar-goto-today)
13836 (if (and diff (not arg)) (calendar-forward-day diff))))
13838 (defun org-get-date-from-calendar ()
13839 "Return a list (month day year) of date at point in calendar."
13840 (with-current-buffer "*Calendar*"
13841 (save-match-data
13842 (calendar-cursor-to-date))))
13844 (defun org-date-from-calendar ()
13845 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13846 If there is already a time stamp at the cursor position, update it."
13847 (interactive)
13848 (if (org-at-timestamp-p t)
13849 (org-timestamp-change 0 'calendar)
13850 (let ((cal-date (org-get-date-from-calendar)))
13851 (org-insert-time-stamp
13852 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13854 (defun org-minutes-to-hh:mm-string (m)
13855 "Compute H:MM from a number of minutes."
13856 (let ((h (/ m 60)))
13857 (setq m (- m (* 60 h)))
13858 (format org-time-clocksum-format h m)))
13860 (defun org-hh:mm-string-to-minutes (s)
13861 "Convert a string H:MM to a number of minutes.
13862 If the string is just a number, interprete it as minutes.
13863 In fact, the first hh:mm or number in the string will be taken,
13864 there can be extra stuff in the string.
13865 If no number is found, the return value is 0."
13866 (cond
13867 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13868 (+ (* (string-to-number (match-string 1 s)) 60)
13869 (string-to-number (match-string 2 s))))
13870 ((string-match "\\([0-9]+\\)" s)
13871 (string-to-number (match-string 1 s)))
13872 (t 0)))
13874 ;;;; Files
13876 (defun org-save-all-org-buffers ()
13877 "Save all Org-mode buffers without user confirmation."
13878 (interactive)
13879 (message "Saving all Org-mode buffers...")
13880 (save-some-buffers t 'org-mode-p)
13881 (when (featurep 'org-id) (org-id-locations-save))
13882 (message "Saving all Org-mode buffers... done"))
13884 (defun org-revert-all-org-buffers ()
13885 "Revert all Org-mode buffers.
13886 Prompt for confirmation when there are unsaved changes.
13887 Be sure you know what you are doing before letting this function
13888 overwrite your changes.
13890 This function is useful in a setup where one tracks org files
13891 with a version control system, to revert on one machine after pulling
13892 changes from another. I believe the procedure must be like this:
13894 1. M-x org-save-all-org-buffers
13895 2. Pull changes from the other machine, resolve conflicts
13896 3. M-x org-revert-all-org-buffers"
13897 (interactive)
13898 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13899 (error "Abort"))
13900 (save-excursion
13901 (save-window-excursion
13902 (mapc
13903 (lambda (b)
13904 (when (and (with-current-buffer b (org-mode-p))
13905 (with-current-buffer b buffer-file-name))
13906 (switch-to-buffer b)
13907 (revert-buffer t 'no-confirm)))
13908 (buffer-list))
13909 (when (and (featurep 'org-id) org-id-track-globally)
13910 (org-id-locations-load)))))
13912 ;;;; Agenda files
13914 ;;;###autoload
13915 (defun org-iswitchb (&optional arg)
13916 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
13917 With a prefix argument, restrict available to files.
13918 With two prefix arguments, restrict available buffers to agenda files."
13919 (interactive "P")
13920 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13921 ((equal arg '(16)) (org-buffer-list 'agenda))
13922 (t (org-buffer-list)))))
13923 (switch-to-buffer
13924 (org-icompleting-read "Org buffer: "
13925 (mapcar 'list (mapcar 'buffer-name blist))
13926 nil t))))
13928 ;;;###autoload
13929 (defalias 'org-ido-switchb 'org-iswitchb)
13931 (defun org-buffer-list (&optional predicate exclude-tmp)
13932 "Return a list of Org buffers.
13933 PREDICATE can be `export', `files' or `agenda'.
13935 export restrict the list to Export buffers.
13936 files restrict the list to buffers visiting Org files.
13937 agenda restrict the list to buffers visiting agenda files.
13939 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13940 (let* ((bfn nil)
13941 (agenda-files (and (eq predicate 'agenda)
13942 (mapcar 'file-truename (org-agenda-files t))))
13943 (filter
13944 (cond
13945 ((eq predicate 'files)
13946 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13947 ((eq predicate 'export)
13948 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13949 ((eq predicate 'agenda)
13950 (lambda (b)
13951 (with-current-buffer b
13952 (and (eq major-mode 'org-mode)
13953 (setq bfn (buffer-file-name b))
13954 (member (file-truename bfn) agenda-files)))))
13955 (t (lambda (b) (with-current-buffer b
13956 (or (eq major-mode 'org-mode)
13957 (string-match "\*Org .*Export"
13958 (buffer-name b)))))))))
13959 (delq nil
13960 (mapcar
13961 (lambda(b)
13962 (if (and (funcall filter b)
13963 (or (not exclude-tmp)
13964 (not (string-match "tmp" (buffer-name b)))))
13966 nil))
13967 (buffer-list)))))
13969 (defun org-agenda-files (&optional unrestricted archives)
13970 "Get the list of agenda files.
13971 Optional UNRESTRICTED means return the full list even if a restriction
13972 is currently in place.
13973 When ARCHIVES is t, include all archive files hat are really being
13974 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13975 `org-agenda-archives-mode' is t."
13976 (let ((files
13977 (cond
13978 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13979 ((stringp org-agenda-files) (org-read-agenda-file-list))
13980 ((listp org-agenda-files) org-agenda-files)
13981 (t (error "Invalid value of `org-agenda-files'")))))
13982 (setq files (apply 'append
13983 (mapcar (lambda (f)
13984 (if (file-directory-p f)
13985 (directory-files
13986 f t org-agenda-file-regexp)
13987 (list f)))
13988 files)))
13989 (when org-agenda-skip-unavailable-files
13990 (setq files (delq nil
13991 (mapcar (function
13992 (lambda (file)
13993 (and (file-readable-p file) file)))
13994 files))))
13995 (when (or (eq archives t)
13996 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13997 (setq files (org-add-archive-files files)))
13998 files))
14000 (defun org-edit-agenda-file-list ()
14001 "Edit the list of agenda files.
14002 Depending on setup, this either uses customize to edit the variable
14003 `org-agenda-files', or it visits the file that is holding the list. In the
14004 latter case, the buffer is set up in a way that saving it automatically kills
14005 the buffer and restores the previous window configuration."
14006 (interactive)
14007 (if (stringp org-agenda-files)
14008 (let ((cw (current-window-configuration)))
14009 (find-file org-agenda-files)
14010 (org-set-local 'org-window-configuration cw)
14011 (org-add-hook 'after-save-hook
14012 (lambda ()
14013 (set-window-configuration
14014 (prog1 org-window-configuration
14015 (kill-buffer (current-buffer))))
14016 (org-install-agenda-files-menu)
14017 (message "New agenda file list installed"))
14018 nil 'local)
14019 (message "%s" (substitute-command-keys
14020 "Edit list and finish with \\[save-buffer]")))
14021 (customize-variable 'org-agenda-files)))
14023 (defun org-store-new-agenda-file-list (list)
14024 "Set new value for the agenda file list and save it correctly."
14025 (if (stringp org-agenda-files)
14026 (let ((f org-agenda-files) b)
14027 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14028 (with-temp-file f
14029 (insert (mapconcat 'identity list "\n") "\n")))
14030 (let ((org-mode-hook nil) (org-inhibit-startup t)
14031 (org-insert-mode-line-in-empty-file nil))
14032 (setq org-agenda-files list)
14033 (customize-save-variable 'org-agenda-files org-agenda-files))))
14035 (defun org-read-agenda-file-list ()
14036 "Read the list of agenda files from a file."
14037 (when (file-directory-p org-agenda-files)
14038 (error "`org-agenda-files' cannot be a single directory"))
14039 (when (stringp org-agenda-files)
14040 (with-temp-buffer
14041 (insert-file-contents org-agenda-files)
14042 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14045 ;;;###autoload
14046 (defun org-cycle-agenda-files ()
14047 "Cycle through the files in `org-agenda-files'.
14048 If the current buffer visits an agenda file, find the next one in the list.
14049 If the current buffer does not, find the first agenda file."
14050 (interactive)
14051 (let* ((fs (org-agenda-files t))
14052 (files (append fs (list (car fs))))
14053 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14054 file)
14055 (unless files (error "No agenda files"))
14056 (catch 'exit
14057 (while (setq file (pop files))
14058 (if (equal (file-truename file) tcf)
14059 (when (car files)
14060 (find-file (car files))
14061 (throw 'exit t))))
14062 (find-file (car fs)))
14063 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14065 (defun org-agenda-file-to-front (&optional to-end)
14066 "Move/add the current file to the top of the agenda file list.
14067 If the file is not present in the list, it is added to the front. If it is
14068 present, it is moved there. With optional argument TO-END, add/move to the
14069 end of the list."
14070 (interactive "P")
14071 (let ((org-agenda-skip-unavailable-files nil)
14072 (file-alist (mapcar (lambda (x)
14073 (cons (file-truename x) x))
14074 (org-agenda-files t)))
14075 (ctf (file-truename buffer-file-name))
14076 x had)
14077 (setq x (assoc ctf file-alist) had x)
14079 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14080 (if to-end
14081 (setq file-alist (append (delq x file-alist) (list x)))
14082 (setq file-alist (cons x (delq x file-alist))))
14083 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14084 (org-install-agenda-files-menu)
14085 (message "File %s to %s of agenda file list"
14086 (if had "moved" "added") (if to-end "end" "front"))))
14088 (defun org-remove-file (&optional file)
14089 "Remove current file from the list of files in variable `org-agenda-files'.
14090 These are the files which are being checked for agenda entries.
14091 Optional argument FILE means, use this file instead of the current."
14092 (interactive)
14093 (let* ((org-agenda-skip-unavailable-files nil)
14094 (file (or file buffer-file-name))
14095 (true-file (file-truename file))
14096 (afile (abbreviate-file-name file))
14097 (files (delq nil (mapcar
14098 (lambda (x)
14099 (if (equal true-file
14100 (file-truename x))
14101 nil x))
14102 (org-agenda-files t)))))
14103 (if (not (= (length files) (length (org-agenda-files t))))
14104 (progn
14105 (org-store-new-agenda-file-list files)
14106 (org-install-agenda-files-menu)
14107 (message "Removed file: %s" afile))
14108 (message "File was not in list: %s (not removed)" afile))))
14110 (defun org-file-menu-entry (file)
14111 (vector file (list 'find-file file) t))
14113 (defun org-check-agenda-file (file)
14114 "Make sure FILE exists. If not, ask user what to do."
14115 (when (not (file-exists-p file))
14116 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14117 (abbreviate-file-name file))
14118 (let ((r (downcase (read-char-exclusive))))
14119 (cond
14120 ((equal r ?r)
14121 (org-remove-file file)
14122 (throw 'nextfile t))
14123 (t (error "Abort"))))))
14125 (defun org-get-agenda-file-buffer (file)
14126 "Get a buffer visiting FILE. If the buffer needs to be created, add
14127 it to the list of buffers which might be released later."
14128 (let ((buf (org-find-base-buffer-visiting file)))
14129 (if buf
14130 buf ; just return it
14131 ;; Make a new buffer and remember it
14132 (setq buf (find-file-noselect file))
14133 (if buf (push buf org-agenda-new-buffers))
14134 buf)))
14136 (defun org-release-buffers (blist)
14137 "Release all buffers in list, asking the user for confirmation when needed.
14138 When a buffer is unmodified, it is just killed. When modified, it is saved
14139 \(if the user agrees) and then killed."
14140 (let (buf file)
14141 (while (setq buf (pop blist))
14142 (setq file (buffer-file-name buf))
14143 (when (and (buffer-modified-p buf)
14144 file
14145 (y-or-n-p (format "Save file %s? " file)))
14146 (with-current-buffer buf (save-buffer)))
14147 (kill-buffer buf))))
14149 (defun org-prepare-agenda-buffers (files)
14150 "Create buffers for all agenda files, protect archived trees and comments."
14151 (interactive)
14152 (let ((pa '(:org-archived t))
14153 (pc '(:org-comment t))
14154 (pall '(:org-archived t :org-comment t))
14155 (inhibit-read-only t)
14156 (rea (concat ":" org-archive-tag ":"))
14157 bmp file re)
14158 (save-excursion
14159 (save-restriction
14160 (while (setq file (pop files))
14161 (catch 'nextfile
14162 (if (bufferp file)
14163 (set-buffer file)
14164 (org-check-agenda-file file)
14165 (set-buffer (org-get-agenda-file-buffer file)))
14166 (widen)
14167 (setq bmp (buffer-modified-p))
14168 (org-refresh-category-properties)
14169 (setq org-todo-keywords-for-agenda
14170 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14171 (setq org-done-keywords-for-agenda
14172 (append org-done-keywords-for-agenda org-done-keywords))
14173 (setq org-todo-keyword-alist-for-agenda
14174 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14175 (setq org-drawers-for-agenda
14176 (append org-drawers-for-agenda org-drawers))
14177 (setq org-tag-alist-for-agenda
14178 (append org-tag-alist-for-agenda org-tag-alist))
14180 (save-excursion
14181 (remove-text-properties (point-min) (point-max) pall)
14182 (when org-agenda-skip-archived-trees
14183 (goto-char (point-min))
14184 (while (re-search-forward rea nil t)
14185 (if (org-on-heading-p t)
14186 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14187 (goto-char (point-min))
14188 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14189 (while (re-search-forward re nil t)
14190 (add-text-properties
14191 (match-beginning 0) (org-end-of-subtree t) pc)))
14192 (set-buffer-modified-p bmp)))))
14193 (setq org-todo-keyword-alist-for-agenda
14194 (org-uniquify org-todo-keyword-alist-for-agenda)
14195 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14197 ;;;; Embedded LaTeX
14199 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14200 "Keymap for the minor `org-cdlatex-mode'.")
14202 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14203 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14204 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14205 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14206 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14208 (defvar org-cdlatex-texmathp-advice-is-done nil
14209 "Flag remembering if we have applied the advice to texmathp already.")
14211 (define-minor-mode org-cdlatex-mode
14212 "Toggle the minor `org-cdlatex-mode'.
14213 This mode supports entering LaTeX environment and math in LaTeX fragments
14214 in Org-mode.
14215 \\{org-cdlatex-mode-map}"
14216 nil " OCDL" nil
14217 (when org-cdlatex-mode (require 'cdlatex))
14218 (unless org-cdlatex-texmathp-advice-is-done
14219 (setq org-cdlatex-texmathp-advice-is-done t)
14220 (defadvice texmathp (around org-math-always-on activate)
14221 "Always return t in org-mode buffers.
14222 This is because we want to insert math symbols without dollars even outside
14223 the LaTeX math segments. If Orgmode thinks that point is actually inside
14224 an embedded LaTeX fragment, let texmathp do its job.
14225 \\[org-cdlatex-mode-map]"
14226 (interactive)
14227 (let (p)
14228 (cond
14229 ((not (org-mode-p)) ad-do-it)
14230 ((eq this-command 'cdlatex-math-symbol)
14231 (setq ad-return-value t
14232 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14234 (let ((p (org-inside-LaTeX-fragment-p)))
14235 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14236 (setq ad-return-value t
14237 texmathp-why '("Org-mode embedded math" . 0))
14238 (if p ad-do-it)))))))))
14240 (defun turn-on-org-cdlatex ()
14241 "Unconditionally turn on `org-cdlatex-mode'."
14242 (org-cdlatex-mode 1))
14244 (defun org-inside-LaTeX-fragment-p ()
14245 "Test if point is inside a LaTeX fragment.
14246 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14247 sequence appearing also before point.
14248 Even though the matchers for math are configurable, this function assumes
14249 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14250 delimiters are skipped when they have been removed by customization.
14251 The return value is nil, or a cons cell with the delimiter and
14252 and the position of this delimiter.
14254 This function does a reasonably good job, but can locally be fooled by
14255 for example currency specifications. For example it will assume being in
14256 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14257 fragments that are properly closed, but during editing, we have to live
14258 with the uncertainty caused by missing closing delimiters. This function
14259 looks only before point, not after."
14260 (catch 'exit
14261 (let ((pos (point))
14262 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14263 (lim (progn
14264 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14265 (point)))
14266 dd-on str (start 0) m re)
14267 (goto-char pos)
14268 (when dodollar
14269 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14270 re (nth 1 (assoc "$" org-latex-regexps)))
14271 (while (string-match re str start)
14272 (cond
14273 ((= (match-end 0) (length str))
14274 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14275 ((= (match-end 0) (- (length str) 5))
14276 (throw 'exit nil))
14277 (t (setq start (match-end 0))))))
14278 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14279 (goto-char pos)
14280 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14281 (and (match-beginning 2) (throw 'exit nil))
14282 ;; count $$
14283 (while (re-search-backward "\\$\\$" lim t)
14284 (setq dd-on (not dd-on)))
14285 (goto-char pos)
14286 (if dd-on (cons "$$" m))))))
14289 (defun org-try-cdlatex-tab ()
14290 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14291 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14292 - inside a LaTeX fragment, or
14293 - after the first word in a line, where an abbreviation expansion could
14294 insert a LaTeX environment."
14295 (when org-cdlatex-mode
14296 (cond
14297 ((save-excursion
14298 (skip-chars-backward "a-zA-Z0-9*")
14299 (skip-chars-backward " \t")
14300 (bolp))
14301 (cdlatex-tab) t)
14302 ((org-inside-LaTeX-fragment-p)
14303 (cdlatex-tab) t)
14304 (t nil))))
14306 (defun org-cdlatex-underscore-caret (&optional arg)
14307 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14308 Revert to the normal definition outside of these fragments."
14309 (interactive "P")
14310 (if (org-inside-LaTeX-fragment-p)
14311 (call-interactively 'cdlatex-sub-superscript)
14312 (let (org-cdlatex-mode)
14313 (call-interactively (key-binding (vector last-input-event))))))
14315 (defun org-cdlatex-math-modify (&optional arg)
14316 "Execute `cdlatex-math-modify' in LaTeX fragments.
14317 Revert to the normal definition outside of these fragments."
14318 (interactive "P")
14319 (if (org-inside-LaTeX-fragment-p)
14320 (call-interactively 'cdlatex-math-modify)
14321 (let (org-cdlatex-mode)
14322 (call-interactively (key-binding (vector last-input-event))))))
14324 (defvar org-latex-fragment-image-overlays nil
14325 "List of overlays carrying the images of latex fragments.")
14326 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14328 (defun org-remove-latex-fragment-image-overlays ()
14329 "Remove all overlays with LaTeX fragment images in current buffer."
14330 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14331 (setq org-latex-fragment-image-overlays nil))
14333 (defun org-preview-latex-fragment (&optional subtree)
14334 "Preview the LaTeX fragment at point, or all locally or globally.
14335 If the cursor is in a LaTeX fragment, create the image and overlay
14336 it over the source code. If there is no fragment at point, display
14337 all fragments in the current text, from one headline to the next. With
14338 prefix SUBTREE, display all fragments in the current subtree. With a
14339 double prefix `C-u C-u', or when the cursor is before the first headline,
14340 display all fragments in the buffer.
14341 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14342 (interactive "P")
14343 (org-remove-latex-fragment-image-overlays)
14344 (save-excursion
14345 (save-restriction
14346 (let (beg end at msg)
14347 (cond
14348 ((or (equal subtree '(16))
14349 (not (save-excursion
14350 (re-search-backward (concat "^" outline-regexp) nil t))))
14351 (setq beg (point-min) end (point-max)
14352 msg "Creating images for buffer...%s"))
14353 ((equal subtree '(4))
14354 (org-back-to-heading)
14355 (setq beg (point) end (org-end-of-subtree t)
14356 msg "Creating images for subtree...%s"))
14358 (if (setq at (org-inside-LaTeX-fragment-p))
14359 (goto-char (max (point-min) (- (cdr at) 2)))
14360 (org-back-to-heading))
14361 (setq beg (point) end (progn (outline-next-heading) (point))
14362 msg (if at "Creating image...%s"
14363 "Creating images for entry...%s"))))
14364 (message msg "")
14365 (narrow-to-region beg end)
14366 (goto-char beg)
14367 (org-format-latex
14368 (concat "ltxpng/" (file-name-sans-extension
14369 (file-name-nondirectory
14370 buffer-file-name)))
14371 default-directory 'overlays msg at 'forbuffer)
14372 (message msg "done. Use `C-c C-c' to remove images.")))))
14374 (defvar org-latex-regexps
14375 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14376 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14377 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14378 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14379 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14380 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14381 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14382 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14383 "Regular expressions for matching embedded LaTeX.")
14385 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14386 "Replace LaTeX fragments with links to an image, and produce images.
14387 Some of the options can be changed using the variable
14388 `org-format-latex-options'."
14389 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14390 (let* ((prefixnodir (file-name-nondirectory prefix))
14391 (absprefix (expand-file-name prefix dir))
14392 (todir (file-name-directory absprefix))
14393 (opt org-format-latex-options)
14394 (matchers (plist-get opt :matchers))
14395 (re-list org-latex-regexps)
14396 (cnt 0) txt link beg end re e checkdir
14397 executables-checked
14398 m n block linkfile movefile ov)
14399 ;; Check if there are old images files with this prefix, and remove them
14400 (when (file-directory-p todir)
14401 (mapc 'delete-file
14402 (directory-files
14403 todir 'full
14404 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
14405 ;; Check the different regular expressions
14406 (while (setq e (pop re-list))
14407 (setq m (car e) re (nth 1 e) n (nth 2 e)
14408 block (if (nth 3 e) "\n\n" ""))
14409 (when (member m matchers)
14410 (goto-char (point-min))
14411 (while (re-search-forward re nil t)
14412 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14413 (not (get-text-property (match-beginning n)
14414 'org-protected))
14415 (or (not overlays)
14416 (not (eq (get-char-property (match-beginning n)
14417 'org-overlay-type)
14418 'org-latex-overlay))))
14419 (setq txt (match-string n)
14420 beg (match-beginning n) end (match-end n)
14421 cnt (1+ cnt)
14422 linkfile (format "%s_%04d.png" prefix cnt)
14423 movefile (format "%s_%04d.png" absprefix cnt)
14424 link (concat block "[[file:" linkfile "]]" block))
14425 (if msg (message msg cnt))
14426 (goto-char beg)
14427 (unless checkdir ; make sure the directory exists
14428 (setq checkdir t)
14429 (or (file-directory-p todir) (make-directory todir)))
14431 (unless executables-checked
14432 (org-check-external-command
14433 "latex" "needed to convert LaTeX fragments to images")
14434 (org-check-external-command
14435 "dvipng" "needed to convert LaTeX fragments to images")
14436 (setq executables-checked t))
14438 (org-create-formula-image
14439 txt movefile opt forbuffer)
14440 (if overlays
14441 (progn
14442 (mapc (lambda (o)
14443 (if (eq (org-overlay-get o 'org-overlay-type)
14444 'org-latex-overlay)
14445 (org-delete-overlay o)))
14446 (org-overlays-in beg end))
14447 (setq ov (org-make-overlay beg end))
14448 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14449 (if (featurep 'xemacs)
14450 (progn
14451 (org-overlay-put ov 'invisible t)
14452 (org-overlay-put
14453 ov 'end-glyph
14454 (make-glyph (vector 'png :file movefile))))
14455 (org-overlay-put
14456 ov 'display
14457 (list 'image :type 'png :file movefile :ascent 'center)))
14458 (push ov org-latex-fragment-image-overlays)
14459 (goto-char end))
14460 (delete-region beg end)
14461 (insert link))))))))
14463 (defvar org-export-latex-packages-alist) ;; defined in org-latex.el
14464 ;; This function borrows from Ganesh Swami's latex2png.el
14465 (defun org-create-formula-image (string tofile options buffer)
14466 "This calls dvipng."
14467 (require 'org-latex)
14468 (let* ((tmpdir (if (featurep 'xemacs)
14469 (temp-directory)
14470 temporary-file-directory))
14471 (texfilebase (make-temp-name
14472 (expand-file-name "orgtex" tmpdir)))
14473 (texfile (concat texfilebase ".tex"))
14474 (dvifile (concat texfilebase ".dvi"))
14475 (pngfile (concat texfilebase ".png"))
14476 (fnh (if (featurep 'xemacs)
14477 (font-height (get-face-font 'default))
14478 (face-attribute 'default :height nil)))
14479 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14480 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14481 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14482 "Black"))
14483 (bg (or (plist-get options (if buffer :background :html-background))
14484 "Transparent")))
14485 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14486 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14487 (with-temp-file texfile
14488 (insert org-format-latex-header
14489 (if org-export-latex-packages-alist
14490 (concat "\n"
14491 (mapconcat (lambda(p)
14492 (if (equal "" (car p))
14493 (format "\\usepackage{%s}" (cadr p))
14494 (format "\\usepackage[%s]{%s}"
14495 (car p) (cadr p))))
14496 org-export-latex-packages-alist "\n"))
14498 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14499 (let ((dir default-directory))
14500 (condition-case nil
14501 (progn
14502 (cd tmpdir)
14503 (call-process "latex" nil nil nil texfile))
14504 (error nil))
14505 (cd dir))
14506 (if (not (file-exists-p dvifile))
14507 (progn (message "Failed to create dvi file from %s" texfile) nil)
14508 (condition-case nil
14509 (call-process "dvipng" nil nil nil
14510 "-fg" fg "-bg" bg
14511 "-D" dpi
14512 ;;"-x" scale "-y" scale
14513 "-T" "tight"
14514 "-o" pngfile
14515 dvifile)
14516 (error nil))
14517 (if (not (file-exists-p pngfile))
14518 (progn (message "Failed to create png file from %s" texfile) nil)
14519 ;; Use the requested file name and clean up
14520 (copy-file pngfile tofile 'replace)
14521 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14522 (delete-file (concat texfilebase e)))
14523 pngfile))))
14525 (defun org-dvipng-color (attr)
14526 "Return an rgb color specification for dvipng."
14527 (apply 'format "rgb %s %s %s"
14528 (mapcar 'org-normalize-color
14529 (color-values (face-attribute 'default attr nil)))))
14531 (defun org-normalize-color (value)
14532 "Return string to be used as color value for an RGB component."
14533 (format "%g" (/ value 65535.0)))
14535 ;;;; Key bindings
14537 ;; Make `C-c C-x' a prefix key
14538 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14540 ;; TAB key with modifiers
14541 (org-defkey org-mode-map "\C-i" 'org-cycle)
14542 (org-defkey org-mode-map [(tab)] 'org-cycle)
14543 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14544 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14545 (org-defkey org-mode-map "\M-\t" 'org-complete)
14546 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14547 ;; The following line is necessary under Suse GNU/Linux
14548 (unless (featurep 'xemacs)
14549 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14550 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14551 (define-key org-mode-map [backtab] 'org-shifttab)
14553 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14554 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14555 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14557 ;; Cursor keys with modifiers
14558 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14559 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14560 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14561 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14563 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14564 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14565 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14566 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14568 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14569 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14570 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14571 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14573 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14574 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14576 ;;; Extra keys for tty access.
14577 ;; We only set them when really needed because otherwise the
14578 ;; menus don't show the simple keys
14580 (when (or org-use-extra-keys
14581 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14582 (not window-system))
14583 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14584 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14585 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14586 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14587 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14588 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14589 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14590 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14591 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14592 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14593 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14594 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14595 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14596 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14597 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14598 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14599 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14600 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14601 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14602 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14603 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14604 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14605 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14606 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14607 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14608 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14609 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14610 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14612 ;; All the other keys
14614 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14615 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14616 (if (boundp 'narrow-map)
14617 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14618 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14619 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14620 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14621 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14622 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14623 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
14624 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14625 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14626 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14627 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14628 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14629 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14630 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14631 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14632 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14633 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14634 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14635 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14636 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14637 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14638 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14639 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14640 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14641 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14642 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14643 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14644 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14645 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14646 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14647 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14648 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14649 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14650 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14651 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14652 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14653 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14654 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14655 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14656 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14657 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14658 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14659 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14660 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14661 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14662 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14663 (org-defkey org-mode-map "\C-c^" 'org-sort)
14664 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14665 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14666 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
14667 (org-defkey org-mode-map "\C-m" 'org-return)
14668 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14669 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14670 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14671 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14672 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14673 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14674 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14675 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14676 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14677 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14678 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14679 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14680 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14681 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14682 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14683 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14684 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14685 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
14686 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
14687 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14688 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14690 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14691 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14692 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14693 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14695 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14696 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14697 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14698 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14699 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14700 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14701 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14702 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14703 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14704 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14705 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14706 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
14707 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14708 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14709 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14711 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14712 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14713 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14714 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14716 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14718 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14720 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14721 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14723 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14726 (when (featurep 'xemacs)
14727 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14730 (defconst org-speed-commands-default
14732 ("a" . org-agenda)
14733 ("/" . org-sparse-tree)
14734 (";" . org-set-tags-command)
14735 ("I" . org-clock-in)
14736 ("O" . org-clock-out)
14737 ("c" . org-cycle)
14738 ("C" . org-shifttab)
14739 ("n" . outline-next-visible-heading)
14740 ("p" . outline-previous-visible-heading)
14741 ("f" . org-forward-same-level)
14742 ("b" . org-backward-same-level)
14743 ("u" . outline-up-heading)
14744 ("U" . org-shiftmetaup)
14745 ("D" . org-shiftmetadown)
14746 ("r" . org-metaright)
14747 ("l" . org-metaleft)
14748 ("R" . org-shiftmetaright)
14749 ("L" . org-shiftmetaleft)
14750 ("i" . (progn (forward-char 1) (call-interactively
14751 'org-insert-heading-respect-content)))
14752 ("o" . org-open-at-point)
14753 ("t" . org-todo)
14754 ("j" . org-goto)
14755 ("g" . (org-refile t))
14756 ("e" . org-set-effort)
14757 ("0" . (org-priority ?\ ))
14758 ("1" . (org-priority ?A))
14759 ("2" . (org-priority ?B))
14760 ("3" . (org-priority ?C))
14761 ("." . outline-mark-subtree)
14762 ("^" . org-sort)
14763 ("w" . org-refile)
14764 ("a" . org-archive-subtree-default-with-confirmation)
14765 ("/" . org-sparse-tree)
14766 ("?" . org-speed-command-help)
14768 "The default speed commands.")
14770 (defun org-print-speed-command (e)
14771 (princ (car e))
14772 (princ " ")
14773 (if (symbolp (cdr e))
14774 (princ (symbol-name (cdr e)))
14775 (prin1 (cdr e)))
14776 (princ "\n"))
14778 (defun org-speed-command-help ()
14779 "Show the available speed commands."
14780 (interactive)
14781 (if (not org-use-speed-commands)
14782 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
14783 (with-output-to-temp-buffer "*Help*"
14784 (princ "Speed commands\n==============\n")
14785 (mapc 'org-print-speed-command org-speed-commands-user)
14786 (princ "\n")
14787 (mapc 'org-print-speed-command org-speed-commands-default))))
14789 (defvar org-self-insert-command-undo-counter 0)
14791 (defvar org-table-auto-blank-field) ; defined in org-table.el
14792 (defvar org-speed-command nil)
14793 (defun org-self-insert-command (N)
14794 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14795 If the cursor is in a table looking at whitespace, the whitespace is
14796 overwritten, and the table is not marked as requiring realignment."
14797 (interactive "p")
14798 (cond
14799 ((and org-use-speed-commands
14800 (bolp)
14801 (looking-at outline-regexp)
14802 (setq
14803 org-speed-command
14804 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
14805 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
14806 (cond
14807 ((commandp org-speed-command)
14808 (setq this-command org-speed-command)
14809 (call-interactively org-speed-command))
14810 ((functionp org-speed-command)
14811 (funcall org-speed-command))
14812 ((and org-speed-command (listp org-speed-command))
14813 (eval org-speed-command))
14814 (t (let (org-use-speed-commands)
14815 (call-interactively 'org-self-insert-command)))))
14816 ((and
14817 (org-table-p)
14818 (progn
14819 ;; check if we blank the field, and if that triggers align
14820 (and (featurep 'org-table) org-table-auto-blank-field
14821 (member last-command
14822 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
14823 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14824 ;; got extra space, this field does not determine column width
14825 (let (org-table-may-need-update) (org-table-blank-field))
14826 ;; no extra space, this field may determine column width
14827 (org-table-blank-field)))
14829 (eq N 1)
14830 (looking-at "[^|\n]* |"))
14831 (let (org-table-may-need-update)
14832 (goto-char (1- (match-end 0)))
14833 (delete-backward-char 1)
14834 (goto-char (match-beginning 0))
14835 (self-insert-command N)))
14837 (setq org-table-may-need-update t)
14838 (self-insert-command N)
14839 (org-fix-tags-on-the-fly)
14840 (if org-self-insert-cluster-for-undo
14841 (if (not (eq last-command 'org-self-insert-command))
14842 (setq org-self-insert-command-undo-counter 1)
14843 (if (>= org-self-insert-command-undo-counter 20)
14844 (setq org-self-insert-command-undo-counter 1)
14845 (and (> org-self-insert-command-undo-counter 0)
14846 buffer-undo-list
14847 (not (cadr buffer-undo-list)) ; remove nil entry
14848 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14849 (setq org-self-insert-command-undo-counter
14850 (1+ org-self-insert-command-undo-counter))))))))
14852 (defun org-fix-tags-on-the-fly ()
14853 (when (and (equal (char-after (point-at-bol)) ?*)
14854 (org-on-heading-p))
14855 (org-align-tags-here org-tags-column)))
14857 (defun org-delete-backward-char (N)
14858 "Like `delete-backward-char', insert whitespace at field end in tables.
14859 When deleting backwards, in tables this function will insert whitespace in
14860 front of the next \"|\" separator, to keep the table aligned. The table will
14861 still be marked for re-alignment if the field did fill the entire column,
14862 because, in this case the deletion might narrow the column."
14863 (interactive "p")
14864 (if (and (org-table-p)
14865 (eq N 1)
14866 (string-match "|" (buffer-substring (point-at-bol) (point)))
14867 (looking-at ".*?|"))
14868 (let ((pos (point))
14869 (noalign (looking-at "[^|\n\r]* |"))
14870 (c org-table-may-need-update))
14871 (backward-delete-char N)
14872 (skip-chars-forward "^|")
14873 (insert " ")
14874 (goto-char (1- pos))
14875 ;; noalign: if there were two spaces at the end, this field
14876 ;; does not determine the width of the column.
14877 (if noalign (setq org-table-may-need-update c)))
14878 (backward-delete-char N)
14879 (org-fix-tags-on-the-fly)))
14881 (defun org-delete-char (N)
14882 "Like `delete-char', but insert whitespace at field end in tables.
14883 When deleting characters, in tables this function will insert whitespace in
14884 front of the next \"|\" separator, to keep the table aligned. The table will
14885 still be marked for re-alignment if the field did fill the entire column,
14886 because, in this case the deletion might narrow the column."
14887 (interactive "p")
14888 (if (and (org-table-p)
14889 (not (bolp))
14890 (not (= (char-after) ?|))
14891 (eq N 1))
14892 (if (looking-at ".*?|")
14893 (let ((pos (point))
14894 (noalign (looking-at "[^|\n\r]* |"))
14895 (c org-table-may-need-update))
14896 (replace-match (concat
14897 (substring (match-string 0) 1 -1)
14898 " |"))
14899 (goto-char pos)
14900 ;; noalign: if there were two spaces at the end, this field
14901 ;; does not determine the width of the column.
14902 (if noalign (setq org-table-may-need-update c)))
14903 (delete-char N))
14904 (delete-char N)
14905 (org-fix-tags-on-the-fly)))
14907 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14908 (put 'org-self-insert-command 'delete-selection t)
14909 (put 'orgtbl-self-insert-command 'delete-selection t)
14910 (put 'org-delete-char 'delete-selection 'supersede)
14911 (put 'org-delete-backward-char 'delete-selection 'supersede)
14912 (put 'org-yank 'delete-selection 'yank)
14914 ;; Make `flyspell-mode' delay after some commands
14915 (put 'org-self-insert-command 'flyspell-delayed t)
14916 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14917 (put 'org-delete-char 'flyspell-delayed t)
14918 (put 'org-delete-backward-char 'flyspell-delayed t)
14920 ;; Make pabbrev-mode expand after org-mode commands
14921 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14922 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14924 ;; How to do this: Measure non-white length of current string
14925 ;; If equal to column width, we should realign.
14927 (defun org-remap (map &rest commands)
14928 "In MAP, remap the functions given in COMMANDS.
14929 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14930 (let (new old)
14931 (while commands
14932 (setq old (pop commands) new (pop commands))
14933 (if (fboundp 'command-remapping)
14934 (org-defkey map (vector 'remap old) new)
14935 (substitute-key-definition old new map global-map)))))
14937 (when (eq org-enable-table-editor 'optimized)
14938 ;; If the user wants maximum table support, we need to hijack
14939 ;; some standard editing functions
14940 (org-remap org-mode-map
14941 'self-insert-command 'org-self-insert-command
14942 'delete-char 'org-delete-char
14943 'delete-backward-char 'org-delete-backward-char)
14944 (org-defkey org-mode-map "|" 'org-force-self-insert))
14946 (defvar org-ctrl-c-ctrl-c-hook nil
14947 "Hook for functions attaching themselves to `C-c C-c'.
14948 This can be used to add additional functionality to the C-c C-c key which
14949 executes context-dependent commands.
14950 Each function will be called with no arguments. The function must check
14951 if the context is appropriate for it to act. If yes, it should do its
14952 thing and then return a non-nil value. If the context is wrong,
14953 just do nothing and return nil.")
14955 (defvar org-tab-first-hook nil
14956 "Hook for functions to attach themselves to TAB.
14957 See `org-ctrl-c-ctrl-c-hook' for more information.
14958 This hook runs as the first action when TAB is pressed, even before
14959 `org-cycle' messes around with the `outline-regexp' to cater for
14960 inline tasks and plain list item folding.
14961 If any function in this hook returns t, not other actions like table
14962 field motion visibility cycling will be done.")
14964 (defvar org-tab-after-check-for-table-hook nil
14965 "Hook for functions to attach themselves to TAB.
14966 See `org-ctrl-c-ctrl-c-hook' for more information.
14967 This hook runs after it has been established that the cursor is not in a
14968 table, but before checking if the cursor is in a headline or if global cycling
14969 should be done.
14970 If any function in this hook returns t, not other actions like visibility
14971 cycling will be done.")
14973 (defvar org-tab-after-check-for-cycling-hook nil
14974 "Hook for functions to attach themselves to TAB.
14975 See `org-ctrl-c-ctrl-c-hook' for more information.
14976 This hook runs after it has been established that not table field motion and
14977 not visibility should be done because of current context. This is probably
14978 the place where a package like yasnippets can hook in.")
14980 (defvar org-tab-before-tab-emulation-hook nil
14981 "Hook for functions to attach themselves to TAB.
14982 See `org-ctrl-c-ctrl-c-hook' for more information.
14983 This hook runs after every other options for TAB have been exhausted, but
14984 before indentation and \t insertion takes place.")
14986 (defvar org-metaleft-hook nil
14987 "Hook for functions attaching themselves to `M-left'.
14988 See `org-ctrl-c-ctrl-c-hook' for more information.")
14989 (defvar org-metaright-hook nil
14990 "Hook for functions attaching themselves to `M-right'.
14991 See `org-ctrl-c-ctrl-c-hook' for more information.")
14992 (defvar org-metaup-hook nil
14993 "Hook for functions attaching themselves to `M-up'.
14994 See `org-ctrl-c-ctrl-c-hook' for more information.")
14995 (defvar org-metadown-hook nil
14996 "Hook for functions attaching themselves to `M-down'.
14997 See `org-ctrl-c-ctrl-c-hook' for more information.")
14998 (defvar org-shiftmetaleft-hook nil
14999 "Hook for functions attaching themselves to `M-S-left'.
15000 See `org-ctrl-c-ctrl-c-hook' for more information.")
15001 (defvar org-shiftmetaright-hook nil
15002 "Hook for functions attaching themselves to `M-S-right'.
15003 See `org-ctrl-c-ctrl-c-hook' for more information.")
15004 (defvar org-shiftmetaup-hook nil
15005 "Hook for functions attaching themselves to `M-S-up'.
15006 See `org-ctrl-c-ctrl-c-hook' for more information.")
15007 (defvar org-shiftmetadown-hook nil
15008 "Hook for functions attaching themselves to `M-S-down'.
15009 See `org-ctrl-c-ctrl-c-hook' for more information.")
15010 (defvar org-metareturn-hook nil
15011 "Hook for functions attaching themselves to `M-RET'.
15012 See `org-ctrl-c-ctrl-c-hook' for more information.")
15014 (defun org-modifier-cursor-error ()
15015 "Throw an error, a modified cursor command was applied in wrong context."
15016 (error "This command is active in special context like tables, headlines or items"))
15018 (defun org-shiftselect-error ()
15019 "Throw an error because Shift-Cursor command was applied in wrong context."
15020 (if (and (boundp 'shift-select-mode) shift-select-mode)
15021 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15022 (error "This command works only in special context like headlines or timestamps")))
15024 (defun org-call-for-shift-select (cmd)
15025 (let ((this-command-keys-shift-translated t))
15026 (call-interactively cmd)))
15028 (defun org-shifttab (&optional arg)
15029 "Global visibility cycling or move to previous table field.
15030 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15031 on context.
15032 See the individual commands for more information."
15033 (interactive "P")
15034 (cond
15035 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15036 ((integerp arg)
15037 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15038 (message "Content view to level: %d" arg)
15039 (org-content (prefix-numeric-value arg2))
15040 (setq org-cycle-global-status 'overview)))
15041 (t (call-interactively 'org-global-cycle))))
15043 (defun org-shiftmetaleft ()
15044 "Promote subtree or delete table column.
15045 Calls `org-promote-subtree', `org-outdent-item',
15046 or `org-table-delete-column', depending on context.
15047 See the individual commands for more information."
15048 (interactive)
15049 (cond
15050 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15051 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15052 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15053 ((org-at-item-p) (call-interactively 'org-outdent-item))
15054 (t (org-modifier-cursor-error))))
15056 (defun org-shiftmetaright ()
15057 "Demote subtree or insert table column.
15058 Calls `org-demote-subtree', `org-indent-item',
15059 or `org-table-insert-column', depending on context.
15060 See the individual commands for more information."
15061 (interactive)
15062 (cond
15063 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15064 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15065 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15066 ((org-at-item-p) (call-interactively 'org-indent-item))
15067 (t (org-modifier-cursor-error))))
15069 (defun org-shiftmetaup (&optional arg)
15070 "Move subtree up or kill table row.
15071 Calls `org-move-subtree-up' or `org-table-kill-row' or
15072 `org-move-item-up' depending on context. See the individual commands
15073 for more information."
15074 (interactive "P")
15075 (cond
15076 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15077 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15078 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15079 ((org-at-item-p) (call-interactively 'org-move-item-up))
15080 (t (org-modifier-cursor-error))))
15082 (defun org-shiftmetadown (&optional arg)
15083 "Move subtree down or insert table row.
15084 Calls `org-move-subtree-down' or `org-table-insert-row' or
15085 `org-move-item-down', depending on context. See the individual
15086 commands for more information."
15087 (interactive "P")
15088 (cond
15089 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15090 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15091 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15092 ((org-at-item-p) (call-interactively 'org-move-item-down))
15093 (t (org-modifier-cursor-error))))
15095 (defun org-metaleft (&optional arg)
15096 "Promote heading or move table column to left.
15097 Calls `org-do-promote' or `org-table-move-column', depending on context.
15098 With no specific context, calls the Emacs default `backward-word'.
15099 See the individual commands for more information."
15100 (interactive "P")
15101 (cond
15102 ((run-hook-with-args-until-success 'org-metaleft-hook))
15103 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15104 ((or (org-on-heading-p)
15105 (and (org-region-active-p)
15106 (save-excursion
15107 (goto-char (region-beginning))
15108 (org-on-heading-p))))
15109 (call-interactively 'org-do-promote))
15110 ((or (org-at-item-p)
15111 (and (org-region-active-p)
15112 (save-excursion
15113 (goto-char (region-beginning))
15114 (org-at-item-p))))
15115 (call-interactively 'org-outdent-item))
15116 (t (call-interactively 'backward-word))))
15118 (defun org-metaright (&optional arg)
15119 "Demote subtree or move table column to right.
15120 Calls `org-do-demote' or `org-table-move-column', depending on context.
15121 With no specific context, calls the Emacs default `forward-word'.
15122 See the individual commands for more information."
15123 (interactive "P")
15124 (cond
15125 ((run-hook-with-args-until-success 'org-metaright-hook))
15126 ((org-at-table-p) (call-interactively 'org-table-move-column))
15127 ((or (org-on-heading-p)
15128 (and (org-region-active-p)
15129 (save-excursion
15130 (goto-char (region-beginning))
15131 (org-on-heading-p))))
15132 (call-interactively 'org-do-demote))
15133 ((or (org-at-item-p)
15134 (and (org-region-active-p)
15135 (save-excursion
15136 (goto-char (region-beginning))
15137 (org-at-item-p))))
15138 (call-interactively 'org-indent-item))
15139 (t (call-interactively 'forward-word))))
15141 (defun org-metaup (&optional arg)
15142 "Move subtree up or move table row up.
15143 Calls `org-move-subtree-up' or `org-table-move-row' or
15144 `org-move-item-up', depending on context. See the individual commands
15145 for more information."
15146 (interactive "P")
15147 (cond
15148 ((run-hook-with-args-until-success 'org-metaup-hook))
15149 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15150 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15151 ((org-at-item-p) (call-interactively 'org-move-item-up))
15152 (t (transpose-lines 1) (beginning-of-line -1))))
15154 (defun org-metadown (&optional arg)
15155 "Move subtree down or move table row down.
15156 Calls `org-move-subtree-down' or `org-table-move-row' or
15157 `org-move-item-down', depending on context. See the individual
15158 commands for more information."
15159 (interactive "P")
15160 (cond
15161 ((run-hook-with-args-until-success 'org-metadown-hook))
15162 ((org-at-table-p) (call-interactively 'org-table-move-row))
15163 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15164 ((org-at-item-p) (call-interactively 'org-move-item-down))
15165 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15167 (defun org-shiftup (&optional arg)
15168 "Increase item in timestamp or increase priority of current headline.
15169 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15170 depending on context. See the individual commands for more information."
15171 (interactive "P")
15172 (cond
15173 ((and org-support-shift-select (org-region-active-p))
15174 (org-call-for-shift-select 'previous-line))
15175 ((org-at-timestamp-p t)
15176 (call-interactively (if org-edit-timestamp-down-means-later
15177 'org-timestamp-down 'org-timestamp-up)))
15178 ((and (not (eq org-support-shift-select 'always))
15179 org-enable-priority-commands
15180 (org-on-heading-p))
15181 (call-interactively 'org-priority-up))
15182 ((and (not org-support-shift-select) (org-at-item-p))
15183 (call-interactively 'org-previous-item))
15184 ((org-clocktable-try-shift 'up arg))
15185 (org-support-shift-select
15186 (org-call-for-shift-select 'previous-line))
15187 (t (org-shiftselect-error))))
15189 (defun org-shiftdown (&optional arg)
15190 "Decrease item in timestamp or decrease priority of current headline.
15191 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15192 depending on context. See the individual commands for more information."
15193 (interactive "P")
15194 (cond
15195 ((and org-support-shift-select (org-region-active-p))
15196 (org-call-for-shift-select 'next-line))
15197 ((org-at-timestamp-p t)
15198 (call-interactively (if org-edit-timestamp-down-means-later
15199 'org-timestamp-up 'org-timestamp-down)))
15200 ((and (not (eq org-support-shift-select 'always))
15201 org-enable-priority-commands
15202 (org-on-heading-p))
15203 (call-interactively 'org-priority-down))
15204 ((and (not org-support-shift-select) (org-at-item-p))
15205 (call-interactively 'org-next-item))
15206 ((org-clocktable-try-shift 'down arg))
15207 (org-support-shift-select
15208 (org-call-for-shift-select 'next-line))
15209 (t (org-shiftselect-error))))
15211 (defun org-shiftright (&optional arg)
15212 "Cycle the thing at point or in the current line, depending on context.
15213 Depending on context, this does one of the following:
15215 - switch a timestamp at point one day into the future
15216 - on a headline, switch to the next TODO keyword.
15217 - on an item, switch entire list to the next bullet type
15218 - on a property line, switch to the next allowed value
15219 - on a clocktable definition line, move time block into the future"
15220 (interactive "P")
15221 (cond
15222 ((and org-support-shift-select (org-region-active-p))
15223 (org-call-for-shift-select 'forward-char))
15224 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15225 ((and (not (eq org-support-shift-select 'always))
15226 (org-on-heading-p))
15227 (let ((org-inhibit-logging
15228 (not org-treat-S-cursor-todo-selection-as-state-change))
15229 (org-inhibit-blocking
15230 (not org-treat-S-cursor-todo-selection-as-state-change)))
15231 (org-call-with-arg 'org-todo 'right)))
15232 ((or (and org-support-shift-select
15233 (not (eq org-support-shift-select 'always))
15234 (org-at-item-bullet-p))
15235 (and (not org-support-shift-select) (org-at-item-p)))
15236 (org-call-with-arg 'org-cycle-list-bullet nil))
15237 ((and (not (eq org-support-shift-select 'always))
15238 (org-at-property-p))
15239 (call-interactively 'org-property-next-allowed-value))
15240 ((org-clocktable-try-shift 'right arg))
15241 (org-support-shift-select
15242 (org-call-for-shift-select 'forward-char))
15243 (t (org-shiftselect-error))))
15245 (defun org-shiftleft (&optional arg)
15246 "Cycle the thing at point or in the current line, depending on context.
15247 Depending on context, this does one of the following:
15249 - switch a timestamp at point one day into the past
15250 - on a headline, switch to the previous TODO keyword.
15251 - on an item, switch entire list to the previous bullet type
15252 - on a property line, switch to the previous allowed value
15253 - on a clocktable definition line, move time block into the past"
15254 (interactive "P")
15255 (cond
15256 ((and org-support-shift-select (org-region-active-p))
15257 (org-call-for-shift-select 'backward-char))
15258 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15259 ((and (not (eq org-support-shift-select 'always))
15260 (org-on-heading-p))
15261 (let ((org-inhibit-logging
15262 (not org-treat-S-cursor-todo-selection-as-state-change))
15263 (org-inhibit-blocking
15264 (not org-treat-S-cursor-todo-selection-as-state-change)))
15265 (org-call-with-arg 'org-todo 'left)))
15266 ((or (and org-support-shift-select
15267 (not (eq org-support-shift-select 'always))
15268 (org-at-item-bullet-p))
15269 (and (not org-support-shift-select) (org-at-item-p)))
15270 (org-call-with-arg 'org-cycle-list-bullet 'previous))
15271 ((and (not (eq org-support-shift-select 'always))
15272 (org-at-property-p))
15273 (call-interactively 'org-property-previous-allowed-value))
15274 ((org-clocktable-try-shift 'left arg))
15275 (org-support-shift-select
15276 (org-call-for-shift-select 'backward-char))
15277 (t (org-shiftselect-error))))
15279 (defun org-shiftcontrolright ()
15280 "Switch to next TODO set."
15281 (interactive)
15282 (cond
15283 ((and org-support-shift-select (org-region-active-p))
15284 (org-call-for-shift-select 'forward-word))
15285 ((and (not (eq org-support-shift-select 'always))
15286 (org-on-heading-p))
15287 (org-call-with-arg 'org-todo 'nextset))
15288 (org-support-shift-select
15289 (org-call-for-shift-select 'forward-word))
15290 (t (org-shiftselect-error))))
15292 (defun org-shiftcontrolleft ()
15293 "Switch to previous TODO set."
15294 (interactive)
15295 (cond
15296 ((and org-support-shift-select (org-region-active-p))
15297 (org-call-for-shift-select 'backward-word))
15298 ((and (not (eq org-support-shift-select 'always))
15299 (org-on-heading-p))
15300 (org-call-with-arg 'org-todo 'previousset))
15301 (org-support-shift-select
15302 (org-call-for-shift-select 'backward-word))
15303 (t (org-shiftselect-error))))
15305 (defun org-ctrl-c-ret ()
15306 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15307 (interactive)
15308 (cond
15309 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15310 (t (call-interactively 'org-insert-heading))))
15312 (defun org-copy-special ()
15313 "Copy region in table or copy current subtree.
15314 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15315 See the individual commands for more information."
15316 (interactive)
15317 (call-interactively
15318 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15320 (defun org-cut-special ()
15321 "Cut region in table or cut current subtree.
15322 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15323 See the individual commands for more information."
15324 (interactive)
15325 (call-interactively
15326 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15328 (defun org-paste-special (arg)
15329 "Paste rectangular region into table, or past subtree relative to level.
15330 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15331 See the individual commands for more information."
15332 (interactive "P")
15333 (if (org-at-table-p)
15334 (org-table-paste-rectangle)
15335 (org-paste-subtree arg)))
15337 (defun org-edit-special ()
15338 "Call a special editor for the stuff at point.
15339 When at a table, call the formula editor with `org-table-edit-formulas'.
15340 When at the first line of an src example, call `org-edit-src-code'.
15341 When in an #+include line, visit the include file. Otherwise call
15342 `ffap' to visit the file at point."
15343 (interactive)
15344 (cond
15345 ((org-at-table-p)
15346 (call-interactively 'org-table-edit-formulas))
15347 ((save-excursion
15348 (beginning-of-line 1)
15349 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
15350 (find-file (org-trim (match-string 1))))
15351 ((org-edit-src-code))
15352 ((org-edit-fixed-width-region))
15353 (t (call-interactively 'ffap))))
15356 (defun org-ctrl-c-ctrl-c (&optional arg)
15357 "Set tags in headline, or update according to changed information at point.
15359 This command does many different things, depending on context:
15361 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15362 this is what we do.
15364 - If the cursor is on a statistics cookie, update it.
15366 - If the cursor is in a headline, prompt for tags and insert them
15367 into the current line, aligned to `org-tags-column'. When called
15368 with prefix arg, realign all tags in the current buffer.
15370 - If the cursor is in one of the special #+KEYWORD lines, this
15371 triggers scanning the buffer for these lines and updating the
15372 information.
15374 - If the cursor is inside a table, realign the table. This command
15375 works even if the automatic table editor has been turned off.
15377 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15378 the entire table.
15380 - If the cursor is at a footnote reference or definition, jump to
15381 the corresponding definition or references, respectively.
15383 - If the cursor is a the beginning of a dynamic block, update it.
15385 - If the cursor is inside a table created by the table.el package,
15386 activate that table.
15388 - If the current buffer is a remember buffer, close note and file
15389 it. A prefix argument of 1 files to the default location
15390 without further interaction. A prefix argument of 2 files to
15391 the currently clocking task.
15393 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15394 links in this buffer.
15396 - If the cursor is on a numbered item in a plain list, renumber the
15397 ordered list.
15399 - If the cursor is on a checkbox, toggle it."
15400 (interactive "P")
15401 (let ((org-enable-table-editor t))
15402 (cond
15403 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15404 org-occur-highlights
15405 org-latex-fragment-image-overlays)
15406 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15407 (org-remove-occur-highlights)
15408 (org-remove-latex-fragment-image-overlays)
15409 (message "Temporary highlights/overlays removed from current buffer"))
15410 ((and (local-variable-p 'org-finish-function (current-buffer))
15411 (fboundp org-finish-function))
15412 (funcall org-finish-function))
15413 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15414 ((org-at-property-p)
15415 (call-interactively 'org-property-action))
15416 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15417 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15418 (or (org-on-heading-p) (org-at-item-p)))
15419 (call-interactively 'org-update-statistics-cookies))
15420 ((org-on-heading-p) (call-interactively 'org-set-tags))
15421 ((org-at-table.el-p)
15422 (require 'table)
15423 (beginning-of-line 1)
15424 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15425 (call-interactively 'table-recognize-table))
15426 ((org-at-table-p)
15427 (org-table-maybe-eval-formula)
15428 (if arg
15429 (call-interactively 'org-table-recalculate)
15430 (org-table-maybe-recalculate-line))
15431 (call-interactively 'org-table-align))
15432 ((or (org-footnote-at-reference-p)
15433 (org-footnote-at-definition-p))
15434 (call-interactively 'org-footnote-action))
15435 ((org-at-item-checkbox-p)
15436 (call-interactively 'org-toggle-checkbox))
15437 ((org-at-item-p)
15438 (if arg
15439 (call-interactively 'org-toggle-checkbox)
15440 (call-interactively 'org-maybe-renumber-ordered-list)))
15441 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15442 ;; Dynamic block
15443 (beginning-of-line 1)
15444 (save-excursion (org-update-dblock)))
15445 ((save-excursion
15446 (beginning-of-line 1)
15447 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15448 (cond
15449 ((equal (match-string 1) "TBLFM")
15450 ;; Recalculate the table before this line
15451 (save-excursion
15452 (beginning-of-line 1)
15453 (skip-chars-backward " \r\n\t")
15454 (if (org-at-table-p)
15455 (org-call-with-arg 'org-table-recalculate (or arg t)))))
15457 ; (org-set-regexps-and-options)
15458 ; (org-restart-font-lock)
15459 (let ((org-inhibit-startup t)) (org-mode-restart))
15460 (message "Local setup has been refreshed"))))
15461 ((org-clock-update-time-maybe))
15462 (t (error "C-c C-c can do nothing useful at this location")))))
15464 (defun org-mode-restart ()
15465 "Restart Org-mode, to scan again for special lines.
15466 Also updates the keyword regular expressions."
15467 (interactive)
15468 (org-mode)
15469 (message "Org-mode restarted"))
15471 (defun org-kill-note-or-show-branches ()
15472 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15473 (interactive)
15474 (if (not org-finish-function)
15475 (call-interactively 'show-branches)
15476 (let ((org-note-abort t))
15477 (funcall org-finish-function))))
15479 (defun org-return (&optional indent)
15480 "Goto next table row or insert a newline.
15481 Calls `org-table-next-row' or `newline', depending on context.
15482 See the individual commands for more information."
15483 (interactive)
15484 (cond
15485 ((bobp) (if indent (newline-and-indent) (newline)))
15486 ((org-at-table-p)
15487 (org-table-justify-field-maybe)
15488 (call-interactively 'org-table-next-row))
15489 ((and org-return-follows-link
15490 (eq (get-text-property (point) 'face) 'org-link))
15491 (call-interactively 'org-open-at-point))
15492 ((and (org-at-heading-p)
15493 (looking-at
15494 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15495 (org-show-entry)
15496 (end-of-line 1)
15497 (newline))
15498 (t (if indent (newline-and-indent) (newline)))))
15500 (defun org-return-indent ()
15501 "Goto next table row or insert a newline and indent.
15502 Calls `org-table-next-row' or `newline-and-indent', depending on
15503 context. See the individual commands for more information."
15504 (interactive)
15505 (org-return t))
15507 (defun org-ctrl-c-star ()
15508 "Compute table, or change heading status of lines.
15509 Calls `org-table-recalculate' or `org-toggle-heading',
15510 depending on context."
15511 (interactive)
15512 (cond
15513 ((org-at-table-p)
15514 (call-interactively 'org-table-recalculate))
15516 ;; Convert all lines in region to list items
15517 (call-interactively 'org-toggle-heading))))
15519 (defun org-ctrl-c-minus ()
15520 "Insert separator line in table or modify bullet status of line.
15521 Also turns a plain line or a region of lines into list items.
15522 Calls `org-table-insert-hline', `org-toggle-item', or
15523 `org-cycle-list-bullet', depending on context."
15524 (interactive)
15525 (cond
15526 ((org-at-table-p)
15527 (call-interactively 'org-table-insert-hline))
15528 ((org-region-active-p)
15529 (call-interactively 'org-toggle-item))
15530 ((org-in-item-p)
15531 (call-interactively 'org-cycle-list-bullet))
15533 (call-interactively 'org-toggle-item))))
15535 (defun org-toggle-item ()
15536 "Convert headings or normal lines to items, items to normal lines.
15537 If there is no active region, only the current line is considered.
15539 If the first line in the region is a headline, convert all headlines to items.
15541 If the first line in the region is an item, convert all items to normal lines.
15543 If the first line is normal text, add an item bullet to each line."
15544 (interactive)
15545 (let (l2 l beg end)
15546 (if (org-region-active-p)
15547 (setq beg (region-beginning) end (region-end))
15548 (setq beg (point-at-bol)
15549 end (min (1+ (point-at-eol)) (point-max))))
15550 (save-excursion
15551 (goto-char end)
15552 (setq l2 (org-current-line))
15553 (goto-char beg)
15554 (beginning-of-line 1)
15555 (setq l (1- (org-current-line)))
15556 (if (org-at-item-p)
15557 ;; We already have items, de-itemize
15558 (while (< (setq l (1+ l)) l2)
15559 (when (org-at-item-p)
15560 (goto-char (match-beginning 2))
15561 (delete-region (match-beginning 2) (match-end 2))
15562 (and (looking-at "[ \t]+") (replace-match "")))
15563 (beginning-of-line 2))
15564 (if (org-on-heading-p)
15565 ;; Headings, convert to items
15566 (while (< (setq l (1+ l)) l2)
15567 (if (looking-at org-outline-regexp)
15568 (replace-match "- " t t))
15569 (beginning-of-line 2))
15570 ;; normal lines, turn them into items
15571 (while (< (setq l (1+ l)) l2)
15572 (unless (org-at-item-p)
15573 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15574 (replace-match "\\1- \\2")))
15575 (beginning-of-line 2)))))))
15577 (defun org-toggle-heading (&optional nstars)
15578 "Convert headings to normal text, or items or text to headings.
15579 If there is no active region, only the current line is considered.
15581 If the first line is a heading, remove the stars from all headlines
15582 in the region.
15584 If the first line is a plain list item, turn all plain list items
15585 into headings.
15587 If the first line is a normal line, turn each and every line in the
15588 region into a heading.
15590 When converting a line into a heading, the number of stars is chosen
15591 such that the lines become children of the current entry. However,
15592 when a prefix argument is given, its value determines the number of
15593 stars to add."
15594 (interactive "P")
15595 (let (l2 l itemp beg end)
15596 (if (org-region-active-p)
15597 (setq beg (region-beginning) end (region-end))
15598 (setq beg (point-at-bol)
15599 end (min (1+ (point-at-eol)) (point-max))))
15600 (save-excursion
15601 (goto-char end)
15602 (setq l2 (org-current-line))
15603 (goto-char beg)
15604 (beginning-of-line 1)
15605 (setq l (1- (org-current-line)))
15606 (if (org-on-heading-p)
15607 ;; We already have headlines, de-star them
15608 (while (< (setq l (1+ l)) l2)
15609 (when (org-on-heading-p t)
15610 (and (looking-at outline-regexp) (replace-match "")))
15611 (beginning-of-line 2))
15612 (setq itemp (org-at-item-p))
15613 (let* ((stars
15614 (if nstars
15615 (make-string (prefix-numeric-value current-prefix-arg)
15617 (save-excursion
15618 (if (re-search-backward org-complex-heading-regexp nil t)
15619 (match-string 1) ""))))
15620 (add-stars (cond (nstars "")
15621 ((equal stars "") "*")
15622 (org-odd-levels-only "**")
15623 (t "*")))
15624 (rpl (concat stars add-stars " ")))
15625 (while (< (setq l (1+ l)) l2)
15626 (if itemp
15627 (and (org-at-item-p) (replace-match rpl t t))
15628 (unless (org-on-heading-p)
15629 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15630 (replace-match (concat rpl (match-string 2))))))
15631 (beginning-of-line 2)))))))
15633 (defun org-meta-return (&optional arg)
15634 "Insert a new heading or wrap a region in a table.
15635 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15636 See the individual commands for more information."
15637 (interactive "P")
15638 (cond
15639 ((run-hook-with-args-until-success 'org-metareturn-hook))
15640 ((org-at-table-p)
15641 (call-interactively 'org-table-wrap-region))
15642 (t (call-interactively 'org-insert-heading))))
15644 ;;; Menu entries
15646 ;; Define the Org-mode menus
15647 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15648 '("Tbl"
15649 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15650 ["Next Field" org-cycle (org-at-table-p)]
15651 ["Previous Field" org-shifttab (org-at-table-p)]
15652 ["Next Row" org-return (org-at-table-p)]
15653 "--"
15654 ["Blank Field" org-table-blank-field (org-at-table-p)]
15655 ["Edit Field" org-table-edit-field (org-at-table-p)]
15656 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15657 "--"
15658 ("Column"
15659 ["Move Column Left" org-metaleft (org-at-table-p)]
15660 ["Move Column Right" org-metaright (org-at-table-p)]
15661 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15662 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15663 ("Row"
15664 ["Move Row Up" org-metaup (org-at-table-p)]
15665 ["Move Row Down" org-metadown (org-at-table-p)]
15666 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15667 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15668 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15669 "--"
15670 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15671 ("Rectangle"
15672 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15673 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15674 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15675 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15676 "--"
15677 ("Calculate"
15678 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15679 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15680 ["Edit Formulas" org-edit-special (org-at-table-p)]
15681 "--"
15682 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15683 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15684 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15685 "--"
15686 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15687 "--"
15688 ["Sum Column/Rectangle" org-table-sum
15689 (or (org-at-table-p) (org-region-active-p))]
15690 ["Which Column?" org-table-current-column (org-at-table-p)])
15691 ["Debug Formulas"
15692 org-table-toggle-formula-debugger
15693 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15694 ["Show Col/Row Numbers"
15695 org-table-toggle-coordinate-overlays
15696 :style toggle
15697 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15698 "--"
15699 ["Create" org-table-create (and (not (org-at-table-p))
15700 org-enable-table-editor)]
15701 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15702 ["Import from File" org-table-import (not (org-at-table-p))]
15703 ["Export to File" org-table-export (org-at-table-p)]
15704 "--"
15705 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15707 (easy-menu-define org-org-menu org-mode-map "Org menu"
15708 '("Org"
15709 ("Show/Hide"
15710 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15711 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15712 ["Sparse Tree..." org-sparse-tree t]
15713 ["Reveal Context" org-reveal t]
15714 ["Show All" show-all t]
15715 "--"
15716 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15717 "--"
15718 ["New Heading" org-insert-heading t]
15719 ("Navigate Headings"
15720 ["Up" outline-up-heading t]
15721 ["Next" outline-next-visible-heading t]
15722 ["Previous" outline-previous-visible-heading t]
15723 ["Next Same Level" outline-forward-same-level t]
15724 ["Previous Same Level" outline-backward-same-level t]
15725 "--"
15726 ["Jump" org-goto t])
15727 ("Edit Structure"
15728 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15729 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15730 "--"
15731 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15732 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15733 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15734 "--"
15735 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15736 "--"
15737 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15738 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15739 ["Demote Heading" org-metaright (not (org-at-table-p))]
15740 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15741 "--"
15742 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15743 "--"
15744 ["Convert to odd levels" org-convert-to-odd-levels t]
15745 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15746 ("Editing"
15747 ["Emphasis..." org-emphasize t]
15748 ["Edit Source Example" org-edit-special t]
15749 "--"
15750 ["Footnote new/jump" org-footnote-action t]
15751 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15752 ("Archive"
15753 ["Archive (default method)" org-archive-subtree-default t]
15754 "--"
15755 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
15756 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15757 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
15759 "--"
15760 ("Hyperlinks"
15761 ["Store Link (Global)" org-store-link t]
15762 ["Find existing link to here" org-occur-link-in-agenda-files t]
15763 ["Insert Link" org-insert-link t]
15764 ["Follow Link" org-open-at-point t]
15765 "--"
15766 ["Next link" org-next-link t]
15767 ["Previous link" org-previous-link t]
15768 "--"
15769 ["Descriptive Links"
15770 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15771 :style radio
15772 :selected (member '(org-link) buffer-invisibility-spec)]
15773 ["Literal Links"
15774 (progn
15775 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15776 :style radio
15777 :selected (not (member '(org-link) buffer-invisibility-spec))])
15778 "--"
15779 ("TODO Lists"
15780 ["TODO/DONE/-" org-todo t]
15781 ("Select keyword"
15782 ["Next keyword" org-shiftright (org-on-heading-p)]
15783 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15784 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15785 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15786 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15787 ["Show TODO Tree" org-show-todo-tree t]
15788 ["Global TODO list" org-todo-list t]
15789 "--"
15790 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15791 :selected org-enforce-todo-dependencies :style toggle :active t]
15792 "Settings for tree at point"
15793 ["Do Children sequentially" org-toggle-ordered-property :style radio
15794 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15795 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15796 ["Do Children parallel" org-toggle-ordered-property :style radio
15797 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15798 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15799 "--"
15800 ["Set Priority" org-priority t]
15801 ["Priority Up" org-shiftup t]
15802 ["Priority Down" org-shiftdown t]
15803 "--"
15804 ["Get news from all feeds" org-feed-update-all t]
15805 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15806 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15807 ("TAGS and Properties"
15808 ["Set Tags" org-set-tags-command t]
15809 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15810 "--"
15811 ["Set property" org-set-property t]
15812 ["Column view of properties" org-columns t]
15813 ["Insert Column View DBlock" org-insert-columns-dblock t])
15814 ("Dates and Scheduling"
15815 ["Timestamp" org-time-stamp t]
15816 ["Timestamp (inactive)" org-time-stamp-inactive t]
15817 ("Change Date"
15818 ["1 Day Later" org-shiftright t]
15819 ["1 Day Earlier" org-shiftleft t]
15820 ["1 ... Later" org-shiftup t]
15821 ["1 ... Earlier" org-shiftdown t])
15822 ["Compute Time Range" org-evaluate-time-range t]
15823 ["Schedule Item" org-schedule t]
15824 ["Deadline" org-deadline t]
15825 "--"
15826 ["Custom time format" org-toggle-time-stamp-overlays
15827 :style radio :selected org-display-custom-times]
15828 "--"
15829 ["Goto Calendar" org-goto-calendar t]
15830 ["Date from Calendar" org-date-from-calendar t]
15831 "--"
15832 ["Start/Restart Timer" org-timer-start t]
15833 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15834 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15835 ["Insert Timer String" org-timer t]
15836 ["Insert Timer Item" org-timer-item t])
15837 ("Logging work"
15838 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
15839 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
15840 ["Clock out" org-clock-out t]
15841 ["Clock cancel" org-clock-cancel t]
15842 "--"
15843 ["Mark as default task" org-clock-mark-default-task t]
15844 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
15845 ["Goto running clock" org-clock-goto t]
15846 "--"
15847 ["Display times" org-clock-display t]
15848 ["Create clock table" org-clock-report t]
15849 "--"
15850 ["Record DONE time"
15851 (progn (setq org-log-done (not org-log-done))
15852 (message "Switching to %s will %s record a timestamp"
15853 (car org-done-keywords)
15854 (if org-log-done "automatically" "not")))
15855 :style toggle :selected org-log-done])
15856 "--"
15857 ["Agenda Command..." org-agenda t]
15858 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15859 ("File List for Agenda")
15860 ("Special views current file"
15861 ["TODO Tree" org-show-todo-tree t]
15862 ["Check Deadlines" org-check-deadlines t]
15863 ["Timeline" org-timeline t]
15864 ["Tags/Property tree" org-match-sparse-tree t])
15865 "--"
15866 ["Export/Publish..." org-export t]
15867 ("LaTeX"
15868 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15869 :selected org-cdlatex-mode]
15870 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15871 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15872 ["Modify math symbol" org-cdlatex-math-modify
15873 (org-inside-LaTeX-fragment-p)]
15874 ["Insert citation" org-reftex-citation t]
15875 "--"
15876 ["Export LaTeX fragments as images"
15877 (if (featurep 'org-exp)
15878 (setq org-export-with-LaTeX-fragments
15879 (not org-export-with-LaTeX-fragments))
15880 (require 'org-exp))
15881 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15882 org-export-with-LaTeX-fragments)])
15883 "--"
15884 ("MobileOrg"
15885 ["Push Files and Views" org-mobile-push t]
15886 ["Get Captured and Flagged" org-mobile-pull t]
15887 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
15888 "--"
15889 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
15890 "--"
15891 ("Documentation"
15892 ["Show Version" org-version t]
15893 ["Info Documentation" org-info t])
15894 ("Customize"
15895 ["Browse Org Group" org-customize t]
15896 "--"
15897 ["Expand This Menu" org-create-customize-menu
15898 (fboundp 'customize-menu-create)])
15899 ["Send bug report" org-submit-bug-report t]
15900 "--"
15901 ("Refresh/Reload"
15902 ["Refresh setup current buffer" org-mode-restart t]
15903 ["Reload Org (after update)" org-reload t]
15904 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15907 (defun org-info (&optional node)
15908 "Read documentation for Org-mode in the info system.
15909 With optional NODE, go directly to that node."
15910 (interactive)
15911 (info (format "(org)%s" (or node ""))))
15913 ;;;###autoload
15914 (defun org-submit-bug-report ()
15915 "Submit a bug report on Org-mode via mail.
15917 Don't hesitate to report any problems or inaccurate documentation.
15919 If you don't have setup sending mail from (X)Emacs, please copy the
15920 output buffer into your mail program, as it gives us important
15921 information about your Org-mode version and configuration."
15922 (interactive)
15923 (require 'reporter)
15924 (org-load-modules-maybe)
15925 (org-require-autoloaded-modules)
15926 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
15927 (reporter-submit-bug-report
15928 "emacs-orgmode@gnu.org"
15929 (org-version)
15930 (let (list)
15931 (save-window-excursion
15932 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
15933 (delete-other-windows)
15934 (erase-buffer)
15935 (insert "You are about to submit a bug report to the Org-mode mailing list.
15937 We would like to add your full Org-mode and Outline configuration to the
15938 bug report. This greatly simplifies the work of the maintainer and
15939 other experts on the mailing list.
15941 HOWEVER, some variables you have customized may contain private
15942 information. The names of customers, colleagues, or friends, might
15943 appear in the form of file names, tags, todo states, or search strings.
15944 If you answer yes to the prompt, you might want to check and remove
15945 such private information before sending the email.")
15946 (add-text-properties (point-min) (point-max) '(face org-warning))
15947 (when (yes-or-no-p "Include your Org-mode configuration ")
15948 (mapatoms
15949 (lambda (v)
15950 (and (boundp v)
15951 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
15952 (or (and (symbol-value v)
15953 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
15954 (and
15955 (get v 'custom-type) (get v 'standard-value)
15956 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
15957 (push v list)))))
15958 (kill-buffer (get-buffer "*Warn about privacy*"))
15959 list))
15960 nil nil
15961 "Remember to cover the basics, that is, what you expected to happen and
15962 what in fact did happen. You don't know how to make a good report? See
15964 http://orgmode.org/manual/Feedback.html#Feedback
15966 Your bug report will be posted to the Org-mode mailing list.
15967 ------------------------------------------------------------------------")))
15969 (defun org-install-agenda-files-menu ()
15970 (let ((bl (buffer-list)))
15971 (save-excursion
15972 (while bl
15973 (set-buffer (pop bl))
15974 (if (org-mode-p) (setq bl nil)))
15975 (when (org-mode-p)
15976 (easy-menu-change
15977 '("Org") "File List for Agenda"
15978 (append
15979 (list
15980 ["Edit File List" (org-edit-agenda-file-list) t]
15981 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15982 ["Remove Current File from List" org-remove-file t]
15983 ["Cycle through agenda files" org-cycle-agenda-files t]
15984 ["Occur in all agenda files" org-occur-in-agenda-files t]
15985 "--")
15986 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15988 ;;;; Documentation
15990 ;;;###autoload
15991 (defun org-require-autoloaded-modules ()
15992 (interactive)
15993 (mapc 'require
15994 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15995 org-docbook org-exp org-html org-icalendar
15996 org-id org-latex
15997 org-publish org-remember org-table
15998 org-timer org-xoxo)))
16000 ;;;###autoload
16001 (defun org-reload (&optional uncompiled)
16002 "Reload all org lisp files.
16003 With prefix arg UNCOMPILED, load the uncompiled versions."
16004 (interactive "P")
16005 (require 'find-func)
16006 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16007 (dir-org (file-name-directory (org-find-library-name "org")))
16008 (dir-org-contrib (ignore-errors
16009 (file-name-directory
16010 (org-find-library-name "org-contribdir"))))
16011 (files
16012 (append (directory-files dir-org t file-re)
16013 (and dir-org-contrib
16014 (directory-files dir-org-contrib t file-re))))
16015 (remove-re (concat (if (featurep 'xemacs)
16016 "org-colview" "org-colview-xemacs")
16017 "\\'")))
16018 (setq files (mapcar 'file-name-sans-extension files))
16019 (setq files (mapcar
16020 (lambda (x) (if (string-match remove-re x) nil x))
16021 files))
16022 (setq files (delq nil files))
16023 (mapc
16024 (lambda (f)
16025 (when (featurep (intern (file-name-nondirectory f)))
16026 (if (and (not uncompiled)
16027 (file-exists-p (concat f ".elc")))
16028 (load (concat f ".elc") nil nil t)
16029 (load (concat f ".el") nil nil t))))
16030 files))
16031 (org-version))
16033 ;;;###autoload
16034 (defun org-customize ()
16035 "Call the customize function with org as argument."
16036 (interactive)
16037 (org-load-modules-maybe)
16038 (org-require-autoloaded-modules)
16039 (customize-browse 'org))
16041 (defun org-create-customize-menu ()
16042 "Create a full customization menu for Org-mode, insert it into the menu."
16043 (interactive)
16044 (org-load-modules-maybe)
16045 (org-require-autoloaded-modules)
16046 (if (fboundp 'customize-menu-create)
16047 (progn
16048 (easy-menu-change
16049 '("Org") "Customize"
16050 `(["Browse Org group" org-customize t]
16051 "--"
16052 ,(customize-menu-create 'org)
16053 ["Set" Custom-set t]
16054 ["Save" Custom-save t]
16055 ["Reset to Current" Custom-reset-current t]
16056 ["Reset to Saved" Custom-reset-saved t]
16057 ["Reset to Standard Settings" Custom-reset-standard t]))
16058 (message "\"Org\"-menu now contains full customization menu"))
16059 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16061 ;;;; Miscellaneous stuff
16063 ;;; Generally useful functions
16065 (defun org-get-at-bol (property)
16066 "Get text property PROPERTY at beginning of line."
16067 (get-text-property (point-at-bol) property))
16069 (defun org-find-text-property-in-string (prop s)
16070 "Return the first non-nil value of property PROP in string S."
16071 (or (get-text-property 0 prop s)
16072 (get-text-property (or (next-single-property-change 0 prop s) 0)
16073 prop s)))
16075 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16076 "Display the given MESSAGE as a warning."
16077 (if (fboundp 'display-warning)
16078 (display-warning 'org message
16079 (if (featurep 'xemacs)
16080 'warning
16081 :warning))
16082 (let ((buf (get-buffer-create "*Org warnings*")))
16083 (with-current-buffer buf
16084 (goto-char (point-max))
16085 (insert "Warning (Org): " message)
16086 (unless (bolp)
16087 (newline)))
16088 (display-buffer buf)
16089 (sit-for 0))))
16091 (defun org-in-commented-line ()
16092 "Is point in a line starting with `#'?"
16093 (equal (char-after (point-at-bol)) ?#))
16095 (defun org-in-verbatim-emphasis ()
16096 (save-match-data
16097 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16099 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16100 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16101 (if (and marker (marker-buffer marker)
16102 (buffer-live-p (marker-buffer marker)))
16103 (progn
16104 (switch-to-buffer (marker-buffer marker))
16105 (if (or (> marker (point-max)) (< marker (point-min)))
16106 (widen))
16107 (goto-char marker)
16108 (org-show-context 'org-goto))
16109 (if bookmark
16110 (bookmark-jump bookmark)
16111 (error "Cannot find location"))))
16113 (defun org-quote-csv-field (s)
16114 "Quote field for inclusion in CSV material."
16115 (if (string-match "[\",]" s)
16116 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16119 (defun org-plist-delete (plist property)
16120 "Delete PROPERTY from PLIST.
16121 This is in contrast to merely setting it to 0."
16122 (let (p)
16123 (while plist
16124 (if (not (eq property (car plist)))
16125 (setq p (plist-put p (car plist) (nth 1 plist))))
16126 (setq plist (cddr plist)))
16129 (defun org-force-self-insert (N)
16130 "Needed to enforce self-insert under remapping."
16131 (interactive "p")
16132 (self-insert-command N))
16134 (defun org-string-width (s)
16135 "Compute width of string, ignoring invisible characters.
16136 This ignores character with invisibility property `org-link', and also
16137 characters with property `org-cwidth', because these will become invisible
16138 upon the next fontification round."
16139 (let (b l)
16140 (when (or (eq t buffer-invisibility-spec)
16141 (assq 'org-link buffer-invisibility-spec))
16142 (while (setq b (text-property-any 0 (length s)
16143 'invisible 'org-link s))
16144 (setq s (concat (substring s 0 b)
16145 (substring s (or (next-single-property-change
16146 b 'invisible s) (length s)))))))
16147 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16148 (setq s (concat (substring s 0 b)
16149 (substring s (or (next-single-property-change
16150 b 'org-cwidth s) (length s))))))
16151 (setq l (string-width s) b -1)
16152 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16153 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16156 (defun org-get-indentation (&optional line)
16157 "Get the indentation of the current line, interpreting tabs.
16158 When LINE is given, assume it represents a line and compute its indentation."
16159 (if line
16160 (if (string-match "^ *" (org-remove-tabs line))
16161 (match-end 0))
16162 (save-excursion
16163 (beginning-of-line 1)
16164 (skip-chars-forward " \t")
16165 (current-column))))
16167 (defun org-remove-tabs (s &optional width)
16168 "Replace tabulators in S with spaces.
16169 Assumes that s is a single line, starting in column 0."
16170 (setq width (or width tab-width))
16171 (while (string-match "\t" s)
16172 (setq s (replace-match
16173 (make-string
16174 (- (* width (/ (+ (match-beginning 0) width) width))
16175 (match-beginning 0)) ?\ )
16176 t t s)))
16179 (defun org-fix-indentation (line ind)
16180 "Fix indentation in LINE.
16181 IND is a cons cell with target and minimum indentation.
16182 If the current indentation in LINE is smaller than the minimum,
16183 leave it alone. If it is larger than ind, set it to the target."
16184 (let* ((l (org-remove-tabs line))
16185 (i (org-get-indentation l))
16186 (i1 (car ind)) (i2 (cdr ind)))
16187 (if (>= i i2) (setq l (substring line i2)))
16188 (if (> i1 0)
16189 (concat (make-string i1 ?\ ) l)
16190 l)))
16192 (defun org-remove-indentation (code &optional n)
16193 "Remove the maximum common indentation from the lines in CODE.
16194 N may optionally be the number of spaces to remove."
16195 (with-temp-buffer
16196 (insert code)
16197 (org-do-remove-indentation n)
16198 (buffer-string)))
16200 (defun org-do-remove-indentation (&optional n)
16201 "Remove the maximum common indentation from the buffer."
16202 (untabify (point-min) (point-max))
16203 (let ((min 10000) re)
16204 (if n
16205 (setq min n)
16206 (goto-char (point-min))
16207 (while (re-search-forward "^ *[^ \n]" nil t)
16208 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16209 (unless (or (= min 0) (= min 10000))
16210 (setq re (format "^ \\{%d\\}" min))
16211 (goto-char (point-min))
16212 (while (re-search-forward re nil t)
16213 (replace-match "")
16214 (end-of-line 1))
16215 min)))
16217 (defun org-fill-template (template alist)
16218 "Find each %key of ALIST in TEMPLATE and replace it."
16219 (let (entry key value)
16220 (setq alist (sort (copy-sequence alist)
16221 (lambda (a b) (< (length (car a)) (length (car b))))))
16222 (while (setq entry (pop alist))
16223 (setq template
16224 (replace-regexp-in-string
16225 (concat "%" (regexp-quote (car entry)))
16226 (cdr entry) template t t)))
16227 template))
16229 (defun org-base-buffer (buffer)
16230 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16231 (if (not buffer)
16232 buffer
16233 (or (buffer-base-buffer buffer)
16234 buffer)))
16236 (defun org-trim (s)
16237 "Remove whitespace at beginning and end of string."
16238 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
16239 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
16242 (defun org-wrap (string &optional width lines)
16243 "Wrap string to either a number of lines, or a width in characters.
16244 If WIDTH is non-nil, the string is wrapped to that width, however many lines
16245 that costs. If there is a word longer than WIDTH, the text is actually
16246 wrapped to the length of that word.
16247 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
16248 many lines, whatever width that takes.
16249 The return value is a list of lines, without newlines at the end."
16250 (let* ((words (org-split-string string "[ \t\n]+"))
16251 (maxword (apply 'max (mapcar 'org-string-width words)))
16252 w ll)
16253 (cond (width
16254 (org-do-wrap words (max maxword width)))
16255 (lines
16256 (setq w maxword)
16257 (setq ll (org-do-wrap words maxword))
16258 (if (<= (length ll) lines)
16260 (setq ll words)
16261 (while (> (length ll) lines)
16262 (setq w (1+ w))
16263 (setq ll (org-do-wrap words w)))
16264 ll))
16265 (t (error "Cannot wrap this")))))
16267 (defun org-do-wrap (words width)
16268 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
16269 (let (lines line)
16270 (while words
16271 (setq line (pop words))
16272 (while (and words (< (+ (length line) (length (car words))) width))
16273 (setq line (concat line " " (pop words))))
16274 (setq lines (push line lines)))
16275 (nreverse lines)))
16277 (defun org-split-string (string &optional separators)
16278 "Splits STRING into substrings at SEPARATORS.
16279 No empty strings are returned if there are matches at the beginning
16280 and end of string."
16281 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
16282 (start 0)
16283 notfirst
16284 (list nil))
16285 (while (and (string-match rexp string
16286 (if (and notfirst
16287 (= start (match-beginning 0))
16288 (< start (length string)))
16289 (1+ start) start))
16290 (< (match-beginning 0) (length string)))
16291 (setq notfirst t)
16292 (or (eq (match-beginning 0) 0)
16293 (and (eq (match-beginning 0) (match-end 0))
16294 (eq (match-beginning 0) start))
16295 (setq list
16296 (cons (substring string start (match-beginning 0))
16297 list)))
16298 (setq start (match-end 0)))
16299 (or (eq start (length string))
16300 (setq list
16301 (cons (substring string start)
16302 list)))
16303 (nreverse list)))
16305 (defun org-quote-vert (s)
16306 "Replace \"|\" with \"\\vert\"."
16307 (while (string-match "|" s)
16308 (setq s (replace-match "\\vert" t t s)))
16311 (defun org-uuidgen-p (s)
16312 "Is S an ID created by UUIDGEN?"
16313 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16315 (defun org-context ()
16316 "Return a list of contexts of the current cursor position.
16317 If several contexts apply, all are returned.
16318 Each context entry is a list with a symbol naming the context, and
16319 two positions indicating start and end of the context. Possible
16320 contexts are:
16322 :headline anywhere in a headline
16323 :headline-stars on the leading stars in a headline
16324 :todo-keyword on a TODO keyword (including DONE) in a headline
16325 :tags on the TAGS in a headline
16326 :priority on the priority cookie in a headline
16327 :item on the first line of a plain list item
16328 :item-bullet on the bullet/number of a plain list item
16329 :checkbox on the checkbox in a plain list item
16330 :table in an org-mode table
16331 :table-special on a special filed in a table
16332 :table-table in a table.el table
16333 :link on a hyperlink
16334 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16335 :target on a <<target>>
16336 :radio-target on a <<<radio-target>>>
16337 :latex-fragment on a LaTeX fragment
16338 :latex-preview on a LaTeX fragment with overlayed preview image
16340 This function expects the position to be visible because it uses font-lock
16341 faces as a help to recognize the following contexts: :table-special, :link,
16342 and :keyword."
16343 (let* ((f (get-text-property (point) 'face))
16344 (faces (if (listp f) f (list f)))
16345 (p (point)) clist o)
16346 ;; First the large context
16347 (cond
16348 ((org-on-heading-p t)
16349 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16350 (when (progn
16351 (beginning-of-line 1)
16352 (looking-at org-todo-line-tags-regexp))
16353 (push (org-point-in-group p 1 :headline-stars) clist)
16354 (push (org-point-in-group p 2 :todo-keyword) clist)
16355 (push (org-point-in-group p 4 :tags) clist))
16356 (goto-char p)
16357 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
16358 (if (looking-at "\\[#[A-Z0-9]\\]")
16359 (push (org-point-in-group p 0 :priority) clist)))
16361 ((org-at-item-p)
16362 (push (org-point-in-group p 2 :item-bullet) clist)
16363 (push (list :item (point-at-bol)
16364 (save-excursion (org-end-of-item) (point)))
16365 clist)
16366 (and (org-at-item-checkbox-p)
16367 (push (org-point-in-group p 0 :checkbox) clist)))
16369 ((org-at-table-p)
16370 (push (list :table (org-table-begin) (org-table-end)) clist)
16371 (if (memq 'org-formula faces)
16372 (push (list :table-special
16373 (previous-single-property-change p 'face)
16374 (next-single-property-change p 'face)) clist)))
16375 ((org-at-table-p 'any)
16376 (push (list :table-table) clist)))
16377 (goto-char p)
16379 ;; Now the small context
16380 (cond
16381 ((org-at-timestamp-p)
16382 (push (org-point-in-group p 0 :timestamp) clist))
16383 ((memq 'org-link faces)
16384 (push (list :link
16385 (previous-single-property-change p 'face)
16386 (next-single-property-change p 'face)) clist))
16387 ((memq 'org-special-keyword faces)
16388 (push (list :keyword
16389 (previous-single-property-change p 'face)
16390 (next-single-property-change p 'face)) clist))
16391 ((org-on-target-p)
16392 (push (org-point-in-group p 0 :target) clist)
16393 (goto-char (1- (match-beginning 0)))
16394 (if (looking-at org-radio-target-regexp)
16395 (push (org-point-in-group p 0 :radio-target) clist))
16396 (goto-char p))
16397 ((setq o (car (delq nil
16398 (mapcar
16399 (lambda (x)
16400 (if (memq x org-latex-fragment-image-overlays) x))
16401 (org-overlays-at (point))))))
16402 (push (list :latex-fragment
16403 (org-overlay-start o) (org-overlay-end o)) clist)
16404 (push (list :latex-preview
16405 (org-overlay-start o) (org-overlay-end o)) clist))
16406 ((org-inside-LaTeX-fragment-p)
16407 ;; FIXME: positions wrong.
16408 (push (list :latex-fragment (point) (point)) clist)))
16410 (setq clist (nreverse (delq nil clist)))
16411 clist))
16413 ;; FIXME: Compare with at-regexp-p Do we need both?
16414 (defun org-in-regexp (re &optional nlines visually)
16415 "Check if point is inside a match of regexp.
16416 Normally only the current line is checked, but you can include NLINES extra
16417 lines both before and after point into the search.
16418 If VISUALLY is set, require that the cursor is not after the match but
16419 really on, so that the block visually is on the match."
16420 (catch 'exit
16421 (let ((pos (point))
16422 (eol (point-at-eol (+ 1 (or nlines 0))))
16423 (inc (if visually 1 0)))
16424 (save-excursion
16425 (beginning-of-line (- 1 (or nlines 0)))
16426 (while (re-search-forward re eol t)
16427 (if (and (<= (match-beginning 0) pos)
16428 (>= (+ inc (match-end 0)) pos))
16429 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16431 (defun org-at-regexp-p (regexp)
16432 "Is point inside a match of REGEXP in the current line?"
16433 (catch 'exit
16434 (save-excursion
16435 (let ((pos (point)) (end (point-at-eol)))
16436 (beginning-of-line 1)
16437 (while (re-search-forward regexp end t)
16438 (if (and (<= (match-beginning 0) pos)
16439 (>= (match-end 0) pos))
16440 (throw 'exit t)))
16441 nil))))
16443 (defun org-occur-in-agenda-files (regexp &optional nlines)
16444 "Call `multi-occur' with buffers for all agenda files."
16445 (interactive "sOrg-files matching: \np")
16446 (let* ((files (org-agenda-files))
16447 (tnames (mapcar 'file-truename files))
16448 (extra org-agenda-text-search-extra-files)
16450 (when (eq (car extra) 'agenda-archives)
16451 (setq extra (cdr extra))
16452 (setq files (org-add-archive-files files)))
16453 (while (setq f (pop extra))
16454 (unless (member (file-truename f) tnames)
16455 (add-to-list 'files f 'append)
16456 (add-to-list 'tnames (file-truename f) 'append)))
16457 (multi-occur
16458 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
16459 regexp)))
16461 (if (boundp 'occur-mode-find-occurrence-hook)
16462 ;; Emacs 23
16463 (add-hook 'occur-mode-find-occurrence-hook
16464 (lambda ()
16465 (when (org-mode-p)
16466 (org-reveal))))
16467 ;; Emacs 22
16468 (defadvice occur-mode-goto-occurrence
16469 (after org-occur-reveal activate)
16470 (and (org-mode-p) (org-reveal)))
16471 (defadvice occur-mode-goto-occurrence-other-window
16472 (after org-occur-reveal activate)
16473 (and (org-mode-p) (org-reveal)))
16474 (defadvice occur-mode-display-occurrence
16475 (after org-occur-reveal activate)
16476 (when (org-mode-p)
16477 (let ((pos (occur-mode-find-occurrence)))
16478 (with-current-buffer (marker-buffer pos)
16479 (save-excursion
16480 (goto-char pos)
16481 (org-reveal)))))))
16483 (defun org-occur-link-in-agenda-files ()
16484 "Create a link and search for it in the agendas.
16485 The link is not stored in `org-stored-links', it is just created
16486 for the search purpose."
16487 (interactive)
16488 (let ((link (condition-case nil
16489 (org-store-link nil)
16490 (error "Unable to create a link to here"))))
16491 (org-occur-in-agenda-files (regexp-quote link))))
16493 (defun org-uniquify (list)
16494 "Remove duplicate elements from LIST."
16495 (let (res)
16496 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16497 res))
16499 (defun org-delete-all (elts list)
16500 "Remove all elements in ELTS from LIST."
16501 (while elts
16502 (setq list (delete (pop elts) list)))
16503 list)
16505 (defun org-back-over-empty-lines ()
16506 "Move backwards over whitespace, to the beginning of the first empty line.
16507 Returns the number of empty lines passed."
16508 (let ((pos (point)))
16509 (skip-chars-backward " \t\n\r")
16510 (beginning-of-line 2)
16511 (goto-char (min (point) pos))
16512 (count-lines (point) pos)))
16514 (defun org-skip-whitespace ()
16515 (skip-chars-forward " \t\n\r"))
16517 (defun org-point-in-group (point group &optional context)
16518 "Check if POINT is in match-group GROUP.
16519 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16520 match. If the match group does ot exist or point is not inside it,
16521 return nil."
16522 (and (match-beginning group)
16523 (>= point (match-beginning group))
16524 (<= point (match-end group))
16525 (if context
16526 (list context (match-beginning group) (match-end group))
16527 t)))
16529 (defun org-switch-to-buffer-other-window (&rest args)
16530 "Switch to buffer in a second window on the current frame.
16531 In particular, do not allow pop-up frames."
16532 (let (pop-up-frames special-display-buffer-names special-display-regexps
16533 special-display-function)
16534 (apply 'switch-to-buffer-other-window args)))
16536 (defun org-combine-plists (&rest plists)
16537 "Create a single property list from all plists in PLISTS.
16538 The process starts by copying the first list, and then setting properties
16539 from the other lists. Settings in the last list are the most significant
16540 ones and overrule settings in the other lists."
16541 (let ((rtn (copy-sequence (pop plists)))
16542 p v ls)
16543 (while plists
16544 (setq ls (pop plists))
16545 (while ls
16546 (setq p (pop ls) v (pop ls))
16547 (setq rtn (plist-put rtn p v))))
16548 rtn))
16550 (defun org-move-line-down (arg)
16551 "Move the current line down. With prefix argument, move it past ARG lines."
16552 (interactive "p")
16553 (let ((col (current-column))
16554 beg end pos)
16555 (beginning-of-line 1) (setq beg (point))
16556 (beginning-of-line 2) (setq end (point))
16557 (beginning-of-line (+ 1 arg))
16558 (setq pos (move-marker (make-marker) (point)))
16559 (insert (delete-and-extract-region beg end))
16560 (goto-char pos)
16561 (org-move-to-column col)))
16563 (defun org-move-line-up (arg)
16564 "Move the current line up. With prefix argument, move it past ARG lines."
16565 (interactive "p")
16566 (let ((col (current-column))
16567 beg end pos)
16568 (beginning-of-line 1) (setq beg (point))
16569 (beginning-of-line 2) (setq end (point))
16570 (beginning-of-line (- arg))
16571 (setq pos (move-marker (make-marker) (point)))
16572 (insert (delete-and-extract-region beg end))
16573 (goto-char pos)
16574 (org-move-to-column col)))
16576 (defun org-replace-escapes (string table)
16577 "Replace %-escapes in STRING with values in TABLE.
16578 TABLE is an association list with keys like \"%a\" and string values.
16579 The sequences in STRING may contain normal field width and padding information,
16580 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
16581 so values can contain further %-escapes if they are define later in TABLE."
16582 (let ((case-fold-search nil)
16583 e re rpl)
16584 (while (setq e (pop table))
16585 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
16586 (while (string-match re string)
16587 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
16588 (cdr e)))
16589 (setq string (replace-match rpl t t string))))
16590 string))
16593 (defun org-sublist (list start end)
16594 "Return a section of LIST, from START to END.
16595 Counting starts at 1."
16596 (let (rtn (c start))
16597 (setq list (nthcdr (1- start) list))
16598 (while (and list (<= c end))
16599 (push (pop list) rtn)
16600 (setq c (1+ c)))
16601 (nreverse rtn)))
16603 (defun org-find-base-buffer-visiting (file)
16604 "Like `find-buffer-visiting' but always return the base buffer and
16605 not an indirect buffer."
16606 (let ((buf (or (get-file-buffer file)
16607 (find-buffer-visiting file))))
16608 (if buf
16609 (or (buffer-base-buffer buf) buf)
16610 nil)))
16612 (defun org-image-file-name-regexp (&optional extensions)
16613 "Return regexp matching the file names of images.
16614 If EXTENSIONS is given, only match these."
16615 (if (and (not extensions) (fboundp 'image-file-name-regexp))
16616 (image-file-name-regexp)
16617 (let ((image-file-name-extensions
16618 (or extensions
16619 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16620 "xbm" "xpm" "pbm" "pgm" "ppm"))))
16621 (concat "\\."
16622 (regexp-opt (nconc (mapcar 'upcase
16623 image-file-name-extensions)
16624 image-file-name-extensions)
16626 "\\'"))))
16628 (defun org-file-image-p (file &optional extensions)
16629 "Return non-nil if FILE is an image."
16630 (save-match-data
16631 (string-match (org-image-file-name-regexp extensions) file)))
16633 (defun org-get-cursor-date ()
16634 "Return the date at cursor in as a time.
16635 This works in the calendar and in the agenda, anywhere else it just
16636 returns the current time."
16637 (let (date day defd)
16638 (cond
16639 ((eq major-mode 'calendar-mode)
16640 (setq date (calendar-cursor-to-date)
16641 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16642 ((eq major-mode 'org-agenda-mode)
16643 (setq day (get-text-property (point) 'day))
16644 (if day
16645 (setq date (calendar-gregorian-from-absolute day)
16646 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
16647 (nth 2 date))))))
16648 (or defd (current-time))))
16650 (defvar org-agenda-action-marker (make-marker)
16651 "Marker pointing to the entry for the next agenda action.")
16653 (defun org-mark-entry-for-agenda-action ()
16654 "Mark the current entry as target of an agenda action.
16655 Agenda actions are actions executed from the agenda with the key `k',
16656 which make use of the date at the cursor."
16657 (interactive)
16658 (move-marker org-agenda-action-marker
16659 (save-excursion (org-back-to-heading t) (point))
16660 (current-buffer))
16661 (message
16662 "Entry marked for action; press `k' at desired date in agenda or calendar"))
16664 ;;; Paragraph filling stuff.
16665 ;; We want this to be just right, so use the full arsenal.
16667 (defun org-indent-line-function ()
16668 "Indent line like previous, but further if previous was headline or item."
16669 (interactive)
16670 (let* ((pos (point))
16671 (itemp (org-at-item-p))
16672 (case-fold-search t)
16673 (org-drawer-regexp (or org-drawer-regexp "\000"))
16674 column bpos bcol tpos tcol bullet btype bullet-type)
16675 ;; Find the previous relevant line
16676 (beginning-of-line 1)
16677 (cond
16678 ((looking-at "#") (setq column 0))
16679 ((looking-at "\\*+ ") (setq column 0))
16680 ((and (looking-at "[ \t]*:END:")
16681 (save-excursion (re-search-backward org-drawer-regexp nil t)))
16682 (save-excursion
16683 (goto-char (1- (match-beginning 1)))
16684 (setq column (current-column))))
16685 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
16686 (save-excursion
16687 (re-search-backward
16688 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
16689 (setq column (org-get-indentation (match-string 0))))
16691 (beginning-of-line 0)
16692 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
16693 (not (looking-at "[ \t]*:END:"))
16694 (not (looking-at org-drawer-regexp)))
16695 (beginning-of-line 0))
16696 (cond
16697 ((looking-at "\\*+[ \t]+")
16698 (if (not org-adapt-indentation)
16699 (setq column 0)
16700 (goto-char (match-end 0))
16701 (setq column (current-column))))
16702 ((looking-at org-drawer-regexp)
16703 (goto-char (1- (match-beginning 1)))
16704 (setq column (current-column)))
16705 ((looking-at "\\([ \t]*\\):END:")
16706 (goto-char (match-end 1))
16707 (setq column (current-column)))
16708 ((org-in-item-p)
16709 (org-beginning-of-item)
16710 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
16711 (setq bpos (match-beginning 1) tpos (match-end 0)
16712 bcol (progn (goto-char bpos) (current-column))
16713 tcol (progn (goto-char tpos) (current-column))
16714 bullet (match-string 1)
16715 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
16716 (if (> tcol (+ bcol org-description-max-indent))
16717 (setq tcol (+ bcol 5)))
16718 (if (not itemp)
16719 (setq column tcol)
16720 (goto-char pos)
16721 (beginning-of-line 1)
16722 (if (looking-at "\\S-")
16723 (progn
16724 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
16725 (setq bullet (match-string 1)
16726 btype (if (string-match "[0-9]" bullet) "n" bullet))
16727 (setq column (if (equal btype bullet-type) bcol tcol)))
16728 (setq column (org-get-indentation)))))
16729 (t (setq column (org-get-indentation))))))
16730 (goto-char pos)
16731 (if (<= (current-column) (current-indentation))
16732 (org-indent-line-to column)
16733 (save-excursion (org-indent-line-to column)))
16734 (setq column (current-column))
16735 (beginning-of-line 1)
16736 (if (looking-at
16737 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16738 (replace-match (concat (match-string 1)
16739 (format org-property-format
16740 (match-string 2) (match-string 3)))
16741 t t))
16742 (org-move-to-column column)))
16744 (defun org-set-autofill-regexps ()
16745 (interactive)
16746 ;; In the paragraph separator we include headlines, because filling
16747 ;; text in a line directly attached to a headline would otherwise
16748 ;; fill the headline as well.
16749 (org-set-local 'comment-start-skip "^#+[ \t]*")
16750 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
16751 ;; The paragraph starter includes hand-formatted lists.
16752 (org-set-local
16753 'paragraph-start
16754 (concat
16755 "\f" "\\|"
16756 "[ ]*$" "\\|"
16757 "\\*+ " "\\|"
16758 "[ \t]*#" "\\|"
16759 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16760 "[ \t]*[:|]" "\\|"
16761 "\\$\\$" "\\|"
16762 "\\\\\\(begin\\|end\\|[][]\\)"))
16763 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16764 ;; But only if the user has not turned off tables or fixed-width regions
16765 (org-set-local
16766 'auto-fill-inhibit-regexp
16767 (concat "\\*+ \\|#\\+"
16768 "\\|[ \t]*" org-keyword-time-regexp
16769 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16770 (concat
16771 "\\|[ \t]*["
16772 (if org-enable-table-editor "|" "")
16773 (if org-enable-fixed-width-editor ":" "")
16774 "]"))))
16775 ;; We use our own fill-paragraph function, to make sure that tables
16776 ;; and fixed-width regions are not wrapped. That function will pass
16777 ;; through to `fill-paragraph' when appropriate.
16778 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16779 ; Adaptive filling: To get full control, first make sure that
16780 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16781 (org-set-local 'adaptive-fill-regexp "\000")
16782 (org-set-local 'adaptive-fill-function
16783 'org-adaptive-fill-function)
16784 (org-set-local
16785 'align-mode-rules-list
16786 '((org-in-buffer-settings
16787 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
16788 (modes . '(org-mode))))))
16790 (defun org-fill-paragraph (&optional justify)
16791 "Re-align a table, pass through to fill-paragraph if no table."
16792 (let ((table-p (org-at-table-p))
16793 (table.el-p (org-at-table.el-p)))
16794 (cond ((and (equal (char-after (point-at-bol)) ?*)
16795 (save-excursion (goto-char (point-at-bol))
16796 (looking-at outline-regexp)))
16797 t) ; skip headlines
16798 (table.el-p t) ; skip table.el tables
16799 (table-p (org-table-align) t) ; align org-mode tables
16800 (t nil)))) ; call paragraph-fill
16802 ;; For reference, this is the default value of adaptive-fill-regexp
16803 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16805 (defun org-adaptive-fill-function ()
16806 "Return a fill prefix for org-mode files.
16807 In particular, this makes sure hanging paragraphs for hand-formatted lists
16808 work correctly."
16809 (cond ((looking-at "#[ \t]+")
16810 (match-string 0))
16811 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
16812 (save-excursion
16813 (if (> (match-end 1) (+ (match-beginning 1)
16814 org-description-max-indent))
16815 (goto-char (+ (match-beginning 1) 5))
16816 (goto-char (match-end 0)))
16817 (make-string (current-column) ?\ )))
16818 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
16819 (save-excursion
16820 (goto-char (match-end 0))
16821 (make-string (current-column) ?\ )))
16822 (t nil)))
16824 ;;; Other stuff.
16826 (defun org-toggle-fixed-width-section (arg)
16827 "Toggle the fixed-width export.
16828 If there is no active region, the QUOTE keyword at the current headline is
16829 inserted or removed. When present, it causes the text between this headline
16830 and the next to be exported as fixed-width text, and unmodified.
16831 If there is an active region, this command adds or removes a colon as the
16832 first character of this line. If the first character of a line is a colon,
16833 this line is also exported in fixed-width font."
16834 (interactive "P")
16835 (let* ((cc 0)
16836 (regionp (org-region-active-p))
16837 (beg (if regionp (region-beginning) (point)))
16838 (end (if regionp (region-end)))
16839 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
16840 (case-fold-search nil)
16841 (re "[ \t]*\\(: \\)")
16842 off)
16843 (if regionp
16844 (save-excursion
16845 (goto-char beg)
16846 (setq cc (current-column))
16847 (beginning-of-line 1)
16848 (setq off (looking-at re))
16849 (while (> nlines 0)
16850 (setq nlines (1- nlines))
16851 (beginning-of-line 1)
16852 (cond
16853 (arg
16854 (org-move-to-column cc t)
16855 (insert ": \n")
16856 (forward-line -1))
16857 ((and off (looking-at re))
16858 (replace-match "" t t nil 1))
16859 ((not off) (org-move-to-column cc t) (insert ": ")))
16860 (forward-line 1)))
16861 (save-excursion
16862 (org-back-to-heading)
16863 (if (looking-at (concat outline-regexp
16864 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
16865 (replace-match "" t t nil 1)
16866 (if (looking-at outline-regexp)
16867 (progn
16868 (goto-char (match-end 0))
16869 (insert org-quote-string " "))))))))
16871 (defun org-reftex-citation ()
16872 "Use reftex-citation to insert a citation into the buffer.
16873 This looks for a line like
16875 #+BIBLIOGRAPHY: foo plain option:-d
16877 and derives from it that foo.bib is the bbliography file relevant
16878 for this document. It then installs the necessary environment for RefTeX
16879 to work in this buffer and calls `reftex-citation' to insert a citation
16880 into the buffer.
16882 Export of such citations to both LaTeX and HTML is handled by the contributed
16883 package org-exp-bibtex by Taru Karttunen."
16884 (interactive)
16885 (let ((reftex-docstruct-symbol 'rds)
16886 (reftex-cite-format "\\cite{%l}")
16887 rds bib)
16888 (save-excursion
16889 (save-restriction
16890 (widen)
16891 (let ((case-fold-search t)
16892 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
16893 (if (not (save-excursion
16894 (or (re-search-forward re nil t)
16895 (re-search-backward re nil t))))
16896 (error "No bibliography defined in file")
16897 (setq bib (concat (match-string 1) ".bib")
16898 rds (list (list 'bib bib)))))))
16899 (call-interactively 'reftex-citation)))
16901 ;;;; Functions extending outline functionality
16903 (defun org-beginning-of-line (&optional arg)
16904 "Go to the beginning of the current line. If that is invisible, continue
16905 to a visible line beginning. This makes the function of C-a more intuitive.
16906 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16907 first attempt, and only move to after the tags when the cursor is already
16908 beyond the end of the headline."
16909 (interactive "P")
16910 (let ((pos (point))
16911 (special (if (consp org-special-ctrl-a/e)
16912 (car org-special-ctrl-a/e)
16913 org-special-ctrl-a/e))
16914 refpos)
16915 (if (org-bound-and-true-p line-move-visual)
16916 (beginning-of-visual-line 1)
16917 (beginning-of-line 1))
16918 (if (and arg (fboundp 'move-beginning-of-line))
16919 (call-interactively 'move-beginning-of-line)
16920 (if (bobp)
16922 (backward-char 1)
16923 (if (org-invisible-p)
16924 (while (and (not (bobp)) (org-invisible-p))
16925 (backward-char 1)
16926 (beginning-of-line 1))
16927 (forward-char 1))))
16928 (when special
16929 (cond
16930 ((and (looking-at org-complex-heading-regexp)
16931 (= (char-after (match-end 1)) ?\ ))
16932 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
16933 (point-at-eol)))
16934 (goto-char
16935 (if (eq special t)
16936 (cond ((> pos refpos) refpos)
16937 ((= pos (point)) refpos)
16938 (t (point)))
16939 (cond ((> pos (point)) (point))
16940 ((not (eq last-command this-command)) (point))
16941 (t refpos)))))
16942 ((org-at-item-p)
16943 (goto-char
16944 (if (eq special t)
16945 (cond ((> pos (match-end 4)) (match-end 4))
16946 ((= pos (point)) (match-end 4))
16947 (t (point)))
16948 (cond ((> pos (point)) (point))
16949 ((not (eq last-command this-command)) (point))
16950 (t (match-end 4))))))))
16951 (org-no-warnings
16952 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16954 (defun org-end-of-line (&optional arg)
16955 "Go to the end of the line.
16956 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16957 first attempt, and only move to after the tags when the cursor is already
16958 beyond the end of the headline."
16959 (interactive "P")
16960 (let ((special (if (consp org-special-ctrl-a/e)
16961 (cdr org-special-ctrl-a/e)
16962 org-special-ctrl-a/e)))
16963 (if (or (not special)
16964 (not (org-on-heading-p))
16965 arg)
16966 (call-interactively
16967 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
16968 ((fboundp 'move-end-of-line) 'move-end-of-line)
16969 (t 'end-of-line)))
16970 (let ((pos (point)))
16971 (beginning-of-line 1)
16972 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
16973 (if (eq special t)
16974 (if (or (< pos (match-beginning 1))
16975 (= pos (match-end 0)))
16976 (goto-char (match-beginning 1))
16977 (goto-char (match-end 0)))
16978 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16979 (goto-char (match-end 0))
16980 (goto-char (match-beginning 1))))
16981 (call-interactively (if (fboundp 'move-end-of-line)
16982 'move-end-of-line
16983 'end-of-line)))))
16984 (org-no-warnings
16985 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16987 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16988 (define-key org-mode-map "\C-e" 'org-end-of-line)
16989 (define-key org-mode-map [home] 'org-beginning-of-line)
16990 (define-key org-mode-map [end] 'org-end-of-line)
16992 (defun org-backward-sentence (&optional arg)
16993 "Go to beginning of sentence, or beginning of table field.
16994 This will call `backward-sentence' or `org-table-beginning-of-field',
16995 depending on context."
16996 (interactive "P")
16997 (cond
16998 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16999 (t (call-interactively 'backward-sentence))))
17001 (defun org-forward-sentence (&optional arg)
17002 "Go to end of sentence, or end of table field.
17003 This will call `forward-sentence' or `org-table-end-of-field',
17004 depending on context."
17005 (interactive "P")
17006 (cond
17007 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17008 (t (call-interactively 'forward-sentence))))
17010 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17011 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17013 (defun org-kill-line (&optional arg)
17014 "Kill line, to tags or end of line."
17015 (interactive "P")
17016 (cond
17017 ((or (not org-special-ctrl-k)
17018 (bolp)
17019 (not (org-on-heading-p)))
17020 (call-interactively 'kill-line))
17021 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17022 (kill-region (point) (match-beginning 1))
17023 (org-set-tags nil t))
17024 (t (kill-region (point) (point-at-eol)))))
17026 (define-key org-mode-map "\C-k" 'org-kill-line)
17028 (defun org-yank (&optional arg)
17029 "Yank. If the kill is a subtree, treat it specially.
17030 This command will look at the current kill and check if is a single
17031 subtree, or a series of subtrees[1]. If it passes the test, and if the
17032 cursor is at the beginning of a line or after the stars of a currently
17033 empty headline, then the yank is handled specially. How exactly depends
17034 on the value of the following variables, both set by default.
17036 org-yank-folded-subtrees
17037 When set, the subtree(s) will be folded after insertion, but only
17038 if doing so would now swallow text after the yanked text.
17040 org-yank-adjusted-subtrees
17041 When set, the subtree will be promoted or demoted in order to
17042 fit into the local outline tree structure, which means that the level
17043 will be adjusted so that it becomes the smaller one of the two
17044 *visible* surrounding headings.
17046 Any prefix to this command will cause `yank' to be called directly with
17047 no special treatment. In particular, a simple `C-u' prefix will just
17048 plainly yank the text as it is.
17050 \[1] The test checks if the first non-white line is a heading
17051 and if there are no other headings with fewer stars."
17052 (interactive "P")
17053 (org-yank-generic 'yank arg))
17055 (defun org-yank-generic (command arg)
17056 "Perform some yank-like command.
17058 This function implements the behavior described in the `org-yank'
17059 documentation. However, it has been generalized to work for any
17060 interactive command with similar behavior."
17062 ;; pretend to be command COMMAND
17063 (setq this-command command)
17065 (if arg
17066 (call-interactively command)
17068 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17069 (and (org-kill-is-subtree-p)
17070 (or (bolp)
17071 (and (looking-at "[ \t]*$")
17072 (string-match
17073 "\\`\\*+\\'"
17074 (buffer-substring (point-at-bol) (point)))))))
17075 swallowp)
17076 (cond
17077 ((and subtreep org-yank-folded-subtrees)
17078 (let ((beg (point))
17079 end)
17080 (if (and subtreep org-yank-adjusted-subtrees)
17081 (org-paste-subtree nil nil 'for-yank)
17082 (call-interactively command))
17084 (setq end (point))
17085 (goto-char beg)
17086 (when (and (bolp) subtreep
17087 (not (setq swallowp
17088 (org-yank-folding-would-swallow-text beg end))))
17089 (or (looking-at outline-regexp)
17090 (re-search-forward (concat "^" outline-regexp) end t))
17091 (while (and (< (point) end) (looking-at outline-regexp))
17092 (hide-subtree)
17093 (org-cycle-show-empty-lines 'folded)
17094 (condition-case nil
17095 (outline-forward-same-level 1)
17096 (error (goto-char end)))))
17097 (when swallowp
17098 (message
17099 "Inserted text not folded because that would swallow text"))
17101 (goto-char end)
17102 (skip-chars-forward " \t\n\r")
17103 (beginning-of-line 1)
17104 (push-mark beg 'nomsg)))
17105 ((and subtreep org-yank-adjusted-subtrees)
17106 (let ((beg (point-at-bol)))
17107 (org-paste-subtree nil nil 'for-yank)
17108 (push-mark beg 'nomsg)))
17110 (call-interactively command))))))
17112 (defun org-yank-folding-would-swallow-text (beg end)
17113 "Would hide-subtree at BEG swallow any text after END?"
17114 (let (level)
17115 (save-excursion
17116 (goto-char beg)
17117 (when (or (looking-at outline-regexp)
17118 (re-search-forward (concat "^" outline-regexp) end t))
17119 (setq level (org-outline-level)))
17120 (goto-char end)
17121 (skip-chars-forward " \t\r\n\v\f")
17122 (if (or (eobp)
17123 (and (bolp) (looking-at org-outline-regexp)
17124 (<= (org-outline-level) level)))
17125 nil ; Nothing would be swallowed
17126 t)))) ; something would swallow
17128 (define-key org-mode-map "\C-y" 'org-yank)
17130 (defun org-invisible-p ()
17131 "Check if point is at a character currently not visible."
17132 ;; Early versions of noutline don't have `outline-invisible-p'.
17133 (if (fboundp 'outline-invisible-p)
17134 (outline-invisible-p)
17135 (get-char-property (point) 'invisible)))
17137 (defun org-invisible-p2 ()
17138 "Check if point is at a character currently not visible."
17139 (save-excursion
17140 (if (and (eolp) (not (bobp))) (backward-char 1))
17141 ;; Early versions of noutline don't have `outline-invisible-p'.
17142 (if (fboundp 'outline-invisible-p)
17143 (outline-invisible-p)
17144 (get-char-property (point) 'invisible))))
17146 (defun org-back-to-heading (&optional invisible-ok)
17147 "Call `outline-back-to-heading', but provide a better error message."
17148 (condition-case nil
17149 (outline-back-to-heading invisible-ok)
17150 (error (error "Before first headline at position %d in buffer %s"
17151 (point) (current-buffer)))))
17153 (defun org-before-first-heading-p ()
17154 "Before first heading?"
17155 (save-excursion
17156 (null (re-search-backward "^\\*+ " nil t))))
17158 (defun org-on-heading-p (&optional ignored)
17159 (outline-on-heading-p t))
17160 (defun org-at-heading-p (&optional ignored)
17161 (outline-on-heading-p t))
17163 (defun org-at-heading-or-item-p ()
17164 (or (org-on-heading-p) (org-at-item-p)))
17166 (defun org-on-target-p ()
17167 (or (org-in-regexp org-radio-target-regexp)
17168 (org-in-regexp org-target-regexp)))
17170 (defun org-up-heading-all (arg)
17171 "Move to the heading line of which the present line is a subheading.
17172 This function considers both visible and invisible heading lines.
17173 With argument, move up ARG levels."
17174 (if (fboundp 'outline-up-heading-all)
17175 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17176 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17178 (defun org-up-heading-safe ()
17179 "Move to the heading line of which the present line is a subheading.
17180 This version will not throw an error. It will return the level of the
17181 headline found, or nil if no higher level is found.
17183 Also, this function will be a lot faster than `outline-up-heading',
17184 because it relies on stars being the outline starters. This can really
17185 make a significant difference in outlines with very many siblings."
17186 (let (start-level re)
17187 (org-back-to-heading t)
17188 (setq start-level (funcall outline-level))
17189 (if (equal start-level 1)
17191 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17192 (if (re-search-backward re nil t)
17193 (funcall outline-level)))))
17195 (defun org-first-sibling-p ()
17196 "Is this heading the first child of its parents?"
17197 (interactive)
17198 (let ((re (concat "^" outline-regexp))
17199 level l)
17200 (unless (org-at-heading-p t)
17201 (error "Not at a heading"))
17202 (setq level (funcall outline-level))
17203 (save-excursion
17204 (if (not (re-search-backward re nil t))
17206 (setq l (funcall outline-level))
17207 (< l level)))))
17209 (defun org-goto-sibling (&optional previous)
17210 "Goto the next sibling, even if it is invisible.
17211 When PREVIOUS is set, go to the previous sibling instead. Returns t
17212 when a sibling was found. When none is found, return nil and don't
17213 move point."
17214 (let ((fun (if previous 're-search-backward 're-search-forward))
17215 (pos (point))
17216 (re (concat "^" outline-regexp))
17217 level l)
17218 (when (condition-case nil (org-back-to-heading t) (error nil))
17219 (setq level (funcall outline-level))
17220 (catch 'exit
17221 (or previous (forward-char 1))
17222 (while (funcall fun re nil t)
17223 (setq l (funcall outline-level))
17224 (when (< l level) (goto-char pos) (throw 'exit nil))
17225 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17226 (goto-char pos)
17227 nil))))
17229 (defun org-show-siblings ()
17230 "Show all siblings of the current headline."
17231 (save-excursion
17232 (while (org-goto-sibling) (org-flag-heading nil)))
17233 (save-excursion
17234 (while (org-goto-sibling 'previous)
17235 (org-flag-heading nil))))
17237 (defun org-show-hidden-entry ()
17238 "Show an entry where even the heading is hidden."
17239 (save-excursion
17240 (org-show-entry)))
17242 (defun org-flag-heading (flag &optional entry)
17243 "Flag the current heading. FLAG non-nil means make invisible.
17244 When ENTRY is non-nil, show the entire entry."
17245 (save-excursion
17246 (org-back-to-heading t)
17247 ;; Check if we should show the entire entry
17248 (if entry
17249 (progn
17250 (org-show-entry)
17251 (save-excursion
17252 (and (outline-next-heading)
17253 (org-flag-heading nil))))
17254 (outline-flag-region (max (point-min) (1- (point)))
17255 (save-excursion (outline-end-of-heading) (point))
17256 flag))))
17258 (defun org-get-next-sibling ()
17259 "Move to next heading of the same level, and return point.
17260 If there is no such heading, return nil.
17261 This is like outline-next-sibling, but invisible headings are ok."
17262 (let ((level (funcall outline-level)))
17263 (outline-next-heading)
17264 (while (and (not (eobp)) (> (funcall outline-level) level))
17265 (outline-next-heading))
17266 (if (or (eobp) (< (funcall outline-level) level))
17268 (point))))
17270 (defun org-get-last-sibling ()
17271 "Move to previous heading of the same level, and return point.
17272 If there is no such heading, return nil."
17273 (let ((opoint (point))
17274 (level (funcall outline-level)))
17275 (outline-previous-heading)
17276 (when (and (/= (point) opoint) (outline-on-heading-p t))
17277 (while (and (> (funcall outline-level) level)
17278 (not (bobp)))
17279 (outline-previous-heading))
17280 (if (< (funcall outline-level) level)
17282 (point)))))
17284 (defun org-end-of-subtree (&optional invisible-OK to-heading)
17285 ;; This contains an exact copy of the original function, but it uses
17286 ;; `org-back-to-heading', to make it work also in invisible
17287 ;; trees. And is uses an invisible-OK argument.
17288 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17289 ;; Furthermore, when used inside Org, finding the end of a large subtree
17290 ;; with many children and grandchildren etc, this can be much faster
17291 ;; than the outline version.
17292 (org-back-to-heading invisible-OK)
17293 (let ((first t)
17294 (level (funcall outline-level)))
17295 (if (and (org-mode-p) (< level 1000))
17296 ;; A true heading (not a plain list item), in Org-mode
17297 ;; This means we can easily find the end by looking
17298 ;; only for the right number of stars. Using a regexp to do
17299 ;; this is so much faster than using a Lisp loop.
17300 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
17301 (forward-char 1)
17302 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
17303 ;; something else, do it the slow way
17304 (while (and (not (eobp))
17305 (or first (> (funcall outline-level) level)))
17306 (setq first nil)
17307 (outline-next-heading)))
17308 (unless to-heading
17309 (if (memq (preceding-char) '(?\n ?\^M))
17310 (progn
17311 ;; Go to end of line before heading
17312 (forward-char -1)
17313 (if (memq (preceding-char) '(?\n ?\^M))
17314 ;; leave blank line before heading
17315 (forward-char -1))))))
17316 (point))
17318 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
17319 "Use Org version in org-mode, for dramatic speed-up."
17320 (if (eq major-mode 'org-mode)
17321 (progn
17322 (org-end-of-subtree nil t)
17323 (unless (eobp) (backward-char 1)))
17324 ad-do-it))
17326 (defun org-forward-same-level (arg &optional invisible-ok)
17327 "Move forward to the arg'th subheading at same level as this one.
17328 Stop at the first and last subheadings of a superior heading."
17329 (interactive "p")
17330 (org-back-to-heading invisible-ok)
17331 (org-on-heading-p)
17332 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17333 (re (format "^\\*\\{1,%d\\} " level))
17335 (forward-char 1)
17336 (while (> arg 0)
17337 (while (and (re-search-forward re nil 'move)
17338 (setq l (- (match-end 0) (match-beginning 0) 1))
17339 (= l level)
17340 (not invisible-ok)
17341 (org-invisible-p))
17342 (if (< l level) (setq arg 1)))
17343 (setq arg (1- arg)))
17344 (beginning-of-line 1)))
17346 (defun org-backward-same-level (arg &optional invisible-ok)
17347 "Move backward to the arg'th subheading at same level as this one.
17348 Stop at the first and last subheadings of a superior heading."
17349 (interactive "p")
17350 (org-back-to-heading)
17351 (org-on-heading-p)
17352 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17353 (re (format "^\\*\\{1,%d\\} " level))
17355 (while (> arg 0)
17356 (while (and (re-search-backward re nil 'move)
17357 (setq l (- (match-end 0) (match-beginning 0) 1))
17358 (= l level)
17359 (not invisible-ok)
17360 (org-invisible-p))
17361 (if (< l level) (setq arg 1)))
17362 (setq arg (1- arg)))))
17364 (defun org-show-subtree ()
17365 "Show everything after this heading at deeper levels."
17366 (outline-flag-region
17367 (point)
17368 (save-excursion
17369 (org-end-of-subtree t t))
17370 nil))
17372 (defun org-show-entry ()
17373 "Show the body directly following this heading.
17374 Show the heading too, if it is currently invisible."
17375 (interactive)
17376 (save-excursion
17377 (condition-case nil
17378 (progn
17379 (org-back-to-heading t)
17380 (outline-flag-region
17381 (max (point-min) (1- (point)))
17382 (save-excursion
17383 (if (re-search-forward
17384 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17385 (match-beginning 1)
17386 (point-max)))
17387 nil)
17388 (org-cycle-hide-drawers 'children))
17389 (error nil))))
17391 (defun org-make-options-regexp (kwds &optional extra)
17392 "Make a regular expression for keyword lines."
17393 (concat
17395 "#?[ \t]*\\+\\("
17396 (mapconcat 'regexp-quote kwds "\\|")
17397 (if extra (concat "\\|" extra))
17398 "\\):[ \t]*"
17399 "\\(.*\\)"))
17401 ;; Make isearch reveal the necessary context
17402 (defun org-isearch-end ()
17403 "Reveal context after isearch exits."
17404 (when isearch-success ; only if search was successful
17405 (if (featurep 'xemacs)
17406 ;; Under XEmacs, the hook is run in the correct place,
17407 ;; we directly show the context.
17408 (org-show-context 'isearch)
17409 ;; In Emacs the hook runs *before* restoring the overlays.
17410 ;; So we have to use a one-time post-command-hook to do this.
17411 ;; (Emacs 22 has a special variable, see function `org-mode')
17412 (unless (and (boundp 'isearch-mode-end-hook-quit)
17413 isearch-mode-end-hook-quit)
17414 ;; Only when the isearch was not quitted.
17415 (org-add-hook 'post-command-hook 'org-isearch-post-command
17416 'append 'local)))))
17418 (defun org-isearch-post-command ()
17419 "Remove self from hook, and show context."
17420 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17421 (org-show-context 'isearch))
17424 ;;;; Integration with and fixes for other packages
17426 ;;; Imenu support
17428 (defvar org-imenu-markers nil
17429 "All markers currently used by Imenu.")
17430 (make-variable-buffer-local 'org-imenu-markers)
17432 (defun org-imenu-new-marker (&optional pos)
17433 "Return a new marker for use by Imenu, and remember the marker."
17434 (let ((m (make-marker)))
17435 (move-marker m (or pos (point)))
17436 (push m org-imenu-markers)
17439 (defun org-imenu-get-tree ()
17440 "Produce the index for Imenu."
17441 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17442 (setq org-imenu-markers nil)
17443 (let* ((n org-imenu-depth)
17444 (re (concat "^" outline-regexp))
17445 (subs (make-vector (1+ n) nil))
17446 (last-level 0)
17447 m level head)
17448 (save-excursion
17449 (save-restriction
17450 (widen)
17451 (goto-char (point-max))
17452 (while (re-search-backward re nil t)
17453 (setq level (org-reduced-level (funcall outline-level)))
17454 (when (<= level n)
17455 (looking-at org-complex-heading-regexp)
17456 (setq head (org-link-display-format
17457 (org-match-string-no-properties 4))
17458 m (org-imenu-new-marker))
17459 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17460 (if (>= level last-level)
17461 (push (cons head m) (aref subs level))
17462 (push (cons head (aref subs (1+ level))) (aref subs level))
17463 (loop for i from (1+ level) to n do (aset subs i nil)))
17464 (setq last-level level)))))
17465 (aref subs 1)))
17467 (eval-after-load "imenu"
17468 '(progn
17469 (add-hook 'imenu-after-jump-hook
17470 (lambda ()
17471 (if (eq major-mode 'org-mode)
17472 (org-show-context 'org-goto))))))
17474 (defun org-link-display-format (link)
17475 "Replace a link with either the description, or the link target
17476 if no description is present"
17477 (save-match-data
17478 (if (string-match org-bracket-link-analytic-regexp link)
17479 (replace-match (or (match-string 5 link)
17480 (concat (match-string 1 link)
17481 (match-string 3 link)))
17482 nil nil link)
17483 link)))
17485 ;; Speedbar support
17487 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17488 "Overlay marking the agenda restriction line in speedbar.")
17489 (org-overlay-put org-speedbar-restriction-lock-overlay
17490 'face 'org-agenda-restriction-lock)
17491 (org-overlay-put org-speedbar-restriction-lock-overlay
17492 'help-echo "Agendas are currently limited to this item.")
17493 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17495 (defun org-speedbar-set-agenda-restriction ()
17496 "Restrict future agenda commands to the location at point in speedbar.
17497 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17498 (interactive)
17499 (require 'org-agenda)
17500 (let (p m tp np dir txt)
17501 (cond
17502 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17503 'org-imenu t))
17504 (setq m (get-text-property p 'org-imenu-marker))
17505 (with-current-buffer (marker-buffer m)
17506 (goto-char m)
17507 (org-agenda-set-restriction-lock 'subtree)))
17508 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17509 'speedbar-function 'speedbar-find-file))
17510 (setq tp (previous-single-property-change
17511 (1+ p) 'speedbar-function)
17512 np (next-single-property-change
17513 tp 'speedbar-function)
17514 dir (speedbar-line-directory)
17515 txt (buffer-substring-no-properties (or tp (point-min))
17516 (or np (point-max))))
17517 (with-current-buffer (find-file-noselect
17518 (let ((default-directory dir))
17519 (expand-file-name txt)))
17520 (unless (org-mode-p)
17521 (error "Cannot restrict to non-Org-mode file"))
17522 (org-agenda-set-restriction-lock 'file)))
17523 (t (error "Don't know how to restrict Org-mode's agenda")))
17524 (org-move-overlay org-speedbar-restriction-lock-overlay
17525 (point-at-bol) (point-at-eol))
17526 (setq current-prefix-arg nil)
17527 (org-agenda-maybe-redo)))
17529 (eval-after-load "speedbar"
17530 '(progn
17531 (speedbar-add-supported-extension ".org")
17532 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
17533 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
17534 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
17535 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17536 (add-hook 'speedbar-visiting-tag-hook
17537 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
17540 ;;; Fixes and Hacks for problems with other packages
17542 ;; Make flyspell not check words in links, to not mess up our keymap
17543 (defun org-mode-flyspell-verify ()
17544 "Don't let flyspell put overlays at active buttons."
17545 (and (not (get-text-property (point) 'keymap))
17546 (not (get-text-property (point) 'org-no-flyspell))))
17548 (defun org-remove-flyspell-overlays-in (beg end)
17549 "Remove flyspell overlays in region."
17550 (and (org-bound-and-true-p flyspell-mode)
17551 (fboundp 'flyspell-delete-region-overlays)
17552 (flyspell-delete-region-overlays beg end))
17553 (add-text-properties beg end '(org-no-flyspell t)))
17555 ;; Make `bookmark-jump' shows the jump location if it was hidden.
17556 (eval-after-load "bookmark"
17557 '(if (boundp 'bookmark-after-jump-hook)
17558 ;; We can use the hook
17559 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17560 ;; Hook not available, use advice
17561 (defadvice bookmark-jump (after org-make-visible activate)
17562 "Make the position visible."
17563 (org-bookmark-jump-unhide))))
17565 ;; Make sure saveplace shows the location if it was hidden
17566 (eval-after-load "saveplace"
17567 '(defadvice save-place-find-file-hook (after org-make-visible activate)
17568 "Make the position visible."
17569 (org-bookmark-jump-unhide)))
17571 ;; Make sure ecb shows the location if it was hidden
17572 (eval-after-load "ecb"
17573 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
17574 "Make hierarchy visible when jumping into location from ECB tree buffer."
17575 (if (eq major-mode 'org-mode)
17576 (org-show-context))))
17578 (defun org-bookmark-jump-unhide ()
17579 "Unhide the current position, to show the bookmark location."
17580 (and (org-mode-p)
17581 (or (org-invisible-p)
17582 (save-excursion (goto-char (max (point-min) (1- (point))))
17583 (org-invisible-p)))
17584 (org-show-context 'bookmark-jump)))
17586 ;; Make session.el ignore our circular variable
17587 (eval-after-load "session"
17588 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17590 ;;;; Experimental code
17592 (defun org-closed-in-range ()
17593 "Sparse tree of items closed in a certain time range.
17594 Still experimental, may disappear in the future."
17595 (interactive)
17596 ;; Get the time interval from the user.
17597 (let* ((time1 (org-float-time
17598 (org-read-date nil 'to-time nil "Starting date: ")))
17599 (time2 (org-float-time
17600 (org-read-date nil 'to-time nil "End date:")))
17601 ;; callback function
17602 (callback (lambda ()
17603 (let ((time
17604 (org-float-time
17605 (apply 'encode-time
17606 (org-parse-time-string
17607 (match-string 1))))))
17608 ;; check if time in interval
17609 (and (>= time time1) (<= time time2))))))
17610 ;; make tree, check each match with the callback
17611 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
17613 ;;;; Finish up
17615 (provide 'org)
17617 (run-hooks 'org-load-hook)
17619 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17621 ;;; org.el ends here