org-babel: avoid inserting blank line at bottom of exported code blocks
[rgr-org-mode.git] / lisp / org.el
blob472f8c0b43e649d2b9822e1abb8987ee66f92c15
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 (save-excursion
114 (set-buffer "*Shell Command Output*")
115 (goto-char (point-min))
116 (re-search-forward "[^\n]+")
117 (setq git-version (match-string 0))
118 (subst-char-in-string ?- ?. git-version t)
119 (shell-command "git diff-index --name-only HEAD --")
120 (unless (eql 1 (point-max))
121 (setq git-version (concat git-version ".dirty")))
122 (setq version (concat version " (" git-version ")")))
123 (cd pwd))))
124 (setq version (format "Org-mode version %s" version))
125 (if here (insert version))
126 (message version)
127 version))
129 ;;; Compatibility constants
131 ;;; The custom variables
133 (defgroup org nil
134 "Outline-based notes management and organizer."
135 :tag "Org"
136 :group 'outlines
137 :group 'hypermedia
138 :group 'calendar)
140 (defcustom org-mode-hook nil
141 "Mode hook for Org-mode, run after the mode was turned on."
142 :group 'org
143 :type 'hook)
145 (defcustom org-load-hook nil
146 "Hook that is run after org.el has been loaded."
147 :group 'org
148 :type 'hook)
150 (defvar org-modules) ; defined below
151 (defvar org-modules-loaded nil
152 "Have the modules been loaded already?")
154 (defun org-load-modules-maybe (&optional force)
155 "Load all extensions listed in `org-modules'."
156 (when (or force (not org-modules-loaded))
157 (mapc (lambda (ext)
158 (condition-case nil (require ext)
159 (error (message "Problems while trying to load feature `%s'" ext))))
160 org-modules)
161 (setq org-modules-loaded t)))
163 (defun org-set-modules (var value)
164 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
165 (set var value)
166 (when (featurep 'org)
167 (org-load-modules-maybe 'force)))
169 (when (org-bound-and-true-p org-modules)
170 (let ((a (member 'org-infojs org-modules)))
171 (and a (setcar a 'org-jsinfo))))
173 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
174 "Modules that should always be loaded together with org.el.
175 If a description starts with <C>, the file is not part of Emacs
176 and loading it will require that you have downloaded and properly installed
177 the org-mode distribution.
179 You can also use this system to load external packages (i.e. neither Org
180 core modules, nor modules from the CONTRIB directory). Just add symbols
181 to the end of the list. If the package is called org-xyz.el, then you need
182 to add the symbol `xyz', and the package must have a call to
184 (provide 'org-xyz)"
185 :group 'org
186 :set 'org-set-modules
187 :type
188 '(set :greedy t
189 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
190 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
191 (const :tag " crypt: Encryption of subtrees" org-crypt)
192 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
193 (const :tag " id: Global IDs for identifying entries" org-id)
194 (const :tag " info: Links to Info nodes" org-info)
195 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
196 (const :tag " habit: Track your consistency with habits" org-habit)
197 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
198 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
199 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
200 (const :tag " mew Links to Mew folders/messages" org-mew)
201 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
202 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
203 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
204 (const :tag " vm: Links to VM folders/messages" org-vm)
205 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
206 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
207 (const :tag " mouse: Additional mouse support" org-mouse)
209 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
210 (const :tag "C annotation-helper: Call Remember directly from Browser\n\t\t\t(OBSOLETE, use org-protocol)" org-annotation-helper)
211 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
212 (const :tag "C browser-url: Store link, directly from Browser\n\t\t\t(OBSOLETE, use org-protocol)" org-browser-url)
213 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
214 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
215 (const :tag "C collector: Collect properties into tables" org-collector)
216 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
217 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
218 (const :tag "C eval: Include command output as text" org-eval)
219 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
220 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
221 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
222 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
223 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
225 (const :tag "C invoice Help manage client invoices in Org-mode" org-invoice)
227 (const :tag "C jira Add a jira:ticket protocol to Org-mode" org-jira)
228 (const :tag "C 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-emulate-tab t
684 "Where should `org-cycle' emulate TAB.
685 nil Never
686 white Only in completely white lines
687 whitestart Only at the beginning of lines, before the first non-white char
688 t Everywhere except in headlines
689 exc-hl-bol Everywhere except at the start of a headline
690 If TAB is used in a place where it does not emulate TAB, the current subtree
691 visibility is cycled."
692 :group 'org-cycle
693 :type '(choice (const :tag "Never" nil)
694 (const :tag "Only in completely white lines" white)
695 (const :tag "Before first char in a line" whitestart)
696 (const :tag "Everywhere except in headlines" t)
697 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
700 (defcustom org-cycle-separator-lines 2
701 "Number of empty lines needed to keep an empty line between collapsed trees.
702 If you leave an empty line between the end of a subtree and the following
703 headline, this empty line is hidden when the subtree is folded.
704 Org-mode will leave (exactly) one empty line visible if the number of
705 empty lines is equal or larger to the number given in this variable.
706 So the default 2 means, at least 2 empty lines after the end of a subtree
707 are needed to produce free space between a collapsed subtree and the
708 following headline.
710 If the number is negative, and the number of empty lines is at least -N,
711 all empty lines are shown.
713 Special case: when 0, never leave empty lines in collapsed view."
714 :group 'org-cycle
715 :type 'integer)
716 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
718 (defcustom org-pre-cycle-hook nil
719 "Hook that is run before visibility cycling is happening.
720 The function(s) in this hook must accept a single argument which indicates
721 the new state that will be set right after running this hook. The
722 argument is a symbol. Before a global state change, it can have the values
723 `overview', `content', or `all'. Before a local state change, it can have
724 the values `folded', `children', or `subtree'."
725 :group 'org-cycle
726 :type 'hook)
728 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
729 org-cycle-hide-drawers
730 org-cycle-show-empty-lines
731 org-optimize-window-after-visibility-change)
732 "Hook that is run after `org-cycle' has changed the buffer visibility.
733 The function(s) in this hook must accept a single argument which indicates
734 the new state that was set by the most recent `org-cycle' command. The
735 argument is a symbol. After a global state change, it can have the values
736 `overview', `content', or `all'. After a local state change, it can have
737 the values `folded', `children', or `subtree'."
738 :group 'org-cycle
739 :type 'hook)
741 (defgroup org-edit-structure nil
742 "Options concerning structure editing in Org-mode."
743 :tag "Org Edit Structure"
744 :group 'org-structure)
746 (defcustom org-odd-levels-only nil
747 "Non-nil means, skip even levels and only use odd levels for the outline.
748 This has the effect that two stars are being added/taken away in
749 promotion/demotion commands. It also influences how levels are
750 handled by the exporters.
751 Changing it requires restart of `font-lock-mode' to become effective
752 for fontification also in regions already fontified.
753 You may also set this on a per-file basis by adding one of the following
754 lines to the buffer:
756 #+STARTUP: odd
757 #+STARTUP: oddeven"
758 :group 'org-edit-structure
759 :group 'org-font-lock
760 :type 'boolean)
762 (defcustom org-adapt-indentation t
763 "Non-nil means, adapt indentation to outline node level.
765 When this variable is set, Org assumes that you write outlines by
766 indenting text in each node to align with the headline (after the stars).
767 The following issues are influenced by this variable:
769 - When this is set and the *entire* text in an entry is indented, the
770 indentation is increased by one space in a demotion command, and
771 decreased by one in a promotion command. If any line in the entry
772 body starts with text at column 0, indentation is not changed at all.
774 - Property drawers and planning information is inserted indented when
775 this variable s set. When nil, they will not be indented.
777 - TAB indents a line relative to context. The lines below a headline
778 will be indented when this variable is set.
780 Note that this is all about true indentation, by adding and removing
781 space characters. See also `org-indent.el' which does level-dependent
782 indentation in a virtual way, i.e. at display time in Emacs."
783 :group 'org-edit-structure
784 :type 'boolean)
786 (defcustom org-special-ctrl-a/e nil
787 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
789 When t, `C-a' will bring back the cursor to the beginning of the
790 headline text, i.e. after the stars and after a possible TODO keyword.
791 In an item, this will be the position after the bullet.
792 When the cursor is already at that position, another `C-a' will bring
793 it to the beginning of the line.
795 `C-e' will jump to the end of the headline, ignoring the presence of tags
796 in the headline. A second `C-e' will then jump to the true end of the
797 line, after any tags. This also means that, when this variable is
798 non-nil, `C-e' also will never jump beyond the end of the heading of a
799 folded section, i.e. not after the ellipses.
801 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
802 going to the true line boundary first. Only a directly following, identical
803 keypress will bring the cursor to the special positions.
805 This may also be a cons cell where the behavior for `C-a' and `C-e' is
806 set separately."
807 :group 'org-edit-structure
808 :type '(choice
809 (const :tag "off" nil)
810 (const :tag "on: after stars/bullet and before tags first" t)
811 (const :tag "reversed: true line boundary first" reversed)
812 (cons :tag "Set C-a and C-e separately"
813 (choice :tag "Special C-a"
814 (const :tag "off" nil)
815 (const :tag "on: after stars/bullet first" t)
816 (const :tag "reversed: before stars/bullet first" reversed))
817 (choice :tag "Special C-e"
818 (const :tag "off" nil)
819 (const :tag "on: before tags first" t)
820 (const :tag "reversed: after tags first" reversed)))))
821 (if (fboundp 'defvaralias)
822 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
824 (defcustom org-special-ctrl-k nil
825 "Non-nil means `C-k' will behave specially in headlines.
826 When nil, `C-k' will call the default `kill-line' command.
827 When t, the following will happen while the cursor is in the headline:
829 - When the cursor is at the beginning of a headline, kill the entire
830 line and possible the folded subtree below the line.
831 - When in the middle of the headline text, kill the headline up to the tags.
832 - When after the headline text, kill the tags."
833 :group 'org-edit-structure
834 :type 'boolean)
836 (defcustom org-yank-folded-subtrees t
837 "Non-nil means, when yanking subtrees, fold them.
838 If the kill is a single subtree, or a sequence of subtrees, i.e. if
839 it starts with a heading and all other headings in it are either children
840 or siblings, then fold all the subtrees. However, do this only if no
841 text after the yank would be swallowed into a folded tree by this action."
842 :group 'org-edit-structure
843 :type 'boolean)
845 (defcustom org-yank-adjusted-subtrees nil
846 "Non-nil means, when yanking subtrees, adjust the level.
847 With this setting, `org-paste-subtree' is used to insert the subtree, see
848 this function for details."
849 :group 'org-edit-structure
850 :type 'boolean)
852 (defcustom org-M-RET-may-split-line '((default . t))
853 "Non-nil means, M-RET will split the line at the cursor position.
854 When nil, it will go to the end of the line before making a
855 new line.
856 You may also set this option in a different way for different
857 contexts. Valid contexts are:
859 headline when creating a new headline
860 item when creating a new item
861 table in a table field
862 default the value to be used for all contexts not explicitly
863 customized"
864 :group 'org-structure
865 :group 'org-table
866 :type '(choice
867 (const :tag "Always" t)
868 (const :tag "Never" nil)
869 (repeat :greedy t :tag "Individual contexts"
870 (cons
871 (choice :tag "Context"
872 (const headline)
873 (const item)
874 (const table)
875 (const default))
876 (boolean)))))
879 (defcustom org-insert-heading-respect-content nil
880 "Non-nil means, insert new headings after the current subtree.
881 When nil, the new heading is created directly after the current line.
882 The commands \\[org-insert-heading-respect-content] and
883 \\[org-insert-todo-heading-respect-content] turn this variable on
884 for the duration of the command."
885 :group 'org-structure
886 :type 'boolean)
888 (defcustom org-blank-before-new-entry '((heading . auto)
889 (plain-list-item . auto))
890 "Should `org-insert-heading' leave a blank line before new heading/item?
891 The value is an alist, with `heading' and `plain-list-item' as car,
892 and a boolean flag as cdr. For plain lists, if the variable
893 `org-empty-line-terminates-plain-lists' is set, the setting here
894 is ignored and no empty line is inserted, to keep the list in tact."
895 :group 'org-edit-structure
896 :type '(list
897 (cons (const heading)
898 (choice (const :tag "Never" nil)
899 (const :tag "Always" t)
900 (const :tag "Auto" auto)))
901 (cons (const plain-list-item)
902 (choice (const :tag "Never" nil)
903 (const :tag "Always" t)
904 (const :tag "Auto" auto)))))
906 (defcustom org-insert-heading-hook nil
907 "Hook being run after inserting a new heading."
908 :group 'org-edit-structure
909 :type 'hook)
911 (defcustom org-enable-fixed-width-editor t
912 "Non-nil means, lines starting with \":\" are treated as fixed-width.
913 This currently only means, they are never auto-wrapped.
914 When nil, such lines will be treated like ordinary lines.
915 See also the QUOTE keyword."
916 :group 'org-edit-structure
917 :type 'boolean)
920 (defcustom org-goto-auto-isearch t
921 "Non-nil means, typing characters in org-goto starts incremental search."
922 :group 'org-edit-structure
923 :type 'boolean)
925 (defgroup org-sparse-trees nil
926 "Options concerning sparse trees in Org-mode."
927 :tag "Org Sparse Trees"
928 :group 'org-structure)
930 (defcustom org-highlight-sparse-tree-matches t
931 "Non-nil means, highlight all matches that define a sparse tree.
932 The highlights will automatically disappear the next time the buffer is
933 changed by an edit command."
934 :group 'org-sparse-trees
935 :type 'boolean)
937 (defcustom org-remove-highlights-with-change t
938 "Non-nil means, any change to the buffer will remove temporary highlights.
939 Such highlights are created by `org-occur' and `org-clock-display'.
940 When nil, `C-c C-c needs to be used to get rid of the highlights.
941 The highlights created by `org-preview-latex-fragment' always need
942 `C-c C-c' to be removed."
943 :group 'org-sparse-trees
944 :group 'org-time
945 :type 'boolean)
948 (defcustom org-occur-hook '(org-first-headline-recenter)
949 "Hook that is run after `org-occur' has constructed a sparse tree.
950 This can be used to recenter the window to show as much of the structure
951 as possible."
952 :group 'org-sparse-trees
953 :type 'hook)
955 (defgroup org-imenu-and-speedbar nil
956 "Options concerning imenu and speedbar in Org-mode."
957 :tag "Org Imenu and Speedbar"
958 :group 'org-structure)
960 (defcustom org-imenu-depth 2
961 "The maximum level for Imenu access to Org-mode headlines.
962 This also applied for speedbar access."
963 :group 'org-imenu-and-speedbar
964 :type 'integer)
966 (defgroup org-table nil
967 "Options concerning tables in Org-mode."
968 :tag "Org Table"
969 :group 'org)
971 (defcustom org-enable-table-editor 'optimized
972 "Non-nil means, lines starting with \"|\" are handled by the table editor.
973 When nil, such lines will be treated like ordinary lines.
975 When equal to the symbol `optimized', the table editor will be optimized to
976 do the following:
977 - Automatic overwrite mode in front of whitespace in table fields.
978 This makes the structure of the table stay in tact as long as the edited
979 field does not exceed the column width.
980 - Minimize the number of realigns. Normally, the table is aligned each time
981 TAB or RET are pressed to move to another field. With optimization this
982 happens only if changes to a field might have changed the column width.
983 Optimization requires replacing the functions `self-insert-command',
984 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
985 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
986 very good at guessing when a re-align will be necessary, but you can always
987 force one with \\[org-ctrl-c-ctrl-c].
989 If you would like to use the optimized version in Org-mode, but the
990 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
992 This variable can be used to turn on and off the table editor during a session,
993 but in order to toggle optimization, a restart is required.
995 See also the variable `org-table-auto-blank-field'."
996 :group 'org-table
997 :type '(choice
998 (const :tag "off" nil)
999 (const :tag "on" t)
1000 (const :tag "on, optimized" optimized)))
1002 (defcustom org-self-insert-cluster-for-undo t
1003 "Non-nil means cluster self-insert commands for undo when possible.
1004 If this is set, then, like in the Emacs command loop, 20 consequtive
1005 characters will be undone together.
1006 This is configurable, because there is some impact on typing performance."
1007 :group 'org-table
1008 :type 'boolean)
1010 (defcustom org-table-tab-recognizes-table.el t
1011 "Non-nil means, TAB will automatically notice a table.el table.
1012 When it sees such a table, it moves point into it and - if necessary -
1013 calls `table-recognize-table'."
1014 :group 'org-table-editing
1015 :type 'boolean)
1017 (defgroup org-link nil
1018 "Options concerning links in Org-mode."
1019 :tag "Org Link"
1020 :group 'org)
1022 (defvar org-link-abbrev-alist-local nil
1023 "Buffer-local version of `org-link-abbrev-alist', which see.
1024 The value of this is taken from the #+LINK lines.")
1025 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1027 (defcustom org-link-abbrev-alist nil
1028 "Alist of link abbreviations.
1029 The car of each element is a string, to be replaced at the start of a link.
1030 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1031 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1033 [[linkkey:tag][description]]
1035 The 'linkkey' must be a word word, starting with a letter, followed
1036 by letters, numbers, '-' or '_'.
1038 If REPLACE is a string, the tag will simply be appended to create the link.
1039 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1040 the placeholder \"%h\" will cause a url-encoded version of the tag to
1041 be inserted at that point (see the function `url-hexify-string').
1043 REPLACE may also be a function that will be called with the tag as the
1044 only argument to create the link, which should be returned as a string.
1046 See the manual for examples."
1047 :group 'org-link
1048 :type '(repeat
1049 (cons
1050 (string :tag "Protocol")
1051 (choice
1052 (string :tag "Format")
1053 (function)))))
1055 (defcustom org-descriptive-links t
1056 "Non-nil means, hide link part and only show description of bracket links.
1057 Bracket links are like [[link][description]]. This variable sets the initial
1058 state in new org-mode buffers. The setting can then be toggled on a
1059 per-buffer basis from the Org->Hyperlinks menu."
1060 :group 'org-link
1061 :type 'boolean)
1063 (defcustom org-link-file-path-type 'adaptive
1064 "How the path name in file links should be stored.
1065 Valid values are:
1067 relative Relative to the current directory, i.e. the directory of the file
1068 into which the link is being inserted.
1069 absolute Absolute path, if possible with ~ for home directory.
1070 noabbrev Absolute path, no abbreviation of home directory.
1071 adaptive Use relative path for files in the current directory and sub-
1072 directories of it. For other files, use an absolute path."
1073 :group 'org-link
1074 :type '(choice
1075 (const relative)
1076 (const absolute)
1077 (const noabbrev)
1078 (const adaptive)))
1080 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1081 "Types of links that should be activated in Org-mode files.
1082 This is a list of symbols, each leading to the activation of a certain link
1083 type. In principle, it does not hurt to turn on most link types - there may
1084 be a small gain when turning off unused link types. The types are:
1086 bracket The recommended [[link][description]] or [[link]] links with hiding.
1087 angular Links in angular brackets that may contain whitespace like
1088 <bbdb:Carsten Dominik>.
1089 plain Plain links in normal text, no whitespace, like http://google.com.
1090 radio Text that is matched by a radio target, see manual for details.
1091 tag Tag settings in a headline (link to tag search).
1092 date Time stamps (link to calendar).
1093 footnote Footnote labels.
1095 Changing this variable requires a restart of Emacs to become effective."
1096 :group 'org-link
1097 :type '(set :greedy t
1098 (const :tag "Double bracket links (new style)" bracket)
1099 (const :tag "Angular bracket links (old style)" angular)
1100 (const :tag "Plain text links" plain)
1101 (const :tag "Radio target matches" radio)
1102 (const :tag "Tags" tag)
1103 (const :tag "Timestamps" date)
1104 (const :tag "Footnotes" footnote)))
1106 (defcustom org-make-link-description-function nil
1107 "Function to use to generate link descriptions from links. If
1108 nil the link location will be used. This function must take two
1109 parameters; the first is the link and the second the description
1110 org-insert-link has generated, and should return the description
1111 to use."
1112 :group 'org-link
1113 :type 'function)
1115 (defgroup org-link-store nil
1116 "Options concerning storing links in Org-mode."
1117 :tag "Org Store Link"
1118 :group 'org-link)
1120 (defcustom org-email-link-description-format "Email %c: %.30s"
1121 "Format of the description part of a link to an email or usenet message.
1122 The following %-escapes will be replaced by corresponding information:
1124 %F full \"From\" field
1125 %f name, taken from \"From\" field, address if no name
1126 %T full \"To\" field
1127 %t first name in \"To\" field, address if no name
1128 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1129 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1130 %s subject
1131 %m message-id.
1133 You may use normal field width specification between the % and the letter.
1134 This is for example useful to limit the length of the subject.
1136 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1137 :group 'org-link-store
1138 :type 'string)
1140 (defcustom org-from-is-user-regexp
1141 (let (r1 r2)
1142 (when (and user-mail-address (not (string= user-mail-address "")))
1143 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1144 (when (and user-full-name (not (string= user-full-name "")))
1145 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1146 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1147 "Regexp matched against the \"From:\" header of an email or usenet message.
1148 It should match if the message is from the user him/herself."
1149 :group 'org-link-store
1150 :type 'regexp)
1152 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1153 "Non-nil means, storing a link to an Org file will use entry IDs.
1155 Note that before this variable is even considered, org-id must be loaded,
1156 so please customize `org-modules' and turn it on.
1158 The variable can have the following values:
1160 t Create an ID if needed to make a link to the current entry.
1162 create-if-interactive
1163 If `org-store-link' is called directly (interactively, as a user
1164 command), do create an ID to support the link. But when doing the
1165 job for remember, only use the ID if it already exists. The
1166 purpose of this setting is to avoid proliferation of unwanted
1167 IDs, just because you happen to be in an Org file when you
1168 call `org-remember' that automatically and preemptively
1169 creates a link. If you do want to get an ID link in a remember
1170 template to an entry not having an ID, create it first by
1171 explicitly creating a link to it, using `C-c C-l' first.
1173 create-if-interactive-and-no-custom-id
1174 Like create-if-interactive, but do not create an ID if there is
1175 a CUSTOM_ID property defined in the entry. This is the default.
1177 use-existing
1178 Use existing ID, do not create one.
1180 nil Never use an ID to make a link, instead link using a text search for
1181 the headline text."
1182 :group 'org-link-store
1183 :type '(choice
1184 (const :tag "Create ID to make link" t)
1185 (const :tag "Create if storing link interactively"
1186 create-if-interactive)
1187 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1188 create-if-interactive-and-no-custom-id)
1189 (const :tag "Only use existing" use-existing)
1190 (const :tag "Do not use ID to create link" nil)))
1192 (defcustom org-context-in-file-links t
1193 "Non-nil means, file links from `org-store-link' contain context.
1194 A search string will be added to the file name with :: as separator and
1195 used to find the context when the link is activated by the command
1196 `org-open-at-point'.
1197 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1198 negates this setting for the duration of the command."
1199 :group 'org-link-store
1200 :type 'boolean)
1202 (defcustom org-keep-stored-link-after-insertion nil
1203 "Non-nil means, keep link in list for entire session.
1205 The command `org-store-link' adds a link pointing to the current
1206 location to an internal list. These links accumulate during a session.
1207 The command `org-insert-link' can be used to insert links into any
1208 Org-mode file (offering completion for all stored links). When this
1209 option is nil, every link which has been inserted once using \\[org-insert-link]
1210 will be removed from the list, to make completing the unused links
1211 more efficient."
1212 :group 'org-link-store
1213 :type 'boolean)
1215 (defgroup org-link-follow nil
1216 "Options concerning following links in Org-mode."
1217 :tag "Org Follow Link"
1218 :group 'org-link)
1220 (defcustom org-link-translation-function nil
1221 "Function to translate links with different syntax to Org syntax.
1222 This can be used to translate links created for example by the Planner
1223 or emacs-wiki packages to Org syntax.
1224 The function must accept two parameters, a TYPE containing the link
1225 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1226 which is everything after the link protocol. It should return a cons
1227 with possibly modified values of type and path.
1228 Org contains a function for this, so if you set this variable to
1229 `org-translate-link-from-planner', you should be able follow many
1230 links created by planner."
1231 :group 'org-link-follow
1232 :type 'function)
1234 (defcustom org-follow-link-hook nil
1235 "Hook that is run after a link has been followed."
1236 :group 'org-link-follow
1237 :type 'hook)
1239 (defcustom org-tab-follows-link nil
1240 "Non-nil means, on links TAB will follow the link.
1241 Needs to be set before org.el is loaded.
1242 This really should not be used, it does not make sense, and the
1243 implementation is bad."
1244 :group 'org-link-follow
1245 :type 'boolean)
1247 (defcustom org-return-follows-link nil
1248 "Non-nil means, on links RET will follow the link.
1249 Needs to be set before org.el is loaded."
1250 :group 'org-link-follow
1251 :type 'boolean)
1253 (defcustom org-mouse-1-follows-link
1254 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1255 "Non-nil means, mouse-1 on a link will follow the link.
1256 A longer mouse click will still set point. Does not work on XEmacs.
1257 Needs to be set before org.el is loaded."
1258 :group 'org-link-follow
1259 :type 'boolean)
1261 (defcustom org-mark-ring-length 4
1262 "Number of different positions to be recorded in the ring
1263 Changing this requires a restart of Emacs to work correctly."
1264 :group 'org-link-follow
1265 :type 'integer)
1267 (defcustom org-link-frame-setup
1268 '((vm . vm-visit-folder-other-frame)
1269 (gnus . gnus-other-frame)
1270 (file . find-file-other-window))
1271 "Setup the frame configuration for following links.
1272 When following a link with Emacs, it may often be useful to display
1273 this link in another window or frame. This variable can be used to
1274 set this up for the different types of links.
1275 For VM, use any of
1276 `vm-visit-folder'
1277 `vm-visit-folder-other-frame'
1278 For Gnus, use any of
1279 `gnus'
1280 `gnus-other-frame'
1281 `org-gnus-no-new-news'
1282 For FILE, use any of
1283 `find-file'
1284 `find-file-other-window'
1285 `find-file-other-frame'
1286 For the calendar, use the variable `calendar-setup'.
1287 For BBDB, it is currently only possible to display the matches in
1288 another window."
1289 :group 'org-link-follow
1290 :type '(list
1291 (cons (const vm)
1292 (choice
1293 (const vm-visit-folder)
1294 (const vm-visit-folder-other-window)
1295 (const vm-visit-folder-other-frame)))
1296 (cons (const gnus)
1297 (choice
1298 (const gnus)
1299 (const gnus-other-frame)
1300 (const org-gnus-no-new-news)))
1301 (cons (const file)
1302 (choice
1303 (const find-file)
1304 (const find-file-other-window)
1305 (const find-file-other-frame)))))
1307 (defcustom org-display-internal-link-with-indirect-buffer nil
1308 "Non-nil means, use indirect buffer to display infile links.
1309 Activating internal links (from one location in a file to another location
1310 in the same file) normally just jumps to the location. When the link is
1311 activated with a C-u prefix (or with mouse-3), the link is displayed in
1312 another window. When this option is set, the other window actually displays
1313 an indirect buffer clone of the current buffer, to avoid any visibility
1314 changes to the current buffer."
1315 :group 'org-link-follow
1316 :type 'boolean)
1318 (defcustom org-open-non-existing-files nil
1319 "Non-nil means, `org-open-file' will open non-existing files.
1320 When nil, an error will be generated.
1321 This variable applies only to external applications because they
1322 might choke on non-existing files. If the link is to a file that
1323 will be openend in Emacs, the variable is ignored."
1324 :group 'org-link-follow
1325 :type 'boolean)
1327 (defcustom org-open-directory-means-index-dot-org nil
1328 "Non-nil means, a link to a directory really means to index.org.
1329 When nil, following a directory link will run dired or open a finder/explorer
1330 window on that directory."
1331 :group 'org-link-follow
1332 :type 'boolean)
1334 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1335 "Function and arguments to call for following mailto links.
1336 This is a list with the first element being a lisp function, and the
1337 remaining elements being arguments to the function. In string arguments,
1338 %a will be replaced by the address, and %s will be replaced by the subject
1339 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1340 :group 'org-link-follow
1341 :type '(choice
1342 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1343 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1344 (const :tag "message-mail" (message-mail "%a" "%s"))
1345 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1347 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1348 "Non-nil means, ask for confirmation before executing shell links.
1349 Shell links can be dangerous: just think about a link
1351 [[shell:rm -rf ~/*][Google Search]]
1353 This link would show up in your Org-mode document as \"Google Search\",
1354 but really it would remove your entire home directory.
1355 Therefore we advise against setting this variable to nil.
1356 Just change it to `y-or-n-p' if you want to confirm with a
1357 single keystroke rather than having to type \"yes\"."
1358 :group 'org-link-follow
1359 :type '(choice
1360 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1361 (const :tag "with y-or-n (faster)" y-or-n-p)
1362 (const :tag "no confirmation (dangerous)" nil)))
1364 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1365 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1366 Elisp links can be dangerous: just think about a link
1368 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1370 This link would show up in your Org-mode document as \"Google Search\",
1371 but really it would remove your entire home directory.
1372 Therefore we advise against setting this variable to nil.
1373 Just change it to `y-or-n-p' if you want to confirm with a
1374 single keystroke rather than having to type \"yes\"."
1375 :group 'org-link-follow
1376 :type '(choice
1377 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1378 (const :tag "with y-or-n (faster)" y-or-n-p)
1379 (const :tag "no confirmation (dangerous)" nil)))
1381 (defconst org-file-apps-defaults-gnu
1382 '((remote . emacs)
1383 (system . mailcap)
1384 (t . mailcap))
1385 "Default file applications on a UNIX or GNU/Linux system.
1386 See `org-file-apps'.")
1388 (defconst org-file-apps-defaults-macosx
1389 '((remote . emacs)
1390 (t . "open %s")
1391 (system . "open %s")
1392 ("ps.gz" . "gv %s")
1393 ("eps.gz" . "gv %s")
1394 ("dvi" . "xdvi %s")
1395 ("fig" . "xfig %s"))
1396 "Default file applications on a MacOS X system.
1397 The system \"open\" is known as a default, but we use X11 applications
1398 for some files for which the OS does not have a good default.
1399 See `org-file-apps'.")
1401 (defconst org-file-apps-defaults-windowsnt
1402 (list
1403 '(remote . emacs)
1404 (cons t
1405 (list (if (featurep 'xemacs)
1406 'mswindows-shell-execute
1407 'w32-shell-execute)
1408 "open" 'file))
1409 (cons 'system
1410 (list (if (featurep 'xemacs)
1411 'mswindows-shell-execute
1412 'w32-shell-execute)
1413 "open" 'file)))
1414 "Default file applications on a Windows NT system.
1415 The system \"open\" is used for most files.
1416 See `org-file-apps'.")
1418 (defcustom org-file-apps
1420 (auto-mode . emacs)
1421 ("\\.mm\\'" . default)
1422 ("\\.x?html?\\'" . default)
1423 ("\\.pdf\\'" . default)
1425 "External applications for opening `file:path' items in a document.
1426 Org-mode uses system defaults for different file types, but
1427 you can use this variable to set the application for a given file
1428 extension. The entries in this list are cons cells where the car identifies
1429 files and the cdr the corresponding command. Possible values for the
1430 file identifier are
1431 \"regex\" Regular expression matched against the file name. For backward
1432 compatibility, this can also be a string with only alphanumeric
1433 characters, which is then interpreted as an extension.
1434 `directory' Matches a directory
1435 `remote' Matches a remote file, accessible through tramp or efs.
1436 Remote files most likely should be visited through Emacs
1437 because external applications cannot handle such paths.
1438 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1439 so all files Emacs knows how to handle. Using this with
1440 command `emacs' will open most files in Emacs. Beware that this
1441 will also open html files inside Emacs, unless you add
1442 (\"html\" . default) to the list as well.
1443 t Default for files not matched by any of the other options.
1444 `system' The system command to open files, like `open' on Windows
1445 and Mac OS X, and mailcap under GNU/Linux. This is the command
1446 that will be selected if you call `C-c C-o' with a double
1447 `C-u C-u' prefix.
1449 Possible values for the command are:
1450 `emacs' The file will be visited by the current Emacs process.
1451 `default' Use the default application for this file type, which is the
1452 association for t in the list, most likely in the system-specific
1453 part.
1454 This can be used to overrule an unwanted setting in the
1455 system-specific variable.
1456 `system' Use the system command for opening files, like \"open\".
1457 This command is specified by the entry whose car is `system'.
1458 Most likely, the system-specific version of this variable
1459 does define this command, but you can overrule/replace it
1460 here.
1461 string A command to be executed by a shell; %s will be replaced
1462 by the path to the file.
1463 sexp A Lisp form which will be evaluated. The file path will
1464 be available in the Lisp variable `file'.
1465 For more examples, see the system specific constants
1466 `org-file-apps-defaults-macosx'
1467 `org-file-apps-defaults-windowsnt'
1468 `org-file-apps-defaults-gnu'."
1469 :group 'org-link-follow
1470 :type '(repeat
1471 (cons (choice :value ""
1472 (string :tag "Extension")
1473 (const :tag "System command to open files" system)
1474 (const :tag "Default for unrecognized files" t)
1475 (const :tag "Remote file" remote)
1476 (const :tag "Links to a directory" directory)
1477 (const :tag "Any files that have Emacs modes"
1478 auto-mode))
1479 (choice :value ""
1480 (const :tag "Visit with Emacs" emacs)
1481 (const :tag "Use default" default)
1482 (const :tag "Use the system command" system)
1483 (string :tag "Command")
1484 (sexp :tag "Lisp form")))))
1486 (defgroup org-refile nil
1487 "Options concerning refiling entries in Org-mode."
1488 :tag "Org Refile"
1489 :group 'org)
1491 (defcustom org-directory "~/org"
1492 "Directory with org files.
1493 This is just a default location to look for Org files. There is no need
1494 at all to put your files into this directory. It is only used in the
1495 following situations:
1497 1. When a remember template specifies a target file that is not an
1498 absolute path. The path will then be interpreted relative to
1499 `org-directory'
1500 2. When a remember note is filed away in an interactive way (when exiting the
1501 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1502 with `org-directory' as the default path."
1503 :group 'org-refile
1504 :group 'org-remember
1505 :type 'directory)
1507 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1508 "Default target for storing notes.
1509 Used by the hooks for remember.el. This can be a string, or nil to mean
1510 the value of `remember-data-file'.
1511 You can set this on a per-template basis with the variable
1512 `org-remember-templates'."
1513 :group 'org-refile
1514 :group 'org-remember
1515 :type '(choice
1516 (const :tag "Default from remember-data-file" nil)
1517 file))
1519 (defcustom org-goto-interface 'outline
1520 "The default interface to be used for `org-goto'.
1521 Allowed values are:
1522 outline The interface shows an outline of the relevant file
1523 and the correct heading is found by moving through
1524 the outline or by searching with incremental search.
1525 outline-path-completion Headlines in the current buffer are offered via
1526 completion. This is the interface also used by
1527 the refile command."
1528 :group 'org-refile
1529 :type '(choice
1530 (const :tag "Outline" outline)
1531 (const :tag "Outline-path-completion" outline-path-completion)))
1533 (defcustom org-goto-max-level 5
1534 "Maximum level to be considered when running org-goto with refile interface."
1535 :group 'org-refile
1536 :type 'integer)
1538 (defcustom org-reverse-note-order nil
1539 "Non-nil means, store new notes at the beginning of a file or entry.
1540 When nil, new notes will be filed to the end of a file or entry.
1541 This can also be a list with cons cells of regular expressions that
1542 are matched against file names, and values."
1543 :group 'org-remember
1544 :group 'org-refile
1545 :type '(choice
1546 (const :tag "Reverse always" t)
1547 (const :tag "Reverse never" nil)
1548 (repeat :tag "By file name regexp"
1549 (cons regexp boolean))))
1551 (defcustom org-refile-targets nil
1552 "Targets for refiling entries with \\[org-refile].
1553 This is list of cons cells. Each cell contains:
1554 - a specification of the files to be considered, either a list of files,
1555 or a symbol whose function or variable value will be used to retrieve
1556 a file name or a list of file names. If you use `org-agenda-files' for
1557 that, all agenda files will be scanned for targets. Nil means, consider
1558 headings in the current buffer.
1559 - A specification of how to find candidate refile targets. This may be
1560 any of:
1561 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1562 This tag has to be present in all target headlines, inheritance will
1563 not be considered.
1564 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1565 todo keyword.
1566 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1567 headlines that are refiling targets.
1568 - a cons cell (:level . N). Any headline of level N is considered a target.
1569 Note that, when `org-odd-levels-only' is set, level corresponds to
1570 order in hierarchy, not to the number of stars.
1571 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1572 Note that, when `org-odd-levels-only' is set, level corresponds to
1573 order in hierarchy, not to the number of stars.
1575 You can set the variable `org-refile-target-verify-function' to a function
1576 to verify each headline found by the simple critery above.
1578 When this variable is nil, all top-level headlines in the current buffer
1579 are used, equivalent to the value `((nil . (:level . 1))'."
1580 :group 'org-refile
1581 :type '(repeat
1582 (cons
1583 (choice :value org-agenda-files
1584 (const :tag "All agenda files" org-agenda-files)
1585 (const :tag "Current buffer" nil)
1586 (function) (variable) (file))
1587 (choice :tag "Identify target headline by"
1588 (cons :tag "Specific tag" (const :value :tag) (string))
1589 (cons :tag "TODO keyword" (const :value :todo) (string))
1590 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1591 (cons :tag "Level number" (const :value :level) (integer))
1592 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1594 (defcustom org-refile-target-verify-function nil
1595 "Function to verify if the headline at point should be a refile target.
1596 The function will be called without arguments, with point at the
1597 beginning of the headline. It should return t and leave point
1598 where it is if the headline is a valid target for refiling.
1600 If the target should not be selected, the function must return nil.
1601 In addition to this, it may move point to a place from where the search
1602 should be continued. For example, the function may decide that the entire
1603 subtree of the current entry should be excluded and move point to the end
1604 of the subtree."
1605 :group 'org-refile
1606 :type 'function)
1608 (defcustom org-refile-use-outline-path nil
1609 "Non-nil means, provide refile targets as paths.
1610 So a level 3 headline will be available as level1/level2/level3.
1612 When the value is `file', also include the file name (without directory)
1613 into the path. In this case, you can also stop the completion after
1614 the file name, to get entries inserted as top level in the file.
1616 When `full-file-path', include the full file path."
1617 :group 'org-refile
1618 :type '(choice
1619 (const :tag "Not" nil)
1620 (const :tag "Yes" t)
1621 (const :tag "Start with file name" file)
1622 (const :tag "Start with full file path" full-file-path)))
1624 (defcustom org-outline-path-complete-in-steps t
1625 "Non-nil means, complete the outline path in hierarchical steps.
1626 When Org-mode uses the refile interface to select an outline path
1627 \(see variable `org-refile-use-outline-path'), the completion of
1628 the path can be done is a single go, or if can be done in steps down
1629 the headline hierarchy. Going in steps is probably the best if you
1630 do not use a special completion package like `ido' or `icicles'.
1631 However, when using these packages, going in one step can be very
1632 fast, while still showing the whole path to the entry."
1633 :group 'org-refile
1634 :type 'boolean)
1636 (defcustom org-refile-allow-creating-parent-nodes nil
1637 "Non-nil means, allow to create new nodes as refile targets.
1638 New nodes are then created by adding \"/new node name\" to the completion
1639 of an existing node. When the value of this variable is `confirm',
1640 new node creation must be confirmed by the user (recommended)
1641 When nil, the completion must match an existing entry.
1643 Note that, if the new heading is not seen by the criteria
1644 listed in `org-refile-targets', multiple instances of the same
1645 heading would be created by trying again to file under the new
1646 heading."
1647 :group 'org-refile
1648 :type '(choice
1649 (const :tag "Never" nil)
1650 (const :tag "Always" t)
1651 (const :tag "Prompt for confirmation" confirm)))
1653 (defgroup org-todo nil
1654 "Options concerning TODO items in Org-mode."
1655 :tag "Org TODO"
1656 :group 'org)
1658 (defgroup org-progress nil
1659 "Options concerning Progress logging in Org-mode."
1660 :tag "Org Progress"
1661 :group 'org-time)
1663 (defvar org-todo-interpretation-widgets
1665 (:tag "Sequence (cycling hits every state)" sequence)
1666 (:tag "Type (cycling directly to DONE)" type))
1667 "The available interpretation symbols for customizing
1668 `org-todo-keywords'.
1669 Interested libraries should add to this list.")
1671 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1672 "List of TODO entry keyword sequences and their interpretation.
1673 \\<org-mode-map>This is a list of sequences.
1675 Each sequence starts with a symbol, either `sequence' or `type',
1676 indicating if the keywords should be interpreted as a sequence of
1677 action steps, or as different types of TODO items. The first
1678 keywords are states requiring action - these states will select a headline
1679 for inclusion into the global TODO list Org-mode produces. If one of
1680 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1681 signify that no further action is necessary. If \"|\" is not found,
1682 the last keyword is treated as the only DONE state of the sequence.
1684 The command \\[org-todo] cycles an entry through these states, and one
1685 additional state where no keyword is present. For details about this
1686 cycling, see the manual.
1688 TODO keywords and interpretation can also be set on a per-file basis with
1689 the special #+SEQ_TODO and #+TYP_TODO lines.
1691 Each keyword can optionally specify a character for fast state selection
1692 \(in combination with the variable `org-use-fast-todo-selection')
1693 and specifiers for state change logging, using the same syntax
1694 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1695 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1696 indicates to record a time stamp each time this state is selected.
1698 Each keyword may also specify if a timestamp or a note should be
1699 recorded when entering or leaving the state, by adding additional
1700 characters in the parenthesis after the keyword. This looks like this:
1701 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1702 record only the time of the state change. With X and Y being either
1703 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1704 Y when leaving the state if and only if the *target* state does not
1705 define X. You may omit any of the fast-selection key or X or /Y,
1706 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1708 For backward compatibility, this variable may also be just a list
1709 of keywords - in this case the interpretation (sequence or type) will be
1710 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1711 :group 'org-todo
1712 :group 'org-keywords
1713 :type '(choice
1714 (repeat :tag "Old syntax, just keywords"
1715 (string :tag "Keyword"))
1716 (repeat :tag "New syntax"
1717 (cons
1718 (choice
1719 :tag "Interpretation"
1720 ;;Quick and dirty way to see
1721 ;;`org-todo-interpretations'. This takes the
1722 ;;place of item arguments
1723 :convert-widget
1724 (lambda (widget)
1725 (widget-put widget
1726 :args (mapcar
1727 #'(lambda (x)
1728 (widget-convert
1729 (cons 'const x)))
1730 org-todo-interpretation-widgets))
1731 widget))
1732 (repeat
1733 (string :tag "Keyword"))))))
1735 (defvar org-todo-keywords-1 nil
1736 "All TODO and DONE keywords active in a buffer.")
1737 (make-variable-buffer-local 'org-todo-keywords-1)
1738 (defvar org-todo-keywords-for-agenda nil)
1739 (defvar org-done-keywords-for-agenda nil)
1740 (defvar org-drawers-for-agenda nil)
1741 (defvar org-todo-keyword-alist-for-agenda nil)
1742 (defvar org-tag-alist-for-agenda nil)
1743 (defvar org-agenda-contributing-files nil)
1744 (defvar org-not-done-keywords nil)
1745 (make-variable-buffer-local 'org-not-done-keywords)
1746 (defvar org-done-keywords nil)
1747 (make-variable-buffer-local 'org-done-keywords)
1748 (defvar org-todo-heads nil)
1749 (make-variable-buffer-local 'org-todo-heads)
1750 (defvar org-todo-sets nil)
1751 (make-variable-buffer-local 'org-todo-sets)
1752 (defvar org-todo-log-states nil)
1753 (make-variable-buffer-local 'org-todo-log-states)
1754 (defvar org-todo-kwd-alist nil)
1755 (make-variable-buffer-local 'org-todo-kwd-alist)
1756 (defvar org-todo-key-alist nil)
1757 (make-variable-buffer-local 'org-todo-key-alist)
1758 (defvar org-todo-key-trigger nil)
1759 (make-variable-buffer-local 'org-todo-key-trigger)
1761 (defcustom org-todo-interpretation 'sequence
1762 "Controls how TODO keywords are interpreted.
1763 This variable is in principle obsolete and is only used for
1764 backward compatibility, if the interpretation of todo keywords is
1765 not given already in `org-todo-keywords'. See that variable for
1766 more information."
1767 :group 'org-todo
1768 :group 'org-keywords
1769 :type '(choice (const sequence)
1770 (const type)))
1772 (defcustom org-use-fast-todo-selection t
1773 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1774 This variable describes if and under what circumstances the cycling
1775 mechanism for TODO keywords will be replaced by a single-key, direct
1776 selection scheme.
1778 When nil, fast selection is never used.
1780 When the symbol `prefix', it will be used when `org-todo' is called with
1781 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1782 in an agenda buffer.
1784 When t, fast selection is used by default. In this case, the prefix
1785 argument forces cycling instead.
1787 In all cases, the special interface is only used if access keys have actually
1788 been assigned by the user, i.e. if keywords in the configuration are followed
1789 by a letter in parenthesis, like TODO(t)."
1790 :group 'org-todo
1791 :type '(choice
1792 (const :tag "Never" nil)
1793 (const :tag "By default" t)
1794 (const :tag "Only with C-u C-c C-t" prefix)))
1796 (defcustom org-provide-todo-statistics t
1797 "Non-nil means, update todo statistics after insert and toggle.
1798 ALL-HEADLINES means update todo statistics by including headlines
1799 with no TODO keyword as well, counting them as not done.
1800 A list of TODO keywords means the same, but skip keywords that are
1801 not in this list.
1803 When this is set, todo statistics is updated in the parent of the
1804 current entry each time a todo state is changed."
1805 :group 'org-todo
1806 :type '(choice
1807 (const :tag "Yes, only for TODO entries" t)
1808 (const :tag "Yes, including all entries" 'all-headlines)
1809 (repeat :tag "Yes, for TODOs in this list"
1810 (string :tag "TODO keyword"))
1811 (other :tag "No TODO statistics" nil)))
1813 (defcustom org-hierarchical-todo-statistics t
1814 "Non-nil means, TODO statistics covers just direct children.
1815 When nil, all entries in the subtree are considered.
1816 This has only an effect if `org-provide-todo-statistics' is set.
1817 To set this to nil for only a single subtree, use a COOKIE_DATA
1818 property and include the word \"recursive\" into the value."
1819 :group 'org-todo
1820 :type 'boolean)
1822 (defcustom org-after-todo-state-change-hook nil
1823 "Hook which is run after the state of a TODO item was changed.
1824 The new state (a string with a TODO keyword, or nil) is available in the
1825 Lisp variable `state'."
1826 :group 'org-todo
1827 :type 'hook)
1829 (defvar org-blocker-hook nil
1830 "Hook for functions that are allowed to block a state change.
1832 Each function gets as its single argument a property list, see
1833 `org-trigger-hook' for more information about this list.
1835 If any of the functions in this hook returns nil, the state change
1836 is blocked.")
1838 (defvar org-trigger-hook nil
1839 "Hook for functions that are triggered by a state change.
1841 Each function gets as its single argument a property list with at least
1842 the following elements:
1844 (:type type-of-change :position pos-at-entry-start
1845 :from old-state :to new-state)
1847 Depending on the type, more properties may be present.
1849 This mechanism is currently implemented for:
1851 TODO state changes
1852 ------------------
1853 :type todo-state-change
1854 :from previous state (keyword as a string), or nil, or a symbol
1855 'todo' or 'done', to indicate the general type of state.
1856 :to new state, like in :from")
1858 (defcustom org-enforce-todo-dependencies nil
1859 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1860 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1861 be blocked if any prior sibling is not yet done.
1862 Finally, if the parent is blocked because of ordered siblings of its own,
1863 the child will also be blocked.
1864 This variable needs to be set before org.el is loaded, and you need to
1865 restart Emacs after a change to make the change effective. The only way
1866 to change is while Emacs is running is through the customize interface."
1867 :set (lambda (var val)
1868 (set var val)
1869 (if val
1870 (add-hook 'org-blocker-hook
1871 'org-block-todo-from-children-or-siblings-or-parent)
1872 (remove-hook 'org-blocker-hook
1873 'org-block-todo-from-children-or-siblings-or-parent)))
1874 :group 'org-todo
1875 :type 'boolean)
1877 (defcustom org-enforce-todo-checkbox-dependencies nil
1878 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1879 When this is nil, checkboxes have no influence on switching TODO states.
1880 When non-nil, you first need to check off all check boxes before the TODO
1881 entry can be switched to DONE.
1882 This variable needs to be set before org.el is loaded, and you need to
1883 restart Emacs after a change to make the change effective. The only way
1884 to change is while Emacs is running is through the customize interface."
1885 :set (lambda (var val)
1886 (set var val)
1887 (if val
1888 (add-hook 'org-blocker-hook
1889 'org-block-todo-from-checkboxes)
1890 (remove-hook 'org-blocker-hook
1891 'org-block-todo-from-checkboxes)))
1892 :group 'org-todo
1893 :type 'boolean)
1895 (defcustom org-treat-insert-todo-heading-as-state-change nil
1896 "Non-nil means, inserting a TODO heading is treated as state change.
1897 So when the command \\[org-insert-todo-heading] is used, state change
1898 logging will apply if appropriate. When nil, the new TODO item will
1899 be inserted directly, and no logging will take place."
1900 :group 'org-todo
1901 :type 'boolean)
1903 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1904 "Non-nil means, switching TODO states with S-cursor counts as state change.
1905 This is the default behavior. However, setting this to nil allows a
1906 convenient way to select a TODO state and bypass any logging associated
1907 with that."
1908 :group 'org-todo
1909 :type 'boolean)
1911 (defcustom org-todo-state-tags-triggers nil
1912 "Tag changes that should be triggered by TODO state changes.
1913 This is a list. Each entry is
1915 (state-change (tag . flag) .......)
1917 State-change can be a string with a state, and empty string to indicate the
1918 state that has no TODO keyword, or it can be one of the symbols `todo'
1919 or `done', meaning any not-done or done state, respectively."
1920 :group 'org-todo
1921 :group 'org-tags
1922 :type '(repeat
1923 (cons (choice :tag "When changing to"
1924 (const :tag "Not-done state" todo)
1925 (const :tag "Done state" done)
1926 (string :tag "State"))
1927 (repeat
1928 (cons :tag "Tag action"
1929 (string :tag "Tag")
1930 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1932 (defcustom org-log-done nil
1933 "Information to record when a task moves to the DONE state.
1935 Possible values are:
1937 nil Don't add anything, just change the keyword
1938 time Add a time stamp to the task
1939 note Prompt a closing note and add it with template `org-log-note-headings'
1941 This option can also be set with on a per-file-basis with
1943 #+STARTUP: nologdone
1944 #+STARTUP: logdone
1945 #+STARTUP: lognotedone
1947 You can have local logging settings for a subtree by setting the LOGGING
1948 property to one or more of these keywords."
1949 :group 'org-todo
1950 :group 'org-progress
1951 :type '(choice
1952 (const :tag "No logging" nil)
1953 (const :tag "Record CLOSED timestamp" time)
1954 (const :tag "Record CLOSED timestamp with closing note." note)))
1956 ;; Normalize old uses of org-log-done.
1957 (cond
1958 ((eq org-log-done t) (setq org-log-done 'time))
1959 ((and (listp org-log-done) (memq 'done org-log-done))
1960 (setq org-log-done 'note)))
1962 (defcustom org-log-note-clock-out nil
1963 "Non-nil means, record a note when clocking out of an item.
1964 This can also be configured on a per-file basis by adding one of
1965 the following lines anywhere in the buffer:
1967 #+STARTUP: lognoteclock-out
1968 #+STARTUP: nolognoteclock-out"
1969 :group 'org-todo
1970 :group 'org-progress
1971 :type 'boolean)
1973 (defcustom org-log-done-with-time t
1974 "Non-nil means, the CLOSED time stamp will contain date and time.
1975 When nil, only the date will be recorded."
1976 :group 'org-progress
1977 :type 'boolean)
1979 (defcustom org-log-note-headings
1980 '((done . "CLOSING NOTE %t")
1981 (state . "State %-12s from %-12S %t")
1982 (note . "Note taken on %t")
1983 (clock-out . ""))
1984 "Headings for notes added to entries.
1985 The value is an alist, with the car being a symbol indicating the note
1986 context, and the cdr is the heading to be used. The heading may also be the
1987 empty string.
1988 %t in the heading will be replaced by a time stamp.
1989 %s will be replaced by the new TODO state, in double quotes.
1990 %S will be replaced by the old TODO state, in double quotes.
1991 %u will be replaced by the user name.
1992 %U will be replaced by the full user name."
1993 :group 'org-todo
1994 :group 'org-progress
1995 :type '(list :greedy t
1996 (cons (const :tag "Heading when closing an item" done) string)
1997 (cons (const :tag
1998 "Heading when changing todo state (todo sequence only)"
1999 state) string)
2000 (cons (const :tag "Heading when just taking a note" note) string)
2001 (cons (const :tag "Heading when clocking out" clock-out) string)))
2003 (unless (assq 'note org-log-note-headings)
2004 (push '(note . "%t") org-log-note-headings))
2006 (defcustom org-log-into-drawer nil
2007 "Non-nil means, insert state change notes and time stamps into a drawer.
2008 When nil, state changes notes will be inserted after the headline and
2009 any scheduling and clock lines, but not inside a drawer.
2011 The value of this variable should be the name of the drawer to use.
2012 LOGBOOK is proposed at the default drawer for this purpose, you can
2013 also set this to a string to define the drawer of your choice.
2015 A value of t is also allowed, representing \"LOGBOOK\".
2017 If this variable is set, `org-log-state-notes-insert-after-drawers'
2018 will be ignored.
2020 You can set the property LOG_INTO_DRAWER to overrule this setting for
2021 a subtree."
2022 :group 'org-todo
2023 :group 'org-progress
2024 :type '(choice
2025 (const :tag "Not into a drawer" nil)
2026 (const :tag "LOGBOOK" t)
2027 (string :tag "Other")))
2029 (if (fboundp 'defvaralias)
2030 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2032 (defun org-log-into-drawer ()
2033 "Return the value of `org-log-into-drawer', but let properties overrule.
2034 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2035 used instead of the default value."
2036 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2037 (cond
2038 ((or (not p) (equal p "nil")) org-log-into-drawer)
2039 ((equal p "t") "LOGBOOK")
2040 (t p))))
2042 (defcustom org-log-state-notes-insert-after-drawers nil
2043 "Non-nil means, insert state change notes after any drawers in entry.
2044 Only the drawers that *immediately* follow the headline and the
2045 deadline/scheduled line are skipped.
2046 When nil, insert notes right after the heading and perhaps the line
2047 with deadline/scheduling if present.
2049 This variable will have no effect if `org-log-into-drawer' is
2050 set."
2051 :group 'org-todo
2052 :group 'org-progress
2053 :type 'boolean)
2055 (defcustom org-log-states-order-reversed t
2056 "Non-nil means, the latest state change note will be directly after heading.
2057 When nil, the notes will be orderer according to time."
2058 :group 'org-todo
2059 :group 'org-progress
2060 :type 'boolean)
2062 (defcustom org-log-repeat 'time
2063 "Non-nil means, record moving through the DONE state when triggering repeat.
2064 An auto-repeating task is immediately switched back to TODO when
2065 marked DONE. If you are not logging state changes (by adding \"@\"
2066 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2067 record a closing note, there will be no record of the task moving
2068 through DONE. This variable forces taking a note anyway.
2070 nil Don't force a record
2071 time Record a time stamp
2072 note Record a note
2074 This option can also be set with on a per-file-basis with
2076 #+STARTUP: logrepeat
2077 #+STARTUP: lognoterepeat
2078 #+STARTUP: nologrepeat
2080 You can have local logging settings for a subtree by setting the LOGGING
2081 property to one or more of these keywords."
2082 :group 'org-todo
2083 :group 'org-progress
2084 :type '(choice
2085 (const :tag "Don't force a record" nil)
2086 (const :tag "Force recording the DONE state" time)
2087 (const :tag "Force recording a note with the DONE state" note)))
2090 (defgroup org-priorities nil
2091 "Priorities in Org-mode."
2092 :tag "Org Priorities"
2093 :group 'org-todo)
2095 (defcustom org-enable-priority-commands t
2096 "Non-nil means, priority commands are active.
2097 When nil, these commands will be disabled, so that you never accidentally
2098 set a priority."
2099 :group 'org-priorities
2100 :type 'boolean)
2102 (defcustom org-highest-priority ?A
2103 "The highest priority of TODO items. A character like ?A, ?B etc.
2104 Must have a smaller ASCII number than `org-lowest-priority'."
2105 :group 'org-priorities
2106 :type 'character)
2108 (defcustom org-lowest-priority ?C
2109 "The lowest priority of TODO items. A character like ?A, ?B etc.
2110 Must have a larger ASCII number than `org-highest-priority'."
2111 :group 'org-priorities
2112 :type 'character)
2114 (defcustom org-default-priority ?B
2115 "The default priority of TODO items.
2116 This is the priority an item get if no explicit priority is given."
2117 :group 'org-priorities
2118 :type 'character)
2120 (defcustom org-priority-start-cycle-with-default t
2121 "Non-nil means, start with default priority when starting to cycle.
2122 When this is nil, the first step in the cycle will be (depending on the
2123 command used) one higher or lower that the default priority."
2124 :group 'org-priorities
2125 :type 'boolean)
2127 (defgroup org-time nil
2128 "Options concerning time stamps and deadlines in Org-mode."
2129 :tag "Org Time"
2130 :group 'org)
2132 (defcustom org-insert-labeled-timestamps-at-point nil
2133 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2134 When nil, these labeled time stamps are forces into the second line of an
2135 entry, just after the headline. When scheduling from the global TODO list,
2136 the time stamp will always be forced into the second line."
2137 :group 'org-time
2138 :type 'boolean)
2140 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2141 "Formats for `format-time-string' which are used for time stamps.
2142 It is not recommended to change this constant.")
2144 (defcustom org-time-stamp-rounding-minutes '(0 5)
2145 "Number of minutes to round time stamps to.
2146 These are two values, the first applies when first creating a time stamp.
2147 The second applies when changing it with the commands `S-up' and `S-down'.
2148 When changing the time stamp, this means that it will change in steps
2149 of N minutes, as given by the second value.
2151 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2152 numbers should be factors of 60, so for example 5, 10, 15.
2154 When this is larger than 1, you can still force an exact time-stamp by using
2155 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2156 and by using a prefix arg to `S-up/down' to specify the exact number
2157 of minutes to shift."
2158 :group 'org-time
2159 :get '(lambda (var) ; Make sure all entries have 5 elements
2160 (if (integerp (default-value var))
2161 (list (default-value var) 5)
2162 (default-value var)))
2163 :type '(list
2164 (integer :tag "when inserting times")
2165 (integer :tag "when modifying times")))
2167 ;; Normalize old customizations of this variable.
2168 (when (integerp org-time-stamp-rounding-minutes)
2169 (setq org-time-stamp-rounding-minutes
2170 (list org-time-stamp-rounding-minutes
2171 org-time-stamp-rounding-minutes)))
2173 (defcustom org-display-custom-times nil
2174 "Non-nil means, overlay custom formats over all time stamps.
2175 The formats are defined through the variable `org-time-stamp-custom-formats'.
2176 To turn this on on a per-file basis, insert anywhere in the file:
2177 #+STARTUP: customtime"
2178 :group 'org-time
2179 :set 'set-default
2180 :type 'sexp)
2181 (make-variable-buffer-local 'org-display-custom-times)
2183 (defcustom org-time-stamp-custom-formats
2184 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2185 "Custom formats for time stamps. See `format-time-string' for the syntax.
2186 These are overlayed over the default ISO format if the variable
2187 `org-display-custom-times' is set. Time like %H:%M should be at the
2188 end of the second format. The custom formats are also honored by export
2189 commands, if custom time display is turned on at the time of export."
2190 :group 'org-time
2191 :type 'sexp)
2193 (defun org-time-stamp-format (&optional long inactive)
2194 "Get the right format for a time string."
2195 (let ((f (if long (cdr org-time-stamp-formats)
2196 (car org-time-stamp-formats))))
2197 (if inactive
2198 (concat "[" (substring f 1 -1) "]")
2199 f)))
2201 (defcustom org-time-clocksum-format "%d:%02d"
2202 "The format string used when creating CLOCKSUM lines, or when
2203 org-mode generates a time duration."
2204 :group 'org-time
2205 :type 'string)
2207 (defcustom org-time-clocksum-use-fractional nil
2208 "If non-nil, \\[org-clock-display] uses fractional times.
2209 org-mode generates a time duration."
2210 :group 'org-time
2211 :type 'boolean)
2213 (defcustom org-time-clocksum-fractional-format "%.2f"
2214 "The format string used when creating CLOCKSUM lines, or when
2215 org-mode generates a time duration."
2216 :group 'org-time
2217 :type 'string)
2219 (defcustom org-deadline-warning-days 14
2220 "No. of days before expiration during which a deadline becomes active.
2221 This variable governs the display in sparse trees and in the agenda.
2222 When 0 or negative, it means use this number (the absolute value of it)
2223 even if a deadline has a different individual lead time specified.
2225 Custom commands can set this variable in the options section."
2226 :group 'org-time
2227 :group 'org-agenda-daily/weekly
2228 :type 'integer)
2230 (defcustom org-read-date-prefer-future t
2231 "Non-nil means, assume future for incomplete date input from user.
2232 This affects the following situations:
2233 1. The user gives a month but not a year.
2234 For example, if it is april and you enter \"feb 2\", this will be read
2235 as feb 2, *next* year. \"May 5\", however, will be this year.
2236 2. The user gives a day, but no month.
2237 For example, if today is the 15th, and you enter \"3\", Org-mode will
2238 read this as the third of *next* month. However, if you enter \"17\",
2239 it will be considered as *this* month.
2241 If you set this variable to the symbol `time', then also the following
2242 will work:
2244 3. If the user gives a time, but no day. If the time is before now,
2245 to will be interpreted as tomorrow.
2247 Currently none of this works for ISO week specifications.
2249 When this option is nil, the current day, month and year will always be
2250 used as defaults."
2251 :group 'org-time
2252 :type '(choice
2253 (const :tag "Never" nil)
2254 (const :tag "Check month and day" t)
2255 (const :tag "Check month, day, and time" time)))
2257 (defcustom org-read-date-display-live t
2258 "Non-nil means, display current interpretation of date prompt live.
2259 This display will be in an overlay, in the minibuffer."
2260 :group 'org-time
2261 :type 'boolean)
2263 (defcustom org-read-date-popup-calendar t
2264 "Non-nil means, pop up a calendar when prompting for a date.
2265 In the calendar, the date can be selected with mouse-1. However, the
2266 minibuffer will also be active, and you can simply enter the date as well.
2267 When nil, only the minibuffer will be available."
2268 :group 'org-time
2269 :type 'boolean)
2270 (if (fboundp 'defvaralias)
2271 (defvaralias 'org-popup-calendar-for-date-prompt
2272 'org-read-date-popup-calendar))
2274 (defcustom org-read-date-minibuffer-setup-hook nil
2275 "Hook to be used to set up keys for the date/time interface.
2276 Add key definitions to `minibuffer-local-map', which will be a temporary
2277 copy."
2278 :group 'org-time
2279 :type 'hook)
2281 (defcustom org-extend-today-until 0
2282 "The hour when your day really ends. Must be an integer.
2283 This has influence for the following applications:
2284 - When switching the agenda to \"today\". It it is still earlier than
2285 the time given here, the day recognized as TODAY is actually yesterday.
2286 - When a date is read from the user and it is still before the time given
2287 here, the current date and time will be assumed to be yesterday, 23:59.
2288 Also, timestamps inserted in remember templates follow this rule.
2290 IMPORTANT: This is a feature whose implementation is and likely will
2291 remain incomplete. Really, it is only here because past midnight seems to
2292 be the favorite working time of John Wiegley :-)"
2293 :group 'org-time
2294 :type 'integer)
2296 (defcustom org-edit-timestamp-down-means-later nil
2297 "Non-nil means, S-down will increase the time in a time stamp.
2298 When nil, S-up will increase."
2299 :group 'org-time
2300 :type 'boolean)
2302 (defcustom org-calendar-follow-timestamp-change t
2303 "Non-nil means, make the calendar window follow timestamp changes.
2304 When a timestamp is modified and the calendar window is visible, it will be
2305 moved to the new date."
2306 :group 'org-time
2307 :type 'boolean)
2309 (defgroup org-tags nil
2310 "Options concerning tags in Org-mode."
2311 :tag "Org Tags"
2312 :group 'org)
2314 (defcustom org-tag-alist nil
2315 "List of tags allowed in Org-mode files.
2316 When this list is nil, Org-mode will base TAG input on what is already in the
2317 buffer.
2318 The value of this variable is an alist, the car of each entry must be a
2319 keyword as a string, the cdr may be a character that is used to select
2320 that tag through the fast-tag-selection interface.
2321 See the manual for details."
2322 :group 'org-tags
2323 :type '(repeat
2324 (choice
2325 (cons (string :tag "Tag name")
2326 (character :tag "Access char"))
2327 (list :tag "Start radio group"
2328 (const :startgroup)
2329 (option (string :tag "Group description")))
2330 (list :tag "End radio group"
2331 (const :endgroup)
2332 (option (string :tag "Group description")))
2333 (const :tag "New line" (:newline)))))
2335 (defcustom org-tag-persistent-alist nil
2336 "List of tags that will always appear in all Org-mode files.
2337 This is in addition to any in buffer settings or customizations
2338 of `org-tag-alist'.
2339 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2340 The value of this variable is an alist, the car of each entry must be a
2341 keyword as a string, the cdr may be a character that is used to select
2342 that tag through the fast-tag-selection interface.
2343 See the manual for details.
2344 To disable these tags on a per-file basis, insert anywhere in the file:
2345 #+STARTUP: noptag"
2346 :group 'org-tags
2347 :type '(repeat
2348 (choice
2349 (cons (string :tag "Tag name")
2350 (character :tag "Access char"))
2351 (const :tag "Start radio group" (:startgroup))
2352 (const :tag "End radio group" (:endgroup))
2353 (const :tag "New line" (:newline)))))
2355 (defvar org-file-tags nil
2356 "List of tags that can be inherited by all entries in the file.
2357 The tags will be inherited if the variable `org-use-tag-inheritance'
2358 says they should be.
2359 This variable is populated from #+FILETAGS lines.")
2361 (defcustom org-use-fast-tag-selection 'auto
2362 "Non-nil means, use fast tag selection scheme.
2363 This is a special interface to select and deselect tags with single keys.
2364 When nil, fast selection is never used.
2365 When the symbol `auto', fast selection is used if and only if selection
2366 characters for tags have been configured, either through the variable
2367 `org-tag-alist' or through a #+TAGS line in the buffer.
2368 When t, fast selection is always used and selection keys are assigned
2369 automatically if necessary."
2370 :group 'org-tags
2371 :type '(choice
2372 (const :tag "Always" t)
2373 (const :tag "Never" nil)
2374 (const :tag "When selection characters are configured" 'auto)))
2376 (defcustom org-fast-tag-selection-single-key nil
2377 "Non-nil means, fast tag selection exits after first change.
2378 When nil, you have to press RET to exit it.
2379 During fast tag selection, you can toggle this flag with `C-c'.
2380 This variable can also have the value `expert'. In this case, the window
2381 displaying the tags menu is not even shown, until you press C-c again."
2382 :group 'org-tags
2383 :type '(choice
2384 (const :tag "No" nil)
2385 (const :tag "Yes" t)
2386 (const :tag "Expert" expert)))
2388 (defvar org-fast-tag-selection-include-todo nil
2389 "Non-nil means, fast tags selection interface will also offer TODO states.
2390 This is an undocumented feature, you should not rely on it.")
2392 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2393 "The column to which tags should be indented in a headline.
2394 If this number is positive, it specifies the column. If it is negative,
2395 it means that the tags should be flushright to that column. For example,
2396 -80 works well for a normal 80 character screen."
2397 :group 'org-tags
2398 :type 'integer)
2400 (defcustom org-auto-align-tags t
2401 "Non-nil means, realign tags after pro/demotion of TODO state change.
2402 These operations change the length of a headline and therefore shift
2403 the tags around. With this options turned on, after each such operation
2404 the tags are again aligned to `org-tags-column'."
2405 :group 'org-tags
2406 :type 'boolean)
2408 (defcustom org-use-tag-inheritance t
2409 "Non-nil means, tags in levels apply also for sublevels.
2410 When nil, only the tags directly given in a specific line apply there.
2411 This may also be a list of tags that should be inherited, or a regexp that
2412 matches tags that should be inherited. Additional control is possible
2413 with the variable `org-tags-exclude-from-inheritance' which gives an
2414 explicit list of tags to be excluded from inheritance., even if the value of
2415 `org-use-tag-inheritance' would select it for inheritance.
2417 If this option is t, a match early-on in a tree can lead to a large
2418 number of matches in the subtree when constructing the agenda or creating
2419 a sparse tree. If you only want to see the first match in a tree during
2420 a search, check out the variable `org-tags-match-list-sublevels'."
2421 :group 'org-tags
2422 :type '(choice
2423 (const :tag "Not" nil)
2424 (const :tag "Always" t)
2425 (repeat :tag "Specific tags" (string :tag "Tag"))
2426 (regexp :tag "Tags matched by regexp")))
2428 (defcustom org-tags-exclude-from-inheritance nil
2429 "List of tags that should never be inherited.
2430 This is a way to exclude a few tags from inheritance. For way to do
2431 the opposite, to actively allow inheritance for selected tags,
2432 see the variable `org-use-tag-inheritance'."
2433 :group 'org-tags
2434 :type '(repeat (string :tag "Tag")))
2436 (defun org-tag-inherit-p (tag)
2437 "Check if TAG is one that should be inherited."
2438 (cond
2439 ((member tag org-tags-exclude-from-inheritance) nil)
2440 ((eq org-use-tag-inheritance t) t)
2441 ((not org-use-tag-inheritance) nil)
2442 ((stringp org-use-tag-inheritance)
2443 (string-match org-use-tag-inheritance tag))
2444 ((listp org-use-tag-inheritance)
2445 (member tag org-use-tag-inheritance))
2446 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2448 (defcustom org-tags-match-list-sublevels t
2449 "Non-nil means list also sublevels of headlines matching a search.
2450 This variable applies to tags/property searches, and also to stuck
2451 projects because this search is based on a tags match as well.
2453 When set to the symbol `indented', sublevels are indented with
2454 leading dots.
2456 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2457 the sublevels of a headline matching a tag search often also match
2458 the same search. Listing all of them can create very long lists.
2459 Setting this variable to nil causes subtrees of a match to be skipped.
2461 This variable is semi-obsolete and probably should always be true. It
2462 is better to limit inheritance to certain tags using the variables
2463 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2464 :group 'org-tags
2465 :type '(choice
2466 (const :tag "No, don't list them" nil)
2467 (const :tag "Yes, do list them" t)
2468 (const :tag "List them, indented with leading dots" indented)))
2470 (defcustom org-tags-sort-function nil
2471 "When set, tags are sorted using this function as a comparator"
2472 :group 'org-tags
2473 :type '(choice
2474 (const :tag "No sorting" nil)
2475 (const :tag "Alphabetical" string<)
2476 (const :tag "Reverse alphabetical" string>)
2477 (function :tag "Custom function" nil)))
2479 (defvar org-tags-history nil
2480 "History of minibuffer reads for tags.")
2481 (defvar org-last-tags-completion-table nil
2482 "The last used completion table for tags.")
2483 (defvar org-after-tags-change-hook nil
2484 "Hook that is run after the tags in a line have changed.")
2486 (defgroup org-properties nil
2487 "Options concerning properties in Org-mode."
2488 :tag "Org Properties"
2489 :group 'org)
2491 (defcustom org-property-format "%-10s %s"
2492 "How property key/value pairs should be formatted by `indent-line'.
2493 When `indent-line' hits a property definition, it will format the line
2494 according to this format, mainly to make sure that the values are
2495 lined-up with respect to each other."
2496 :group 'org-properties
2497 :type 'string)
2499 (defcustom org-use-property-inheritance nil
2500 "Non-nil means, properties apply also for sublevels.
2502 This setting is chiefly used during property searches. Turning it on can
2503 cause significant overhead when doing a search, which is why it is not
2504 on by default.
2506 When nil, only the properties directly given in the current entry count.
2507 When t, every property is inherited. The value may also be a list of
2508 properties that should have inheritance, or a regular expression matching
2509 properties that should be inherited.
2511 However, note that some special properties use inheritance under special
2512 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2513 and the properties ending in \"_ALL\" when they are used as descriptor
2514 for valid values of a property.
2516 Note for programmers:
2517 When querying an entry with `org-entry-get', you can control if inheritance
2518 should be used. By default, `org-entry-get' looks only at the local
2519 properties. You can request inheritance by setting the inherit argument
2520 to t (to force inheritance) or to `selective' (to respect the setting
2521 in this variable)."
2522 :group 'org-properties
2523 :type '(choice
2524 (const :tag "Not" nil)
2525 (const :tag "Always" t)
2526 (repeat :tag "Specific properties" (string :tag "Property"))
2527 (regexp :tag "Properties matched by regexp")))
2529 (defun org-property-inherit-p (property)
2530 "Check if PROPERTY is one that should be inherited."
2531 (cond
2532 ((eq org-use-property-inheritance t) t)
2533 ((not org-use-property-inheritance) nil)
2534 ((stringp org-use-property-inheritance)
2535 (string-match org-use-property-inheritance property))
2536 ((listp org-use-property-inheritance)
2537 (member property org-use-property-inheritance))
2538 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2540 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2541 "The default column format, if no other format has been defined.
2542 This variable can be set on the per-file basis by inserting a line
2544 #+COLUMNS: %25ITEM ....."
2545 :group 'org-properties
2546 :type 'string)
2548 (defcustom org-columns-ellipses ".."
2549 "The ellipses to be used when a field in column view is truncated.
2550 When this is the empty string, as many characters as possible are shown,
2551 but then there will be no visual indication that the field has been truncated.
2552 When this is a string of length N, the last N characters of a truncated
2553 field are replaced by this string. If the column is narrower than the
2554 ellipses string, only part of the ellipses string will be shown."
2555 :group 'org-properties
2556 :type 'string)
2558 (defcustom org-columns-modify-value-for-display-function nil
2559 "Function that modifies values for display in column view.
2560 For example, it can be used to cut out a certain part from a time stamp.
2561 The function must take 2 arguments:
2563 column-title The title of the column (*not* the property name)
2564 value The value that should be modified.
2566 The function should return the value that should be displayed,
2567 or nil if the normal value should be used."
2568 :group 'org-properties
2569 :type 'function)
2571 (defcustom org-effort-property "Effort"
2572 "The property that is being used to keep track of effort estimates.
2573 Effort estimates given in this property need to have the format H:MM."
2574 :group 'org-properties
2575 :group 'org-progress
2576 :type '(string :tag "Property"))
2578 (defconst org-global-properties-fixed
2579 '(("VISIBILITY_ALL" . "folded children content all")
2580 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2581 "List of property/value pairs that can be inherited by any entry.
2583 These are fixed values, for the preset properties. The user variable
2584 that can be used to add to this list is `org-global-properties'.
2586 The entries in this list are cons cells where the car is a property
2587 name and cdr is a string with the value. If the value represents
2588 multiple items like an \"_ALL\" property, separate the items by
2589 spaces.")
2591 (defcustom org-global-properties nil
2592 "List of property/value pairs that can be inherited by any entry.
2594 This list will be combined with the constant `org-global-properties-fixed'.
2596 The entries in this list are cons cells where the car is a property
2597 name and cdr is a string with the value.
2599 You can set buffer-local values for the same purpose in the variable
2600 `org-file-properties' this by adding lines like
2602 #+PROPERTY: NAME VALUE"
2603 :group 'org-properties
2604 :type '(repeat
2605 (cons (string :tag "Property")
2606 (string :tag "Value"))))
2608 (defvar org-file-properties nil
2609 "List of property/value pairs that can be inherited by any entry.
2610 Valid for the current buffer.
2611 This variable is populated from #+PROPERTY lines.")
2612 (make-variable-buffer-local 'org-file-properties)
2614 (defgroup org-agenda nil
2615 "Options concerning agenda views in Org-mode."
2616 :tag "Org Agenda"
2617 :group 'org)
2619 (defvar org-category nil
2620 "Variable used by org files to set a category for agenda display.
2621 Such files should use a file variable to set it, for example
2623 # -*- mode: org; org-category: \"ELisp\"
2625 or contain a special line
2627 #+CATEGORY: ELisp
2629 If the file does not specify a category, then file's base name
2630 is used instead.")
2631 (make-variable-buffer-local 'org-category)
2632 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2634 (defcustom org-agenda-files nil
2635 "The files to be used for agenda display.
2636 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2637 \\[org-remove-file]. You can also use customize to edit the list.
2639 If an entry is a directory, all files in that directory that are matched by
2640 `org-agenda-file-regexp' will be part of the file list.
2642 If the value of the variable is not a list but a single file name, then
2643 the list of agenda files is actually stored and maintained in that file, one
2644 agenda file per line."
2645 :group 'org-agenda
2646 :type '(choice
2647 (repeat :tag "List of files and directories" file)
2648 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2650 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2651 "Regular expression to match files for `org-agenda-files'.
2652 If any element in the list in that variable contains a directory instead
2653 of a normal file, all files in that directory that are matched by this
2654 regular expression will be included."
2655 :group 'org-agenda
2656 :type 'regexp)
2658 (defcustom org-agenda-text-search-extra-files nil
2659 "List of extra files to be searched by text search commands.
2660 These files will be search in addition to the agenda files by the
2661 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2662 Note that these files will only be searched for text search commands,
2663 not for the other agenda views like todo lists, tag searches or the weekly
2664 agenda. This variable is intended to list notes and possibly archive files
2665 that should also be searched by these two commands.
2666 In fact, if the first element in the list is the symbol `agenda-archives',
2667 than all archive files of all agenda files will be added to the search
2668 scope."
2669 :group 'org-agenda
2670 :type '(set :greedy t
2671 (const :tag "Agenda Archives" agenda-archives)
2672 (repeat :inline t (file))))
2674 (if (fboundp 'defvaralias)
2675 (defvaralias 'org-agenda-multi-occur-extra-files
2676 'org-agenda-text-search-extra-files))
2678 (defcustom org-agenda-skip-unavailable-files nil
2679 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2680 A nil value means to remove them, after a query, from the list."
2681 :group 'org-agenda
2682 :type 'boolean)
2684 (defcustom org-calendar-to-agenda-key [?c]
2685 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2686 The command `org-calendar-goto-agenda' will be bound to this key. The
2687 default is the character `c' because then `c' can be used to switch back and
2688 forth between agenda and calendar."
2689 :group 'org-agenda
2690 :type 'sexp)
2692 (defcustom org-calendar-agenda-action-key [?k]
2693 "The key to be installed in `calendar-mode-map' for agenda-action.
2694 The command `org-agenda-action' will be bound to this key. The
2695 default is the character `k' because we use the same key in the agenda."
2696 :group 'org-agenda
2697 :type 'sexp)
2699 (eval-after-load "calendar"
2700 '(progn
2701 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2702 'org-calendar-goto-agenda)
2703 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2704 'org-agenda-action)))
2706 (defgroup org-latex nil
2707 "Options for embedding LaTeX code into Org-mode."
2708 :tag "Org LaTeX"
2709 :group 'org)
2711 (defcustom org-format-latex-options
2712 '(:foreground default :background default :scale 1.0
2713 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2714 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2715 "Options for creating images from LaTeX fragments.
2716 This is a property list with the following properties:
2717 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2718 `default' means use the foreground of the default face.
2719 :background the background color, or \"Transparent\".
2720 `default' means use the background of the default face.
2721 :scale a scaling factor for the size of the images.
2722 :html-foreground, :html-background, :html-scale
2723 the same numbers for HTML export.
2724 :matchers a list indicating which matchers should be used to
2725 find LaTeX fragments. Valid members of this list are:
2726 \"begin\" find environments
2727 \"$1\" find single characters surrounded by $.$
2728 \"$\" find math expressions surrounded by $...$
2729 \"$$\" find math expressions surrounded by $$....$$
2730 \"\\(\" find math expressions surrounded by \\(...\\)
2731 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2732 :group 'org-latex
2733 :type 'plist)
2735 (defcustom org-format-latex-header "\\documentclass{article}
2736 \\usepackage{amssymb}
2737 \\usepackage[usenames]{color}
2738 \\usepackage{amsmath}
2739 \\usepackage{latexsym}
2740 \\usepackage[mathscr]{eucal}
2741 \\pagestyle{empty} % do not remove
2742 % The settings below are copied from fullpage.sty
2743 \\setlength{\\textwidth}{\\paperwidth}
2744 \\addtolength{\\textwidth}{-3cm}
2745 \\setlength{\\oddsidemargin}{1.5cm}
2746 \\addtolength{\\oddsidemargin}{-2.54cm}
2747 \\setlength{\\evensidemargin}{\\oddsidemargin}
2748 \\setlength{\\textheight}{\\paperheight}
2749 \\addtolength{\\textheight}{-\\headheight}
2750 \\addtolength{\\textheight}{-\\headsep}
2751 \\addtolength{\\textheight}{-\\footskip}
2752 \\addtolength{\\textheight}{-3cm}
2753 \\setlength{\\topmargin}{1.5cm}
2754 \\addtolength{\\topmargin}{-2.54cm}"
2755 "The document header used for processing LaTeX fragments.
2756 It is imperative that this header make sure that no page number
2757 appears on the page."
2758 :group 'org-latex
2759 :type 'string)
2762 (defgroup org-font-lock nil
2763 "Font-lock settings for highlighting in Org-mode."
2764 :tag "Org Font Lock"
2765 :group 'org)
2767 (defcustom org-level-color-stars-only nil
2768 "Non-nil means fontify only the stars in each headline.
2769 When nil, the entire headline is fontified.
2770 Changing it requires restart of `font-lock-mode' to become effective
2771 also in regions already fontified."
2772 :group 'org-font-lock
2773 :type 'boolean)
2775 (defcustom org-hide-leading-stars nil
2776 "Non-nil means, hide the first N-1 stars in a headline.
2777 This works by using the face `org-hide' for these stars. This
2778 face is white for a light background, and black for a dark
2779 background. You may have to customize the face `org-hide' to
2780 make this work.
2781 Changing it requires restart of `font-lock-mode' to become effective
2782 also in regions already fontified.
2783 You may also set this on a per-file basis by adding one of the following
2784 lines to the buffer:
2786 #+STARTUP: hidestars
2787 #+STARTUP: showstars"
2788 :group 'org-font-lock
2789 :type 'boolean)
2791 (defcustom org-fontify-done-headline nil
2792 "Non-nil means, change the face of a headline if it is marked DONE.
2793 Normally, only the TODO/DONE keyword indicates the state of a headline.
2794 When this is non-nil, the headline after the keyword is set to the
2795 `org-headline-done' as an additional indication."
2796 :group 'org-font-lock
2797 :type 'boolean)
2799 (defcustom org-fontify-emphasized-text t
2800 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2801 Changing this variable requires a restart of Emacs to take effect."
2802 :group 'org-font-lock
2803 :type 'boolean)
2805 (defcustom org-fontify-whole-heading-line nil
2806 "Non-nil means fontify the whole line for headings.
2807 This is useful when setting a background color for the
2808 org-leve-* faces."
2809 :group 'org-font-lock
2810 :type 'boolean)
2812 (defcustom org-highlight-latex-fragments-and-specials nil
2813 "Non-nil means, fontify what is treated specially by the exporters."
2814 :group 'org-font-lock
2815 :type 'boolean)
2817 (defcustom org-hide-emphasis-markers nil
2818 "Non-nil mean font-lock should hide the emphasis marker characters."
2819 :group 'org-font-lock
2820 :type 'boolean)
2822 (defvar org-emph-re nil
2823 "Regular expression for matching emphasis.")
2824 (defvar org-verbatim-re nil
2825 "Regular expression for matching verbatim text.")
2826 (defvar org-emphasis-regexp-components) ; defined just below
2827 (defvar org-emphasis-alist) ; defined just below
2828 (defun org-set-emph-re (var val)
2829 "Set variable and compute the emphasis regular expression."
2830 (set var val)
2831 (when (and (boundp 'org-emphasis-alist)
2832 (boundp 'org-emphasis-regexp-components)
2833 org-emphasis-alist org-emphasis-regexp-components)
2834 (let* ((e org-emphasis-regexp-components)
2835 (pre (car e))
2836 (post (nth 1 e))
2837 (border (nth 2 e))
2838 (body (nth 3 e))
2839 (nl (nth 4 e))
2840 (body1 (concat body "*?"))
2841 (markers (mapconcat 'car org-emphasis-alist ""))
2842 (vmarkers (mapconcat
2843 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2844 org-emphasis-alist "")))
2845 ;; make sure special characters appear at the right position in the class
2846 (if (string-match "\\^" markers)
2847 (setq markers (concat (replace-match "" t t markers) "^")))
2848 (if (string-match "-" markers)
2849 (setq markers (concat (replace-match "" t t markers) "-")))
2850 (if (string-match "\\^" vmarkers)
2851 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2852 (if (string-match "-" vmarkers)
2853 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2854 (if (> nl 0)
2855 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2856 (int-to-string nl) "\\}")))
2857 ;; Make the regexp
2858 (setq org-emph-re
2859 (concat "\\([" pre "]\\|^\\)"
2860 "\\("
2861 "\\([" markers "]\\)"
2862 "\\("
2863 "[^" border "]\\|"
2864 "[^" border "]"
2865 body1
2866 "[^" border "]"
2867 "\\)"
2868 "\\3\\)"
2869 "\\([" post "]\\|$\\)"))
2870 (setq org-verbatim-re
2871 (concat "\\([" pre "]\\|^\\)"
2872 "\\("
2873 "\\([" vmarkers "]\\)"
2874 "\\("
2875 "[^" border "]\\|"
2876 "[^" border "]"
2877 body1
2878 "[^" border "]"
2879 "\\)"
2880 "\\3\\)"
2881 "\\([" post "]\\|$\\)")))))
2883 (defcustom org-emphasis-regexp-components
2884 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
2885 "Components used to build the regular expression for emphasis.
2886 This is a list with 6 entries. Terminology: In an emphasis string
2887 like \" *strong word* \", we call the initial space PREMATCH, the final
2888 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2889 and \"trong wor\" is the body. The different components in this variable
2890 specify what is allowed/forbidden in each part:
2892 pre Chars allowed as prematch. Beginning of line will be allowed too.
2893 post Chars allowed as postmatch. End of line will be allowed too.
2894 border The chars *forbidden* as border characters.
2895 body-regexp A regexp like \".\" to match a body character. Don't use
2896 non-shy groups here, and don't allow newline here.
2897 newline The maximum number of newlines allowed in an emphasis exp.
2899 Use customize to modify this, or restart Emacs after changing it."
2900 :group 'org-font-lock
2901 :set 'org-set-emph-re
2902 :type '(list
2903 (sexp :tag "Allowed chars in pre ")
2904 (sexp :tag "Allowed chars in post ")
2905 (sexp :tag "Forbidden chars in border ")
2906 (sexp :tag "Regexp for body ")
2907 (integer :tag "number of newlines allowed")
2908 (option (boolean :tag "Please ignore this button"))))
2910 (defcustom org-emphasis-alist
2911 `(("*" bold "<b>" "</b>")
2912 ("/" italic "<i>" "</i>")
2913 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2914 ("=" org-code "<code>" "</code>" verbatim)
2915 ("~" org-verbatim "<code>" "</code>" verbatim)
2916 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2917 "<del>" "</del>")
2919 "Special syntax for emphasized text.
2920 Text starting and ending with a special character will be emphasized, for
2921 example *bold*, _underlined_ and /italic/. This variable sets the marker
2922 characters, the face to be used by font-lock for highlighting in Org-mode
2923 Emacs buffers, and the HTML tags to be used for this.
2924 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2925 Use customize to modify this, or restart Emacs after changing it."
2926 :group 'org-font-lock
2927 :set 'org-set-emph-re
2928 :type '(repeat
2929 (list
2930 (string :tag "Marker character")
2931 (choice
2932 (face :tag "Font-lock-face")
2933 (plist :tag "Face property list"))
2934 (string :tag "HTML start tag")
2935 (string :tag "HTML end tag")
2936 (option (const verbatim)))))
2938 (defvar org-protecting-blocks
2939 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
2940 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
2941 This is needed for font-lock setup.")
2943 ;;; Miscellaneous options
2945 (defgroup org-completion nil
2946 "Completion in Org-mode."
2947 :tag "Org Completion"
2948 :group 'org)
2950 (defcustom org-completion-use-ido nil
2951 "Non-nil means, use ido completion wherever possible.
2952 Note that `ido-mode' must be active for this variable to be relevant.
2953 If you decide to turn this variable on, you might well want to turn off
2954 `org-outline-path-complete-in-steps'.
2955 See also `org-completion-use-iswitchb'."
2956 :group 'org-completion
2957 :type 'boolean)
2959 (defcustom org-completion-use-iswitchb nil
2960 "Non-nil means, use iswitchb completion wherever possible.
2961 Note that `iswitchb-mode' must be active for this variable to be relevant.
2962 If you decide to turn this variable on, you might well want to turn off
2963 `org-outline-path-complete-in-steps'.
2964 Note that thi variable has only an effect if `org-completion-use-ido' is nil."
2965 :group 'org-completion
2966 :type 'boolean)
2968 (defcustom org-completion-fallback-command 'hippie-expand
2969 "The expansion command called by \\[org-complete] in normal context.
2970 Normal means, no org-mode-specific context."
2971 :group 'org-completion
2972 :type 'function)
2974 ;;; Functions and variables from ther packages
2975 ;; Declared here to avoid compiler warnings
2977 ;; XEmacs only
2978 (defvar outline-mode-menu-heading)
2979 (defvar outline-mode-menu-show)
2980 (defvar outline-mode-menu-hide)
2981 (defvar zmacs-regions) ; XEmacs regions
2983 ;; Emacs only
2984 (defvar mark-active)
2986 ;; Various packages
2987 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2988 (declare-function calendar-forward-day "cal-move" (arg))
2989 (declare-function calendar-goto-date "cal-move" (date))
2990 (declare-function calendar-goto-today "cal-move" ())
2991 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2992 (defvar calc-embedded-close-formula)
2993 (defvar calc-embedded-open-formula)
2994 (declare-function cdlatex-tab "ext:cdlatex" ())
2995 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2996 (defvar font-lock-unfontify-region-function)
2997 (declare-function iswitchb-read-buffer "iswitchb"
2998 (prompt &optional default require-match start matches-set))
2999 (defvar iswitchb-temp-buflist)
3000 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3001 (defvar org-agenda-tags-todo-honor-ignore-options)
3002 (declare-function org-agenda-skip "org-agenda" ())
3003 (declare-function org-format-agenda-item "org-agenda"
3004 (extra txt &optional category tags dotime noprefix remove-re))
3005 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3006 (declare-function org-agenda-change-all-lines "org-agenda"
3007 (newhead hdmarker &optional fixface just-this))
3008 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3009 (declare-function org-agenda-maybe-redo "org-agenda" ())
3010 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3011 (beg end))
3012 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3013 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3014 "org-agenda" (&optional end))
3015 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3016 (declare-function org-indent-mode "org-indent" (&optional arg))
3017 (declare-function parse-time-string "parse-time" (string))
3018 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3019 (defvar remember-data-file)
3020 (defvar texmathp-why)
3021 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3022 (declare-function table--at-cell-p "table" (position &optional object at-column))
3024 (defvar w3m-current-url)
3025 (defvar w3m-current-title)
3027 (defvar org-latex-regexps)
3029 ;;; Autoload and prepare some org modules
3031 ;; Some table stuff that needs to be defined here, because it is used
3032 ;; by the functions setting up org-mode or checking for table context.
3034 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3035 "Detects an org-type or table-type table.")
3036 (defconst org-table-line-regexp "^[ \t]*|"
3037 "Detects an org-type table line.")
3038 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3039 "Detects an org-type table line.")
3040 (defconst org-table-hline-regexp "^[ \t]*|-"
3041 "Detects an org-type table hline.")
3042 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3043 "Detects a table-type table hline.")
3044 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3045 "Searching from within a table (any type) this finds the first line
3046 outside the table.")
3048 ;; Autoload the functions in org-table.el that are needed by functions here.
3050 (eval-and-compile
3051 (org-autoload "org-table"
3052 '(org-table-align org-table-begin org-table-blank-field
3053 org-table-convert org-table-convert-region org-table-copy-down
3054 org-table-copy-region org-table-create
3055 org-table-create-or-convert-from-region
3056 org-table-create-with-table.el org-table-current-dline
3057 org-table-cut-region org-table-delete-column org-table-edit-field
3058 org-table-edit-formulas org-table-end org-table-eval-formula
3059 org-table-export org-table-field-info
3060 org-table-get-stored-formulas org-table-goto-column
3061 org-table-hline-and-move org-table-import org-table-insert-column
3062 org-table-insert-hline org-table-insert-row org-table-iterate
3063 org-table-justify-field-maybe org-table-kill-row
3064 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3065 org-table-move-column org-table-move-column-left
3066 org-table-move-column-right org-table-move-row
3067 org-table-move-row-down org-table-move-row-up
3068 org-table-next-field org-table-next-row org-table-paste-rectangle
3069 org-table-previous-field org-table-recalculate
3070 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3071 org-table-toggle-coordinate-overlays
3072 org-table-toggle-formula-debugger org-table-wrap-region
3073 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3075 (defun org-at-table-p (&optional table-type)
3076 "Return t if the cursor is inside an org-type table.
3077 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3078 (if org-enable-table-editor
3079 (save-excursion
3080 (beginning-of-line 1)
3081 (looking-at (if table-type org-table-any-line-regexp
3082 org-table-line-regexp)))
3083 nil))
3084 (defsubst org-table-p () (org-at-table-p))
3086 (defun org-at-table.el-p ()
3087 "Return t if and only if we are at a table.el table."
3088 (and (org-at-table-p 'any)
3089 (save-excursion
3090 (goto-char (org-table-begin 'any))
3091 (looking-at org-table1-hline-regexp))))
3092 (defun org-table-recognize-table.el ()
3093 "If there is a table.el table nearby, recognize it and move into it."
3094 (if org-table-tab-recognizes-table.el
3095 (if (org-at-table.el-p)
3096 (progn
3097 (beginning-of-line 1)
3098 (if (looking-at org-table-dataline-regexp)
3100 (if (looking-at org-table1-hline-regexp)
3101 (progn
3102 (beginning-of-line 2)
3103 (if (looking-at org-table-any-border-regexp)
3104 (beginning-of-line -1)))))
3105 (if (re-search-forward "|" (org-table-end t) t)
3106 (progn
3107 (require 'table)
3108 (if (table--at-cell-p (point))
3110 (message "recognizing table.el table...")
3111 (table-recognize-table)
3112 (message "recognizing table.el table...done")))
3113 (error "This should not happen..."))
3115 nil)
3116 nil))
3118 (defun org-at-table-hline-p ()
3119 "Return t if the cursor is inside a hline in a table."
3120 (if org-enable-table-editor
3121 (save-excursion
3122 (beginning-of-line 1)
3123 (looking-at org-table-hline-regexp))
3124 nil))
3126 (defvar org-table-clean-did-remove-column nil)
3128 (defun org-table-map-tables (function)
3129 "Apply FUNCTION to the start of all tables in the buffer."
3130 (save-excursion
3131 (save-restriction
3132 (widen)
3133 (goto-char (point-min))
3134 (while (re-search-forward org-table-any-line-regexp nil t)
3135 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3136 (beginning-of-line 1)
3137 (when (looking-at org-table-line-regexp)
3138 (save-excursion (funcall function))
3139 (or (looking-at org-table-line-regexp)
3140 (forward-char 1)))
3141 (re-search-forward org-table-any-border-regexp nil 1))))
3142 (message "Mapping tables: done"))
3144 ;; Declare and autoload functions from org-exp.el & Co
3146 (declare-function org-default-export-plist "org-exp")
3147 (declare-function org-infile-export-plist "org-exp")
3148 (declare-function org-get-current-options "org-exp")
3149 (eval-and-compile
3150 (org-autoload "org-exp"
3151 '(org-export org-export-visible
3152 org-insert-export-options-template
3153 org-table-clean-before-export))
3154 (org-autoload "org-ascii"
3155 '(org-export-as-ascii org-export-ascii-preprocess
3156 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3157 org-export-region-as-ascii))
3158 (org-autoload "org-html"
3159 '(org-export-as-html-and-open
3160 org-export-as-html-batch org-export-as-html-to-buffer
3161 org-replace-region-by-html org-export-region-as-html
3162 org-export-as-html))
3163 (org-autoload "org-icalendar"
3164 '(org-export-icalendar-this-file
3165 org-export-icalendar-all-agenda-files
3166 org-export-icalendar-combine-agenda-files))
3167 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3169 ;; Declare and autoload functions from org-agenda.el
3171 (eval-and-compile
3172 (org-autoload "org-agenda"
3173 '(org-agenda org-agenda-list org-search-view
3174 org-todo-list org-tags-view org-agenda-list-stuck-projects
3175 org-diary org-agenda-to-appt
3176 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3178 ;; Autoload org-remember
3180 (eval-and-compile
3181 (org-autoload "org-remember"
3182 '(org-remember-insinuate org-remember-annotation
3183 org-remember-apply-template org-remember org-remember-handler)))
3185 ;; Autoload org-clock.el
3188 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3189 (beg end))
3190 (declare-function org-clock-update-mode-line "org-clock" ())
3191 (declare-function org-resolve-clocks "org-clock"
3192 (&optional also-non-dangling-p prompt last-valid))
3193 (defvar org-clock-start-time)
3194 (defvar org-clock-marker (make-marker)
3195 "Marker recording the last clock-in.")
3196 (defvar org-clock-hd-marker (make-marker)
3197 "Marker recording the last clock-in, but the headline position.")
3198 (defun org-clock-is-active ()
3199 "Return non-nil if clock is currently running.
3200 The return value is actually the clock marker."
3201 (marker-buffer org-clock-marker))
3203 (eval-and-compile
3204 (org-autoload
3205 "org-clock"
3206 '(org-clock-in org-clock-out org-clock-cancel
3207 org-clock-goto org-clock-sum org-clock-display
3208 org-clock-remove-overlays org-clock-report
3209 org-clocktable-shift org-dblock-write:clocktable
3210 org-get-clocktable org-resolve-clocks)))
3212 (defun org-clock-update-time-maybe ()
3213 "If this is a CLOCK line, update it and return t.
3214 Otherwise, return nil."
3215 (interactive)
3216 (save-excursion
3217 (beginning-of-line 1)
3218 (skip-chars-forward " \t")
3219 (when (looking-at org-clock-string)
3220 (let ((re (concat "[ \t]*" org-clock-string
3221 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3222 "\\([ \t]*=>.*\\)?\\)?"))
3223 ts te h m s neg)
3224 (cond
3225 ((not (looking-at re))
3226 nil)
3227 ((not (match-end 2))
3228 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3229 (> org-clock-marker (point))
3230 (<= org-clock-marker (point-at-eol)))
3231 ;; The clock is running here
3232 (setq org-clock-start-time
3233 (apply 'encode-time
3234 (org-parse-time-string (match-string 1))))
3235 (org-clock-update-mode-line)))
3237 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3238 (end-of-line 1)
3239 (setq ts (match-string 1)
3240 te (match-string 3))
3241 (setq s (- (org-float-time
3242 (apply 'encode-time (org-parse-time-string te)))
3243 (org-float-time
3244 (apply 'encode-time (org-parse-time-string ts))))
3245 neg (< s 0)
3246 s (abs s)
3247 h (floor (/ s 3600))
3248 s (- s (* 3600 h))
3249 m (floor (/ s 60))
3250 s (- s (* 60 s)))
3251 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3252 t))))))
3254 (defun org-check-running-clock ()
3255 "Check if the current buffer contains the running clock.
3256 If yes, offer to stop it and to save the buffer with the changes."
3257 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3258 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3259 (buffer-name))))
3260 (org-clock-out)
3261 (when (y-or-n-p "Save changed buffer?")
3262 (save-buffer))))
3264 (defun org-clocktable-try-shift (dir n)
3265 "Check if this line starts a clock table, if yes, shift the time block."
3266 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3267 (org-clocktable-shift dir n)))
3269 ;; Autoload org-timer.el
3271 (eval-and-compile
3272 (org-autoload
3273 "org-timer"
3274 '(org-timer-start org-timer org-timer-item
3275 org-timer-change-times-in-region
3276 org-timer-set-timer
3277 org-timer-reset-timers
3278 org-timer-show-remaining-time)))
3280 ;; Autoload org-feed.el
3282 (eval-and-compile
3283 (org-autoload
3284 "org-feed"
3285 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3288 ;; Autoload org-indent.el
3290 (eval-and-compile
3291 (org-autoload
3292 "org-indent"
3293 '(org-indent-mode)))
3295 ;; Autoload org-mobile.el
3297 (eval-and-compile
3298 (org-autoload
3299 "org-mobile"
3300 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3302 ;; Autoload archiving code
3303 ;; The stuff that is needed for cycling and tags has to be defined here.
3305 (defgroup org-archive nil
3306 "Options concerning archiving in Org-mode."
3307 :tag "Org Archive"
3308 :group 'org-structure)
3310 (defcustom org-archive-location "%s_archive::"
3311 "The location where subtrees should be archived.
3313 The value of this variable is a string, consisting of two parts,
3314 separated by a double-colon. The first part is a filename and
3315 the second part is a headline.
3317 When the filename is omitted, archiving happens in the same file.
3318 %s in the filename will be replaced by the current file
3319 name (without the directory part). Archiving to a different file
3320 is useful to keep archived entries from contributing to the
3321 Org-mode Agenda.
3323 The archived entries will be filed as subtrees of the specified
3324 headline. When the headline is omitted, the subtrees are simply
3325 filed away at the end of the file, as top-level entries. Also in
3326 the heading you can use %s to represent the file name, this can be
3327 useful when using the same archive for a number of different files.
3329 Here are a few examples:
3330 \"%s_archive::\"
3331 If the current file is Projects.org, archive in file
3332 Projects.org_archive, as top-level trees. This is the default.
3334 \"::* Archived Tasks\"
3335 Archive in the current file, under the top-level headline
3336 \"* Archived Tasks\".
3338 \"~/org/archive.org::\"
3339 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3341 \"~/org/archive.org::From %s\"
3342 Archive in file ~/org/archive.org (absolute path), und headlines
3343 \"From FILENAME\" where file name is the current file name.
3345 \"basement::** Finished Tasks\"
3346 Archive in file ./basement (relative path), as level 3 trees
3347 below the level 2 heading \"** Finished Tasks\".
3349 You may set this option on a per-file basis by adding to the buffer a
3350 line like
3352 #+ARCHIVE: basement::** Finished Tasks
3354 You may also define it locally for a subtree by setting an ARCHIVE property
3355 in the entry. If such a property is found in an entry, or anywhere up
3356 the hierarchy, it will be used."
3357 :group 'org-archive
3358 :type 'string)
3360 (defcustom org-archive-tag "ARCHIVE"
3361 "The tag that marks a subtree as archived.
3362 An archived subtree does not open during visibility cycling, and does
3363 not contribute to the agenda listings.
3364 After changing this, font-lock must be restarted in the relevant buffers to
3365 get the proper fontification."
3366 :group 'org-archive
3367 :group 'org-keywords
3368 :type 'string)
3370 (defcustom org-agenda-skip-archived-trees t
3371 "Non-nil means, the agenda will skip any items located in archived trees.
3372 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3373 variable is no longer recommended, you should leave it at the value t.
3374 Instead, use the key `v' to cycle the archives-mode in the agenda."
3375 :group 'org-archive
3376 :group 'org-agenda-skip
3377 :type 'boolean)
3379 (defcustom org-columns-skip-arrchived-trees t
3380 "Non-nil means, irgnore archived trees when creating column view."
3381 :group 'org-archive
3382 :group 'org-properties
3383 :type 'boolean)
3385 (defcustom org-cycle-open-archived-trees nil
3386 "Non-nil means, `org-cycle' will open archived trees.
3387 An archived tree is a tree marked with the tag ARCHIVE.
3388 When nil, archived trees will stay folded. You can still open them with
3389 normal outline commands like `show-all', but not with the cycling commands."
3390 :group 'org-archive
3391 :group 'org-cycle
3392 :type 'boolean)
3394 (defcustom org-sparse-tree-open-archived-trees nil
3395 "Non-nil means sparse tree construction shows matches in archived trees.
3396 When nil, matches in these trees are highlighted, but the trees are kept in
3397 collapsed state."
3398 :group 'org-archive
3399 :group 'org-sparse-trees
3400 :type 'boolean)
3402 (defun org-cycle-hide-archived-subtrees (state)
3403 "Re-hide all archived subtrees after a visibility state change."
3404 (when (and (not org-cycle-open-archived-trees)
3405 (not (memq state '(overview folded))))
3406 (save-excursion
3407 (let* ((globalp (memq state '(contents all)))
3408 (beg (if globalp (point-min) (point)))
3409 (end (if globalp (point-max) (org-end-of-subtree t))))
3410 (org-hide-archived-subtrees beg end)
3411 (goto-char beg)
3412 (if (looking-at (concat ".*:" org-archive-tag ":"))
3413 (message "%s" (substitute-command-keys
3414 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3416 (defun org-force-cycle-archived ()
3417 "Cycle subtree even if it is archived."
3418 (interactive)
3419 (setq this-command 'org-cycle)
3420 (let ((org-cycle-open-archived-trees t))
3421 (call-interactively 'org-cycle)))
3423 (defun org-hide-archived-subtrees (beg end)
3424 "Re-hide all archived subtrees after a visibility state change."
3425 (save-excursion
3426 (let* ((re (concat ":" org-archive-tag ":")))
3427 (goto-char beg)
3428 (while (re-search-forward re end t)
3429 (and (org-on-heading-p) (hide-subtree))
3430 (org-end-of-subtree t)))))
3432 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3434 (eval-and-compile
3435 (org-autoload "org-archive"
3436 '(org-add-archive-files org-archive-subtree
3437 org-archive-to-archive-sibling org-toggle-archive-tag)))
3439 ;; Autoload Column View Code
3441 (declare-function org-columns-number-to-string "org-colview")
3442 (declare-function org-columns-get-format-and-top-level "org-colview")
3443 (declare-function org-columns-compute "org-colview")
3445 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3446 '(org-columns-number-to-string org-columns-get-format-and-top-level
3447 org-columns-compute org-agenda-columns org-columns-remove-overlays
3448 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3450 ;; Autoload ID code
3452 (declare-function org-id-store-link "org-id")
3453 (declare-function org-id-locations-load "org-id")
3454 (declare-function org-id-locations-save "org-id")
3455 (defvar org-id-track-globally)
3456 (org-autoload "org-id"
3457 '(org-id-get-create org-id-new org-id-copy org-id-get
3458 org-id-get-with-outline-path-completion
3459 org-id-get-with-outline-drilling
3460 org-id-goto org-id-find org-id-store-link))
3462 ;; Autoload Plotting Code
3464 (org-autoload "org-plot"
3465 '(org-plot/gnuplot))
3467 ;;; Variables for pre-computed regular expressions, all buffer local
3469 (defvar org-drawer-regexp nil
3470 "Matches first line of a hidden block.")
3471 (make-variable-buffer-local 'org-drawer-regexp)
3472 (defvar org-todo-regexp nil
3473 "Matches any of the TODO state keywords.")
3474 (make-variable-buffer-local 'org-todo-regexp)
3475 (defvar org-not-done-regexp nil
3476 "Matches any of the TODO state keywords except the last one.")
3477 (make-variable-buffer-local 'org-not-done-regexp)
3478 (defvar org-not-done-heading-regexp nil
3479 "Matches a TODO headline that is not done.")
3480 (make-variable-buffer-local 'org-not-done-regexp)
3481 (defvar org-todo-line-regexp nil
3482 "Matches a headline and puts TODO state into group 2 if present.")
3483 (make-variable-buffer-local 'org-todo-line-regexp)
3484 (defvar org-complex-heading-regexp nil
3485 "Matches a headline and puts everything into groups:
3486 group 1: the stars
3487 group 2: The todo keyword, maybe
3488 group 3: Priority cookie
3489 group 4: True headline
3490 group 5: Tags")
3491 (make-variable-buffer-local 'org-complex-heading-regexp)
3492 (defvar org-complex-heading-regexp-format nil)
3493 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3494 (defvar org-todo-line-tags-regexp nil
3495 "Matches a headline and puts TODO state into group 2 if present.
3496 Also put tags into group 4 if tags are present.")
3497 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3498 (defvar org-nl-done-regexp nil
3499 "Matches newline followed by a headline with the DONE keyword.")
3500 (make-variable-buffer-local 'org-nl-done-regexp)
3501 (defvar org-looking-at-done-regexp nil
3502 "Matches the DONE keyword a point.")
3503 (make-variable-buffer-local 'org-looking-at-done-regexp)
3504 (defvar org-ds-keyword-length 12
3505 "Maximum length of the Deadline and SCHEDULED keywords.")
3506 (make-variable-buffer-local 'org-ds-keyword-length)
3507 (defvar org-deadline-regexp nil
3508 "Matches the DEADLINE keyword.")
3509 (make-variable-buffer-local 'org-deadline-regexp)
3510 (defvar org-deadline-time-regexp nil
3511 "Matches the DEADLINE keyword together with a time stamp.")
3512 (make-variable-buffer-local 'org-deadline-time-regexp)
3513 (defvar org-deadline-line-regexp nil
3514 "Matches the DEADLINE keyword and the rest of the line.")
3515 (make-variable-buffer-local 'org-deadline-line-regexp)
3516 (defvar org-scheduled-regexp nil
3517 "Matches the SCHEDULED keyword.")
3518 (make-variable-buffer-local 'org-scheduled-regexp)
3519 (defvar org-scheduled-time-regexp nil
3520 "Matches the SCHEDULED keyword together with a time stamp.")
3521 (make-variable-buffer-local 'org-scheduled-time-regexp)
3522 (defvar org-closed-time-regexp nil
3523 "Matches the CLOSED keyword together with a time stamp.")
3524 (make-variable-buffer-local 'org-closed-time-regexp)
3526 (defvar org-keyword-time-regexp nil
3527 "Matches any of the 4 keywords, together with the time stamp.")
3528 (make-variable-buffer-local 'org-keyword-time-regexp)
3529 (defvar org-keyword-time-not-clock-regexp nil
3530 "Matches any of the 3 keywords, together with the time stamp.")
3531 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3532 (defvar org-maybe-keyword-time-regexp nil
3533 "Matches a timestamp, possibly preceeded by a keyword.")
3534 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3535 (defvar org-planning-or-clock-line-re nil
3536 "Matches a line with planning or clock info.")
3537 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3539 (defconst org-plain-time-of-day-regexp
3540 (concat
3541 "\\(\\<[012]?[0-9]"
3542 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3543 "\\(--?"
3544 "\\(\\<[012]?[0-9]"
3545 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3546 "\\)?")
3547 "Regular expression to match a plain time or time range.
3548 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3549 groups carry important information:
3550 0 the full match
3551 1 the first time, range or not
3552 8 the second time, if it is a range.")
3554 (defconst org-plain-time-extension-regexp
3555 (concat
3556 "\\(\\<[012]?[0-9]"
3557 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3558 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3559 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3560 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3561 groups carry important information:
3562 0 the full match
3563 7 hours of duration
3564 9 minutes of duration")
3566 (defconst org-stamp-time-of-day-regexp
3567 (concat
3568 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3569 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3570 "\\(--?"
3571 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3572 "Regular expression to match a timestamp time or time range.
3573 After a match, the following groups carry important information:
3574 0 the full match
3575 1 date plus weekday, for backreferencing to make sure both times on same day
3576 2 the first time, range or not
3577 4 the second time, if it is a range.")
3579 (defconst org-startup-options
3580 '(("fold" org-startup-folded t)
3581 ("overview" org-startup-folded t)
3582 ("nofold" org-startup-folded nil)
3583 ("showall" org-startup-folded nil)
3584 ("showeverything" org-startup-folded showeverything)
3585 ("content" org-startup-folded content)
3586 ("indent" org-startup-indented t)
3587 ("noindent" org-startup-indented nil)
3588 ("hidestars" org-hide-leading-stars t)
3589 ("showstars" org-hide-leading-stars nil)
3590 ("odd" org-odd-levels-only t)
3591 ("oddeven" org-odd-levels-only nil)
3592 ("align" org-startup-align-all-tables t)
3593 ("noalign" org-startup-align-all-tables nil)
3594 ("customtime" org-display-custom-times t)
3595 ("logdone" org-log-done time)
3596 ("lognotedone" org-log-done note)
3597 ("nologdone" org-log-done nil)
3598 ("lognoteclock-out" org-log-note-clock-out t)
3599 ("nolognoteclock-out" org-log-note-clock-out nil)
3600 ("logrepeat" org-log-repeat state)
3601 ("lognoterepeat" org-log-repeat note)
3602 ("nologrepeat" org-log-repeat nil)
3603 ("fninline" org-footnote-define-inline t)
3604 ("nofninline" org-footnote-define-inline nil)
3605 ("fnlocal" org-footnote-section nil)
3606 ("fnauto" org-footnote-auto-label t)
3607 ("fnprompt" org-footnote-auto-label nil)
3608 ("fnconfirm" org-footnote-auto-label confirm)
3609 ("fnplain" org-footnote-auto-label plain)
3610 ("fnadjust" org-footnote-auto-adjust t)
3611 ("nofnadjust" org-footnote-auto-adjust nil)
3612 ("constcgs" constants-unit-system cgs)
3613 ("constSI" constants-unit-system SI)
3614 ("noptag" org-tag-persistent-alist nil)
3615 ("hideblocks" org-hide-block-startup t)
3616 ("nohideblocks" org-hide-block-startup nil))
3617 "Variable associated with STARTUP options for org-mode.
3618 Each element is a list of three items: The startup options as written
3619 in the #+STARTUP line, the corresponding variable, and the value to
3620 set this variable to if the option is found. An optional forth element PUSH
3621 means to push this value onto the list in the variable.")
3623 (defun org-set-regexps-and-options ()
3624 "Precompute regular expressions for current buffer."
3625 (when (org-mode-p)
3626 (org-set-local 'org-todo-kwd-alist nil)
3627 (org-set-local 'org-todo-key-alist nil)
3628 (org-set-local 'org-todo-key-trigger nil)
3629 (org-set-local 'org-todo-keywords-1 nil)
3630 (org-set-local 'org-done-keywords nil)
3631 (org-set-local 'org-todo-heads nil)
3632 (org-set-local 'org-todo-sets nil)
3633 (org-set-local 'org-todo-log-states nil)
3634 (org-set-local 'org-file-properties nil)
3635 (org-set-local 'org-file-tags nil)
3636 (let ((re (org-make-options-regexp
3637 '("CATEGORY" "TODO" "COLUMNS"
3638 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3639 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3640 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3641 (splitre "[ \t]+")
3642 kwds kws0 kwsa key log value cat arch tags const links hw dws
3643 tail sep kws1 prio props ftags drawers
3644 ext-setup-or-nil setup-contents (start 0))
3645 (save-excursion
3646 (save-restriction
3647 (widen)
3648 (goto-char (point-min))
3649 (while (or (and ext-setup-or-nil
3650 (string-match re ext-setup-or-nil start)
3651 (setq start (match-end 0)))
3652 (and (setq ext-setup-or-nil nil start 0)
3653 (re-search-forward re nil t)))
3654 (setq key (upcase (match-string 1 ext-setup-or-nil))
3655 value (org-match-string-no-properties 2 ext-setup-or-nil))
3656 (cond
3657 ((equal key "CATEGORY")
3658 (if (string-match "[ \t]+$" value)
3659 (setq value (replace-match "" t t value)))
3660 (setq cat value))
3661 ((member key '("SEQ_TODO" "TODO"))
3662 (push (cons 'sequence (org-split-string value splitre)) kwds))
3663 ((equal key "TYP_TODO")
3664 (push (cons 'type (org-split-string value splitre)) kwds))
3665 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3666 ;; general TODO-like setup
3667 (push (cons (intern (downcase (match-string 1 key)))
3668 (org-split-string value splitre)) kwds))
3669 ((equal key "TAGS")
3670 (setq tags (append tags (if tags '("\\n") nil)
3671 (org-split-string value splitre))))
3672 ((equal key "COLUMNS")
3673 (org-set-local 'org-columns-default-format value))
3674 ((equal key "LINK")
3675 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3676 (push (cons (match-string 1 value)
3677 (org-trim (match-string 2 value)))
3678 links)))
3679 ((equal key "PRIORITIES")
3680 (setq prio (org-split-string value " +")))
3681 ((equal key "PROPERTY")
3682 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3683 (push (cons (match-string 1 value) (match-string 2 value))
3684 props)))
3685 ((equal key "FILETAGS")
3686 (when (string-match "\\S-" value)
3687 (setq ftags
3688 (append
3689 ftags
3690 (apply 'append
3691 (mapcar (lambda (x) (org-split-string x ":"))
3692 (org-split-string value)))))))
3693 ((equal key "DRAWERS")
3694 (setq drawers (org-split-string value splitre)))
3695 ((equal key "CONSTANTS")
3696 (setq const (append const (org-split-string value splitre))))
3697 ((equal key "STARTUP")
3698 (let ((opts (org-split-string value splitre))
3699 l var val)
3700 (while (setq l (pop opts))
3701 (when (setq l (assoc l org-startup-options))
3702 (setq var (nth 1 l) val (nth 2 l))
3703 (if (not (nth 3 l))
3704 (set (make-local-variable var) val)
3705 (if (not (listp (symbol-value var)))
3706 (set (make-local-variable var) nil))
3707 (set (make-local-variable var) (symbol-value var))
3708 (add-to-list var val))))))
3709 ((equal key "ARCHIVE")
3710 (string-match " *$" value)
3711 (setq arch (replace-match "" t t value))
3712 (remove-text-properties 0 (length arch)
3713 '(face t fontified t) arch))
3714 ((equal key "SETUPFILE")
3715 (setq setup-contents (org-file-contents
3716 (expand-file-name
3717 (org-remove-double-quotes value))
3718 'noerror))
3719 (if (not ext-setup-or-nil)
3720 (setq ext-setup-or-nil setup-contents start 0)
3721 (setq ext-setup-or-nil
3722 (concat (substring ext-setup-or-nil 0 start)
3723 "\n" setup-contents "\n"
3724 (substring ext-setup-or-nil start)))))
3725 ))))
3726 (when cat
3727 (org-set-local 'org-category (intern cat))
3728 (push (cons "CATEGORY" cat) props))
3729 (when prio
3730 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3731 (setq prio (mapcar 'string-to-char prio))
3732 (org-set-local 'org-highest-priority (nth 0 prio))
3733 (org-set-local 'org-lowest-priority (nth 1 prio))
3734 (org-set-local 'org-default-priority (nth 2 prio)))
3735 (and props (org-set-local 'org-file-properties (nreverse props)))
3736 (and ftags (org-set-local 'org-file-tags
3737 (mapcar 'org-add-prop-inherited ftags)))
3738 (and drawers (org-set-local 'org-drawers drawers))
3739 (and arch (org-set-local 'org-archive-location arch))
3740 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3741 ;; Process the TODO keywords
3742 (unless kwds
3743 ;; Use the global values as if they had been given locally.
3744 (setq kwds (default-value 'org-todo-keywords))
3745 (if (stringp (car kwds))
3746 (setq kwds (list (cons org-todo-interpretation
3747 (default-value 'org-todo-keywords)))))
3748 (setq kwds (reverse kwds)))
3749 (setq kwds (nreverse kwds))
3750 (let (inter kws kw)
3751 (while (setq kws (pop kwds))
3752 (let ((kws (or
3753 (run-hook-with-args-until-success
3754 'org-todo-setup-filter-hook kws)
3755 kws)))
3756 (setq inter (pop kws) sep (member "|" kws)
3757 kws0 (delete "|" (copy-sequence kws))
3758 kwsa nil
3759 kws1 (mapcar
3760 (lambda (x)
3761 ;; 1 2
3762 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3763 (progn
3764 (setq kw (match-string 1 x)
3765 key (and (match-end 2) (match-string 2 x))
3766 log (org-extract-log-state-settings x))
3767 (push (cons kw (and key (string-to-char key))) kwsa)
3768 (and log (push log org-todo-log-states))
3770 (error "Invalid TODO keyword %s" x)))
3771 kws0)
3772 kwsa (if kwsa (append '((:startgroup))
3773 (nreverse kwsa)
3774 '((:endgroup))))
3775 hw (car kws1)
3776 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3777 tail (list inter hw (car dws) (org-last dws))))
3778 (add-to-list 'org-todo-heads hw 'append)
3779 (push kws1 org-todo-sets)
3780 (setq org-done-keywords (append org-done-keywords dws nil))
3781 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3782 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3783 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3784 (setq org-todo-sets (nreverse org-todo-sets)
3785 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3786 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3787 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3788 ;; Process the constants
3789 (when const
3790 (let (e cst)
3791 (while (setq e (pop const))
3792 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3793 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3794 (setq org-table-formula-constants-local cst)))
3796 ;; Process the tags.
3797 (when tags
3798 (let (e tgs)
3799 (while (setq e (pop tags))
3800 (cond
3801 ((equal e "{") (push '(:startgroup) tgs))
3802 ((equal e "}") (push '(:endgroup) tgs))
3803 ((equal e "\\n") (push '(:newline) tgs))
3804 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3805 (push (cons (match-string 1 e)
3806 (string-to-char (match-string 2 e)))
3807 tgs))
3808 (t (push (list e) tgs))))
3809 (org-set-local 'org-tag-alist nil)
3810 (while (setq e (pop tgs))
3811 (or (and (stringp (car e))
3812 (assoc (car e) org-tag-alist))
3813 (push e org-tag-alist)))))
3815 ;; Compute the regular expressions and other local variables
3816 (if (not org-done-keywords)
3817 (setq org-done-keywords (and org-todo-keywords-1
3818 (list (org-last org-todo-keywords-1)))))
3819 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3820 (length org-scheduled-string)
3821 (length org-clock-string)
3822 (length org-closed-string)))
3823 org-drawer-regexp
3824 (concat "^[ \t]*:\\("
3825 (mapconcat 'regexp-quote org-drawers "\\|")
3826 "\\):[ \t]*$")
3827 org-not-done-keywords
3828 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3829 org-todo-regexp
3830 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3831 "\\|") "\\)\\>")
3832 org-not-done-regexp
3833 (concat "\\<\\("
3834 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3835 "\\)\\>")
3836 org-not-done-heading-regexp
3837 (concat "^\\(\\*+\\)[ \t]+\\("
3838 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3839 "\\)\\>")
3840 org-todo-line-regexp
3841 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3842 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3843 "\\)\\>\\)?[ \t]*\\(.*\\)")
3844 org-complex-heading-regexp
3845 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3846 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3847 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3848 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3849 org-complex-heading-regexp-format
3850 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3851 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3852 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
3853 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3854 org-nl-done-regexp
3855 (concat "\n\\*+[ \t]+"
3856 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3857 "\\)" "\\>")
3858 org-todo-line-tags-regexp
3859 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3860 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3861 (org-re
3862 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3863 org-looking-at-done-regexp
3864 (concat "^" "\\(?:"
3865 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3866 "\\>")
3867 org-deadline-regexp (concat "\\<" org-deadline-string)
3868 org-deadline-time-regexp
3869 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3870 org-deadline-line-regexp
3871 (concat "\\<\\(" org-deadline-string "\\).*")
3872 org-scheduled-regexp
3873 (concat "\\<" org-scheduled-string)
3874 org-scheduled-time-regexp
3875 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3876 org-closed-time-regexp
3877 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3878 org-keyword-time-regexp
3879 (concat "\\<\\(" org-scheduled-string
3880 "\\|" org-deadline-string
3881 "\\|" org-closed-string
3882 "\\|" org-clock-string "\\)"
3883 " *[[<]\\([^]>]+\\)[]>]")
3884 org-keyword-time-not-clock-regexp
3885 (concat "\\<\\(" org-scheduled-string
3886 "\\|" org-deadline-string
3887 "\\|" org-closed-string
3888 "\\)"
3889 " *[[<]\\([^]>]+\\)[]>]")
3890 org-maybe-keyword-time-regexp
3891 (concat "\\(\\<\\(" org-scheduled-string
3892 "\\|" org-deadline-string
3893 "\\|" org-closed-string
3894 "\\|" org-clock-string "\\)\\)?"
3895 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3896 org-planning-or-clock-line-re
3897 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3898 "\\|" org-deadline-string
3899 "\\|" org-closed-string "\\|" org-clock-string
3900 "\\)\\>\\)")
3902 (org-compute-latex-and-specials-regexp)
3903 (org-set-font-lock-defaults))))
3905 (defun org-file-contents (file &optional noerror)
3906 "Return the contents of FILE, as a string."
3907 (if (or (not file)
3908 (not (file-readable-p file)))
3909 (if noerror
3910 (progn
3911 (message "Cannot read file %s" file)
3912 (ding) (sit-for 2)
3914 (error "Cannot read file %s" file))
3915 (with-temp-buffer
3916 (insert-file-contents file)
3917 (buffer-string))))
3919 (defun org-extract-log-state-settings (x)
3920 "Extract the log state setting from a TODO keyword string.
3921 This will extract info from a string like \"WAIT(w@/!)\"."
3922 (let (kw key log1 log2)
3923 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3924 (setq kw (match-string 1 x)
3925 key (and (match-end 2) (match-string 2 x))
3926 log1 (and (match-end 3) (match-string 3 x))
3927 log2 (and (match-end 4) (match-string 4 x)))
3928 (and (or log1 log2)
3929 (list kw
3930 (and log1 (if (equal log1 "!") 'time 'note))
3931 (and log2 (if (equal log2 "!") 'time 'note)))))))
3933 (defun org-remove-keyword-keys (list)
3934 "Remove a pair of parenthesis at the end of each string in LIST."
3935 (mapcar (lambda (x)
3936 (if (string-match "(.*)$" x)
3937 (substring x 0 (match-beginning 0))
3939 list))
3941 ;; FIXME: this could be done much better, using second characters etc.
3942 (defun org-assign-fast-keys (alist)
3943 "Assign fast keys to a keyword-key alist.
3944 Respect keys that are already there."
3945 (let (new e k c c1 c2 (char ?a))
3946 (while (setq e (pop alist))
3947 (cond
3948 ((equal e '(:startgroup)) (push e new))
3949 ((equal e '(:endgroup)) (push e new))
3950 ((equal e '(:newline)) (push e new))
3952 (setq k (car e) c2 nil)
3953 (if (cdr e)
3954 (setq c (cdr e))
3955 ;; automatically assign a character.
3956 (setq c1 (string-to-char
3957 (downcase (substring
3958 k (if (= (string-to-char k) ?@) 1 0)))))
3959 (if (or (rassoc c1 new) (rassoc c1 alist))
3960 (while (or (rassoc char new) (rassoc char alist))
3961 (setq char (1+ char)))
3962 (setq c2 c1))
3963 (setq c (or c2 char)))
3964 (push (cons k c) new))))
3965 (nreverse new)))
3967 ;;; Some variables used in various places
3969 (defvar org-window-configuration nil
3970 "Used in various places to store a window configuration.")
3971 (defvar org-selected-window nil
3972 "Used in various places to store a window configuration.")
3973 (defvar org-finish-function nil
3974 "Function to be called when `C-c C-c' is used.
3975 This is for getting out of special buffers like remember.")
3978 ;; FIXME: Occasionally check by commenting these, to make sure
3979 ;; no other functions uses these, forgetting to let-bind them.
3980 (defvar entry)
3981 (defvar last-state)
3982 (defvar date)
3984 ;; Defined somewhere in this file, but used before definition.
3985 (defvar org-html-entities)
3986 (defvar org-struct-menu)
3987 (defvar org-org-menu)
3988 (defvar org-tbl-menu)
3989 (defvar org-agenda-keymap)
3991 ;;;; Define the Org-mode
3993 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3994 (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."))
3997 ;; We use a before-change function to check if a table might need
3998 ;; an update.
3999 (defvar org-table-may-need-update t
4000 "Indicates that a table might need an update.
4001 This variable is set by `org-before-change-function'.
4002 `org-table-align' sets it back to nil.")
4003 (defun org-before-change-function (beg end)
4004 "Every change indicates that a table might need an update."
4005 (setq org-table-may-need-update t))
4006 (defvar org-mode-map)
4007 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4008 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4009 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4010 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4011 (defvar org-table-buffer-is-an nil)
4012 (defconst org-outline-regexp "\\*+ ")
4014 ;;;###autoload
4015 (define-derived-mode org-mode outline-mode "Org"
4016 "Outline-based notes management and organizer, alias
4017 \"Carsten's outline-mode for keeping track of everything.\"
4019 Org-mode develops organizational tasks around a NOTES file which
4020 contains information about projects as plain text. Org-mode is
4021 implemented on top of outline-mode, which is ideal to keep the content
4022 of large files well structured. It supports ToDo items, deadlines and
4023 time stamps, which magically appear in the diary listing of the Emacs
4024 calendar. Tables are easily created with a built-in table editor.
4025 Plain text URL-like links connect to websites, emails (VM), Usenet
4026 messages (Gnus), BBDB entries, and any files related to the project.
4027 For printing and sharing of notes, an Org-mode file (or a part of it)
4028 can be exported as a structured ASCII or HTML file.
4030 The following commands are available:
4032 \\{org-mode-map}"
4034 ;; Get rid of Outline menus, they are not needed
4035 ;; Need to do this here because define-derived-mode sets up
4036 ;; the keymap so late. Still, it is a waste to call this each time
4037 ;; we switch another buffer into org-mode.
4038 (if (featurep 'xemacs)
4039 (when (boundp 'outline-mode-menu-heading)
4040 ;; Assume this is Greg's port, it used easymenu
4041 (easy-menu-remove outline-mode-menu-heading)
4042 (easy-menu-remove outline-mode-menu-show)
4043 (easy-menu-remove outline-mode-menu-hide))
4044 (define-key org-mode-map [menu-bar headings] 'undefined)
4045 (define-key org-mode-map [menu-bar hide] 'undefined)
4046 (define-key org-mode-map [menu-bar show] 'undefined))
4048 (org-load-modules-maybe)
4049 (easy-menu-add org-org-menu)
4050 (easy-menu-add org-tbl-menu)
4051 (org-install-agenda-files-menu)
4052 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4053 (org-add-to-invisibility-spec '(org-cwidth))
4054 (org-add-to-invisibility-spec '(org-hide-block . t))
4055 (when (featurep 'xemacs)
4056 (org-set-local 'line-move-ignore-invisible t))
4057 (org-set-local 'outline-regexp org-outline-regexp)
4058 (org-set-local 'outline-level 'org-outline-level)
4059 (when (and org-ellipsis
4060 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4061 (fboundp 'make-glyph-code))
4062 (unless org-display-table
4063 (setq org-display-table (make-display-table)))
4064 (set-display-table-slot
4065 org-display-table 4
4066 (vconcat (mapcar
4067 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4068 org-ellipsis)))
4069 (if (stringp org-ellipsis) org-ellipsis "..."))))
4070 (setq buffer-display-table org-display-table))
4071 (org-set-regexps-and-options)
4072 (when (and org-tag-faces (not org-tags-special-faces-re))
4073 ;; tag faces set outside customize.... force initialization.
4074 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4075 ;; Calc embedded
4076 (org-set-local 'calc-embedded-open-mode "# ")
4077 (modify-syntax-entry ?# "<")
4078 (modify-syntax-entry ?@ "w")
4079 (if org-startup-truncated (setq truncate-lines t))
4080 (org-set-local 'font-lock-unfontify-region-function
4081 'org-unfontify-region)
4082 ;; Activate before-change-function
4083 (org-set-local 'org-table-may-need-update t)
4084 (org-add-hook 'before-change-functions 'org-before-change-function nil
4085 'local)
4086 ;; Check for running clock before killing a buffer
4087 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4088 ;; Paragraphs and auto-filling
4089 (org-set-autofill-regexps)
4090 (setq indent-line-function 'org-indent-line-function)
4091 (org-update-radio-target-regexp)
4092 ;; Make sure dependence stuff works reliably, even for users who set it
4093 ;; too late :-(
4094 (if org-enforce-todo-dependencies
4095 (add-hook 'org-blocker-hook
4096 'org-block-todo-from-children-or-siblings-or-parent)
4097 (remove-hook 'org-blocker-hook
4098 'org-block-todo-from-children-or-siblings-or-parent))
4099 (if org-enforce-todo-checkbox-dependencies
4100 (add-hook 'org-blocker-hook
4101 'org-block-todo-from-checkboxes)
4102 (remove-hook 'org-blocker-hook
4103 'org-block-todo-from-checkboxes))
4105 ;; Comment characters
4106 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4107 (org-set-local 'comment-padding " ")
4109 ;; Align options lines
4110 (org-set-local
4111 'align-mode-rules-list
4112 '((org-in-buffer-settings
4113 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4114 (modes . '(org-mode)))))
4116 ;; Imenu
4117 (org-set-local 'imenu-create-index-function
4118 'org-imenu-get-tree)
4120 ;; Make isearch reveal context
4121 (if (or (featurep 'xemacs)
4122 (not (boundp 'outline-isearch-open-invisible-function)))
4123 ;; Emacs 21 and XEmacs make use of the hook
4124 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4125 ;; Emacs 22 deals with this through a special variable
4126 (org-set-local 'outline-isearch-open-invisible-function
4127 (lambda (&rest ignore) (org-show-context 'isearch))))
4129 ;; If empty file that did not turn on org-mode automatically, make it to.
4130 (if (and org-insert-mode-line-in-empty-file
4131 (interactive-p)
4132 (= (point-min) (point-max)))
4133 (insert "# -*- mode: org -*-\n\n"))
4135 (unless org-inhibit-startup
4136 (when org-startup-align-all-tables
4137 (let ((bmp (buffer-modified-p)))
4138 (org-table-map-tables 'org-table-align)
4139 (set-buffer-modified-p bmp)))
4140 (when org-startup-indented
4141 (require 'org-indent)
4142 (org-indent-mode 1))
4143 (org-set-startup-visibility)))
4145 (when (fboundp 'abbrev-table-put)
4146 (abbrev-table-put org-mode-abbrev-table
4147 :parents (list text-mode-abbrev-table)))
4149 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4151 (defun org-current-time ()
4152 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4153 (if (> (car org-time-stamp-rounding-minutes) 1)
4154 (let ((r (car org-time-stamp-rounding-minutes))
4155 (time (decode-time)))
4156 (apply 'encode-time
4157 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4158 (nthcdr 2 time))))
4159 (current-time)))
4161 ;;;; Font-Lock stuff, including the activators
4163 (defvar org-mouse-map (make-sparse-keymap))
4164 (org-defkey org-mouse-map
4165 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4166 (org-defkey org-mouse-map
4167 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4168 (when org-mouse-1-follows-link
4169 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4170 (when org-tab-follows-link
4171 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4172 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4174 (require 'font-lock)
4176 (defconst org-non-link-chars "]\t\n\r<>")
4177 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4178 "shell" "elisp"))
4179 (defvar org-link-types-re nil
4180 "Matches a link that has a url-like prefix like \"http:\"")
4181 (defvar org-link-re-with-space nil
4182 "Matches a link with spaces, optional angular brackets around it.")
4183 (defvar org-link-re-with-space2 nil
4184 "Matches a link with spaces, optional angular brackets around it.")
4185 (defvar org-link-re-with-space3 nil
4186 "Matches a link with spaces, only for internal part in bracket links.")
4187 (defvar org-angle-link-re nil
4188 "Matches link with angular brackets, spaces are allowed.")
4189 (defvar org-plain-link-re nil
4190 "Matches plain link, without spaces.")
4191 (defvar org-bracket-link-regexp nil
4192 "Matches a link in double brackets.")
4193 (defvar org-bracket-link-analytic-regexp nil
4194 "Regular expression used to analyze links.
4195 Here is what the match groups contain after a match:
4196 1: http:
4197 2: http
4198 3: path
4199 4: [desc]
4200 5: desc")
4201 (defvar org-bracket-link-analytic-regexp++ nil
4202 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4203 (defvar org-any-link-re nil
4204 "Regular expression matching any link.")
4206 (defun org-make-link-regexps ()
4207 "Update the link regular expressions.
4208 This should be called after the variable `org-link-types' has changed."
4209 (setq org-link-types-re
4210 (concat
4211 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4212 org-link-re-with-space
4213 (concat
4214 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4215 "\\([^" org-non-link-chars " ]"
4216 "[^" org-non-link-chars "]*"
4217 "[^" org-non-link-chars " ]\\)>?")
4218 org-link-re-with-space2
4219 (concat
4220 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4221 "\\([^" org-non-link-chars " ]"
4222 "[^\t\n\r]*"
4223 "[^" org-non-link-chars " ]\\)>?")
4224 org-link-re-with-space3
4225 (concat
4226 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4227 "\\([^" org-non-link-chars " ]"
4228 "[^\t\n\r]*\\)")
4229 org-angle-link-re
4230 (concat
4231 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4232 "\\([^" org-non-link-chars " ]"
4233 "[^" org-non-link-chars "]*"
4234 "\\)>")
4235 org-plain-link-re
4236 (concat
4237 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4238 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4239 org-bracket-link-regexp
4240 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4241 org-bracket-link-analytic-regexp
4242 (concat
4243 "\\[\\["
4244 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4245 "\\([^]]+\\)"
4246 "\\]"
4247 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4248 "\\]")
4249 org-bracket-link-analytic-regexp++
4250 (concat
4251 "\\[\\["
4252 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4253 "\\([^]]+\\)"
4254 "\\]"
4255 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4256 "\\]")
4257 org-any-link-re
4258 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4259 org-angle-link-re "\\)\\|\\("
4260 org-plain-link-re "\\)")))
4262 (org-make-link-regexps)
4264 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4265 "Regular expression for fast time stamp matching.")
4266 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4267 "Regular expression for fast time stamp matching.")
4268 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4269 "Regular expression matching time strings for analysis.
4270 This one does not require the space after the date, so it can be used
4271 on a string that terminates immediately after the date.")
4272 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4273 "Regular expression matching time strings for analysis.")
4274 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4275 "Regular expression matching time stamps, with groups.")
4276 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4277 "Regular expression matching time stamps (also [..]), with groups.")
4278 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4279 "Regular expression matching a time stamp range.")
4280 (defconst org-tr-regexp-both
4281 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4282 "Regular expression matching a time stamp range.")
4283 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4284 org-ts-regexp "\\)?")
4285 "Regular expression matching a time stamp or time stamp range.")
4286 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4287 org-ts-regexp-both "\\)?")
4288 "Regular expression matching a time stamp or time stamp range.
4289 The time stamps may be either active or inactive.")
4291 (defvar org-emph-face nil)
4293 (defun org-do-emphasis-faces (limit)
4294 "Run through the buffer and add overlays to links."
4295 (let (rtn a)
4296 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4297 (if (not (= (char-after (match-beginning 3))
4298 (char-after (match-beginning 4))))
4299 (progn
4300 (setq rtn t)
4301 (setq a (assoc (match-string 3) org-emphasis-alist))
4302 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4303 'face
4304 (nth 1 a))
4305 (and (nth 4 a)
4306 (org-remove-flyspell-overlays-in
4307 (match-beginning 0) (match-end 0)))
4308 (add-text-properties (match-beginning 2) (match-end 2)
4309 '(font-lock-multiline t))
4310 (when org-hide-emphasis-markers
4311 (add-text-properties (match-end 4) (match-beginning 5)
4312 '(invisible org-link))
4313 (add-text-properties (match-beginning 3) (match-end 3)
4314 '(invisible org-link)))))
4315 (backward-char 1))
4316 rtn))
4318 (defun org-emphasize (&optional char)
4319 "Insert or change an emphasis, i.e. a font like bold or italic.
4320 If there is an active region, change that region to a new emphasis.
4321 If there is no region, just insert the marker characters and position
4322 the cursor between them.
4323 CHAR should be either the marker character, or the first character of the
4324 HTML tag associated with that emphasis. If CHAR is a space, the means
4325 to remove the emphasis of the selected region.
4326 If char is not given (for example in an interactive call) it
4327 will be prompted for."
4328 (interactive)
4329 (let ((eal org-emphasis-alist) e det
4330 (erc org-emphasis-regexp-components)
4331 (prompt "")
4332 (string "") beg end move tag c s)
4333 (if (org-region-active-p)
4334 (setq beg (region-beginning) end (region-end)
4335 string (buffer-substring beg end))
4336 (setq move t))
4338 (while (setq e (pop eal))
4339 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4340 c (aref tag 0))
4341 (push (cons c (string-to-char (car e))) det)
4342 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4343 (substring tag 1)))))
4344 (setq det (nreverse det))
4345 (unless char
4346 (message "%s" (concat "Emphasis marker or tag:" prompt))
4347 (setq char (read-char-exclusive)))
4348 (setq char (or (cdr (assoc char det)) char))
4349 (if (equal char ?\ )
4350 (setq s "" move nil)
4351 (unless (assoc (char-to-string char) org-emphasis-alist)
4352 (error "No such emphasis marker: \"%c\"" char))
4353 (setq s (char-to-string char)))
4354 (while (and (> (length string) 1)
4355 (equal (substring string 0 1) (substring string -1))
4356 (assoc (substring string 0 1) org-emphasis-alist))
4357 (setq string (substring string 1 -1)))
4358 (setq string (concat s string s))
4359 (if beg (delete-region beg end))
4360 (unless (or (bolp)
4361 (string-match (concat "[" (nth 0 erc) "\n]")
4362 (char-to-string (char-before (point)))))
4363 (insert " "))
4364 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4365 (char-to-string (char-after (point))))
4366 (insert " ") (backward-char 1))
4367 (insert string)
4368 (and move (backward-char 1))))
4370 (defconst org-nonsticky-props
4371 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4373 (defsubst org-rear-nonsticky-at (pos)
4374 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4376 (defun org-activate-plain-links (limit)
4377 "Run through the buffer and add overlays to links."
4378 (catch 'exit
4379 (let (f)
4380 (if (re-search-forward org-plain-link-re limit t)
4381 (progn
4382 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4383 (setq f (get-text-property (match-beginning 0) 'face))
4384 (if (or (eq f 'org-tag)
4385 (and (listp f) (memq 'org-tag f)))
4387 (add-text-properties (match-beginning 0) (match-end 0)
4388 (list 'mouse-face 'highlight
4389 'keymap org-mouse-map))
4390 (org-rear-nonsticky-at (match-end 0)))
4391 t)))))
4393 (defun org-activate-code (limit)
4394 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4395 (progn
4396 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4397 (remove-text-properties (match-beginning 0) (match-end 0)
4398 '(display t invisible t intangible t))
4399 t)))
4401 (defun org-fontify-meta-lines-and-blocks (limit)
4402 "Fontify #+ lines and blocks, in the correct ways."
4403 (let ((case-fold-search t))
4404 (if (re-search-forward
4405 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4406 limit t)
4407 (let ((beg (match-beginning 0))
4408 (beg1 (line-beginning-position 2))
4409 (dc1 (downcase (match-string 2)))
4410 (dc3 (downcase (match-string 3)))
4411 end end1 quoting)
4412 (cond
4413 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4414 ;; a single line of backend-specific content
4415 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4416 (remove-text-properties (match-beginning 0) (match-end 0)
4417 '(display t invisible t intangible t))
4418 (add-text-properties (match-beginning 1) (match-end 3)
4419 '(font-lock-fontified t face org-meta-line))
4420 (add-text-properties (match-beginning 6) (match-end 6)
4421 '(font-lock-fontified t face org-block))
4423 ((and (match-end 4) (equal dc3 "begin"))
4424 ;; Truely a block
4425 (setq quoting (member (downcase (match-string 5))
4426 org-protecting-blocks))
4427 (when (re-search-forward
4428 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4429 nil t) ;; on purpose, we look further than LIMIT
4430 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4431 (when quoting
4432 (remove-text-properties beg end
4433 '(display t invisible t intangible t)))
4434 (add-text-properties
4435 beg end
4436 '(font-lock-fontified t font-lock-multiline t))
4437 (add-text-properties beg beg1 '(face org-meta-line))
4438 (add-text-properties end1 end '(face org-meta-line))
4439 (when quoting
4440 (add-text-properties beg1 end1 '(face org-block)))
4442 ((not (member (char-after beg) '(?\ ?\t)))
4443 ;; just any other in-buffer setting, but not indented
4444 (add-text-properties
4445 beg (match-end 0)
4446 '(font-lock-fontified t face org-meta-line))
4448 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4449 "orgtbl:" "tblfm:" "tblname:"))
4450 (and (match-end 4) (equal dc3 "attr")))
4451 (add-text-properties
4452 beg (match-end 0)
4453 '(font-lock-fontified t face org-meta-line))
4455 ((member dc3 '(" " ""))
4456 (add-text-properties
4457 beg (match-end 0)
4458 '(font-lock-fontified t face font-lock-comment-face)))
4459 (t nil))))))
4461 (defun org-activate-angle-links (limit)
4462 "Run through the buffer and add overlays to links."
4463 (if (re-search-forward org-angle-link-re limit t)
4464 (progn
4465 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4466 (add-text-properties (match-beginning 0) (match-end 0)
4467 (list 'mouse-face 'highlight
4468 'keymap org-mouse-map))
4469 (org-rear-nonsticky-at (match-end 0))
4470 t)))
4472 (defun org-activate-footnote-links (limit)
4473 "Run through the buffer and add overlays to links."
4474 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4475 limit t)
4476 (progn
4477 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4478 (add-text-properties (match-beginning 2) (match-end 2)
4479 (list 'mouse-face 'highlight
4480 'keymap org-mouse-map
4481 'help-echo
4482 (if (= (point-at-bol) (match-beginning 2))
4483 "Footnote definition"
4484 "Footnote reference")
4486 (org-rear-nonsticky-at (match-end 2))
4487 t)))
4489 (defun org-activate-bracket-links (limit)
4490 "Run through the buffer and add overlays to bracketed links."
4491 (if (re-search-forward org-bracket-link-regexp limit t)
4492 (let* ((help (concat "LINK: "
4493 (org-match-string-no-properties 1)))
4494 ;; FIXME: above we should remove the escapes.
4495 ;; but that requires another match, protecting match data,
4496 ;; a lot of overhead for font-lock.
4497 (ip (org-maybe-intangible
4498 (list 'invisible 'org-link
4499 'keymap org-mouse-map 'mouse-face 'highlight
4500 'font-lock-multiline t 'help-echo help)))
4501 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4502 'font-lock-multiline t 'help-echo help)))
4503 ;; We need to remove the invisible property here. Table narrowing
4504 ;; may have made some of this invisible.
4505 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4506 (remove-text-properties (match-beginning 0) (match-end 0)
4507 '(invisible nil))
4508 (if (match-end 3)
4509 (progn
4510 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4511 (org-rear-nonsticky-at (match-beginning 3))
4512 (add-text-properties (match-beginning 3) (match-end 3) vp)
4513 (org-rear-nonsticky-at (match-end 3))
4514 (add-text-properties (match-end 3) (match-end 0) ip)
4515 (org-rear-nonsticky-at (match-end 0)))
4516 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4517 (org-rear-nonsticky-at (match-beginning 1))
4518 (add-text-properties (match-beginning 1) (match-end 1) vp)
4519 (org-rear-nonsticky-at (match-end 1))
4520 (add-text-properties (match-end 1) (match-end 0) ip)
4521 (org-rear-nonsticky-at (match-end 0)))
4522 t)))
4524 (defun org-activate-dates (limit)
4525 "Run through the buffer and add overlays to dates."
4526 (if (re-search-forward org-tsr-regexp-both limit t)
4527 (progn
4528 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4529 (add-text-properties (match-beginning 0) (match-end 0)
4530 (list 'mouse-face 'highlight
4531 'keymap org-mouse-map))
4532 (org-rear-nonsticky-at (match-end 0))
4533 (when org-display-custom-times
4534 (if (match-end 3)
4535 (org-display-custom-time (match-beginning 3) (match-end 3)))
4536 (org-display-custom-time (match-beginning 1) (match-end 1)))
4537 t)))
4539 (defvar org-target-link-regexp nil
4540 "Regular expression matching radio targets in plain text.")
4541 (make-variable-buffer-local 'org-target-link-regexp)
4542 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4543 "Regular expression matching a link target.")
4544 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4545 "Regular expression matching a radio target.")
4546 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4547 "Regular expression matching any target.")
4549 (defun org-activate-target-links (limit)
4550 "Run through the buffer and add overlays to target matches."
4551 (when org-target-link-regexp
4552 (let ((case-fold-search t))
4553 (if (re-search-forward org-target-link-regexp limit t)
4554 (progn
4555 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4556 (add-text-properties (match-beginning 0) (match-end 0)
4557 (list 'mouse-face 'highlight
4558 'keymap org-mouse-map
4559 'help-echo "Radio target link"
4560 'org-linked-text t))
4561 (org-rear-nonsticky-at (match-end 0))
4562 t)))))
4564 (defun org-update-radio-target-regexp ()
4565 "Find all radio targets in this file and update the regular expression."
4566 (interactive)
4567 (when (memq 'radio org-activate-links)
4568 (setq org-target-link-regexp
4569 (org-make-target-link-regexp (org-all-targets 'radio)))
4570 (org-restart-font-lock)))
4572 (defun org-hide-wide-columns (limit)
4573 (let (s e)
4574 (setq s (text-property-any (point) (or limit (point-max))
4575 'org-cwidth t))
4576 (when s
4577 (setq e (next-single-property-change s 'org-cwidth))
4578 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4579 (goto-char e)
4580 t)))
4582 (defvar org-latex-and-specials-regexp nil
4583 "Regular expression for highlighting export special stuff.")
4584 (defvar org-match-substring-regexp)
4585 (defvar org-match-substring-with-braces-regexp)
4587 ;; This should be with the exporter code, but we also use if for font-locking
4588 (defconst org-export-html-special-string-regexps
4589 '(("\\\\-" . "&shy;")
4590 ("---\\([^-]\\)" . "&mdash;\\1")
4591 ("--\\([^-]\\)" . "&ndash;\\1")
4592 ("\\.\\.\\." . "&hellip;"))
4593 "Regular expressions for special string conversion.")
4596 (defun org-compute-latex-and-specials-regexp ()
4597 "Compute regular expression for stuff treated specially by exporters."
4598 (if (not org-highlight-latex-fragments-and-specials)
4599 (org-set-local 'org-latex-and-specials-regexp nil)
4600 (require 'org-exp)
4601 (let*
4602 ((matchers (plist-get org-format-latex-options :matchers))
4603 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4604 org-latex-regexps)))
4605 (options (org-combine-plists (org-default-export-plist)
4606 (org-infile-export-plist)))
4607 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4608 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4609 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4610 (org-export-html-expand (plist-get options :expand-quoted-html))
4611 (org-export-with-special-strings (plist-get options :special-strings))
4612 (re-sub
4613 (cond
4614 ((equal org-export-with-sub-superscripts '{})
4615 (list org-match-substring-with-braces-regexp))
4616 (org-export-with-sub-superscripts
4617 (list org-match-substring-regexp))
4618 (t nil)))
4619 (re-latex
4620 (if org-export-with-LaTeX-fragments
4621 (mapcar (lambda (x) (nth 1 x)) latexs)))
4622 (re-macros
4623 (if org-export-with-TeX-macros
4624 (list (concat "\\\\"
4625 (regexp-opt
4626 (append (mapcar 'car org-html-entities)
4627 (if (boundp 'org-latex-entities)
4628 (mapcar (lambda (x)
4629 (or (car-safe x) x))
4630 org-latex-entities)
4631 nil))
4632 'words))) ; FIXME
4634 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4635 (re-special (if org-export-with-special-strings
4636 (mapcar (lambda (x) (car x))
4637 org-export-html-special-string-regexps)))
4638 (re-rest
4639 (delq nil
4640 (list
4641 (if org-export-html-expand "@<[^>\n]+>")
4642 ))))
4643 (org-set-local
4644 'org-latex-and-specials-regexp
4645 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4646 re-rest) "\\|")))))
4648 (defun org-do-latex-and-special-faces (limit)
4649 "Run through the buffer and add overlays to links."
4650 (when org-latex-and-specials-regexp
4651 (let (rtn d)
4652 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4653 limit t))
4654 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4655 'face))
4656 '(org-code org-verbatim underline)))
4657 (progn
4658 (setq rtn t
4659 d (cond ((member (char-after (1+ (match-beginning 0)))
4660 '(?_ ?^)) 1)
4661 (t 0)))
4662 (font-lock-prepend-text-property
4663 (+ d (match-beginning 0)) (match-end 0)
4664 'face 'org-latex-and-export-specials)
4665 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4666 '(font-lock-multiline t)))))
4667 rtn)))
4669 (defun org-restart-font-lock ()
4670 "Restart font-lock-mode, to force refontification."
4671 (when (and (boundp 'font-lock-mode) font-lock-mode)
4672 (font-lock-mode -1)
4673 (font-lock-mode 1)))
4675 (defun org-all-targets (&optional radio)
4676 "Return a list of all targets in this file.
4677 With optional argument RADIO, only find radio targets."
4678 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4679 rtn)
4680 (save-excursion
4681 (goto-char (point-min))
4682 (while (re-search-forward re nil t)
4683 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4684 rtn)))
4686 (defun org-make-target-link-regexp (targets)
4687 "Make regular expression matching all strings in TARGETS.
4688 The regular expression finds the targets also if there is a line break
4689 between words."
4690 (and targets
4691 (concat
4692 "\\<\\("
4693 (mapconcat
4694 (lambda (x)
4695 (while (string-match " +" x)
4696 (setq x (replace-match "\\s-+" t t x)))
4698 targets
4699 "\\|")
4700 "\\)\\>")))
4702 (defun org-activate-tags (limit)
4703 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4704 (progn
4705 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4706 (add-text-properties (match-beginning 1) (match-end 1)
4707 (list 'mouse-face 'highlight
4708 'keymap org-mouse-map))
4709 (org-rear-nonsticky-at (match-end 1))
4710 t)))
4712 (defun org-outline-level ()
4713 "Compute the outline level of the heading at point.
4714 This function assumes that the cursor is at the beginning of a line matched
4715 by outline-regexp. Otherwise it returns garbage.
4716 If this is called at a normal headline, the level is the number of stars.
4717 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4718 For plain list items, if they are matched by `outline-regexp', this returns
4719 1000 plus the line indentation."
4720 (save-excursion
4721 (looking-at outline-regexp)
4722 (if (match-beginning 1)
4723 (+ (org-get-string-indentation (match-string 1)) 1000)
4724 (1- (- (match-end 0) (match-beginning 0))))))
4726 (defvar org-font-lock-keywords nil)
4728 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4729 "Regular expression matching a property line.")
4731 (defvar org-font-lock-hook nil
4732 "Functions to be called for special font lock stuff.")
4734 (defun org-font-lock-hook (limit)
4735 (run-hook-with-args 'org-font-lock-hook limit))
4737 (defun org-set-font-lock-defaults ()
4738 (let* ((em org-fontify-emphasized-text)
4739 (lk org-activate-links)
4740 (org-font-lock-extra-keywords
4741 (list
4742 ;; Call the hook
4743 '(org-font-lock-hook)
4744 ;; Headlines
4745 `(,(if org-fontify-whole-heading-line
4746 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4747 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4748 (1 (org-get-level-face 1))
4749 (2 (org-get-level-face 2))
4750 (3 (org-get-level-face 3)))
4751 ;; Table lines
4752 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4753 (1 'org-table t))
4754 ;; Table internals
4755 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4756 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4757 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4758 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4759 ;; Drawers
4760 (list org-drawer-regexp '(0 'org-special-keyword t))
4761 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4762 ;; Properties
4763 (list org-property-re
4764 '(1 'org-special-keyword t)
4765 '(3 'org-property-value t))
4766 ;; Links
4767 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4768 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4769 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4770 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4771 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4772 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4773 (if (memq 'footnote lk) '(org-activate-footnote-links
4774 (2 'org-footnote t)))
4775 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4776 '(org-hide-wide-columns (0 nil append))
4777 ;; TODO lines
4778 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4779 '(1 (org-get-todo-face 1) t))
4780 ;; DONE
4781 (if org-fontify-done-headline
4782 (list (concat "^[*]+ +\\<\\("
4783 (mapconcat 'regexp-quote org-done-keywords "\\|")
4784 "\\)\\(.*\\)")
4785 '(2 'org-headline-done t))
4786 nil)
4787 ;; Priorities
4788 '(org-font-lock-add-priority-faces)
4789 ;; Tags
4790 '(org-font-lock-add-tag-faces)
4791 ;; Special keywords
4792 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4793 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4794 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4795 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4796 ;; Emphasis
4797 (if em
4798 (if (featurep 'xemacs)
4799 '(org-do-emphasis-faces (0 nil append))
4800 '(org-do-emphasis-faces)))
4801 ;; Checkboxes
4802 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4803 2 'org-checkbox prepend)
4804 (if org-provide-checkbox-statistics
4805 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4806 (0 (org-get-checkbox-statistics-face) t)))
4807 ;; Description list items
4808 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4809 2 'bold prepend)
4810 ;; ARCHIVEd headings
4811 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4812 '(1 'org-archived prepend))
4813 ;; Specials
4814 '(org-do-latex-and-special-faces)
4815 ;; Code
4816 '(org-activate-code (1 'org-code t))
4817 ;; COMMENT
4818 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4819 "\\|" org-quote-string "\\)\\>")
4820 '(1 'org-special-keyword t))
4821 '("^#.*" (0 'font-lock-comment-face t))
4822 ;; Blocks and meta lines
4823 '(org-fontify-meta-lines-and-blocks)
4825 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4826 ;; Now set the full font-lock-keywords
4827 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4828 (org-set-local 'font-lock-defaults
4829 '(org-font-lock-keywords t nil nil backward-paragraph))
4830 (kill-local-variable 'font-lock-keywords) nil))
4832 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4833 "Fontify string S like in Org-mode"
4834 (with-temp-buffer
4835 (insert s)
4836 (let ((org-odd-levels-only odd-levels))
4837 (org-mode)
4838 (font-lock-fontify-buffer)
4839 (buffer-string))))
4841 (defvar org-m nil)
4842 (defvar org-l nil)
4843 (defvar org-f nil)
4844 (defun org-get-level-face (n)
4845 "Get the right face for match N in font-lock matching of headlines."
4846 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4847 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4848 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4849 (cond
4850 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4851 ((eq n 2) org-f)
4852 (t (if org-level-color-stars-only nil org-f))))
4854 (defun org-get-todo-face (kwd)
4855 "Get the right face for a TODO keyword KWD.
4856 If KWD is a number, get the corresponding match group."
4857 (if (numberp kwd) (setq kwd (match-string kwd)))
4858 (or (cdr (assoc kwd org-todo-keyword-faces))
4859 (and (member kwd org-done-keywords) 'org-done)
4860 'org-todo))
4862 (defun org-font-lock-add-tag-faces (limit)
4863 "Add the special tag faces."
4864 (when (and org-tag-faces org-tags-special-faces-re)
4865 (while (re-search-forward org-tags-special-faces-re limit t)
4866 (add-text-properties (match-beginning 1) (match-end 1)
4867 (list 'face (org-get-tag-face 1)
4868 'font-lock-fontified t))
4869 (backward-char 1))))
4871 (defun org-font-lock-add-priority-faces (limit)
4872 "Add the special priority faces."
4873 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4874 (add-text-properties
4875 (match-beginning 0) (match-end 0)
4876 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4877 org-priority-faces))
4878 'org-special-keyword)
4879 'font-lock-fontified t))))
4881 (defun org-get-tag-face (kwd)
4882 "Get the right face for a TODO keyword KWD.
4883 If KWD is a number, get the corresponding match group."
4884 (if (numberp kwd) (setq kwd (match-string kwd)))
4885 (or (cdr (assoc kwd org-tag-faces))
4886 'org-tag))
4888 (defun org-unfontify-region (beg end &optional maybe_loudly)
4889 "Remove fontification and activation overlays from links."
4890 (font-lock-default-unfontify-region beg end)
4891 (let* ((buffer-undo-list t)
4892 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4893 (inhibit-modification-hooks t)
4894 deactivate-mark buffer-file-name buffer-file-truename)
4895 (remove-text-properties beg end
4896 '(mouse-face t keymap t org-linked-text t
4897 invisible t intangible t
4898 line-prefix t wrap-prefix t
4899 org-no-flyspell t))))
4901 ;;;; Visibility cycling, including org-goto and indirect buffer
4903 ;;; Cycling
4905 (defvar org-cycle-global-status nil)
4906 (make-variable-buffer-local 'org-cycle-global-status)
4907 (defvar org-cycle-subtree-status nil)
4908 (make-variable-buffer-local 'org-cycle-subtree-status)
4910 ;;;###autoload
4912 (defvar org-inlinetask-min-level)
4914 (defun org-cycle (&optional arg)
4915 "TAB-action and visibility cycling for Org-mode.
4917 This is the command invoked in Org-mode by the TAB key. Its main purpose
4918 is outine visibility cycling, but it also invokes other actions
4919 in special contexts.
4921 - When this function is called with a prefix argument, rotate the entire
4922 buffer through 3 states (global cycling)
4923 1. OVERVIEW: Show only top-level headlines.
4924 2. CONTENTS: Show all headlines of all levels, but no body text.
4925 3. SHOW ALL: Show everything.
4926 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4927 determined by the variable `org-startup-folded', and by any VISIBILITY
4928 properties in the buffer.
4929 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4930 including any drawers.
4932 - When inside a table, re-align the table and move to the next field.
4934 - When point is at the beginning of a headline, rotate the subtree started
4935 by this line through 3 different states (local cycling)
4936 1. FOLDED: Only the main headline is shown.
4937 2. CHILDREN: The main headline and the direct children are shown.
4938 From this state, you can move to one of the children
4939 and zoom in further.
4940 3. SUBTREE: Show the entire subtree, including body text.
4941 If there is no subtree, switch directly from CHILDREN to FOLDED.
4943 - When there is a numeric prefix, go up to a heading with level ARG, do
4944 a `show-subtree' and return to the previous cursor position. If ARG
4945 is negative, go up that many levels.
4947 - When point is not at the beginning of a headline, execute the global
4948 binding for TAB, which is re-indenting the line. See the option
4949 `org-cycle-emulate-tab' for details.
4951 - Special case: if point is at the beginning of the buffer and there is
4952 no headline in line 1, this function will act as if called with prefix arg.
4953 But only if also the variable `org-cycle-global-at-bob' is t."
4954 (interactive "P")
4955 (org-load-modules-maybe)
4956 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4957 (let* ((limit-level
4958 (or org-cycle-max-level
4959 (and (boundp 'org-inlinetask-min-level)
4960 org-inlinetask-min-level
4961 (1- org-inlinetask-min-level))))
4962 (nstars (and limit-level
4963 (if org-odd-levels-only
4964 (and limit-level (1- (* limit-level 2)))
4965 limit-level)))
4966 (outline-regexp
4967 (cond
4968 ((not (org-mode-p)) outline-regexp)
4969 ((or (eq org-cycle-include-plain-lists 'integrate)
4970 (and org-cycle-include-plain-lists (org-at-item-p)))
4971 (concat "\\(?:\\*"
4972 (if nstars (format "\\{1,%d\\}" nstars) "+")
4973 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4974 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4975 (bob-special (and org-cycle-global-at-bob (bobp)
4976 (not (looking-at outline-regexp))))
4977 (org-cycle-hook
4978 (if bob-special
4979 (delq 'org-optimize-window-after-visibility-change
4980 (copy-sequence org-cycle-hook))
4981 org-cycle-hook))
4982 (pos (point)))
4984 (if (or bob-special (equal arg '(4)))
4985 ;; special case: use global cycling
4986 (setq arg t))
4988 (cond
4990 ((equal arg '(16))
4991 (org-set-startup-visibility)
4992 (message "Startup visibility, plus VISIBILITY properties"))
4994 ((equal arg '(64))
4995 (show-all)
4996 (message "Entire buffer visible, including drawers"))
4998 ((org-at-table-p 'any)
4999 ;; Enter the table or move to the next field in the table
5000 (or (org-table-recognize-table.el)
5001 (progn
5002 (if arg (org-table-edit-field t)
5003 (org-table-justify-field-maybe)
5004 (call-interactively 'org-table-next-field)))))
5006 ((run-hook-with-args-until-success
5007 'org-tab-after-check-for-table-hook))
5009 ((eq arg t) ;; Global cycling
5010 (org-cycle-internal-global))
5012 ((and org-drawers org-drawer-regexp
5013 (save-excursion
5014 (beginning-of-line 1)
5015 (looking-at org-drawer-regexp)))
5016 ;; Toggle block visibility
5017 (org-flag-drawer
5018 (not (get-char-property (match-end 0) 'invisible))))
5020 ((integerp arg)
5021 ;; Show-subtree, ARG levels up from here.
5022 (save-excursion
5023 (org-back-to-heading)
5024 (outline-up-heading (if (< arg 0) (- arg)
5025 (- (funcall outline-level) arg)))
5026 (org-show-subtree)))
5028 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5029 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5031 (org-cycle-internal-local))
5033 ;; TAB emulation and template completion
5034 (buffer-read-only (org-back-to-heading))
5036 ((run-hook-with-args-until-success
5037 'org-tab-after-check-for-cycling-hook))
5039 ((org-try-structure-completion))
5041 ((org-try-cdlatex-tab))
5043 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5044 (or (not (bolp))
5045 (not (looking-at outline-regexp))))
5046 (call-interactively (global-key-binding "\t")))
5048 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5049 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5050 (or (and (eq org-cycle-emulate-tab 'white)
5051 (= (match-end 0) (point-at-eol)))
5052 (and (eq org-cycle-emulate-tab 'whitestart)
5053 (>= (match-end 0) pos))))
5055 (eq org-cycle-emulate-tab t))
5056 (call-interactively (global-key-binding "\t")))
5058 (t (save-excursion
5059 (org-back-to-heading)
5060 (org-cycle)))))))
5062 (defun org-cycle-internal-global ()
5063 "Do the global cycling action."
5064 (cond
5065 ((and (eq last-command this-command)
5066 (eq org-cycle-global-status 'overview))
5067 ;; We just created the overview - now do table of contents
5068 ;; This can be slow in very large buffers, so indicate action
5069 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5070 (message "CONTENTS...")
5071 (org-content)
5072 (message "CONTENTS...done")
5073 (setq org-cycle-global-status 'contents)
5074 (run-hook-with-args 'org-cycle-hook 'contents))
5076 ((and (eq last-command this-command)
5077 (eq org-cycle-global-status 'contents))
5078 ;; We just showed the table of contents - now show everything
5079 (run-hook-with-args 'org-pre-cycle-hook 'all)
5080 (show-all)
5081 (message "SHOW ALL")
5082 (setq org-cycle-global-status 'all)
5083 (run-hook-with-args 'org-cycle-hook 'all))
5086 ;; Default action: go to overview
5087 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5088 (org-overview)
5089 (message "OVERVIEW")
5090 (setq org-cycle-global-status 'overview)
5091 (run-hook-with-args 'org-cycle-hook 'overview))))
5093 (defun org-cycle-internal-local ()
5094 "Do the local cycling action."
5095 (org-back-to-heading)
5096 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5097 ;; First, some boundaries
5098 (save-excursion
5099 (org-back-to-heading)
5100 (setq level (funcall outline-level))
5101 (save-excursion
5102 (beginning-of-line 2)
5103 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5104 ; XEmacs does not have `next-single-char-property-change'
5105 ; I'm not sure about Emacs 21.
5106 (while (and (not (eobp)) ;; this is like `next-line'
5107 (get-char-property (1- (point)) 'invisible))
5108 (beginning-of-line 2))
5109 (while (and (not (eobp)) ;; this is like `next-line'
5110 (get-char-property (1- (point)) 'invisible))
5111 (goto-char (next-single-char-property-change (point) 'invisible))
5112 ;;;??? (or (bolp) (beginning-of-line 2))))
5113 (and (eolp) (beginning-of-line 2))))
5114 (setq eol (point)))
5115 (outline-end-of-heading) (setq eoh (point))
5116 (save-excursion
5117 (outline-next-heading)
5118 (setq has-children (and (org-at-heading-p t)
5119 (> (funcall outline-level) level))))
5120 (org-end-of-subtree t)
5121 (unless (eobp)
5122 (skip-chars-forward " \t\n")
5123 (beginning-of-line 1) ; in case this is an item
5125 (setq eos (if (eobp) (point) (1- (point)))))
5126 ;; Find out what to do next and set `this-command'
5127 (cond
5128 ((= eos eoh)
5129 ;; Nothing is hidden behind this heading
5130 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5131 (message "EMPTY ENTRY")
5132 (setq org-cycle-subtree-status nil)
5133 (save-excursion
5134 (goto-char eos)
5135 (outline-next-heading)
5136 (if (org-invisible-p) (org-flag-heading nil))))
5137 ((and (or (>= eol eos)
5138 (not (string-match "\\S-" (buffer-substring eol eos))))
5139 (or has-children
5140 (not (setq children-skipped
5141 org-cycle-skip-children-state-if-no-children))))
5142 ;; Entire subtree is hidden in one line: children view
5143 (run-hook-with-args 'org-pre-cycle-hook 'children)
5144 (org-show-entry)
5145 (show-children)
5146 (message "CHILDREN")
5147 (save-excursion
5148 (goto-char eos)
5149 (outline-next-heading)
5150 (if (org-invisible-p) (org-flag-heading nil)))
5151 (setq org-cycle-subtree-status 'children)
5152 (run-hook-with-args 'org-cycle-hook 'children))
5153 ((or children-skipped
5154 (and (eq last-command this-command)
5155 (eq org-cycle-subtree-status 'children)))
5156 ;; We just showed the children, or no children are there,
5157 ;; now show everything.
5158 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5159 (org-show-subtree)
5160 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5161 (setq org-cycle-subtree-status 'subtree)
5162 (run-hook-with-args 'org-cycle-hook 'subtree))
5164 ;; Default action: hide the subtree.
5165 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5166 (hide-subtree)
5167 (message "FOLDED")
5168 (setq org-cycle-subtree-status 'folded)
5169 (run-hook-with-args 'org-cycle-hook 'folded)))))
5171 ;;;###autoload
5172 (defun org-global-cycle (&optional arg)
5173 "Cycle the global visibility. For details see `org-cycle'.
5174 With C-u prefix arg, switch to startup visibility.
5175 With a numeric prefix, show all headlines up to that level."
5176 (interactive "P")
5177 (let ((org-cycle-include-plain-lists
5178 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5179 (cond
5180 ((integerp arg)
5181 (show-all)
5182 (hide-sublevels arg)
5183 (setq org-cycle-global-status 'contents))
5184 ((equal arg '(4))
5185 (org-set-startup-visibility)
5186 (message "Startup visibility, plus VISIBILITY properties."))
5188 (org-cycle '(4))))))
5190 (defun org-set-startup-visibility ()
5191 "Set the visibility required by startup options and properties."
5192 (cond
5193 ((eq org-startup-folded t)
5194 (org-cycle '(4)))
5195 ((eq org-startup-folded 'content)
5196 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5197 (org-cycle '(4)) (org-cycle '(4)))))
5198 (unless (eq org-startup-folded 'showeverything)
5199 (if org-hide-block-startup (org-hide-block-all))
5200 (org-set-visibility-according-to-property 'no-cleanup)
5201 (org-cycle-hide-archived-subtrees 'all)
5202 (org-cycle-hide-drawers 'all)
5203 (org-cycle-show-empty-lines 'all)))
5205 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5206 "Switch subtree visibilities according to :VISIBILITY: property."
5207 (interactive)
5208 (let (org-show-entry-below state)
5209 (save-excursion
5210 (goto-char (point-min))
5211 (while (re-search-forward
5212 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5213 nil t)
5214 (setq state (match-string 1))
5215 (save-excursion
5216 (org-back-to-heading t)
5217 (hide-subtree)
5218 (org-reveal)
5219 (cond
5220 ((equal state '("fold" "folded"))
5221 (hide-subtree))
5222 ((equal state "children")
5223 (org-show-hidden-entry)
5224 (show-children))
5225 ((equal state "content")
5226 (save-excursion
5227 (save-restriction
5228 (org-narrow-to-subtree)
5229 (org-content))))
5230 ((member state '("all" "showall"))
5231 (show-subtree)))))
5232 (unless no-cleanup
5233 (org-cycle-hide-archived-subtrees 'all)
5234 (org-cycle-hide-drawers 'all)
5235 (org-cycle-show-empty-lines 'all)))))
5237 (defun org-overview ()
5238 "Switch to overview mode, showing only top-level headlines.
5239 Really, this shows all headlines with level equal or greater than the level
5240 of the first headline in the buffer. This is important, because if the
5241 first headline is not level one, then (hide-sublevels 1) gives confusing
5242 results."
5243 (interactive)
5244 (let ((level (save-excursion
5245 (goto-char (point-min))
5246 (if (re-search-forward (concat "^" outline-regexp) nil t)
5247 (progn
5248 (goto-char (match-beginning 0))
5249 (funcall outline-level))))))
5250 (and level (hide-sublevels level))))
5252 (defun org-content (&optional arg)
5253 "Show all headlines in the buffer, like a table of contents.
5254 With numerical argument N, show content up to level N."
5255 (interactive "P")
5256 (save-excursion
5257 ;; Visit all headings and show their offspring
5258 (and (integerp arg) (org-overview))
5259 (goto-char (point-max))
5260 (catch 'exit
5261 (while (and (progn (condition-case nil
5262 (outline-previous-visible-heading 1)
5263 (error (goto-char (point-min))))
5265 (looking-at outline-regexp))
5266 (if (integerp arg)
5267 (show-children (1- arg))
5268 (show-branches))
5269 (if (bobp) (throw 'exit nil))))))
5272 (defun org-optimize-window-after-visibility-change (state)
5273 "Adjust the window after a change in outline visibility.
5274 This function is the default value of the hook `org-cycle-hook'."
5275 (when (get-buffer-window (current-buffer))
5276 (cond
5277 ((eq state 'content) nil)
5278 ((eq state 'all) nil)
5279 ((eq state 'folded) nil)
5280 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5281 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5283 ;; FIXME: no longer in use
5284 (defun org-compact-display-after-subtree-move ()
5285 "Show a compacter version of the tree of the entry's parent."
5286 (save-excursion
5287 (if (org-up-heading-safe)
5288 (progn
5289 (hide-subtree)
5290 (show-entry)
5291 (show-children)
5292 (org-cycle-show-empty-lines 'children)
5293 (org-cycle-hide-drawers 'children))
5294 (org-overview))))
5296 (defun org-remove-empty-overlays-at (pos)
5297 "Remove outline overlays that do not contain non-white stuff."
5298 (mapc
5299 (lambda (o)
5300 (and (eq 'outline (org-overlay-get o 'invisible))
5301 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5302 (org-overlay-end o))))
5303 (org-delete-overlay o)))
5304 (org-overlays-at pos)))
5306 (defun org-clean-visibility-after-subtree-move ()
5307 "Fix visibility issues after moving a subtree."
5308 ;; First, find a reasonable region to look at:
5309 ;; Start two siblings above, end three below
5310 (let* ((beg (save-excursion
5311 (and (org-get-last-sibling)
5312 (org-get-last-sibling))
5313 (point)))
5314 (end (save-excursion
5315 (and (org-get-next-sibling)
5316 (org-get-next-sibling)
5317 (org-get-next-sibling))
5318 (if (org-at-heading-p)
5319 (point-at-eol)
5320 (point))))
5321 (level (looking-at "\\*+"))
5322 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5323 (save-excursion
5324 (save-restriction
5325 (narrow-to-region beg end)
5326 (when re
5327 ;; Properly fold already folded siblings
5328 (goto-char (point-min))
5329 (while (re-search-forward re nil t)
5330 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5331 (hide-entry))))
5332 (org-cycle-show-empty-lines 'overview)
5333 (org-cycle-hide-drawers 'overview)))))
5335 (defun org-cycle-show-empty-lines (state)
5336 "Show empty lines above all visible headlines.
5337 The region to be covered depends on STATE when called through
5338 `org-cycle-hook'. Lisp program can use t for STATE to get the
5339 entire buffer covered. Note that an empty line is only shown if there
5340 are at least `org-cycle-separator-lines' empty lines before the headline."
5341 (when (not (= org-cycle-separator-lines 0))
5342 (save-excursion
5343 (let* ((n (abs org-cycle-separator-lines))
5344 (re (cond
5345 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5346 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5347 (t (let ((ns (number-to-string (- n 2))))
5348 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5349 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5350 beg end b e)
5351 (cond
5352 ((memq state '(overview contents t))
5353 (setq beg (point-min) end (point-max)))
5354 ((memq state '(children folded))
5355 (setq beg (point) end (progn (org-end-of-subtree t t)
5356 (beginning-of-line 2)
5357 (point)))))
5358 (when beg
5359 (goto-char beg)
5360 (while (re-search-forward re end t)
5361 (unless (get-char-property (match-end 1) 'invisible)
5362 (setq e (match-end 1))
5363 (if (< org-cycle-separator-lines 0)
5364 (setq b (save-excursion
5365 (goto-char (match-beginning 0))
5366 (org-back-over-empty-lines)
5367 (if (save-excursion
5368 (goto-char (max (point-min) (1- (point))))
5369 (org-on-heading-p))
5370 (1- (point))
5371 (point))))
5372 (setq b (match-beginning 1)))
5373 (outline-flag-region b e nil)))))))
5374 ;; Never hide empty lines at the end of the file.
5375 (save-excursion
5376 (goto-char (point-max))
5377 (outline-previous-heading)
5378 (outline-end-of-heading)
5379 (if (and (looking-at "[ \t\n]+")
5380 (= (match-end 0) (point-max)))
5381 (outline-flag-region (point) (match-end 0) nil))))
5383 (defun org-show-empty-lines-in-parent ()
5384 "Move to the parent and re-show empty lines before visible headlines."
5385 (save-excursion
5386 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5387 (org-cycle-show-empty-lines context))))
5389 (defun org-files-list ()
5390 "Return `org-agenda-files' list, plus all open org-mode files.
5391 This is useful for operations that need to scan all of a user's
5392 open and agenda-wise Org files."
5393 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5394 (dolist (buf (buffer-list))
5395 (with-current-buffer buf
5396 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5397 (let ((file (expand-file-name (buffer-file-name))))
5398 (unless (member file files)
5399 (push file files))))))
5400 files))
5402 (defsubst org-entry-beginning-position ()
5403 "Return the beginning position of the current entry."
5404 (save-excursion (outline-back-to-heading t) (point)))
5406 (defsubst org-entry-end-position ()
5407 "Return the end position of the current entry."
5408 (save-excursion (outline-next-heading) (point)))
5410 (defun org-cycle-hide-drawers (state)
5411 "Re-hide all drawers after a visibility state change."
5412 (when (and (org-mode-p)
5413 (not (memq state '(overview folded contents))))
5414 (save-excursion
5415 (let* ((globalp (memq state '(contents all)))
5416 (beg (if globalp (point-min) (point)))
5417 (end (if globalp (point-max)
5418 (if (eq state 'children)
5419 (save-excursion (outline-next-heading) (point))
5420 (org-end-of-subtree t)))))
5421 (goto-char beg)
5422 (while (re-search-forward org-drawer-regexp end t)
5423 (org-flag-drawer t))))))
5425 (defun org-flag-drawer (flag)
5426 (save-excursion
5427 (beginning-of-line 1)
5428 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5429 (let ((b (match-end 0))
5430 (outline-regexp org-outline-regexp))
5431 (if (re-search-forward
5432 "^[ \t]*:END:"
5433 (save-excursion (outline-next-heading) (point)) t)
5434 (outline-flag-region b (point-at-eol) flag)
5435 (error ":END: line missing at position %s" b))))))
5437 (defun org-subtree-end-visible-p ()
5438 "Is the end of the current subtree visible?"
5439 (pos-visible-in-window-p
5440 (save-excursion (org-end-of-subtree t) (point))))
5442 (defun org-first-headline-recenter (&optional N)
5443 "Move cursor to the first headline and recenter the headline.
5444 Optional argument N means, put the headline into the Nth line of the window."
5445 (goto-char (point-min))
5446 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5447 (beginning-of-line)
5448 (recenter (prefix-numeric-value N))))
5450 ;;; Folding of blocks
5452 (defconst org-block-regexp
5454 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5455 "Regular expression for hiding blocks.")
5457 (defvar org-hide-block-overlays nil
5458 "Overays hiding blocks.")
5459 (make-variable-buffer-local 'org-hide-block-overlays)
5461 (defun org-block-map (function &optional start end)
5462 "Call func at the head of all source blocks in the current
5463 buffer. Optional arguments START and END can be used to limit
5464 the range."
5465 (let ((start (or start (point-min)))
5466 (end (or end (point-max))))
5467 (save-excursion
5468 (goto-char start)
5469 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5470 (save-excursion
5471 (save-match-data
5472 (goto-char (match-beginning 0))
5473 (funcall function)))))))
5475 (defun org-hide-block-toggle-all ()
5476 "Toggle the visibility of all blocks in the current buffer."
5477 (org-block-map #'org-hide-block-toggle))
5479 (defun org-hide-block-all ()
5480 "Fold all blocks in the current buffer."
5481 (interactive)
5482 (org-show-block-all)
5483 (org-block-map #'org-hide-block-toggle-maybe))
5485 (defun org-show-block-all ()
5486 "Unfold all blocks in the current buffer."
5487 (mapc 'org-delete-overlay org-hide-block-overlays)
5488 (setq org-hide-block-overlays nil))
5490 (defun org-hide-block-toggle-maybe ()
5491 "Toggle visibility of block at point."
5492 (interactive)
5493 (let ((case-fold-search t))
5494 (if (save-excursion
5495 (beginning-of-line 1)
5496 (looking-at org-block-regexp))
5497 (progn (org-hide-block-toggle)
5498 t) ;; to signal that we took action
5499 nil))) ;; to signal that we did not
5501 (defun org-hide-block-toggle (&optional force)
5502 "Toggle the visibility of the current block."
5503 (interactive)
5504 (save-excursion
5505 (beginning-of-line)
5506 (if (re-search-forward org-block-regexp nil t)
5507 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5508 (end (match-end 0)) ;; end of entire body
5510 (if (memq t (mapcar (lambda (overlay)
5511 (eq (org-overlay-get overlay 'invisible)
5512 'org-hide-block))
5513 (org-overlays-at start)))
5514 (if (or (not force) (eq force 'off))
5515 (mapc (lambda (ov)
5516 (when (member ov org-hide-block-overlays)
5517 (setq org-hide-block-overlays
5518 (delq ov org-hide-block-overlays)))
5519 (when (eq (org-overlay-get ov 'invisible)
5520 'org-hide-block)
5521 (org-delete-overlay ov)))
5522 (org-overlays-at start)))
5523 (setq ov (org-make-overlay start end))
5524 (org-overlay-put ov 'invisible 'org-hide-block)
5525 ;; make the block accessible to isearch
5526 (org-overlay-put
5527 ov 'isearch-open-invisible
5528 (lambda (ov)
5529 (when (member ov org-hide-block-overlays)
5530 (setq org-hide-block-overlays
5531 (delq ov org-hide-block-overlays)))
5532 (when (eq (org-overlay-get ov 'invisible)
5533 'org-hide-block)
5534 (org-delete-overlay ov))))
5535 (push ov org-hide-block-overlays)))
5536 (error "Not looking at a source block"))))
5538 ;; org-tab-after-check-for-cycling-hook
5539 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5540 ;; Remove overlays when changing major mode
5541 (add-hook 'org-mode-hook
5542 (lambda () (org-add-hook 'change-major-mode-hook
5543 'org-show-block-all 'append 'local)))
5545 ;;; Org-goto
5547 (defvar org-goto-window-configuration nil)
5548 (defvar org-goto-marker nil)
5549 (defvar org-goto-map
5550 (let ((map (make-sparse-keymap)))
5551 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5552 (while (setq cmd (pop cmds))
5553 (substitute-key-definition cmd cmd map global-map)))
5554 (suppress-keymap map)
5555 (org-defkey map "\C-m" 'org-goto-ret)
5556 (org-defkey map [(return)] 'org-goto-ret)
5557 (org-defkey map [(left)] 'org-goto-left)
5558 (org-defkey map [(right)] 'org-goto-right)
5559 (org-defkey map [(control ?g)] 'org-goto-quit)
5560 (org-defkey map "\C-i" 'org-cycle)
5561 (org-defkey map [(tab)] 'org-cycle)
5562 (org-defkey map [(down)] 'outline-next-visible-heading)
5563 (org-defkey map [(up)] 'outline-previous-visible-heading)
5564 (if org-goto-auto-isearch
5565 (if (fboundp 'define-key-after)
5566 (define-key-after map [t] 'org-goto-local-auto-isearch)
5567 nil)
5568 (org-defkey map "q" 'org-goto-quit)
5569 (org-defkey map "n" 'outline-next-visible-heading)
5570 (org-defkey map "p" 'outline-previous-visible-heading)
5571 (org-defkey map "f" 'outline-forward-same-level)
5572 (org-defkey map "b" 'outline-backward-same-level)
5573 (org-defkey map "u" 'outline-up-heading))
5574 (org-defkey map "/" 'org-occur)
5575 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5576 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5577 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5578 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5579 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5580 map))
5582 (defconst org-goto-help
5583 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5584 RET=jump to location [Q]uit and return to previous location
5585 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5587 (defvar org-goto-start-pos) ; dynamically scoped parameter
5589 ;; FIXME: Docstring doe not mention both interfaces
5590 (defun org-goto (&optional alternative-interface)
5591 "Look up a different location in the current file, keeping current visibility.
5593 When you want look-up or go to a different location in a document, the
5594 fastest way is often to fold the entire buffer and then dive into the tree.
5595 This method has the disadvantage, that the previous location will be folded,
5596 which may not be what you want.
5598 This command works around this by showing a copy of the current buffer
5599 in an indirect buffer, in overview mode. You can dive into the tree in
5600 that copy, use org-occur and incremental search to find a location.
5601 When pressing RET or `Q', the command returns to the original buffer in
5602 which the visibility is still unchanged. After RET is will also jump to
5603 the location selected in the indirect buffer and expose the
5604 the headline hierarchy above."
5605 (interactive "P")
5606 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5607 (org-refile-use-outline-path t)
5608 (org-refile-target-verify-function nil)
5609 (interface
5610 (if (not alternative-interface)
5611 org-goto-interface
5612 (if (eq org-goto-interface 'outline)
5613 'outline-path-completion
5614 'outline)))
5615 (org-goto-start-pos (point))
5616 (selected-point
5617 (if (eq interface 'outline)
5618 (car (org-get-location (current-buffer) org-goto-help))
5619 (nth 3 (org-refile-get-location "Goto: ")))))
5620 (if selected-point
5621 (progn
5622 (org-mark-ring-push org-goto-start-pos)
5623 (goto-char selected-point)
5624 (if (or (org-invisible-p) (org-invisible-p2))
5625 (org-show-context 'org-goto)))
5626 (message "Quit"))))
5628 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5629 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5630 (defvar org-goto-local-auto-isearch-map) ; defined below
5632 (defun org-get-location (buf help)
5633 "Let the user select a location in the Org-mode buffer BUF.
5634 This function uses a recursive edit. It returns the selected position
5635 or nil."
5636 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5637 (isearch-hide-immediately nil)
5638 (isearch-search-fun-function
5639 (lambda () 'org-goto-local-search-headings))
5640 (org-goto-selected-point org-goto-exit-command))
5641 (save-excursion
5642 (save-window-excursion
5643 (delete-other-windows)
5644 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5645 (switch-to-buffer
5646 (condition-case nil
5647 (make-indirect-buffer (current-buffer) "*org-goto*")
5648 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5649 (with-output-to-temp-buffer "*Help*"
5650 (princ help))
5651 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5652 (setq buffer-read-only nil)
5653 (let ((org-startup-truncated t)
5654 (org-startup-folded nil)
5655 (org-startup-align-all-tables nil))
5656 (org-mode)
5657 (org-overview))
5658 (setq buffer-read-only t)
5659 (if (and (boundp 'org-goto-start-pos)
5660 (integer-or-marker-p org-goto-start-pos))
5661 (let ((org-show-hierarchy-above t)
5662 (org-show-siblings t)
5663 (org-show-following-heading t))
5664 (goto-char org-goto-start-pos)
5665 (and (org-invisible-p) (org-show-context)))
5666 (goto-char (point-min)))
5667 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5668 (message "Select location and press RET")
5669 (use-local-map org-goto-map)
5670 (recursive-edit)
5672 (kill-buffer "*org-goto*")
5673 (cons org-goto-selected-point org-goto-exit-command)))
5675 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5676 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5677 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5678 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5680 (defun org-goto-local-search-headings (string bound noerror)
5681 "Search and make sure that any matches are in headlines."
5682 (catch 'return
5683 (while (if isearch-forward
5684 (search-forward string bound noerror)
5685 (search-backward string bound noerror))
5686 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5687 (and (member :headline context)
5688 (not (member :tags context))))
5689 (throw 'return (point))))))
5691 (defun org-goto-local-auto-isearch ()
5692 "Start isearch."
5693 (interactive)
5694 (goto-char (point-min))
5695 (let ((keys (this-command-keys)))
5696 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5697 (isearch-mode t)
5698 (isearch-process-search-char (string-to-char keys)))))
5700 (defun org-goto-ret (&optional arg)
5701 "Finish `org-goto' by going to the new location."
5702 (interactive "P")
5703 (setq org-goto-selected-point (point)
5704 org-goto-exit-command 'return)
5705 (throw 'exit nil))
5707 (defun org-goto-left ()
5708 "Finish `org-goto' by going to the new location."
5709 (interactive)
5710 (if (org-on-heading-p)
5711 (progn
5712 (beginning-of-line 1)
5713 (setq org-goto-selected-point (point)
5714 org-goto-exit-command 'left)
5715 (throw 'exit nil))
5716 (error "Not on a heading")))
5718 (defun org-goto-right ()
5719 "Finish `org-goto' by going to the new location."
5720 (interactive)
5721 (if (org-on-heading-p)
5722 (progn
5723 (setq org-goto-selected-point (point)
5724 org-goto-exit-command 'right)
5725 (throw 'exit nil))
5726 (error "Not on a heading")))
5728 (defun org-goto-quit ()
5729 "Finish `org-goto' without cursor motion."
5730 (interactive)
5731 (setq org-goto-selected-point nil)
5732 (setq org-goto-exit-command 'quit)
5733 (throw 'exit nil))
5735 ;;; Indirect buffer display of subtrees
5737 (defvar org-indirect-dedicated-frame nil
5738 "This is the frame being used for indirect tree display.")
5739 (defvar org-last-indirect-buffer nil)
5741 (defun org-tree-to-indirect-buffer (&optional arg)
5742 "Create indirect buffer and narrow it to current subtree.
5743 With numerical prefix ARG, go up to this level and then take that tree.
5744 If ARG is negative, go up that many levels.
5745 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5746 indirect buffer previously made with this command, to avoid proliferation of
5747 indirect buffers. However, when you call the command with a `C-u' prefix, or
5748 when `org-indirect-buffer-display' is `new-frame', the last buffer
5749 is kept so that you can work with several indirect buffers at the same time.
5750 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5751 requests that a new frame be made for the new buffer, so that the dedicated
5752 frame is not changed."
5753 (interactive "P")
5754 (let ((cbuf (current-buffer))
5755 (cwin (selected-window))
5756 (pos (point))
5757 beg end level heading ibuf)
5758 (save-excursion
5759 (org-back-to-heading t)
5760 (when (numberp arg)
5761 (setq level (org-outline-level))
5762 (if (< arg 0) (setq arg (+ level arg)))
5763 (while (> (setq level (org-outline-level)) arg)
5764 (outline-up-heading 1 t)))
5765 (setq beg (point)
5766 heading (org-get-heading))
5767 (org-end-of-subtree t t) (setq end (point)))
5768 (if (and (buffer-live-p org-last-indirect-buffer)
5769 (not (eq org-indirect-buffer-display 'new-frame))
5770 (not arg))
5771 (kill-buffer org-last-indirect-buffer))
5772 (setq ibuf (org-get-indirect-buffer cbuf)
5773 org-last-indirect-buffer ibuf)
5774 (cond
5775 ((or (eq org-indirect-buffer-display 'new-frame)
5776 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5777 (select-frame (make-frame))
5778 (delete-other-windows)
5779 (switch-to-buffer ibuf)
5780 (org-set-frame-title heading))
5781 ((eq org-indirect-buffer-display 'dedicated-frame)
5782 (raise-frame
5783 (select-frame (or (and org-indirect-dedicated-frame
5784 (frame-live-p org-indirect-dedicated-frame)
5785 org-indirect-dedicated-frame)
5786 (setq org-indirect-dedicated-frame (make-frame)))))
5787 (delete-other-windows)
5788 (switch-to-buffer ibuf)
5789 (org-set-frame-title (concat "Indirect: " heading)))
5790 ((eq org-indirect-buffer-display 'current-window)
5791 (switch-to-buffer ibuf))
5792 ((eq org-indirect-buffer-display 'other-window)
5793 (pop-to-buffer ibuf))
5794 (t (error "Invalid value")))
5795 (if (featurep 'xemacs)
5796 (save-excursion (org-mode) (turn-on-font-lock)))
5797 (narrow-to-region beg end)
5798 (show-all)
5799 (goto-char pos)
5800 (and (window-live-p cwin) (select-window cwin))))
5802 (defun org-get-indirect-buffer (&optional buffer)
5803 (setq buffer (or buffer (current-buffer)))
5804 (let ((n 1) (base (buffer-name buffer)) bname)
5805 (while (buffer-live-p
5806 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5807 (setq n (1+ n)))
5808 (condition-case nil
5809 (make-indirect-buffer buffer bname 'clone)
5810 (error (make-indirect-buffer buffer bname)))))
5812 (defun org-set-frame-title (title)
5813 "Set the title of the current frame to the string TITLE."
5814 ;; FIXME: how to name a single frame in XEmacs???
5815 (unless (featurep 'xemacs)
5816 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5818 ;;;; Structure editing
5820 ;;; Inserting headlines
5822 (defun org-previous-line-empty-p ()
5823 (save-excursion
5824 (and (not (bobp))
5825 (or (beginning-of-line 0) t)
5826 (save-match-data
5827 (looking-at "[ \t]*$")))))
5829 (defun org-insert-heading (&optional force-heading)
5830 "Insert a new heading or item with same depth at point.
5831 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5832 If point is at the beginning of a headline, insert a sibling before the
5833 current headline. If point is not at the beginning, do not split the line,
5834 but create the new headline after the current line."
5835 (interactive "P")
5836 (if (= (buffer-size) 0)
5837 (insert "\n* ")
5838 (when (or force-heading (not (org-insert-item)))
5839 (let* ((empty-line-p nil)
5840 (head (save-excursion
5841 (condition-case nil
5842 (progn
5843 (org-back-to-heading)
5844 (setq empty-line-p (org-previous-line-empty-p))
5845 (match-string 0))
5846 (error "*"))))
5847 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5848 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5849 pos hide-previous previous-pos)
5850 (cond
5851 ((and (org-on-heading-p) (bolp)
5852 (or (bobp)
5853 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5854 ;; insert before the current line
5855 (open-line (if blank 2 1)))
5856 ((and (bolp)
5857 (not org-insert-heading-respect-content)
5858 (or (bobp)
5859 (save-excursion
5860 (backward-char 1) (not (org-invisible-p)))))
5861 ;; insert right here
5862 nil)
5864 ;; somewhere in the line
5865 (save-excursion
5866 (setq previous-pos (point-at-bol))
5867 (end-of-line)
5868 (setq hide-previous (org-invisible-p)))
5869 (and org-insert-heading-respect-content (org-show-subtree))
5870 (let ((split
5871 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5872 (save-excursion
5873 (let ((p (point)))
5874 (goto-char (point-at-bol))
5875 (and (looking-at org-complex-heading-regexp)
5876 (> p (match-beginning 4)))))))
5877 tags pos)
5878 (cond
5879 (org-insert-heading-respect-content
5880 (org-end-of-subtree nil t)
5881 (or (bolp) (newline))
5882 (or (org-previous-line-empty-p)
5883 (and blank (newline)))
5884 (open-line 1))
5885 ((org-on-heading-p)
5886 (when hide-previous
5887 (show-children)
5888 (org-show-entry))
5889 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5890 (setq tags (and (match-end 2) (match-string 2)))
5891 (and (match-end 1)
5892 (delete-region (match-beginning 1) (match-end 1)))
5893 (setq pos (point-at-bol))
5894 (or split (end-of-line 1))
5895 (delete-horizontal-space)
5896 (newline (if blank 2 1))
5897 (when tags
5898 (save-excursion
5899 (goto-char pos)
5900 (end-of-line 1)
5901 (insert " " tags)
5902 (org-set-tags nil 'align))))
5904 (or split (end-of-line 1))
5905 (newline (if blank 2 1)))))))
5906 (insert head) (just-one-space)
5907 (setq pos (point))
5908 (end-of-line 1)
5909 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5910 (when (and org-insert-heading-respect-content hide-previous)
5911 (save-excursion
5912 (goto-char previous-pos)
5913 (hide-subtree)))
5914 (run-hooks 'org-insert-heading-hook)))))
5916 (defun org-get-heading (&optional no-tags)
5917 "Return the heading of the current entry, without the stars."
5918 (save-excursion
5919 (org-back-to-heading t)
5920 (if (looking-at
5921 (if no-tags
5922 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5923 "\\*+[ \t]+\\([^\r\n]*\\)"))
5924 (match-string 1) "")))
5926 (defun org-heading-components ()
5927 "Return the components of the current heading.
5928 This is a list with the following elements:
5929 - the level as an integer
5930 - the reduced level, different if `org-odd-levels-only' is set.
5931 - the TODO keyword, or nil
5932 - the priority character, like ?A, or nil if no priority is given
5933 - the headline text itself, or the tags string if no headline text
5934 - the tags string, or nil."
5935 (save-excursion
5936 (org-back-to-heading t)
5937 (if (looking-at org-complex-heading-regexp)
5938 (list (length (match-string 1))
5939 (org-reduced-level (length (match-string 1)))
5940 (org-match-string-no-properties 2)
5941 (and (match-end 3) (aref (match-string 3) 2))
5942 (org-match-string-no-properties 4)
5943 (org-match-string-no-properties 5)))))
5945 (defun org-get-entry ()
5946 "Get the entry text, after heading, entire subtree."
5947 (save-excursion
5948 (org-back-to-heading t)
5949 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5951 (defun org-insert-heading-after-current ()
5952 "Insert a new heading with same level as current, after current subtree."
5953 (interactive)
5954 (org-back-to-heading)
5955 (org-insert-heading)
5956 (org-move-subtree-down)
5957 (end-of-line 1))
5959 (defun org-insert-heading-respect-content ()
5960 (interactive)
5961 (let ((org-insert-heading-respect-content t))
5962 (org-insert-heading t)))
5964 (defun org-insert-todo-heading-respect-content (&optional force-state)
5965 (interactive "P")
5966 (let ((org-insert-heading-respect-content t))
5967 (org-insert-todo-heading force-state t)))
5969 (defun org-insert-todo-heading (arg &optional force-heading)
5970 "Insert a new heading with the same level and TODO state as current heading.
5971 If the heading has no TODO state, or if the state is DONE, use the first
5972 state (TODO by default). Also with prefix arg, force first state."
5973 (interactive "P")
5974 (when (or force-heading (not (org-insert-item 'checkbox)))
5975 (org-insert-heading force-heading)
5976 (save-excursion
5977 (org-back-to-heading)
5978 (outline-previous-heading)
5979 (looking-at org-todo-line-regexp))
5980 (let*
5981 ((new-mark-x
5982 (if (or arg
5983 (not (match-beginning 2))
5984 (member (match-string 2) org-done-keywords))
5985 (car org-todo-keywords-1)
5986 (match-string 2)))
5987 (new-mark
5989 (run-hook-with-args-until-success
5990 'org-todo-get-default-hook new-mark-x nil)
5991 new-mark-x)))
5992 (beginning-of-line 1)
5993 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5994 (if org-treat-insert-todo-heading-as-state-change
5995 (org-todo new-mark)
5996 (insert new-mark " "))))
5997 (when org-provide-todo-statistics
5998 (org-update-parent-todo-statistics))))
6000 (defun org-insert-subheading (arg)
6001 "Insert a new subheading and demote it.
6002 Works for outline headings and for plain lists alike."
6003 (interactive "P")
6004 (org-insert-heading arg)
6005 (cond
6006 ((org-on-heading-p) (org-do-demote))
6007 ((org-at-item-p) (org-indent-item 1))))
6009 (defun org-insert-todo-subheading (arg)
6010 "Insert a new subheading with TODO keyword or checkbox and demote it.
6011 Works for outline headings and for plain lists alike."
6012 (interactive "P")
6013 (org-insert-todo-heading arg)
6014 (cond
6015 ((org-on-heading-p) (org-do-demote))
6016 ((org-at-item-p) (org-indent-item 1))))
6018 ;;; Promotion and Demotion
6020 (defvar org-after-demote-entry-hook nil
6021 "Hook run after an entry has been demoted.
6022 The cursor will be at the beginning of the entry.
6023 When a subtree is being demoted, the hook will be called for each node.")
6025 (defvar org-after-promote-entry-hook nil
6026 "Hook run after an entry has been promoted.
6027 The cursor will be at the beginning of the entry.
6028 When a subtree is being promoted, the hook will be called for each node.")
6030 (defun org-promote-subtree ()
6031 "Promote the entire subtree.
6032 See also `org-promote'."
6033 (interactive)
6034 (save-excursion
6035 (org-map-tree 'org-promote))
6036 (org-fix-position-after-promote))
6038 (defun org-demote-subtree ()
6039 "Demote the entire subtree. See `org-demote'.
6040 See also `org-promote'."
6041 (interactive)
6042 (save-excursion
6043 (org-map-tree 'org-demote))
6044 (org-fix-position-after-promote))
6047 (defun org-do-promote ()
6048 "Promote the current heading higher up the tree.
6049 If the region is active in `transient-mark-mode', promote all headings
6050 in the region."
6051 (interactive)
6052 (save-excursion
6053 (if (org-region-active-p)
6054 (org-map-region 'org-promote (region-beginning) (region-end))
6055 (org-promote)))
6056 (org-fix-position-after-promote))
6058 (defun org-do-demote ()
6059 "Demote the current heading lower down the tree.
6060 If the region is active in `transient-mark-mode', demote all headings
6061 in the region."
6062 (interactive)
6063 (save-excursion
6064 (if (org-region-active-p)
6065 (org-map-region 'org-demote (region-beginning) (region-end))
6066 (org-demote)))
6067 (org-fix-position-after-promote))
6069 (defun org-fix-position-after-promote ()
6070 "Make sure that after pro/demotion cursor position is right."
6071 (let ((pos (point)))
6072 (when (save-excursion
6073 (beginning-of-line 1)
6074 (looking-at org-todo-line-regexp)
6075 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6076 (cond ((eobp) (insert " "))
6077 ((eolp) (insert " "))
6078 ((equal (char-after) ?\ ) (forward-char 1))))))
6080 (defun org-reduced-level (l)
6081 "Compute the effective level of a heading.
6082 This takes into account the setting of `org-odd-levels-only'."
6083 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6085 (defun org-get-valid-level (level &optional change)
6086 "Rectify a level change under the influence of `org-odd-levels-only'
6087 LEVEL is a current level, CHANGE is by how much the level should be
6088 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6089 even level numbers will become the next higher odd number."
6090 (if org-odd-levels-only
6091 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6092 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6093 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6094 (max 1 (+ level (or change 0)))))
6096 (if (boundp 'define-obsolete-function-alias)
6097 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6098 (define-obsolete-function-alias 'org-get-legal-level
6099 'org-get-valid-level)
6100 (define-obsolete-function-alias 'org-get-legal-level
6101 'org-get-valid-level "23.1")))
6103 (defun org-promote ()
6104 "Promote the current heading higher up the tree.
6105 If the region is active in `transient-mark-mode', promote all headings
6106 in the region."
6107 (org-back-to-heading t)
6108 (let* ((level (save-match-data (funcall outline-level)))
6109 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6110 (diff (abs (- level (length up-head) -1))))
6111 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6112 (replace-match up-head nil t)
6113 ;; Fixup tag positioning
6114 (and org-auto-align-tags (org-set-tags nil t))
6115 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6116 (run-hooks 'org-after-promote-entry-hook)))
6118 (defun org-demote ()
6119 "Demote the current heading lower down the tree.
6120 If the region is active in `transient-mark-mode', demote all headings
6121 in the region."
6122 (org-back-to-heading t)
6123 (let* ((level (save-match-data (funcall outline-level)))
6124 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6125 (diff (abs (- level (length down-head) -1))))
6126 (replace-match down-head nil t)
6127 ;; Fixup tag positioning
6128 (and org-auto-align-tags (org-set-tags nil t))
6129 (if org-adapt-indentation (org-fixup-indentation diff))
6130 (run-hooks 'org-after-demote-entry-hook)))
6132 (defun org-map-tree (fun)
6133 "Call FUN for every heading underneath the current one."
6134 (org-back-to-heading)
6135 (let ((level (funcall outline-level)))
6136 (save-excursion
6137 (funcall fun)
6138 (while (and (progn
6139 (outline-next-heading)
6140 (> (funcall outline-level) level))
6141 (not (eobp)))
6142 (funcall fun)))))
6144 (defun org-map-region (fun beg end)
6145 "Call FUN for every heading between BEG and END."
6146 (let ((org-ignore-region t))
6147 (save-excursion
6148 (setq end (copy-marker end))
6149 (goto-char beg)
6150 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6151 (< (point) end))
6152 (funcall fun))
6153 (while (and (progn
6154 (outline-next-heading)
6155 (< (point) end))
6156 (not (eobp)))
6157 (funcall fun)))))
6159 (defun org-fixup-indentation (diff)
6160 "Change the indentation in the current entry by DIFF
6161 However, if any line in the current entry has no indentation, or if it
6162 would end up with no indentation after the change, nothing at all is done."
6163 (save-excursion
6164 (let ((end (save-excursion (outline-next-heading)
6165 (point-marker)))
6166 (prohibit (if (> diff 0)
6167 "^\\S-"
6168 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6169 col)
6170 (unless (save-excursion (end-of-line 1)
6171 (re-search-forward prohibit end t))
6172 (while (and (< (point) end)
6173 (re-search-forward "^[ \t]+" end t))
6174 (goto-char (match-end 0))
6175 (setq col (current-column))
6176 (if (< diff 0) (replace-match ""))
6177 (org-indent-to-column (+ diff col))))
6178 (move-marker end nil))))
6180 (defun org-convert-to-odd-levels ()
6181 "Convert an org-mode file with all levels allowed to one with odd levels.
6182 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6183 level 5 etc."
6184 (interactive)
6185 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6186 (let ((outline-regexp org-outline-regexp)
6187 (outline-level 'org-outline-level)
6188 (org-odd-levels-only nil) n)
6189 (save-excursion
6190 (goto-char (point-min))
6191 (while (re-search-forward "^\\*\\*+ " nil t)
6192 (setq n (- (length (match-string 0)) 2))
6193 (while (>= (setq n (1- n)) 0)
6194 (org-demote))
6195 (end-of-line 1))))))
6197 (defun org-convert-to-oddeven-levels ()
6198 "Convert an org-mode file with only odd levels to one with odd and even levels.
6199 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6200 section with an even level, conversion would destroy the structure of the file. An error
6201 is signaled in this case."
6202 (interactive)
6203 (goto-char (point-min))
6204 ;; First check if there are no even levels
6205 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6206 (org-show-context t)
6207 (error "Not all levels are odd in this file. Conversion not possible"))
6208 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6209 (let ((outline-regexp org-outline-regexp)
6210 (outline-level 'org-outline-level)
6211 (org-odd-levels-only nil) n)
6212 (save-excursion
6213 (goto-char (point-min))
6214 (while (re-search-forward "^\\*\\*+ " nil t)
6215 (setq n (/ (1- (length (match-string 0))) 2))
6216 (while (>= (setq n (1- n)) 0)
6217 (org-promote))
6218 (end-of-line 1))))))
6220 (defun org-tr-level (n)
6221 "Make N odd if required."
6222 (if org-odd-levels-only (1+ (/ n 2)) n))
6224 ;;; Vertical tree motion, cutting and pasting of subtrees
6226 (defun org-move-subtree-up (&optional arg)
6227 "Move the current subtree up past ARG headlines of the same level."
6228 (interactive "p")
6229 (org-move-subtree-down (- (prefix-numeric-value arg))))
6231 (defun org-move-subtree-down (&optional arg)
6232 "Move the current subtree down past ARG headlines of the same level."
6233 (interactive "p")
6234 (setq arg (prefix-numeric-value arg))
6235 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6236 'org-get-last-sibling))
6237 (ins-point (make-marker))
6238 (cnt (abs arg))
6239 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6240 ;; Select the tree
6241 (org-back-to-heading)
6242 (setq beg0 (point))
6243 (save-excursion
6244 (setq ne-beg (org-back-over-empty-lines))
6245 (setq beg (point)))
6246 (save-match-data
6247 (save-excursion (outline-end-of-heading)
6248 (setq folded (org-invisible-p)))
6249 (outline-end-of-subtree))
6250 (outline-next-heading)
6251 (setq ne-end (org-back-over-empty-lines))
6252 (setq end (point))
6253 (goto-char beg0)
6254 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6255 ;; include less whitespace
6256 (save-excursion
6257 (goto-char beg)
6258 (forward-line (- ne-beg ne-end))
6259 (setq beg (point))))
6260 ;; Find insertion point, with error handling
6261 (while (> cnt 0)
6262 (or (and (funcall movfunc) (looking-at outline-regexp))
6263 (progn (goto-char beg0)
6264 (error "Cannot move past superior level or buffer limit")))
6265 (setq cnt (1- cnt)))
6266 (if (> arg 0)
6267 ;; Moving forward - still need to move over subtree
6268 (progn (org-end-of-subtree t t)
6269 (save-excursion
6270 (org-back-over-empty-lines)
6271 (or (bolp) (newline)))))
6272 (setq ne-ins (org-back-over-empty-lines))
6273 (move-marker ins-point (point))
6274 (setq txt (buffer-substring beg end))
6275 (org-save-markers-in-region beg end)
6276 (delete-region beg end)
6277 (org-remove-empty-overlays-at beg)
6278 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6279 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6280 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6281 (let ((bbb (point)))
6282 (insert-before-markers txt)
6283 (org-reinstall-markers-in-region bbb)
6284 (move-marker ins-point bbb))
6285 (or (bolp) (insert "\n"))
6286 (setq ins-end (point))
6287 (goto-char ins-point)
6288 (org-skip-whitespace)
6289 (when (and (< arg 0)
6290 (org-first-sibling-p)
6291 (> ne-ins ne-beg))
6292 ;; Move whitespace back to beginning
6293 (save-excursion
6294 (goto-char ins-end)
6295 (let ((kill-whole-line t))
6296 (kill-line (- ne-ins ne-beg)) (point)))
6297 (insert (make-string (- ne-ins ne-beg) ?\n)))
6298 (move-marker ins-point nil)
6299 (if folded
6300 (hide-subtree)
6301 (org-show-entry)
6302 (show-children)
6303 (org-cycle-hide-drawers 'children))
6304 (org-clean-visibility-after-subtree-move)))
6306 (defvar org-subtree-clip ""
6307 "Clipboard for cut and paste of subtrees.
6308 This is actually only a copy of the kill, because we use the normal kill
6309 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6311 (defvar org-subtree-clip-folded nil
6312 "Was the last copied subtree folded?
6313 This is used to fold the tree back after pasting.")
6315 (defun org-cut-subtree (&optional n)
6316 "Cut the current subtree into the clipboard.
6317 With prefix arg N, cut this many sequential subtrees.
6318 This is a short-hand for marking the subtree and then cutting it."
6319 (interactive "p")
6320 (org-copy-subtree n 'cut))
6322 (defun org-copy-subtree (&optional n cut force-store-markers)
6323 "Cut the current subtree into the clipboard.
6324 With prefix arg N, cut this many sequential subtrees.
6325 This is a short-hand for marking the subtree and then copying it.
6326 If CUT is non-nil, actually cut the subtree.
6327 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6328 of some markers in the region, even if CUT is non-nil. This is
6329 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6330 (interactive "p")
6331 (let (beg end folded (beg0 (point)))
6332 (if (interactive-p)
6333 (org-back-to-heading nil) ; take what looks like a subtree
6334 (org-back-to-heading t)) ; take what is really there
6335 (org-back-over-empty-lines)
6336 (setq beg (point))
6337 (skip-chars-forward " \t\r\n")
6338 (save-match-data
6339 (save-excursion (outline-end-of-heading)
6340 (setq folded (org-invisible-p)))
6341 (condition-case nil
6342 (org-forward-same-level (1- n) t)
6343 (error nil))
6344 (org-end-of-subtree t t))
6345 (org-back-over-empty-lines)
6346 (setq end (point))
6347 (goto-char beg0)
6348 (when (> end beg)
6349 (setq org-subtree-clip-folded folded)
6350 (when (or cut force-store-markers)
6351 (org-save-markers-in-region beg end))
6352 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6353 (setq org-subtree-clip (current-kill 0))
6354 (message "%s: Subtree(s) with %d characters"
6355 (if cut "Cut" "Copied")
6356 (length org-subtree-clip)))))
6358 (defun org-paste-subtree (&optional level tree for-yank)
6359 "Paste the clipboard as a subtree, with modification of headline level.
6360 The entire subtree is promoted or demoted in order to match a new headline
6361 level.
6363 If the cursor is at the beginning of a headline, the same level as
6364 that headline is used to paste the tree
6366 If not, the new level is derived from the *visible* headings
6367 before and after the insertion point, and taken to be the inferior headline
6368 level of the two. So if the previous visible heading is level 3 and the
6369 next is level 4 (or vice versa), level 4 will be used for insertion.
6370 This makes sure that the subtree remains an independent subtree and does
6371 not swallow low level entries.
6373 You can also force a different level, either by using a numeric prefix
6374 argument, or by inserting the heading marker by hand. For example, if the
6375 cursor is after \"*****\", then the tree will be shifted to level 5.
6377 If optional TREE is given, use this text instead of the kill ring.
6379 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6380 move back over whitespace before inserting, and move point to the end of
6381 the inserted text when done."
6382 (interactive "P")
6383 (setq tree (or tree (and kill-ring (current-kill 0))))
6384 (unless (org-kill-is-subtree-p tree)
6385 (error "%s"
6386 (substitute-command-keys
6387 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6388 (let* ((visp (not (org-invisible-p)))
6389 (txt tree)
6390 (^re (concat "^\\(" outline-regexp "\\)"))
6391 (re (concat "\\(" outline-regexp "\\)"))
6392 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6394 (old-level (if (string-match ^re txt)
6395 (- (match-end 0) (match-beginning 0) 1)
6396 -1))
6397 (force-level (cond (level (prefix-numeric-value level))
6398 ((and (looking-at "[ \t]*$")
6399 (string-match
6400 ^re_ (buffer-substring
6401 (point-at-bol) (point))))
6402 (- (match-end 1) (match-beginning 1)))
6403 ((and (bolp)
6404 (looking-at org-outline-regexp))
6405 (- (match-end 0) (point) 1))
6406 (t nil)))
6407 (previous-level (save-excursion
6408 (condition-case nil
6409 (progn
6410 (outline-previous-visible-heading 1)
6411 (if (looking-at re)
6412 (- (match-end 0) (match-beginning 0) 1)
6414 (error 1))))
6415 (next-level (save-excursion
6416 (condition-case nil
6417 (progn
6418 (or (looking-at outline-regexp)
6419 (outline-next-visible-heading 1))
6420 (if (looking-at re)
6421 (- (match-end 0) (match-beginning 0) 1)
6423 (error 1))))
6424 (new-level (or force-level (max previous-level next-level)))
6425 (shift (if (or (= old-level -1)
6426 (= new-level -1)
6427 (= old-level new-level))
6429 (- new-level old-level)))
6430 (delta (if (> shift 0) -1 1))
6431 (func (if (> shift 0) 'org-demote 'org-promote))
6432 (org-odd-levels-only nil)
6433 beg end newend)
6434 ;; Remove the forced level indicator
6435 (if force-level
6436 (delete-region (point-at-bol) (point)))
6437 ;; Paste
6438 (beginning-of-line 1)
6439 (unless for-yank (org-back-over-empty-lines))
6440 (setq beg (point))
6441 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6442 (insert-before-markers txt)
6443 (unless (string-match "\n\\'" txt) (insert "\n"))
6444 (setq newend (point))
6445 (org-reinstall-markers-in-region beg)
6446 (setq end (point))
6447 (goto-char beg)
6448 (skip-chars-forward " \t\n\r")
6449 (setq beg (point))
6450 (if (and (org-invisible-p) visp)
6451 (save-excursion (outline-show-heading)))
6452 ;; Shift if necessary
6453 (unless (= shift 0)
6454 (save-restriction
6455 (narrow-to-region beg end)
6456 (while (not (= shift 0))
6457 (org-map-region func (point-min) (point-max))
6458 (setq shift (+ delta shift)))
6459 (goto-char (point-min))
6460 (setq newend (point-max))))
6461 (when (or (interactive-p) for-yank)
6462 (message "Clipboard pasted as level %d subtree" new-level))
6463 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6464 kill-ring
6465 (eq org-subtree-clip (current-kill 0))
6466 org-subtree-clip-folded)
6467 ;; The tree was folded before it was killed/copied
6468 (hide-subtree))
6469 (and for-yank (goto-char newend))))
6471 (defun org-kill-is-subtree-p (&optional txt)
6472 "Check if the current kill is an outline subtree, or a set of trees.
6473 Returns nil if kill does not start with a headline, or if the first
6474 headline level is not the largest headline level in the tree.
6475 So this will actually accept several entries of equal levels as well,
6476 which is OK for `org-paste-subtree'.
6477 If optional TXT is given, check this string instead of the current kill."
6478 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6479 (start-level (and kill
6480 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6481 org-outline-regexp "\\)")
6482 kill)
6483 (- (match-end 2) (match-beginning 2) 1)))
6484 (re (concat "^" org-outline-regexp))
6485 (start (1+ (or (match-beginning 2) -1))))
6486 (if (not start-level)
6487 (progn
6488 nil) ;; does not even start with a heading
6489 (catch 'exit
6490 (while (setq start (string-match re kill (1+ start)))
6491 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6492 (throw 'exit nil)))
6493 t))))
6495 (defvar org-markers-to-move nil
6496 "Markers that should be moved with a cut-and-paste operation.
6497 Those markers are stored together with their positions relative to
6498 the start of the region.")
6500 (defun org-save-markers-in-region (beg end)
6501 "Check markers in region.
6502 If these markers are between BEG and END, record their position relative
6503 to BEG, so that after moving the block of text, we can put the markers back
6504 into place.
6505 This function gets called just before an entry or tree gets cut from the
6506 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6507 called immediately, to move the markers with the entries."
6508 (setq org-markers-to-move nil)
6509 (when (featurep 'org-clock)
6510 (org-clock-save-markers-for-cut-and-paste beg end))
6511 (when (featurep 'org-agenda)
6512 (org-agenda-save-markers-for-cut-and-paste beg end)))
6514 (defun org-check-and-save-marker (marker beg end)
6515 "Check if MARKER is between BEG and END.
6516 If yes, remember the marker and the distance to BEG."
6517 (when (and (marker-buffer marker)
6518 (equal (marker-buffer marker) (current-buffer)))
6519 (if (and (>= marker beg) (< marker end))
6520 (push (cons marker (- marker beg)) org-markers-to-move))))
6522 (defun org-reinstall-markers-in-region (beg)
6523 "Move all remembered markers to their position relative to BEG."
6524 (mapc (lambda (x)
6525 (move-marker (car x) (+ beg (cdr x))))
6526 org-markers-to-move)
6527 (setq org-markers-to-move nil))
6529 (defun org-narrow-to-subtree ()
6530 "Narrow buffer to the current subtree."
6531 (interactive)
6532 (save-excursion
6533 (save-match-data
6534 (narrow-to-region
6535 (progn (org-back-to-heading t) (point))
6536 (progn (org-end-of-subtree t t) (point))))))
6538 (defun org-clone-subtree-with-time-shift (n &optional shift)
6539 "Clone the task (subtree) at point N times.
6540 The clones will be inserted as siblings.
6542 In interactive use, the user will be prompted for the number of clones
6543 to be produced, and for a time SHIFT, which may be a repeater as used
6544 in time stamps, for example `+3d'.
6546 When a valid repeater is given and the entry contains any time stamps,
6547 the clones will become a sequence in time, with time stamps in the
6548 subtree shifted for each clone produced. If SHIFT is nil or the
6549 empty string, time stamps will be left alone.
6551 If the original subtree did contain time stamps with a repeater,
6552 the following will happen:
6553 - the repeater will be removed in each clone
6554 - an additional clone will be produced, with the current, unshifted
6555 date(s) in the entry.
6556 - the original entry will be placed *after* all the clones, with
6557 repeater intact.
6558 - the start days in the repeater in the original entry will be shifted
6559 to past the last clone.
6560 I this way you can spell out a number of instances of a repeating task,
6561 and still retain the repeater to cover future instances of the task."
6562 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6563 (let (beg end template task
6564 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6565 (if (not (and (integerp n) (> n 0)))
6566 (error "Invalid number of replications %s" n))
6567 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6568 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6569 shift)))
6570 (error "Invalid shift specification %s" shift))
6571 (when doshift
6572 (setq shift-n (string-to-number (match-string 1 shift))
6573 shift-what (cdr (assoc (match-string 2 shift)
6574 '(("d" . day) ("w" . week)
6575 ("m" . month) ("y" . year))))))
6576 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6577 (setq nmin 1 nmax n)
6578 (org-back-to-heading t)
6579 (setq beg (point))
6580 (org-end-of-subtree t t)
6581 (setq end (point))
6582 (setq template (buffer-substring beg end))
6583 (when (and doshift
6584 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6585 (delete-region beg end)
6586 (setq end beg)
6587 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6588 (goto-char end)
6589 (loop for n from nmin to nmax do
6590 (if (not doshift)
6591 (setq task template)
6592 (with-temp-buffer
6593 (insert template)
6594 (org-mode)
6595 (goto-char (point-min))
6596 (while (re-search-forward org-ts-regexp-both nil t)
6597 (org-timestamp-change (* n shift-n) shift-what))
6598 (unless (= n n-no-remove)
6599 (goto-char (point-min))
6600 (while (re-search-forward org-ts-regexp nil t)
6601 (save-excursion
6602 (goto-char (match-beginning 0))
6603 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6604 (delete-region (match-beginning 1) (match-end 1))))))
6605 (setq task (buffer-string))))
6606 (insert task))
6607 (goto-char beg)))
6609 ;;; Outline Sorting
6611 (defun org-sort (with-case)
6612 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6613 Optional argument WITH-CASE means sort case-sensitively.
6614 With a double prefix argument, also remove duplicate entries."
6615 (interactive "P")
6616 (if (org-at-table-p)
6617 (org-call-with-arg 'org-table-sort-lines with-case)
6618 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6620 (defun org-sort-remove-invisible (s)
6621 (remove-text-properties 0 (length s) org-rm-props s)
6622 (while (string-match org-bracket-link-regexp s)
6623 (setq s (replace-match (if (match-end 2)
6624 (match-string 3 s)
6625 (match-string 1 s)) t t s)))
6628 (defvar org-priority-regexp) ; defined later in the file
6630 (defvar org-after-sorting-entries-or-items-hook nil
6631 "Hook that is run after a bunch of entries or items have been sorted.
6632 When children are sorted, the cursor is in the parent line when this
6633 hook gets called. When a region or a plain list is sorted, the cursor
6634 will be in the first entry of the sorted region/list.")
6636 (defun org-sort-entries-or-items
6637 (&optional with-case sorting-type getkey-func compare-func property)
6638 "Sort entries on a certain level of an outline tree, or plain list items.
6639 If there is an active region, the entries in the region are sorted.
6640 Else, if the cursor is before the first entry, sort the top-level items.
6641 Else, the children of the entry at point are sorted.
6642 If the cursor is at the first item in a plain list, the list items will be
6643 sorted.
6645 Sorting can be alphabetically, numerically, by date/time as given by
6646 a time stamp, by a property or by priority.
6648 The command prompts for the sorting type unless it has been given to the
6649 function through the SORTING-TYPE argument, which needs to a character,
6650 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6651 precise meaning of each character:
6653 n Numerically, by converting the beginning of the entry/item to a number.
6654 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6655 t By date/time, either the first active time stamp in the entry, or, if
6656 none exist, by the first inactive one.
6657 In items, only the first line will be chekced.
6658 s By the scheduled date/time.
6659 d By deadline date/time.
6660 c By creation time, which is assumed to be the first inactive time stamp
6661 at the beginning of a line.
6662 p By priority according to the cookie.
6663 r By the value of a property.
6665 Capital letters will reverse the sort order.
6667 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6668 called with point at the beginning of the record. It must return either
6669 a string or a number that should serve as the sorting key for that record.
6671 Comparing entries ignores case by default. However, with an optional argument
6672 WITH-CASE, the sorting considers case as well."
6673 (interactive "P")
6674 (let ((case-func (if with-case 'identity 'downcase))
6675 start beg end stars re re2
6676 txt what tmp plain-list-p)
6677 ;; Find beginning and end of region to sort
6678 (cond
6679 ((org-region-active-p)
6680 ;; we will sort the region
6681 (setq end (region-end)
6682 what "region")
6683 (goto-char (region-beginning))
6684 (if (not (org-on-heading-p)) (outline-next-heading))
6685 (setq start (point)))
6686 ((org-at-item-p)
6687 ;; we will sort this plain list
6688 (org-beginning-of-item-list) (setq start (point))
6689 (org-end-of-item-list) (setq end (point))
6690 (goto-char start)
6691 (setq plain-list-p t
6692 what "plain list"))
6693 ((or (org-on-heading-p)
6694 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6695 ;; we will sort the children of the current headline
6696 (org-back-to-heading)
6697 (setq start (point)
6698 end (progn (org-end-of-subtree t t)
6699 (org-back-over-empty-lines)
6700 (point))
6701 what "children")
6702 (goto-char start)
6703 (show-subtree)
6704 (outline-next-heading))
6706 ;; we will sort the top-level entries in this file
6707 (goto-char (point-min))
6708 (or (org-on-heading-p) (outline-next-heading))
6709 (setq start (point) end (point-max) what "top-level")
6710 (goto-char start)
6711 (show-all)))
6713 (setq beg (point))
6714 (if (>= beg end) (error "Nothing to sort"))
6716 (unless plain-list-p
6717 (looking-at "\\(\\*+\\)")
6718 (setq stars (match-string 1)
6719 re (concat "^" (regexp-quote stars) " +")
6720 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6721 txt (buffer-substring beg end))
6722 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6723 (if (and (not (equal stars "*")) (string-match re2 txt))
6724 (error "Region to sort contains a level above the first entry")))
6726 (unless sorting-type
6727 (message
6728 (if plain-list-p
6729 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6730 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6731 [t]ime [s]cheduled [d]eadline [c]reated
6732 A/N/T/S/D/C/P/O/F means reversed:")
6733 what)
6734 (setq sorting-type (read-char-exclusive))
6736 (and (= (downcase sorting-type) ?f)
6737 (setq getkey-func
6738 (org-icompleting-read "Sort using function: "
6739 obarray 'fboundp t nil nil))
6740 (setq getkey-func (intern getkey-func)))
6742 (and (= (downcase sorting-type) ?r)
6743 (setq property
6744 (org-icompleting-read "Property: "
6745 (mapcar 'list (org-buffer-property-keys t))
6746 nil t))))
6748 (message "Sorting entries...")
6750 (save-restriction
6751 (narrow-to-region start end)
6753 (let ((dcst (downcase sorting-type))
6754 (case-fold-search nil)
6755 (now (current-time)))
6756 (sort-subr
6757 (/= dcst sorting-type)
6758 ;; This function moves to the beginning character of the "record" to
6759 ;; be sorted.
6760 (if plain-list-p
6761 (lambda nil
6762 (if (org-at-item-p) t (goto-char (point-max))))
6763 (lambda nil
6764 (if (re-search-forward re nil t)
6765 (goto-char (match-beginning 0))
6766 (goto-char (point-max)))))
6767 ;; This function moves to the last character of the "record" being
6768 ;; sorted.
6769 (if plain-list-p
6770 'org-end-of-item
6771 (lambda nil
6772 (save-match-data
6773 (condition-case nil
6774 (outline-forward-same-level 1)
6775 (error
6776 (goto-char (point-max)))))))
6778 ;; This function returns the value that gets sorted against.
6779 (if plain-list-p
6780 (lambda nil
6781 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6782 (cond
6783 ((= dcst ?n)
6784 (string-to-number (buffer-substring (match-end 0)
6785 (point-at-eol))))
6786 ((= dcst ?a)
6787 (buffer-substring (match-end 0) (point-at-eol)))
6788 ((= dcst ?t)
6789 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6790 (re-search-forward org-ts-regexp-both
6791 (point-at-eol) t))
6792 (org-time-string-to-seconds (match-string 0))
6793 (org-float-time now)))
6794 ((= dcst ?f)
6795 (if getkey-func
6796 (progn
6797 (setq tmp (funcall getkey-func))
6798 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6799 tmp)
6800 (error "Invalid key function `%s'" getkey-func)))
6801 (t (error "Invalid sorting type `%c'" sorting-type)))))
6802 (lambda nil
6803 (cond
6804 ((= dcst ?n)
6805 (if (looking-at org-complex-heading-regexp)
6806 (string-to-number (match-string 4))
6807 nil))
6808 ((= dcst ?a)
6809 (if (looking-at org-complex-heading-regexp)
6810 (funcall case-func (match-string 4))
6811 nil))
6812 ((= dcst ?t)
6813 (let ((end (save-excursion (outline-next-heading) (point))))
6814 (if (or (re-search-forward org-ts-regexp end t)
6815 (re-search-forward org-ts-regexp-both end t))
6816 (org-time-string-to-seconds (match-string 0))
6817 (org-float-time now))))
6818 ((= dcst ?c)
6819 (let ((end (save-excursion (outline-next-heading) (point))))
6820 (if (re-search-forward
6821 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6822 end t)
6823 (org-time-string-to-seconds (match-string 0))
6824 (org-float-time now))))
6825 ((= dcst ?s)
6826 (let ((end (save-excursion (outline-next-heading) (point))))
6827 (if (re-search-forward org-scheduled-time-regexp end t)
6828 (org-time-string-to-seconds (match-string 1))
6829 (org-float-time now))))
6830 ((= dcst ?d)
6831 (let ((end (save-excursion (outline-next-heading) (point))))
6832 (if (re-search-forward org-deadline-time-regexp end t)
6833 (org-time-string-to-seconds (match-string 1))
6834 (org-float-time now))))
6835 ((= dcst ?p)
6836 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6837 (string-to-char (match-string 2))
6838 org-default-priority))
6839 ((= dcst ?r)
6840 (or (org-entry-get nil property) ""))
6841 ((= dcst ?o)
6842 (if (looking-at org-complex-heading-regexp)
6843 (- 9999 (length (member (match-string 2)
6844 org-todo-keywords-1)))))
6845 ((= dcst ?f)
6846 (if getkey-func
6847 (progn
6848 (setq tmp (funcall getkey-func))
6849 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6850 tmp)
6851 (error "Invalid key function `%s'" getkey-func)))
6852 (t (error "Invalid sorting type `%c'" sorting-type)))))
6854 (cond
6855 ((= dcst ?a) 'string<)
6856 ((= dcst ?f) compare-func)
6857 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6858 (t nil)))))
6859 (run-hooks 'org-after-sorting-entries-or-items-hook)
6860 (message "Sorting entries...done")))
6862 (defun org-do-sort (table what &optional with-case sorting-type)
6863 "Sort TABLE of WHAT according to SORTING-TYPE.
6864 The user will be prompted for the SORTING-TYPE if the call to this
6865 function does not specify it. WHAT is only for the prompt, to indicate
6866 what is being sorted. The sorting key will be extracted from
6867 the car of the elements of the table.
6868 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6869 (unless sorting-type
6870 (message
6871 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6872 what)
6873 (setq sorting-type (read-char-exclusive)))
6874 (let ((dcst (downcase sorting-type))
6875 extractfun comparefun)
6876 ;; Define the appropriate functions
6877 (cond
6878 ((= dcst ?n)
6879 (setq extractfun 'string-to-number
6880 comparefun (if (= dcst sorting-type) '< '>)))
6881 ((= dcst ?a)
6882 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6883 (lambda(x) (downcase (org-sort-remove-invisible x))))
6884 comparefun (if (= dcst sorting-type)
6885 'string<
6886 (lambda (a b) (and (not (string< a b))
6887 (not (string= a b)))))))
6888 ((= dcst ?t)
6889 (setq extractfun
6890 (lambda (x)
6891 (if (or (string-match org-ts-regexp x)
6892 (string-match org-ts-regexp-both x))
6893 (org-float-time
6894 (org-time-string-to-time (match-string 0 x)))
6896 comparefun (if (= dcst sorting-type) '< '>)))
6897 (t (error "Invalid sorting type `%c'" sorting-type)))
6899 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6900 table)
6901 (lambda (a b) (funcall comparefun (car a) (car b))))))
6904 ;;; The orgstruct minor mode
6906 ;; Define a minor mode which can be used in other modes in order to
6907 ;; integrate the org-mode structure editing commands.
6909 ;; This is really a hack, because the org-mode structure commands use
6910 ;; keys which normally belong to the major mode. Here is how it
6911 ;; works: The minor mode defines all the keys necessary to operate the
6912 ;; structure commands, but wraps the commands into a function which
6913 ;; tests if the cursor is currently at a headline or a plain list
6914 ;; item. If that is the case, the structure command is used,
6915 ;; temporarily setting many Org-mode variables like regular
6916 ;; expressions for filling etc. However, when any of those keys is
6917 ;; used at a different location, function uses `key-binding' to look
6918 ;; up if the key has an associated command in another currently active
6919 ;; keymap (minor modes, major mode, global), and executes that
6920 ;; command. There might be problems if any of the keys is otherwise
6921 ;; used as a prefix key.
6923 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6924 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6925 ;; addresses this by checking explicitly for both bindings.
6927 (defvar orgstruct-mode-map (make-sparse-keymap)
6928 "Keymap for the minor `orgstruct-mode'.")
6930 (defvar org-local-vars nil
6931 "List of local variables, for use by `orgstruct-mode'")
6933 ;;;###autoload
6934 (define-minor-mode orgstruct-mode
6935 "Toggle the minor more `orgstruct-mode'.
6936 This mode is for using Org-mode structure commands in other modes.
6937 The following key behave as if Org-mode was active, if the cursor
6938 is on a headline, or on a plain list item (both in the definition
6939 of Org-mode).
6941 M-up Move entry/item up
6942 M-down Move entry/item down
6943 M-left Promote
6944 M-right Demote
6945 M-S-up Move entry/item up
6946 M-S-down Move entry/item down
6947 M-S-left Promote subtree
6948 M-S-right Demote subtree
6949 M-q Fill paragraph and items like in Org-mode
6950 C-c ^ Sort entries
6951 C-c - Cycle list bullet
6952 TAB Cycle item visibility
6953 M-RET Insert new heading/item
6954 S-M-RET Insert new TODO heading / Checkbox item
6955 C-c C-c Set tags / toggle checkbox"
6956 nil " OrgStruct" nil
6957 (org-load-modules-maybe)
6958 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6960 ;;;###autoload
6961 (defun turn-on-orgstruct ()
6962 "Unconditionally turn on `orgstruct-mode'."
6963 (orgstruct-mode 1))
6965 (defun orgstruct++-mode (&optional arg)
6966 "Toggle `orgstruct-mode', the enhanced version of it.
6967 In addition to setting orgstruct-mode, this also exports all indentation
6968 and autofilling variables from org-mode into the buffer. It will also
6969 recognize item context in multiline items.
6970 Note that turning off orgstruct-mode will *not* remove the
6971 indentation/paragraph settings. This can only be done by refreshing the
6972 major mode, for example with \\[normal-mode]."
6973 (interactive "P")
6974 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6975 (if (< arg 1)
6976 (orgstruct-mode -1)
6977 (orgstruct-mode 1)
6978 (let (var val)
6979 (mapc
6980 (lambda (x)
6981 (when (string-match
6982 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6983 (symbol-name (car x)))
6984 (setq var (car x) val (nth 1 x))
6985 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6986 org-local-vars)
6987 (org-set-local 'orgstruct-is-++ t))))
6989 (defvar orgstruct-is-++ nil
6990 "Is orgstruct-mode in ++ version in the current-buffer?")
6991 (make-variable-buffer-local 'orgstruct-is-++)
6993 ;;;###autoload
6994 (defun turn-on-orgstruct++ ()
6995 "Unconditionally turn on `orgstruct++-mode'."
6996 (orgstruct++-mode 1))
6998 (defun orgstruct-error ()
6999 "Error when there is no default binding for a structure key."
7000 (interactive)
7001 (error "This key has no function outside structure elements"))
7003 (defun orgstruct-setup ()
7004 "Setup orgstruct keymaps."
7005 (let ((nfunc 0)
7006 (bindings
7007 (list
7008 '([(meta up)] org-metaup)
7009 '([(meta down)] org-metadown)
7010 '([(meta left)] org-metaleft)
7011 '([(meta right)] org-metaright)
7012 '([(meta shift up)] org-shiftmetaup)
7013 '([(meta shift down)] org-shiftmetadown)
7014 '([(meta shift left)] org-shiftmetaleft)
7015 '([(meta shift right)] org-shiftmetaright)
7016 '([?\e (up)] org-metaup)
7017 '([?\e (down)] org-metadown)
7018 '([?\e (left)] org-metaleft)
7019 '([?\e (right)] org-metaright)
7020 '([?\e (shift up)] org-shiftmetaup)
7021 '([?\e (shift down)] org-shiftmetadown)
7022 '([?\e (shift left)] org-shiftmetaleft)
7023 '([?\e (shift right)] org-shiftmetaright)
7024 '([(shift up)] org-shiftup)
7025 '([(shift down)] org-shiftdown)
7026 '([(shift left)] org-shiftleft)
7027 '([(shift right)] org-shiftright)
7028 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7029 '("\M-q" fill-paragraph)
7030 '("\C-c^" org-sort)
7031 '("\C-c-" org-cycle-list-bullet)))
7032 elt key fun cmd)
7033 (while (setq elt (pop bindings))
7034 (setq nfunc (1+ nfunc))
7035 (setq key (org-key (car elt))
7036 fun (nth 1 elt)
7037 cmd (orgstruct-make-binding fun nfunc key))
7038 (org-defkey orgstruct-mode-map key cmd))
7040 ;; Special treatment needed for TAB and RET
7041 (org-defkey orgstruct-mode-map [(tab)]
7042 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7043 (org-defkey orgstruct-mode-map "\C-i"
7044 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7046 (org-defkey orgstruct-mode-map "\M-\C-m"
7047 (orgstruct-make-binding 'org-insert-heading 105
7048 "\M-\C-m" [(meta return)]))
7049 (org-defkey orgstruct-mode-map [(meta return)]
7050 (orgstruct-make-binding 'org-insert-heading 106
7051 [(meta return)] "\M-\C-m"))
7053 (org-defkey orgstruct-mode-map [(shift meta return)]
7054 (orgstruct-make-binding 'org-insert-todo-heading 107
7055 [(meta return)] "\M-\C-m"))
7057 (org-defkey orgstruct-mode-map "\e\C-m"
7058 (orgstruct-make-binding 'org-insert-heading 108
7059 "\e\C-m" [?\e (return)]))
7060 (org-defkey orgstruct-mode-map [?\e (return)]
7061 (orgstruct-make-binding 'org-insert-heading 109
7062 [?\e (return)] "\e\C-m"))
7063 (org-defkey orgstruct-mode-map [?\e (shift return)]
7064 (orgstruct-make-binding 'org-insert-todo-heading 110
7065 [?\e (return)] "\e\C-m"))
7067 (unless org-local-vars
7068 (setq org-local-vars (org-get-local-variables)))
7072 (defun orgstruct-make-binding (fun n &rest keys)
7073 "Create a function for binding in the structure minor mode.
7074 FUN is the command to call inside a table. N is used to create a unique
7075 command name. KEYS are keys that should be checked in for a command
7076 to execute outside of tables."
7077 (eval
7078 (list 'defun
7079 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7080 '(arg)
7081 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7082 "Outside of structure, run the binding of `"
7083 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7084 "'.")
7085 '(interactive "p")
7086 (list 'if
7087 `(org-context-p 'headline 'item
7088 (and orgstruct-is-++
7089 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7090 'item-body))
7091 (list 'org-run-like-in-org-mode (list 'quote fun))
7092 (list 'let '(orgstruct-mode)
7093 (list 'call-interactively
7094 (append '(or)
7095 (mapcar (lambda (k)
7096 (list 'key-binding k))
7097 keys)
7098 '('orgstruct-error))))))))
7100 (defun org-context-p (&rest contexts)
7101 "Check if local context is any of CONTEXTS.
7102 Possible values in the list of contexts are `table', `headline', and `item'."
7103 (let ((pos (point)))
7104 (goto-char (point-at-bol))
7105 (prog1 (or (and (memq 'table contexts)
7106 (looking-at "[ \t]*|"))
7107 (and (memq 'headline contexts)
7108 ;;????????? (looking-at "\\*+"))
7109 (looking-at outline-regexp))
7110 (and (memq 'item contexts)
7111 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7112 (and (memq 'item-body contexts)
7113 (org-in-item-p)))
7114 (goto-char pos))))
7116 (defun org-get-local-variables ()
7117 "Return a list of all local variables in an org-mode buffer."
7118 (let (varlist)
7119 (with-current-buffer (get-buffer-create "*Org tmp*")
7120 (erase-buffer)
7121 (org-mode)
7122 (setq varlist (buffer-local-variables)))
7123 (kill-buffer "*Org tmp*")
7124 (delq nil
7125 (mapcar
7126 (lambda (x)
7127 (setq x
7128 (if (symbolp x)
7129 (list x)
7130 (list (car x) (list 'quote (cdr x)))))
7131 (if (string-match
7132 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7133 (symbol-name (car x)))
7134 x nil))
7135 varlist))))
7137 ;;;###autoload
7138 (defun org-run-like-in-org-mode (cmd)
7139 "Run a command, pretending that the current buffer is in Org-mode.
7140 This will temporarily bind local variables that are typically bound in
7141 Org-mode to the values they have in Org-mode, and then interactively
7142 call CMD."
7143 (org-load-modules-maybe)
7144 (unless org-local-vars
7145 (setq org-local-vars (org-get-local-variables)))
7146 (eval (list 'let org-local-vars
7147 (list 'call-interactively (list 'quote cmd)))))
7149 ;;;; Archiving
7151 (defun org-get-category (&optional pos)
7152 "Get the category applying to position POS."
7153 (get-text-property (or pos (point)) 'org-category))
7155 (defun org-refresh-category-properties ()
7156 "Refresh category text properties in the buffer."
7157 (let ((def-cat (cond
7158 ((null org-category)
7159 (if buffer-file-name
7160 (file-name-sans-extension
7161 (file-name-nondirectory buffer-file-name))
7162 "???"))
7163 ((symbolp org-category) (symbol-name org-category))
7164 (t org-category)))
7165 beg end cat pos optionp)
7166 (org-unmodified
7167 (save-excursion
7168 (save-restriction
7169 (widen)
7170 (goto-char (point-min))
7171 (put-text-property (point) (point-max) 'org-category def-cat)
7172 (while (re-search-forward
7173 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7174 (setq pos (match-end 0)
7175 optionp (equal (char-after (match-beginning 0)) ?#)
7176 cat (org-trim (match-string 2)))
7177 (if optionp
7178 (setq beg (point-at-bol) end (point-max))
7179 (org-back-to-heading t)
7180 (setq beg (point) end (org-end-of-subtree t t)))
7181 (put-text-property beg end 'org-category cat)
7182 (goto-char pos)))))))
7185 ;;;; Link Stuff
7187 ;;; Link abbreviations
7189 (defun org-link-expand-abbrev (link)
7190 "Apply replacements as defined in `org-link-abbrev-alist."
7191 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7192 (let* ((key (match-string 1 link))
7193 (as (or (assoc key org-link-abbrev-alist-local)
7194 (assoc key org-link-abbrev-alist)))
7195 (tag (and (match-end 2) (match-string 3 link)))
7196 rpl)
7197 (if (not as)
7198 link
7199 (setq rpl (cdr as))
7200 (cond
7201 ((symbolp rpl) (funcall rpl tag))
7202 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7203 ((string-match "%h" rpl)
7204 (replace-match (url-hexify-string (or tag "")) t t rpl))
7205 (t (concat rpl tag)))))
7206 link))
7208 ;;; Storing and inserting links
7210 (defvar org-insert-link-history nil
7211 "Minibuffer history for links inserted with `org-insert-link'.")
7213 (defvar org-stored-links nil
7214 "Contains the links stored with `org-store-link'.")
7216 (defvar org-store-link-plist nil
7217 "Plist with info about the most recently link created with `org-store-link'.")
7219 (defvar org-link-protocols nil
7220 "Link protocols added to Org-mode using `org-add-link-type'.")
7222 (defvar org-store-link-functions nil
7223 "List of functions that are called to create and store a link.
7224 Each function will be called in turn until one returns a non-nil
7225 value. Each function should check if it is responsible for creating
7226 this link (for example by looking at the major mode).
7227 If not, it must exit and return nil.
7228 If yes, it should return a non-nil value after a calling
7229 `org-store-link-props' with a list of properties and values.
7230 Special properties are:
7232 :type The link prefix. like \"http\". This must be given.
7233 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7234 This is obligatory as well.
7235 :description Optional default description for the second pair
7236 of brackets in an Org-mode link. The user can still change
7237 this when inserting this link into an Org-mode buffer.
7239 In addition to these, any additional properties can be specified
7240 and then used in remember templates.")
7242 (defun org-add-link-type (type &optional follow export)
7243 "Add TYPE to the list of `org-link-types'.
7244 Re-compute all regular expressions depending on `org-link-types'
7246 FOLLOW and EXPORT are two functions.
7248 FOLLOW should take the link path as the single argument and do whatever
7249 is necessary to follow the link, for example find a file or display
7250 a mail message.
7252 EXPORT should format the link path for export to one of the export formats.
7253 It should be a function accepting three arguments:
7255 path the path of the link, the text after the prefix (like \"http:\")
7256 desc the description of the link, if any, nil if there was no description
7257 format the export format, a symbol like `html' or `latex'.
7259 The function may use the FORMAT information to return different values
7260 depending on the format. The return value will be put literally into
7261 the exported file.
7262 Org-mode has a built-in default for exporting links. If you are happy with
7263 this default, there is no need to define an export function for the link
7264 type. For a simple example of an export function, see `org-bbdb.el'."
7265 (add-to-list 'org-link-types type t)
7266 (org-make-link-regexps)
7267 (if (assoc type org-link-protocols)
7268 (setcdr (assoc type org-link-protocols) (list follow export))
7269 (push (list type follow export) org-link-protocols)))
7271 (defvar org-agenda-buffer-name)
7273 ;;;###autoload
7274 (defun org-store-link (arg)
7275 "\\<org-mode-map>Store an org-link to the current location.
7276 This link is added to `org-stored-links' and can later be inserted
7277 into an org-buffer with \\[org-insert-link].
7279 For some link types, a prefix arg is interpreted:
7280 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7281 For file links, arg negates `org-context-in-file-links'."
7282 (interactive "P")
7283 (org-load-modules-maybe)
7284 (setq org-store-link-plist nil) ; reset
7285 (let ((outline-regexp (org-get-limited-outline-regexp))
7286 link cpltxt desc description search txt custom-id)
7287 (cond
7289 ((run-hook-with-args-until-success 'org-store-link-functions)
7290 (setq link (plist-get org-store-link-plist :link)
7291 desc (or (plist-get org-store-link-plist :description) link)))
7293 ((equal (buffer-name) "*Org Edit Src Example*")
7294 (let (label gc)
7295 (while (or (not label)
7296 (save-excursion
7297 (save-restriction
7298 (widen)
7299 (goto-char (point-min))
7300 (re-search-forward
7301 (regexp-quote (format org-coderef-label-format label))
7302 nil t))))
7303 (when label (message "Label exists already") (sit-for 2))
7304 (setq label (read-string "Code line label: " label)))
7305 (end-of-line 1)
7306 (setq link (format org-coderef-label-format label))
7307 (setq gc (- 79 (length link)))
7308 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7309 (insert link)
7310 (setq link (concat "(" label ")") desc nil)))
7312 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7313 ;; We are in the agenda, link to referenced location
7314 (let ((m (or (get-text-property (point) 'org-hd-marker)
7315 (get-text-property (point) 'org-marker))))
7316 (when m
7317 (org-with-point-at m
7318 (call-interactively 'org-store-link)))))
7320 ((eq major-mode 'calendar-mode)
7321 (let ((cd (calendar-cursor-to-date)))
7322 (setq link
7323 (format-time-string
7324 (car org-time-stamp-formats)
7325 (apply 'encode-time
7326 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7327 nil nil nil))))
7328 (org-store-link-props :type "calendar" :date cd)))
7330 ((eq major-mode 'w3-mode)
7331 (setq cpltxt (if (and (buffer-name)
7332 (not (string-match "Untitled" (buffer-name))))
7333 (buffer-name)
7334 (url-view-url t))
7335 link (org-make-link (url-view-url t)))
7336 (org-store-link-props :type "w3" :url (url-view-url t)))
7338 ((eq major-mode 'w3m-mode)
7339 (setq cpltxt (or w3m-current-title w3m-current-url)
7340 link (org-make-link w3m-current-url))
7341 (org-store-link-props :type "w3m" :url (url-view-url t)))
7343 ((setq search (run-hook-with-args-until-success
7344 'org-create-file-search-functions))
7345 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7346 "::" search))
7347 (setq cpltxt (or description link)))
7349 ((eq major-mode 'image-mode)
7350 (setq cpltxt (concat "file:"
7351 (abbreviate-file-name buffer-file-name))
7352 link (org-make-link cpltxt))
7353 (org-store-link-props :type "image" :file buffer-file-name))
7355 ((eq major-mode 'dired-mode)
7356 ;; link to the file in the current line
7357 (setq cpltxt (concat "file:"
7358 (abbreviate-file-name
7359 (expand-file-name
7360 (dired-get-filename nil t))))
7361 link (org-make-link cpltxt)))
7363 ((and buffer-file-name (org-mode-p))
7364 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7365 (cond
7366 ((org-in-regexp "<<\\(.*?\\)>>")
7367 (setq cpltxt
7368 (concat "file:"
7369 (abbreviate-file-name buffer-file-name)
7370 "::" (match-string 1))
7371 link (org-make-link cpltxt)))
7372 ((and (featurep 'org-id)
7373 (or (eq org-link-to-org-use-id t)
7374 (and (eq org-link-to-org-use-id 'create-if-interactive)
7375 (interactive-p))
7376 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7377 (interactive-p)
7378 (not custom-id))
7379 (and org-link-to-org-use-id
7380 (condition-case nil
7381 (org-entry-get nil "ID")
7382 (error nil)))))
7383 ;; We can make a link using the ID.
7384 (setq link (condition-case nil
7385 (prog1 (org-id-store-link)
7386 (setq desc (plist-get org-store-link-plist
7387 :description)))
7388 (error
7389 ;; probably before first headline, link to file only
7390 (concat "file:"
7391 (abbreviate-file-name buffer-file-name))))))
7393 ;; Just link to current headline
7394 (setq cpltxt (concat "file:"
7395 (abbreviate-file-name buffer-file-name)))
7396 ;; Add a context search string
7397 (when (org-xor org-context-in-file-links arg)
7398 (setq txt (cond
7399 ((org-on-heading-p) nil)
7400 ((org-region-active-p)
7401 (buffer-substring (region-beginning) (region-end)))
7402 (t nil)))
7403 (when (or (null txt) (string-match "\\S-" txt))
7404 (setq cpltxt
7405 (concat cpltxt "::"
7406 (condition-case nil
7407 (org-make-org-heading-search-string txt)
7408 (error "")))
7409 desc (or (nth 4 (ignore-errors
7410 (org-heading-components))) "NONE"))))
7411 (if (string-match "::\\'" cpltxt)
7412 (setq cpltxt (substring cpltxt 0 -2)))
7413 (setq link (org-make-link cpltxt)))))
7415 ((buffer-file-name (buffer-base-buffer))
7416 ;; Just link to this file here.
7417 (setq cpltxt (concat "file:"
7418 (abbreviate-file-name
7419 (buffer-file-name (buffer-base-buffer)))))
7420 ;; Add a context string
7421 (when (org-xor org-context-in-file-links arg)
7422 (setq txt (if (org-region-active-p)
7423 (buffer-substring (region-beginning) (region-end))
7424 (buffer-substring (point-at-bol) (point-at-eol))))
7425 ;; Only use search option if there is some text.
7426 (when (string-match "\\S-" txt)
7427 (setq cpltxt
7428 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7429 desc "NONE")))
7430 (setq link (org-make-link cpltxt)))
7432 ((interactive-p)
7433 (error "Cannot link to a buffer which is not visiting a file"))
7435 (t (setq link nil)))
7437 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7438 (setq link (or link cpltxt)
7439 desc (or desc cpltxt))
7440 (if (equal desc "NONE") (setq desc nil))
7442 (if (and (or (interactive-p) executing-kbd-macro) link)
7443 (progn
7444 (setq org-stored-links
7445 (cons (list link desc) org-stored-links))
7446 (message "Stored: %s" (or desc link))
7447 (when custom-id
7448 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7449 "::#" custom-id))
7450 (setq org-stored-links
7451 (cons (list link desc) org-stored-links))))
7452 (and link (org-make-link-string link desc)))))
7454 (defun org-store-link-props (&rest plist)
7455 "Store link properties, extract names and addresses."
7456 (let (x adr)
7457 (when (setq x (plist-get plist :from))
7458 (setq adr (mail-extract-address-components x))
7459 (setq plist (plist-put plist :fromname (car adr)))
7460 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7461 (when (setq x (plist-get plist :to))
7462 (setq adr (mail-extract-address-components x))
7463 (setq plist (plist-put plist :toname (car adr)))
7464 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7465 (let ((from (plist-get plist :from))
7466 (to (plist-get plist :to)))
7467 (when (and from to org-from-is-user-regexp)
7468 (setq plist
7469 (plist-put plist :fromto
7470 (if (string-match org-from-is-user-regexp from)
7471 (concat "to %t")
7472 (concat "from %f"))))))
7473 (setq org-store-link-plist plist))
7475 (defun org-add-link-props (&rest plist)
7476 "Add these properties to the link property list."
7477 (let (key value)
7478 (while plist
7479 (setq key (pop plist) value (pop plist))
7480 (setq org-store-link-plist
7481 (plist-put org-store-link-plist key value)))))
7483 (defun org-email-link-description (&optional fmt)
7484 "Return the description part of an email link.
7485 This takes information from `org-store-link-plist' and formats it
7486 according to FMT (default from `org-email-link-description-format')."
7487 (setq fmt (or fmt org-email-link-description-format))
7488 (let* ((p org-store-link-plist)
7489 (to (plist-get p :toaddress))
7490 (from (plist-get p :fromaddress))
7491 (table
7492 (list
7493 (cons "%c" (plist-get p :fromto))
7494 (cons "%F" (plist-get p :from))
7495 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7496 (cons "%T" (plist-get p :to))
7497 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7498 (cons "%s" (plist-get p :subject))
7499 (cons "%m" (plist-get p :message-id)))))
7500 (when (string-match "%c" fmt)
7501 ;; Check if the user wrote this message
7502 (if (and org-from-is-user-regexp from to
7503 (save-match-data (string-match org-from-is-user-regexp from)))
7504 (setq fmt (replace-match "to %t" t t fmt))
7505 (setq fmt (replace-match "from %f" t t fmt))))
7506 (org-replace-escapes fmt table)))
7508 (defun org-make-org-heading-search-string (&optional string heading)
7509 "Make search string for STRING or current headline."
7510 (interactive)
7511 (let ((s (or string (org-get-heading))))
7512 (unless (and string (not heading))
7513 ;; We are using a headline, clean up garbage in there.
7514 (if (string-match org-todo-regexp s)
7515 (setq s (replace-match "" t t s)))
7516 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7517 (setq s (replace-match "" t t s)))
7518 (setq s (org-trim s))
7519 (if (string-match (concat "^\\(" org-quote-string "\\|"
7520 org-comment-string "\\)") s)
7521 (setq s (replace-match "" t t s)))
7522 (while (string-match org-ts-regexp s)
7523 (setq s (replace-match "" t t s))))
7524 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7525 (setq s (replace-match " " t t s)))
7526 (or string (setq s (concat "*" s))) ; Add * for headlines
7527 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7529 (defun org-make-link (&rest strings)
7530 "Concatenate STRINGS."
7531 (apply 'concat strings))
7533 (defun org-make-link-string (link &optional description)
7534 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7535 (unless (string-match "\\S-" link)
7536 (error "Empty link"))
7537 (when (stringp description)
7538 ;; Remove brackets from the description, they are fatal.
7539 (while (string-match "\\[" description)
7540 (setq description (replace-match "{" t t description)))
7541 (while (string-match "\\]" description)
7542 (setq description (replace-match "}" t t description))))
7543 (when (equal (org-link-escape link) description)
7544 ;; No description needed, it is identical
7545 (setq description nil))
7546 (when (and (not description)
7547 (not (equal link (org-link-escape link))))
7548 (setq description (org-extract-attributes link)))
7549 (concat "[[" (org-link-escape link) "]"
7550 (if description (concat "[" description "]") "")
7551 "]"))
7553 (defconst org-link-escape-chars
7554 '((?\ . "%20")
7555 (?\[ . "%5B")
7556 (?\] . "%5D")
7557 (?\340 . "%E0") ; `a
7558 (?\342 . "%E2") ; ^a
7559 (?\347 . "%E7") ; ,c
7560 (?\350 . "%E8") ; `e
7561 (?\351 . "%E9") ; 'e
7562 (?\352 . "%EA") ; ^e
7563 (?\356 . "%EE") ; ^i
7564 (?\364 . "%F4") ; ^o
7565 (?\371 . "%F9") ; `u
7566 (?\373 . "%FB") ; ^u
7567 (?\; . "%3B")
7568 (?? . "%3F")
7569 (?= . "%3D")
7570 (?+ . "%2B")
7572 "Association list of escapes for some characters problematic in links.
7573 This is the list that is used for internal purposes.")
7575 (defvar org-url-encoding-use-url-hexify nil)
7577 (defconst org-link-escape-chars-browser
7578 '((?\ . "%20")) ; 32 for the SPC char
7579 "Association list of escapes for some characters problematic in links.
7580 This is the list that is used before handing over to the browser.")
7582 (defun org-link-escape (text &optional table)
7583 "Escape characters in TEXT that are problematic for links."
7584 (if org-url-encoding-use-url-hexify
7585 (url-hexify-string text)
7586 (setq table (or table org-link-escape-chars))
7587 (when text
7588 (let ((re (mapconcat (lambda (x) (regexp-quote
7589 (char-to-string (car x))))
7590 table "\\|")))
7591 (while (string-match re text)
7592 (setq text
7593 (replace-match
7594 (cdr (assoc (string-to-char (match-string 0 text))
7595 table))
7596 t t text)))
7597 text))))
7599 (defun org-link-unescape (text &optional table)
7600 "Reverse the action of `org-link-escape'."
7601 (if org-url-encoding-use-url-hexify
7602 (url-unhex-string text)
7603 (setq table (or table org-link-escape-chars))
7604 (when text
7605 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7606 table "\\|")))
7607 (while (string-match re text)
7608 (setq text
7609 (replace-match
7610 (char-to-string (car (rassoc (match-string 0 text) table)))
7611 t t text)))
7612 text))))
7614 (defun org-xor (a b)
7615 "Exclusive or."
7616 (if a (not b) b))
7618 (defun org-fixup-message-id-for-http (s)
7619 "Replace special characters in a message id, so it can be used in an http query."
7620 (while (string-match "<" s)
7621 (setq s (replace-match "%3C" t t s)))
7622 (while (string-match ">" s)
7623 (setq s (replace-match "%3E" t t s)))
7624 (while (string-match "@" s)
7625 (setq s (replace-match "%40" t t s)))
7628 ;;;###autoload
7629 (defun org-insert-link-global ()
7630 "Insert a link like Org-mode does.
7631 This command can be called in any mode to insert a link in Org-mode syntax."
7632 (interactive)
7633 (org-load-modules-maybe)
7634 (org-run-like-in-org-mode 'org-insert-link))
7636 (defun org-insert-link (&optional complete-file link-location)
7637 "Insert a link. At the prompt, enter the link.
7639 Completion can be used to insert any of the link protocol prefixes like
7640 http or ftp in use.
7642 The history can be used to select a link previously stored with
7643 `org-store-link'. When the empty string is entered (i.e. if you just
7644 press RET at the prompt), the link defaults to the most recently
7645 stored link. As SPC triggers completion in the minibuffer, you need to
7646 use M-SPC or C-q SPC to force the insertion of a space character.
7648 You will also be prompted for a description, and if one is given, it will
7649 be displayed in the buffer instead of the link.
7651 If there is already a link at point, this command will allow you to edit link
7652 and description parts.
7654 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7655 be selected using completion. The path to the file will be relative to the
7656 current directory if the file is in the current directory or a subdirectory.
7657 Otherwise, the link will be the absolute path as completed in the minibuffer
7658 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7659 option `org-link-file-path-type'.
7661 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7662 the current directory or below.
7664 With three \\[universal-argument] prefixes, negate the meaning of
7665 `org-keep-stored-link-after-insertion'.
7667 If `org-make-link-description-function' is non-nil, this function will be
7668 called with the link target, and the result will be the default
7669 link description.
7671 If the LINK-LOCATION parameter is non-nil, this value will be
7672 used as the link location instead of reading one interactively."
7673 (interactive "P")
7674 (let* ((wcf (current-window-configuration))
7675 (region (if (org-region-active-p)
7676 (buffer-substring (region-beginning) (region-end))))
7677 (remove (and region (list (region-beginning) (region-end))))
7678 (desc region)
7679 tmphist ; byte-compile incorrectly complains about this
7680 (link link-location)
7681 entry file all-prefixes)
7682 (cond
7683 (link-location) ; specified by arg, just use it.
7684 ((org-in-regexp org-bracket-link-regexp 1)
7685 ;; We do have a link at point, and we are going to edit it.
7686 (setq remove (list (match-beginning 0) (match-end 0)))
7687 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7688 (setq link (read-string "Link: "
7689 (org-link-unescape
7690 (org-match-string-no-properties 1)))))
7691 ((or (org-in-regexp org-angle-link-re)
7692 (org-in-regexp org-plain-link-re))
7693 ;; Convert to bracket link
7694 (setq remove (list (match-beginning 0) (match-end 0))
7695 link (read-string "Link: "
7696 (org-remove-angle-brackets (match-string 0)))))
7697 ((member complete-file '((4) (16)))
7698 ;; Completing read for file names.
7699 (setq link (org-file-complete-link complete-file)))
7701 ;; Read link, with completion for stored links.
7702 (with-output-to-temp-buffer "*Org Links*"
7703 (princ "Insert a link.
7704 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7705 (when org-stored-links
7706 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7707 (princ (mapconcat
7708 (lambda (x)
7709 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7710 (reverse org-stored-links) "\n"))))
7711 (let ((cw (selected-window)))
7712 (select-window (get-buffer-window "*Org Links*"))
7713 (setq truncate-lines t)
7714 (unless (pos-visible-in-window-p (point-max))
7715 (org-fit-window-to-buffer))
7716 (and (window-live-p cw) (select-window cw)))
7717 ;; Fake a link history, containing the stored links.
7718 (setq tmphist (append (mapcar 'car org-stored-links)
7719 org-insert-link-history))
7720 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7721 (mapcar 'car org-link-abbrev-alist)
7722 org-link-types))
7723 (unwind-protect
7724 (progn
7725 (setq link
7726 (let ((org-completion-use-ido nil)
7727 (org-completion-use-iswitchb nil))
7728 (org-completing-read
7729 "Link: "
7730 (append
7731 (mapcar (lambda (x) (list (concat x ":")))
7732 all-prefixes)
7733 (mapcar 'car org-stored-links))
7734 nil nil nil
7735 'tmphist
7736 (car (car org-stored-links)))))
7737 (if (or (member link all-prefixes)
7738 (and (equal ":" (substring link -1))
7739 (member (substring link 0 -1) all-prefixes)
7740 (setq link (substring link 0 -1))))
7741 (setq link (org-link-try-special-completion link))))
7742 (set-window-configuration wcf)
7743 (kill-buffer "*Org Links*"))
7744 (setq entry (assoc link org-stored-links))
7745 (or entry (push link org-insert-link-history))
7746 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7747 (not org-keep-stored-link-after-insertion))
7748 (setq org-stored-links (delq (assoc link org-stored-links)
7749 org-stored-links)))
7750 (setq desc (or desc (nth 1 entry)))))
7752 (if (string-match org-plain-link-re link)
7753 ;; URL-like link, normalize the use of angular brackets.
7754 (setq link (org-make-link (org-remove-angle-brackets link))))
7756 ;; Check if we are linking to the current file with a search option
7757 ;; If yes, simplify the link by using only the search option.
7758 (when (and buffer-file-name
7759 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7760 (let* ((path (match-string 1 link))
7761 (case-fold-search nil)
7762 (search (match-string 2 link)))
7763 (save-match-data
7764 (if (equal (file-truename buffer-file-name) (file-truename path))
7765 ;; We are linking to this same file, with a search option
7766 (setq link search)))))
7768 ;; Check if we can/should use a relative path. If yes, simplify the link
7769 (when (string-match "^file:\\(.*\\)" link)
7770 (let* ((path (match-string 1 link))
7771 (origpath path)
7772 (case-fold-search nil))
7773 (cond
7774 ((or (eq org-link-file-path-type 'absolute)
7775 (equal complete-file '(16)))
7776 (setq path (abbreviate-file-name (expand-file-name path))))
7777 ((eq org-link-file-path-type 'noabbrev)
7778 (setq path (expand-file-name path)))
7779 ((eq org-link-file-path-type 'relative)
7780 (setq path (file-relative-name path)))
7782 (save-match-data
7783 (if (string-match (concat "^" (regexp-quote
7784 (file-name-as-directory
7785 (expand-file-name "."))))
7786 (expand-file-name path))
7787 ;; We are linking a file with relative path name.
7788 (setq path (substring (expand-file-name path)
7789 (match-end 0)))
7790 (setq path (abbreviate-file-name (expand-file-name path)))))))
7791 (setq link (concat "file:" path))
7792 (if (equal desc origpath)
7793 (setq desc path))))
7795 (if org-make-link-description-function
7796 (setq desc (funcall org-make-link-description-function link desc)))
7798 (setq desc (read-string "Description: " desc))
7799 (unless (string-match "\\S-" desc) (setq desc nil))
7800 (if remove (apply 'delete-region remove))
7801 (insert (org-make-link-string link desc))))
7803 (defun org-link-try-special-completion (type)
7804 "If there is completion support for link type TYPE, offer it."
7805 (let ((fun (intern (concat "org-" type "-complete-link"))))
7806 (if (functionp fun)
7807 (funcall fun)
7808 (read-string "Link (no completion support): " (concat type ":")))))
7810 (defun org-file-complete-link (&optional arg)
7811 "Create a file link using completion."
7812 (let (file link)
7813 (setq file (read-file-name "File: "))
7814 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7815 (pwd1 (file-name-as-directory (abbreviate-file-name
7816 (expand-file-name ".")))))
7817 (cond
7818 ((equal arg '(16))
7819 (setq link (org-make-link
7820 "file:"
7821 (abbreviate-file-name (expand-file-name file)))))
7822 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7823 (setq link (org-make-link "file:" (match-string 1 file))))
7824 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7825 (expand-file-name file))
7826 (setq link (org-make-link
7827 "file:" (match-string 1 (expand-file-name file)))))
7828 (t (setq link (org-make-link "file:" file)))))
7829 link))
7831 (defun org-completing-read (&rest args)
7832 "Completing-read with SPACE being a normal character."
7833 (let ((minibuffer-local-completion-map
7834 (copy-keymap minibuffer-local-completion-map)))
7835 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7836 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7837 (apply 'org-icompleting-read args)))
7839 (defun org-completing-read-no-i (&rest args)
7840 (let (org-completion-use-ido org-completion-use-iswitchb)
7841 (apply 'org-completing-read args)))
7843 (defun org-iswitchb-completing-read (prompt choices &rest args)
7844 "Use iswitch as a completing-read replacement to choose from choices.
7845 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
7846 from."
7847 (let* ((iswitchb-use-virtual-buffers nil)
7848 (iswitchb-make-buflist-hook
7849 (lambda ()
7850 (setq iswitchb-temp-buflist choices))))
7851 (iswitchb-read-buffer prompt)))
7853 (defun org-icompleting-read (&rest args)
7854 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
7855 (org-without-partial-completion
7856 (if (and org-completion-use-ido
7857 (fboundp 'ido-completing-read)
7858 (boundp 'ido-mode) ido-mode
7859 (listp (second args)))
7860 (let ((ido-enter-matching-directory nil))
7861 (apply 'ido-completing-read (concat (car args))
7862 (if (consp (car (nth 1 args)))
7863 (mapcar (lambda (x) (car x)) (nth 1 args))
7864 (nth 1 args))
7865 (cddr args)))
7866 (if (and org-completion-use-iswitchb
7867 (boundp 'iswitchb-mode) iswitchb-mode
7868 (listp (second args)))
7869 (apply 'org-iswitchb-completing-read (concat (car args))
7870 (if (consp (car (nth 1 args)))
7871 (mapcar (lambda (x) (car x)) (nth 1 args))
7872 (nth 1 args))
7873 (cddr args))
7874 (apply 'completing-read args)))))
7876 (defun org-extract-attributes (s)
7877 "Extract the attributes cookie from a string and set as text property."
7878 (let (a attr (start 0) key value)
7879 (save-match-data
7880 (when (string-match "{{\\([^}]+\\)}}$" s)
7881 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7882 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7883 (setq key (match-string 1 a) value (match-string 2 a)
7884 start (match-end 0)
7885 attr (plist-put attr (intern key) value))))
7886 (org-add-props s nil 'org-attr attr))
7889 (defun org-extract-attributes-from-string (tag)
7890 (let (key value attr)
7891 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7892 (setq key (match-string 1 tag) value (match-string 2 tag)
7893 tag (replace-match "" t t tag)
7894 attr (plist-put attr (intern key) value)))
7895 (cons tag attr)))
7897 (defun org-attributes-to-string (plist)
7898 "Format a property list into an HTML attribute list."
7899 (let ((s "") key value)
7900 (while plist
7901 (setq key (pop plist) value (pop plist))
7902 (and value
7903 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7906 ;;; Opening/following a link
7908 (defvar org-link-search-failed nil)
7910 (defun org-next-link ()
7911 "Move forward to the next link.
7912 If the link is in hidden text, expose it."
7913 (interactive)
7914 (when (and org-link-search-failed (eq this-command last-command))
7915 (goto-char (point-min))
7916 (message "Link search wrapped back to beginning of buffer"))
7917 (setq org-link-search-failed nil)
7918 (let* ((pos (point))
7919 (ct (org-context))
7920 (a (assoc :link ct)))
7921 (if a (goto-char (nth 2 a)))
7922 (if (re-search-forward org-any-link-re nil t)
7923 (progn
7924 (goto-char (match-beginning 0))
7925 (if (org-invisible-p) (org-show-context)))
7926 (goto-char pos)
7927 (setq org-link-search-failed t)
7928 (error "No further link found"))))
7930 (defun org-previous-link ()
7931 "Move backward to the previous link.
7932 If the link is in hidden text, expose it."
7933 (interactive)
7934 (when (and org-link-search-failed (eq this-command last-command))
7935 (goto-char (point-max))
7936 (message "Link search wrapped back to end of buffer"))
7937 (setq org-link-search-failed nil)
7938 (let* ((pos (point))
7939 (ct (org-context))
7940 (a (assoc :link ct)))
7941 (if a (goto-char (nth 1 a)))
7942 (if (re-search-backward org-any-link-re nil t)
7943 (progn
7944 (goto-char (match-beginning 0))
7945 (if (org-invisible-p) (org-show-context)))
7946 (goto-char pos)
7947 (setq org-link-search-failed t)
7948 (error "No further link found"))))
7950 (defun org-translate-link (s)
7951 "Translate a link string if a translation function has been defined."
7952 (if (and org-link-translation-function
7953 (fboundp org-link-translation-function)
7954 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7955 (progn
7956 (setq s (funcall org-link-translation-function
7957 (match-string 1) (match-string 2)))
7958 (concat (car s) ":" (cdr s)))
7961 (defun org-translate-link-from-planner (type path)
7962 "Translate a link from Emacs Planner syntax so that Org can follow it.
7963 This is still an experimental function, your mileage may vary."
7964 (cond
7965 ((member type '("http" "https" "news" "ftp"))
7966 ;; standard Internet links are the same.
7967 nil)
7968 ((and (equal type "irc") (string-match "^//" path))
7969 ;; Planner has two / at the beginning of an irc link, we have 1.
7970 ;; We should have zero, actually....
7971 (setq path (substring path 1)))
7972 ((and (equal type "lisp") (string-match "^/" path))
7973 ;; Planner has a slash, we do not.
7974 (setq type "elisp" path (substring path 1)))
7975 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7976 ;; A typical message link. Planner has the id after the fina slash,
7977 ;; we separate it with a hash mark
7978 (setq path (concat (match-string 1 path) "#"
7979 (org-remove-angle-brackets (match-string 2 path)))))
7981 (cons type path))
7983 (defun org-find-file-at-mouse (ev)
7984 "Open file link or URL at mouse."
7985 (interactive "e")
7986 (mouse-set-point ev)
7987 (org-open-at-point 'in-emacs))
7989 (defun org-open-at-mouse (ev)
7990 "Open file link or URL at mouse."
7991 (interactive "e")
7992 (mouse-set-point ev)
7993 (if (eq major-mode 'org-agenda-mode)
7994 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7995 (org-open-at-point))
7997 (defvar org-window-config-before-follow-link nil
7998 "The window configuration before following a link.
7999 This is saved in case the need arises to restore it.")
8001 (defvar org-open-link-marker (make-marker)
8002 "Marker pointing to the location where `org-open-at-point; was called.")
8004 ;;;###autoload
8005 (defun org-open-at-point-global ()
8006 "Follow a link like Org-mode does.
8007 This command can be called in any mode to follow a link that has
8008 Org-mode syntax."
8009 (interactive)
8010 (org-run-like-in-org-mode 'org-open-at-point))
8012 ;;;###autoload
8013 (defun org-open-link-from-string (s &optional arg reference-buffer)
8014 "Open a link in the string S, as if it was in Org-mode."
8015 (interactive "sLink: \nP")
8016 (let ((reference-buffer (or reference-buffer (current-buffer))))
8017 (with-temp-buffer
8018 (let ((org-inhibit-startup t))
8019 (org-mode)
8020 (insert s)
8021 (goto-char (point-min))
8022 (org-open-at-point arg reference-buffer)))))
8024 (defun org-open-at-point (&optional in-emacs reference-buffer)
8025 "Open link at or after point.
8026 If there is no link at point, this function will search forward up to
8027 the end of the current line.
8028 Normally, files will be opened by an appropriate application. If the
8029 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8030 With a double prefix argument, try to open outside of Emacs, in the
8031 application the system uses for this file type."
8032 (interactive "P")
8033 (org-load-modules-maybe)
8034 (move-marker org-open-link-marker (point))
8035 (setq org-window-config-before-follow-link (current-window-configuration))
8036 (org-remove-occur-highlights nil nil t)
8037 (cond
8038 ((and (org-on-heading-p)
8039 (not (org-in-regexp
8040 (concat org-plain-link-re "\\|"
8041 org-bracket-link-regexp "\\|"
8042 org-angle-link-re "\\|"
8043 "[ \t]:[^ \t\n]+:[ \t]*$"))))
8044 (or (org-offer-links-in-entry in-emacs)
8045 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8046 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8047 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8048 (org-footnote-action))
8050 (let (type path link line search (pos (point)))
8051 (catch 'match
8052 (save-excursion
8053 (skip-chars-forward "^]\n\r")
8054 (when (org-in-regexp org-bracket-link-regexp)
8055 (setq link (org-extract-attributes
8056 (org-link-unescape (org-match-string-no-properties 1))))
8057 (while (string-match " *\n *" link)
8058 (setq link (replace-match " " t t link)))
8059 (setq link (org-link-expand-abbrev link))
8060 (cond
8061 ((or (file-name-absolute-p link)
8062 (string-match "^\\.\\.?/" link))
8063 (setq type "file" path link))
8064 ((string-match org-link-re-with-space3 link)
8065 (setq type (match-string 1 link) path (match-string 2 link)))
8066 (t (setq type "thisfile" path link)))
8067 (throw 'match t)))
8069 (when (get-text-property (point) 'org-linked-text)
8070 (setq type "thisfile"
8071 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8072 (1+ (point)) (point))
8073 path (buffer-substring
8074 (previous-single-property-change pos 'org-linked-text)
8075 (next-single-property-change pos 'org-linked-text)))
8076 (throw 'match t))
8078 (save-excursion
8079 (when (or (org-in-regexp org-angle-link-re)
8080 (org-in-regexp org-plain-link-re))
8081 (setq type (match-string 1) path (match-string 2))
8082 (throw 'match t)))
8083 (save-excursion
8084 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8085 (setq type "tags"
8086 path (match-string 1))
8087 (while (string-match ":" path)
8088 (setq path (replace-match "+" t t path)))
8089 (throw 'match t)))
8090 (when (org-in-regexp "<\\([^><\n]+\\)>")
8091 (setq type "tree-match"
8092 path (match-string 1))
8093 (throw 'match t)))
8094 (unless path
8095 (error "No link found"))
8097 ;; switch back to reference buffer
8098 ;; needed when if called in a temporary buffer through
8099 ;; org-open-link-from-string
8100 (with-current-buffer (or reference-buffer (current-buffer))
8102 ;; Remove any trailing spaces in path
8103 (if (string-match " +\\'" path)
8104 (setq path (replace-match "" t t path)))
8105 (if (and org-link-translation-function
8106 (fboundp org-link-translation-function))
8107 ;; Check if we need to translate the link
8108 (let ((tmp (funcall org-link-translation-function type path)))
8109 (setq type (car tmp) path (cdr tmp))))
8111 (cond
8113 ((assoc type org-link-protocols)
8114 (funcall (nth 1 (assoc type org-link-protocols)) path))
8116 ((equal type "mailto")
8117 (let ((cmd (car org-link-mailto-program))
8118 (args (cdr org-link-mailto-program)) args1
8119 (address path) (subject "") a)
8120 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8121 (setq address (match-string 1 path)
8122 subject (org-link-escape (match-string 2 path))))
8123 (while args
8124 (cond
8125 ((not (stringp (car args))) (push (pop args) args1))
8126 (t (setq a (pop args))
8127 (if (string-match "%a" a)
8128 (setq a (replace-match address t t a)))
8129 (if (string-match "%s" a)
8130 (setq a (replace-match subject t t a)))
8131 (push a args1))))
8132 (apply cmd (nreverse args1))))
8134 ((member type '("http" "https" "ftp" "news"))
8135 (browse-url (concat type ":" (org-link-escape
8136 path org-link-escape-chars-browser))))
8138 ((member type '("message"))
8139 (browse-url (concat type ":" path)))
8141 ((string= type "tags")
8142 (org-tags-view in-emacs path))
8143 ((string= type "thisfile")
8144 (if in-emacs
8145 (switch-to-buffer-other-window
8146 (org-get-buffer-for-internal-link (current-buffer)))
8147 (org-mark-ring-push))
8148 (let ((cmd `(org-link-search
8149 ,path
8150 ,(cond ((equal in-emacs '(4)) 'occur)
8151 ((equal in-emacs '(16)) 'org-occur)
8152 (t nil))
8153 ,pos)))
8154 (condition-case nil (eval cmd)
8155 (error (progn (widen) (eval cmd))))))
8157 ((string= type "tree-match")
8158 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8160 ((string= type "file")
8161 (if (string-match "::\\([0-9]+\\)\\'" path)
8162 (setq line (string-to-number (match-string 1 path))
8163 path (substring path 0 (match-beginning 0)))
8164 (if (string-match "::\\(.+\\)\\'" path)
8165 (setq search (match-string 1 path)
8166 path (substring path 0 (match-beginning 0)))))
8167 (if (string-match "[*?{]" (file-name-nondirectory path))
8168 (dired path)
8169 (org-open-file path in-emacs line search)))
8171 ((string= type "news")
8172 (require 'org-gnus)
8173 (org-gnus-follow-link path))
8175 ((string= type "shell")
8176 (let ((cmd path))
8177 (if (or (not org-confirm-shell-link-function)
8178 (funcall org-confirm-shell-link-function
8179 (format "Execute \"%s\" in shell? "
8180 (org-add-props cmd nil
8181 'face 'org-warning))))
8182 (progn
8183 (message "Executing %s" cmd)
8184 (shell-command cmd))
8185 (error "Abort"))))
8187 ((string= type "elisp")
8188 (let ((cmd path))
8189 (if (or (not org-confirm-elisp-link-function)
8190 (funcall org-confirm-elisp-link-function
8191 (format "Execute \"%s\" as elisp? "
8192 (org-add-props cmd nil
8193 'face 'org-warning))))
8194 (message "%s => %s" cmd
8195 (if (equal (string-to-char cmd) ?\()
8196 (eval (read cmd))
8197 (call-interactively (read cmd))))
8198 (error "Abort"))))
8201 (browse-url-at-point)))))))
8202 (move-marker org-open-link-marker nil)
8203 (run-hook-with-args 'org-follow-link-hook))
8205 (defun org-offer-links-in-entry (&optional nth zero)
8206 "Offer links in the curren entry and follow the selected link.
8207 If there is only one link, follow it immediately as well.
8208 If NTH is an integer, immediately pick the NTH link found.
8209 If ZERO is a string, check also this string for a link, and if
8210 there is one, offer it as link number zero."
8211 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8212 "\\(" org-angle-link-re "\\)\\|"
8213 "\\(" org-plain-link-re "\\)"))
8214 (cnt ?0)
8215 (in-emacs (if (integerp nth) nil nth))
8216 have-zero end links link c)
8217 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8218 (push (match-string 0 zero) links)
8219 (setq cnt (1- cnt) have-zero t))
8220 (save-excursion
8221 (org-back-to-heading t)
8222 (setq end (save-excursion (outline-next-heading) (point)))
8223 (while (re-search-forward re end t)
8224 (push (match-string 0) links))
8225 (setq links (org-uniquify (reverse links))))
8227 (cond
8228 ((null links)
8229 (message "No links"))
8230 ((equal (length links) 1)
8231 (setq link (car links)))
8232 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8233 (setq link (nth (if have-zero nth (1- nth)) links)))
8234 (t ; we have to select a link
8235 (save-excursion
8236 (save-window-excursion
8237 (delete-other-windows)
8238 (with-output-to-temp-buffer "*Select Link*"
8239 (mapc (lambda (l)
8240 (if (not (string-match org-bracket-link-regexp l))
8241 (princ (format "[%c] %s\n" (incf cnt)
8242 (org-remove-angle-brackets l)))
8243 (if (match-end 3)
8244 (princ (format "[%c] %s (%s)\n" (incf cnt)
8245 (match-string 3 l) (match-string 1 l)))
8246 (princ (format "[%c] %s\n" (incf cnt)
8247 (match-string 1 l))))))
8248 links))
8249 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8250 (message "Select link to open:")
8251 (setq c (read-char-exclusive))
8252 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8253 (when (equal c ?q) (error "Abort"))
8254 (setq nth (- c ?0))
8255 (if have-zero (setq nth (1+ nth)))
8256 (unless (and (integerp nth) (>= (length links) nth))
8257 (error "Invalid link selection"))
8258 (setq link (nth (1- nth) links))))
8259 (if link
8260 (progn (org-open-link-from-string link in-emacs (current-buffer)) t)
8261 nil)))
8263 ;;;; Time estimates
8265 (defun org-get-effort (&optional pom)
8266 "Get the effort estimate for the current entry."
8267 (org-entry-get pom org-effort-property))
8269 ;;; File search
8271 (defvar org-create-file-search-functions nil
8272 "List of functions to construct the right search string for a file link.
8273 These functions are called in turn with point at the location to
8274 which the link should point.
8276 A function in the hook should first test if it would like to
8277 handle this file type, for example by checking the major-mode or
8278 the file extension. If it decides not to handle this file, it
8279 should just return nil to give other functions a chance. If it
8280 does handle the file, it must return the search string to be used
8281 when following the link. The search string will be part of the
8282 file link, given after a double colon, and `org-open-at-point'
8283 will automatically search for it. If special measures must be
8284 taken to make the search successful, another function should be
8285 added to the companion hook `org-execute-file-search-functions',
8286 which see.
8288 A function in this hook may also use `setq' to set the variable
8289 `description' to provide a suggestion for the descriptive text to
8290 be used for this link when it gets inserted into an Org-mode
8291 buffer with \\[org-insert-link].")
8293 (defvar org-execute-file-search-functions nil
8294 "List of functions to execute a file search triggered by a link.
8296 Functions added to this hook must accept a single argument, the
8297 search string that was part of the file link, the part after the
8298 double colon. The function must first check if it would like to
8299 handle this search, for example by checking the major-mode or the
8300 file extension. If it decides not to handle this search, it
8301 should just return nil to give other functions a chance. If it
8302 does handle the search, it must return a non-nil value to keep
8303 other functions from trying.
8305 Each function can access the current prefix argument through the
8306 variable `current-prefix-argument'. Note that a single prefix is
8307 used to force opening a link in Emacs, so it may be good to only
8308 use a numeric or double prefix to guide the search function.
8310 In case this is needed, a function in this hook can also restore
8311 the window configuration before `org-open-at-point' was called using:
8313 (set-window-configuration org-window-config-before-follow-link)")
8315 (defun org-link-search (s &optional type avoid-pos)
8316 "Search for a link search option.
8317 If S is surrounded by forward slashes, it is interpreted as a
8318 regular expression. In org-mode files, this will create an `org-occur'
8319 sparse tree. In ordinary files, `occur' will be used to list matches.
8320 If the current buffer is in `dired-mode', grep will be used to search
8321 in all files. If AVOID-POS is given, ignore matches near that position."
8322 (let ((case-fold-search t)
8323 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8324 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8325 (append '(("") (" ") ("\t") ("\n"))
8326 org-emphasis-alist)
8327 "\\|") "\\)"))
8328 (pos (point))
8329 (pre nil) (post nil)
8330 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8331 (cond
8332 ;; First check if there are any special
8333 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8334 ;; Now try the builtin stuff
8335 ((and (equal (string-to-char s0) ?#)
8336 (> (length s0) 1)
8337 (save-excursion
8338 (goto-char (point-min))
8339 (and
8340 (re-search-forward
8341 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8342 (setq type 'dedicated
8343 pos (match-beginning 0))))
8344 ;; There is an exact target for this
8345 (goto-char pos)
8346 (org-back-to-heading t)))
8347 ((save-excursion
8348 (goto-char (point-min))
8349 (and
8350 (re-search-forward
8351 (concat "<<" (regexp-quote s0) ">>") nil t)
8352 (setq type 'dedicated
8353 pos (match-beginning 0))))
8354 ;; There is an exact target for this
8355 (goto-char pos))
8356 ((and (string-match "^(\\(.*\\))$" s0)
8357 (save-excursion
8358 (goto-char (point-min))
8359 (and
8360 (re-search-forward
8361 (concat "[^[]" (regexp-quote
8362 (format org-coderef-label-format
8363 (match-string 1 s0))))
8364 nil t)
8365 (setq type 'dedicated
8366 pos (1+ (match-beginning 0))))))
8367 ;; There is a coderef target for this
8368 (goto-char pos))
8369 ((string-match "^/\\(.*\\)/$" s)
8370 ;; A regular expression
8371 (cond
8372 ((org-mode-p)
8373 (org-occur (match-string 1 s)))
8374 ;;((eq major-mode 'dired-mode)
8375 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8376 (t (org-do-occur (match-string 1 s)))))
8378 ;; A normal search strings
8379 (when (equal (string-to-char s) ?*)
8380 ;; Anchor on headlines, post may include tags.
8381 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8382 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8383 s (substring s 1)))
8384 (remove-text-properties
8385 0 (length s)
8386 '(face nil mouse-face nil keymap nil fontified nil) s)
8387 ;; Make a series of regular expressions to find a match
8388 (setq words (org-split-string s "[ \n\r\t]+")
8390 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8391 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8392 "\\)" markers)
8393 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8394 re2a (concat "[ \t\r\n]" re2a_)
8395 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8396 re4 (concat "[^a-zA-Z_]" re4_)
8398 re1 (concat pre re2 post)
8399 re3 (concat pre (if pre re4_ re4) post)
8400 re5 (concat pre ".*" re4)
8401 re2 (concat pre re2)
8402 re2a (concat pre (if pre re2a_ re2a))
8403 re4 (concat pre (if pre re4_ re4))
8404 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8405 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8406 re5 "\\)"
8408 (cond
8409 ((eq type 'org-occur) (org-occur reall))
8410 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8411 (t (goto-char (point-min))
8412 (setq type 'fuzzy)
8413 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8414 (org-search-not-self 1 re1 nil t)
8415 (org-search-not-self 1 re2 nil t)
8416 (org-search-not-self 1 re2a nil t)
8417 (org-search-not-self 1 re3 nil t)
8418 (org-search-not-self 1 re4 nil t)
8419 (org-search-not-self 1 re5 nil t)
8421 (goto-char (match-beginning 1))
8422 (goto-char pos)
8423 (error "No match")))))
8425 ;; Normal string-search
8426 (goto-char (point-min))
8427 (if (search-forward s nil t)
8428 (goto-char (match-beginning 0))
8429 (error "No match"))))
8430 (and (org-mode-p) (org-show-context 'link-search))
8431 type))
8433 (defun org-search-not-self (group &rest args)
8434 "Execute `re-search-forward', but only accept matches that do not
8435 enclose the position of `org-open-link-marker'."
8436 (let ((m org-open-link-marker))
8437 (catch 'exit
8438 (while (apply 're-search-forward args)
8439 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8440 (goto-char (match-end group))
8441 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8442 (> (match-beginning 0) (marker-position m))
8443 (< (match-end 0) (marker-position m)))
8444 (save-match-data
8445 (or (not (org-in-regexp
8446 org-bracket-link-analytic-regexp 1))
8447 (not (match-end 4)) ; no description
8448 (and (<= (match-beginning 4) (point))
8449 (>= (match-end 4) (point))))))
8450 (throw 'exit (point))))))))
8452 (defun org-get-buffer-for-internal-link (buffer)
8453 "Return a buffer to be used for displaying the link target of internal links."
8454 (cond
8455 ((not org-display-internal-link-with-indirect-buffer)
8456 buffer)
8457 ((string-match "(Clone)$" (buffer-name buffer))
8458 (message "Buffer is already a clone, not making another one")
8459 ;; we also do not modify visibility in this case
8460 buffer)
8461 (t ; make a new indirect buffer for displaying the link
8462 (let* ((bn (buffer-name buffer))
8463 (ibn (concat bn "(Clone)"))
8464 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8465 (with-current-buffer ib (org-overview))
8466 ib))))
8468 (defun org-do-occur (regexp &optional cleanup)
8469 "Call the Emacs command `occur'.
8470 If CLEANUP is non-nil, remove the printout of the regular expression
8471 in the *Occur* buffer. This is useful if the regex is long and not useful
8472 to read."
8473 (occur regexp)
8474 (when cleanup
8475 (let ((cwin (selected-window)) win beg end)
8476 (when (setq win (get-buffer-window "*Occur*"))
8477 (select-window win))
8478 (goto-char (point-min))
8479 (when (re-search-forward "match[a-z]+" nil t)
8480 (setq beg (match-end 0))
8481 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8482 (setq end (1- (match-beginning 0)))))
8483 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8484 (goto-char (point-min))
8485 (select-window cwin))))
8487 ;;; The mark ring for links jumps
8489 (defvar org-mark-ring nil
8490 "Mark ring for positions before jumps in Org-mode.")
8491 (defvar org-mark-ring-last-goto nil
8492 "Last position in the mark ring used to go back.")
8493 ;; Fill and close the ring
8494 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8495 (loop for i from 1 to org-mark-ring-length do
8496 (push (make-marker) org-mark-ring))
8497 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8498 org-mark-ring)
8500 (defun org-mark-ring-push (&optional pos buffer)
8501 "Put the current position or POS into the mark ring and rotate it."
8502 (interactive)
8503 (setq pos (or pos (point)))
8504 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8505 (move-marker (car org-mark-ring)
8506 (or pos (point))
8507 (or buffer (current-buffer)))
8508 (message "%s"
8509 (substitute-command-keys
8510 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8512 (defun org-mark-ring-goto (&optional n)
8513 "Jump to the previous position in the mark ring.
8514 With prefix arg N, jump back that many stored positions. When
8515 called several times in succession, walk through the entire ring.
8516 Org-mode commands jumping to a different position in the current file,
8517 or to another Org-mode file, automatically push the old position
8518 onto the ring."
8519 (interactive "p")
8520 (let (p m)
8521 (if (eq last-command this-command)
8522 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8523 (setq p org-mark-ring))
8524 (setq org-mark-ring-last-goto p)
8525 (setq m (car p))
8526 (switch-to-buffer (marker-buffer m))
8527 (goto-char m)
8528 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8530 (defun org-remove-angle-brackets (s)
8531 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8532 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8534 (defun org-add-angle-brackets (s)
8535 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8536 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8538 (defun org-remove-double-quotes (s)
8539 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8540 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8543 ;;; Following specific links
8545 (defun org-follow-timestamp-link ()
8546 (cond
8547 ((org-at-date-range-p t)
8548 (let ((org-agenda-start-on-weekday)
8549 (t1 (match-string 1))
8550 (t2 (match-string 2)))
8551 (setq t1 (time-to-days (org-time-string-to-time t1))
8552 t2 (time-to-days (org-time-string-to-time t2)))
8553 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8554 ((org-at-timestamp-p t)
8555 (org-agenda-list nil (time-to-days (org-time-string-to-time
8556 (substring (match-string 1) 0 10)))
8558 (t (error "This should not happen"))))
8561 ;;; Following file links
8562 (defvar org-wait nil)
8563 (defun org-open-file (path &optional in-emacs line search)
8564 "Open the file at PATH.
8565 First, this expands any special file name abbreviations. Then the
8566 configuration variable `org-file-apps' is checked if it contains an
8567 entry for this file type, and if yes, the corresponding command is launched.
8569 If no application is found, Emacs simply visits the file.
8571 With optional prefix argument IN-EMACS, Emacs will visit the file.
8572 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8573 and o use an external application to visit the file.
8575 Optional LINE specifies a line to go to, optional SEARCH a string to
8576 search for. If LINE or SEARCH is given, the file will always be
8577 opened in Emacs.
8578 If the file does not exist, an error is thrown."
8579 (setq in-emacs (or in-emacs line search))
8580 (let* ((file (if (equal path "")
8581 buffer-file-name
8582 (substitute-in-file-name (expand-file-name path))))
8583 (apps (append org-file-apps (org-default-apps)))
8584 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8585 (dirp (if remp nil (file-directory-p file)))
8586 (file (if (and dirp org-open-directory-means-index-dot-org)
8587 (concat (file-name-as-directory file) "index.org")
8588 file))
8589 (a-m-a-p (assq 'auto-mode apps))
8590 (dfile (downcase file))
8591 (old-buffer (current-buffer))
8592 (old-pos (point))
8593 (old-mode major-mode)
8594 ext cmd)
8595 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8596 (setq ext (match-string 1 dfile))
8597 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8598 (setq ext (match-string 1 dfile))))
8599 (cond
8600 ((equal in-emacs '(16))
8601 (setq cmd (cdr (assoc 'system apps))))
8602 (in-emacs (setq cmd 'emacs))
8604 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8605 (and dirp (cdr (assoc 'directory apps)))
8606 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8607 'string-match)
8608 (cdr (assoc ext apps))
8609 (cdr (assoc t apps))))))
8610 (when (eq cmd 'system)
8611 (setq cmd (cdr (assoc 'system apps))))
8612 (when (eq cmd 'default)
8613 (setq cmd (cdr (assoc t apps))))
8614 (when (eq cmd 'mailcap)
8615 (require 'mailcap)
8616 (mailcap-parse-mailcaps)
8617 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8618 (command (mailcap-mime-info mime-type)))
8619 (if (stringp command)
8620 (setq cmd command)
8621 (setq cmd 'emacs))))
8622 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8623 (not (file-exists-p file))
8624 (not org-open-non-existing-files))
8625 (error "No such file: %s" file))
8626 (cond
8627 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8628 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8629 (while (string-match "['\"]%s['\"]" cmd)
8630 (setq cmd (replace-match "%s" t t cmd)))
8631 (while (string-match "%s" cmd)
8632 (setq cmd (replace-match
8633 (save-match-data
8634 (shell-quote-argument
8635 (convert-standard-filename file)))
8636 t t cmd)))
8637 (save-window-excursion
8638 (start-process-shell-command cmd nil cmd)
8639 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8641 ((or (stringp cmd)
8642 (eq cmd 'emacs))
8643 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8644 (widen)
8645 (if line (org-goto-line line)
8646 (if search (org-link-search search))))
8647 ((consp cmd)
8648 (let ((file (convert-standard-filename file)))
8649 (eval cmd)))
8650 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8651 (and (org-mode-p) (eq old-mode 'org-mode)
8652 (or (not (equal old-buffer (current-buffer)))
8653 (not (equal old-pos (point))))
8654 (org-mark-ring-push old-pos old-buffer))))
8656 (defun org-default-apps ()
8657 "Return the default applications for this operating system."
8658 (cond
8659 ((eq system-type 'darwin)
8660 org-file-apps-defaults-macosx)
8661 ((eq system-type 'windows-nt)
8662 org-file-apps-defaults-windowsnt)
8663 (t org-file-apps-defaults-gnu)))
8665 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8666 "Convert extensions to regular expressions in the cars of LIST.
8667 Also, weed out any non-string entries, because the return value is used
8668 only for regexp matching.
8669 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8670 point to the symbol `emacs', indicating that the file should
8671 be opened in Emacs."
8672 (append
8673 (delq nil
8674 (mapcar (lambda (x)
8675 (if (not (stringp (car x)))
8677 (if (string-match "\\W" (car x))
8679 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8680 list))
8681 (if add-auto-mode
8682 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8684 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8685 (defun org-file-remote-p (file)
8686 "Test whether FILE specifies a location on a remote system.
8687 Return non-nil if the location is indeed remote.
8689 For example, the filename \"/user@host:/foo\" specifies a location
8690 on the system \"/user@host:\"."
8691 (cond ((fboundp 'file-remote-p)
8692 (file-remote-p file))
8693 ((fboundp 'tramp-handle-file-remote-p)
8694 (tramp-handle-file-remote-p file))
8695 ((and (boundp 'ange-ftp-name-format)
8696 (string-match (car ange-ftp-name-format) file))
8698 (t nil)))
8701 ;;;; Refiling
8703 (defun org-get-org-file ()
8704 "Read a filename, with default directory `org-directory'."
8705 (let ((default (or org-default-notes-file remember-data-file)))
8706 (read-file-name (format "File name [%s]: " default)
8707 (file-name-as-directory org-directory)
8708 default)))
8710 (defun org-notes-order-reversed-p ()
8711 "Check if the current file should receive notes in reversed order."
8712 (cond
8713 ((not org-reverse-note-order) nil)
8714 ((eq t org-reverse-note-order) t)
8715 ((not (listp org-reverse-note-order)) nil)
8716 (t (catch 'exit
8717 (let ((all org-reverse-note-order)
8718 entry)
8719 (while (setq entry (pop all))
8720 (if (string-match (car entry) buffer-file-name)
8721 (throw 'exit (cdr entry))))
8722 nil)))))
8724 (defvar org-refile-target-table nil
8725 "The list of refile targets, created by `org-refile'.")
8727 (defvar org-agenda-new-buffers nil
8728 "Buffers created to visit agenda files.")
8730 (defun org-get-refile-targets (&optional default-buffer)
8731 "Produce a table with refile targets."
8732 (let ((case-fold-search nil)
8733 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8734 (entries (or org-refile-targets '((nil . (:level . 1)))))
8735 targets txt re files f desc descre fast-path-p level pos0)
8736 (message "Getting targets...")
8737 (with-current-buffer (or default-buffer (current-buffer))
8738 (while (setq entry (pop entries))
8739 (setq files (car entry) desc (cdr entry))
8740 (setq fast-path-p nil)
8741 (cond
8742 ((null files) (setq files (list (current-buffer))))
8743 ((eq files 'org-agenda-files)
8744 (setq files (org-agenda-files 'unrestricted)))
8745 ((and (symbolp files) (fboundp files))
8746 (setq files (funcall files)))
8747 ((and (symbolp files) (boundp files))
8748 (setq files (symbol-value files))))
8749 (if (stringp files) (setq files (list files)))
8750 (cond
8751 ((eq (car desc) :tag)
8752 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8753 ((eq (car desc) :todo)
8754 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8755 ((eq (car desc) :regexp)
8756 (setq descre (cdr desc)))
8757 ((eq (car desc) :level)
8758 (setq descre (concat "^\\*\\{" (number-to-string
8759 (if org-odd-levels-only
8760 (1- (* 2 (cdr desc)))
8761 (cdr desc)))
8762 "\\}[ \t]")))
8763 ((eq (car desc) :maxlevel)
8764 (setq fast-path-p t)
8765 (setq descre (concat "^\\*\\{1," (number-to-string
8766 (if org-odd-levels-only
8767 (1- (* 2 (cdr desc)))
8768 (cdr desc)))
8769 "\\}[ \t]")))
8770 (t (error "Bad refiling target description %s" desc)))
8771 (while (setq f (pop files))
8772 (save-excursion
8773 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8774 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8775 (setq f (expand-file-name f))
8776 (if (eq org-refile-use-outline-path 'file)
8777 (push (list (file-name-nondirectory f) f nil nil) targets))
8778 (save-excursion
8779 (save-restriction
8780 (widen)
8781 (goto-char (point-min))
8782 (while (re-search-forward descre nil t)
8783 (goto-char (setq pos0 (point-at-bol)))
8784 (catch 'next
8785 (when org-refile-target-verify-function
8786 (save-match-data
8787 (or (funcall org-refile-target-verify-function)
8788 (throw 'next t))))
8789 (when (looking-at org-complex-heading-regexp)
8790 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8791 txt (org-link-display-format (match-string 4))
8792 re (concat "^" (regexp-quote
8793 (buffer-substring (match-beginning 1)
8794 (match-end 4)))))
8795 (if (match-end 5) (setq re (concat re "[ \t]+"
8796 (regexp-quote
8797 (match-string 5)))))
8798 (setq re (concat re "[ \t]*$"))
8799 (when org-refile-use-outline-path
8800 (setq txt (mapconcat 'org-protect-slash
8801 (append
8802 (if (eq org-refile-use-outline-path 'file)
8803 (list (file-name-nondirectory
8804 (buffer-file-name (buffer-base-buffer))))
8805 (if (eq org-refile-use-outline-path 'full-file-path)
8806 (list (buffer-file-name (buffer-base-buffer)))))
8807 (org-get-outline-path fast-path-p level txt)
8808 (list txt))
8809 "/")))
8810 (push (list txt f re (point)) targets)))
8811 (when (= (point) pos0)
8812 ;; verification function has not moved point
8813 (goto-char (point-at-eol))))))))))
8814 (message "Getting targets...done")
8815 (nreverse targets)))
8817 (defun org-protect-slash (s)
8818 (while (string-match "/" s)
8819 (setq s (replace-match "\\" t t s)))
8822 (defvar org-olpa (make-vector 20 nil))
8824 (defun org-get-outline-path (&optional fastp level heading)
8825 "Return the outline path to the current entry, as a list."
8826 (if fastp
8827 (progn
8828 (if (> level 19)
8829 (error "Outline path failure, more than 19 levels."))
8830 (loop for i from level upto 19 do
8831 (aset org-olpa i nil))
8832 (prog1
8833 (delq nil (append org-olpa nil))
8834 (aset org-olpa level heading)))
8835 (let (rtn)
8836 (save-excursion
8837 (while (org-up-heading-safe)
8838 (when (looking-at org-complex-heading-regexp)
8839 (push (org-match-string-no-properties 4) rtn)))
8840 rtn))))
8842 (defvar org-refile-history nil
8843 "History for refiling operations.")
8845 (defvar org-after-refile-insert-hook nil
8846 "Hook run after `org-refile' has inserted its stuff at the new location.
8847 Note that this is still *before* the stuff will be removed from
8848 the *old* location.")
8850 (defun org-refile (&optional goto default-buffer rfloc)
8851 "Move the entry at point to another heading.
8852 The list of target headings is compiled using the information in
8853 `org-refile-targets', which see. This list is created before each use
8854 and will therefore always be up-to-date.
8856 At the target location, the entry is filed as a subitem of the target heading.
8857 Depending on `org-reverse-note-order', the new subitem will either be the
8858 first or the last subitem.
8860 If there is an active region, all entries in that region will be moved.
8861 However, the region must fulfil the requirement that the first heading
8862 is the first one sets the top-level of the moved text - at most siblings
8863 below it are allowed.
8865 With prefix arg GOTO, the command will only visit the target location,
8866 not actually move anything.
8867 With a double prefix `C-u C-u', go to the location where the last refiling
8868 operation has put the subtree.
8870 RFLOC can be a refile location obtained in a different way.
8872 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8873 (interactive "P")
8874 (let* ((cbuf (current-buffer))
8875 (regionp (org-region-active-p))
8876 (region-start (and regionp (region-beginning)))
8877 (region-end (and regionp (region-end)))
8878 (region-length (and regionp (- region-end region-start)))
8879 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8880 pos it nbuf file re level reversed)
8881 (when regionp
8882 (goto-char region-start)
8883 (or (bolp) (goto-char (point-at-bol)))
8884 (setq region-start (point))
8885 (unless (org-kill-is-subtree-p
8886 (buffer-substring region-start region-end))
8887 (error "The region is not a (sequence of) subtree(s)")))
8888 (if (equal goto '(16))
8889 (org-refile-goto-last-stored)
8890 (when (setq it (or rfloc
8891 (save-excursion
8892 (org-refile-get-location
8893 (if goto "Goto: " "Refile to: ") default-buffer
8894 org-refile-allow-creating-parent-nodes))))
8895 (setq file (nth 1 it)
8896 re (nth 2 it)
8897 pos (nth 3 it))
8898 (if (and (not goto)
8900 (equal (buffer-file-name) file)
8901 (if regionp
8902 (and (>= pos region-start)
8903 (<= pos region-end))
8904 (and (>= pos (point))
8905 (< pos (save-excursion
8906 (org-end-of-subtree t t))))))
8907 (error "Cannot refile to position inside the tree or region"))
8909 (setq nbuf (or (find-buffer-visiting file)
8910 (find-file-noselect file)))
8911 (if goto
8912 (progn
8913 (switch-to-buffer nbuf)
8914 (goto-char pos)
8915 (org-show-context 'org-goto))
8916 (if regionp
8917 (progn
8918 (org-kill-new (buffer-substring region-start region-end))
8919 (org-save-markers-in-region region-start region-end))
8920 (org-copy-subtree 1 nil t))
8921 (save-excursion
8922 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8923 (find-file-noselect file))))
8924 (setq reversed (org-notes-order-reversed-p))
8925 (save-excursion
8926 (save-restriction
8927 (widen)
8928 (if pos
8929 (progn
8930 (goto-char pos)
8931 (looking-at outline-regexp)
8932 (setq level (org-get-valid-level (funcall outline-level) 1))
8933 (goto-char
8934 (if reversed
8935 (or (outline-next-heading) (point-max))
8936 (or (save-excursion (org-get-next-sibling))
8937 (org-end-of-subtree t t)
8938 (point-max)))))
8939 (setq level 1)
8940 (if (not reversed)
8941 (goto-char (point-max))
8942 (goto-char (point-min))
8943 (or (outline-next-heading) (goto-char (point-max)))))
8944 (if (not (bolp)) (newline))
8945 (bookmark-set "org-refile-last-stored")
8946 (org-paste-subtree level)
8947 (if (fboundp 'deactivate-mark) (deactivate-mark))
8948 (run-hooks 'org-after-refile-insert-hook))))
8949 (if regionp
8950 (delete-region (point) (+ (point) region-length))
8951 (org-cut-subtree))
8952 (when (featurep 'org-inlinetask)
8953 (org-inlinetask-remove-END-maybe))
8954 (setq org-markers-to-move nil)
8955 (message "Refiled to \"%s\"" (car it))))))
8956 (org-reveal))
8958 (defun org-refile-goto-last-stored ()
8959 "Go to the location where the last refile was stored."
8960 (interactive)
8961 (bookmark-jump "org-refile-last-stored")
8962 (message "This is the location of the last refile"))
8964 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8965 "Prompt the user for a refile location, using PROMPT."
8966 (let ((org-refile-targets org-refile-targets)
8967 (org-refile-use-outline-path org-refile-use-outline-path))
8968 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8969 (unless org-refile-target-table
8970 (error "No refile targets"))
8971 (let* ((cbuf (current-buffer))
8972 (partial-completion-mode nil)
8973 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8974 (cfunc (if (and org-refile-use-outline-path
8975 org-outline-path-complete-in-steps)
8976 'org-olpath-completing-read
8977 'org-icompleting-read))
8978 (extra (if org-refile-use-outline-path "/" ""))
8979 (filename (and cfn (expand-file-name cfn)))
8980 (tbl (mapcar
8981 (lambda (x)
8982 (if (and (not (member org-refile-use-outline-path
8983 '(file full-file-path)))
8984 (not (equal filename (nth 1 x))))
8985 (cons (concat (car x) extra " ("
8986 (file-name-nondirectory (nth 1 x)) ")")
8987 (cdr x))
8988 (cons (concat (car x) extra) (cdr x))))
8989 org-refile-target-table))
8990 (completion-ignore-case t)
8991 pa answ parent-target child parent old-hist)
8992 (setq old-hist org-refile-history)
8993 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8994 nil 'org-refile-history))
8995 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8996 (if pa
8997 (progn
8998 (when (or (not org-refile-history)
8999 (not (eq old-hist org-refile-history))
9000 (not (equal (car pa) (car org-refile-history))))
9001 (setq org-refile-history
9002 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9003 org-refile-history
9004 (cdr org-refile-history))))
9005 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9006 (pop org-refile-history)))
9008 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9009 (setq parent (match-string 1 answ)
9010 child (match-string 2 answ))
9011 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
9012 (when (and parent-target
9013 (or (eq new-nodes t)
9014 (and (eq new-nodes 'confirm)
9015 (y-or-n-p (format "Create new node \"%s\"? " child)))))
9016 (org-refile-new-child parent-target child))))))
9018 (defun org-refile-new-child (parent-target child)
9019 "Use refile target PARENT-TARGET to add new CHILD below it."
9020 (unless parent-target
9021 (error "Cannot find parent for new node"))
9022 (let ((file (nth 1 parent-target))
9023 (pos (nth 3 parent-target))
9024 level)
9025 (with-current-buffer (or (find-buffer-visiting file)
9026 (find-file-noselect file))
9027 (save-excursion
9028 (save-restriction
9029 (widen)
9030 (if pos
9031 (goto-char pos)
9032 (goto-char (point-max))
9033 (if (not (bolp)) (newline)))
9034 (when (looking-at outline-regexp)
9035 (setq level (funcall outline-level))
9036 (org-end-of-subtree t t))
9037 (org-back-over-empty-lines)
9038 (insert "\n" (make-string
9039 (if pos (org-get-valid-level level 1) 1) ?*)
9040 " " child "\n")
9041 (beginning-of-line 0)
9042 (list (concat (car parent-target) "/" child) file "" (point)))))))
9044 (defun org-olpath-completing-read (prompt collection &rest args)
9045 "Read an outline path like a file name."
9046 (let ((thetable collection)
9047 (org-completion-use-ido nil) ; does not work with ido.
9048 (org-completion-use-iswitchb nil)) ; or iswitchb
9049 (apply
9050 'org-icompleting-read prompt
9051 (lambda (string predicate &optional flag)
9052 (let (rtn r f (l (length string)))
9053 (cond
9054 ((eq flag nil)
9055 ;; try completion
9056 (try-completion string thetable))
9057 ((eq flag t)
9058 ;; all-completions
9059 (setq rtn (all-completions string thetable predicate))
9060 (mapcar
9061 (lambda (x)
9062 (setq r (substring x l))
9063 (if (string-match " ([^)]*)$" x)
9064 (setq f (match-string 0 x))
9065 (setq f ""))
9066 (if (string-match "/" r)
9067 (concat string (substring r 0 (match-end 0)) f)
9069 rtn))
9070 ((eq flag 'lambda)
9071 ;; exact match?
9072 (assoc string thetable)))
9074 args)))
9076 ;;;; Dynamic blocks
9078 (defun org-find-dblock (name)
9079 "Find the first dynamic block with name NAME in the buffer.
9080 If not found, stay at current position and return nil."
9081 (let (pos)
9082 (save-excursion
9083 (goto-char (point-min))
9084 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9085 nil t)
9086 (match-beginning 0))))
9087 (if pos (goto-char pos))
9088 pos))
9090 (defconst org-dblock-start-re
9091 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9092 "Matches the startline of a dynamic block, with parameters.")
9094 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9095 "Matches the end of a dynamic block.")
9097 (defun org-create-dblock (plist)
9098 "Create a dynamic block section, with parameters taken from PLIST.
9099 PLIST must contain a :name entry which is used as name of the block."
9100 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9101 (end-of-line 1)
9102 (newline))
9103 (let ((col (current-column))
9104 (name (plist-get plist :name)))
9105 (insert "#+BEGIN: " name)
9106 (while plist
9107 (if (eq (car plist) :name)
9108 (setq plist (cddr plist))
9109 (insert " " (prin1-to-string (pop plist)))))
9110 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9111 (beginning-of-line -2)))
9113 (defun org-prepare-dblock ()
9114 "Prepare dynamic block for refresh.
9115 This empties the block, puts the cursor at the insert position and returns
9116 the property list including an extra property :name with the block name."
9117 (unless (looking-at org-dblock-start-re)
9118 (error "Not at a dynamic block"))
9119 (let* ((begdel (1+ (match-end 0)))
9120 (name (org-no-properties (match-string 1)))
9121 (params (append (list :name name)
9122 (read (concat "(" (match-string 3) ")")))))
9123 (save-excursion
9124 (beginning-of-line 1)
9125 (skip-chars-forward " \t")
9126 (setq params (plist-put params :indentation-column (current-column))))
9127 (unless (re-search-forward org-dblock-end-re nil t)
9128 (error "Dynamic block not terminated"))
9129 (setq params
9130 (append params
9131 (list :content (buffer-substring
9132 begdel (match-beginning 0)))))
9133 (delete-region begdel (match-beginning 0))
9134 (goto-char begdel)
9135 (open-line 1)
9136 params))
9138 (defun org-map-dblocks (&optional command)
9139 "Apply COMMAND to all dynamic blocks in the current buffer.
9140 If COMMAND is not given, use `org-update-dblock'."
9141 (let ((cmd (or command 'org-update-dblock))
9142 pos)
9143 (save-excursion
9144 (goto-char (point-min))
9145 (while (re-search-forward org-dblock-start-re nil t)
9146 (goto-char (setq pos (match-beginning 0)))
9147 (condition-case nil
9148 (funcall cmd)
9149 (error (message "Error during update of dynamic block")))
9150 (goto-char pos)
9151 (unless (re-search-forward org-dblock-end-re nil t)
9152 (error "Dynamic block not terminated"))))))
9154 (defun org-dblock-update (&optional arg)
9155 "User command for updating dynamic blocks.
9156 Update the dynamic block at point. With prefix ARG, update all dynamic
9157 blocks in the buffer."
9158 (interactive "P")
9159 (if arg
9160 (org-update-all-dblocks)
9161 (or (looking-at org-dblock-start-re)
9162 (org-beginning-of-dblock))
9163 (org-update-dblock)))
9165 (defun org-update-dblock ()
9166 "Update the dynamic block at point
9167 This means to empty the block, parse for parameters and then call
9168 the correct writing function."
9169 (save-window-excursion
9170 (let* ((pos (point))
9171 (line (org-current-line))
9172 (params (org-prepare-dblock))
9173 (name (plist-get params :name))
9174 (indent (plist-get params :indentation-column))
9175 (cmd (intern (concat "org-dblock-write:" name))))
9176 (message "Updating dynamic block `%s' at line %d..." name line)
9177 (funcall cmd params)
9178 (message "Updating dynamic block `%s' at line %d...done" name line)
9179 (goto-char pos)
9180 (when (and indent (> indent 0))
9181 (setq indent (make-string indent ?\ ))
9182 (save-excursion
9183 (org-beginning-of-dblock)
9184 (forward-line 1)
9185 (while (not (looking-at org-dblock-end-re))
9186 (insert indent)
9187 (beginning-of-line 2))
9188 (when (looking-at org-dblock-end-re)
9189 (and (looking-at "[ \t]+")
9190 (replace-match ""))
9191 (insert indent)))))))
9193 (defun org-beginning-of-dblock ()
9194 "Find the beginning of the dynamic block at point.
9195 Error if there is no such block at point."
9196 (let ((pos (point))
9197 beg)
9198 (end-of-line 1)
9199 (if (and (re-search-backward org-dblock-start-re nil t)
9200 (setq beg (match-beginning 0))
9201 (re-search-forward org-dblock-end-re nil t)
9202 (> (match-end 0) pos))
9203 (goto-char beg)
9204 (goto-char pos)
9205 (error "Not in a dynamic block"))))
9207 (defun org-update-all-dblocks ()
9208 "Update all dynamic blocks in the buffer.
9209 This function can be used in a hook."
9210 (when (org-mode-p)
9211 (org-map-dblocks 'org-update-dblock)))
9214 ;;;; Completion
9216 (defconst org-additional-option-like-keywords
9217 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9218 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9219 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "LATEX_CLASS:" "ATTR_LaTeX"
9220 "BEGIN:" "END:"
9221 "ORGTBL" "TBLFM:" "TBLNAME:"
9222 "BEGIN_EXAMPLE" "END_EXAMPLE"
9223 "BEGIN_QUOTE" "END_QUOTE"
9224 "BEGIN_VERSE" "END_VERSE"
9225 "BEGIN_CENTER" "END_CENTER"
9226 "BEGIN_SRC" "END_SRC"
9227 "CATEGORY" "COLUMNS"
9228 "CAPTION" "LABEL"
9229 "SETUPFILE"
9230 "BIND"
9231 "MACRO"))
9233 (defcustom org-structure-template-alist
9235 ("s" "#+begin_src ?\n\n#+end_src"
9236 "<src lang=\"?\">\n\n</src>")
9237 ("e" "#+begin_example\n?\n#+end_example"
9238 "<example>\n?\n</example>")
9239 ("q" "#+begin_quote\n?\n#+end_quote"
9240 "<quote>\n?\n</quote>")
9241 ("v" "#+begin_verse\n?\n#+end_verse"
9242 "<verse>\n?\n/verse>")
9243 ("c" "#+begin_center\n?\n#+end_center"
9244 "<center>\n?\n/center>")
9245 ("l" "#+begin_latex\n?\n#+end_latex"
9246 "<literal style=\"latex\">\n?\n</literal>")
9247 ("L" "#+latex: "
9248 "<literal style=\"latex\">?</literal>")
9249 ("h" "#+begin_html\n?\n#+end_html"
9250 "<literal style=\"html\">\n?\n</literal>")
9251 ("H" "#+html: "
9252 "<literal style=\"html\">?</literal>")
9253 ("a" "#+begin_ascii\n?\n#+end_ascii")
9254 ("A" "#+ascii: ")
9255 ("i" "#+include %file ?"
9256 "<include file=%file markup=\"?\">")
9258 "Structure completion elements.
9259 This is a list of abbreviation keys and values. The value gets inserted
9260 it you type @samp{.} followed by the key and then the completion key,
9261 usually `M-TAB'. %file will be replaced by a file name after prompting
9262 for the file using completion.
9263 There are two templates for each key, the first uses the original Org syntax,
9264 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9265 the default when the /org-mtags.el/ module has been loaded. See also the
9266 variable `org-mtags-prefer-muse-templates'.
9267 This is an experimental feature, it is undecided if it is going to stay in."
9268 :group 'org-completion
9269 :type '(repeat
9270 (string :tag "Key")
9271 (string :tag "Template")
9272 (string :tag "Muse Template")))
9274 (defun org-try-structure-completion ()
9275 "Try to complete a structure template before point.
9276 This looks for strings like \"<e\" on an otherwise empty line and
9277 expands them."
9278 (let ((l (buffer-substring (point-at-bol) (point)))
9280 (when (and (looking-at "[ \t]*$")
9281 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9282 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9283 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9284 (match-beginning 1)) a)
9285 t)))
9287 (defun org-complete-expand-structure-template (start cell)
9288 "Expand a structure template."
9289 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9290 (rpl (nth (if musep 2 1) cell))
9291 (ind ""))
9292 (delete-region start (point))
9293 (when (string-match "\\`#\\+" rpl)
9294 (cond
9295 ((bolp))
9296 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9297 (setq ind (buffer-substring (point-at-bol) (point))))
9298 (t (newline))))
9299 (setq start (point))
9300 (if (string-match "%file" rpl)
9301 (setq rpl (replace-match
9302 (concat
9303 "\""
9304 (save-match-data
9305 (abbreviate-file-name (read-file-name "Include file: ")))
9306 "\"")
9307 t t rpl)))
9308 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9309 (concat "\n" ind)))
9310 (insert rpl)
9311 (if (re-search-backward "\\?" start t) (delete-char 1))))
9314 (defun org-complete (&optional arg)
9315 "Perform completion on word at point.
9316 At the beginning of a headline, this completes TODO keywords as given in
9317 `org-todo-keywords'.
9318 If the current word is preceded by a backslash, completes the TeX symbols
9319 that are supported for HTML support.
9320 If the current word is preceded by \"#+\", completes special words for
9321 setting file options.
9322 In the line after \"#+STARTUP:, complete valid keywords.\"
9323 At all other locations, this simply calls the value of
9324 `org-completion-fallback-command'."
9325 (interactive "P")
9326 (org-without-partial-completion
9327 (catch 'exit
9328 (let* ((a nil)
9329 (end (point))
9330 (beg1 (save-excursion
9331 (skip-chars-backward (org-re "[:alnum:]_@"))
9332 (point)))
9333 (beg (save-excursion
9334 (skip-chars-backward "a-zA-Z0-9_:$")
9335 (point)))
9336 (confirm (lambda (x) (stringp (car x))))
9337 (searchhead (equal (char-before beg) ?*))
9338 (struct
9339 (when (and (member (char-before beg1) '(?. ?<))
9340 (setq a (assoc (buffer-substring beg1 (point))
9341 org-structure-template-alist)))
9342 (org-complete-expand-structure-template (1- beg1) a)
9343 (throw 'exit t)))
9344 (tag (and (equal (char-before beg1) ?:)
9345 (equal (char-after (point-at-bol)) ?*)))
9346 (prop (and (equal (char-before beg1) ?:)
9347 (not (equal (char-after (point-at-bol)) ?*))))
9348 (texp (equal (char-before beg) ?\\))
9349 (link (equal (char-before beg) ?\[))
9350 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9351 beg)
9352 "#+"))
9353 (startup (string-match "^#\\+STARTUP:.*"
9354 (buffer-substring (point-at-bol) (point))))
9355 (completion-ignore-case opt)
9356 (type nil)
9357 (tbl nil)
9358 (table (cond
9359 (opt
9360 (setq type :opt)
9361 (require 'org-exp)
9362 (append
9363 (delq nil
9364 (mapcar
9365 (lambda (x)
9366 (if (string-match
9367 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9368 (cons (match-string 2 x)
9369 (match-string 1 x))))
9370 (org-split-string (org-get-current-options) "\n")))
9371 (mapcar 'list org-additional-option-like-keywords)))
9372 (startup
9373 (setq type :startup)
9374 org-startup-options)
9375 (link (append org-link-abbrev-alist-local
9376 org-link-abbrev-alist))
9377 (texp
9378 (setq type :tex)
9379 org-html-entities)
9380 ((string-match "\\`\\*+[ \t]+\\'"
9381 (buffer-substring (point-at-bol) beg))
9382 (setq type :todo)
9383 (mapcar 'list org-todo-keywords-1))
9384 (searchhead
9385 (setq type :searchhead)
9386 (save-excursion
9387 (goto-char (point-min))
9388 (while (re-search-forward org-todo-line-regexp nil t)
9389 (push (list
9390 (org-make-org-heading-search-string
9391 (match-string 3) t))
9392 tbl)))
9393 tbl)
9394 (tag (setq type :tag beg beg1)
9395 (or org-tag-alist (org-get-buffer-tags)))
9396 (prop (setq type :prop beg beg1)
9397 (mapcar 'list (org-buffer-property-keys nil t t)))
9398 (t (progn
9399 (call-interactively org-completion-fallback-command)
9400 (throw 'exit nil)))))
9401 (pattern (buffer-substring-no-properties beg end))
9402 (completion (try-completion pattern table confirm)))
9403 (cond ((eq completion t)
9404 (if (not (assoc (upcase pattern) table))
9405 (message "Already complete")
9406 (if (and (equal type :opt)
9407 (not (member (car (assoc (upcase pattern) table))
9408 org-additional-option-like-keywords)))
9409 (insert (substring (cdr (assoc (upcase pattern) table))
9410 (length pattern)))
9411 (if (memq type '(:tag :prop)) (insert ":")))))
9412 ((null completion)
9413 (message "Can't find completion for \"%s\"" pattern)
9414 (ding))
9415 ((not (string= pattern completion))
9416 (delete-region beg end)
9417 (if (string-match " +$" completion)
9418 (setq completion (replace-match "" t t completion)))
9419 (insert completion)
9420 (if (get-buffer-window "*Completions*")
9421 (delete-window (get-buffer-window "*Completions*")))
9422 (if (assoc completion table)
9423 (if (eq type :todo) (insert " ")
9424 (if (memq type '(:tag :prop)) (insert ":"))))
9425 (if (and (equal type :opt) (assoc completion table))
9426 (message "%s" (substitute-command-keys
9427 "Press \\[org-complete] again to insert example settings"))))
9429 (message "Making completion list...")
9430 (let ((list (sort (all-completions pattern table confirm)
9431 'string<)))
9432 (with-output-to-temp-buffer "*Completions*"
9433 (condition-case nil
9434 ;; Protection needed for XEmacs and emacs 21
9435 (display-completion-list list pattern)
9436 (error (display-completion-list list)))))
9437 (message "Making completion list...%s" "done")))))))
9439 ;;;; TODO, DEADLINE, Comments
9441 (defun org-toggle-comment ()
9442 "Change the COMMENT state of an entry."
9443 (interactive)
9444 (save-excursion
9445 (org-back-to-heading)
9446 (let (case-fold-search)
9447 (if (looking-at (concat outline-regexp
9448 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9449 (replace-match "" t t nil 1)
9450 (if (looking-at outline-regexp)
9451 (progn
9452 (goto-char (match-end 0))
9453 (insert org-comment-string " ")))))))
9455 (defvar org-last-todo-state-is-todo nil
9456 "This is non-nil when the last TODO state change led to a TODO state.
9457 If the last change removed the TODO tag or switched to DONE, then
9458 this is nil.")
9460 (defvar org-setting-tags nil) ; dynamically skipped
9462 (defun org-parse-local-options (string var)
9463 "Parse STRING for startup setting relevant for variable VAR."
9464 (let ((rtn (symbol-value var))
9465 e opts)
9466 (save-match-data
9467 (if (or (not string) (not (string-match "\\S-" string)))
9469 (setq opts (delq nil (mapcar (lambda (x)
9470 (setq e (assoc x org-startup-options))
9471 (if (eq (nth 1 e) var) e nil))
9472 (org-split-string string "[ \t]+"))))
9473 (if (not opts)
9475 (setq rtn nil)
9476 (while (setq e (pop opts))
9477 (if (not (nth 3 e))
9478 (setq rtn (nth 2 e))
9479 (if (not (listp rtn)) (setq rtn nil))
9480 (push (nth 2 e) rtn)))
9481 rtn)))))
9483 (defvar org-todo-setup-filter-hook nil
9484 "Hook for functions that pre-filter todo specs.
9486 Each function takes a todo spec and returns either `nil' or the spec
9487 transformed into canonical form." )
9489 (defvar org-todo-get-default-hook nil
9490 "Hook for functions that get a default item for todo.
9492 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9493 `nil' or a string to be used for the todo mark." )
9495 (defvar org-agenda-headline-snapshot-before-repeat)
9497 (defun org-todo (&optional arg)
9498 "Change the TODO state of an item.
9499 The state of an item is given by a keyword at the start of the heading,
9500 like
9501 *** TODO Write paper
9502 *** DONE Call mom
9504 The different keywords are specified in the variable `org-todo-keywords'.
9505 By default the available states are \"TODO\" and \"DONE\".
9506 So for this example: when the item starts with TODO, it is changed to DONE.
9507 When it starts with DONE, the DONE is removed. And when neither TODO nor
9508 DONE are present, add TODO at the beginning of the heading.
9510 With C-u prefix arg, use completion to determine the new state.
9511 With numeric prefix arg, switch to that state.
9512 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9513 With a tripple C-u prefix, circumvent any state blocking.
9515 For calling through lisp, arg is also interpreted in the following way:
9516 'none -> empty state
9517 \"\"(empty string) -> switch to empty state
9518 'done -> switch to DONE
9519 'nextset -> switch to the next set of keywords
9520 'previousset -> switch to the previous set of keywords
9521 \"WAITING\" -> switch to the specified keyword, but only if it
9522 really is a member of `org-todo-keywords'."
9523 (interactive "P")
9524 (if (equal arg '(16)) (setq arg 'nextset))
9525 (let ((org-blocker-hook org-blocker-hook)
9526 (case-fold-search nil))
9527 (when (equal arg '(64))
9528 (setq arg nil org-blocker-hook nil))
9529 (when (and org-blocker-hook
9530 (or org-inhibit-blocking
9531 (org-entry-get nil "NOBLOCKING")))
9532 (setq org-blocker-hook nil))
9533 (save-excursion
9534 (catch 'exit
9535 (org-back-to-heading t)
9536 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9537 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9538 (looking-at " *"))
9539 (let* ((match-data (match-data))
9540 (startpos (point-at-bol))
9541 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9542 (org-log-done org-log-done)
9543 (org-log-repeat org-log-repeat)
9544 (org-todo-log-states org-todo-log-states)
9545 (this (match-string 1))
9546 (hl-pos (match-beginning 0))
9547 (head (org-get-todo-sequence-head this))
9548 (ass (assoc head org-todo-kwd-alist))
9549 (interpret (nth 1 ass))
9550 (done-word (nth 3 ass))
9551 (final-done-word (nth 4 ass))
9552 (last-state (or this ""))
9553 (completion-ignore-case t)
9554 (member (member this org-todo-keywords-1))
9555 (tail (cdr member))
9556 (state (cond
9557 ((and org-todo-key-trigger
9558 (or (and (equal arg '(4))
9559 (eq org-use-fast-todo-selection 'prefix))
9560 (and (not arg) org-use-fast-todo-selection
9561 (not (eq org-use-fast-todo-selection
9562 'prefix)))))
9563 ;; Use fast selection
9564 (org-fast-todo-selection))
9565 ((and (equal arg '(4))
9566 (or (not org-use-fast-todo-selection)
9567 (not org-todo-key-trigger)))
9568 ;; Read a state with completion
9569 (org-icompleting-read
9570 "State: " (mapcar (lambda(x) (list x))
9571 org-todo-keywords-1)
9572 nil t))
9573 ((eq arg 'right)
9574 (if this
9575 (if tail (car tail) nil)
9576 (car org-todo-keywords-1)))
9577 ((eq arg 'left)
9578 (if (equal member org-todo-keywords-1)
9580 (if this
9581 (nth (- (length org-todo-keywords-1)
9582 (length tail) 2)
9583 org-todo-keywords-1)
9584 (org-last org-todo-keywords-1))))
9585 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9586 (setq arg nil))) ; hack to fall back to cycling
9587 (arg
9588 ;; user or caller requests a specific state
9589 (cond
9590 ((equal arg "") nil)
9591 ((eq arg 'none) nil)
9592 ((eq arg 'done) (or done-word (car org-done-keywords)))
9593 ((eq arg 'nextset)
9594 (or (car (cdr (member head org-todo-heads)))
9595 (car org-todo-heads)))
9596 ((eq arg 'previousset)
9597 (let ((org-todo-heads (reverse org-todo-heads)))
9598 (or (car (cdr (member head org-todo-heads)))
9599 (car org-todo-heads))))
9600 ((car (member arg org-todo-keywords-1)))
9601 ((stringp arg)
9602 (error "State `%s' not valid in this file" arg))
9603 ((nth (1- (prefix-numeric-value arg))
9604 org-todo-keywords-1))))
9605 ((null member) (or head (car org-todo-keywords-1)))
9606 ((equal this final-done-word) nil) ;; -> make empty
9607 ((null tail) nil) ;; -> first entry
9608 ((memq interpret '(type priority))
9609 (if (eq this-command last-command)
9610 (car tail)
9611 (if (> (length tail) 0)
9612 (or done-word (car org-done-keywords))
9613 nil)))
9615 (car tail))))
9616 (state (or
9617 (run-hook-with-args-until-success
9618 'org-todo-get-default-hook state last-state)
9619 state))
9620 (next (if state (concat " " state " ") " "))
9621 (change-plist (list :type 'todo-state-change :from this :to state
9622 :position startpos))
9623 dolog now-done-p)
9624 (when org-blocker-hook
9625 (setq org-last-todo-state-is-todo
9626 (not (member this org-done-keywords)))
9627 (unless (save-excursion
9628 (save-match-data
9629 (run-hook-with-args-until-failure
9630 'org-blocker-hook change-plist)))
9631 (if (interactive-p)
9632 (error "TODO state change from %s to %s blocked" this state)
9633 ;; fail silently
9634 (message "TODO state change from %s to %s blocked" this state)
9635 (throw 'exit nil))))
9636 (store-match-data match-data)
9637 (replace-match next t t)
9638 (unless (pos-visible-in-window-p hl-pos)
9639 (message "TODO state changed to %s" (org-trim next)))
9640 (unless head
9641 (setq head (org-get-todo-sequence-head state)
9642 ass (assoc head org-todo-kwd-alist)
9643 interpret (nth 1 ass)
9644 done-word (nth 3 ass)
9645 final-done-word (nth 4 ass)))
9646 (when (memq arg '(nextset previousset))
9647 (message "Keyword-Set %d/%d: %s"
9648 (- (length org-todo-sets) -1
9649 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9650 (length org-todo-sets)
9651 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9652 (setq org-last-todo-state-is-todo
9653 (not (member state org-done-keywords)))
9654 (setq now-done-p (and (member state org-done-keywords)
9655 (not (member this org-done-keywords))))
9656 (and logging (org-local-logging logging))
9657 (when (and (or org-todo-log-states org-log-done)
9658 (not (eq org-inhibit-logging t))
9659 (not (memq arg '(nextset previousset))))
9660 ;; we need to look at recording a time and note
9661 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9662 (nth 2 (assoc this org-todo-log-states))))
9663 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9664 (setq dolog 'time))
9665 (when (and state
9666 (member state org-not-done-keywords)
9667 (not (member this org-not-done-keywords)))
9668 ;; This is now a todo state and was not one before
9669 ;; If there was a CLOSED time stamp, get rid of it.
9670 (org-add-planning-info nil nil 'closed))
9671 (when (and now-done-p org-log-done)
9672 ;; It is now done, and it was not done before
9673 (org-add-planning-info 'closed (org-current-time))
9674 (if (and (not dolog) (eq 'note org-log-done))
9675 (org-add-log-setup 'done state this 'findpos 'note)))
9676 (when (and state dolog)
9677 ;; This is a non-nil state, and we need to log it
9678 (org-add-log-setup 'state state this 'findpos dolog)))
9679 ;; Fixup tag positioning
9680 (org-todo-trigger-tag-changes state)
9681 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9682 (when org-provide-todo-statistics
9683 (org-update-parent-todo-statistics))
9684 (run-hooks 'org-after-todo-state-change-hook)
9685 (if (and arg (not (member state org-done-keywords)))
9686 (setq head (org-get-todo-sequence-head state)))
9687 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9688 ;; Do we need to trigger a repeat?
9689 (when now-done-p
9690 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9691 ;; This is for the agenda, take a snapshot of the headline.
9692 (save-match-data
9693 (setq org-agenda-headline-snapshot-before-repeat
9694 (org-get-heading))))
9695 (org-auto-repeat-maybe state))
9696 ;; Fixup cursor location if close to the keyword
9697 (if (and (outline-on-heading-p)
9698 (not (bolp))
9699 (save-excursion (beginning-of-line 1)
9700 (looking-at org-todo-line-regexp))
9701 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9702 (progn
9703 (goto-char (or (match-end 2) (match-end 1)))
9704 (and (looking-at " ") (just-one-space))))
9705 (when org-trigger-hook
9706 (save-excursion
9707 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9709 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9710 "Block turning an entry into a TODO, using the hierarchy.
9711 This checks whether the current task should be blocked from state
9712 changes. Such blocking occurs when:
9714 1. The task has children which are not all in a completed state.
9716 2. A task has a parent with the property :ORDERED:, and there
9717 are siblings prior to the current task with incomplete
9718 status.
9720 3. The parent of the task is blocked because it has siblings that should
9721 be done first, or is child of a block grandparent TODO entry."
9723 (catch 'dont-block
9724 ;; If this is not a todo state change, or if this entry is already DONE,
9725 ;; do not block
9726 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9727 (member (plist-get change-plist :from)
9728 (cons 'done org-done-keywords))
9729 (member (plist-get change-plist :to)
9730 (cons 'todo org-not-done-keywords)))
9731 (throw 'dont-block t))
9732 ;; If this task has children, and any are undone, it's blocked
9733 (save-excursion
9734 (org-back-to-heading t)
9735 (let ((this-level (funcall outline-level)))
9736 (outline-next-heading)
9737 (let ((child-level (funcall outline-level)))
9738 (while (and (not (eobp))
9739 (> child-level this-level))
9740 ;; this todo has children, check whether they are all
9741 ;; completed
9742 (if (and (not (org-entry-is-done-p))
9743 (org-entry-is-todo-p))
9744 (throw 'dont-block nil))
9745 (outline-next-heading)
9746 (setq child-level (funcall outline-level))))))
9747 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9748 ;; any previous siblings are undone, it's blocked
9749 (save-excursion
9750 (org-back-to-heading t)
9751 (let* ((pos (point))
9752 (parent-pos (and (org-up-heading-safe) (point))))
9753 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9754 (when (and (org-entry-get (point) "ORDERED")
9755 (forward-line 1)
9756 (re-search-forward org-not-done-heading-regexp pos t))
9757 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9758 ;; Search further up the hierarchy, to see if an anchestor is blocked
9759 (while t
9760 (goto-char parent-pos)
9761 (if (not (looking-at org-not-done-heading-regexp))
9762 (throw 'dont-block t)) ; do not block, parent is not a TODO
9763 (setq pos (point))
9764 (setq parent-pos (and (org-up-heading-safe) (point)))
9765 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9766 (when (and (org-entry-get (point) "ORDERED")
9767 (forward-line 1)
9768 (re-search-forward org-not-done-heading-regexp pos t))
9769 (throw 'dont-block nil))))))) ; block, older sibling not done.
9771 (defcustom org-track-ordered-property-with-tag nil
9772 "Should the ORDERED property also be shown as a tag?
9773 The ORDERED property decides if an entry should require subtasks to be
9774 completed in sequence. Since a property is not very visible, setting
9775 this option means that toggling the ORDERED property with the command
9776 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9777 not relevant for the behavior, but it makes things more visible.
9779 Note that toggling the tag with tags commands will not change the property
9780 and therefore not influence behavior!
9782 This can be t, meaning the tag ORDERED should be used, It can also be a
9783 string to select a different tag for this task."
9784 :group 'org-todo
9785 :type '(choice
9786 (const :tag "No tracking" nil)
9787 (const :tag "Track with ORDERED tag" t)
9788 (string :tag "Use other tag")))
9790 (defun org-toggle-ordered-property ()
9791 "Toggle the ORDERED property of the current entry.
9792 For better visibility, you can track the value of this property with a tag.
9793 See variable `org-track-ordered-property-with-tag'."
9794 (interactive)
9795 (let* ((t1 org-track-ordered-property-with-tag)
9796 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9797 (save-excursion
9798 (org-back-to-heading)
9799 (if (org-entry-get nil "ORDERED")
9800 (progn
9801 (org-delete-property "ORDERED")
9802 (and tag (org-toggle-tag tag 'off))
9803 (message "Subtasks can be completed in arbitrary order"))
9804 (org-entry-put nil "ORDERED" "t")
9805 (and tag (org-toggle-tag tag 'on))
9806 (message "Subtasks must be completed in sequence")))))
9808 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9809 (defun org-block-todo-from-checkboxes (change-plist)
9810 "Block turning an entry into a TODO, using checkboxes.
9811 This checks whether the current task should be blocked from state
9812 changes because there are uncheckd boxes in this entry."
9813 (catch 'dont-block
9814 ;; If this is not a todo state change, or if this entry is already DONE,
9815 ;; do not block
9816 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9817 (member (plist-get change-plist :from)
9818 (cons 'done org-done-keywords))
9819 (member (plist-get change-plist :to)
9820 (cons 'todo org-not-done-keywords)))
9821 (throw 'dont-block t))
9822 ;; If this task has checkboxes that are not checked, it's blocked
9823 (save-excursion
9824 (org-back-to-heading t)
9825 (let ((beg (point)) end)
9826 (outline-next-heading)
9827 (setq end (point))
9828 (goto-char beg)
9829 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9830 end t)
9831 (progn
9832 (if (boundp 'org-blocked-by-checkboxes)
9833 (setq org-blocked-by-checkboxes t))
9834 (throw 'dont-block nil)))))
9835 t)) ; do not block
9837 (defun org-update-statistics-cookies (all)
9838 "Update the statistics cookie, either from TODO or from checkboxes.
9839 This should be called with the cursor in a line with a statistics cookie."
9840 (interactive "P")
9841 (if all
9842 (progn
9843 (org-update-checkbox-count 'all)
9844 (org-map-entries 'org-update-parent-todo-statistics))
9845 (if (not (org-on-heading-p))
9846 (org-update-checkbox-count)
9847 (let ((pos (move-marker (make-marker) (point)))
9848 end l1 l2)
9849 (ignore-errors (org-back-to-heading t))
9850 (if (not (org-on-heading-p))
9851 (org-update-checkbox-count)
9852 (setq l1 (org-outline-level))
9853 (setq end (save-excursion
9854 (outline-next-heading)
9855 (if (org-on-heading-p) (setq l2 (org-outline-level)))
9856 (point)))
9857 (if (and (save-excursion (re-search-forward
9858 "^[ \t]*[-+*] \\[[- X]\\]" end t))
9859 (not (save-excursion (re-search-forward
9860 ":COOKIE_DATA:.*\\<todo\\>" end t))))
9861 (org-update-checkbox-count)
9862 (if (and l2 (> l2 l1))
9863 (progn
9864 (goto-char end)
9865 (org-update-parent-todo-statistics))
9866 (error "No data for statistics cookie"))))
9867 (goto-char pos)
9868 (move-marker pos nil)))))
9870 (defvar org-entry-property-inherited-from) ;; defined below
9871 (defun org-update-parent-todo-statistics ()
9872 "Update any statistics cookie in the parent of the current headline.
9873 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9874 the entire subtree and this will travel up the hierarchy and update
9875 statistics everywhere."
9876 (interactive)
9877 (let* ((lim 0) prop
9878 (recursive (or (not org-hierarchical-todo-statistics)
9879 (string-match
9880 "\\<recursive\\>"
9881 (or (setq prop (org-entry-get
9882 nil "COOKIE_DATA" 'inherit)) ""))))
9883 (lim (or (and prop (marker-position
9884 org-entry-property-inherited-from))
9885 lim))
9886 (first t)
9887 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9888 level ltoggle l1 new ndel
9889 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9890 (catch 'exit
9891 (save-excursion
9892 (beginning-of-line 1)
9893 (if (org-at-heading-p)
9894 (setq ltoggle (funcall outline-level))
9895 (error "This should not happen"))
9896 (while (and (setq level (org-up-heading-safe))
9897 (or recursive first)
9898 (>= (point) lim))
9899 (setq first nil)
9900 (unless (and level
9901 (not (string-match
9902 "\\<checkbox\\>"
9903 (downcase
9904 (or (org-entry-get
9905 nil "COOKIE_DATA")
9906 "")))))
9907 (throw 'exit nil))
9908 (while (re-search-forward box-re (point-at-eol) t)
9909 (setq cnt-all 0 cnt-done 0 cookie-present t)
9910 (setq is-percent (match-end 2))
9911 (save-match-data
9912 (unless (outline-next-heading) (throw 'exit nil))
9913 (while (and (looking-at org-complex-heading-regexp)
9914 (> (setq l1 (length (match-string 1))) level))
9915 (setq kwd (and (or recursive (= l1 ltoggle))
9916 (match-string 2)))
9917 (if (or (eq org-provide-todo-statistics 'all-headlines)
9918 (and (listp org-provide-todo-statistics)
9919 (or (member kwd org-provide-todo-statistics)
9920 (member kwd org-done-keywords))))
9921 (setq cnt-all (1+ cnt-all))
9922 (if (eq org-provide-todo-statistics t)
9923 (and kwd (setq cnt-all (1+ cnt-all)))))
9924 (and (member kwd org-done-keywords)
9925 (setq cnt-done (1+ cnt-done)))
9926 (outline-next-heading)))
9927 (setq new
9928 (if is-percent
9929 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9930 (format "[%d/%d]" cnt-done cnt-all))
9931 ndel (- (match-end 0) (match-beginning 0)))
9932 (goto-char (match-beginning 0))
9933 (insert new)
9934 (delete-region (point) (+ (point) ndel))))
9935 (when cookie-present
9936 (run-hook-with-args 'org-after-todo-statistics-hook
9937 cnt-done (- cnt-all cnt-done)))))
9938 (run-hooks 'org-todo-statistics-hook)))
9940 (defvar org-after-todo-statistics-hook nil
9941 "Hook that is called after a TODO statistics cookie has been updated.
9942 Each function is called with two arguments: the number of not-done entries
9943 and the number of done entries.
9945 For example, the following function, when added to this hook, will switch
9946 an entry to DONE when all children are done, and back to TODO when new
9947 entries are set to a TODO status. Note that this hook is only called
9948 when there is a statistics cookie in the headline!
9950 (defun org-summary-todo (n-done n-not-done)
9951 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9952 (let (org-log-done org-log-states) ; turn off logging
9953 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9956 (defvar org-todo-statistics-hook nil
9957 "Hook that is run whenever Org thinks TODO statistics should be updated.
9958 This hook runs even if there is no statisics cookie present, in which case
9959 `org-after-todo-statistics-hook' would not run.")
9961 (defun org-todo-trigger-tag-changes (state)
9962 "Apply the changes defined in `org-todo-state-tags-triggers'."
9963 (let ((l org-todo-state-tags-triggers)
9964 changes)
9965 (when (or (not state) (equal state ""))
9966 (setq changes (append changes (cdr (assoc "" l)))))
9967 (when (and (stringp state) (> (length state) 0))
9968 (setq changes (append changes (cdr (assoc state l)))))
9969 (when (member state org-not-done-keywords)
9970 (setq changes (append changes (cdr (assoc 'todo l)))))
9971 (when (member state org-done-keywords)
9972 (setq changes (append changes (cdr (assoc 'done l)))))
9973 (dolist (c changes)
9974 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9976 (defun org-local-logging (value)
9977 "Get logging settings from a property VALUE."
9978 (let* (words w a)
9979 ;; directly set the variables, they are already local.
9980 (setq org-log-done nil
9981 org-log-repeat nil
9982 org-todo-log-states nil)
9983 (setq words (org-split-string value))
9984 (while (setq w (pop words))
9985 (cond
9986 ((setq a (assoc w org-startup-options))
9987 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9988 (set (nth 1 a) (nth 2 a))))
9989 ((setq a (org-extract-log-state-settings w))
9990 (and (member (car a) org-todo-keywords-1)
9991 (push a org-todo-log-states)))))))
9993 (defun org-get-todo-sequence-head (kwd)
9994 "Return the head of the TODO sequence to which KWD belongs.
9995 If KWD is not set, check if there is a text property remembering the
9996 right sequence."
9997 (let (p)
9998 (cond
9999 ((not kwd)
10000 (or (get-text-property (point-at-bol) 'org-todo-head)
10001 (progn
10002 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10003 nil (point-at-eol)))
10004 (get-text-property p 'org-todo-head))))
10005 ((not (member kwd org-todo-keywords-1))
10006 (car org-todo-keywords-1))
10007 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10009 (defun org-fast-todo-selection ()
10010 "Fast TODO keyword selection with single keys.
10011 Returns the new TODO keyword, or nil if no state change should occur."
10012 (let* ((fulltable org-todo-key-alist)
10013 (done-keywords org-done-keywords) ;; needed for the faces.
10014 (maxlen (apply 'max (mapcar
10015 (lambda (x)
10016 (if (stringp (car x)) (string-width (car x)) 0))
10017 fulltable)))
10018 (expert nil)
10019 (fwidth (+ maxlen 3 1 3))
10020 (ncol (/ (- (window-width) 4) fwidth))
10021 tg cnt e c tbl
10022 groups ingroup)
10023 (save-excursion
10024 (save-window-excursion
10025 (if expert
10026 (set-buffer (get-buffer-create " *Org todo*"))
10027 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10028 (erase-buffer)
10029 (org-set-local 'org-done-keywords done-keywords)
10030 (setq tbl fulltable cnt 0)
10031 (while (setq e (pop tbl))
10032 (cond
10033 ((equal e '(:startgroup))
10034 (push '() groups) (setq ingroup t)
10035 (when (not (= cnt 0))
10036 (setq cnt 0)
10037 (insert "\n"))
10038 (insert "{ "))
10039 ((equal e '(:endgroup))
10040 (setq ingroup nil cnt 0)
10041 (insert "}\n"))
10042 ((equal e '(:newline))
10043 (when (not (= cnt 0))
10044 (setq cnt 0)
10045 (insert "\n")
10046 (setq e (car tbl))
10047 (while (equal (car tbl) '(:newline))
10048 (insert "\n")
10049 (setq tbl (cdr tbl)))))
10051 (setq tg (car e) c (cdr e))
10052 (if ingroup (push tg (car groups)))
10053 (setq tg (org-add-props tg nil 'face
10054 (org-get-todo-face tg)))
10055 (if (and (= cnt 0) (not ingroup)) (insert " "))
10056 (insert "[" c "] " tg (make-string
10057 (- fwidth 4 (length tg)) ?\ ))
10058 (when (= (setq cnt (1+ cnt)) ncol)
10059 (insert "\n")
10060 (if ingroup (insert " "))
10061 (setq cnt 0)))))
10062 (insert "\n")
10063 (goto-char (point-min))
10064 (if (not expert) (org-fit-window-to-buffer))
10065 (message "[a-z..]:Set [SPC]:clear")
10066 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10067 (cond
10068 ((or (= c ?\C-g)
10069 (and (= c ?q) (not (rassoc c fulltable))))
10070 (setq quit-flag t))
10071 ((= c ?\ ) nil)
10072 ((setq e (rassoc c fulltable) tg (car e))
10074 (t (setq quit-flag t)))))))
10076 (defun org-entry-is-todo-p ()
10077 (member (org-get-todo-state) org-not-done-keywords))
10079 (defun org-entry-is-done-p ()
10080 (member (org-get-todo-state) org-done-keywords))
10082 (defun org-get-todo-state ()
10083 (save-excursion
10084 (org-back-to-heading t)
10085 (and (looking-at org-todo-line-regexp)
10086 (match-end 2)
10087 (match-string 2))))
10089 (defun org-at-date-range-p (&optional inactive-ok)
10090 "Is the cursor inside a date range?"
10091 (interactive)
10092 (save-excursion
10093 (catch 'exit
10094 (let ((pos (point)))
10095 (skip-chars-backward "^[<\r\n")
10096 (skip-chars-backward "<[")
10097 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10098 (>= (match-end 0) pos)
10099 (throw 'exit t))
10100 (skip-chars-backward "^<[\r\n")
10101 (skip-chars-backward "<[")
10102 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10103 (>= (match-end 0) pos)
10104 (throw 'exit t)))
10105 nil)))
10107 (defun org-get-repeat (&optional tagline)
10108 "Check if there is a deadline/schedule with repeater in this entry."
10109 (save-match-data
10110 (save-excursion
10111 (org-back-to-heading t)
10112 (and (re-search-forward (if tagline
10113 (concat tagline "\\s-*" org-repeat-re)
10114 org-repeat-re)
10115 (org-entry-end-position) t)
10116 (match-string-no-properties 1)))))
10118 (defvar org-last-changed-timestamp)
10119 (defvar org-last-inserted-timestamp)
10120 (defvar org-log-post-message)
10121 (defvar org-log-note-purpose)
10122 (defvar org-log-note-how)
10123 (defvar org-log-note-extra)
10124 (defun org-auto-repeat-maybe (done-word)
10125 "Check if the current headline contains a repeated deadline/schedule.
10126 If yes, set TODO state back to what it was and change the base date
10127 of repeating deadline/scheduled time stamps to new date.
10128 This function is run automatically after each state change to a DONE state."
10129 ;; last-state is dynamically scoped into this function
10130 (let* ((repeat (org-get-repeat))
10131 (aa (assoc last-state org-todo-kwd-alist))
10132 (interpret (nth 1 aa))
10133 (head (nth 2 aa))
10134 (whata '(("d" . day) ("m" . month) ("y" . year)))
10135 (msg "Entry repeats: ")
10136 (org-log-done nil)
10137 (org-todo-log-states nil)
10138 (nshiftmax 10) (nshift 0)
10139 re type n what ts time)
10140 (when repeat
10141 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10142 (org-todo (if (eq interpret 'type) last-state head))
10143 (org-entry-put nil "LAST_REPEAT" (format-time-string
10144 (org-time-stamp-format t t)))
10145 (when org-log-repeat
10146 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10147 (memq 'org-add-log-note post-command-hook))
10148 ;; OK, we are already setup for some record
10149 (if (eq org-log-repeat 'note)
10150 ;; make sure we take a note, not only a time stamp
10151 (setq org-log-note-how 'note))
10152 ;; Set up for taking a record
10153 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10154 last-state
10155 'findpos org-log-repeat)))
10156 (org-back-to-heading t)
10157 (org-add-planning-info nil nil 'closed)
10158 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10159 org-deadline-time-regexp "\\)\\|\\("
10160 org-ts-regexp "\\)"))
10161 (while (re-search-forward
10162 re (save-excursion (outline-next-heading) (point)) t)
10163 (setq type (if (match-end 1) org-scheduled-string
10164 (if (match-end 3) org-deadline-string "Plain:"))
10165 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10166 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10167 (setq n (string-to-number (match-string 2 ts))
10168 what (match-string 3 ts))
10169 (if (equal what "w") (setq n (* n 7) what "d"))
10170 ;; Preparation, see if we need to modify the start date for the change
10171 (when (match-end 1)
10172 (setq time (save-match-data (org-time-string-to-time ts)))
10173 (cond
10174 ((equal (match-string 1 ts) ".")
10175 ;; Shift starting date to today
10176 (org-timestamp-change
10177 (- (time-to-days (current-time)) (time-to-days time))
10178 'day))
10179 ((equal (match-string 1 ts) "+")
10180 (while (or (= nshift 0)
10181 (<= (time-to-days time) (time-to-days (current-time))))
10182 (when (= (incf nshift) nshiftmax)
10183 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10184 (error "Abort")))
10185 (org-timestamp-change n (cdr (assoc what whata)))
10186 (org-at-timestamp-p t)
10187 (setq ts (match-string 1))
10188 (setq time (save-match-data (org-time-string-to-time ts))))
10189 (org-timestamp-change (- n) (cdr (assoc what whata)))
10190 ;; rematch, so that we have everything in place for the real shift
10191 (org-at-timestamp-p t)
10192 (setq ts (match-string 1))
10193 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10194 (org-timestamp-change n (cdr (assoc what whata)))
10195 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10196 (setq org-log-post-message msg)
10197 (message "%s" msg))))
10199 (defun org-show-todo-tree (arg)
10200 "Make a compact tree which shows all headlines marked with TODO.
10201 The tree will show the lines where the regexp matches, and all higher
10202 headlines above the match.
10203 With a \\[universal-argument] prefix, prompt for a regexp to match.
10204 With a numeric prefix N, construct a sparse tree for the Nth element
10205 of `org-todo-keywords-1'."
10206 (interactive "P")
10207 (let ((case-fold-search nil)
10208 (kwd-re
10209 (cond ((null arg) org-not-done-regexp)
10210 ((equal arg '(4))
10211 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10212 (mapcar 'list org-todo-keywords-1))))
10213 (concat "\\("
10214 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10215 "\\)\\>")))
10216 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10217 (regexp-quote (nth (1- (prefix-numeric-value arg))
10218 org-todo-keywords-1)))
10219 (t (error "Invalid prefix argument: %s" arg)))))
10220 (message "%d TODO entries found"
10221 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10223 (defun org-deadline (&optional remove time)
10224 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10225 With argument REMOVE, remove any deadline from the item.
10226 When TIME is set, it should be an internal time specification, and the
10227 scheduling will use the corresponding date."
10228 (interactive "P")
10229 (if remove
10230 (progn
10231 (org-remove-timestamp-with-keyword org-deadline-string)
10232 (message "Item no longer has a deadline."))
10233 (if (org-get-repeat)
10234 (error "Cannot change deadline on task with repeater, please do that by hand")
10235 (org-add-planning-info 'deadline time 'closed)
10236 (message "Deadline on %s" org-last-inserted-timestamp))))
10238 (defun org-schedule (&optional remove time)
10239 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10240 With argument REMOVE, remove any scheduling date from the item.
10241 When TIME is set, it should be an internal time specification, and the
10242 scheduling will use the corresponding date."
10243 (interactive "P")
10244 (if remove
10245 (progn
10246 (org-remove-timestamp-with-keyword org-scheduled-string)
10247 (message "Item is no longer scheduled."))
10248 (if (org-get-repeat)
10249 (error "Cannot reschedule task with repeater, please do that by hand")
10250 (org-add-planning-info 'scheduled time 'closed)
10251 (message "Scheduled to %s" org-last-inserted-timestamp))))
10253 (defun org-get-scheduled-time (pom &optional inherit)
10254 "Get the scheduled time as a time tuple, of a format suitable
10255 for calling org-schedule with, or if there is no scheduling,
10256 returns nil."
10257 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10258 (when time
10259 (apply 'encode-time (org-parse-time-string time)))))
10261 (defun org-get-deadline-time (pom &optional inherit)
10262 "Get the deadine as a time tuple, of a format suitable for
10263 calling org-deadlin with, or if there is no scheduling, returns
10264 nil."
10265 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10266 (when time
10267 (apply 'encode-time (org-parse-time-string time)))))
10269 (defun org-remove-timestamp-with-keyword (keyword)
10270 "Remove all time stamps with KEYWORD in the current entry."
10271 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10272 beg)
10273 (save-excursion
10274 (org-back-to-heading t)
10275 (setq beg (point))
10276 (outline-next-heading)
10277 (while (re-search-backward re beg t)
10278 (replace-match "")
10279 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10280 (equal (char-before) ?\ ))
10281 (backward-delete-char 1)
10282 (if (string-match "^[ \t]*$" (buffer-substring
10283 (point-at-bol) (point-at-eol)))
10284 (delete-region (point-at-bol)
10285 (min (point-max) (1+ (point-at-eol))))))))))
10287 (defun org-add-planning-info (what &optional time &rest remove)
10288 "Insert new timestamp with keyword in the line directly after the headline.
10289 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10290 If non is given, the user is prompted for a date.
10291 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10292 be removed."
10293 (interactive)
10294 (let (org-time-was-given org-end-time-was-given ts
10295 end default-time default-input)
10297 (catch 'exit
10298 (when (and (not time) (memq what '(scheduled deadline)))
10299 ;; Try to get a default date/time from existing timestamp
10300 (save-excursion
10301 (org-back-to-heading t)
10302 (setq end (save-excursion (outline-next-heading) (point)))
10303 (when (re-search-forward (if (eq what 'scheduled)
10304 org-scheduled-time-regexp
10305 org-deadline-time-regexp)
10306 end t)
10307 (setq ts (match-string 1)
10308 default-time
10309 (apply 'encode-time (org-parse-time-string ts))
10310 default-input (and ts (org-get-compact-tod ts))))))
10311 (when what
10312 ;; If necessary, get the time from the user
10313 (setq time (or time (org-read-date nil 'to-time nil nil
10314 default-time default-input))))
10316 (when (and org-insert-labeled-timestamps-at-point
10317 (member what '(scheduled deadline)))
10318 (insert
10319 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10320 (org-insert-time-stamp time org-time-was-given
10321 nil nil nil (list org-end-time-was-given))
10322 (setq what nil))
10323 (save-excursion
10324 (save-restriction
10325 (let (col list elt ts buffer-invisibility-spec)
10326 (org-back-to-heading t)
10327 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10328 (goto-char (match-end 1))
10329 (setq col (current-column))
10330 (goto-char (match-end 0))
10331 (if (eobp) (insert "\n") (forward-char 1))
10332 (when (and (not what)
10333 (not (looking-at
10334 (concat "[ \t]*"
10335 org-keyword-time-not-clock-regexp))))
10336 ;; Nothing to add, nothing to remove...... :-)
10337 (throw 'exit nil))
10338 (if (and (not (looking-at outline-regexp))
10339 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10340 "[^\r\n]*"))
10341 (not (equal (match-string 1) org-clock-string)))
10342 (narrow-to-region (match-beginning 0) (match-end 0))
10343 (insert-before-markers "\n")
10344 (backward-char 1)
10345 (narrow-to-region (point) (point))
10346 (and org-adapt-indentation (org-indent-to-column col)))
10347 ;; Check if we have to remove something.
10348 (setq list (cons what remove))
10349 (while list
10350 (setq elt (pop list))
10351 (goto-char (point-min))
10352 (when (or (and (eq elt 'scheduled)
10353 (re-search-forward org-scheduled-time-regexp nil t))
10354 (and (eq elt 'deadline)
10355 (re-search-forward org-deadline-time-regexp nil t))
10356 (and (eq elt 'closed)
10357 (re-search-forward org-closed-time-regexp nil t)))
10358 (replace-match "")
10359 (if (looking-at "--+<[^>]+>") (replace-match ""))
10360 (skip-chars-backward " ")
10361 (if (looking-at " +") (replace-match ""))))
10362 (goto-char (point-max))
10363 (and org-adapt-indentation (bolp) (org-indent-to-column col))
10364 (when what
10365 (insert
10366 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10367 (cond ((eq what 'scheduled) org-scheduled-string)
10368 ((eq what 'deadline) org-deadline-string)
10369 ((eq what 'closed) org-closed-string))
10370 " ")
10371 (setq ts (org-insert-time-stamp
10372 time
10373 (or org-time-was-given
10374 (and (eq what 'closed) org-log-done-with-time))
10375 (eq what 'closed)
10376 nil nil (list org-end-time-was-given)))
10377 (end-of-line 1))
10378 (goto-char (point-min))
10379 (widen)
10380 (if (and (looking-at "[ \t]+\n")
10381 (equal (char-before) ?\n))
10382 (delete-region (1- (point)) (point-at-eol)))
10383 ts))))))
10385 (defvar org-log-note-marker (make-marker))
10386 (defvar org-log-note-purpose nil)
10387 (defvar org-log-note-state nil)
10388 (defvar org-log-note-previous-state nil)
10389 (defvar org-log-note-how nil)
10390 (defvar org-log-note-extra nil)
10391 (defvar org-log-note-window-configuration nil)
10392 (defvar org-log-note-return-to (make-marker))
10393 (defvar org-log-post-message nil
10394 "Message to be displayed after a log note has been stored.
10395 The auto-repeater uses this.")
10397 (defun org-add-note ()
10398 "Add a note to the current entry.
10399 This is done in the same way as adding a state change note."
10400 (interactive)
10401 (org-add-log-setup 'note nil nil 'findpos nil))
10403 (defvar org-property-end-re)
10404 (defun org-add-log-setup (&optional purpose state prev-state
10405 findpos how &optional extra)
10406 "Set up the post command hook to take a note.
10407 If this is about to TODO state change, the new state is expected in STATE.
10408 When FINDPOS is non-nil, find the correct position for the note in
10409 the current entry. If not, assume that it can be inserted at point.
10410 HOW is an indicator what kind of note should be created.
10411 EXTRA is additional text that will be inserted into the notes buffer."
10412 (let* ((org-log-into-drawer (org-log-into-drawer))
10413 (drawer (cond ((stringp org-log-into-drawer)
10414 org-log-into-drawer)
10415 (org-log-into-drawer "LOGBOOK")
10416 (t nil))))
10417 (save-restriction
10418 (save-excursion
10419 (when findpos
10420 (org-back-to-heading t)
10421 (narrow-to-region (point) (save-excursion
10422 (outline-next-heading) (point)))
10423 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10424 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10425 "[^\r\n]*\\)?"))
10426 (goto-char (match-end 0))
10427 (cond
10428 (drawer
10429 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10430 nil t)
10431 (progn
10432 (goto-char (match-end 0))
10433 (or org-log-states-order-reversed
10434 (and (re-search-forward org-property-end-re nil t)
10435 (goto-char (1- (match-beginning 0))))))
10436 (insert "\n:" drawer ":\n:END:")
10437 (beginning-of-line 0)
10438 (org-indent-line-function)
10439 (beginning-of-line 2)
10440 (org-indent-line-function)
10441 (end-of-line 0)))
10442 ((and org-log-state-notes-insert-after-drawers
10443 (save-excursion
10444 (forward-line) (looking-at org-drawer-regexp)))
10445 (forward-line)
10446 (while (looking-at org-drawer-regexp)
10447 (goto-char (match-end 0))
10448 (re-search-forward org-property-end-re (point-max) t)
10449 (forward-line))
10450 (forward-line -1)))
10451 (unless org-log-states-order-reversed
10452 (and (= (char-after) ?\n) (forward-char 1))
10453 (org-skip-over-state-notes)
10454 (skip-chars-backward " \t\n\r")))
10455 (move-marker org-log-note-marker (point))
10456 (setq org-log-note-purpose purpose
10457 org-log-note-state state
10458 org-log-note-previous-state prev-state
10459 org-log-note-how how
10460 org-log-note-extra extra)
10461 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10463 (defun org-skip-over-state-notes ()
10464 "Skip past the list of State notes in an entry."
10465 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10466 (while (looking-at "[ \t]*- State")
10467 (condition-case nil
10468 (org-next-item)
10469 (error (org-end-of-item)))))
10471 (defun org-add-log-note (&optional purpose)
10472 "Pop up a window for taking a note, and add this note later at point."
10473 (remove-hook 'post-command-hook 'org-add-log-note)
10474 (setq org-log-note-window-configuration (current-window-configuration))
10475 (delete-other-windows)
10476 (move-marker org-log-note-return-to (point))
10477 (switch-to-buffer (marker-buffer org-log-note-marker))
10478 (goto-char org-log-note-marker)
10479 (org-switch-to-buffer-other-window "*Org Note*")
10480 (erase-buffer)
10481 (if (memq org-log-note-how '(time state))
10482 (let (current-prefix-arg) (org-store-log-note))
10483 (let ((org-inhibit-startup t)) (org-mode))
10484 (insert (format "# Insert note for %s.
10485 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10486 (cond
10487 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10488 ((eq org-log-note-purpose 'done) "closed todo item")
10489 ((eq org-log-note-purpose 'state)
10490 (format "state change from \"%s\" to \"%s\""
10491 (or org-log-note-previous-state "")
10492 (or org-log-note-state "")))
10493 ((eq org-log-note-purpose 'note)
10494 "this entry")
10495 (t (error "This should not happen")))))
10496 (if org-log-note-extra (insert org-log-note-extra))
10497 (org-set-local 'org-finish-function 'org-store-log-note)))
10499 (defvar org-note-abort nil) ; dynamically scoped
10500 (defun org-store-log-note ()
10501 "Finish taking a log note, and insert it to where it belongs."
10502 (let ((txt (buffer-string))
10503 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10504 lines ind)
10505 (kill-buffer (current-buffer))
10506 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10507 (setq txt (replace-match "" t t txt)))
10508 (if (string-match "\\s-+\\'" txt)
10509 (setq txt (replace-match "" t t txt)))
10510 (setq lines (org-split-string txt "\n"))
10511 (when (and note (string-match "\\S-" note))
10512 (setq note
10513 (org-replace-escapes
10514 note
10515 (list (cons "%u" (user-login-name))
10516 (cons "%U" user-full-name)
10517 (cons "%t" (format-time-string
10518 (org-time-stamp-format 'long 'inactive)
10519 (current-time)))
10520 (cons "%s" (if org-log-note-state
10521 (concat "\"" org-log-note-state "\"")
10522 ""))
10523 (cons "%S" (if org-log-note-previous-state
10524 (concat "\"" org-log-note-previous-state "\"")
10525 "\"\"")))))
10526 (if lines (setq note (concat note " \\\\")))
10527 (push note lines))
10528 (when (or current-prefix-arg org-note-abort)
10529 (when org-log-into-drawer
10530 (org-remove-empty-drawer-at
10531 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10532 org-log-note-marker))
10533 (setq lines nil))
10534 (when lines
10535 (save-excursion
10536 (set-buffer (marker-buffer org-log-note-marker))
10537 (save-excursion
10538 (goto-char org-log-note-marker)
10539 (move-marker org-log-note-marker nil)
10540 (end-of-line 1)
10541 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10542 (insert "- " (pop lines))
10543 (org-indent-line-function)
10544 (beginning-of-line 1)
10545 (looking-at "[ \t]*")
10546 (setq ind (concat (match-string 0) " "))
10547 (end-of-line 1)
10548 (while lines (insert "\n" ind (pop lines)))
10549 (message "Note stored")
10550 (org-back-to-heading t)
10551 (org-cycle-hide-drawers 'children)))))
10552 (set-window-configuration org-log-note-window-configuration)
10553 (with-current-buffer (marker-buffer org-log-note-return-to)
10554 (goto-char org-log-note-return-to))
10555 (move-marker org-log-note-return-to nil)
10556 (and org-log-post-message (message "%s" org-log-post-message)))
10558 (defun org-remove-empty-drawer-at (drawer pos)
10559 "Remove an emptyr DARWER drawer at position POS.
10560 POS may also be a marker."
10561 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10562 (save-excursion
10563 (save-restriction
10564 (widen)
10565 (goto-char pos)
10566 (if (org-in-regexp
10567 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10568 (replace-match ""))))))
10570 (defun org-sparse-tree (&optional arg)
10571 "Create a sparse tree, prompt for the details.
10572 This command can create sparse trees. You first need to select the type
10573 of match used to create the tree:
10575 t Show entries with a specific TODO keyword.
10576 m Show entries selected by a tags/property match.
10577 p Enter a property name and its value (both with completion on existing
10578 names/values) and show entries with that property.
10579 r Show entries matching a regular expression.
10580 d Show deadlines due within `org-deadline-warning-days'.
10581 b Show deadlines and scheduled items before a date.
10582 a Show deadlines and scheduled items after a date."
10583 (interactive "P")
10584 (let (ans kwd value)
10585 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10586 (setq ans (read-char-exclusive))
10587 (cond
10588 ((equal ans ?d)
10589 (call-interactively 'org-check-deadlines))
10590 ((equal ans ?b)
10591 (call-interactively 'org-check-before-date))
10592 ((equal ans ?a)
10593 (call-interactively 'org-check-after-date))
10594 ((equal ans ?t)
10595 (org-show-todo-tree '(4)))
10596 ((member ans '(?T ?m))
10597 (call-interactively 'org-match-sparse-tree))
10598 ((member ans '(?p ?P))
10599 (setq kwd (org-icompleting-read "Property: "
10600 (mapcar 'list (org-buffer-property-keys))))
10601 (setq value (org-icompleting-read "Value: "
10602 (mapcar 'list (org-property-values kwd))))
10603 (unless (string-match "\\`{.*}\\'" value)
10604 (setq value (concat "\"" value "\"")))
10605 (org-match-sparse-tree arg (concat kwd "=" value)))
10606 ((member ans '(?r ?R ?/))
10607 (call-interactively 'org-occur))
10608 (t (error "No such sparse tree command \"%c\"" ans)))))
10610 (defvar org-occur-highlights nil
10611 "List of overlays used for occur matches.")
10612 (make-variable-buffer-local 'org-occur-highlights)
10613 (defvar org-occur-parameters nil
10614 "Parameters of the active org-occur calls.
10615 This is a list, each call to org-occur pushes as cons cell,
10616 containing the regular expression and the callback, onto the list.
10617 The list can contain several entries if `org-occur' has been called
10618 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10619 will only contain one set of parameters. When the highlights are
10620 removed (for example with `C-c C-c', or with the next edit (depending
10621 on `org-remove-highlights-with-change'), this variable is emptied
10622 as well.")
10623 (make-variable-buffer-local 'org-occur-parameters)
10625 (defun org-occur (regexp &optional keep-previous callback)
10626 "Make a compact tree which shows all matches of REGEXP.
10627 The tree will show the lines where the regexp matches, and all higher
10628 headlines above the match. It will also show the heading after the match,
10629 to make sure editing the matching entry is easy.
10630 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10631 call to `org-occur' will be kept, to allow stacking of calls to this
10632 command.
10633 If CALLBACK is non-nil, it is a function which is called to confirm
10634 that the match should indeed be shown."
10635 (interactive "sRegexp: \nP")
10636 (when (equal regexp "")
10637 (error "Regexp cannot be empty"))
10638 (unless keep-previous
10639 (org-remove-occur-highlights nil nil t))
10640 (push (cons regexp callback) org-occur-parameters)
10641 (let ((cnt 0))
10642 (save-excursion
10643 (goto-char (point-min))
10644 (if (or (not keep-previous) ; do not want to keep
10645 (not org-occur-highlights)) ; no previous matches
10646 ;; hide everything
10647 (org-overview))
10648 (while (re-search-forward regexp nil t)
10649 (when (or (not callback)
10650 (save-match-data (funcall callback)))
10651 (setq cnt (1+ cnt))
10652 (when org-highlight-sparse-tree-matches
10653 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10654 (org-show-context 'occur-tree))))
10655 (when org-remove-highlights-with-change
10656 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10657 nil 'local))
10658 (unless org-sparse-tree-open-archived-trees
10659 (org-hide-archived-subtrees (point-min) (point-max)))
10660 (run-hooks 'org-occur-hook)
10661 (if (interactive-p)
10662 (message "%d match(es) for regexp %s" cnt regexp))
10663 cnt))
10665 (defun org-show-context (&optional key)
10666 "Make sure point and context and visible.
10667 How much context is shown depends upon the variables
10668 `org-show-hierarchy-above', `org-show-following-heading'. and
10669 `org-show-siblings'."
10670 (let ((heading-p (org-on-heading-p t))
10671 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10672 (following-p (org-get-alist-option org-show-following-heading key))
10673 (entry-p (org-get-alist-option org-show-entry-below key))
10674 (siblings-p (org-get-alist-option org-show-siblings key)))
10675 (catch 'exit
10676 ;; Show heading or entry text
10677 (if (and heading-p (not entry-p))
10678 (org-flag-heading nil) ; only show the heading
10679 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10680 (org-show-hidden-entry))) ; show entire entry
10681 (when following-p
10682 ;; Show next sibling, or heading below text
10683 (save-excursion
10684 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10685 (org-flag-heading nil))))
10686 (when siblings-p (org-show-siblings))
10687 (when hierarchy-p
10688 ;; show all higher headings, possibly with siblings
10689 (save-excursion
10690 (while (and (condition-case nil
10691 (progn (org-up-heading-all 1) t)
10692 (error nil))
10693 (not (bobp)))
10694 (org-flag-heading nil)
10695 (when siblings-p (org-show-siblings))))))))
10697 (defun org-reveal (&optional siblings)
10698 "Show current entry, hierarchy above it, and the following headline.
10699 This can be used to show a consistent set of context around locations
10700 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10701 not t for the search context.
10703 With optional argument SIBLINGS, on each level of the hierarchy all
10704 siblings are shown. This repairs the tree structure to what it would
10705 look like when opened with hierarchical calls to `org-cycle'."
10706 (interactive "P")
10707 (let ((org-show-hierarchy-above t)
10708 (org-show-following-heading t)
10709 (org-show-siblings (if siblings t org-show-siblings)))
10710 (org-show-context nil)))
10712 (defun org-highlight-new-match (beg end)
10713 "Highlight from BEG to END and mark the highlight is an occur headline."
10714 (let ((ov (org-make-overlay beg end)))
10715 (org-overlay-put ov 'face 'secondary-selection)
10716 (push ov org-occur-highlights)))
10718 (defun org-remove-occur-highlights (&optional beg end noremove)
10719 "Remove the occur highlights from the buffer.
10720 BEG and END are ignored. If NOREMOVE is nil, remove this function
10721 from the `before-change-functions' in the current buffer."
10722 (interactive)
10723 (unless org-inhibit-highlight-removal
10724 (mapc 'org-delete-overlay org-occur-highlights)
10725 (setq org-occur-highlights nil)
10726 (setq org-occur-parameters nil)
10727 (unless noremove
10728 (remove-hook 'before-change-functions
10729 'org-remove-occur-highlights 'local))))
10731 ;;;; Priorities
10733 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10734 "Regular expression matching the priority indicator.")
10736 (defvar org-remove-priority-next-time nil)
10738 (defun org-priority-up ()
10739 "Increase the priority of the current item."
10740 (interactive)
10741 (org-priority 'up))
10743 (defun org-priority-down ()
10744 "Decrease the priority of the current item."
10745 (interactive)
10746 (org-priority 'down))
10748 (defun org-priority (&optional action)
10749 "Change the priority of an item by ARG.
10750 ACTION can be `set', `up', `down', or a character."
10751 (interactive)
10752 (unless org-enable-priority-commands
10753 (error "Priority commands are disabled"))
10754 (setq action (or action 'set))
10755 (let (current new news have remove)
10756 (save-excursion
10757 (org-back-to-heading t)
10758 (if (looking-at org-priority-regexp)
10759 (setq current (string-to-char (match-string 2))
10760 have t)
10761 (setq current org-default-priority))
10762 (cond
10763 ((or (eq action 'set)
10764 (if (featurep 'xemacs) (characterp action) (integerp action)))
10765 (if (not (eq action 'set))
10766 (setq new action)
10767 (message "Priority %c-%c, SPC to remove: "
10768 org-highest-priority org-lowest-priority)
10769 (setq new (read-char-exclusive)))
10770 (if (and (= (upcase org-highest-priority) org-highest-priority)
10771 (= (upcase org-lowest-priority) org-lowest-priority))
10772 (setq new (upcase new)))
10773 (cond ((equal new ?\ ) (setq remove t))
10774 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10775 (error "Priority must be between `%c' and `%c'"
10776 org-highest-priority org-lowest-priority))))
10777 ((eq action 'up)
10778 (if (and (not have) (eq last-command this-command))
10779 (setq new org-lowest-priority)
10780 (setq new (if (and org-priority-start-cycle-with-default (not have))
10781 org-default-priority (1- current)))))
10782 ((eq action 'down)
10783 (if (and (not have) (eq last-command this-command))
10784 (setq new org-highest-priority)
10785 (setq new (if (and org-priority-start-cycle-with-default (not have))
10786 org-default-priority (1+ current)))))
10787 (t (error "Invalid action")))
10788 (if (or (< (upcase new) org-highest-priority)
10789 (> (upcase new) org-lowest-priority))
10790 (setq remove t))
10791 (setq news (format "%c" new))
10792 (if have
10793 (if remove
10794 (replace-match "" t t nil 1)
10795 (replace-match news t t nil 2))
10796 (if remove
10797 (error "No priority cookie found in line")
10798 (let ((case-fold-search nil))
10799 (looking-at org-todo-line-regexp))
10800 (if (match-end 2)
10801 (progn
10802 (goto-char (match-end 2))
10803 (insert " [#" news "]"))
10804 (goto-char (match-beginning 3))
10805 (insert "[#" news "] "))))
10806 (org-preserve-lc (org-set-tags nil 'align)))
10807 (if remove
10808 (message "Priority removed")
10809 (message "Priority of current item set to %s" news))))
10811 (defun org-get-priority (s)
10812 "Find priority cookie and return priority."
10813 (save-match-data
10814 (if (not (string-match org-priority-regexp s))
10815 (* 1000 (- org-lowest-priority org-default-priority))
10816 (* 1000 (- org-lowest-priority
10817 (string-to-char (match-string 2 s)))))))
10819 ;;;; Tags
10821 (defvar org-agenda-archives-mode)
10822 (defvar org-map-continue-from nil
10823 "Position from where mapping should continue.
10824 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10826 (defvar org-scanner-tags nil
10827 "The current tag list while the tags scanner is running.")
10828 (defvar org-trust-scanner-tags nil
10829 "Should `org-get-tags-at' use the tags fro the scanner.
10830 This is for internal dynamical scoping only.
10831 When this is non-nil, the function `org-get-tags-at' will return the value
10832 of `org-scanner-tags' instead of building the list by itself. This
10833 can lead to large speed-ups when the tags scanner is used in a file with
10834 many entries, and when the list of tags is retrieved, for example to
10835 obtain a list of properties. Building the tags list for each entry in such
10836 a file becomes an N^2 operation - but with this variable set, it scales
10837 as N.")
10839 (defun org-scan-tags (action matcher &optional todo-only)
10840 "Scan headline tags with inheritance and produce output ACTION.
10842 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10843 or `agenda' to produce an entry list for an agenda view. It can also be
10844 a Lisp form or a function that should be called at each matched headline, in
10845 this case the return value is a list of all return values from these calls.
10847 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10848 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10849 only lines with a TODO keyword are included in the output."
10850 (require 'org-agenda)
10851 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10852 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10853 (org-re
10854 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10855 (props (list 'face 'default
10856 'done-face 'org-agenda-done
10857 'undone-face 'default
10858 'mouse-face 'highlight
10859 'org-not-done-regexp org-not-done-regexp
10860 'org-todo-regexp org-todo-regexp
10861 'keymap org-agenda-keymap
10862 'help-echo
10863 (format "mouse-2 or RET jump to org file %s"
10864 (abbreviate-file-name
10865 (or (buffer-file-name (buffer-base-buffer))
10866 (buffer-name (buffer-base-buffer)))))))
10867 (case-fold-search nil)
10868 (org-map-continue-from nil)
10869 lspos tags tags-list
10870 (tags-alist (list (cons 0 org-file-tags)))
10871 (llast 0) rtn rtn1 level category i txt
10872 todo marker entry priority)
10873 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10874 (setq action (list 'lambda nil action)))
10875 (save-excursion
10876 (goto-char (point-min))
10877 (when (eq action 'sparse-tree)
10878 (org-overview)
10879 (org-remove-occur-highlights))
10880 (while (re-search-forward re nil t)
10881 (catch :skip
10882 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10883 tags (if (match-end 4) (org-match-string-no-properties 4)))
10884 (goto-char (setq lspos (match-beginning 0)))
10885 (setq level (org-reduced-level (funcall outline-level))
10886 category (org-get-category))
10887 (setq i llast llast level)
10888 ;; remove tag lists from same and sublevels
10889 (while (>= i level)
10890 (when (setq entry (assoc i tags-alist))
10891 (setq tags-alist (delete entry tags-alist)))
10892 (setq i (1- i)))
10893 ;; add the next tags
10894 (when tags
10895 (setq tags (org-split-string tags ":")
10896 tags-alist
10897 (cons (cons level tags) tags-alist)))
10898 ;; compile tags for current headline
10899 (setq tags-list
10900 (if org-use-tag-inheritance
10901 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10902 tags)
10903 org-scanner-tags tags-list)
10904 (when org-use-tag-inheritance
10905 (setcdr (car tags-alist)
10906 (mapcar (lambda (x)
10907 (setq x (copy-sequence x))
10908 (org-add-prop-inherited x))
10909 (cdar tags-alist))))
10910 (when (and tags org-use-tag-inheritance
10911 (or (not (eq t org-use-tag-inheritance))
10912 org-tags-exclude-from-inheritance))
10913 ;; selective inheritance, remove uninherited ones
10914 (setcdr (car tags-alist)
10915 (org-remove-uniherited-tags (cdar tags-alist))))
10916 (when (and (or (not todo-only)
10917 (and (member todo org-not-done-keywords)
10918 (or (not org-agenda-tags-todo-honor-ignore-options)
10919 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10920 (let ((case-fold-search t)) (eval matcher))
10922 (not (member org-archive-tag tags-list))
10923 ;; we have an archive tag, should we use this anyway?
10924 (or (not org-agenda-skip-archived-trees)
10925 (and (eq action 'agenda) org-agenda-archives-mode))))
10926 (unless (eq action 'sparse-tree) (org-agenda-skip))
10928 ;; select this headline
10930 (cond
10931 ((eq action 'sparse-tree)
10932 (and org-highlight-sparse-tree-matches
10933 (org-get-heading) (match-end 0)
10934 (org-highlight-new-match
10935 (match-beginning 0) (match-beginning 1)))
10936 (org-show-context 'tags-tree))
10937 ((eq action 'agenda)
10938 (setq txt (org-format-agenda-item
10940 (concat
10941 (if (eq org-tags-match-list-sublevels 'indented)
10942 (make-string (1- level) ?.) "")
10943 (org-get-heading))
10944 category
10945 tags-list
10947 priority (org-get-priority txt))
10948 (goto-char lspos)
10949 (setq marker (org-agenda-new-marker))
10950 (org-add-props txt props
10951 'org-marker marker 'org-hd-marker marker 'org-category category
10952 'todo-state todo
10953 'priority priority 'type "tagsmatch")
10954 (push txt rtn))
10955 ((functionp action)
10956 (setq org-map-continue-from nil)
10957 (save-excursion
10958 (setq rtn1 (funcall action))
10959 (push rtn1 rtn)))
10960 (t (error "Invalid action")))
10962 ;; if we are to skip sublevels, jump to end of subtree
10963 (unless org-tags-match-list-sublevels
10964 (org-end-of-subtree t)
10965 (backward-char 1))))
10966 ;; Get the correct position from where to continue
10967 (if org-map-continue-from
10968 (goto-char org-map-continue-from)
10969 (and (= (point) lspos) (end-of-line 1)))))
10970 (when (and (eq action 'sparse-tree)
10971 (not org-sparse-tree-open-archived-trees))
10972 (org-hide-archived-subtrees (point-min) (point-max)))
10973 (nreverse rtn)))
10975 (defun org-remove-uniherited-tags (tags)
10976 "Remove all tags that are not inherited from the list TAGS."
10977 (cond
10978 ((eq org-use-tag-inheritance t)
10979 (if org-tags-exclude-from-inheritance
10980 (org-delete-all org-tags-exclude-from-inheritance tags)
10981 tags))
10982 ((not org-use-tag-inheritance) nil)
10983 ((stringp org-use-tag-inheritance)
10984 (delq nil (mapcar
10985 (lambda (x)
10986 (if (and (string-match org-use-tag-inheritance x)
10987 (not (member x org-tags-exclude-from-inheritance)))
10988 x nil))
10989 tags)))
10990 ((listp org-use-tag-inheritance)
10991 (delq nil (mapcar
10992 (lambda (x)
10993 (if (member x org-use-tag-inheritance) x nil))
10994 tags)))))
10996 (defvar todo-only) ;; dynamically scoped
10998 (defun org-match-sparse-tree (&optional todo-only match)
10999 "Create a sparse tree according to tags string MATCH.
11000 MATCH can contain positive and negative selection of tags, like
11001 \"+WORK+URGENT-WITHBOSS\".
11002 If optional argument TODO-ONLY is non-nil, only select lines that are
11003 also TODO lines."
11004 (interactive "P")
11005 (org-prepare-agenda-buffers (list (current-buffer)))
11006 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11008 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11010 (defvar org-cached-props nil)
11011 (defun org-cached-entry-get (pom property)
11012 (if (or (eq t org-use-property-inheritance)
11013 (and (stringp org-use-property-inheritance)
11014 (string-match org-use-property-inheritance property))
11015 (and (listp org-use-property-inheritance)
11016 (member property org-use-property-inheritance)))
11017 ;; Caching is not possible, check it directly
11018 (org-entry-get pom property 'inherit)
11019 ;; Get all properties, so that we can do complicated checks easily
11020 (cdr (assoc property (or org-cached-props
11021 (setq org-cached-props
11022 (org-entry-properties pom)))))))
11024 (defun org-global-tags-completion-table (&optional files)
11025 "Return the list of all tags in all agenda buffer/files."
11026 (save-excursion
11027 (org-uniquify
11028 (delq nil
11029 (apply 'append
11030 (mapcar
11031 (lambda (file)
11032 (set-buffer (find-file-noselect file))
11033 (append (org-get-buffer-tags)
11034 (mapcar (lambda (x) (if (stringp (car-safe x))
11035 (list (car-safe x)) nil))
11036 org-tag-alist)))
11037 (if (and files (car files))
11038 files
11039 (org-agenda-files))))))))
11041 (defun org-make-tags-matcher (match)
11042 "Create the TAGS//TODO matcher form for the selection string MATCH."
11043 ;; todo-only is scoped dynamically into this function, and the function
11044 ;; may change it if the matcher asks for it.
11045 (unless match
11046 ;; Get a new match request, with completion
11047 (let ((org-last-tags-completion-table
11048 (org-global-tags-completion-table)))
11049 (setq match (org-completing-read-no-i
11050 "Match: " 'org-tags-completion-function nil nil nil
11051 'org-tags-history))))
11053 ;; Parse the string and create a lisp form
11054 (let ((match0 match)
11055 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11056 minus tag mm
11057 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11058 orterms term orlist re-p str-p level-p level-op time-p
11059 prop-p pn pv po cat-p gv rest)
11060 (if (string-match "/+" match)
11061 ;; match contains also a todo-matching request
11062 (progn
11063 (setq tagsmatch (substring match 0 (match-beginning 0))
11064 todomatch (substring match (match-end 0)))
11065 (if (string-match "^!" todomatch)
11066 (setq todo-only t todomatch (substring todomatch 1)))
11067 (if (string-match "^\\s-*$" todomatch)
11068 (setq todomatch nil)))
11069 ;; only matching tags
11070 (setq tagsmatch match todomatch nil))
11072 ;; Make the tags matcher
11073 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11074 (setq tagsmatcher t)
11075 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11076 (while (setq term (pop orterms))
11077 (while (and (equal (substring term -1) "\\") orterms)
11078 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11079 (while (string-match re term)
11080 (setq rest (substring term (match-end 0))
11081 minus (and (match-end 1)
11082 (equal (match-string 1 term) "-"))
11083 tag (match-string 2 term)
11084 re-p (equal (string-to-char tag) ?{)
11085 level-p (match-end 4)
11086 prop-p (match-end 5)
11087 mm (cond
11088 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11089 (level-p
11090 (setq level-op (org-op-to-function (match-string 3 term)))
11091 `(,level-op level ,(string-to-number
11092 (match-string 4 term))))
11093 (prop-p
11094 (setq pn (match-string 5 term)
11095 po (match-string 6 term)
11096 pv (match-string 7 term)
11097 cat-p (equal pn "CATEGORY")
11098 re-p (equal (string-to-char pv) ?{)
11099 str-p (equal (string-to-char pv) ?\")
11100 time-p (save-match-data
11101 (string-match "^\"[[<].*[]>]\"$" pv))
11102 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11103 (if time-p (setq pv (org-matcher-time pv)))
11104 (setq po (org-op-to-function po (if time-p 'time str-p)))
11105 (cond
11106 ((equal pn "CATEGORY")
11107 (setq gv '(get-text-property (point) 'org-category)))
11108 ((equal pn "TODO")
11109 (setq gv 'todo))
11111 (setq gv `(org-cached-entry-get nil ,pn))))
11112 (if re-p
11113 (if (eq po 'org<>)
11114 `(not (string-match ,pv (or ,gv "")))
11115 `(string-match ,pv (or ,gv "")))
11116 (if str-p
11117 `(,po (or ,gv "") ,pv)
11118 `(,po (string-to-number (or ,gv ""))
11119 ,(string-to-number pv) ))))
11120 (t `(member ,tag tags-list)))
11121 mm (if minus (list 'not mm) mm)
11122 term rest)
11123 (push mm tagsmatcher))
11124 (push (if (> (length tagsmatcher) 1)
11125 (cons 'and tagsmatcher)
11126 (car tagsmatcher))
11127 orlist)
11128 (setq tagsmatcher nil))
11129 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11130 (setq tagsmatcher
11131 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11132 ;; Make the todo matcher
11133 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11134 (setq todomatcher t)
11135 (setq orterms (org-split-string todomatch "|") orlist nil)
11136 (while (setq term (pop orterms))
11137 (while (string-match re term)
11138 (setq minus (and (match-end 1)
11139 (equal (match-string 1 term) "-"))
11140 kwd (match-string 2 term)
11141 re-p (equal (string-to-char kwd) ?{)
11142 term (substring term (match-end 0))
11143 mm (if re-p
11144 `(string-match ,(substring kwd 1 -1) todo)
11145 (list 'equal 'todo kwd))
11146 mm (if minus (list 'not mm) mm))
11147 (push mm todomatcher))
11148 (push (if (> (length todomatcher) 1)
11149 (cons 'and todomatcher)
11150 (car todomatcher))
11151 orlist)
11152 (setq todomatcher nil))
11153 (setq todomatcher (if (> (length orlist) 1)
11154 (cons 'or orlist) (car orlist))))
11156 ;; Return the string and lisp forms of the matcher
11157 (setq matcher (if todomatcher
11158 (list 'and tagsmatcher todomatcher)
11159 tagsmatcher))
11160 (cons match0 matcher)))
11162 (defun org-op-to-function (op &optional stringp)
11163 "Turn an operator into the appropriate function."
11164 (setq op
11165 (cond
11166 ((equal op "<" ) '(< string< org-time<))
11167 ((equal op ">" ) '(> org-string> org-time>))
11168 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11169 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11170 ((member op '("=" "==")) '(= string= org-time=))
11171 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11172 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11174 (defun org<> (a b) (not (= a b)))
11175 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11176 (defun org-string>= (a b) (not (string< a b)))
11177 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11178 (defun org-string<> (a b) (not (string= a b)))
11179 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11180 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11181 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11182 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11183 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11184 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11185 (defun org-2ft (s)
11186 "Convert S to a floating point time.
11187 If S is already a number, just return it. If it is a string, parse
11188 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11189 (cond
11190 ((numberp s) s)
11191 ((stringp s)
11192 (condition-case nil
11193 (float-time (apply 'encode-time (org-parse-time-string s)))
11194 (error 0.)))
11195 (t 0.)))
11197 (defun org-time-today ()
11198 "Time in seconds today at 0:00.
11199 Returns the float number of seconds since the beginning of the
11200 epoch to the beginning of today (00:00)."
11201 (float-time (apply 'encode-time
11202 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11204 (defun org-matcher-time (s)
11205 "Interpret a time comparison value."
11206 (save-match-data
11207 (cond
11208 ((string= s "<now>") (float-time))
11209 ((string= s "<today>") (org-time-today))
11210 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11211 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11212 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11213 (+ (org-time-today)
11214 (* (string-to-number (match-string 1 s))
11215 (cdr (assoc (match-string 2 s)
11216 '(("d" . 86400.0) ("w" . 604800.0)
11217 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11218 (t (org-2ft s)))))
11220 (defun org-match-any-p (re list)
11221 "Does re match any element of list?"
11222 (setq list (mapcar (lambda (x) (string-match re x)) list))
11223 (delq nil list))
11225 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11226 (defvar org-tags-overlay (org-make-overlay 1 1))
11227 (org-detach-overlay org-tags-overlay)
11229 (defun org-get-local-tags-at (&optional pos)
11230 "Get a list of tags defined in the current headline."
11231 (org-get-tags-at pos 'local))
11233 (defun org-get-local-tags ()
11234 "Get a list of tags defined in the current headline."
11235 (org-get-tags-at nil 'local))
11237 (defun org-get-tags-at (&optional pos local)
11238 "Get a list of all headline tags applicable at POS.
11239 POS defaults to point. If tags are inherited, the list contains
11240 the targets in the same sequence as the headlines appear, i.e.
11241 the tags of the current headline come last.
11242 When LOCAL is non-nil, only return tags from the current headline,
11243 ignore inherited ones."
11244 (interactive)
11245 (if (and org-trust-scanner-tags
11246 (or (not pos) (equal pos (point)))
11247 (not local))
11248 org-scanner-tags
11249 (let (tags ltags lastpos parent)
11250 (save-excursion
11251 (save-restriction
11252 (widen)
11253 (goto-char (or pos (point)))
11254 (save-match-data
11255 (catch 'done
11256 (condition-case nil
11257 (progn
11258 (org-back-to-heading t)
11259 (while (not (equal lastpos (point)))
11260 (setq lastpos (point))
11261 (when (looking-at
11262 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11263 (setq ltags (org-split-string
11264 (org-match-string-no-properties 1) ":"))
11265 (when parent
11266 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11267 (setq tags (append
11268 (if parent
11269 (org-remove-uniherited-tags ltags)
11270 ltags)
11271 tags)))
11272 (or org-use-tag-inheritance (throw 'done t))
11273 (if local (throw 'done t))
11274 (or (org-up-heading-safe) (error nil))
11275 (setq parent t)))
11276 (error nil)))))
11277 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11279 (defun org-add-prop-inherited (s)
11280 (add-text-properties 0 (length s) '(inherited t) s)
11283 (defun org-toggle-tag (tag &optional onoff)
11284 "Toggle the tag TAG for the current line.
11285 If ONOFF is `on' or `off', don't toggle but set to this state."
11286 (let (res current)
11287 (save-excursion
11288 (org-back-to-heading t)
11289 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11290 (point-at-eol) t)
11291 (progn
11292 (setq current (match-string 1))
11293 (replace-match ""))
11294 (setq current ""))
11295 (setq current (nreverse (org-split-string current ":")))
11296 (cond
11297 ((eq onoff 'on)
11298 (setq res t)
11299 (or (member tag current) (push tag current)))
11300 ((eq onoff 'off)
11301 (or (not (member tag current)) (setq current (delete tag current))))
11302 (t (if (member tag current)
11303 (setq current (delete tag current))
11304 (setq res t)
11305 (push tag current))))
11306 (end-of-line 1)
11307 (if current
11308 (progn
11309 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11310 (org-set-tags nil t))
11311 (delete-horizontal-space))
11312 (run-hooks 'org-after-tags-change-hook))
11313 res))
11315 (defun org-align-tags-here (to-col)
11316 ;; Assumes that this is a headline
11317 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11318 (beginning-of-line 1)
11319 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11320 (< pos (match-beginning 2)))
11321 (progn
11322 (setq tags-l (- (match-end 2) (match-beginning 2)))
11323 (goto-char (match-beginning 1))
11324 (insert " ")
11325 (delete-region (point) (1+ (match-beginning 2)))
11326 (setq ncol (max (1+ (current-column))
11327 (1+ col)
11328 (if (> to-col 0)
11329 to-col
11330 (- (abs to-col) tags-l))))
11331 (setq p (point))
11332 (insert (make-string (- ncol (current-column)) ?\ ))
11333 (setq ncol (current-column))
11334 (when indent-tabs-mode (tabify p (point-at-eol)))
11335 (org-move-to-column (min ncol col) t))
11336 (goto-char pos))))
11338 (defun org-set-tags-command (&optional arg just-align)
11339 "Call the set-tags command for the current entry."
11340 (interactive "P")
11341 (if (org-on-heading-p)
11342 (org-set-tags arg just-align)
11343 (save-excursion
11344 (org-back-to-heading t)
11345 (org-set-tags arg just-align))))
11347 (defun org-set-tags-to (data)
11348 "Set the tags of the current entry to DATA, replacing the current tags.
11349 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11350 If DATA is nil or the empty string, any tags will be removed."
11351 (interactive "sTags: ")
11352 (setq data
11353 (cond
11354 ((eq data nil) "")
11355 ((equal data "") "")
11356 ((stringp data)
11357 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11358 ":"))
11359 ((listp data)
11360 (concat ":" (mapconcat 'identity data ":") ":"))
11361 (t nil)))
11362 (when data
11363 (save-excursion
11364 (org-back-to-heading t)
11365 (when (looking-at org-complex-heading-regexp)
11366 (if (match-end 5)
11367 (progn
11368 (goto-char (match-beginning 5))
11369 (insert data)
11370 (delete-region (point) (point-at-eol))
11371 (org-set-tags nil 'align))
11372 (goto-char (point-at-eol))
11373 (insert " " data)
11374 (org-set-tags nil 'align)))
11375 (beginning-of-line 1)
11376 (if (looking-at ".*?\\([ \t]+\\)$")
11377 (delete-region (match-beginning 1) (match-end 1))))))
11379 (defun org-set-tags (&optional arg just-align)
11380 "Set the tags for the current headline.
11381 With prefix ARG, realign all tags in headings in the current buffer."
11382 (interactive "P")
11383 (let* ((re (concat "^" outline-regexp))
11384 (current (org-get-tags-string))
11385 (col (current-column))
11386 (org-setting-tags t)
11387 table current-tags inherited-tags ; computed below when needed
11388 tags p0 c0 c1 rpl)
11389 (if arg
11390 (save-excursion
11391 (goto-char (point-min))
11392 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11393 (while (re-search-forward re nil t)
11394 (org-set-tags nil t)
11395 (end-of-line 1)))
11396 (message "All tags realigned to column %d" org-tags-column))
11397 (if just-align
11398 (setq tags current)
11399 ;; Get a new set of tags from the user
11400 (save-excursion
11401 (setq table (append org-tag-persistent-alist
11402 (or org-tag-alist (org-get-buffer-tags)))
11403 org-last-tags-completion-table table
11404 current-tags (org-split-string current ":")
11405 inherited-tags (nreverse
11406 (nthcdr (length current-tags)
11407 (nreverse (org-get-tags-at))))
11408 tags
11409 (if (or (eq t org-use-fast-tag-selection)
11410 (and org-use-fast-tag-selection
11411 (delq nil (mapcar 'cdr table))))
11412 (org-fast-tag-selection
11413 current-tags inherited-tags table
11414 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11415 (let ((org-add-colon-after-tag-completion t))
11416 (org-trim
11417 (org-without-partial-completion
11418 (org-icompleting-read "Tags: " 'org-tags-completion-function
11419 nil nil current 'org-tags-history)))))))
11420 (while (string-match "[-+&]+" tags)
11421 ;; No boolean logic, just a list
11422 (setq tags (replace-match ":" t t tags))))
11424 (if org-tags-sort-function
11425 (setq tags (mapconcat 'identity
11426 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11427 org-tags-sort-function) ":")))
11429 (if (string-match "\\`[\t ]*\\'" tags)
11430 (setq tags "")
11431 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11432 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11434 ;; Insert new tags at the correct column
11435 (beginning-of-line 1)
11436 (cond
11437 ((and (equal current "") (equal tags "")))
11438 ((re-search-forward
11439 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11440 (point-at-eol) t)
11441 (if (equal tags "")
11442 (setq rpl "")
11443 (goto-char (match-beginning 0))
11444 (setq c0 (current-column) p0 (point)
11445 c1 (max (1+ c0) (if (> org-tags-column 0)
11446 org-tags-column
11447 (- (- org-tags-column) (length tags))))
11448 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11449 (replace-match rpl t t)
11450 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11451 tags)
11452 (t (error "Tags alignment failed")))
11453 (org-move-to-column col)
11454 (unless just-align
11455 (run-hooks 'org-after-tags-change-hook)))))
11457 (defun org-change-tag-in-region (beg end tag off)
11458 "Add or remove TAG for each entry in the region.
11459 This works in the agenda, and also in an org-mode buffer."
11460 (interactive
11461 (list (region-beginning) (region-end)
11462 (let ((org-last-tags-completion-table
11463 (if (org-mode-p)
11464 (org-get-buffer-tags)
11465 (org-global-tags-completion-table))))
11466 (org-icompleting-read
11467 "Tag: " 'org-tags-completion-function nil nil nil
11468 'org-tags-history))
11469 (progn
11470 (message "[s]et or [r]emove? ")
11471 (equal (read-char-exclusive) ?r))))
11472 (if (fboundp 'deactivate-mark) (deactivate-mark))
11473 (let ((agendap (equal major-mode 'org-agenda-mode))
11474 l1 l2 m buf pos newhead (cnt 0))
11475 (goto-char end)
11476 (setq l2 (1- (org-current-line)))
11477 (goto-char beg)
11478 (setq l1 (org-current-line))
11479 (loop for l from l1 to l2 do
11480 (org-goto-line l)
11481 (setq m (get-text-property (point) 'org-hd-marker))
11482 (when (or (and (org-mode-p) (org-on-heading-p))
11483 (and agendap m))
11484 (setq buf (if agendap (marker-buffer m) (current-buffer))
11485 pos (if agendap m (point)))
11486 (with-current-buffer buf
11487 (save-excursion
11488 (save-restriction
11489 (goto-char pos)
11490 (setq cnt (1+ cnt))
11491 (org-toggle-tag tag (if off 'off 'on))
11492 (setq newhead (org-get-heading)))))
11493 (and agendap (org-agenda-change-all-lines newhead m))))
11494 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11496 (defun org-tags-completion-function (string predicate &optional flag)
11497 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11498 (confirm (lambda (x) (stringp (car x)))))
11499 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11500 (setq s1 (match-string 1 string)
11501 s2 (match-string 2 string))
11502 (setq s1 "" s2 string))
11503 (cond
11504 ((eq flag nil)
11505 ;; try completion
11506 (setq rtn (try-completion s2 ctable confirm))
11507 (if (stringp rtn)
11508 (setq rtn
11509 (concat s1 s2 (substring rtn (length s2))
11510 (if (and org-add-colon-after-tag-completion
11511 (assoc rtn ctable))
11512 ":" ""))))
11513 rtn)
11514 ((eq flag t)
11515 ;; all-completions
11516 (all-completions s2 ctable confirm)
11518 ((eq flag 'lambda)
11519 ;; exact match?
11520 (assoc s2 ctable)))
11523 (defun org-fast-tag-insert (kwd tags face &optional end)
11524 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11525 (insert (format "%-12s" (concat kwd ":"))
11526 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11527 (or end "")))
11529 (defun org-fast-tag-show-exit (flag)
11530 (save-excursion
11531 (org-goto-line 3)
11532 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11533 (replace-match ""))
11534 (when flag
11535 (end-of-line 1)
11536 (org-move-to-column (- (window-width) 19) t)
11537 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11539 (defun org-set-current-tags-overlay (current prefix)
11540 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11541 (if (featurep 'xemacs)
11542 (org-overlay-display org-tags-overlay (concat prefix s)
11543 'secondary-selection)
11544 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11545 (org-overlay-display org-tags-overlay (concat prefix s)))))
11547 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11548 "Fast tag selection with single keys.
11549 CURRENT is the current list of tags in the headline, INHERITED is the
11550 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11551 possibly with grouping information. TODO-TABLE is a similar table with
11552 TODO keywords, should these have keys assigned to them.
11553 If the keys are nil, a-z are automatically assigned.
11554 Returns the new tags string, or nil to not change the current settings."
11555 (let* ((fulltable (append table todo-table))
11556 (maxlen (apply 'max (mapcar
11557 (lambda (x)
11558 (if (stringp (car x)) (string-width (car x)) 0))
11559 fulltable)))
11560 (buf (current-buffer))
11561 (expert (eq org-fast-tag-selection-single-key 'expert))
11562 (buffer-tags nil)
11563 (fwidth (+ maxlen 3 1 3))
11564 (ncol (/ (- (window-width) 4) fwidth))
11565 (i-face 'org-done)
11566 (c-face 'org-todo)
11567 tg cnt e c char c1 c2 ntable tbl rtn
11568 ov-start ov-end ov-prefix
11569 (exit-after-next org-fast-tag-selection-single-key)
11570 (done-keywords org-done-keywords)
11571 groups ingroup)
11572 (save-excursion
11573 (beginning-of-line 1)
11574 (if (looking-at
11575 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11576 (setq ov-start (match-beginning 1)
11577 ov-end (match-end 1)
11578 ov-prefix "")
11579 (setq ov-start (1- (point-at-eol))
11580 ov-end (1+ ov-start))
11581 (skip-chars-forward "^\n\r")
11582 (setq ov-prefix
11583 (concat
11584 (buffer-substring (1- (point)) (point))
11585 (if (> (current-column) org-tags-column)
11587 (make-string (- org-tags-column (current-column)) ?\ ))))))
11588 (org-move-overlay org-tags-overlay ov-start ov-end)
11589 (save-window-excursion
11590 (if expert
11591 (set-buffer (get-buffer-create " *Org tags*"))
11592 (delete-other-windows)
11593 (split-window-vertically)
11594 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11595 (erase-buffer)
11596 (org-set-local 'org-done-keywords done-keywords)
11597 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11598 (org-fast-tag-insert "Current" current c-face "\n\n")
11599 (org-fast-tag-show-exit exit-after-next)
11600 (org-set-current-tags-overlay current ov-prefix)
11601 (setq tbl fulltable char ?a cnt 0)
11602 (while (setq e (pop tbl))
11603 (cond
11604 ((equal (car e) :startgroup)
11605 (push '() groups) (setq ingroup t)
11606 (when (not (= cnt 0))
11607 (setq cnt 0)
11608 (insert "\n"))
11609 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
11610 ((equal (car e) :endgroup)
11611 (setq ingroup nil cnt 0)
11612 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
11613 ((equal e '(:newline))
11614 (when (not (= cnt 0))
11615 (setq cnt 0)
11616 (insert "\n")
11617 (setq e (car tbl))
11618 (while (equal (car tbl) '(:newline))
11619 (insert "\n")
11620 (setq tbl (cdr tbl)))))
11622 (setq tg (copy-sequence (car e)) c2 nil)
11623 (if (cdr e)
11624 (setq c (cdr e))
11625 ;; automatically assign a character.
11626 (setq c1 (string-to-char
11627 (downcase (substring
11628 tg (if (= (string-to-char tg) ?@) 1 0)))))
11629 (if (or (rassoc c1 ntable) (rassoc c1 table))
11630 (while (or (rassoc char ntable) (rassoc char table))
11631 (setq char (1+ char)))
11632 (setq c2 c1))
11633 (setq c (or c2 char)))
11634 (if ingroup (push tg (car groups)))
11635 (setq tg (org-add-props tg nil 'face
11636 (cond
11637 ((not (assoc tg table))
11638 (org-get-todo-face tg))
11639 ((member tg current) c-face)
11640 ((member tg inherited) i-face)
11641 (t nil))))
11642 (if (and (= cnt 0) (not ingroup)) (insert " "))
11643 (insert "[" c "] " tg (make-string
11644 (- fwidth 4 (length tg)) ?\ ))
11645 (push (cons tg c) ntable)
11646 (when (= (setq cnt (1+ cnt)) ncol)
11647 (insert "\n")
11648 (if ingroup (insert " "))
11649 (setq cnt 0)))))
11650 (setq ntable (nreverse ntable))
11651 (insert "\n")
11652 (goto-char (point-min))
11653 (if (not expert) (org-fit-window-to-buffer))
11654 (setq rtn
11655 (catch 'exit
11656 (while t
11657 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
11658 (if (not groups) "no " "")
11659 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11660 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11661 (cond
11662 ((= c ?\r) (throw 'exit t))
11663 ((= c ?!)
11664 (setq groups (not groups))
11665 (goto-char (point-min))
11666 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11667 ((= c ?\C-c)
11668 (if (not expert)
11669 (org-fast-tag-show-exit
11670 (setq exit-after-next (not exit-after-next)))
11671 (setq expert nil)
11672 (delete-other-windows)
11673 (split-window-vertically)
11674 (org-switch-to-buffer-other-window " *Org tags*")
11675 (org-fit-window-to-buffer)))
11676 ((or (= c ?\C-g)
11677 (and (= c ?q) (not (rassoc c ntable))))
11678 (org-detach-overlay org-tags-overlay)
11679 (setq quit-flag t))
11680 ((= c ?\ )
11681 (setq current nil)
11682 (if exit-after-next (setq exit-after-next 'now)))
11683 ((= c ?\t)
11684 (condition-case nil
11685 (setq tg (org-icompleting-read
11686 "Tag: "
11687 (or buffer-tags
11688 (with-current-buffer buf
11689 (org-get-buffer-tags)))))
11690 (quit (setq tg "")))
11691 (when (string-match "\\S-" tg)
11692 (add-to-list 'buffer-tags (list tg))
11693 (if (member tg current)
11694 (setq current (delete tg current))
11695 (push tg current)))
11696 (if exit-after-next (setq exit-after-next 'now)))
11697 ((setq e (rassoc c todo-table) tg (car e))
11698 (with-current-buffer buf
11699 (save-excursion (org-todo tg)))
11700 (if exit-after-next (setq exit-after-next 'now)))
11701 ((setq e (rassoc c ntable) tg (car e))
11702 (if (member tg current)
11703 (setq current (delete tg current))
11704 (loop for g in groups do
11705 (if (member tg g)
11706 (mapc (lambda (x)
11707 (setq current (delete x current)))
11708 g)))
11709 (push tg current))
11710 (if exit-after-next (setq exit-after-next 'now))))
11712 ;; Create a sorted list
11713 (setq current
11714 (sort current
11715 (lambda (a b)
11716 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11717 (if (eq exit-after-next 'now) (throw 'exit t))
11718 (goto-char (point-min))
11719 (beginning-of-line 2)
11720 (delete-region (point) (point-at-eol))
11721 (org-fast-tag-insert "Current" current c-face)
11722 (org-set-current-tags-overlay current ov-prefix)
11723 (while (re-search-forward
11724 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11725 (setq tg (match-string 1))
11726 (add-text-properties
11727 (match-beginning 1) (match-end 1)
11728 (list 'face
11729 (cond
11730 ((member tg current) c-face)
11731 ((member tg inherited) i-face)
11732 (t (get-text-property (match-beginning 1) 'face))))))
11733 (goto-char (point-min)))))
11734 (org-detach-overlay org-tags-overlay)
11735 (if rtn
11736 (mapconcat 'identity current ":")
11737 nil))))
11739 (defun org-get-tags-string ()
11740 "Get the TAGS string in the current headline."
11741 (unless (org-on-heading-p t)
11742 (error "Not on a heading"))
11743 (save-excursion
11744 (beginning-of-line 1)
11745 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11746 (org-match-string-no-properties 1)
11747 "")))
11749 (defun org-get-tags ()
11750 "Get the list of tags specified in the current headline."
11751 (org-split-string (org-get-tags-string) ":"))
11753 (defun org-get-buffer-tags ()
11754 "Get a table of all tags used in the buffer, for completion."
11755 (let (tags)
11756 (save-excursion
11757 (goto-char (point-min))
11758 (while (re-search-forward
11759 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11760 (when (equal (char-after (point-at-bol 0)) ?*)
11761 (mapc (lambda (x) (add-to-list 'tags x))
11762 (org-split-string (org-match-string-no-properties 1) ":")))))
11763 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
11764 (mapcar 'list tags)))
11766 ;;;; The mapping API
11768 ;;;###autoload
11769 (defun org-map-entries (func &optional match scope &rest skip)
11770 "Call FUNC at each headline selected by MATCH in SCOPE.
11772 FUNC is a function or a lisp form. The function will be called without
11773 arguments, with the cursor positioned at the beginning of the headline.
11774 The return values of all calls to the function will be collected and
11775 returned as a list.
11777 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11778 does not need to preserve point. After evaluation, the cursor will be
11779 moved to the end of the line (presumably of the headline of the
11780 processed entry) and search continues from there. Under some
11781 circumstances, this may not produce the wanted results. For example,
11782 if you have removed (e.g. archived) the current (sub)tree it could
11783 mean that the next entry will be skipped entirely. In such cases, you
11784 can specify the position from where search should continue by making
11785 FUNC set the variable `org-map-continue-from' to the desired buffer
11786 position.
11788 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11789 Only headlines that are matched by this query will be considered during
11790 the iteration. When MATCH is nil or t, all headlines will be
11791 visited by the iteration.
11793 SCOPE determines the scope of this command. It can be any of:
11795 nil The current buffer, respecting the restriction if any
11796 tree The subtree started with the entry at point
11797 file The current buffer, without restriction
11798 file-with-archives
11799 The current buffer, and any archives associated with it
11800 agenda All agenda files
11801 agenda-with-archives
11802 All agenda files with any archive files associated with them
11803 \(file1 file2 ...)
11804 If this is a list, all files in the list will be scanned
11806 The remaining args are treated as settings for the skipping facilities of
11807 the scanner. The following items can be given here:
11809 archive skip trees with the archive tag.
11810 comment skip trees with the COMMENT keyword
11811 function or Emacs Lisp form:
11812 will be used as value for `org-agenda-skip-function', so whenever
11813 the function returns t, FUNC will not be called for that
11814 entry and search will continue from the point where the
11815 function leaves it.
11817 If your function needs to retrieve the tags including inherited tags
11818 at the *current* entry, you can use the value of the variable
11819 `org-scanner-tags' which will be much faster than getting the value
11820 with `org-get-tags-at'. If your function gets properties with
11821 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11822 to t around the call to `org-entry-properties' to get the same speedup.
11823 Note that if your function moves around to retrieve tags and properties at
11824 a *different* entry, you cannot use these techniques."
11825 (let* ((org-agenda-archives-mode nil) ; just to make sure
11826 (org-agenda-skip-archived-trees (memq 'archive skip))
11827 (org-agenda-skip-comment-trees (memq 'comment skip))
11828 (org-agenda-skip-function
11829 (car (org-delete-all '(comment archive) skip)))
11830 (org-tags-match-list-sublevels t)
11831 matcher file res
11832 org-todo-keywords-for-agenda
11833 org-done-keywords-for-agenda
11834 org-todo-keyword-alist-for-agenda
11835 org-drawers-for-agenda
11836 org-tag-alist-for-agenda)
11838 (cond
11839 ((eq match t) (setq matcher t))
11840 ((eq match nil) (setq matcher t))
11841 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11843 (save-excursion
11844 (save-restriction
11845 (when (eq scope 'tree)
11846 (org-back-to-heading t)
11847 (org-narrow-to-subtree)
11848 (setq scope nil))
11850 (if (not scope)
11851 (progn
11852 (org-prepare-agenda-buffers
11853 (list (buffer-file-name (current-buffer))))
11854 (setq res (org-scan-tags func matcher)))
11855 ;; Get the right scope
11856 (cond
11857 ((and scope (listp scope) (symbolp (car scope)))
11858 (setq scope (eval scope)))
11859 ((eq scope 'agenda)
11860 (setq scope (org-agenda-files t)))
11861 ((eq scope 'agenda-with-archives)
11862 (setq scope (org-agenda-files t))
11863 (setq scope (org-add-archive-files scope)))
11864 ((eq scope 'file)
11865 (setq scope (list (buffer-file-name))))
11866 ((eq scope 'file-with-archives)
11867 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11868 (org-prepare-agenda-buffers scope)
11869 (while (setq file (pop scope))
11870 (with-current-buffer (org-find-base-buffer-visiting file)
11871 (save-excursion
11872 (save-restriction
11873 (widen)
11874 (goto-char (point-min))
11875 (setq res (append res (org-scan-tags func matcher))))))))))
11876 res))
11878 ;;;; Properties
11880 ;;; Setting and retrieving properties
11882 (defconst org-special-properties
11883 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11884 "TIMESTAMP" "TIMESTAMP_IA")
11885 "The special properties valid in Org-mode.
11887 These are properties that are not defined in the property drawer,
11888 but in some other way.")
11890 (defconst org-default-properties
11891 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11892 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11893 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11894 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11895 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
11896 "CLOCK_MODELINE_TOTAL" "STYLE")
11897 "Some properties that are used by Org-mode for various purposes.
11898 Being in this list makes sure that they are offered for completion.")
11900 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11901 "Regular expression matching the first line of a property drawer.")
11903 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11904 "Regular expression matching the first line of a property drawer.")
11906 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11907 "Regular expression matching the first line of a property drawer.")
11909 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11910 "Regular expression matching the first line of a property drawer.")
11912 (defconst org-property-drawer-re
11913 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11914 org-property-end-re "\\)\n?")
11915 "Matches an entire property drawer.")
11917 (defconst org-clock-drawer-re
11918 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11919 org-property-end-re "\\)\n?")
11920 "Matches an entire clock drawer.")
11922 (defun org-property-action ()
11923 "Do an action on properties."
11924 (interactive)
11925 (let (c)
11926 (org-at-property-p)
11927 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11928 (setq c (read-char-exclusive))
11929 (cond
11930 ((equal c ?s)
11931 (call-interactively 'org-set-property))
11932 ((equal c ?d)
11933 (call-interactively 'org-delete-property))
11934 ((equal c ?D)
11935 (call-interactively 'org-delete-property-globally))
11936 ((equal c ?c)
11937 (call-interactively 'org-compute-property-at-point))
11938 (t (error "No such property action %c" c)))))
11940 (defun org-set-effort (&optional value)
11941 "Set the effort property of the current entry.
11942 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
11943 allowed value."
11944 (interactive "P")
11945 (if (equal value 0) (setq value 10))
11946 (let* ((completion-ignore-case t)
11947 (prop org-effort-property)
11948 (cur (org-entry-get nil prop))
11949 (allowed (org-property-get-allowed-values nil prop 'table))
11950 (existing (mapcar 'list (org-property-values prop)))
11951 (val (cond
11952 ((stringp value) value)
11953 ((and allowed (integerp value))
11954 (or (car (nth (1- value) allowed))
11955 (car (org-last allowed))))
11956 (allowed
11957 (org-completing-read "Value: " allowed nil 'req-match))
11959 (let (org-completion-use-ido org-completion-use-iswitchb)
11960 (org-completing-read
11961 (concat "Value " (if (and cur (string-match "\\S-" cur))
11962 (concat "[" cur "]") "")
11963 ": ")
11964 existing nil nil "" nil cur))))))
11965 (unless (equal (org-entry-get nil prop) val)
11966 (org-entry-put nil prop val))
11967 (message "%s is now %s" prop val)))
11969 (defun org-at-property-p ()
11970 "Is the cursor in a property line?"
11971 ;; FIXME: Does not check if we are actually in the drawer.
11972 ;; FIXME: also returns true on any drawers.....
11973 ;; This is used by C-c C-c for property action.
11974 (save-excursion
11975 (beginning-of-line 1)
11976 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11978 (defun org-get-property-block (&optional beg end force)
11979 "Return the (beg . end) range of the body of the property drawer.
11980 BEG and END can be beginning and end of subtree, if not given
11981 they will be found.
11982 If the drawer does not exist and FORCE is non-nil, create the drawer."
11983 (catch 'exit
11984 (save-excursion
11985 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11986 (end (or end (progn (outline-next-heading) (point)))))
11987 (goto-char beg)
11988 (if (re-search-forward org-property-start-re end t)
11989 (setq beg (1+ (match-end 0)))
11990 (if force
11991 (save-excursion
11992 (org-insert-property-drawer)
11993 (setq end (progn (outline-next-heading) (point))))
11994 (throw 'exit nil))
11995 (goto-char beg)
11996 (if (re-search-forward org-property-start-re end t)
11997 (setq beg (1+ (match-end 0)))))
11998 (if (re-search-forward org-property-end-re end t)
11999 (setq end (match-beginning 0))
12000 (or force (throw 'exit nil))
12001 (goto-char beg)
12002 (setq end beg)
12003 (org-indent-line-function)
12004 (insert ":END:\n"))
12005 (cons beg end)))))
12007 (defun org-entry-properties (&optional pom which)
12008 "Get all properties of the entry at point-or-marker POM.
12009 This includes the TODO keyword, the tags, time strings for deadline,
12010 scheduled, and clocking, and any additional properties defined in the
12011 entry. The return value is an alist, keys may occur multiple times
12012 if the property key was used several times.
12013 POM may also be nil, in which case the current entry is used.
12014 If WHICH is nil or `all', get all properties. If WHICH is
12015 `special' or `standard', only get that subclass."
12016 (setq which (or which 'all))
12017 (org-with-point-at pom
12018 (let ((clockstr (substring org-clock-string 0 -1))
12019 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
12020 beg end range props sum-props key value string clocksum)
12021 (save-excursion
12022 (when (condition-case nil
12023 (and (org-mode-p) (org-back-to-heading t))
12024 (error nil))
12025 (setq beg (point))
12026 (setq sum-props (get-text-property (point) 'org-summaries))
12027 (setq clocksum (get-text-property (point) :org-clock-minutes))
12028 (outline-next-heading)
12029 (setq end (point))
12030 (when (memq which '(all special))
12031 ;; Get the special properties, like TODO and tags
12032 (goto-char beg)
12033 (when (and (looking-at org-todo-line-regexp) (match-end 2))
12034 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12035 (when (looking-at org-priority-regexp)
12036 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12037 (when (and (setq value (org-get-tags-string))
12038 (string-match "\\S-" value))
12039 (push (cons "TAGS" value) props))
12040 (when (setq value (org-get-tags-at))
12041 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
12042 props))
12043 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12044 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12045 string (if (equal key clockstr)
12046 (org-no-properties
12047 (org-trim
12048 (buffer-substring
12049 (match-beginning 3) (goto-char (point-at-eol)))))
12050 (substring (org-match-string-no-properties 3) 1 -1)))
12051 (unless key
12052 (if (= (char-after (match-beginning 3)) ?\[)
12053 (setq key "TIMESTAMP_IA")
12054 (setq key "TIMESTAMP")))
12055 (when (or (equal key clockstr) (not (assoc key props)))
12056 (push (cons key string) props)))
12060 (when (memq which '(all standard))
12061 ;; Get the standard properties, like :PROP: ...
12062 (setq range (org-get-property-block beg end))
12063 (when range
12064 (goto-char (car range))
12065 (while (re-search-forward
12066 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12067 (cdr range) t)
12068 (setq key (org-match-string-no-properties 1)
12069 value (org-trim (or (org-match-string-no-properties 2) "")))
12070 (unless (member key excluded)
12071 (push (cons key (or value "")) props)))))
12072 (if clocksum
12073 (push (cons "CLOCKSUM"
12074 (org-columns-number-to-string (/ (float clocksum) 60.)
12075 'add_times))
12076 props))
12077 (unless (assoc "CATEGORY" props)
12078 (setq value (or (org-get-category)
12079 (progn (org-refresh-category-properties)
12080 (org-get-category))))
12081 (push (cons "CATEGORY" value) props))
12082 (append sum-props (nreverse props)))))))
12084 (defun org-entry-get (pom property &optional inherit)
12085 "Get value of PROPERTY for entry at point-or-marker POM.
12086 If INHERIT is non-nil and the entry does not have the property,
12087 then also check higher levels of the hierarchy.
12088 If INHERIT is the symbol `selective', use inheritance only if the setting
12089 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12090 If the property is present but empty, the return value is the empty string.
12091 If the property is not present at all, nil is returned."
12092 (org-with-point-at pom
12093 (if (and inherit (if (eq inherit 'selective)
12094 (org-property-inherit-p property)
12096 (org-entry-get-with-inheritance property)
12097 (if (member property org-special-properties)
12098 ;; We need a special property. Use brute force, get all properties.
12099 (cdr (assoc property (org-entry-properties nil 'special)))
12100 (let ((range (org-get-property-block)))
12101 (if (and range
12102 (goto-char (car range))
12103 (re-search-forward
12104 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12105 (cdr range) t))
12106 ;; Found the property, return it.
12107 (if (match-end 1)
12108 (org-match-string-no-properties 1)
12109 "")))))))
12111 (defun org-property-or-variable-value (var &optional inherit)
12112 "Check if there is a property fixing the value of VAR.
12113 If yes, return this value. If not, return the current value of the variable."
12114 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12115 (if (and prop (stringp prop) (string-match "\\S-" prop))
12116 (read prop)
12117 (symbol-value var))))
12119 (defun org-entry-delete (pom property)
12120 "Delete the property PROPERTY from entry at point-or-marker POM."
12121 (org-with-point-at pom
12122 (if (member property org-special-properties)
12123 nil ; cannot delete these properties.
12124 (let ((range (org-get-property-block)))
12125 (if (and range
12126 (goto-char (car range))
12127 (re-search-forward
12128 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12129 (cdr range) t))
12130 (progn
12131 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12133 nil)))))
12135 ;; Multi-values properties are properties that contain multiple values
12136 ;; These values are assumed to be single words, separated by whitespace.
12137 (defun org-entry-add-to-multivalued-property (pom property value)
12138 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12139 (let* ((old (org-entry-get pom property))
12140 (values (and old (org-split-string old "[ \t]"))))
12141 (setq value (org-entry-protect-space value))
12142 (unless (member value values)
12143 (setq values (cons value values))
12144 (org-entry-put pom property
12145 (mapconcat 'identity values " ")))))
12147 (defun org-entry-remove-from-multivalued-property (pom property value)
12148 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12149 (let* ((old (org-entry-get pom property))
12150 (values (and old (org-split-string old "[ \t]"))))
12151 (setq value (org-entry-protect-space value))
12152 (when (member value values)
12153 (setq values (delete value values))
12154 (org-entry-put pom property
12155 (mapconcat 'identity values " ")))))
12157 (defun org-entry-member-in-multivalued-property (pom property value)
12158 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12159 (let* ((old (org-entry-get pom property))
12160 (values (and old (org-split-string old "[ \t]"))))
12161 (setq value (org-entry-protect-space value))
12162 (member value values)))
12164 (defun org-entry-get-multivalued-property (pom property)
12165 "Return a list of values in a multivalued property."
12166 (let* ((value (org-entry-get pom property))
12167 (values (and value (org-split-string value "[ \t]"))))
12168 (mapcar 'org-entry-restore-space values)))
12170 (defun org-entry-put-multivalued-property (pom property &rest values)
12171 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12172 VALUES should be a list of strings. Spaces will be protected."
12173 (org-entry-put pom property
12174 (mapconcat 'org-entry-protect-space values " "))
12175 (let* ((value (org-entry-get pom property))
12176 (values (and value (org-split-string value "[ \t]"))))
12177 (mapcar 'org-entry-restore-space values)))
12179 (defun org-entry-protect-space (s)
12180 "Protect spaces and newline in string S."
12181 (while (string-match " " s)
12182 (setq s (replace-match "%20" t t s)))
12183 (while (string-match "\n" s)
12184 (setq s (replace-match "%0A" t t s)))
12187 (defun org-entry-restore-space (s)
12188 "Restore spaces and newline in string S."
12189 (while (string-match "%20" s)
12190 (setq s (replace-match " " t t s)))
12191 (while (string-match "%0A" s)
12192 (setq s (replace-match "\n" t t s)))
12195 (defvar org-entry-property-inherited-from (make-marker)
12196 "Marker pointing to the entry from where a property was inherited.
12197 Each call to `org-entry-get-with-inheritance' will set this marker to the
12198 location of the entry where the inheritance search matched. If there was
12199 no match, the marker will point nowhere.
12200 Note that also `org-entry-get' calls this function, if the INHERIT flag
12201 is set.")
12203 (defun org-entry-get-with-inheritance (property)
12204 "Get entry property, and search higher levels if not present."
12205 (move-marker org-entry-property-inherited-from nil)
12206 (let (tmp)
12207 (save-excursion
12208 (save-restriction
12209 (widen)
12210 (catch 'ex
12211 (while t
12212 (when (setq tmp (org-entry-get nil property))
12213 (org-back-to-heading t)
12214 (move-marker org-entry-property-inherited-from (point))
12215 (throw 'ex tmp))
12216 (or (org-up-heading-safe) (throw 'ex nil)))))
12217 (or tmp
12218 (cdr (assoc property org-file-properties))
12219 (cdr (assoc property org-global-properties))
12220 (cdr (assoc property org-global-properties-fixed))))))
12222 (defun org-entry-put (pom property value)
12223 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12224 (org-with-point-at pom
12225 (org-back-to-heading t)
12226 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12227 range)
12228 (cond
12229 ((equal property "TODO")
12230 (when (and (stringp value) (string-match "\\S-" value)
12231 (not (member value org-todo-keywords-1)))
12232 (error "\"%s\" is not a valid TODO state" value))
12233 (if (or (not value)
12234 (not (string-match "\\S-" value)))
12235 (setq value 'none))
12236 (org-todo value)
12237 (org-set-tags nil 'align))
12238 ((equal property "PRIORITY")
12239 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12240 (string-to-char value) ?\ ))
12241 (org-set-tags nil 'align))
12242 ((equal property "SCHEDULED")
12243 (if (re-search-forward org-scheduled-time-regexp end t)
12244 (cond
12245 ((eq value 'earlier) (org-timestamp-change -1 'day))
12246 ((eq value 'later) (org-timestamp-change 1 'day))
12247 (t (call-interactively 'org-schedule)))
12248 (call-interactively 'org-schedule)))
12249 ((equal property "DEADLINE")
12250 (if (re-search-forward org-deadline-time-regexp end t)
12251 (cond
12252 ((eq value 'earlier) (org-timestamp-change -1 'day))
12253 ((eq value 'later) (org-timestamp-change 1 'day))
12254 (t (call-interactively 'org-deadline)))
12255 (call-interactively 'org-deadline)))
12256 ((member property org-special-properties)
12257 (error "The %s property can not yet be set with `org-entry-put'"
12258 property))
12259 (t ; a non-special property
12260 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12261 (setq range (org-get-property-block beg end 'force))
12262 (goto-char (car range))
12263 (if (re-search-forward
12264 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12265 (progn
12266 (delete-region (match-beginning 1) (match-end 1))
12267 (goto-char (match-beginning 1)))
12268 (goto-char (cdr range))
12269 (insert "\n")
12270 (backward-char 1)
12271 (org-indent-line-function)
12272 (insert ":" property ":"))
12273 (and value (insert " " value))
12274 (org-indent-line-function)))))))
12276 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12277 "Get all property keys in the current buffer.
12278 With INCLUDE-SPECIALS, also list the special properties that reflect things
12279 like tags and TODO state.
12280 With INCLUDE-DEFAULTS, also include properties that has special meaning
12281 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12282 With INCLUDE-COLUMNS, also include property names given in COLUMN
12283 formats in the current buffer."
12284 (let (rtn range cfmt s p)
12285 (save-excursion
12286 (save-restriction
12287 (widen)
12288 (goto-char (point-min))
12289 (while (re-search-forward org-property-start-re nil t)
12290 (setq range (org-get-property-block))
12291 (goto-char (car range))
12292 (while (re-search-forward
12293 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12294 (cdr range) t)
12295 (add-to-list 'rtn (org-match-string-no-properties 1)))
12296 (outline-next-heading))))
12298 (when include-specials
12299 (setq rtn (append org-special-properties rtn)))
12301 (when include-defaults
12302 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12303 (add-to-list 'rtn org-effort-property))
12305 (when include-columns
12306 (save-excursion
12307 (save-restriction
12308 (widen)
12309 (goto-char (point-min))
12310 (while (re-search-forward
12311 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12312 nil t)
12313 (setq cfmt (match-string 2) s 0)
12314 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12315 cfmt s)
12316 (setq s (match-end 0)
12317 p (match-string 1 cfmt))
12318 (unless (or (equal p "ITEM")
12319 (member p org-special-properties))
12320 (add-to-list 'rtn (match-string 1 cfmt))))))))
12322 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12324 (defun org-property-values (key)
12325 "Return a list of all values of property KEY."
12326 (save-excursion
12327 (save-restriction
12328 (widen)
12329 (goto-char (point-min))
12330 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12331 values)
12332 (while (re-search-forward re nil t)
12333 (add-to-list 'values (org-trim (match-string 1))))
12334 (delete "" values)))))
12336 (defun org-insert-property-drawer ()
12337 "Insert a property drawer into the current entry."
12338 (interactive)
12339 (org-back-to-heading t)
12340 (looking-at outline-regexp)
12341 (let ((indent (if org-adapt-indentation
12342 (- (match-end 0)(match-beginning 0))
12344 (beg (point))
12345 (re (concat "^[ \t]*" org-keyword-time-regexp))
12346 end hiddenp)
12347 (outline-next-heading)
12348 (setq end (point))
12349 (goto-char beg)
12350 (while (re-search-forward re end t))
12351 (setq hiddenp (org-invisible-p))
12352 (end-of-line 1)
12353 (and (equal (char-after) ?\n) (forward-char 1))
12354 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12355 (if (member (match-string 1) '("CLOCK:" ":END:"))
12356 ;; just skip this line
12357 (beginning-of-line 2)
12358 ;; Drawer start, find the end
12359 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12360 (beginning-of-line 1)))
12361 (org-skip-over-state-notes)
12362 (skip-chars-backward " \t\n\r")
12363 (if (eq (char-before) ?*) (forward-char 1))
12364 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12365 (beginning-of-line 0)
12366 (org-indent-to-column indent)
12367 (beginning-of-line 2)
12368 (org-indent-to-column indent)
12369 (beginning-of-line 0)
12370 (if hiddenp
12371 (save-excursion
12372 (org-back-to-heading t)
12373 (hide-entry))
12374 (org-flag-drawer t))))
12376 (defun org-set-property (property value)
12377 "In the current entry, set PROPERTY to VALUE.
12378 When called interactively, this will prompt for a property name, offering
12379 completion on existing and default properties. And then it will prompt
12380 for a value, offering completion either on allowed values (via an inherited
12381 xxx_ALL property) or on existing values in other instances of this property
12382 in the current file."
12383 (interactive
12384 (let* ((completion-ignore-case t)
12385 (keys (org-buffer-property-keys nil t t))
12386 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12387 (prop (if (member prop0 keys)
12388 prop0
12389 (or (cdr (assoc (downcase prop0)
12390 (mapcar (lambda (x) (cons (downcase x) x))
12391 keys)))
12392 prop0)))
12393 (cur (org-entry-get nil prop))
12394 (allowed (org-property-get-allowed-values nil prop 'table))
12395 (existing (mapcar 'list (org-property-values prop)))
12396 (val (if allowed
12397 (org-completing-read "Value: " allowed nil 'req-match)
12398 (let (org-completion-use-ido org-completion-use-iswitchb)
12399 (org-completing-read
12400 (concat "Value " (if (and cur (string-match "\\S-" cur))
12401 (concat "[" cur "]") "")
12402 ": ")
12403 existing nil nil "" nil cur)))))
12404 (list prop (if (equal val "") cur val))))
12405 (unless (equal (org-entry-get nil property) value)
12406 (org-entry-put nil property value)))
12408 (defun org-delete-property (property)
12409 "In the current entry, delete PROPERTY."
12410 (interactive
12411 (let* ((completion-ignore-case t)
12412 (prop (org-icompleting-read
12413 "Property: " (org-entry-properties nil 'standard))))
12414 (list prop)))
12415 (message "Property %s %s" property
12416 (if (org-entry-delete nil property)
12417 "deleted"
12418 "was not present in the entry")))
12420 (defun org-delete-property-globally (property)
12421 "Remove PROPERTY globally, from all entries."
12422 (interactive
12423 (let* ((completion-ignore-case t)
12424 (prop (org-icompleting-read
12425 "Globally remove property: "
12426 (mapcar 'list (org-buffer-property-keys)))))
12427 (list prop)))
12428 (save-excursion
12429 (save-restriction
12430 (widen)
12431 (goto-char (point-min))
12432 (let ((cnt 0))
12433 (while (re-search-forward
12434 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12435 nil t)
12436 (setq cnt (1+ cnt))
12437 (replace-match ""))
12438 (message "Property \"%s\" removed from %d entries" property cnt)))))
12440 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12442 (defun org-compute-property-at-point ()
12443 "Compute the property at point.
12444 This looks for an enclosing column format, extracts the operator and
12445 then applies it to the property in the column format's scope."
12446 (interactive)
12447 (unless (org-at-property-p)
12448 (error "Not at a property"))
12449 (let ((prop (org-match-string-no-properties 2)))
12450 (org-columns-get-format-and-top-level)
12451 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12452 (error "No operator defined for property %s" prop))
12453 (org-columns-compute prop)))
12455 (defun org-property-get-allowed-values (pom property &optional table)
12456 "Get allowed values for the property PROPERTY.
12457 When TABLE is non-nil, return an alist that can directly be used for
12458 completion."
12459 (let (vals)
12460 (cond
12461 ((equal property "TODO")
12462 (setq vals (org-with-point-at pom
12463 (append org-todo-keywords-1 '("")))))
12464 ((equal property "PRIORITY")
12465 (let ((n org-lowest-priority))
12466 (while (>= n org-highest-priority)
12467 (push (char-to-string n) vals)
12468 (setq n (1- n)))))
12469 ((member property org-special-properties))
12471 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12473 (when (and vals (string-match "\\S-" vals))
12474 (setq vals (car (read-from-string (concat "(" vals ")"))))
12475 (setq vals (mapcar (lambda (x)
12476 (cond ((stringp x) x)
12477 ((numberp x) (number-to-string x))
12478 ((symbolp x) (symbol-name x))
12479 (t "???")))
12480 vals)))))
12481 (if table (mapcar 'list vals) vals)))
12483 (defun org-property-previous-allowed-value (&optional previous)
12484 "Switch to the next allowed value for this property."
12485 (interactive)
12486 (org-property-next-allowed-value t))
12488 (defun org-property-next-allowed-value (&optional previous)
12489 "Switch to the next allowed value for this property."
12490 (interactive)
12491 (unless (org-at-property-p)
12492 (error "Not at a property"))
12493 (let* ((key (match-string 2))
12494 (value (match-string 3))
12495 (allowed (or (org-property-get-allowed-values (point) key)
12496 (and (member value '("[ ]" "[-]" "[X]"))
12497 '("[ ]" "[X]"))))
12498 nval)
12499 (unless allowed
12500 (error "Allowed values for this property have not been defined"))
12501 (if previous (setq allowed (reverse allowed)))
12502 (if (member value allowed)
12503 (setq nval (car (cdr (member value allowed)))))
12504 (setq nval (or nval (car allowed)))
12505 (if (equal nval value)
12506 (error "Only one allowed value for this property"))
12507 (org-at-property-p)
12508 (replace-match (concat " :" key ": " nval) t t)
12509 (org-indent-line-function)
12510 (beginning-of-line 1)
12511 (skip-chars-forward " \t")))
12513 (defun org-find-entry-with-id (ident)
12514 "Locate the entry that contains the ID property with exact value IDENT.
12515 IDENT can be a string, a symbol or a number, this function will search for
12516 the string representation of it.
12517 Return the position where this entry starts, or nil if there is no such entry."
12518 (interactive "sID: ")
12519 (let ((id (cond
12520 ((stringp ident) ident)
12521 ((symbol-name ident) (symbol-name ident))
12522 ((numberp ident) (number-to-string ident))
12523 (t (error "IDENT %s must be a string, symbol or number" ident))))
12524 (case-fold-search nil))
12525 (save-excursion
12526 (save-restriction
12527 (widen)
12528 (goto-char (point-min))
12529 (when (re-search-forward
12530 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12531 nil t)
12532 (org-back-to-heading t)
12533 (point))))))
12535 ;;;; Timestamps
12537 (defvar org-last-changed-timestamp nil)
12538 (defvar org-last-inserted-timestamp nil
12539 "The last time stamp inserted with `org-insert-time-stamp'.")
12540 (defvar org-time-was-given) ; dynamically scoped parameter
12541 (defvar org-end-time-was-given) ; dynamically scoped parameter
12542 (defvar org-ts-what) ; dynamically scoped parameter
12544 (defun org-time-stamp (arg &optional inactive)
12545 "Prompt for a date/time and insert a time stamp.
12546 If the user specifies a time like HH:MM, or if this command is called
12547 with a prefix argument, the time stamp will contain date and time.
12548 Otherwise, only the date will be included. All parts of a date not
12549 specified by the user will be filled in from the current date/time.
12550 So if you press just return without typing anything, the time stamp
12551 will represent the current date/time. If there is already a timestamp
12552 at the cursor, it will be modified."
12553 (interactive "P")
12554 (let* ((ts nil)
12555 (default-time
12556 ;; Default time is either today, or, when entering a range,
12557 ;; the range start.
12558 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12559 (save-excursion
12560 (re-search-backward
12561 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12562 (- (point) 20) t)))
12563 (apply 'encode-time (org-parse-time-string (match-string 1)))
12564 (current-time)))
12565 (default-input (and ts (org-get-compact-tod ts)))
12566 org-time-was-given org-end-time-was-given time)
12567 (cond
12568 ((and (org-at-timestamp-p t)
12569 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12570 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12571 (insert "--")
12572 (setq time (let ((this-command this-command))
12573 (org-read-date arg 'totime nil nil
12574 default-time default-input)))
12575 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12576 ((org-at-timestamp-p t)
12577 (setq time (let ((this-command this-command))
12578 (org-read-date arg 'totime nil nil default-time default-input)))
12579 (when (org-at-timestamp-p t) ; just to get the match data
12580 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12581 (replace-match "")
12582 (setq org-last-changed-timestamp
12583 (org-insert-time-stamp
12584 time (or org-time-was-given arg)
12585 inactive nil nil (list org-end-time-was-given))))
12586 (message "Timestamp updated"))
12588 (setq time (let ((this-command this-command))
12589 (org-read-date arg 'totime nil nil default-time default-input)))
12590 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12591 nil nil (list org-end-time-was-given))))))
12593 ;; FIXME: can we use this for something else, like computing time differences?
12594 (defun org-get-compact-tod (s)
12595 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12596 (let* ((t1 (match-string 1 s))
12597 (h1 (string-to-number (match-string 2 s)))
12598 (m1 (string-to-number (match-string 3 s)))
12599 (t2 (and (match-end 4) (match-string 5 s)))
12600 (h2 (and t2 (string-to-number (match-string 6 s))))
12601 (m2 (and t2 (string-to-number (match-string 7 s))))
12602 dh dm)
12603 (if (not t2)
12605 (setq dh (- h2 h1) dm (- m2 m1))
12606 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12607 (concat t1 "+" (number-to-string dh)
12608 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12610 (defun org-time-stamp-inactive (&optional arg)
12611 "Insert an inactive time stamp.
12612 An inactive time stamp is enclosed in square brackets instead of angle
12613 brackets. It is inactive in the sense that it does not trigger agenda entries,
12614 does not link to the calendar and cannot be changed with the S-cursor keys.
12615 So these are more for recording a certain time/date."
12616 (interactive "P")
12617 (org-time-stamp arg 'inactive))
12619 (defvar org-date-ovl (org-make-overlay 1 1))
12620 (org-overlay-put org-date-ovl 'face 'org-warning)
12621 (org-detach-overlay org-date-ovl)
12623 (defvar org-ans1) ; dynamically scoped parameter
12624 (defvar org-ans2) ; dynamically scoped parameter
12626 (defvar org-plain-time-of-day-regexp) ; defined below
12628 (defvar org-overriding-default-time nil) ; dynamically scoped
12629 (defvar org-read-date-overlay nil)
12630 (defvar org-dcst nil) ; dynamically scoped
12631 (defvar org-read-date-history nil)
12632 (defvar org-read-date-final-answer nil)
12634 (defun org-read-date (&optional with-time to-time from-string prompt
12635 default-time default-input)
12636 "Read a date, possibly a time, and make things smooth for the user.
12637 The prompt will suggest to enter an ISO date, but you can also enter anything
12638 which will at least partially be understood by `parse-time-string'.
12639 Unrecognized parts of the date will default to the current day, month, year,
12640 hour and minute. If this command is called to replace a timestamp at point,
12641 of to enter the second timestamp of a range, the default time is taken from the
12642 existing stamp. For example,
12643 3-2-5 --> 2003-02-05
12644 feb 15 --> currentyear-02-15
12645 sep 12 9 --> 2009-09-12
12646 12:45 --> today 12:45
12647 22 sept 0:34 --> currentyear-09-22 0:34
12648 12 --> currentyear-currentmonth-12
12649 Fri --> nearest Friday (today or later)
12650 etc.
12652 Furthermore you can specify a relative date by giving, as the *first* thing
12653 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12654 change in days weeks, months, years.
12655 With a single plus or minus, the date is relative to today. With a double
12656 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12657 +4d --> four days from today
12658 +4 --> same as above
12659 +2w --> two weeks from today
12660 ++5 --> five days from default date
12662 The function understands only English month and weekday abbreviations,
12663 but this can be configured with the variables `parse-time-months' and
12664 `parse-time-weekdays'.
12666 While prompting, a calendar is popped up - you can also select the
12667 date with the mouse (button 1). The calendar shows a period of three
12668 months. To scroll it to other months, use the keys `>' and `<'.
12669 If you don't like the calendar, turn it off with
12670 \(setq org-read-date-popup-calendar nil)
12672 With optional argument TO-TIME, the date will immediately be converted
12673 to an internal time.
12674 With an optional argument WITH-TIME, the prompt will suggest to also
12675 insert a time. Note that when WITH-TIME is not set, you can still
12676 enter a time, and this function will inform the calling routine about
12677 this change. The calling routine may then choose to change the format
12678 used to insert the time stamp into the buffer to include the time.
12679 With optional argument FROM-STRING, read from this string instead from
12680 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12681 the time/date that is used for everything that is not specified by the
12682 user."
12683 (require 'parse-time)
12684 (let* ((org-time-stamp-rounding-minutes
12685 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12686 (org-dcst org-display-custom-times)
12687 (ct (org-current-time))
12688 (def (or org-overriding-default-time default-time ct))
12689 (defdecode (decode-time def))
12690 (dummy (progn
12691 (when (< (nth 2 defdecode) org-extend-today-until)
12692 (setcar (nthcdr 2 defdecode) -1)
12693 (setcar (nthcdr 1 defdecode) 59)
12694 (setq def (apply 'encode-time defdecode)
12695 defdecode (decode-time def)))))
12696 (calendar-frame-setup nil)
12697 (calendar-move-hook nil)
12698 (calendar-view-diary-initially-flag nil)
12699 (view-diary-entries-initially nil)
12700 (calendar-view-holidays-initially-flag nil)
12701 (view-calendar-holidays-initially nil)
12702 (timestr (format-time-string
12703 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12704 (prompt (concat (if prompt (concat prompt " ") "")
12705 (format "Date+time [%s]: " timestr)))
12706 ans (org-ans0 "") org-ans1 org-ans2 final)
12708 (cond
12709 (from-string (setq ans from-string))
12710 (org-read-date-popup-calendar
12711 (save-excursion
12712 (save-window-excursion
12713 (calendar)
12714 (calendar-forward-day (- (time-to-days def)
12715 (calendar-absolute-from-gregorian
12716 (calendar-current-date))))
12717 (org-eval-in-calendar nil t)
12718 (let* ((old-map (current-local-map))
12719 (map (copy-keymap calendar-mode-map))
12720 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12721 (org-defkey map (kbd "RET") 'org-calendar-select)
12722 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12723 'org-calendar-select-mouse)
12724 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12725 'org-calendar-select-mouse)
12726 (org-defkey minibuffer-local-map [(meta shift left)]
12727 (lambda () (interactive)
12728 (org-eval-in-calendar '(calendar-backward-month 1))))
12729 (org-defkey minibuffer-local-map [(meta shift right)]
12730 (lambda () (interactive)
12731 (org-eval-in-calendar '(calendar-forward-month 1))))
12732 (org-defkey minibuffer-local-map [(meta shift up)]
12733 (lambda () (interactive)
12734 (org-eval-in-calendar '(calendar-backward-year 1))))
12735 (org-defkey minibuffer-local-map [(meta shift down)]
12736 (lambda () (interactive)
12737 (org-eval-in-calendar '(calendar-forward-year 1))))
12738 (org-defkey minibuffer-local-map [?\e (shift left)]
12739 (lambda () (interactive)
12740 (org-eval-in-calendar '(calendar-backward-month 1))))
12741 (org-defkey minibuffer-local-map [?\e (shift right)]
12742 (lambda () (interactive)
12743 (org-eval-in-calendar '(calendar-forward-month 1))))
12744 (org-defkey minibuffer-local-map [?\e (shift up)]
12745 (lambda () (interactive)
12746 (org-eval-in-calendar '(calendar-backward-year 1))))
12747 (org-defkey minibuffer-local-map [?\e (shift down)]
12748 (lambda () (interactive)
12749 (org-eval-in-calendar '(calendar-forward-year 1))))
12750 (org-defkey minibuffer-local-map [(shift up)]
12751 (lambda () (interactive)
12752 (org-eval-in-calendar '(calendar-backward-week 1))))
12753 (org-defkey minibuffer-local-map [(shift down)]
12754 (lambda () (interactive)
12755 (org-eval-in-calendar '(calendar-forward-week 1))))
12756 (org-defkey minibuffer-local-map [(shift left)]
12757 (lambda () (interactive)
12758 (org-eval-in-calendar '(calendar-backward-day 1))))
12759 (org-defkey minibuffer-local-map [(shift right)]
12760 (lambda () (interactive)
12761 (org-eval-in-calendar '(calendar-forward-day 1))))
12762 (org-defkey minibuffer-local-map ">"
12763 (lambda () (interactive)
12764 (org-eval-in-calendar '(scroll-calendar-left 1))))
12765 (org-defkey minibuffer-local-map "<"
12766 (lambda () (interactive)
12767 (org-eval-in-calendar '(scroll-calendar-right 1))))
12768 (run-hooks 'org-read-date-minibuffer-setup-hook)
12769 (unwind-protect
12770 (progn
12771 (use-local-map map)
12772 (add-hook 'post-command-hook 'org-read-date-display)
12773 (setq org-ans0 (read-string prompt default-input
12774 'org-read-date-history nil))
12775 ;; org-ans0: from prompt
12776 ;; org-ans1: from mouse click
12777 ;; org-ans2: from calendar motion
12778 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12779 (remove-hook 'post-command-hook 'org-read-date-display)
12780 (use-local-map old-map)
12781 (when org-read-date-overlay
12782 (org-delete-overlay org-read-date-overlay)
12783 (setq org-read-date-overlay nil)))))))
12785 (t ; Naked prompt only
12786 (unwind-protect
12787 (setq ans (read-string prompt default-input
12788 'org-read-date-history timestr))
12789 (when org-read-date-overlay
12790 (org-delete-overlay org-read-date-overlay)
12791 (setq org-read-date-overlay nil)))))
12793 (setq final (org-read-date-analyze ans def defdecode))
12794 (setq org-read-date-final-answer ans)
12796 (if to-time
12797 (apply 'encode-time final)
12798 (if (and (boundp 'org-time-was-given) org-time-was-given)
12799 (format "%04d-%02d-%02d %02d:%02d"
12800 (nth 5 final) (nth 4 final) (nth 3 final)
12801 (nth 2 final) (nth 1 final))
12802 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12804 (defvar def)
12805 (defvar defdecode)
12806 (defvar with-time)
12807 (defvar org-read-date-analyze-futurep nil)
12808 (defun org-read-date-display ()
12809 "Display the current date prompt interpretation in the minibuffer."
12810 (when org-read-date-display-live
12811 (when org-read-date-overlay
12812 (org-delete-overlay org-read-date-overlay))
12813 (let ((p (point)))
12814 (end-of-line 1)
12815 (while (not (equal (buffer-substring
12816 (max (point-min) (- (point) 4)) (point))
12817 " "))
12818 (insert " "))
12819 (goto-char p))
12820 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12821 " " (or org-ans1 org-ans2)))
12822 (org-end-time-was-given nil)
12823 (f (org-read-date-analyze ans def defdecode))
12824 (fmts (if org-dcst
12825 org-time-stamp-custom-formats
12826 org-time-stamp-formats))
12827 (fmt (if (or with-time
12828 (and (boundp 'org-time-was-given) org-time-was-given))
12829 (cdr fmts)
12830 (car fmts)))
12831 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12832 (when (and org-end-time-was-given
12833 (string-match org-plain-time-of-day-regexp txt))
12834 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12835 org-end-time-was-given
12836 (substring txt (match-end 0)))))
12837 (when org-read-date-analyze-futurep
12838 (setq txt (concat txt " (=>F)")))
12839 (setq org-read-date-overlay
12840 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12841 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12843 (defun org-read-date-analyze (ans def defdecode)
12844 "Analyse the combined answer of the date prompt."
12845 ;; FIXME: cleanup and comment
12846 (let (delta deltan deltaw deltadef year month day
12847 hour minute second wday pm h2 m2 tl wday1
12848 iso-year iso-weekday iso-week iso-year iso-date futurep)
12849 (setq org-read-date-analyze-futurep nil)
12850 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12851 (setq ans "+0"))
12853 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12854 (setq ans (replace-match "" t t ans)
12855 deltan (car delta)
12856 deltaw (nth 1 delta)
12857 deltadef (nth 2 delta)))
12859 ;; Check if there is an iso week date in there
12860 ;; If yes, sore the info and postpone interpreting it until the rest
12861 ;; of the parsing is done
12862 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12863 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12864 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12865 iso-week (string-to-number (match-string 2 ans)))
12866 (setq ans (replace-match "" t t ans)))
12868 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12869 (when (string-match
12870 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12871 (setq year (if (match-end 2)
12872 (string-to-number (match-string 2 ans))
12873 (string-to-number (format-time-string "%Y")))
12874 month (string-to-number (match-string 3 ans))
12875 day (string-to-number (match-string 4 ans)))
12876 (if (< year 100) (setq year (+ 2000 year)))
12877 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12878 t nil ans)))
12879 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12880 ;; If there is a time with am/pm, and *no* time without it, we convert
12881 ;; so that matching will be successful.
12882 (loop for i from 1 to 2 do ; twice, for end time as well
12883 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12884 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12885 (setq hour (string-to-number (match-string 1 ans))
12886 minute (if (match-end 3)
12887 (string-to-number (match-string 3 ans))
12889 pm (equal ?p
12890 (string-to-char (downcase (match-string 4 ans)))))
12891 (if (and (= hour 12) (not pm))
12892 (setq hour 0)
12893 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12894 (setq ans (replace-match (format "%02d:%02d" hour minute)
12895 t t ans))))
12897 ;; Check if a time range is given as a duration
12898 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12899 (setq hour (string-to-number (match-string 1 ans))
12900 h2 (+ hour (string-to-number (match-string 3 ans)))
12901 minute (string-to-number (match-string 2 ans))
12902 m2 (+ minute (if (match-end 5) (string-to-number
12903 (match-string 5 ans))0)))
12904 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12905 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12906 t t ans)))
12908 ;; Check if there is a time range
12909 (when (boundp 'org-end-time-was-given)
12910 (setq org-time-was-given nil)
12911 (when (and (string-match org-plain-time-of-day-regexp ans)
12912 (match-end 8))
12913 (setq org-end-time-was-given (match-string 8 ans))
12914 (setq ans (concat (substring ans 0 (match-beginning 7))
12915 (substring ans (match-end 7))))))
12917 (setq tl (parse-time-string ans)
12918 day (or (nth 3 tl) (nth 3 defdecode))
12919 month (or (nth 4 tl)
12920 (if (and org-read-date-prefer-future
12921 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12922 (prog1 (1+ (nth 4 defdecode)) (setq futurep t))
12923 (nth 4 defdecode)))
12924 year (or (nth 5 tl)
12925 (if (and org-read-date-prefer-future
12926 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12927 (prog1 (1+ (nth 5 defdecode)) (setq futurep t))
12928 (nth 5 defdecode)))
12929 hour (or (nth 2 tl) (nth 2 defdecode))
12930 minute (or (nth 1 tl) (nth 1 defdecode))
12931 second (or (nth 0 tl) 0)
12932 wday (nth 6 tl))
12934 (when (and (eq org-read-date-prefer-future 'time)
12935 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
12936 (equal day (nth 3 defdecode))
12937 (equal month (nth 4 defdecode))
12938 (equal year (nth 5 defdecode))
12939 (nth 2 tl)
12940 (or (< (nth 2 tl) (nth 2 defdecode))
12941 (and (= (nth 2 tl) (nth 2 defdecode))
12942 (nth 1 tl)
12943 (< (nth 1 tl) (nth 1 defdecode)))))
12944 (setq day (1+ day)
12945 futurep t))
12947 ;; Special date definitions below
12948 (cond
12949 (iso-week
12950 ;; There was an iso week
12951 (setq futurep nil)
12952 (setq year (or iso-year year)
12953 day (or iso-weekday wday 1)
12954 wday nil ; to make sure that the trigger below does not match
12955 iso-date (calendar-gregorian-from-absolute
12956 (calendar-absolute-from-iso
12957 (list iso-week day year))))
12958 ; FIXME: Should we also push ISO weeks into the future?
12959 ; (when (and org-read-date-prefer-future
12960 ; (not iso-year)
12961 ; (< (calendar-absolute-from-gregorian iso-date)
12962 ; (time-to-days (current-time))))
12963 ; (setq year (1+ year)
12964 ; iso-date (calendar-gregorian-from-absolute
12965 ; (calendar-absolute-from-iso
12966 ; (list iso-week day year)))))
12967 (setq month (car iso-date)
12968 year (nth 2 iso-date)
12969 day (nth 1 iso-date)))
12970 (deltan
12971 (setq futurep nil)
12972 (unless deltadef
12973 (let ((now (decode-time (current-time))))
12974 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12975 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12976 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12977 ((equal deltaw "m") (setq month (+ month deltan)))
12978 ((equal deltaw "y") (setq year (+ year deltan)))))
12979 ((and wday (not (nth 3 tl)))
12980 (setq futurep nil)
12981 ;; Weekday was given, but no day, so pick that day in the week
12982 ;; on or after the derived date.
12983 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12984 (unless (equal wday wday1)
12985 (setq day (+ day (% (- wday wday1 -7) 7))))))
12986 (if (and (boundp 'org-time-was-given)
12987 (nth 2 tl))
12988 (setq org-time-was-given t))
12989 (if (< year 100) (setq year (+ 2000 year)))
12990 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12991 (setq org-read-date-analyze-futurep futurep)
12992 (list second minute hour day month year)))
12994 (defvar parse-time-weekdays)
12996 (defun org-read-date-get-relative (s today default)
12997 "Check string S for special relative date string.
12998 TODAY and DEFAULT are internal times, for today and for a default.
12999 Return shift list (N what def-flag)
13000 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13001 N is the number of WHATs to shift.
13002 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13003 the DEFAULT date rather than TODAY."
13004 (when (and
13005 (string-match
13006 (concat
13007 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13008 "\\([0-9]+\\)?"
13009 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13010 "\\([ \t]\\|$\\)") s)
13011 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13012 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13013 (string-to-char (substring (match-string 1 s) -1))
13014 ?+))
13015 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13016 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13017 (what (if (match-end 3) (match-string 3 s) "d"))
13018 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13019 (date (if rel default today))
13020 (wday (nth 6 (decode-time date)))
13021 delta)
13022 (if wday1
13023 (progn
13024 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13025 (if (= dir ?-) (setq delta (- delta 7)))
13026 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13027 (list delta "d" rel))
13028 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13030 (defun org-eval-in-calendar (form &optional keepdate)
13031 "Eval FORM in the calendar window and return to current window.
13032 Also, store the cursor date in variable org-ans2."
13033 (let ((sf (selected-frame))
13034 (sw (selected-window)))
13035 (select-window (get-buffer-window "*Calendar*" t))
13036 (eval form)
13037 (when (and (not keepdate) (calendar-cursor-to-date))
13038 (let* ((date (calendar-cursor-to-date))
13039 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13040 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13041 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13042 (select-window sw)
13043 (org-select-frame-set-input-focus sf)))
13045 (defun org-calendar-select ()
13046 "Return to `org-read-date' with the date currently selected.
13047 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13048 (interactive)
13049 (when (calendar-cursor-to-date)
13050 (let* ((date (calendar-cursor-to-date))
13051 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13052 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13053 (if (active-minibuffer-window) (exit-minibuffer))))
13055 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13056 "Insert a date stamp for the date given by the internal TIME.
13057 WITH-HM means, use the stamp format that includes the time of the day.
13058 INACTIVE means use square brackets instead of angular ones, so that the
13059 stamp will not contribute to the agenda.
13060 PRE and POST are optional strings to be inserted before and after the
13061 stamp.
13062 The command returns the inserted time stamp."
13063 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13064 stamp)
13065 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13066 (insert-before-markers (or pre ""))
13067 (insert-before-markers (setq stamp (format-time-string fmt time)))
13068 (when (listp extra)
13069 (setq extra (car extra))
13070 (if (and (stringp extra)
13071 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13072 (setq extra (format "-%02d:%02d"
13073 (string-to-number (match-string 1 extra))
13074 (string-to-number (match-string 2 extra))))
13075 (setq extra nil)))
13076 (when extra
13077 (backward-char 1)
13078 (insert-before-markers extra)
13079 (forward-char 1))
13080 (insert-before-markers (or post ""))
13081 (setq org-last-inserted-timestamp stamp)))
13083 (defun org-toggle-time-stamp-overlays ()
13084 "Toggle the use of custom time stamp formats."
13085 (interactive)
13086 (setq org-display-custom-times (not org-display-custom-times))
13087 (unless org-display-custom-times
13088 (let ((p (point-min)) (bmp (buffer-modified-p)))
13089 (while (setq p (next-single-property-change p 'display))
13090 (if (and (get-text-property p 'display)
13091 (eq (get-text-property p 'face) 'org-date))
13092 (remove-text-properties
13093 p (setq p (next-single-property-change p 'display))
13094 '(display t))))
13095 (set-buffer-modified-p bmp)))
13096 (if (featurep 'xemacs)
13097 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13098 (org-restart-font-lock)
13099 (setq org-table-may-need-update t)
13100 (if org-display-custom-times
13101 (message "Time stamps are overlayed with custom format")
13102 (message "Time stamp overlays removed")))
13104 (defun org-display-custom-time (beg end)
13105 "Overlay modified time stamp format over timestamp between BEG and END."
13106 (let* ((ts (buffer-substring beg end))
13107 t1 w1 with-hm tf time str w2 (off 0))
13108 (save-match-data
13109 (setq t1 (org-parse-time-string ts t))
13110 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13111 (setq off (- (match-end 0) (match-beginning 0)))))
13112 (setq end (- end off))
13113 (setq w1 (- end beg)
13114 with-hm (and (nth 1 t1) (nth 2 t1))
13115 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13116 time (org-fix-decoded-time t1)
13117 str (org-add-props
13118 (format-time-string
13119 (substring tf 1 -1) (apply 'encode-time time))
13120 nil 'mouse-face 'highlight)
13121 w2 (length str))
13122 (if (not (= w2 w1))
13123 (add-text-properties (1+ beg) (+ 2 beg)
13124 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13125 (if (featurep 'xemacs)
13126 (progn
13127 (put-text-property beg end 'invisible t)
13128 (put-text-property beg end 'end-glyph (make-glyph str)))
13129 (put-text-property beg end 'display str))))
13131 (defun org-translate-time (string)
13132 "Translate all timestamps in STRING to custom format.
13133 But do this only if the variable `org-display-custom-times' is set."
13134 (when org-display-custom-times
13135 (save-match-data
13136 (let* ((start 0)
13137 (re org-ts-regexp-both)
13138 t1 with-hm inactive tf time str beg end)
13139 (while (setq start (string-match re string start))
13140 (setq beg (match-beginning 0)
13141 end (match-end 0)
13142 t1 (save-match-data
13143 (org-parse-time-string (substring string beg end) t))
13144 with-hm (and (nth 1 t1) (nth 2 t1))
13145 inactive (equal (substring string beg (1+ beg)) "[")
13146 tf (funcall (if with-hm 'cdr 'car)
13147 org-time-stamp-custom-formats)
13148 time (org-fix-decoded-time t1)
13149 str (format-time-string
13150 (concat
13151 (if inactive "[" "<") (substring tf 1 -1)
13152 (if inactive "]" ">"))
13153 (apply 'encode-time time))
13154 string (replace-match str t t string)
13155 start (+ start (length str)))))))
13156 string)
13158 (defun org-fix-decoded-time (time)
13159 "Set 0 instead of nil for the first 6 elements of time.
13160 Don't touch the rest."
13161 (let ((n 0))
13162 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13164 (defun org-days-to-time (timestamp-string)
13165 "Difference between TIMESTAMP-STRING and now in days."
13166 (- (time-to-days (org-time-string-to-time timestamp-string))
13167 (time-to-days (current-time))))
13169 (defun org-deadline-close (timestamp-string &optional ndays)
13170 "Is the time in TIMESTAMP-STRING close to the current date?"
13171 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13172 (and (< (org-days-to-time timestamp-string) ndays)
13173 (not (org-entry-is-done-p))))
13175 (defun org-get-wdays (ts)
13176 "Get the deadline lead time appropriate for timestring TS."
13177 (cond
13178 ((<= org-deadline-warning-days 0)
13179 ;; 0 or negative, enforce this value no matter what
13180 (- org-deadline-warning-days))
13181 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13182 ;; lead time is specified.
13183 (floor (* (string-to-number (match-string 1 ts))
13184 (cdr (assoc (match-string 2 ts)
13185 '(("d" . 1) ("w" . 7)
13186 ("m" . 30.4) ("y" . 365.25)))))))
13187 ;; go for the default.
13188 (t org-deadline-warning-days)))
13190 (defun org-calendar-select-mouse (ev)
13191 "Return to `org-read-date' with the date currently selected.
13192 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13193 (interactive "e")
13194 (mouse-set-point ev)
13195 (when (calendar-cursor-to-date)
13196 (let* ((date (calendar-cursor-to-date))
13197 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13198 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13199 (if (active-minibuffer-window) (exit-minibuffer))))
13201 (defun org-check-deadlines (ndays)
13202 "Check if there are any deadlines due or past due.
13203 A deadline is considered due if it happens within `org-deadline-warning-days'
13204 days from today's date. If the deadline appears in an entry marked DONE,
13205 it is not shown. The prefix arg NDAYS can be used to test that many
13206 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13207 (interactive "P")
13208 (let* ((org-warn-days
13209 (cond
13210 ((equal ndays '(4)) 100000)
13211 (ndays (prefix-numeric-value ndays))
13212 (t (abs org-deadline-warning-days))))
13213 (case-fold-search nil)
13214 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13215 (callback
13216 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13218 (message "%d deadlines past-due or due within %d days"
13219 (org-occur regexp nil callback)
13220 org-warn-days)))
13222 (defun org-check-before-date (date)
13223 "Check if there are deadlines or scheduled entries before DATE."
13224 (interactive (list (org-read-date)))
13225 (let ((case-fold-search nil)
13226 (regexp (concat "\\<\\(" org-deadline-string
13227 "\\|" org-scheduled-string
13228 "\\) *<\\([^>]+\\)>"))
13229 (callback
13230 (lambda () (time-less-p
13231 (org-time-string-to-time (match-string 2))
13232 (org-time-string-to-time date)))))
13233 (message "%d entries before %s"
13234 (org-occur regexp nil callback) date)))
13236 (defun org-check-after-date (date)
13237 "Check if there are deadlines or scheduled entries after DATE."
13238 (interactive (list (org-read-date)))
13239 (let ((case-fold-search nil)
13240 (regexp (concat "\\<\\(" org-deadline-string
13241 "\\|" org-scheduled-string
13242 "\\) *<\\([^>]+\\)>"))
13243 (callback
13244 (lambda () (not
13245 (time-less-p
13246 (org-time-string-to-time (match-string 2))
13247 (org-time-string-to-time date))))))
13248 (message "%d entries after %s"
13249 (org-occur regexp nil callback) date)))
13251 (defun org-evaluate-time-range (&optional to-buffer)
13252 "Evaluate a time range by computing the difference between start and end.
13253 Normally the result is just printed in the echo area, but with prefix arg
13254 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13255 If the time range is actually in a table, the result is inserted into the
13256 next column.
13257 For time difference computation, a year is assumed to be exactly 365
13258 days in order to avoid rounding problems."
13259 (interactive "P")
13261 (org-clock-update-time-maybe)
13262 (save-excursion
13263 (unless (org-at-date-range-p t)
13264 (goto-char (point-at-bol))
13265 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13266 (if (not (org-at-date-range-p t))
13267 (error "Not at a time-stamp range, and none found in current line")))
13268 (let* ((ts1 (match-string 1))
13269 (ts2 (match-string 2))
13270 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13271 (match-end (match-end 0))
13272 (time1 (org-time-string-to-time ts1))
13273 (time2 (org-time-string-to-time ts2))
13274 (t1 (org-float-time time1))
13275 (t2 (org-float-time time2))
13276 (diff (abs (- t2 t1)))
13277 (negative (< (- t2 t1) 0))
13278 ;; (ys (floor (* 365 24 60 60)))
13279 (ds (* 24 60 60))
13280 (hs (* 60 60))
13281 (fy "%dy %dd %02d:%02d")
13282 (fy1 "%dy %dd")
13283 (fd "%dd %02d:%02d")
13284 (fd1 "%dd")
13285 (fh "%02d:%02d")
13286 y d h m align)
13287 (if havetime
13288 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13290 d (floor (/ diff ds)) diff (mod diff ds)
13291 h (floor (/ diff hs)) diff (mod diff hs)
13292 m (floor (/ diff 60)))
13293 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13295 d (floor (+ (/ diff ds) 0.5))
13296 h 0 m 0))
13297 (if (not to-buffer)
13298 (message "%s" (org-make-tdiff-string y d h m))
13299 (if (org-at-table-p)
13300 (progn
13301 (goto-char match-end)
13302 (setq align t)
13303 (and (looking-at " *|") (goto-char (match-end 0))))
13304 (goto-char match-end))
13305 (if (looking-at
13306 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13307 (replace-match ""))
13308 (if negative (insert " -"))
13309 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13310 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13311 (insert " " (format fh h m))))
13312 (if align (org-table-align))
13313 (message "Time difference inserted")))))
13315 (defun org-make-tdiff-string (y d h m)
13316 (let ((fmt "")
13317 (l nil))
13318 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13319 l (push y l)))
13320 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13321 l (push d l)))
13322 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13323 l (push h l)))
13324 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13325 l (push m l)))
13326 (apply 'format fmt (nreverse l))))
13328 (defun org-time-string-to-time (s)
13329 (apply 'encode-time (org-parse-time-string s)))
13330 (defun org-time-string-to-seconds (s)
13331 (org-float-time (org-time-string-to-time s)))
13333 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13334 "Convert a time stamp to an absolute day number.
13335 If there is a specifyer for a cyclic time stamp, get the closest date to
13336 DAYNR.
13337 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13338 the variable date is bound by the calendar when this is called."
13339 (cond
13340 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13341 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13342 daynr
13343 (+ daynr 1000)))
13344 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13345 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13346 (time-to-days (current-time))) (match-string 0 s)
13347 prefer show-all))
13348 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13350 (defun org-days-to-iso-week (days)
13351 "Return the iso week number."
13352 (require 'cal-iso)
13353 (car (calendar-iso-from-absolute days)))
13355 (defun org-small-year-to-year (year)
13356 "Convert 2-digit years into 4-digit years.
13357 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13358 The year 2000 cannot be abbreviated. Any year larger than 99
13359 is returned unchanged."
13360 (if (< year 38)
13361 (setq year (+ 2000 year))
13362 (if (< year 100)
13363 (setq year (+ 1900 year))))
13364 year)
13366 (defun org-time-from-absolute (d)
13367 "Return the time corresponding to date D.
13368 D may be an absolute day number, or a calendar-type list (month day year)."
13369 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13370 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13372 (defun org-calendar-holiday ()
13373 "List of holidays, for Diary display in Org-mode."
13374 (require 'holidays)
13375 (let ((hl (funcall
13376 (if (fboundp 'calendar-check-holidays)
13377 'calendar-check-holidays 'check-calendar-holidays) date)))
13378 (if hl (mapconcat 'identity hl "; "))))
13380 (defun org-diary-sexp-entry (sexp entry date)
13381 "Process a SEXP diary ENTRY for DATE."
13382 (require 'diary-lib)
13383 (let ((result (if calendar-debug-sexp
13384 (let ((stack-trace-on-error t))
13385 (eval (car (read-from-string sexp))))
13386 (condition-case nil
13387 (eval (car (read-from-string sexp)))
13388 (error
13389 (beep)
13390 (message "Bad sexp at line %d in %s: %s"
13391 (org-current-line)
13392 (buffer-file-name) sexp)
13393 (sleep-for 2))))))
13394 (cond ((stringp result) result)
13395 ((and (consp result)
13396 (stringp (cdr result))) (cdr result))
13397 (result entry)
13398 (t nil))))
13400 (defun org-diary-to-ical-string (frombuf)
13401 "Get iCalendar entries from diary entries in buffer FROMBUF.
13402 This uses the icalendar.el library."
13403 (let* ((tmpdir (if (featurep 'xemacs)
13404 (temp-directory)
13405 temporary-file-directory))
13406 (tmpfile (make-temp-name
13407 (expand-file-name "orgics" tmpdir)))
13408 buf rtn b e)
13409 (save-excursion
13410 (set-buffer frombuf)
13411 (icalendar-export-region (point-min) (point-max) tmpfile)
13412 (setq buf (find-buffer-visiting tmpfile))
13413 (set-buffer buf)
13414 (goto-char (point-min))
13415 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13416 (setq b (match-beginning 0)))
13417 (goto-char (point-max))
13418 (if (re-search-backward "^END:VEVENT" nil t)
13419 (setq e (match-end 0)))
13420 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13421 (kill-buffer buf)
13422 (delete-file tmpfile)
13423 rtn))
13425 (defun org-closest-date (start current change prefer show-all)
13426 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13427 When PREFER is `past' return a date that is either CURRENT or past.
13428 When PREFER is `future', return a date that is either CURRENT or future.
13429 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13430 ;; Make the proper lists from the dates
13431 (catch 'exit
13432 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13433 dn dw sday cday n1 n2 n0
13434 d m y y1 y2 date1 date2 nmonths nm ny m2)
13436 (setq start (org-date-to-gregorian start)
13437 current (org-date-to-gregorian
13438 (if show-all
13439 current
13440 (time-to-days (current-time))))
13441 sday (calendar-absolute-from-gregorian start)
13442 cday (calendar-absolute-from-gregorian current))
13444 (if (<= cday sday) (throw 'exit sday))
13446 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13447 (setq dn (string-to-number (match-string 1 change))
13448 dw (cdr (assoc (match-string 2 change) a1)))
13449 (error "Invalid change specifyer: %s" change))
13450 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13451 (cond
13452 ((eq dw 'day)
13453 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13454 n2 (+ n1 dn)))
13455 ((eq dw 'year)
13456 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13457 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13458 (setq date1 (list m d y1)
13459 n1 (calendar-absolute-from-gregorian date1)
13460 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13461 n2 (calendar-absolute-from-gregorian date2)))
13462 ((eq dw 'month)
13463 ;; approx number of month between the two dates
13464 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13465 ;; How often does dn fit in there?
13466 (setq d (nth 1 start) m (car start) y (nth 2 start)
13467 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13468 m (+ m nm)
13469 ny (floor (/ m 12))
13470 y (+ y ny)
13471 m (- m (* ny 12)))
13472 (while (> m 12) (setq m (- m 12) y (1+ y)))
13473 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13474 (setq m2 (+ m dn) y2 y)
13475 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13476 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13477 (while (<= n2 cday)
13478 (setq n1 n2 m m2 y y2)
13479 (setq m2 (+ m dn) y2 y)
13480 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13481 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13482 ;; Make sure n1 is the earlier date
13483 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13484 (if show-all
13485 (cond
13486 ((eq prefer 'past) (if (= cday n2) n2 n1))
13487 ((eq prefer 'future) (if (= cday n1) n1 n2))
13488 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13489 (cond
13490 ((eq prefer 'past) (if (= cday n2) n2 n1))
13491 ((eq prefer 'future) (if (= cday n1) n1 n2))
13492 (t (if (= cday n1) n1 n2)))))))
13494 (defun org-date-to-gregorian (date)
13495 "Turn any specification of DATE into a gregorian date for the calendar."
13496 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13497 ((and (listp date) (= (length date) 3)) date)
13498 ((stringp date)
13499 (setq date (org-parse-time-string date))
13500 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13501 ((listp date)
13502 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13504 (defun org-parse-time-string (s &optional nodefault)
13505 "Parse the standard Org-mode time string.
13506 This should be a lot faster than the normal `parse-time-string'.
13507 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13508 hour and minute fields will be nil if not given."
13509 (if (string-match org-ts-regexp0 s)
13510 (list 0
13511 (if (or (match-beginning 8) (not nodefault))
13512 (string-to-number (or (match-string 8 s) "0")))
13513 (if (or (match-beginning 7) (not nodefault))
13514 (string-to-number (or (match-string 7 s) "0")))
13515 (string-to-number (match-string 4 s))
13516 (string-to-number (match-string 3 s))
13517 (string-to-number (match-string 2 s))
13518 nil nil nil)
13519 (error "Not a standard Org-mode time string: %s" s)))
13521 (defun org-timestamp-up (&optional arg)
13522 "Increase the date item at the cursor by one.
13523 If the cursor is on the year, change the year. If it is on the month or
13524 the day, change that.
13525 With prefix ARG, change by that many units."
13526 (interactive "p")
13527 (org-timestamp-change (prefix-numeric-value arg)))
13529 (defun org-timestamp-down (&optional arg)
13530 "Decrease the date item at the cursor by one.
13531 If the cursor is on the year, change the year. If it is on the month or
13532 the day, change that.
13533 With prefix ARG, change by that many units."
13534 (interactive "p")
13535 (org-timestamp-change (- (prefix-numeric-value arg))))
13537 (defun org-timestamp-up-day (&optional arg)
13538 "Increase the date in the time stamp by one day.
13539 With prefix ARG, change that many days."
13540 (interactive "p")
13541 (if (and (not (org-at-timestamp-p t))
13542 (org-on-heading-p))
13543 (org-todo 'up)
13544 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13546 (defun org-timestamp-down-day (&optional arg)
13547 "Decrease the date in the time stamp by one day.
13548 With prefix ARG, change that many days."
13549 (interactive "p")
13550 (if (and (not (org-at-timestamp-p t))
13551 (org-on-heading-p))
13552 (org-todo 'down)
13553 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13555 (defun org-at-timestamp-p (&optional inactive-ok)
13556 "Determine if the cursor is in or at a timestamp."
13557 (interactive)
13558 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13559 (pos (point))
13560 (ans (or (looking-at tsr)
13561 (save-excursion
13562 (skip-chars-backward "^[<\n\r\t")
13563 (if (> (point) (point-min)) (backward-char 1))
13564 (and (looking-at tsr)
13565 (> (- (match-end 0) pos) -1))))))
13566 (and ans
13567 (boundp 'org-ts-what)
13568 (setq org-ts-what
13569 (cond
13570 ((= pos (match-beginning 0)) 'bracket)
13571 ((= pos (1- (match-end 0))) 'bracket)
13572 ((org-pos-in-match-range pos 2) 'year)
13573 ((org-pos-in-match-range pos 3) 'month)
13574 ((org-pos-in-match-range pos 7) 'hour)
13575 ((org-pos-in-match-range pos 8) 'minute)
13576 ((or (org-pos-in-match-range pos 4)
13577 (org-pos-in-match-range pos 5)) 'day)
13578 ((and (> pos (or (match-end 8) (match-end 5)))
13579 (< pos (match-end 0)))
13580 (- pos (or (match-end 8) (match-end 5))))
13581 (t 'day))))
13582 ans))
13584 (defun org-toggle-timestamp-type ()
13585 "Toggle the type (<active> or [inactive]) of a time stamp."
13586 (interactive)
13587 (when (org-at-timestamp-p t)
13588 (let ((beg (match-beginning 0)) (end (match-end 0))
13589 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13590 (save-excursion
13591 (goto-char beg)
13592 (while (re-search-forward "[][<>]" end t)
13593 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13594 t t)))
13595 (message "Timestamp is now %sactive"
13596 (if (equal (char-after beg) ?<) "" "in")))))
13598 (defun org-timestamp-change (n &optional what)
13599 "Change the date in the time stamp at point.
13600 The date will be changed by N times WHAT. WHAT can be `day', `month',
13601 `year', `minute', `second'. If WHAT is not given, the cursor position
13602 in the timestamp determines what will be changed."
13603 (let ((pos (point))
13604 with-hm inactive
13605 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13606 org-ts-what
13607 extra rem
13608 ts time time0)
13609 (if (not (org-at-timestamp-p t))
13610 (error "Not at a timestamp"))
13611 (if (and (not what) (eq org-ts-what 'bracket))
13612 (org-toggle-timestamp-type)
13613 (if (and (not what) (not (eq org-ts-what 'day))
13614 org-display-custom-times
13615 (get-text-property (point) 'display)
13616 (not (get-text-property (1- (point)) 'display)))
13617 (setq org-ts-what 'day))
13618 (setq org-ts-what (or what org-ts-what)
13619 inactive (= (char-after (match-beginning 0)) ?\[)
13620 ts (match-string 0))
13621 (replace-match "")
13622 (if (string-match
13623 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
13625 (setq extra (match-string 1 ts)))
13626 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13627 (setq with-hm t))
13628 (setq time0 (org-parse-time-string ts))
13629 (when (and (eq org-ts-what 'minute)
13630 (eq current-prefix-arg nil))
13631 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13632 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13633 (setcar (cdr time0) (+ (nth 1 time0)
13634 (if (> n 0) (- rem) (- dm rem))))))
13635 (setq time
13636 (encode-time (or (car time0) 0)
13637 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13638 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13639 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13640 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13641 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13642 (nthcdr 6 time0)))
13643 (when (and (member org-ts-what '(hour minute))
13644 extra
13645 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13646 (setq extra (org-modify-ts-extra
13647 extra
13648 (if (eq org-ts-what 'hour) 2 5)
13649 n dm)))
13650 (when (integerp org-ts-what)
13651 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13652 (if (eq what 'calendar)
13653 (let ((cal-date (org-get-date-from-calendar)))
13654 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13655 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13656 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13657 (setcar time0 (or (car time0) 0))
13658 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13659 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13660 (setq time (apply 'encode-time time0))))
13661 (setq org-last-changed-timestamp
13662 (org-insert-time-stamp time with-hm inactive nil nil extra))
13663 (org-clock-update-time-maybe)
13664 (goto-char pos)
13665 ;; Try to recenter the calendar window, if any
13666 (if (and org-calendar-follow-timestamp-change
13667 (get-buffer-window "*Calendar*" t)
13668 (memq org-ts-what '(day month year)))
13669 (org-recenter-calendar (time-to-days time))))))
13671 (defun org-modify-ts-extra (s pos n dm)
13672 "Change the different parts of the lead-time and repeat fields in timestamp."
13673 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13674 ng h m new rem)
13675 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13676 (cond
13677 ((or (org-pos-in-match-range pos 2)
13678 (org-pos-in-match-range pos 3))
13679 (setq m (string-to-number (match-string 3 s))
13680 h (string-to-number (match-string 2 s)))
13681 (if (org-pos-in-match-range pos 2)
13682 (setq h (+ h n))
13683 (setq n (* dm (org-no-warnings (signum n))))
13684 (when (not (= 0 (setq rem (% m dm))))
13685 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13686 (setq m (+ m n)))
13687 (if (< m 0) (setq m (+ m 60) h (1- h)))
13688 (if (> m 59) (setq m (- m 60) h (1+ h)))
13689 (setq h (min 24 (max 0 h)))
13690 (setq ng 1 new (format "-%02d:%02d" h m)))
13691 ((org-pos-in-match-range pos 6)
13692 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13693 ((org-pos-in-match-range pos 5)
13694 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13696 ((org-pos-in-match-range pos 9)
13697 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13698 ((org-pos-in-match-range pos 8)
13699 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13701 (when ng
13702 (setq s (concat
13703 (substring s 0 (match-beginning ng))
13705 (substring s (match-end ng))))))
13708 (defun org-recenter-calendar (date)
13709 "If the calendar is visible, recenter it to DATE."
13710 (let* ((win (selected-window))
13711 (cwin (get-buffer-window "*Calendar*" t))
13712 (calendar-move-hook nil))
13713 (when cwin
13714 (select-window cwin)
13715 (calendar-goto-date (if (listp date) date
13716 (calendar-gregorian-from-absolute date)))
13717 (select-window win))))
13719 (defun org-goto-calendar (&optional arg)
13720 "Go to the Emacs calendar at the current date.
13721 If there is a time stamp in the current line, go to that date.
13722 A prefix ARG can be used to force the current date."
13723 (interactive "P")
13724 (let ((tsr org-ts-regexp) diff
13725 (calendar-move-hook nil)
13726 (calendar-view-holidays-initially-flag nil)
13727 (view-calendar-holidays-initially nil)
13728 (calendar-view-diary-initially-flag nil)
13729 (view-diary-entries-initially nil))
13730 (if (or (org-at-timestamp-p)
13731 (save-excursion
13732 (beginning-of-line 1)
13733 (looking-at (concat ".*" tsr))))
13734 (let ((d1 (time-to-days (current-time)))
13735 (d2 (time-to-days
13736 (org-time-string-to-time (match-string 1)))))
13737 (setq diff (- d2 d1))))
13738 (calendar)
13739 (calendar-goto-today)
13740 (if (and diff (not arg)) (calendar-forward-day diff))))
13742 (defun org-get-date-from-calendar ()
13743 "Return a list (month day year) of date at point in calendar."
13744 (with-current-buffer "*Calendar*"
13745 (save-match-data
13746 (calendar-cursor-to-date))))
13748 (defun org-date-from-calendar ()
13749 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13750 If there is already a time stamp at the cursor position, update it."
13751 (interactive)
13752 (if (org-at-timestamp-p t)
13753 (org-timestamp-change 0 'calendar)
13754 (let ((cal-date (org-get-date-from-calendar)))
13755 (org-insert-time-stamp
13756 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13758 (defun org-minutes-to-hh:mm-string (m)
13759 "Compute H:MM from a number of minutes."
13760 (let ((h (/ m 60)))
13761 (setq m (- m (* 60 h)))
13762 (format org-time-clocksum-format h m)))
13764 (defun org-hh:mm-string-to-minutes (s)
13765 "Convert a string H:MM to a number of minutes.
13766 If the string is just a number, interprete it as minutes.
13767 In fact, the first hh:mm or number in the string will be taken,
13768 there can be extra stuff in the string.
13769 If no number is found, the return value is 0."
13770 (cond
13771 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13772 (+ (* (string-to-number (match-string 1 s)) 60)
13773 (string-to-number (match-string 2 s))))
13774 ((string-match "\\([0-9]+\\)" s)
13775 (string-to-number (match-string 1 s)))
13776 (t 0)))
13778 ;;;; Files
13780 (defun org-save-all-org-buffers ()
13781 "Save all Org-mode buffers without user confirmation."
13782 (interactive)
13783 (message "Saving all Org-mode buffers...")
13784 (save-some-buffers t 'org-mode-p)
13785 (when (featurep 'org-id) (org-id-locations-save))
13786 (message "Saving all Org-mode buffers... done"))
13788 (defun org-revert-all-org-buffers ()
13789 "Revert all Org-mode buffers.
13790 Prompt for confirmation when there are unsaved changes.
13791 Be sure you know what you are doing before letting this function
13792 overwrite your changes.
13794 This function is useful in a setup where one tracks org files
13795 with a version control system, to revert on one machine after pulling
13796 changes from another. I believe the procedure must be like this:
13798 1. M-x org-save-all-org-buffers
13799 2. Pull changes from the other machine, resolve conflicts
13800 3. M-x org-revert-all-org-buffers"
13801 (interactive)
13802 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13803 (error "Abort"))
13804 (save-excursion
13805 (save-window-excursion
13806 (mapc
13807 (lambda (b)
13808 (when (and (with-current-buffer b (org-mode-p))
13809 (with-current-buffer b buffer-file-name))
13810 (switch-to-buffer b)
13811 (revert-buffer t 'no-confirm)))
13812 (buffer-list))
13813 (when (and (featurep 'org-id) org-id-track-globally)
13814 (org-id-locations-load)))))
13816 ;;;; Agenda files
13818 ;;;###autoload
13819 (defun org-iswitchb (&optional arg)
13820 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
13821 With a prefix argument, restrict available to files.
13822 With two prefix arguments, restrict available buffers to agenda files."
13823 (interactive "P")
13824 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13825 ((equal arg '(16)) (org-buffer-list 'agenda))
13826 (t (org-buffer-list)))))
13827 (switch-to-buffer
13828 (org-icompleting-read "Org buffer: "
13829 (mapcar 'list (mapcar 'buffer-name blist))
13830 nil t))))
13832 ;;;###autoload
13833 (defalias 'org-ido-switchb 'org-iswitchb)
13835 (defun org-buffer-list (&optional predicate exclude-tmp)
13836 "Return a list of Org buffers.
13837 PREDICATE can be `export', `files' or `agenda'.
13839 export restrict the list to Export buffers.
13840 files restrict the list to buffers visiting Org files.
13841 agenda restrict the list to buffers visiting agenda files.
13843 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13844 (let* ((bfn nil)
13845 (agenda-files (and (eq predicate 'agenda)
13846 (mapcar 'file-truename (org-agenda-files t))))
13847 (filter
13848 (cond
13849 ((eq predicate 'files)
13850 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13851 ((eq predicate 'export)
13852 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13853 ((eq predicate 'agenda)
13854 (lambda (b)
13855 (with-current-buffer b
13856 (and (eq major-mode 'org-mode)
13857 (setq bfn (buffer-file-name b))
13858 (member (file-truename bfn) agenda-files)))))
13859 (t (lambda (b) (with-current-buffer b
13860 (or (eq major-mode 'org-mode)
13861 (string-match "\*Org .*Export"
13862 (buffer-name b)))))))))
13863 (delq nil
13864 (mapcar
13865 (lambda(b)
13866 (if (and (funcall filter b)
13867 (or (not exclude-tmp)
13868 (not (string-match "tmp" (buffer-name b)))))
13870 nil))
13871 (buffer-list)))))
13873 (defun org-agenda-files (&optional unrestricted archives)
13874 "Get the list of agenda files.
13875 Optional UNRESTRICTED means return the full list even if a restriction
13876 is currently in place.
13877 When ARCHIVES is t, include all archive files hat are really being
13878 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13879 `org-agenda-archives-mode' is t."
13880 (let ((files
13881 (cond
13882 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13883 ((stringp org-agenda-files) (org-read-agenda-file-list))
13884 ((listp org-agenda-files) org-agenda-files)
13885 (t (error "Invalid value of `org-agenda-files'")))))
13886 (setq files (apply 'append
13887 (mapcar (lambda (f)
13888 (if (file-directory-p f)
13889 (directory-files
13890 f t org-agenda-file-regexp)
13891 (list f)))
13892 files)))
13893 (when org-agenda-skip-unavailable-files
13894 (setq files (delq nil
13895 (mapcar (function
13896 (lambda (file)
13897 (and (file-readable-p file) file)))
13898 files))))
13899 (when (or (eq archives t)
13900 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13901 (setq files (org-add-archive-files files)))
13902 files))
13904 (defun org-edit-agenda-file-list ()
13905 "Edit the list of agenda files.
13906 Depending on setup, this either uses customize to edit the variable
13907 `org-agenda-files', or it visits the file that is holding the list. In the
13908 latter case, the buffer is set up in a way that saving it automatically kills
13909 the buffer and restores the previous window configuration."
13910 (interactive)
13911 (if (stringp org-agenda-files)
13912 (let ((cw (current-window-configuration)))
13913 (find-file org-agenda-files)
13914 (org-set-local 'org-window-configuration cw)
13915 (org-add-hook 'after-save-hook
13916 (lambda ()
13917 (set-window-configuration
13918 (prog1 org-window-configuration
13919 (kill-buffer (current-buffer))))
13920 (org-install-agenda-files-menu)
13921 (message "New agenda file list installed"))
13922 nil 'local)
13923 (message "%s" (substitute-command-keys
13924 "Edit list and finish with \\[save-buffer]")))
13925 (customize-variable 'org-agenda-files)))
13927 (defun org-store-new-agenda-file-list (list)
13928 "Set new value for the agenda file list and save it correctly."
13929 (if (stringp org-agenda-files)
13930 (let ((f org-agenda-files) b)
13931 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13932 (with-temp-file f
13933 (insert (mapconcat 'identity list "\n") "\n")))
13934 (let ((org-mode-hook nil) (org-inhibit-startup t)
13935 (org-insert-mode-line-in-empty-file nil))
13936 (setq org-agenda-files list)
13937 (customize-save-variable 'org-agenda-files org-agenda-files))))
13939 (defun org-read-agenda-file-list ()
13940 "Read the list of agenda files from a file."
13941 (when (file-directory-p org-agenda-files)
13942 (error "`org-agenda-files' cannot be a single directory"))
13943 (when (stringp org-agenda-files)
13944 (with-temp-buffer
13945 (insert-file-contents org-agenda-files)
13946 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13949 ;;;###autoload
13950 (defun org-cycle-agenda-files ()
13951 "Cycle through the files in `org-agenda-files'.
13952 If the current buffer visits an agenda file, find the next one in the list.
13953 If the current buffer does not, find the first agenda file."
13954 (interactive)
13955 (let* ((fs (org-agenda-files t))
13956 (files (append fs (list (car fs))))
13957 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13958 file)
13959 (unless files (error "No agenda files"))
13960 (catch 'exit
13961 (while (setq file (pop files))
13962 (if (equal (file-truename file) tcf)
13963 (when (car files)
13964 (find-file (car files))
13965 (throw 'exit t))))
13966 (find-file (car fs)))
13967 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13969 (defun org-agenda-file-to-front (&optional to-end)
13970 "Move/add the current file to the top of the agenda file list.
13971 If the file is not present in the list, it is added to the front. If it is
13972 present, it is moved there. With optional argument TO-END, add/move to the
13973 end of the list."
13974 (interactive "P")
13975 (let ((org-agenda-skip-unavailable-files nil)
13976 (file-alist (mapcar (lambda (x)
13977 (cons (file-truename x) x))
13978 (org-agenda-files t)))
13979 (ctf (file-truename buffer-file-name))
13980 x had)
13981 (setq x (assoc ctf file-alist) had x)
13983 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13984 (if to-end
13985 (setq file-alist (append (delq x file-alist) (list x)))
13986 (setq file-alist (cons x (delq x file-alist))))
13987 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13988 (org-install-agenda-files-menu)
13989 (message "File %s to %s of agenda file list"
13990 (if had "moved" "added") (if to-end "end" "front"))))
13992 (defun org-remove-file (&optional file)
13993 "Remove current file from the list of files in variable `org-agenda-files'.
13994 These are the files which are being checked for agenda entries.
13995 Optional argument FILE means, use this file instead of the current."
13996 (interactive)
13997 (let* ((org-agenda-skip-unavailable-files nil)
13998 (file (or file buffer-file-name))
13999 (true-file (file-truename file))
14000 (afile (abbreviate-file-name file))
14001 (files (delq nil (mapcar
14002 (lambda (x)
14003 (if (equal true-file
14004 (file-truename x))
14005 nil x))
14006 (org-agenda-files t)))))
14007 (if (not (= (length files) (length (org-agenda-files t))))
14008 (progn
14009 (org-store-new-agenda-file-list files)
14010 (org-install-agenda-files-menu)
14011 (message "Removed file: %s" afile))
14012 (message "File was not in list: %s (not removed)" afile))))
14014 (defun org-file-menu-entry (file)
14015 (vector file (list 'find-file file) t))
14017 (defun org-check-agenda-file (file)
14018 "Make sure FILE exists. If not, ask user what to do."
14019 (when (not (file-exists-p file))
14020 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14021 (abbreviate-file-name file))
14022 (let ((r (downcase (read-char-exclusive))))
14023 (cond
14024 ((equal r ?r)
14025 (org-remove-file file)
14026 (throw 'nextfile t))
14027 (t (error "Abort"))))))
14029 (defun org-get-agenda-file-buffer (file)
14030 "Get a buffer visiting FILE. If the buffer needs to be created, add
14031 it to the list of buffers which might be released later."
14032 (let ((buf (org-find-base-buffer-visiting file)))
14033 (if buf
14034 buf ; just return it
14035 ;; Make a new buffer and remember it
14036 (setq buf (find-file-noselect file))
14037 (if buf (push buf org-agenda-new-buffers))
14038 buf)))
14040 (defun org-release-buffers (blist)
14041 "Release all buffers in list, asking the user for confirmation when needed.
14042 When a buffer is unmodified, it is just killed. When modified, it is saved
14043 \(if the user agrees) and then killed."
14044 (let (buf file)
14045 (while (setq buf (pop blist))
14046 (setq file (buffer-file-name buf))
14047 (when (and (buffer-modified-p buf)
14048 file
14049 (y-or-n-p (format "Save file %s? " file)))
14050 (with-current-buffer buf (save-buffer)))
14051 (kill-buffer buf))))
14053 (defun org-prepare-agenda-buffers (files)
14054 "Create buffers for all agenda files, protect archived trees and comments."
14055 (interactive)
14056 (let ((pa '(:org-archived t))
14057 (pc '(:org-comment t))
14058 (pall '(:org-archived t :org-comment t))
14059 (inhibit-read-only t)
14060 (rea (concat ":" org-archive-tag ":"))
14061 bmp file re)
14062 (save-excursion
14063 (save-restriction
14064 (while (setq file (pop files))
14065 (catch 'nextfile
14066 (if (bufferp file)
14067 (set-buffer file)
14068 (org-check-agenda-file file)
14069 (set-buffer (org-get-agenda-file-buffer file)))
14070 (widen)
14071 (setq bmp (buffer-modified-p))
14072 (org-refresh-category-properties)
14073 (setq org-todo-keywords-for-agenda
14074 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14075 (setq org-done-keywords-for-agenda
14076 (append org-done-keywords-for-agenda org-done-keywords))
14077 (setq org-todo-keyword-alist-for-agenda
14078 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14079 (setq org-drawers-for-agenda
14080 (append org-drawers-for-agenda org-drawers))
14081 (setq org-tag-alist-for-agenda
14082 (append org-tag-alist-for-agenda org-tag-alist))
14084 (save-excursion
14085 (remove-text-properties (point-min) (point-max) pall)
14086 (when org-agenda-skip-archived-trees
14087 (goto-char (point-min))
14088 (while (re-search-forward rea nil t)
14089 (if (org-on-heading-p t)
14090 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14091 (goto-char (point-min))
14092 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14093 (while (re-search-forward re nil t)
14094 (add-text-properties
14095 (match-beginning 0) (org-end-of-subtree t) pc)))
14096 (set-buffer-modified-p bmp)))))
14097 (setq org-todo-keyword-alist-for-agenda
14098 (org-uniquify org-todo-keyword-alist-for-agenda)
14099 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14101 ;;;; Embedded LaTeX
14103 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14104 "Keymap for the minor `org-cdlatex-mode'.")
14106 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14107 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14108 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14109 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14110 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14112 (defvar org-cdlatex-texmathp-advice-is-done nil
14113 "Flag remembering if we have applied the advice to texmathp already.")
14115 (define-minor-mode org-cdlatex-mode
14116 "Toggle the minor `org-cdlatex-mode'.
14117 This mode supports entering LaTeX environment and math in LaTeX fragments
14118 in Org-mode.
14119 \\{org-cdlatex-mode-map}"
14120 nil " OCDL" nil
14121 (when org-cdlatex-mode (require 'cdlatex))
14122 (unless org-cdlatex-texmathp-advice-is-done
14123 (setq org-cdlatex-texmathp-advice-is-done t)
14124 (defadvice texmathp (around org-math-always-on activate)
14125 "Always return t in org-mode buffers.
14126 This is because we want to insert math symbols without dollars even outside
14127 the LaTeX math segments. If Orgmode thinks that point is actually inside
14128 an embedded LaTeX fragment, let texmathp do its job.
14129 \\[org-cdlatex-mode-map]"
14130 (interactive)
14131 (let (p)
14132 (cond
14133 ((not (org-mode-p)) ad-do-it)
14134 ((eq this-command 'cdlatex-math-symbol)
14135 (setq ad-return-value t
14136 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14138 (let ((p (org-inside-LaTeX-fragment-p)))
14139 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14140 (setq ad-return-value t
14141 texmathp-why '("Org-mode embedded math" . 0))
14142 (if p ad-do-it)))))))))
14144 (defun turn-on-org-cdlatex ()
14145 "Unconditionally turn on `org-cdlatex-mode'."
14146 (org-cdlatex-mode 1))
14148 (defun org-inside-LaTeX-fragment-p ()
14149 "Test if point is inside a LaTeX fragment.
14150 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14151 sequence appearing also before point.
14152 Even though the matchers for math are configurable, this function assumes
14153 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14154 delimiters are skipped when they have been removed by customization.
14155 The return value is nil, or a cons cell with the delimiter and
14156 and the position of this delimiter.
14158 This function does a reasonably good job, but can locally be fooled by
14159 for example currency specifications. For example it will assume being in
14160 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14161 fragments that are properly closed, but during editing, we have to live
14162 with the uncertainty caused by missing closing delimiters. This function
14163 looks only before point, not after."
14164 (catch 'exit
14165 (let ((pos (point))
14166 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14167 (lim (progn
14168 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14169 (point)))
14170 dd-on str (start 0) m re)
14171 (goto-char pos)
14172 (when dodollar
14173 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14174 re (nth 1 (assoc "$" org-latex-regexps)))
14175 (while (string-match re str start)
14176 (cond
14177 ((= (match-end 0) (length str))
14178 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14179 ((= (match-end 0) (- (length str) 5))
14180 (throw 'exit nil))
14181 (t (setq start (match-end 0))))))
14182 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14183 (goto-char pos)
14184 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14185 (and (match-beginning 2) (throw 'exit nil))
14186 ;; count $$
14187 (while (re-search-backward "\\$\\$" lim t)
14188 (setq dd-on (not dd-on)))
14189 (goto-char pos)
14190 (if dd-on (cons "$$" m))))))
14193 (defun org-try-cdlatex-tab ()
14194 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14195 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14196 - inside a LaTeX fragment, or
14197 - after the first word in a line, where an abbreviation expansion could
14198 insert a LaTeX environment."
14199 (when org-cdlatex-mode
14200 (cond
14201 ((save-excursion
14202 (skip-chars-backward "a-zA-Z0-9*")
14203 (skip-chars-backward " \t")
14204 (bolp))
14205 (cdlatex-tab) t)
14206 ((org-inside-LaTeX-fragment-p)
14207 (cdlatex-tab) t)
14208 (t nil))))
14210 (defun org-cdlatex-underscore-caret (&optional arg)
14211 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14212 Revert to the normal definition outside of these fragments."
14213 (interactive "P")
14214 (if (org-inside-LaTeX-fragment-p)
14215 (call-interactively 'cdlatex-sub-superscript)
14216 (let (org-cdlatex-mode)
14217 (call-interactively (key-binding (vector last-input-event))))))
14219 (defun org-cdlatex-math-modify (&optional arg)
14220 "Execute `cdlatex-math-modify' in LaTeX fragments.
14221 Revert to the normal definition outside of these fragments."
14222 (interactive "P")
14223 (if (org-inside-LaTeX-fragment-p)
14224 (call-interactively 'cdlatex-math-modify)
14225 (let (org-cdlatex-mode)
14226 (call-interactively (key-binding (vector last-input-event))))))
14228 (defvar org-latex-fragment-image-overlays nil
14229 "List of overlays carrying the images of latex fragments.")
14230 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14232 (defun org-remove-latex-fragment-image-overlays ()
14233 "Remove all overlays with LaTeX fragment images in current buffer."
14234 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14235 (setq org-latex-fragment-image-overlays nil))
14237 (defun org-preview-latex-fragment (&optional subtree)
14238 "Preview the LaTeX fragment at point, or all locally or globally.
14239 If the cursor is in a LaTeX fragment, create the image and overlay
14240 it over the source code. If there is no fragment at point, display
14241 all fragments in the current text, from one headline to the next. With
14242 prefix SUBTREE, display all fragments in the current subtree. With a
14243 double prefix `C-u C-u', or when the cursor is before the first headline,
14244 display all fragments in the buffer.
14245 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14246 (interactive "P")
14247 (org-remove-latex-fragment-image-overlays)
14248 (save-excursion
14249 (save-restriction
14250 (let (beg end at msg)
14251 (cond
14252 ((or (equal subtree '(16))
14253 (not (save-excursion
14254 (re-search-backward (concat "^" outline-regexp) nil t))))
14255 (setq beg (point-min) end (point-max)
14256 msg "Creating images for buffer...%s"))
14257 ((equal subtree '(4))
14258 (org-back-to-heading)
14259 (setq beg (point) end (org-end-of-subtree t)
14260 msg "Creating images for subtree...%s"))
14262 (if (setq at (org-inside-LaTeX-fragment-p))
14263 (goto-char (max (point-min) (- (cdr at) 2)))
14264 (org-back-to-heading))
14265 (setq beg (point) end (progn (outline-next-heading) (point))
14266 msg (if at "Creating image...%s"
14267 "Creating images for entry...%s"))))
14268 (message msg "")
14269 (narrow-to-region beg end)
14270 (goto-char beg)
14271 (org-format-latex
14272 (concat "ltxpng/" (file-name-sans-extension
14273 (file-name-nondirectory
14274 buffer-file-name)))
14275 default-directory 'overlays msg at 'forbuffer)
14276 (message msg "done. Use `C-c C-c' to remove images.")))))
14278 (defvar org-latex-regexps
14279 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14280 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14281 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14282 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14283 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14284 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14285 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14286 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14287 "Regular expressions for matching embedded LaTeX.")
14289 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14290 "Replace LaTeX fragments with links to an image, and produce images.
14291 Some of the options can be changed using the variable
14292 `org-format-latex-options'."
14293 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14294 (let* ((prefixnodir (file-name-nondirectory prefix))
14295 (absprefix (expand-file-name prefix dir))
14296 (todir (file-name-directory absprefix))
14297 (opt org-format-latex-options)
14298 (matchers (plist-get opt :matchers))
14299 (re-list org-latex-regexps)
14300 (cnt 0) txt link beg end re e checkdir
14301 executables-checked
14302 m n block linkfile movefile ov)
14303 ;; Check if there are old images files with this prefix, and remove them
14304 (when (file-directory-p todir)
14305 (mapc 'delete-file
14306 (directory-files
14307 todir 'full
14308 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
14309 ;; Check the different regular expressions
14310 (while (setq e (pop re-list))
14311 (setq m (car e) re (nth 1 e) n (nth 2 e)
14312 block (if (nth 3 e) "\n\n" ""))
14313 (when (member m matchers)
14314 (goto-char (point-min))
14315 (while (re-search-forward re nil t)
14316 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14317 (not (get-text-property (match-beginning n)
14318 'org-protected))
14319 (or (not overlays)
14320 (not (eq (get-char-property (match-beginning n)
14321 'org-overlay-type)
14322 'org-latex-overlay))))
14323 (setq txt (match-string n)
14324 beg (match-beginning n) end (match-end n)
14325 cnt (1+ cnt)
14326 linkfile (format "%s_%04d.png" prefix cnt)
14327 movefile (format "%s_%04d.png" absprefix cnt)
14328 link (concat block "[[file:" linkfile "]]" block))
14329 (if msg (message msg cnt))
14330 (goto-char beg)
14331 (unless checkdir ; make sure the directory exists
14332 (setq checkdir t)
14333 (or (file-directory-p todir) (make-directory todir)))
14335 (unless executables-checked
14336 (org-check-external-command
14337 "latex" "needed to convert LaTeX fragments to images")
14338 (org-check-external-command
14339 "dvipng" "needed to convert LaTeX fragments to images")
14340 (setq executables-checked t))
14342 (org-create-formula-image
14343 txt movefile opt forbuffer)
14344 (if overlays
14345 (progn
14346 (mapc (lambda (o)
14347 (if (eq (org-overlay-get o 'org-overlay-type)
14348 'org-latex-overlay)
14349 (org-delete-overlay o)))
14350 (org-overlays-in beg end))
14351 (setq ov (org-make-overlay beg end))
14352 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14353 (if (featurep 'xemacs)
14354 (progn
14355 (org-overlay-put ov 'invisible t)
14356 (org-overlay-put
14357 ov 'end-glyph
14358 (make-glyph (vector 'png :file movefile))))
14359 (org-overlay-put
14360 ov 'display
14361 (list 'image :type 'png :file movefile :ascent 'center)))
14362 (push ov org-latex-fragment-image-overlays)
14363 (goto-char end))
14364 (delete-region beg end)
14365 (insert link))))))))
14367 (defvar org-export-latex-packages-alist) ;; defined in org-latex.el
14368 ;; This function borrows from Ganesh Swami's latex2png.el
14369 (defun org-create-formula-image (string tofile options buffer)
14370 "This calls dvipng."
14371 (require 'org-latex)
14372 (let* ((tmpdir (if (featurep 'xemacs)
14373 (temp-directory)
14374 temporary-file-directory))
14375 (texfilebase (make-temp-name
14376 (expand-file-name "orgtex" tmpdir)))
14377 (texfile (concat texfilebase ".tex"))
14378 (dvifile (concat texfilebase ".dvi"))
14379 (pngfile (concat texfilebase ".png"))
14380 (fnh (if (featurep 'xemacs)
14381 (font-height (get-face-font 'default))
14382 (face-attribute 'default :height nil)))
14383 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14384 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14385 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14386 "Black"))
14387 (bg (or (plist-get options (if buffer :background :html-background))
14388 "Transparent")))
14389 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14390 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14391 (with-temp-file texfile
14392 (insert org-format-latex-header
14393 (if org-export-latex-packages-alist
14394 (concat "\n"
14395 (mapconcat (lambda(p)
14396 (if (equal "" (car p))
14397 (format "\\usepackage{%s}" (cadr p))
14398 (format "\\usepackage[%s]{%s}"
14399 (car p) (cadr p))))
14400 org-export-latex-packages-alist "\n"))
14402 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14403 (let ((dir default-directory))
14404 (condition-case nil
14405 (progn
14406 (cd tmpdir)
14407 (call-process "latex" nil nil nil texfile))
14408 (error nil))
14409 (cd dir))
14410 (if (not (file-exists-p dvifile))
14411 (progn (message "Failed to create dvi file from %s" texfile) nil)
14412 (condition-case nil
14413 (call-process "dvipng" nil nil nil
14414 "-fg" fg "-bg" bg
14415 "-D" dpi
14416 ;;"-x" scale "-y" scale
14417 "-T" "tight"
14418 "-o" pngfile
14419 dvifile)
14420 (error nil))
14421 (if (not (file-exists-p pngfile))
14422 (progn (message "Failed to create png file from %s" texfile) nil)
14423 ;; Use the requested file name and clean up
14424 (copy-file pngfile tofile 'replace)
14425 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14426 (delete-file (concat texfilebase e)))
14427 pngfile))))
14429 (defun org-dvipng-color (attr)
14430 "Return an rgb color specification for dvipng."
14431 (apply 'format "rgb %s %s %s"
14432 (mapcar 'org-normalize-color
14433 (color-values (face-attribute 'default attr nil)))))
14435 (defun org-normalize-color (value)
14436 "Return string to be used as color value for an RGB component."
14437 (format "%g" (/ value 65535.0)))
14439 ;;;; Key bindings
14441 ;; Make `C-c C-x' a prefix key
14442 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14444 ;; TAB key with modifiers
14445 (org-defkey org-mode-map "\C-i" 'org-cycle)
14446 (org-defkey org-mode-map [(tab)] 'org-cycle)
14447 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14448 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14449 (org-defkey org-mode-map "\M-\t" 'org-complete)
14450 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14451 ;; The following line is necessary under Suse GNU/Linux
14452 (unless (featurep 'xemacs)
14453 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14454 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14455 (define-key org-mode-map [backtab] 'org-shifttab)
14457 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14458 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14459 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14461 ;; Cursor keys with modifiers
14462 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14463 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14464 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14465 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14467 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14468 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14469 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14470 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14472 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14473 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14474 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14475 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14477 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14478 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14480 ;;; Extra keys for tty access.
14481 ;; We only set them when really needed because otherwise the
14482 ;; menus don't show the simple keys
14484 (when (or org-use-extra-keys
14485 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14486 (not window-system))
14487 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14488 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14489 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14490 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14491 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14492 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14493 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14494 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14495 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14496 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14497 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14498 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14499 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14500 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14501 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14502 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14503 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14504 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14505 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14506 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14507 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14508 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14509 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14510 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14511 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14512 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14513 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14514 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14516 ;; All the other keys
14518 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14519 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14520 (if (boundp 'narrow-map)
14521 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14522 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14523 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14524 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14525 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14526 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14527 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
14528 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14529 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14530 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14531 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14532 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14533 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14534 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14535 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14536 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14537 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14538 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14539 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14540 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14541 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14542 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14543 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14544 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14545 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14546 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14547 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14548 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14549 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14550 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14551 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14552 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14553 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14554 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14555 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14556 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14557 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14558 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14559 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14560 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14561 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14562 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14563 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14564 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14565 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14566 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14567 (org-defkey org-mode-map "\C-c^" 'org-sort)
14568 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14569 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14570 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
14571 (org-defkey org-mode-map "\C-m" 'org-return)
14572 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14573 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14574 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14575 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14576 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14577 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14578 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14579 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14580 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14581 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14582 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14583 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14584 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14585 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14586 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14587 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14588 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14589 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
14590 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
14591 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14592 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14594 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14595 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14596 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14597 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14599 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14600 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14601 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14602 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14603 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14604 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14605 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14606 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14607 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14608 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14609 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14610 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
14611 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14612 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14613 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14615 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14616 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14617 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14618 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14620 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14622 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14624 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14625 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14627 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14630 (when (featurep 'xemacs)
14631 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14634 (defconst org-speed-commands-default
14636 ("c" . org-cycle)
14637 ("C" . org-shifttab)
14638 ("n" . outline-next-visible-heading)
14639 ("p" . outline-previous-visible-heading)
14640 ("f" . org-forward-same-level)
14641 ("b" . org-backward-same-level)
14642 ("u" . outline-up-heading)
14643 ("U" . org-shiftmetaup)
14644 ("D" . org-shiftmetadown)
14645 ("r" . org-metaright)
14646 ("l" . org-metaleft)
14647 ("R" . org-shiftmetaright)
14648 ("L" . org-shiftmetaleft)
14649 ("i" . (progn (forward-char 1) (call-interactively
14650 'org-insert-heading-respect-content)))
14651 ("o" . org-open-at-point)
14652 ("t" . org-todo)
14653 ("j" . org-goto)
14654 ("1" . (org-priority ?A))
14655 ("2" . (org-priority ?B))
14656 ("3" . (org-priority ?C))
14657 ("." . outline-mark-subtree)
14658 ("^" . org-sort)
14659 ("w" . org-refile)
14660 ("a" . org-archive-subtree-default-with-confirmation)
14661 ("/" . org-sparse-tree)
14662 ("?" . org-speed-command-help)
14664 "The default speed commands.")
14666 (defun org-print-speed-command (e)
14667 (princ (car e))
14668 (princ " ")
14669 (if (symbolp (cdr e))
14670 (princ (symbol-name (cdr e)))
14671 (prin1 (cdr e)))
14672 (princ "\n"))
14674 (defun org-speed-command-help ()
14675 "Show the available speed commands."
14676 (interactive)
14677 (if (not org-use-speed-commands)
14678 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
14679 (with-output-to-temp-buffer "*Help*"
14680 (princ "Speed commands\n==============\n")
14681 (mapc 'org-print-speed-command org-speed-commands-user)
14682 (princ "\n")
14683 (mapc 'org-print-speed-command org-speed-commands-default))))
14685 (defvar org-self-insert-command-undo-counter 0)
14687 (defvar org-table-auto-blank-field) ; defined in org-table.el
14688 (defvar org-speed-command nil)
14689 (defun org-self-insert-command (N)
14690 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14691 If the cursor is in a table looking at whitespace, the whitespace is
14692 overwritten, and the table is not marked as requiring realignment."
14693 (interactive "p")
14694 (cond
14695 ((and org-use-speed-commands
14696 (bolp)
14697 (looking-at outline-regexp)
14698 (setq
14699 org-speed-command
14700 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
14701 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
14702 (cond
14703 ((commandp org-speed-command)
14704 (setq this-command org-speed-command)
14705 (call-interactively org-speed-command))
14706 ((functionp org-speed-command)
14707 (funcall org-speed-command))
14708 ((and org-speed-command (listp org-speed-command))
14709 (eval org-speed-command))
14710 (t (let (org-use-speed-commands)
14711 (call-interactively 'org-self-insert-command)))))
14712 ((and
14713 (org-table-p)
14714 (progn
14715 ;; check if we blank the field, and if that triggers align
14716 (and (featurep 'org-table) org-table-auto-blank-field
14717 (member last-command
14718 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
14719 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14720 ;; got extra space, this field does not determine column width
14721 (let (org-table-may-need-update) (org-table-blank-field))
14722 ;; no extra space, this field may determine column width
14723 (org-table-blank-field)))
14725 (eq N 1)
14726 (looking-at "[^|\n]* |"))
14727 (let (org-table-may-need-update)
14728 (goto-char (1- (match-end 0)))
14729 (delete-backward-char 1)
14730 (goto-char (match-beginning 0))
14731 (self-insert-command N)))
14733 (setq org-table-may-need-update t)
14734 (self-insert-command N)
14735 (org-fix-tags-on-the-fly)
14736 (if org-self-insert-cluster-for-undo
14737 (if (not (eq last-command 'org-self-insert-command))
14738 (setq org-self-insert-command-undo-counter 1)
14739 (if (>= org-self-insert-command-undo-counter 20)
14740 (setq org-self-insert-command-undo-counter 1)
14741 (and (> org-self-insert-command-undo-counter 0)
14742 buffer-undo-list
14743 (not (cadr buffer-undo-list)) ; remove nil entry
14744 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14745 (setq org-self-insert-command-undo-counter
14746 (1+ org-self-insert-command-undo-counter))))))))
14748 (defun org-fix-tags-on-the-fly ()
14749 (when (and (equal (char-after (point-at-bol)) ?*)
14750 (org-on-heading-p))
14751 (org-align-tags-here org-tags-column)))
14753 (defun org-delete-backward-char (N)
14754 "Like `delete-backward-char', insert whitespace at field end in tables.
14755 When deleting backwards, in tables this function will insert whitespace in
14756 front of the next \"|\" separator, to keep the table aligned. The table will
14757 still be marked for re-alignment if the field did fill the entire column,
14758 because, in this case the deletion might narrow the column."
14759 (interactive "p")
14760 (if (and (org-table-p)
14761 (eq N 1)
14762 (string-match "|" (buffer-substring (point-at-bol) (point)))
14763 (looking-at ".*?|"))
14764 (let ((pos (point))
14765 (noalign (looking-at "[^|\n\r]* |"))
14766 (c org-table-may-need-update))
14767 (backward-delete-char N)
14768 (skip-chars-forward "^|")
14769 (insert " ")
14770 (goto-char (1- pos))
14771 ;; noalign: if there were two spaces at the end, this field
14772 ;; does not determine the width of the column.
14773 (if noalign (setq org-table-may-need-update c)))
14774 (backward-delete-char N)
14775 (org-fix-tags-on-the-fly)))
14777 (defun org-delete-char (N)
14778 "Like `delete-char', but insert whitespace at field end in tables.
14779 When deleting characters, in tables this function will insert whitespace in
14780 front of the next \"|\" separator, to keep the table aligned. The table will
14781 still be marked for re-alignment if the field did fill the entire column,
14782 because, in this case the deletion might narrow the column."
14783 (interactive "p")
14784 (if (and (org-table-p)
14785 (not (bolp))
14786 (not (= (char-after) ?|))
14787 (eq N 1))
14788 (if (looking-at ".*?|")
14789 (let ((pos (point))
14790 (noalign (looking-at "[^|\n\r]* |"))
14791 (c org-table-may-need-update))
14792 (replace-match (concat
14793 (substring (match-string 0) 1 -1)
14794 " |"))
14795 (goto-char pos)
14796 ;; noalign: if there were two spaces at the end, this field
14797 ;; does not determine the width of the column.
14798 (if noalign (setq org-table-may-need-update c)))
14799 (delete-char N))
14800 (delete-char N)
14801 (org-fix-tags-on-the-fly)))
14803 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14804 (put 'org-self-insert-command 'delete-selection t)
14805 (put 'orgtbl-self-insert-command 'delete-selection t)
14806 (put 'org-delete-char 'delete-selection 'supersede)
14807 (put 'org-delete-backward-char 'delete-selection 'supersede)
14808 (put 'org-yank 'delete-selection 'yank)
14810 ;; Make `flyspell-mode' delay after some commands
14811 (put 'org-self-insert-command 'flyspell-delayed t)
14812 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14813 (put 'org-delete-char 'flyspell-delayed t)
14814 (put 'org-delete-backward-char 'flyspell-delayed t)
14816 ;; Make pabbrev-mode expand after org-mode commands
14817 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14818 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14820 ;; How to do this: Measure non-white length of current string
14821 ;; If equal to column width, we should realign.
14823 (defun org-remap (map &rest commands)
14824 "In MAP, remap the functions given in COMMANDS.
14825 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14826 (let (new old)
14827 (while commands
14828 (setq old (pop commands) new (pop commands))
14829 (if (fboundp 'command-remapping)
14830 (org-defkey map (vector 'remap old) new)
14831 (substitute-key-definition old new map global-map)))))
14833 (when (eq org-enable-table-editor 'optimized)
14834 ;; If the user wants maximum table support, we need to hijack
14835 ;; some standard editing functions
14836 (org-remap org-mode-map
14837 'self-insert-command 'org-self-insert-command
14838 'delete-char 'org-delete-char
14839 'delete-backward-char 'org-delete-backward-char)
14840 (org-defkey org-mode-map "|" 'org-force-self-insert))
14842 (defvar org-ctrl-c-ctrl-c-hook nil
14843 "Hook for functions attaching themselves to `C-c C-c'.
14844 This can be used to add additional functionality to the C-c C-c key which
14845 executes context-dependent commands.
14846 Each function will be called with no arguments. The function must check
14847 if the context is appropriate for it to act. If yes, it should do its
14848 thing and then return a non-nil value. If the context is wrong,
14849 just do nothing and return nil.")
14851 (defvar org-tab-first-hook nil
14852 "Hook for functions to attach themselves to TAB.
14853 See `org-ctrl-c-ctrl-c-hook' for more information.
14854 This hook runs as the first action when TAB is pressed, even before
14855 `org-cycle' messes around with the `outline-regexp' to cater for
14856 inline tasks and plain list item folding.
14857 If any function in this hook returns t, not other actions like table
14858 field motion visibility cycling will be done.")
14860 (defvar org-tab-after-check-for-table-hook nil
14861 "Hook for functions to attach themselves to TAB.
14862 See `org-ctrl-c-ctrl-c-hook' for more information.
14863 This hook runs after it has been established that the cursor is not in a
14864 table, but before checking if the cursor is in a headline or if global cycling
14865 should be done.
14866 If any function in this hook returns t, not other actions like visibility
14867 cycling will be done.")
14869 (defvar org-tab-after-check-for-cycling-hook nil
14870 "Hook for functions to attach themselves to TAB.
14871 See `org-ctrl-c-ctrl-c-hook' for more information.
14872 This hook runs after it has been established that not table field motion and
14873 not visibility should be done because of current context. This is probably
14874 the place where a package like yasnippets can hook in.")
14876 (defvar org-metaleft-hook nil
14877 "Hook for functions attaching themselves to `M-left'.
14878 See `org-ctrl-c-ctrl-c-hook' for more information.")
14879 (defvar org-metaright-hook nil
14880 "Hook for functions attaching themselves to `M-right'.
14881 See `org-ctrl-c-ctrl-c-hook' for more information.")
14882 (defvar org-metaup-hook nil
14883 "Hook for functions attaching themselves to `M-up'.
14884 See `org-ctrl-c-ctrl-c-hook' for more information.")
14885 (defvar org-metadown-hook nil
14886 "Hook for functions attaching themselves to `M-down'.
14887 See `org-ctrl-c-ctrl-c-hook' for more information.")
14888 (defvar org-shiftmetaleft-hook nil
14889 "Hook for functions attaching themselves to `M-S-left'.
14890 See `org-ctrl-c-ctrl-c-hook' for more information.")
14891 (defvar org-shiftmetaright-hook nil
14892 "Hook for functions attaching themselves to `M-S-right'.
14893 See `org-ctrl-c-ctrl-c-hook' for more information.")
14894 (defvar org-shiftmetaup-hook nil
14895 "Hook for functions attaching themselves to `M-S-up'.
14896 See `org-ctrl-c-ctrl-c-hook' for more information.")
14897 (defvar org-shiftmetadown-hook nil
14898 "Hook for functions attaching themselves to `M-S-down'.
14899 See `org-ctrl-c-ctrl-c-hook' for more information.")
14900 (defvar org-metareturn-hook nil
14901 "Hook for functions attaching themselves to `M-RET'.
14902 See `org-ctrl-c-ctrl-c-hook' for more information.")
14904 (defun org-modifier-cursor-error ()
14905 "Throw an error, a modified cursor command was applied in wrong context."
14906 (error "This command is active in special context like tables, headlines or items"))
14908 (defun org-shiftselect-error ()
14909 "Throw an error because Shift-Cursor command was applied in wrong context."
14910 (if (and (boundp 'shift-select-mode) shift-select-mode)
14911 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
14912 (error "This command works only in special context like headlines or timestamps")))
14914 (defun org-call-for-shift-select (cmd)
14915 (let ((this-command-keys-shift-translated t))
14916 (call-interactively cmd)))
14918 (defun org-shifttab (&optional arg)
14919 "Global visibility cycling or move to previous table field.
14920 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14921 on context.
14922 See the individual commands for more information."
14923 (interactive "P")
14924 (cond
14925 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14926 ((integerp arg)
14927 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
14928 (message "Content view to level: %d" arg)
14929 (org-content (prefix-numeric-value arg2))
14930 (setq org-cycle-global-status 'overview)))
14931 (t (call-interactively 'org-global-cycle))))
14933 (defun org-shiftmetaleft ()
14934 "Promote subtree or delete table column.
14935 Calls `org-promote-subtree', `org-outdent-item',
14936 or `org-table-delete-column', depending on context.
14937 See the individual commands for more information."
14938 (interactive)
14939 (cond
14940 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14941 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14942 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14943 ((org-at-item-p) (call-interactively 'org-outdent-item))
14944 (t (org-modifier-cursor-error))))
14946 (defun org-shiftmetaright ()
14947 "Demote subtree or insert table column.
14948 Calls `org-demote-subtree', `org-indent-item',
14949 or `org-table-insert-column', depending on context.
14950 See the individual commands for more information."
14951 (interactive)
14952 (cond
14953 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14954 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14955 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14956 ((org-at-item-p) (call-interactively 'org-indent-item))
14957 (t (org-modifier-cursor-error))))
14959 (defun org-shiftmetaup (&optional arg)
14960 "Move subtree up or kill table row.
14961 Calls `org-move-subtree-up' or `org-table-kill-row' or
14962 `org-move-item-up' depending on context. See the individual commands
14963 for more information."
14964 (interactive "P")
14965 (cond
14966 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14967 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14968 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14969 ((org-at-item-p) (call-interactively 'org-move-item-up))
14970 (t (org-modifier-cursor-error))))
14972 (defun org-shiftmetadown (&optional arg)
14973 "Move subtree down or insert table row.
14974 Calls `org-move-subtree-down' or `org-table-insert-row' or
14975 `org-move-item-down', depending on context. See the individual
14976 commands for more information."
14977 (interactive "P")
14978 (cond
14979 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14980 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14981 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14982 ((org-at-item-p) (call-interactively 'org-move-item-down))
14983 (t (org-modifier-cursor-error))))
14985 (defun org-metaleft (&optional arg)
14986 "Promote heading or move table column to left.
14987 Calls `org-do-promote' or `org-table-move-column', depending on context.
14988 With no specific context, calls the Emacs default `backward-word'.
14989 See the individual commands for more information."
14990 (interactive "P")
14991 (cond
14992 ((run-hook-with-args-until-success 'org-metaleft-hook))
14993 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14994 ((or (org-on-heading-p)
14995 (and (org-region-active-p)
14996 (save-excursion
14997 (goto-char (region-beginning))
14998 (org-on-heading-p))))
14999 (call-interactively 'org-do-promote))
15000 ((or (org-at-item-p)
15001 (and (org-region-active-p)
15002 (save-excursion
15003 (goto-char (region-beginning))
15004 (org-at-item-p))))
15005 (call-interactively 'org-outdent-item))
15006 (t (call-interactively 'backward-word))))
15008 (defun org-metaright (&optional arg)
15009 "Demote subtree or move table column to right.
15010 Calls `org-do-demote' or `org-table-move-column', depending on context.
15011 With no specific context, calls the Emacs default `forward-word'.
15012 See the individual commands for more information."
15013 (interactive "P")
15014 (cond
15015 ((run-hook-with-args-until-success 'org-metaright-hook))
15016 ((org-at-table-p) (call-interactively 'org-table-move-column))
15017 ((or (org-on-heading-p)
15018 (and (org-region-active-p)
15019 (save-excursion
15020 (goto-char (region-beginning))
15021 (org-on-heading-p))))
15022 (call-interactively 'org-do-demote))
15023 ((or (org-at-item-p)
15024 (and (org-region-active-p)
15025 (save-excursion
15026 (goto-char (region-beginning))
15027 (org-at-item-p))))
15028 (call-interactively 'org-indent-item))
15029 (t (call-interactively 'forward-word))))
15031 (defun org-metaup (&optional arg)
15032 "Move subtree up or move table row up.
15033 Calls `org-move-subtree-up' or `org-table-move-row' or
15034 `org-move-item-up', depending on context. See the individual commands
15035 for more information."
15036 (interactive "P")
15037 (cond
15038 ((run-hook-with-args-until-success 'org-metaup-hook))
15039 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15040 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15041 ((org-at-item-p) (call-interactively 'org-move-item-up))
15042 (t (transpose-lines 1) (beginning-of-line -1))))
15044 (defun org-metadown (&optional arg)
15045 "Move subtree down or move table row down.
15046 Calls `org-move-subtree-down' or `org-table-move-row' or
15047 `org-move-item-down', depending on context. See the individual
15048 commands for more information."
15049 (interactive "P")
15050 (cond
15051 ((run-hook-with-args-until-success 'org-metadown-hook))
15052 ((org-at-table-p) (call-interactively 'org-table-move-row))
15053 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15054 ((org-at-item-p) (call-interactively 'org-move-item-down))
15055 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15057 (defun org-shiftup (&optional arg)
15058 "Increase item in timestamp or increase priority of current headline.
15059 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15060 depending on context. See the individual commands for more information."
15061 (interactive "P")
15062 (cond
15063 ((and org-support-shift-select (org-region-active-p))
15064 (org-call-for-shift-select 'previous-line))
15065 ((org-at-timestamp-p t)
15066 (call-interactively (if org-edit-timestamp-down-means-later
15067 'org-timestamp-down 'org-timestamp-up)))
15068 ((and (not (eq org-support-shift-select 'always))
15069 org-enable-priority-commands
15070 (org-on-heading-p))
15071 (call-interactively 'org-priority-up))
15072 ((and (not org-support-shift-select) (org-at-item-p))
15073 (call-interactively 'org-previous-item))
15074 ((org-clocktable-try-shift 'up arg))
15075 (org-support-shift-select
15076 (org-call-for-shift-select 'previous-line))
15077 (t (org-shiftselect-error))))
15079 (defun org-shiftdown (&optional arg)
15080 "Decrease item in timestamp or decrease priority of current headline.
15081 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15082 depending on context. See the individual commands for more information."
15083 (interactive "P")
15084 (cond
15085 ((and org-support-shift-select (org-region-active-p))
15086 (org-call-for-shift-select 'next-line))
15087 ((org-at-timestamp-p t)
15088 (call-interactively (if org-edit-timestamp-down-means-later
15089 'org-timestamp-up 'org-timestamp-down)))
15090 ((and (not (eq org-support-shift-select 'always))
15091 org-enable-priority-commands
15092 (org-on-heading-p))
15093 (call-interactively 'org-priority-down))
15094 ((and (not org-support-shift-select) (org-at-item-p))
15095 (call-interactively 'org-next-item))
15096 ((org-clocktable-try-shift 'down arg))
15097 (org-support-shift-select
15098 (org-call-for-shift-select 'next-line))
15099 (t (org-shiftselect-error))))
15101 (defun org-shiftright (&optional arg)
15102 "Cycle the thing at point or in the current line, depending on context.
15103 Depending on context, this does one of the following:
15105 - switch a timestamp at point one day into the future
15106 - on a headline, switch to the next TODO keyword.
15107 - on an item, switch entire list to the next bullet type
15108 - on a property line, switch to the next allowed value
15109 - on a clocktable definition line, move time block into the future"
15110 (interactive "P")
15111 (cond
15112 ((and org-support-shift-select (org-region-active-p))
15113 (org-call-for-shift-select 'forward-char))
15114 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15115 ((and (not (eq org-support-shift-select 'always))
15116 (org-on-heading-p))
15117 (let ((org-inhibit-logging
15118 (not org-treat-S-cursor-todo-selection-as-state-change))
15119 (org-inhibit-blocking
15120 (not org-treat-S-cursor-todo-selection-as-state-change)))
15121 (org-call-with-arg 'org-todo 'right)))
15122 ((or (and org-support-shift-select
15123 (not (eq org-support-shift-select 'always))
15124 (org-at-item-bullet-p))
15125 (and (not org-support-shift-select) (org-at-item-p)))
15126 (org-call-with-arg 'org-cycle-list-bullet nil))
15127 ((and (not (eq org-support-shift-select 'always))
15128 (org-at-property-p))
15129 (call-interactively 'org-property-next-allowed-value))
15130 ((org-clocktable-try-shift 'right arg))
15131 (org-support-shift-select
15132 (org-call-for-shift-select 'forward-char))
15133 (t (org-shiftselect-error))))
15135 (defun org-shiftleft (&optional arg)
15136 "Cycle the thing at point or in the current line, depending on context.
15137 Depending on context, this does one of the following:
15139 - switch a timestamp at point one day into the past
15140 - on a headline, switch to the previous TODO keyword.
15141 - on an item, switch entire list to the previous bullet type
15142 - on a property line, switch to the previous allowed value
15143 - on a clocktable definition line, move time block into the past"
15144 (interactive "P")
15145 (cond
15146 ((and org-support-shift-select (org-region-active-p))
15147 (org-call-for-shift-select 'backward-char))
15148 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15149 ((and (not (eq org-support-shift-select 'always))
15150 (org-on-heading-p))
15151 (let ((org-inhibit-logging
15152 (not org-treat-S-cursor-todo-selection-as-state-change))
15153 (org-inhibit-blocking
15154 (not org-treat-S-cursor-todo-selection-as-state-change)))
15155 (org-call-with-arg 'org-todo 'left)))
15156 ((or (and org-support-shift-select
15157 (not (eq org-support-shift-select 'always))
15158 (org-at-item-bullet-p))
15159 (and (not org-support-shift-select) (org-at-item-p)))
15160 (org-call-with-arg 'org-cycle-list-bullet 'previous))
15161 ((and (not (eq org-support-shift-select 'always))
15162 (org-at-property-p))
15163 (call-interactively 'org-property-previous-allowed-value))
15164 ((org-clocktable-try-shift 'left arg))
15165 (org-support-shift-select
15166 (org-call-for-shift-select 'backward-char))
15167 (t (org-shiftselect-error))))
15169 (defun org-shiftcontrolright ()
15170 "Switch to next TODO set."
15171 (interactive)
15172 (cond
15173 ((and org-support-shift-select (org-region-active-p))
15174 (org-call-for-shift-select 'forward-word))
15175 ((and (not (eq org-support-shift-select 'always))
15176 (org-on-heading-p))
15177 (org-call-with-arg 'org-todo 'nextset))
15178 (org-support-shift-select
15179 (org-call-for-shift-select 'forward-word))
15180 (t (org-shiftselect-error))))
15182 (defun org-shiftcontrolleft ()
15183 "Switch to previous TODO set."
15184 (interactive)
15185 (cond
15186 ((and org-support-shift-select (org-region-active-p))
15187 (org-call-for-shift-select 'backward-word))
15188 ((and (not (eq org-support-shift-select 'always))
15189 (org-on-heading-p))
15190 (org-call-with-arg 'org-todo 'previousset))
15191 (org-support-shift-select
15192 (org-call-for-shift-select 'backward-word))
15193 (t (org-shiftselect-error))))
15195 (defun org-ctrl-c-ret ()
15196 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15197 (interactive)
15198 (cond
15199 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15200 (t (call-interactively 'org-insert-heading))))
15202 (defun org-copy-special ()
15203 "Copy region in table or copy current subtree.
15204 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15205 See the individual commands for more information."
15206 (interactive)
15207 (call-interactively
15208 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15210 (defun org-cut-special ()
15211 "Cut region in table or cut current subtree.
15212 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15213 See the individual commands for more information."
15214 (interactive)
15215 (call-interactively
15216 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15218 (defun org-paste-special (arg)
15219 "Paste rectangular region into table, or past subtree relative to level.
15220 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15221 See the individual commands for more information."
15222 (interactive "P")
15223 (if (org-at-table-p)
15224 (org-table-paste-rectangle)
15225 (org-paste-subtree arg)))
15227 (defun org-edit-special ()
15228 "Call a special editor for the stuff at point.
15229 When at a table, call the formula editor with `org-table-edit-formulas'.
15230 When at the first line of an src example, call `org-edit-src-code'.
15231 When in an #+include line, visit the include file. Otherwise call
15232 `ffap' to visit the file at point."
15233 (interactive)
15234 (cond
15235 ((org-at-table-p)
15236 (call-interactively 'org-table-edit-formulas))
15237 ((save-excursion
15238 (beginning-of-line 1)
15239 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
15240 (find-file (org-trim (match-string 1))))
15241 ((org-edit-src-code))
15242 ((org-edit-fixed-width-region))
15243 (t (call-interactively 'ffap))))
15246 (defun org-ctrl-c-ctrl-c (&optional arg)
15247 "Set tags in headline, or update according to changed information at point.
15249 This command does many different things, depending on context:
15251 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15252 this is what we do.
15254 - If the cursor is on a statistics cookie, update it.
15256 - If the cursor is in a headline, prompt for tags and insert them
15257 into the current line, aligned to `org-tags-column'. When called
15258 with prefix arg, realign all tags in the current buffer.
15260 - If the cursor is in one of the special #+KEYWORD lines, this
15261 triggers scanning the buffer for these lines and updating the
15262 information.
15264 - If the cursor is inside a table, realign the table. This command
15265 works even if the automatic table editor has been turned off.
15267 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15268 the entire table.
15270 - If the cursor is at a footnote reference or definition, jump to
15271 the corresponding definition or references, respectively.
15273 - If the cursor is a the beginning of a dynamic block, update it.
15275 - If the cursor is inside a table created by the table.el package,
15276 activate that table.
15278 - If the current buffer is a remember buffer, close note and file
15279 it. A prefix argument of 1 files to the default location
15280 without further interaction. A prefix argument of 2 files to
15281 the currently clocking task.
15283 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15284 links in this buffer.
15286 - If the cursor is on a numbered item in a plain list, renumber the
15287 ordered list.
15289 - If the cursor is on a checkbox, toggle it."
15290 (interactive "P")
15291 (let ((org-enable-table-editor t))
15292 (cond
15293 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15294 org-occur-highlights
15295 org-latex-fragment-image-overlays)
15296 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15297 (org-remove-occur-highlights)
15298 (org-remove-latex-fragment-image-overlays)
15299 (message "Temporary highlights/overlays removed from current buffer"))
15300 ((and (local-variable-p 'org-finish-function (current-buffer))
15301 (fboundp org-finish-function))
15302 (funcall org-finish-function))
15303 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15304 ((org-at-property-p)
15305 (call-interactively 'org-property-action))
15306 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15307 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15308 (or (org-on-heading-p) (org-at-item-p)))
15309 (call-interactively 'org-update-statistics-cookies))
15310 ((org-on-heading-p) (call-interactively 'org-set-tags))
15311 ((org-at-table.el-p)
15312 (require 'table)
15313 (beginning-of-line 1)
15314 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15315 (call-interactively 'table-recognize-table))
15316 ((org-at-table-p)
15317 (org-table-maybe-eval-formula)
15318 (if arg
15319 (call-interactively 'org-table-recalculate)
15320 (org-table-maybe-recalculate-line))
15321 (call-interactively 'org-table-align))
15322 ((or (org-footnote-at-reference-p)
15323 (org-footnote-at-definition-p))
15324 (call-interactively 'org-footnote-action))
15325 ((org-at-item-checkbox-p)
15326 (call-interactively 'org-toggle-checkbox))
15327 ((org-at-item-p)
15328 (if arg
15329 (call-interactively 'org-toggle-checkbox)
15330 (call-interactively 'org-maybe-renumber-ordered-list)))
15331 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15332 ;; Dynamic block
15333 (beginning-of-line 1)
15334 (save-excursion (org-update-dblock)))
15335 ((save-excursion
15336 (beginning-of-line 1)
15337 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15338 (cond
15339 ((equal (match-string 1) "TBLFM")
15340 ;; Recalculate the table before this line
15341 (save-excursion
15342 (beginning-of-line 1)
15343 (skip-chars-backward " \r\n\t")
15344 (if (org-at-table-p)
15345 (org-call-with-arg 'org-table-recalculate (or arg t)))))
15347 ; (org-set-regexps-and-options)
15348 ; (org-restart-font-lock)
15349 (let ((org-inhibit-startup t)) (org-mode-restart))
15350 (message "Local setup has been refreshed"))))
15351 ((org-clock-update-time-maybe))
15352 (t (error "C-c C-c can do nothing useful at this location")))))
15354 (defun org-mode-restart ()
15355 "Restart Org-mode, to scan again for special lines.
15356 Also updates the keyword regular expressions."
15357 (interactive)
15358 (org-mode)
15359 (message "Org-mode restarted"))
15361 (defun org-kill-note-or-show-branches ()
15362 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15363 (interactive)
15364 (if (not org-finish-function)
15365 (call-interactively 'show-branches)
15366 (let ((org-note-abort t))
15367 (funcall org-finish-function))))
15369 (defun org-return (&optional indent)
15370 "Goto next table row or insert a newline.
15371 Calls `org-table-next-row' or `newline', depending on context.
15372 See the individual commands for more information."
15373 (interactive)
15374 (cond
15375 ((bobp) (if indent (newline-and-indent) (newline)))
15376 ((org-at-table-p)
15377 (org-table-justify-field-maybe)
15378 (call-interactively 'org-table-next-row))
15379 ((and org-return-follows-link
15380 (eq (get-text-property (point) 'face) 'org-link))
15381 (call-interactively 'org-open-at-point))
15382 ((and (org-at-heading-p)
15383 (looking-at
15384 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15385 (org-show-entry)
15386 (end-of-line 1)
15387 (newline))
15388 (t (if indent (newline-and-indent) (newline)))))
15390 (defun org-return-indent ()
15391 "Goto next table row or insert a newline and indent.
15392 Calls `org-table-next-row' or `newline-and-indent', depending on
15393 context. See the individual commands for more information."
15394 (interactive)
15395 (org-return t))
15397 (defun org-ctrl-c-star ()
15398 "Compute table, or change heading status of lines.
15399 Calls `org-table-recalculate' or `org-toggle-heading',
15400 depending on context."
15401 (interactive)
15402 (cond
15403 ((org-at-table-p)
15404 (call-interactively 'org-table-recalculate))
15406 ;; Convert all lines in region to list items
15407 (call-interactively 'org-toggle-heading))))
15409 (defun org-ctrl-c-minus ()
15410 "Insert separator line in table or modify bullet status of line.
15411 Also turns a plain line or a region of lines into list items.
15412 Calls `org-table-insert-hline', `org-toggle-item', or
15413 `org-cycle-list-bullet', depending on context."
15414 (interactive)
15415 (cond
15416 ((org-at-table-p)
15417 (call-interactively 'org-table-insert-hline))
15418 ((org-region-active-p)
15419 (call-interactively 'org-toggle-item))
15420 ((org-in-item-p)
15421 (call-interactively 'org-cycle-list-bullet))
15423 (call-interactively 'org-toggle-item))))
15425 (defun org-toggle-item ()
15426 "Convert headings or normal lines to items, items to normal lines.
15427 If there is no active region, only the current line is considered.
15429 If the first line in the region is a headline, convert all headlines to items.
15431 If the first line in the region is an item, convert all items to normal lines.
15433 If the first line is normal text, add an item bullet to each line."
15434 (interactive)
15435 (let (l2 l beg end)
15436 (if (org-region-active-p)
15437 (setq beg (region-beginning) end (region-end))
15438 (setq beg (point-at-bol)
15439 end (min (1+ (point-at-eol)) (point-max))))
15440 (save-excursion
15441 (goto-char end)
15442 (setq l2 (org-current-line))
15443 (goto-char beg)
15444 (beginning-of-line 1)
15445 (setq l (1- (org-current-line)))
15446 (if (org-at-item-p)
15447 ;; We already have items, de-itemize
15448 (while (< (setq l (1+ l)) l2)
15449 (when (org-at-item-p)
15450 (goto-char (match-beginning 2))
15451 (delete-region (match-beginning 2) (match-end 2))
15452 (and (looking-at "[ \t]+") (replace-match "")))
15453 (beginning-of-line 2))
15454 (if (org-on-heading-p)
15455 ;; Headings, convert to items
15456 (while (< (setq l (1+ l)) l2)
15457 (if (looking-at org-outline-regexp)
15458 (replace-match "- " t t))
15459 (beginning-of-line 2))
15460 ;; normal lines, turn them into items
15461 (while (< (setq l (1+ l)) l2)
15462 (unless (org-at-item-p)
15463 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15464 (replace-match "\\1- \\2")))
15465 (beginning-of-line 2)))))))
15467 (defun org-toggle-heading (&optional nstars)
15468 "Convert headings to normal text, or items or text to headings.
15469 If there is no active region, only the current line is considered.
15471 If the first line is a heading, remove the stars from all headlines
15472 in the region.
15474 If the first line is a plain list item, turn all plain list items
15475 into headings.
15477 If the first line is a normal line, turn each and every line in the
15478 region into a heading.
15480 When converting a line into a heading, the number of stars is chosen
15481 such that the lines become children of the current entry. However,
15482 when a prefix argument is given, its value determines the number of
15483 stars to add."
15484 (interactive "P")
15485 (let (l2 l itemp beg end)
15486 (if (org-region-active-p)
15487 (setq beg (region-beginning) end (region-end))
15488 (setq beg (point-at-bol)
15489 end (min (1+ (point-at-eol)) (point-max))))
15490 (save-excursion
15491 (goto-char end)
15492 (setq l2 (org-current-line))
15493 (goto-char beg)
15494 (beginning-of-line 1)
15495 (setq l (1- (org-current-line)))
15496 (if (org-on-heading-p)
15497 ;; We already have headlines, de-star them
15498 (while (< (setq l (1+ l)) l2)
15499 (when (org-on-heading-p t)
15500 (and (looking-at outline-regexp) (replace-match "")))
15501 (beginning-of-line 2))
15502 (setq itemp (org-at-item-p))
15503 (let* ((stars
15504 (if nstars
15505 (make-string (prefix-numeric-value current-prefix-arg)
15507 (save-excursion
15508 (if (re-search-backward org-complex-heading-regexp nil t)
15509 (match-string 1) ""))))
15510 (add-stars (cond (nstars "")
15511 ((equal stars "") "*")
15512 (org-odd-levels-only "**")
15513 (t "*")))
15514 (rpl (concat stars add-stars " ")))
15515 (while (< (setq l (1+ l)) l2)
15516 (if itemp
15517 (and (org-at-item-p) (replace-match rpl t t))
15518 (unless (org-on-heading-p)
15519 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15520 (replace-match (concat rpl (match-string 2))))))
15521 (beginning-of-line 2)))))))
15523 (defun org-meta-return (&optional arg)
15524 "Insert a new heading or wrap a region in a table.
15525 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15526 See the individual commands for more information."
15527 (interactive "P")
15528 (cond
15529 ((run-hook-with-args-until-success 'org-metareturn-hook))
15530 ((org-at-table-p)
15531 (call-interactively 'org-table-wrap-region))
15532 (t (call-interactively 'org-insert-heading))))
15534 ;;; Menu entries
15536 ;; Define the Org-mode menus
15537 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15538 '("Tbl"
15539 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15540 ["Next Field" org-cycle (org-at-table-p)]
15541 ["Previous Field" org-shifttab (org-at-table-p)]
15542 ["Next Row" org-return (org-at-table-p)]
15543 "--"
15544 ["Blank Field" org-table-blank-field (org-at-table-p)]
15545 ["Edit Field" org-table-edit-field (org-at-table-p)]
15546 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15547 "--"
15548 ("Column"
15549 ["Move Column Left" org-metaleft (org-at-table-p)]
15550 ["Move Column Right" org-metaright (org-at-table-p)]
15551 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15552 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15553 ("Row"
15554 ["Move Row Up" org-metaup (org-at-table-p)]
15555 ["Move Row Down" org-metadown (org-at-table-p)]
15556 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15557 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15558 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15559 "--"
15560 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15561 ("Rectangle"
15562 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15563 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15564 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15565 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15566 "--"
15567 ("Calculate"
15568 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15569 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15570 ["Edit Formulas" org-edit-special (org-at-table-p)]
15571 "--"
15572 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15573 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15574 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15575 "--"
15576 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15577 "--"
15578 ["Sum Column/Rectangle" org-table-sum
15579 (or (org-at-table-p) (org-region-active-p))]
15580 ["Which Column?" org-table-current-column (org-at-table-p)])
15581 ["Debug Formulas"
15582 org-table-toggle-formula-debugger
15583 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15584 ["Show Col/Row Numbers"
15585 org-table-toggle-coordinate-overlays
15586 :style toggle
15587 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15588 "--"
15589 ["Create" org-table-create (and (not (org-at-table-p))
15590 org-enable-table-editor)]
15591 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15592 ["Import from File" org-table-import (not (org-at-table-p))]
15593 ["Export to File" org-table-export (org-at-table-p)]
15594 "--"
15595 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15597 (easy-menu-define org-org-menu org-mode-map "Org menu"
15598 '("Org"
15599 ("Show/Hide"
15600 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15601 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15602 ["Sparse Tree..." org-sparse-tree t]
15603 ["Reveal Context" org-reveal t]
15604 ["Show All" show-all t]
15605 "--"
15606 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15607 "--"
15608 ["New Heading" org-insert-heading t]
15609 ("Navigate Headings"
15610 ["Up" outline-up-heading t]
15611 ["Next" outline-next-visible-heading t]
15612 ["Previous" outline-previous-visible-heading t]
15613 ["Next Same Level" outline-forward-same-level t]
15614 ["Previous Same Level" outline-backward-same-level t]
15615 "--"
15616 ["Jump" org-goto t])
15617 ("Edit Structure"
15618 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15619 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15620 "--"
15621 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15622 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15623 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15624 "--"
15625 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15626 "--"
15627 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15628 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15629 ["Demote Heading" org-metaright (not (org-at-table-p))]
15630 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15631 "--"
15632 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15633 "--"
15634 ["Convert to odd levels" org-convert-to-odd-levels t]
15635 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15636 ("Editing"
15637 ["Emphasis..." org-emphasize t]
15638 ["Edit Source Example" org-edit-special t]
15639 "--"
15640 ["Footnote new/jump" org-footnote-action t]
15641 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15642 ("Archive"
15643 ["Archive (default method)" org-archive-subtree-default t]
15644 "--"
15645 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
15646 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15647 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
15649 "--"
15650 ("Hyperlinks"
15651 ["Store Link (Global)" org-store-link t]
15652 ["Find existing link to here" org-occur-link-in-agenda-files t]
15653 ["Insert Link" org-insert-link t]
15654 ["Follow Link" org-open-at-point t]
15655 "--"
15656 ["Next link" org-next-link t]
15657 ["Previous link" org-previous-link t]
15658 "--"
15659 ["Descriptive Links"
15660 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15661 :style radio
15662 :selected (member '(org-link) buffer-invisibility-spec)]
15663 ["Literal Links"
15664 (progn
15665 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15666 :style radio
15667 :selected (not (member '(org-link) buffer-invisibility-spec))])
15668 "--"
15669 ("TODO Lists"
15670 ["TODO/DONE/-" org-todo t]
15671 ("Select keyword"
15672 ["Next keyword" org-shiftright (org-on-heading-p)]
15673 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15674 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15675 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15676 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15677 ["Show TODO Tree" org-show-todo-tree t]
15678 ["Global TODO list" org-todo-list t]
15679 "--"
15680 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15681 :selected org-enforce-todo-dependencies :style toggle :active t]
15682 "Settings for tree at point"
15683 ["Do Children sequentially" org-toggle-ordered-property :style radio
15684 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15685 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15686 ["Do Children parallel" org-toggle-ordered-property :style radio
15687 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15688 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15689 "--"
15690 ["Set Priority" org-priority t]
15691 ["Priority Up" org-shiftup t]
15692 ["Priority Down" org-shiftdown t]
15693 "--"
15694 ["Get news from all feeds" org-feed-update-all t]
15695 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15696 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15697 ("TAGS and Properties"
15698 ["Set Tags" org-set-tags-command t]
15699 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15700 "--"
15701 ["Set property" org-set-property t]
15702 ["Column view of properties" org-columns t]
15703 ["Insert Column View DBlock" org-insert-columns-dblock t])
15704 ("Dates and Scheduling"
15705 ["Timestamp" org-time-stamp t]
15706 ["Timestamp (inactive)" org-time-stamp-inactive t]
15707 ("Change Date"
15708 ["1 Day Later" org-shiftright t]
15709 ["1 Day Earlier" org-shiftleft t]
15710 ["1 ... Later" org-shiftup t]
15711 ["1 ... Earlier" org-shiftdown t])
15712 ["Compute Time Range" org-evaluate-time-range t]
15713 ["Schedule Item" org-schedule t]
15714 ["Deadline" org-deadline t]
15715 "--"
15716 ["Custom time format" org-toggle-time-stamp-overlays
15717 :style radio :selected org-display-custom-times]
15718 "--"
15719 ["Goto Calendar" org-goto-calendar t]
15720 ["Date from Calendar" org-date-from-calendar t]
15721 "--"
15722 ["Start/Restart Timer" org-timer-start t]
15723 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15724 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15725 ["Insert Timer String" org-timer t]
15726 ["Insert Timer Item" org-timer-item t])
15727 ("Logging work"
15728 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
15729 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
15730 ["Clock out" org-clock-out t]
15731 ["Clock cancel" org-clock-cancel t]
15732 "--"
15733 ["Mark as default task" org-clock-mark-default-task t]
15734 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
15735 ["Goto running clock" org-clock-goto t]
15736 "--"
15737 ["Display times" org-clock-display t]
15738 ["Create clock table" org-clock-report t]
15739 "--"
15740 ["Record DONE time"
15741 (progn (setq org-log-done (not org-log-done))
15742 (message "Switching to %s will %s record a timestamp"
15743 (car org-done-keywords)
15744 (if org-log-done "automatically" "not")))
15745 :style toggle :selected org-log-done])
15746 "--"
15747 ["Agenda Command..." org-agenda t]
15748 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15749 ("File List for Agenda")
15750 ("Special views current file"
15751 ["TODO Tree" org-show-todo-tree t]
15752 ["Check Deadlines" org-check-deadlines t]
15753 ["Timeline" org-timeline t]
15754 ["Tags/Property tree" org-match-sparse-tree t])
15755 "--"
15756 ["Export/Publish..." org-export t]
15757 ("LaTeX"
15758 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15759 :selected org-cdlatex-mode]
15760 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15761 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15762 ["Modify math symbol" org-cdlatex-math-modify
15763 (org-inside-LaTeX-fragment-p)]
15764 ["Insert citation" org-reftex-citation t]
15765 "--"
15766 ["Export LaTeX fragments as images"
15767 (if (featurep 'org-exp)
15768 (setq org-export-with-LaTeX-fragments
15769 (not org-export-with-LaTeX-fragments))
15770 (require 'org-exp))
15771 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15772 org-export-with-LaTeX-fragments)])
15773 "--"
15774 ("MobileOrg"
15775 ["Push Files and Views" org-mobile-push t]
15776 ["Get Captured and Flagged" org-mobile-pull t]
15777 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
15778 "--"
15779 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
15780 "--"
15781 ("Documentation"
15782 ["Show Version" org-version t]
15783 ["Info Documentation" org-info t])
15784 ("Customize"
15785 ["Browse Org Group" org-customize t]
15786 "--"
15787 ["Expand This Menu" org-create-customize-menu
15788 (fboundp 'customize-menu-create)])
15789 ["Send bug report" org-submit-bug-report t]
15790 "--"
15791 ("Refresh/Reload"
15792 ["Refresh setup current buffer" org-mode-restart t]
15793 ["Reload Org (after update)" org-reload t]
15794 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15797 (defun org-info (&optional node)
15798 "Read documentation for Org-mode in the info system.
15799 With optional NODE, go directly to that node."
15800 (interactive)
15801 (info (format "(org)%s" (or node ""))))
15803 ;;;###autoload
15804 (defun org-submit-bug-report ()
15805 "Submit a bug report on Org-mode via mail.
15807 Don't hesitate to report any problems or inaccurate documentation.
15809 If you don't have setup sending mail from (X)Emacs, please copy the
15810 output buffer into your mail program, as it gives us important
15811 information about your Org-mode version and configuration."
15812 (interactive)
15813 (require 'reporter)
15814 (org-load-modules-maybe)
15815 (org-require-autoloaded-modules)
15816 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
15817 (reporter-submit-bug-report
15818 "emacs-orgmode@gnu.org"
15819 (org-version)
15820 (let (list)
15821 (save-window-excursion
15822 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
15823 (delete-other-windows)
15824 (erase-buffer)
15825 (insert "You are about to submit a bug report to the Org-mode mailing list.
15827 We would like to add your full Org-mode and Outline configuration to the
15828 bug report. This greatly simplifies the work of the maintainer and
15829 other experts on the mailing list.
15831 HOWEVER, some variables you have customized may contain private
15832 information. The names of customers, colleagues, or friends, might
15833 appear in the form of file names, tags, todo states, or search strings.
15834 If you answer yes to the prompt, you might want to check and remove
15835 such private information before sending the email.")
15836 (add-text-properties (point-min) (point-max) '(face org-warning))
15837 (when (yes-or-no-p "Include your Org-mode configuration ")
15838 (mapatoms
15839 (lambda (v)
15840 (and (boundp v)
15841 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
15842 (or (and (symbol-value v)
15843 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
15844 (and
15845 (get v 'custom-type) (get v 'standard-value)
15846 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
15847 (push v list)))))
15848 (kill-buffer (get-buffer "*Warn about privacy*"))
15849 list))
15850 nil nil
15851 "Remember to cover the basics, that is, what you expected to happen and
15852 what in fact did happen. You don't know how to make a good report? See
15854 http://orgmode.org/manual/Feedback.html#Feedback
15856 Your bug report will be posted to the Org-mode mailing list.
15857 ------------------------------------------------------------------------")))
15859 (defun org-install-agenda-files-menu ()
15860 (let ((bl (buffer-list)))
15861 (save-excursion
15862 (while bl
15863 (set-buffer (pop bl))
15864 (if (org-mode-p) (setq bl nil)))
15865 (when (org-mode-p)
15866 (easy-menu-change
15867 '("Org") "File List for Agenda"
15868 (append
15869 (list
15870 ["Edit File List" (org-edit-agenda-file-list) t]
15871 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15872 ["Remove Current File from List" org-remove-file t]
15873 ["Cycle through agenda files" org-cycle-agenda-files t]
15874 ["Occur in all agenda files" org-occur-in-agenda-files t]
15875 "--")
15876 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15878 ;;;; Documentation
15880 ;;;###autoload
15881 (defun org-require-autoloaded-modules ()
15882 (interactive)
15883 (mapc 'require
15884 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15885 org-docbook org-exp org-html org-icalendar
15886 org-id org-latex
15887 org-publish org-remember org-table
15888 org-timer org-xoxo)))
15890 ;;;###autoload
15891 (defun org-reload (&optional uncompiled)
15892 "Reload all org lisp files.
15893 With prefix arg UNCOMPILED, load the uncompiled versions."
15894 (interactive "P")
15895 (require 'find-func)
15896 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15897 (dir-org (file-name-directory (org-find-library-name "org")))
15898 (dir-org-contrib (ignore-errors
15899 (file-name-directory
15900 (org-find-library-name "org-contribdir"))))
15901 (files
15902 (append (directory-files dir-org t file-re)
15903 (and dir-org-contrib
15904 (directory-files dir-org-contrib t file-re))))
15905 (remove-re (concat (if (featurep 'xemacs)
15906 "org-colview" "org-colview-xemacs")
15907 "\\'")))
15908 (setq files (mapcar 'file-name-sans-extension files))
15909 (setq files (mapcar
15910 (lambda (x) (if (string-match remove-re x) nil x))
15911 files))
15912 (setq files (delq nil files))
15913 (mapc
15914 (lambda (f)
15915 (when (featurep (intern (file-name-nondirectory f)))
15916 (if (and (not uncompiled)
15917 (file-exists-p (concat f ".elc")))
15918 (load (concat f ".elc") nil nil t)
15919 (load (concat f ".el") nil nil t))))
15920 files))
15921 (org-version))
15923 ;;;###autoload
15924 (defun org-customize ()
15925 "Call the customize function with org as argument."
15926 (interactive)
15927 (org-load-modules-maybe)
15928 (org-require-autoloaded-modules)
15929 (customize-browse 'org))
15931 (defun org-create-customize-menu ()
15932 "Create a full customization menu for Org-mode, insert it into the menu."
15933 (interactive)
15934 (org-load-modules-maybe)
15935 (org-require-autoloaded-modules)
15936 (if (fboundp 'customize-menu-create)
15937 (progn
15938 (easy-menu-change
15939 '("Org") "Customize"
15940 `(["Browse Org group" org-customize t]
15941 "--"
15942 ,(customize-menu-create 'org)
15943 ["Set" Custom-set t]
15944 ["Save" Custom-save t]
15945 ["Reset to Current" Custom-reset-current t]
15946 ["Reset to Saved" Custom-reset-saved t]
15947 ["Reset to Standard Settings" Custom-reset-standard t]))
15948 (message "\"Org\"-menu now contains full customization menu"))
15949 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15951 ;;;; Miscellaneous stuff
15953 ;;; Generally useful functions
15955 (defun org-get-at-bol (property)
15956 "Get text property PROPERTY at beginning of line."
15957 (get-text-property (point-at-bol) property))
15959 (defun org-find-text-property-in-string (prop s)
15960 "Return the first non-nil value of property PROP in string S."
15961 (or (get-text-property 0 prop s)
15962 (get-text-property (or (next-single-property-change 0 prop s) 0)
15963 prop s)))
15965 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15966 "Display the given MESSAGE as a warning."
15967 (if (fboundp 'display-warning)
15968 (display-warning 'org message
15969 (if (featurep 'xemacs)
15970 'warning
15971 :warning))
15972 (let ((buf (get-buffer-create "*Org warnings*")))
15973 (with-current-buffer buf
15974 (goto-char (point-max))
15975 (insert "Warning (Org): " message)
15976 (unless (bolp)
15977 (newline)))
15978 (display-buffer buf)
15979 (sit-for 0))))
15981 (defun org-in-commented-line ()
15982 "Is point in a line starting with `#'?"
15983 (equal (char-after (point-at-bol)) ?#))
15985 (defun org-in-verbatim-emphasis ()
15986 (save-match-data
15987 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
15989 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15990 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15991 (if (and marker (marker-buffer marker)
15992 (buffer-live-p (marker-buffer marker)))
15993 (progn
15994 (switch-to-buffer (marker-buffer marker))
15995 (if (or (> marker (point-max)) (< marker (point-min)))
15996 (widen))
15997 (goto-char marker)
15998 (org-show-context 'org-goto))
15999 (if bookmark
16000 (bookmark-jump bookmark)
16001 (error "Cannot find location"))))
16003 (defun org-quote-csv-field (s)
16004 "Quote field for inclusion in CSV material."
16005 (if (string-match "[\",]" s)
16006 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16009 (defun org-plist-delete (plist property)
16010 "Delete PROPERTY from PLIST.
16011 This is in contrast to merely setting it to 0."
16012 (let (p)
16013 (while plist
16014 (if (not (eq property (car plist)))
16015 (setq p (plist-put p (car plist) (nth 1 plist))))
16016 (setq plist (cddr plist)))
16019 (defun org-force-self-insert (N)
16020 "Needed to enforce self-insert under remapping."
16021 (interactive "p")
16022 (self-insert-command N))
16024 (defun org-string-width (s)
16025 "Compute width of string, ignoring invisible characters.
16026 This ignores character with invisibility property `org-link', and also
16027 characters with property `org-cwidth', because these will become invisible
16028 upon the next fontification round."
16029 (let (b l)
16030 (when (or (eq t buffer-invisibility-spec)
16031 (assq 'org-link buffer-invisibility-spec))
16032 (while (setq b (text-property-any 0 (length s)
16033 'invisible 'org-link s))
16034 (setq s (concat (substring s 0 b)
16035 (substring s (or (next-single-property-change
16036 b 'invisible s) (length s)))))))
16037 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16038 (setq s (concat (substring s 0 b)
16039 (substring s (or (next-single-property-change
16040 b 'org-cwidth s) (length s))))))
16041 (setq l (string-width s) b -1)
16042 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16043 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16046 (defun org-get-indentation (&optional line)
16047 "Get the indentation of the current line, interpreting tabs.
16048 When LINE is given, assume it represents a line and compute its indentation."
16049 (if line
16050 (if (string-match "^ *" (org-remove-tabs line))
16051 (match-end 0))
16052 (save-excursion
16053 (beginning-of-line 1)
16054 (skip-chars-forward " \t")
16055 (current-column))))
16057 (defun org-remove-tabs (s &optional width)
16058 "Replace tabulators in S with spaces.
16059 Assumes that s is a single line, starting in column 0."
16060 (setq width (or width tab-width))
16061 (while (string-match "\t" s)
16062 (setq s (replace-match
16063 (make-string
16064 (- (* width (/ (+ (match-beginning 0) width) width))
16065 (match-beginning 0)) ?\ )
16066 t t s)))
16069 (defun org-fix-indentation (line ind)
16070 "Fix indentation in LINE.
16071 IND is a cons cell with target and minimum indentation.
16072 If the current indentation in LINE is smaller than the minimum,
16073 leave it alone. If it is larger than ind, set it to the target."
16074 (let* ((l (org-remove-tabs line))
16075 (i (org-get-indentation l))
16076 (i1 (car ind)) (i2 (cdr ind)))
16077 (if (>= i i2) (setq l (substring line i2)))
16078 (if (> i1 0)
16079 (concat (make-string i1 ?\ ) l)
16080 l)))
16082 (defun org-remove-indentation (code &optional n)
16083 "Remove the maximum common indentation from the lines in CODE.
16084 N may optionally be the number of spaces to remove."
16085 (with-temp-buffer
16086 (insert code)
16087 (org-do-remove-indentation n)
16088 (buffer-string)))
16090 (defun org-do-remove-indentation (&optional n)
16091 "Remove the maximum common indentation from the buffer."
16092 (untabify (point-min) (point-max))
16093 (let ((min 10000) re)
16094 (if n
16095 (setq min n)
16096 (goto-char (point-min))
16097 (while (re-search-forward "^ *[^ \n]" nil t)
16098 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16099 (unless (or (= min 0) (= min 10000))
16100 (setq re (format "^ \\{%d\\}" min))
16101 (goto-char (point-min))
16102 (while (re-search-forward re nil t)
16103 (replace-match "")
16104 (end-of-line 1))
16105 min)))
16107 (defun org-fill-template (template alist)
16108 "Find each %key of ALIST in TEMPLATE and replace it."
16109 (let (entry key value)
16110 (setq alist (sort (copy-sequence alist)
16111 (lambda (a b) (< (length (car a)) (length (car b))))))
16112 (while (setq entry (pop alist))
16113 (setq template
16114 (replace-regexp-in-string
16115 (concat "%" (regexp-quote (car entry)))
16116 (cdr entry) template t t)))
16117 template))
16119 (defun org-base-buffer (buffer)
16120 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16121 (if (not buffer)
16122 buffer
16123 (or (buffer-base-buffer buffer)
16124 buffer)))
16126 (defun org-trim (s)
16127 "Remove whitespace at beginning and end of string."
16128 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
16129 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
16132 (defun org-wrap (string &optional width lines)
16133 "Wrap string to either a number of lines, or a width in characters.
16134 If WIDTH is non-nil, the string is wrapped to that width, however many lines
16135 that costs. If there is a word longer than WIDTH, the text is actually
16136 wrapped to the length of that word.
16137 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
16138 many lines, whatever width that takes.
16139 The return value is a list of lines, without newlines at the end."
16140 (let* ((words (org-split-string string "[ \t\n]+"))
16141 (maxword (apply 'max (mapcar 'org-string-width words)))
16142 w ll)
16143 (cond (width
16144 (org-do-wrap words (max maxword width)))
16145 (lines
16146 (setq w maxword)
16147 (setq ll (org-do-wrap words maxword))
16148 (if (<= (length ll) lines)
16150 (setq ll words)
16151 (while (> (length ll) lines)
16152 (setq w (1+ w))
16153 (setq ll (org-do-wrap words w)))
16154 ll))
16155 (t (error "Cannot wrap this")))))
16157 (defun org-do-wrap (words width)
16158 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
16159 (let (lines line)
16160 (while words
16161 (setq line (pop words))
16162 (while (and words (< (+ (length line) (length (car words))) width))
16163 (setq line (concat line " " (pop words))))
16164 (setq lines (push line lines)))
16165 (nreverse lines)))
16167 (defun org-split-string (string &optional separators)
16168 "Splits STRING into substrings at SEPARATORS.
16169 No empty strings are returned if there are matches at the beginning
16170 and end of string."
16171 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
16172 (start 0)
16173 notfirst
16174 (list nil))
16175 (while (and (string-match rexp string
16176 (if (and notfirst
16177 (= start (match-beginning 0))
16178 (< start (length string)))
16179 (1+ start) start))
16180 (< (match-beginning 0) (length string)))
16181 (setq notfirst t)
16182 (or (eq (match-beginning 0) 0)
16183 (and (eq (match-beginning 0) (match-end 0))
16184 (eq (match-beginning 0) start))
16185 (setq list
16186 (cons (substring string start (match-beginning 0))
16187 list)))
16188 (setq start (match-end 0)))
16189 (or (eq start (length string))
16190 (setq list
16191 (cons (substring string start)
16192 list)))
16193 (nreverse list)))
16195 (defun org-quote-vert (s)
16196 "Replace \"|\" with \"\\vert\"."
16197 (while (string-match "|" s)
16198 (setq s (replace-match "\\vert" t t s)))
16201 (defun org-uuidgen-p (s)
16202 "Is S an ID created by UUIDGEN?"
16203 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16205 (defun org-context ()
16206 "Return a list of contexts of the current cursor position.
16207 If several contexts apply, all are returned.
16208 Each context entry is a list with a symbol naming the context, and
16209 two positions indicating start and end of the context. Possible
16210 contexts are:
16212 :headline anywhere in a headline
16213 :headline-stars on the leading stars in a headline
16214 :todo-keyword on a TODO keyword (including DONE) in a headline
16215 :tags on the TAGS in a headline
16216 :priority on the priority cookie in a headline
16217 :item on the first line of a plain list item
16218 :item-bullet on the bullet/number of a plain list item
16219 :checkbox on the checkbox in a plain list item
16220 :table in an org-mode table
16221 :table-special on a special filed in a table
16222 :table-table in a table.el table
16223 :link on a hyperlink
16224 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16225 :target on a <<target>>
16226 :radio-target on a <<<radio-target>>>
16227 :latex-fragment on a LaTeX fragment
16228 :latex-preview on a LaTeX fragment with overlayed preview image
16230 This function expects the position to be visible because it uses font-lock
16231 faces as a help to recognize the following contexts: :table-special, :link,
16232 and :keyword."
16233 (let* ((f (get-text-property (point) 'face))
16234 (faces (if (listp f) f (list f)))
16235 (p (point)) clist o)
16236 ;; First the large context
16237 (cond
16238 ((org-on-heading-p t)
16239 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16240 (when (progn
16241 (beginning-of-line 1)
16242 (looking-at org-todo-line-tags-regexp))
16243 (push (org-point-in-group p 1 :headline-stars) clist)
16244 (push (org-point-in-group p 2 :todo-keyword) clist)
16245 (push (org-point-in-group p 4 :tags) clist))
16246 (goto-char p)
16247 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
16248 (if (looking-at "\\[#[A-Z0-9]\\]")
16249 (push (org-point-in-group p 0 :priority) clist)))
16251 ((org-at-item-p)
16252 (push (org-point-in-group p 2 :item-bullet) clist)
16253 (push (list :item (point-at-bol)
16254 (save-excursion (org-end-of-item) (point)))
16255 clist)
16256 (and (org-at-item-checkbox-p)
16257 (push (org-point-in-group p 0 :checkbox) clist)))
16259 ((org-at-table-p)
16260 (push (list :table (org-table-begin) (org-table-end)) clist)
16261 (if (memq 'org-formula faces)
16262 (push (list :table-special
16263 (previous-single-property-change p 'face)
16264 (next-single-property-change p 'face)) clist)))
16265 ((org-at-table-p 'any)
16266 (push (list :table-table) clist)))
16267 (goto-char p)
16269 ;; Now the small context
16270 (cond
16271 ((org-at-timestamp-p)
16272 (push (org-point-in-group p 0 :timestamp) clist))
16273 ((memq 'org-link faces)
16274 (push (list :link
16275 (previous-single-property-change p 'face)
16276 (next-single-property-change p 'face)) clist))
16277 ((memq 'org-special-keyword faces)
16278 (push (list :keyword
16279 (previous-single-property-change p 'face)
16280 (next-single-property-change p 'face)) clist))
16281 ((org-on-target-p)
16282 (push (org-point-in-group p 0 :target) clist)
16283 (goto-char (1- (match-beginning 0)))
16284 (if (looking-at org-radio-target-regexp)
16285 (push (org-point-in-group p 0 :radio-target) clist))
16286 (goto-char p))
16287 ((setq o (car (delq nil
16288 (mapcar
16289 (lambda (x)
16290 (if (memq x org-latex-fragment-image-overlays) x))
16291 (org-overlays-at (point))))))
16292 (push (list :latex-fragment
16293 (org-overlay-start o) (org-overlay-end o)) clist)
16294 (push (list :latex-preview
16295 (org-overlay-start o) (org-overlay-end o)) clist))
16296 ((org-inside-LaTeX-fragment-p)
16297 ;; FIXME: positions wrong.
16298 (push (list :latex-fragment (point) (point)) clist)))
16300 (setq clist (nreverse (delq nil clist)))
16301 clist))
16303 ;; FIXME: Compare with at-regexp-p Do we need both?
16304 (defun org-in-regexp (re &optional nlines visually)
16305 "Check if point is inside a match of regexp.
16306 Normally only the current line is checked, but you can include NLINES extra
16307 lines both before and after point into the search.
16308 If VISUALLY is set, require that the cursor is not after the match but
16309 really on, so that the block visually is on the match."
16310 (catch 'exit
16311 (let ((pos (point))
16312 (eol (point-at-eol (+ 1 (or nlines 0))))
16313 (inc (if visually 1 0)))
16314 (save-excursion
16315 (beginning-of-line (- 1 (or nlines 0)))
16316 (while (re-search-forward re eol t)
16317 (if (and (<= (match-beginning 0) pos)
16318 (>= (+ inc (match-end 0)) pos))
16319 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16321 (defun org-at-regexp-p (regexp)
16322 "Is point inside a match of REGEXP in the current line?"
16323 (catch 'exit
16324 (save-excursion
16325 (let ((pos (point)) (end (point-at-eol)))
16326 (beginning-of-line 1)
16327 (while (re-search-forward regexp end t)
16328 (if (and (<= (match-beginning 0) pos)
16329 (>= (match-end 0) pos))
16330 (throw 'exit t)))
16331 nil))))
16333 (defun org-occur-in-agenda-files (regexp &optional nlines)
16334 "Call `multi-occur' with buffers for all agenda files."
16335 (interactive "sOrg-files matching: \np")
16336 (let* ((files (org-agenda-files))
16337 (tnames (mapcar 'file-truename files))
16338 (extra org-agenda-text-search-extra-files)
16340 (when (eq (car extra) 'agenda-archives)
16341 (setq extra (cdr extra))
16342 (setq files (org-add-archive-files files)))
16343 (while (setq f (pop extra))
16344 (unless (member (file-truename f) tnames)
16345 (add-to-list 'files f 'append)
16346 (add-to-list 'tnames (file-truename f) 'append)))
16347 (multi-occur
16348 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
16349 regexp)))
16351 (if (boundp 'occur-mode-find-occurrence-hook)
16352 ;; Emacs 23
16353 (add-hook 'occur-mode-find-occurrence-hook
16354 (lambda ()
16355 (when (org-mode-p)
16356 (org-reveal))))
16357 ;; Emacs 22
16358 (defadvice occur-mode-goto-occurrence
16359 (after org-occur-reveal activate)
16360 (and (org-mode-p) (org-reveal)))
16361 (defadvice occur-mode-goto-occurrence-other-window
16362 (after org-occur-reveal activate)
16363 (and (org-mode-p) (org-reveal)))
16364 (defadvice occur-mode-display-occurrence
16365 (after org-occur-reveal activate)
16366 (when (org-mode-p)
16367 (let ((pos (occur-mode-find-occurrence)))
16368 (with-current-buffer (marker-buffer pos)
16369 (save-excursion
16370 (goto-char pos)
16371 (org-reveal)))))))
16373 (defun org-occur-link-in-agenda-files ()
16374 "Create a link and search for it in the agendas.
16375 The link is not stored in `org-stored-links', it is just created
16376 for the search purpose."
16377 (interactive)
16378 (let ((link (condition-case nil
16379 (org-store-link nil)
16380 (error "Unable to create a link to here"))))
16381 (org-occur-in-agenda-files (regexp-quote link))))
16383 (defun org-uniquify (list)
16384 "Remove duplicate elements from LIST."
16385 (let (res)
16386 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16387 res))
16389 (defun org-delete-all (elts list)
16390 "Remove all elements in ELTS from LIST."
16391 (while elts
16392 (setq list (delete (pop elts) list)))
16393 list)
16395 (defun org-back-over-empty-lines ()
16396 "Move backwards over whitespace, to the beginning of the first empty line.
16397 Returns the number of empty lines passed."
16398 (let ((pos (point)))
16399 (skip-chars-backward " \t\n\r")
16400 (beginning-of-line 2)
16401 (goto-char (min (point) pos))
16402 (count-lines (point) pos)))
16404 (defun org-skip-whitespace ()
16405 (skip-chars-forward " \t\n\r"))
16407 (defun org-point-in-group (point group &optional context)
16408 "Check if POINT is in match-group GROUP.
16409 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16410 match. If the match group does ot exist or point is not inside it,
16411 return nil."
16412 (and (match-beginning group)
16413 (>= point (match-beginning group))
16414 (<= point (match-end group))
16415 (if context
16416 (list context (match-beginning group) (match-end group))
16417 t)))
16419 (defun org-switch-to-buffer-other-window (&rest args)
16420 "Switch to buffer in a second window on the current frame.
16421 In particular, do not allow pop-up frames."
16422 (let (pop-up-frames special-display-buffer-names special-display-regexps
16423 special-display-function)
16424 (apply 'switch-to-buffer-other-window args)))
16426 (defun org-combine-plists (&rest plists)
16427 "Create a single property list from all plists in PLISTS.
16428 The process starts by copying the first list, and then setting properties
16429 from the other lists. Settings in the last list are the most significant
16430 ones and overrule settings in the other lists."
16431 (let ((rtn (copy-sequence (pop plists)))
16432 p v ls)
16433 (while plists
16434 (setq ls (pop plists))
16435 (while ls
16436 (setq p (pop ls) v (pop ls))
16437 (setq rtn (plist-put rtn p v))))
16438 rtn))
16440 (defun org-move-line-down (arg)
16441 "Move the current line down. With prefix argument, move it past ARG lines."
16442 (interactive "p")
16443 (let ((col (current-column))
16444 beg end pos)
16445 (beginning-of-line 1) (setq beg (point))
16446 (beginning-of-line 2) (setq end (point))
16447 (beginning-of-line (+ 1 arg))
16448 (setq pos (move-marker (make-marker) (point)))
16449 (insert (delete-and-extract-region beg end))
16450 (goto-char pos)
16451 (org-move-to-column col)))
16453 (defun org-move-line-up (arg)
16454 "Move the current line up. With prefix argument, move it past ARG lines."
16455 (interactive "p")
16456 (let ((col (current-column))
16457 beg end pos)
16458 (beginning-of-line 1) (setq beg (point))
16459 (beginning-of-line 2) (setq end (point))
16460 (beginning-of-line (- arg))
16461 (setq pos (move-marker (make-marker) (point)))
16462 (insert (delete-and-extract-region beg end))
16463 (goto-char pos)
16464 (org-move-to-column col)))
16466 (defun org-replace-escapes (string table)
16467 "Replace %-escapes in STRING with values in TABLE.
16468 TABLE is an association list with keys like \"%a\" and string values.
16469 The sequences in STRING may contain normal field width and padding information,
16470 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
16471 so values can contain further %-escapes if they are define later in TABLE."
16472 (let ((case-fold-search nil)
16473 e re rpl)
16474 (while (setq e (pop table))
16475 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
16476 (while (string-match re string)
16477 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
16478 (cdr e)))
16479 (setq string (replace-match rpl t t string))))
16480 string))
16483 (defun org-sublist (list start end)
16484 "Return a section of LIST, from START to END.
16485 Counting starts at 1."
16486 (let (rtn (c start))
16487 (setq list (nthcdr (1- start) list))
16488 (while (and list (<= c end))
16489 (push (pop list) rtn)
16490 (setq c (1+ c)))
16491 (nreverse rtn)))
16493 (defun org-find-base-buffer-visiting (file)
16494 "Like `find-buffer-visiting' but always return the base buffer and
16495 not an indirect buffer."
16496 (let ((buf (or (get-file-buffer file)
16497 (find-buffer-visiting file))))
16498 (if buf
16499 (or (buffer-base-buffer buf) buf)
16500 nil)))
16502 (defun org-image-file-name-regexp (&optional extensions)
16503 "Return regexp matching the file names of images.
16504 If EXTENSIONS is given, only match these."
16505 (if (and (not extensions) (fboundp 'image-file-name-regexp))
16506 (image-file-name-regexp)
16507 (let ((image-file-name-extensions
16508 (or extensions
16509 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16510 "xbm" "xpm" "pbm" "pgm" "ppm"))))
16511 (concat "\\."
16512 (regexp-opt (nconc (mapcar 'upcase
16513 image-file-name-extensions)
16514 image-file-name-extensions)
16516 "\\'"))))
16518 (defun org-file-image-p (file &optional extensions)
16519 "Return non-nil if FILE is an image."
16520 (save-match-data
16521 (string-match (org-image-file-name-regexp extensions) file)))
16523 (defun org-get-cursor-date ()
16524 "Return the date at cursor in as a time.
16525 This works in the calendar and in the agenda, anywhere else it just
16526 returns the current time."
16527 (let (date day defd)
16528 (cond
16529 ((eq major-mode 'calendar-mode)
16530 (setq date (calendar-cursor-to-date)
16531 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16532 ((eq major-mode 'org-agenda-mode)
16533 (setq day (get-text-property (point) 'day))
16534 (if day
16535 (setq date (calendar-gregorian-from-absolute day)
16536 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
16537 (nth 2 date))))))
16538 (or defd (current-time))))
16540 (defvar org-agenda-action-marker (make-marker)
16541 "Marker pointing to the entry for the next agenda action.")
16543 (defun org-mark-entry-for-agenda-action ()
16544 "Mark the current entry as target of an agenda action.
16545 Agenda actions are actions executed from the agenda with the key `k',
16546 which make use of the date at the cursor."
16547 (interactive)
16548 (move-marker org-agenda-action-marker
16549 (save-excursion (org-back-to-heading t) (point))
16550 (current-buffer))
16551 (message
16552 "Entry marked for action; press `k' at desired date in agenda or calendar"))
16554 ;;; Paragraph filling stuff.
16555 ;; We want this to be just right, so use the full arsenal.
16557 (defun org-indent-line-function ()
16558 "Indent line like previous, but further if previous was headline or item."
16559 (interactive)
16560 (let* ((pos (point))
16561 (itemp (org-at-item-p))
16562 (case-fold-search t)
16563 (org-drawer-regexp (or org-drawer-regexp "\000"))
16564 column bpos bcol tpos tcol bullet btype bullet-type)
16565 ;; Find the previous relevant line
16566 (beginning-of-line 1)
16567 (cond
16568 ((looking-at "#") (setq column 0))
16569 ((looking-at "\\*+ ") (setq column 0))
16570 ((and (looking-at "[ \t]*:END:")
16571 (save-excursion (re-search-backward org-drawer-regexp nil t)))
16572 (save-excursion
16573 (goto-char (1- (match-beginning 1)))
16574 (setq column (current-column))))
16575 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
16576 (save-excursion
16577 (re-search-backward
16578 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
16579 (setq column (org-get-indentation (match-string 0))))
16581 (beginning-of-line 0)
16582 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
16583 (not (looking-at "[ \t]*:END:"))
16584 (not (looking-at org-drawer-regexp)))
16585 (beginning-of-line 0))
16586 (cond
16587 ((looking-at "\\*+[ \t]+")
16588 (if (not org-adapt-indentation)
16589 (setq column 0)
16590 (goto-char (match-end 0))
16591 (setq column (current-column))))
16592 ((looking-at org-drawer-regexp)
16593 (goto-char (1- (match-beginning 1)))
16594 (setq column (current-column)))
16595 ((looking-at "\\([ \t]*\\):END:")
16596 (goto-char (match-end 1))
16597 (setq column (current-column)))
16598 ((org-in-item-p)
16599 (org-beginning-of-item)
16600 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
16601 (setq bpos (match-beginning 1) tpos (match-end 0)
16602 bcol (progn (goto-char bpos) (current-column))
16603 tcol (progn (goto-char tpos) (current-column))
16604 bullet (match-string 1)
16605 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
16606 (if (> tcol (+ bcol org-description-max-indent))
16607 (setq tcol (+ bcol 5)))
16608 (if (not itemp)
16609 (setq column tcol)
16610 (goto-char pos)
16611 (beginning-of-line 1)
16612 (if (looking-at "\\S-")
16613 (progn
16614 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
16615 (setq bullet (match-string 1)
16616 btype (if (string-match "[0-9]" bullet) "n" bullet))
16617 (setq column (if (equal btype bullet-type) bcol tcol)))
16618 (setq column (org-get-indentation)))))
16619 (t (setq column (org-get-indentation))))))
16620 (goto-char pos)
16621 (if (<= (current-column) (current-indentation))
16622 (org-indent-line-to column)
16623 (save-excursion (org-indent-line-to column)))
16624 (setq column (current-column))
16625 (beginning-of-line 1)
16626 (if (looking-at
16627 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16628 (replace-match (concat (match-string 1)
16629 (format org-property-format
16630 (match-string 2) (match-string 3)))
16631 t t))
16632 (org-move-to-column column)))
16634 (defun org-set-autofill-regexps ()
16635 (interactive)
16636 ;; In the paragraph separator we include headlines, because filling
16637 ;; text in a line directly attached to a headline would otherwise
16638 ;; fill the headline as well.
16639 (org-set-local 'comment-start-skip "^#+[ \t]*")
16640 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
16641 ;; The paragraph starter includes hand-formatted lists.
16642 (org-set-local
16643 'paragraph-start
16644 (concat
16645 "\f" "\\|"
16646 "[ ]*$" "\\|"
16647 "\\*+ " "\\|"
16648 "[ \t]*#" "\\|"
16649 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16650 "[ \t]*[:|]" "\\|"
16651 "\\$\\$" "\\|"
16652 "\\\\\\(begin\\|end\\|[][]\\)"))
16653 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16654 ;; But only if the user has not turned off tables or fixed-width regions
16655 (org-set-local
16656 'auto-fill-inhibit-regexp
16657 (concat "\\*+ \\|#\\+"
16658 "\\|[ \t]*" org-keyword-time-regexp
16659 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16660 (concat
16661 "\\|[ \t]*["
16662 (if org-enable-table-editor "|" "")
16663 (if org-enable-fixed-width-editor ":" "")
16664 "]"))))
16665 ;; We use our own fill-paragraph function, to make sure that tables
16666 ;; and fixed-width regions are not wrapped. That function will pass
16667 ;; through to `fill-paragraph' when appropriate.
16668 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16669 ; Adaptive filling: To get full control, first make sure that
16670 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16671 (org-set-local 'adaptive-fill-regexp "\000")
16672 (org-set-local 'adaptive-fill-function
16673 'org-adaptive-fill-function)
16674 (org-set-local
16675 'align-mode-rules-list
16676 '((org-in-buffer-settings
16677 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
16678 (modes . '(org-mode))))))
16680 (defun org-fill-paragraph (&optional justify)
16681 "Re-align a table, pass through to fill-paragraph if no table."
16682 (let ((table-p (org-at-table-p))
16683 (table.el-p (org-at-table.el-p)))
16684 (cond ((and (equal (char-after (point-at-bol)) ?*)
16685 (save-excursion (goto-char (point-at-bol))
16686 (looking-at outline-regexp)))
16687 t) ; skip headlines
16688 (table.el-p t) ; skip table.el tables
16689 (table-p (org-table-align) t) ; align org-mode tables
16690 (t nil)))) ; call paragraph-fill
16692 ;; For reference, this is the default value of adaptive-fill-regexp
16693 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16695 (defun org-adaptive-fill-function ()
16696 "Return a fill prefix for org-mode files.
16697 In particular, this makes sure hanging paragraphs for hand-formatted lists
16698 work correctly."
16699 (cond ((looking-at "#[ \t]+")
16700 (match-string 0))
16701 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
16702 (save-excursion
16703 (if (> (match-end 1) (+ (match-beginning 1)
16704 org-description-max-indent))
16705 (goto-char (+ (match-beginning 1) 5))
16706 (goto-char (match-end 0)))
16707 (make-string (current-column) ?\ )))
16708 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
16709 (save-excursion
16710 (goto-char (match-end 0))
16711 (make-string (current-column) ?\ )))
16712 (t nil)))
16714 ;;; Other stuff.
16716 (defun org-toggle-fixed-width-section (arg)
16717 "Toggle the fixed-width export.
16718 If there is no active region, the QUOTE keyword at the current headline is
16719 inserted or removed. When present, it causes the text between this headline
16720 and the next to be exported as fixed-width text, and unmodified.
16721 If there is an active region, this command adds or removes a colon as the
16722 first character of this line. If the first character of a line is a colon,
16723 this line is also exported in fixed-width font."
16724 (interactive "P")
16725 (let* ((cc 0)
16726 (regionp (org-region-active-p))
16727 (beg (if regionp (region-beginning) (point)))
16728 (end (if regionp (region-end)))
16729 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
16730 (case-fold-search nil)
16731 (re "[ \t]*\\(: \\)")
16732 off)
16733 (if regionp
16734 (save-excursion
16735 (goto-char beg)
16736 (setq cc (current-column))
16737 (beginning-of-line 1)
16738 (setq off (looking-at re))
16739 (while (> nlines 0)
16740 (setq nlines (1- nlines))
16741 (beginning-of-line 1)
16742 (cond
16743 (arg
16744 (org-move-to-column cc t)
16745 (insert ": \n")
16746 (forward-line -1))
16747 ((and off (looking-at re))
16748 (replace-match "" t t nil 1))
16749 ((not off) (org-move-to-column cc t) (insert ": ")))
16750 (forward-line 1)))
16751 (save-excursion
16752 (org-back-to-heading)
16753 (if (looking-at (concat outline-regexp
16754 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
16755 (replace-match "" t t nil 1)
16756 (if (looking-at outline-regexp)
16757 (progn
16758 (goto-char (match-end 0))
16759 (insert org-quote-string " "))))))))
16761 (defun org-reftex-citation ()
16762 "Use reftex-citation to insert a citation into the buffer.
16763 This looks for a line like
16765 #+BIBLIOGRAPHY: foo plain option:-d
16767 and derives from it that foo.bib is the bbliography file relevant
16768 for this document. It then installs the necessary environment for RefTeX
16769 to work in this buffer and calls `reftex-citation' to insert a citation
16770 into the buffer.
16772 Export of such citations to both LaTeX and HTML is handled by the contributed
16773 package org-exp-bibtex by Taru Karttunen."
16774 (interactive)
16775 (let ((reftex-docstruct-symbol 'rds)
16776 (reftex-cite-format "\\cite{%l}")
16777 rds bib)
16778 (save-excursion
16779 (save-restriction
16780 (widen)
16781 (let ((case-fold-search t)
16782 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
16783 (if (not (save-excursion
16784 (or (re-search-forward re nil t)
16785 (re-search-backward re nil t))))
16786 (error "No bibliography defined in file")
16787 (setq bib (concat (match-string 1) ".bib")
16788 rds (list (list 'bib bib)))))))
16789 (call-interactively 'reftex-citation)))
16791 ;;;; Functions extending outline functionality
16793 (defun org-beginning-of-line (&optional arg)
16794 "Go to the beginning of the current line. If that is invisible, continue
16795 to a visible line beginning. This makes the function of C-a more intuitive.
16796 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16797 first attempt, and only move to after the tags when the cursor is already
16798 beyond the end of the headline."
16799 (interactive "P")
16800 (let ((pos (point))
16801 (special (if (consp org-special-ctrl-a/e)
16802 (car org-special-ctrl-a/e)
16803 org-special-ctrl-a/e))
16804 refpos)
16805 (if (org-bound-and-true-p line-move-visual)
16806 (beginning-of-visual-line 1)
16807 (beginning-of-line 1))
16808 (if (and arg (fboundp 'move-beginning-of-line))
16809 (call-interactively 'move-beginning-of-line)
16810 (if (bobp)
16812 (backward-char 1)
16813 (if (org-invisible-p)
16814 (while (and (not (bobp)) (org-invisible-p))
16815 (backward-char 1)
16816 (beginning-of-line 1))
16817 (forward-char 1))))
16818 (when special
16819 (cond
16820 ((and (looking-at org-complex-heading-regexp)
16821 (= (char-after (match-end 1)) ?\ ))
16822 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
16823 (point-at-eol)))
16824 (goto-char
16825 (if (eq special t)
16826 (cond ((> pos refpos) refpos)
16827 ((= pos (point)) refpos)
16828 (t (point)))
16829 (cond ((> pos (point)) (point))
16830 ((not (eq last-command this-command)) (point))
16831 (t refpos)))))
16832 ((org-at-item-p)
16833 (goto-char
16834 (if (eq special t)
16835 (cond ((> pos (match-end 4)) (match-end 4))
16836 ((= pos (point)) (match-end 4))
16837 (t (point)))
16838 (cond ((> pos (point)) (point))
16839 ((not (eq last-command this-command)) (point))
16840 (t (match-end 4))))))))
16841 (org-no-warnings
16842 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16844 (defun org-end-of-line (&optional arg)
16845 "Go to the end of the line.
16846 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16847 first attempt, and only move to after the tags when the cursor is already
16848 beyond the end of the headline."
16849 (interactive "P")
16850 (let ((special (if (consp org-special-ctrl-a/e)
16851 (cdr org-special-ctrl-a/e)
16852 org-special-ctrl-a/e)))
16853 (if (or (not special)
16854 (not (org-on-heading-p))
16855 arg)
16856 (call-interactively
16857 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
16858 ((fboundp 'move-end-of-line) 'move-end-of-line)
16859 (t 'end-of-line)))
16860 (let ((pos (point)))
16861 (beginning-of-line 1)
16862 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
16863 (if (eq special t)
16864 (if (or (< pos (match-beginning 1))
16865 (= pos (match-end 0)))
16866 (goto-char (match-beginning 1))
16867 (goto-char (match-end 0)))
16868 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16869 (goto-char (match-end 0))
16870 (goto-char (match-beginning 1))))
16871 (call-interactively (if (fboundp 'move-end-of-line)
16872 'move-end-of-line
16873 'end-of-line)))))
16874 (org-no-warnings
16875 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16877 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16878 (define-key org-mode-map "\C-e" 'org-end-of-line)
16879 (define-key org-mode-map [home] 'org-beginning-of-line)
16880 (define-key org-mode-map [end] 'org-end-of-line)
16882 (defun org-backward-sentence (&optional arg)
16883 "Go to beginning of sentence, or beginning of table field.
16884 This will call `backward-sentence' or `org-table-beginning-of-field',
16885 depending on context."
16886 (interactive "P")
16887 (cond
16888 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16889 (t (call-interactively 'backward-sentence))))
16891 (defun org-forward-sentence (&optional arg)
16892 "Go to end of sentence, or end of table field.
16893 This will call `forward-sentence' or `org-table-end-of-field',
16894 depending on context."
16895 (interactive "P")
16896 (cond
16897 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16898 (t (call-interactively 'forward-sentence))))
16900 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16901 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16903 (defun org-kill-line (&optional arg)
16904 "Kill line, to tags or end of line."
16905 (interactive "P")
16906 (cond
16907 ((or (not org-special-ctrl-k)
16908 (bolp)
16909 (not (org-on-heading-p)))
16910 (call-interactively 'kill-line))
16911 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16912 (kill-region (point) (match-beginning 1))
16913 (org-set-tags nil t))
16914 (t (kill-region (point) (point-at-eol)))))
16916 (define-key org-mode-map "\C-k" 'org-kill-line)
16918 (defun org-yank (&optional arg)
16919 "Yank. If the kill is a subtree, treat it specially.
16920 This command will look at the current kill and check if is a single
16921 subtree, or a series of subtrees[1]. If it passes the test, and if the
16922 cursor is at the beginning of a line or after the stars of a currently
16923 empty headline, then the yank is handled specially. How exactly depends
16924 on the value of the following variables, both set by default.
16926 org-yank-folded-subtrees
16927 When set, the subtree(s) will be folded after insertion, but only
16928 if doing so would now swallow text after the yanked text.
16930 org-yank-adjusted-subtrees
16931 When set, the subtree will be promoted or demoted in order to
16932 fit into the local outline tree structure, which means that the level
16933 will be adjusted so that it becomes the smaller one of the two
16934 *visible* surrounding headings.
16936 Any prefix to this command will cause `yank' to be called directly with
16937 no special treatment. In particular, a simple `C-u' prefix will just
16938 plainly yank the text as it is.
16940 \[1] The test checks if the first non-white line is a heading
16941 and if there are no other headings with fewer stars."
16942 (interactive "P")
16943 (org-yank-generic 'yank arg))
16945 (defun org-yank-generic (command arg)
16946 "Perform some yank-like command.
16948 This function implements the behavior described in the `org-yank'
16949 documentation. However, it has been generalized to work for any
16950 interactive command with similar behavior."
16952 ;; pretend to be command COMMAND
16953 (setq this-command command)
16955 (if arg
16956 (call-interactively command)
16958 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16959 (and (org-kill-is-subtree-p)
16960 (or (bolp)
16961 (and (looking-at "[ \t]*$")
16962 (string-match
16963 "\\`\\*+\\'"
16964 (buffer-substring (point-at-bol) (point)))))))
16965 swallowp)
16966 (cond
16967 ((and subtreep org-yank-folded-subtrees)
16968 (let ((beg (point))
16969 end)
16970 (if (and subtreep org-yank-adjusted-subtrees)
16971 (org-paste-subtree nil nil 'for-yank)
16972 (call-interactively command))
16974 (setq end (point))
16975 (goto-char beg)
16976 (when (and (bolp) subtreep
16977 (not (setq swallowp
16978 (org-yank-folding-would-swallow-text beg end))))
16979 (or (looking-at outline-regexp)
16980 (re-search-forward (concat "^" outline-regexp) end t))
16981 (while (and (< (point) end) (looking-at outline-regexp))
16982 (hide-subtree)
16983 (org-cycle-show-empty-lines 'folded)
16984 (condition-case nil
16985 (outline-forward-same-level 1)
16986 (error (goto-char end)))))
16987 (when swallowp
16988 (message
16989 "Inserted text not folded because that would swallow text"))
16991 (goto-char end)
16992 (skip-chars-forward " \t\n\r")
16993 (beginning-of-line 1)
16994 (push-mark beg 'nomsg)))
16995 ((and subtreep org-yank-adjusted-subtrees)
16996 (let ((beg (point-at-bol)))
16997 (org-paste-subtree nil nil 'for-yank)
16998 (push-mark beg 'nomsg)))
17000 (call-interactively command))))))
17002 (defun org-yank-folding-would-swallow-text (beg end)
17003 "Would hide-subtree at BEG swallow any text after END?"
17004 (let (level)
17005 (save-excursion
17006 (goto-char beg)
17007 (when (or (looking-at outline-regexp)
17008 (re-search-forward (concat "^" outline-regexp) end t))
17009 (setq level (org-outline-level)))
17010 (goto-char end)
17011 (skip-chars-forward " \t\r\n\v\f")
17012 (if (or (eobp)
17013 (and (bolp) (looking-at org-outline-regexp)
17014 (<= (org-outline-level) level)))
17015 nil ; Nothing would be swallowed
17016 t)))) ; something would swallow
17018 (define-key org-mode-map "\C-y" 'org-yank)
17020 (defun org-invisible-p ()
17021 "Check if point is at a character currently not visible."
17022 ;; Early versions of noutline don't have `outline-invisible-p'.
17023 (if (fboundp 'outline-invisible-p)
17024 (outline-invisible-p)
17025 (get-char-property (point) 'invisible)))
17027 (defun org-invisible-p2 ()
17028 "Check if point is at a character currently not visible."
17029 (save-excursion
17030 (if (and (eolp) (not (bobp))) (backward-char 1))
17031 ;; Early versions of noutline don't have `outline-invisible-p'.
17032 (if (fboundp 'outline-invisible-p)
17033 (outline-invisible-p)
17034 (get-char-property (point) 'invisible))))
17036 (defun org-back-to-heading (&optional invisible-ok)
17037 "Call `outline-back-to-heading', but provide a better error message."
17038 (condition-case nil
17039 (outline-back-to-heading invisible-ok)
17040 (error (error "Before first headline at position %d in buffer %s"
17041 (point) (current-buffer)))))
17043 (defun org-before-first-heading-p ()
17044 "Before first heading?"
17045 (save-excursion
17046 (null (re-search-backward "^\\*+ " nil t))))
17048 (defun org-on-heading-p (&optional ignored)
17049 (outline-on-heading-p t))
17050 (defun org-at-heading-p (&optional ignored)
17051 (outline-on-heading-p t))
17053 (defun org-at-heading-or-item-p ()
17054 (or (org-on-heading-p) (org-at-item-p)))
17056 (defun org-on-target-p ()
17057 (or (org-in-regexp org-radio-target-regexp)
17058 (org-in-regexp org-target-regexp)))
17060 (defun org-up-heading-all (arg)
17061 "Move to the heading line of which the present line is a subheading.
17062 This function considers both visible and invisible heading lines.
17063 With argument, move up ARG levels."
17064 (if (fboundp 'outline-up-heading-all)
17065 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17066 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17068 (defun org-up-heading-safe ()
17069 "Move to the heading line of which the present line is a subheading.
17070 This version will not throw an error. It will return the level of the
17071 headline found, or nil if no higher level is found.
17073 Also, this function will be a lot faster than `outline-up-heading',
17074 because it relies on stars being the outline starters. This can really
17075 make a significant difference in outlines with very many siblings."
17076 (let (start-level re)
17077 (org-back-to-heading t)
17078 (setq start-level (funcall outline-level))
17079 (if (equal start-level 1)
17081 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17082 (if (re-search-backward re nil t)
17083 (funcall outline-level)))))
17085 (defun org-first-sibling-p ()
17086 "Is this heading the first child of its parents?"
17087 (interactive)
17088 (let ((re (concat "^" outline-regexp))
17089 level l)
17090 (unless (org-at-heading-p t)
17091 (error "Not at a heading"))
17092 (setq level (funcall outline-level))
17093 (save-excursion
17094 (if (not (re-search-backward re nil t))
17096 (setq l (funcall outline-level))
17097 (< l level)))))
17099 (defun org-goto-sibling (&optional previous)
17100 "Goto the next sibling, even if it is invisible.
17101 When PREVIOUS is set, go to the previous sibling instead. Returns t
17102 when a sibling was found. When none is found, return nil and don't
17103 move point."
17104 (let ((fun (if previous 're-search-backward 're-search-forward))
17105 (pos (point))
17106 (re (concat "^" outline-regexp))
17107 level l)
17108 (when (condition-case nil (org-back-to-heading t) (error nil))
17109 (setq level (funcall outline-level))
17110 (catch 'exit
17111 (or previous (forward-char 1))
17112 (while (funcall fun re nil t)
17113 (setq l (funcall outline-level))
17114 (when (< l level) (goto-char pos) (throw 'exit nil))
17115 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17116 (goto-char pos)
17117 nil))))
17119 (defun org-show-siblings ()
17120 "Show all siblings of the current headline."
17121 (save-excursion
17122 (while (org-goto-sibling) (org-flag-heading nil)))
17123 (save-excursion
17124 (while (org-goto-sibling 'previous)
17125 (org-flag-heading nil))))
17127 (defun org-show-hidden-entry ()
17128 "Show an entry where even the heading is hidden."
17129 (save-excursion
17130 (org-show-entry)))
17132 (defun org-flag-heading (flag &optional entry)
17133 "Flag the current heading. FLAG non-nil means make invisible.
17134 When ENTRY is non-nil, show the entire entry."
17135 (save-excursion
17136 (org-back-to-heading t)
17137 ;; Check if we should show the entire entry
17138 (if entry
17139 (progn
17140 (org-show-entry)
17141 (save-excursion
17142 (and (outline-next-heading)
17143 (org-flag-heading nil))))
17144 (outline-flag-region (max (point-min) (1- (point)))
17145 (save-excursion (outline-end-of-heading) (point))
17146 flag))))
17148 (defun org-get-next-sibling ()
17149 "Move to next heading of the same level, and return point.
17150 If there is no such heading, return nil.
17151 This is like outline-next-sibling, but invisible headings are ok."
17152 (let ((level (funcall outline-level)))
17153 (outline-next-heading)
17154 (while (and (not (eobp)) (> (funcall outline-level) level))
17155 (outline-next-heading))
17156 (if (or (eobp) (< (funcall outline-level) level))
17158 (point))))
17160 (defun org-get-last-sibling ()
17161 "Move to previous heading of the same level, and return point.
17162 If there is no such heading, return nil."
17163 (let ((opoint (point))
17164 (level (funcall outline-level)))
17165 (outline-previous-heading)
17166 (when (and (/= (point) opoint) (outline-on-heading-p t))
17167 (while (and (> (funcall outline-level) level)
17168 (not (bobp)))
17169 (outline-previous-heading))
17170 (if (< (funcall outline-level) level)
17172 (point)))))
17174 (defun org-end-of-subtree (&optional invisible-OK to-heading)
17175 ;; This contains an exact copy of the original function, but it uses
17176 ;; `org-back-to-heading', to make it work also in invisible
17177 ;; trees. And is uses an invisible-OK argument.
17178 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17179 ;; Furthermore, when used inside Org, finding the end of a large subtree
17180 ;; with many children and grandchildren etc, this can be much faster
17181 ;; than the outline version.
17182 (org-back-to-heading invisible-OK)
17183 (let ((first t)
17184 (level (funcall outline-level)))
17185 (if (and (org-mode-p) (< level 1000))
17186 ;; A true heading (not a plain list item), in Org-mode
17187 ;; This means we can easily find the end by looking
17188 ;; only for the right number of stars. Using a regexp to do
17189 ;; this is so much faster than using a Lisp loop.
17190 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
17191 (forward-char 1)
17192 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
17193 ;; something else, do it the slow way
17194 (while (and (not (eobp))
17195 (or first (> (funcall outline-level) level)))
17196 (setq first nil)
17197 (outline-next-heading)))
17198 (unless to-heading
17199 (if (memq (preceding-char) '(?\n ?\^M))
17200 (progn
17201 ;; Go to end of line before heading
17202 (forward-char -1)
17203 (if (memq (preceding-char) '(?\n ?\^M))
17204 ;; leave blank line before heading
17205 (forward-char -1))))))
17206 (point))
17208 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
17209 "Use Org version in org-mode, for dramatic speed-up."
17210 (if (eq major-mode 'org-mode)
17211 (progn
17212 (org-end-of-subtree nil t)
17213 (unless (eobp) (backward-char 1)))
17214 ad-do-it))
17216 (defun org-forward-same-level (arg &optional invisible-ok)
17217 "Move forward to the arg'th subheading at same level as this one.
17218 Stop at the first and last subheadings of a superior heading."
17219 (interactive "p")
17220 (org-back-to-heading invisible-ok)
17221 (org-on-heading-p)
17222 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17223 (re (format "^\\*\\{1,%d\\} " level))
17225 (forward-char 1)
17226 (while (> arg 0)
17227 (while (and (re-search-forward re nil 'move)
17228 (setq l (- (match-end 0) (match-beginning 0) 1))
17229 (= l level)
17230 (not invisible-ok)
17231 (org-invisible-p))
17232 (if (< l level) (setq arg 1)))
17233 (setq arg (1- arg)))
17234 (beginning-of-line 1)))
17236 (defun org-backward-same-level (arg &optional invisible-ok)
17237 "Move backward to the arg'th subheading at same level as this one.
17238 Stop at the first and last subheadings of a superior heading."
17239 (interactive "p")
17240 (org-back-to-heading)
17241 (org-on-heading-p)
17242 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17243 (re (format "^\\*\\{1,%d\\} " level))
17245 (while (> arg 0)
17246 (while (and (re-search-backward re nil 'move)
17247 (setq l (- (match-end 0) (match-beginning 0) 1))
17248 (= l level)
17249 (not invisible-ok)
17250 (org-invisible-p))
17251 (if (< l level) (setq arg 1)))
17252 (setq arg (1- arg)))))
17254 (defun org-show-subtree ()
17255 "Show everything after this heading at deeper levels."
17256 (outline-flag-region
17257 (point)
17258 (save-excursion
17259 (org-end-of-subtree t t))
17260 nil))
17262 (defun org-show-entry ()
17263 "Show the body directly following this heading.
17264 Show the heading too, if it is currently invisible."
17265 (interactive)
17266 (save-excursion
17267 (condition-case nil
17268 (progn
17269 (org-back-to-heading t)
17270 (outline-flag-region
17271 (max (point-min) (1- (point)))
17272 (save-excursion
17273 (if (re-search-forward
17274 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17275 (match-beginning 1)
17276 (point-max)))
17277 nil)
17278 (org-cycle-hide-drawers 'children))
17279 (error nil))))
17281 (defun org-make-options-regexp (kwds &optional extra)
17282 "Make a regular expression for keyword lines."
17283 (concat
17285 "#?[ \t]*\\+\\("
17286 (mapconcat 'regexp-quote kwds "\\|")
17287 (if extra (concat "\\|" extra))
17288 "\\):[ \t]*"
17289 "\\(.*\\)"))
17291 ;; Make isearch reveal the necessary context
17292 (defun org-isearch-end ()
17293 "Reveal context after isearch exits."
17294 (when isearch-success ; only if search was successful
17295 (if (featurep 'xemacs)
17296 ;; Under XEmacs, the hook is run in the correct place,
17297 ;; we directly show the context.
17298 (org-show-context 'isearch)
17299 ;; In Emacs the hook runs *before* restoring the overlays.
17300 ;; So we have to use a one-time post-command-hook to do this.
17301 ;; (Emacs 22 has a special variable, see function `org-mode')
17302 (unless (and (boundp 'isearch-mode-end-hook-quit)
17303 isearch-mode-end-hook-quit)
17304 ;; Only when the isearch was not quitted.
17305 (org-add-hook 'post-command-hook 'org-isearch-post-command
17306 'append 'local)))))
17308 (defun org-isearch-post-command ()
17309 "Remove self from hook, and show context."
17310 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17311 (org-show-context 'isearch))
17314 ;;;; Integration with and fixes for other packages
17316 ;;; Imenu support
17318 (defvar org-imenu-markers nil
17319 "All markers currently used by Imenu.")
17320 (make-variable-buffer-local 'org-imenu-markers)
17322 (defun org-imenu-new-marker (&optional pos)
17323 "Return a new marker for use by Imenu, and remember the marker."
17324 (let ((m (make-marker)))
17325 (move-marker m (or pos (point)))
17326 (push m org-imenu-markers)
17329 (defun org-imenu-get-tree ()
17330 "Produce the index for Imenu."
17331 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17332 (setq org-imenu-markers nil)
17333 (let* ((n org-imenu-depth)
17334 (re (concat "^" outline-regexp))
17335 (subs (make-vector (1+ n) nil))
17336 (last-level 0)
17337 m level head)
17338 (save-excursion
17339 (save-restriction
17340 (widen)
17341 (goto-char (point-max))
17342 (while (re-search-backward re nil t)
17343 (setq level (org-reduced-level (funcall outline-level)))
17344 (when (<= level n)
17345 (looking-at org-complex-heading-regexp)
17346 (setq head (org-link-display-format
17347 (org-match-string-no-properties 4))
17348 m (org-imenu-new-marker))
17349 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17350 (if (>= level last-level)
17351 (push (cons head m) (aref subs level))
17352 (push (cons head (aref subs (1+ level))) (aref subs level))
17353 (loop for i from (1+ level) to n do (aset subs i nil)))
17354 (setq last-level level)))))
17355 (aref subs 1)))
17357 (eval-after-load "imenu"
17358 '(progn
17359 (add-hook 'imenu-after-jump-hook
17360 (lambda ()
17361 (if (eq major-mode 'org-mode)
17362 (org-show-context 'org-goto))))))
17364 (defun org-link-display-format (link)
17365 "Replace a link with either the description, or the link target
17366 if no description is present"
17367 (save-match-data
17368 (if (string-match org-bracket-link-analytic-regexp link)
17369 (replace-match (or (match-string 5 link)
17370 (concat (match-string 1 link)
17371 (match-string 3 link)))
17372 nil nil link)
17373 link)))
17375 ;; Speedbar support
17377 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17378 "Overlay marking the agenda restriction line in speedbar.")
17379 (org-overlay-put org-speedbar-restriction-lock-overlay
17380 'face 'org-agenda-restriction-lock)
17381 (org-overlay-put org-speedbar-restriction-lock-overlay
17382 'help-echo "Agendas are currently limited to this item.")
17383 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17385 (defun org-speedbar-set-agenda-restriction ()
17386 "Restrict future agenda commands to the location at point in speedbar.
17387 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17388 (interactive)
17389 (require 'org-agenda)
17390 (let (p m tp np dir txt)
17391 (cond
17392 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17393 'org-imenu t))
17394 (setq m (get-text-property p 'org-imenu-marker))
17395 (save-excursion
17396 (save-restriction
17397 (set-buffer (marker-buffer m))
17398 (goto-char m)
17399 (org-agenda-set-restriction-lock 'subtree))))
17400 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17401 'speedbar-function 'speedbar-find-file))
17402 (setq tp (previous-single-property-change
17403 (1+ p) 'speedbar-function)
17404 np (next-single-property-change
17405 tp 'speedbar-function)
17406 dir (speedbar-line-directory)
17407 txt (buffer-substring-no-properties (or tp (point-min))
17408 (or np (point-max))))
17409 (save-excursion
17410 (save-restriction
17411 (set-buffer (find-file-noselect
17412 (let ((default-directory dir))
17413 (expand-file-name txt))))
17414 (unless (org-mode-p)
17415 (error "Cannot restrict to non-Org-mode file"))
17416 (org-agenda-set-restriction-lock 'file))))
17417 (t (error "Don't know how to restrict Org-mode's agenda")))
17418 (org-move-overlay org-speedbar-restriction-lock-overlay
17419 (point-at-bol) (point-at-eol))
17420 (setq current-prefix-arg nil)
17421 (org-agenda-maybe-redo)))
17423 (eval-after-load "speedbar"
17424 '(progn
17425 (speedbar-add-supported-extension ".org")
17426 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
17427 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
17428 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
17429 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17430 (add-hook 'speedbar-visiting-tag-hook
17431 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
17434 ;;; Fixes and Hacks for problems with other packages
17436 ;; Make flyspell not check words in links, to not mess up our keymap
17437 (defun org-mode-flyspell-verify ()
17438 "Don't let flyspell put overlays at active buttons."
17439 (and (not (get-text-property (point) 'keymap))
17440 (not (get-text-property (point) 'org-no-flyspell))))
17442 (defun org-remove-flyspell-overlays-in (beg end)
17443 "Remove flyspell overlays in region."
17444 (and (org-bound-and-true-p flyspell-mode)
17445 (fboundp 'flyspell-delete-region-overlays)
17446 (flyspell-delete-region-overlays beg end))
17447 (add-text-properties beg end '(org-no-flyspell t)))
17449 ;; Make `bookmark-jump' shows the jump location if it was hidden.
17450 (eval-after-load "bookmark"
17451 '(if (boundp 'bookmark-after-jump-hook)
17452 ;; We can use the hook
17453 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17454 ;; Hook not available, use advice
17455 (defadvice bookmark-jump (after org-make-visible activate)
17456 "Make the position visible."
17457 (org-bookmark-jump-unhide))))
17459 ;; Make sure saveplace shows the location if it was hidden
17460 (eval-after-load "saveplace"
17461 '(defadvice save-place-find-file-hook (after org-make-visible activate)
17462 "Make the position visible."
17463 (org-bookmark-jump-unhide)))
17465 ;; Make sure ecb shows the location if it was hidden
17466 (eval-after-load "ecb"
17467 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
17468 "Make hierarchy visible when jumping into location from ECB tree buffer."
17469 (if (eq major-mode 'org-mode)
17470 (org-show-context))))
17472 (defun org-bookmark-jump-unhide ()
17473 "Unhide the current position, to show the bookmark location."
17474 (and (org-mode-p)
17475 (or (org-invisible-p)
17476 (save-excursion (goto-char (max (point-min) (1- (point))))
17477 (org-invisible-p)))
17478 (org-show-context 'bookmark-jump)))
17480 ;; Make session.el ignore our circular variable
17481 (eval-after-load "session"
17482 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17484 ;;;; Experimental code
17486 (defun org-closed-in-range ()
17487 "Sparse tree of items closed in a certain time range.
17488 Still experimental, may disappear in the future."
17489 (interactive)
17490 ;; Get the time interval from the user.
17491 (let* ((time1 (org-float-time
17492 (org-read-date nil 'to-time nil "Starting date: ")))
17493 (time2 (org-float-time
17494 (org-read-date nil 'to-time nil "End date:")))
17495 ;; callback function
17496 (callback (lambda ()
17497 (let ((time
17498 (org-float-time
17499 (apply 'encode-time
17500 (org-parse-time-string
17501 (match-string 1))))))
17502 ;; check if time in interval
17503 (and (>= time time1) (<= time time2))))))
17504 ;; make tree, check each match with the callback
17505 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
17507 ;;;; Finish up
17509 (provide 'org)
17511 (run-hooks 'org-load-hook)
17513 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17515 ;;; org.el ends here