Reorganize Custom groups.
[emacs.git] / lisp / org / org.el
blob54025f4d83ca416328c6debff4efabb590e4c661
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, 2010
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.33x
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.33x"
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* ((origin default-directory)
106 (version org-version)
107 (git-version)
108 (dir (concat (file-name-directory (locate-library "org")) "../" )))
109 (when (and (file-exists-p (expand-file-name ".git" dir))
110 (executable-find "git"))
111 (unwind-protect
112 (progn
113 (cd dir)
114 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
115 (with-current-buffer "*Shell Command Output*"
116 (goto-char (point-min))
117 (setq git-version (buffer-substring (point) (point-at-eol))))
118 (subst-char-in-string ?- ?. git-version t)
119 (when (string-match "\\S-"
120 (shell-command-to-string
121 "git diff-index --name-only HEAD --"))
122 (setq git-version (concat git-version ".dirty")))
123 (setq version (concat version " (" git-version ")"))))
124 (cd origin)))
125 (setq version (format "Org-mode version %s" version))
126 (if here (insert version))
127 (message 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 'calendar)
139 (defcustom org-mode-hook nil
140 "Mode hook for Org-mode, run after the mode was turned on."
141 :group 'org
142 :type 'hook)
144 (defcustom org-load-hook nil
145 "Hook that is run after org.el has been loaded."
146 :group 'org
147 :type 'hook)
149 (defvar org-modules) ; defined below
150 (defvar org-modules-loaded nil
151 "Have the modules been loaded already?")
153 (defun org-load-modules-maybe (&optional force)
154 "Load all extensions listed in `org-modules'."
155 (when (or force (not org-modules-loaded))
156 (mapc (lambda (ext)
157 (condition-case nil (require ext)
158 (error (message "Problems while trying to load feature `%s'" ext))))
159 org-modules)
160 (setq org-modules-loaded t)))
162 (defun org-set-modules (var value)
163 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
164 (set var value)
165 (when (featurep 'org)
166 (org-load-modules-maybe 'force)))
168 (when (org-bound-and-true-p org-modules)
169 (let ((a (member 'org-infojs org-modules)))
170 (and a (setcar a 'org-jsinfo))))
172 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
173 "Modules that should always be loaded together with org.el.
174 If a description starts with <C>, the file is not part of Emacs
175 and loading it will require that you have downloaded and properly installed
176 the org-mode distribution.
178 You can also use this system to load external packages (i.e. neither Org
179 core modules, nor modules from the CONTRIB directory). Just add symbols
180 to the end of the list. If the package is called org-xyz.el, then you need
181 to add the symbol `xyz', and the package must have a call to
183 (provide 'org-xyz)"
184 :group 'org
185 :set 'org-set-modules
186 :type
187 '(set :greedy t
188 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
189 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
190 (const :tag " crypt: Encryption of subtrees" org-crypt)
191 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
192 (const :tag " id: Global IDs for identifying entries" org-id)
193 (const :tag " info: Links to Info nodes" org-info)
194 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
195 (const :tag " habit: Track your consistency with habits" org-habit)
196 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
197 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
198 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
199 (const :tag " mew Links to Mew folders/messages" org-mew)
200 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
201 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
202 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
203 (const :tag " vm: Links to VM folders/messages" org-vm)
204 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
205 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
206 (const :tag " mouse: Additional mouse support" org-mouse)
208 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
209 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
210 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
211 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
212 (const :tag "C collector: Collect properties into tables" org-collector)
213 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
214 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
215 (const :tag "C eval: Include command output as text" org-eval)
216 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
217 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
218 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
219 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
220 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
222 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
224 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
225 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
226 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
227 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
228 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
229 (const :tag "C mtags: Support for muse-like tags" org-mtags)
230 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
231 (const :tag "C R: Computation using the R language" org-R)
232 (const :tag "C registry: A registry for Org-mode links" org-registry)
233 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
234 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
235 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
236 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
237 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
238 (const :tag "C track: Keep up with Org-mode development" org-track)
239 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
241 (defcustom org-support-shift-select nil
242 "Non-nil means, make shift-cursor commands select text when possible.
244 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
245 selecting a region, or enlarge thusly regions started in this way.
246 In Org-mode, in special contexts, these same keys are used for other
247 purposes, important enough to compete with shift selection. Org tries
248 to balance these needs by supporting `shift-select-mode' outside these
249 special contexts, under control of this variable.
251 The default of this variable is nil, to avoid confusing behavior. Shifted
252 cursor keys will then execute Org commands in the following contexts:
253 - on a headline, changing TODO state (left/right) and priority (up/down)
254 - on a time stamp, changing the time
255 - in a plain list item, changing the bullet type
256 - in a property definition line, switching between allowed values
257 - in the BEGIN line of a clock table (changing the time block).
258 Outside these contexts, the commands will throw an error.
260 When this variable is t and the cursor is not in a special context,
261 Org-mode will support shift-selection for making and enlarging regions.
262 To make this more effective, the bullet cycling will no longer happen
263 anywhere in an item line, but only if the cursor is exactly on the bullet.
265 If you set this variable to the symbol `always', then the keys
266 will not be special in headlines, property lines, and item lines, to make
267 shift selection work there as well. If this is what you want, you can
268 use the following alternative commands: `C-c C-t' and `C-c ,' to
269 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
270 TODO sets, `C-c -' to cycle item bullet types, and properties can be
271 edited by hand or in column view.
273 However, when the cursor is on a timestamp, shift-cursor commands
274 will still edit the time stamp - this is just too good to give up.
276 XEmacs user should have this variable set to nil, because shift-select-mode
277 is Emacs 23 only."
278 :group 'org
279 :type '(choice
280 (const :tag "Never" nil)
281 (const :tag "When outside special context" t)
282 (const :tag "Everywhere except timestamps" always)))
284 (defgroup org-startup nil
285 "Options concerning startup of Org-mode."
286 :tag "Org Startup"
287 :group 'org)
289 (defcustom org-startup-folded t
290 "Non-nil means, entering Org-mode will switch to OVERVIEW.
291 This can also be configured on a per-file basis by adding one of
292 the following lines anywhere in the buffer:
294 #+STARTUP: fold (or `overview', this is equivalent)
295 #+STARTUP: nofold (or `showall', this is equivalent)
296 #+STARTUP: content
297 #+STARTUP: showeverything"
298 :group 'org-startup
299 :type '(choice
300 (const :tag "nofold: show all" nil)
301 (const :tag "fold: overview" t)
302 (const :tag "content: all headlines" content)
303 (const :tag "show everything, even drawers" showeverything)))
305 (defcustom org-startup-truncated t
306 "Non-nil means, entering Org-mode will set `truncate-lines'.
307 This is useful since some lines containing links can be very long and
308 uninteresting. Also tables look terrible when wrapped."
309 :group 'org-startup
310 :type 'boolean)
312 (defcustom org-startup-indented nil
313 "Non-nil means, turn on `org-indent-mode' on startup.
314 This can also be configured on a per-file basis by adding one of
315 the following lines anywhere in the buffer:
317 #+STARTUP: indent
318 #+STARTUP: noindent"
319 :group 'org-structure
320 :type '(choice
321 (const :tag "Not" nil)
322 (const :tag "Globally (slow on startup in large files)" t)))
324 (defcustom org-startup-align-all-tables nil
325 "Non-nil means, align all tables when visiting a file.
326 This is useful when the column width in tables is forced with <N> cookies
327 in table fields. Such tables will look correct only after the first re-align.
328 This can also be configured on a per-file basis by adding one of
329 the following lines anywhere in the buffer:
330 #+STARTUP: align
331 #+STARTUP: noalign"
332 :group 'org-startup
333 :type 'boolean)
335 (defcustom org-insert-mode-line-in-empty-file nil
336 "Non-nil means insert the first line setting Org-mode in empty files.
337 When the function `org-mode' is called interactively in an empty file, this
338 normally means that the file name does not automatically trigger Org-mode.
339 To ensure that the file will always be in Org-mode in the future, a
340 line enforcing Org-mode will be inserted into the buffer, if this option
341 has been set."
342 :group 'org-startup
343 :type 'boolean)
345 (defcustom org-replace-disputed-keys nil
346 "Non-nil means use alternative key bindings for some keys.
347 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
348 These keys are also used by other packages like shift-selection-mode'
349 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
350 If you want to use Org-mode together with one of these other modes,
351 or more generally if you would like to move some Org-mode commands to
352 other keys, set this variable and configure the keys with the variable
353 `org-disputed-keys'.
355 This option is only relevant at load-time of Org-mode, and must be set
356 *before* org.el is loaded. Changing it requires a restart of Emacs to
357 become effective."
358 :group 'org-startup
359 :type 'boolean)
361 (defcustom org-use-extra-keys nil
362 "Non-nil means use extra key sequence definitions for certain
363 commands. This happens automatically if you run XEmacs or if
364 window-system is nil. This variable lets you do the same
365 manually. You must set it before loading org.
367 Example: on Carbon Emacs 22 running graphically, with an external
368 keyboard on a Powerbook, the default way of setting M-left might
369 not work for either Alt or ESC. Setting this variable will make
370 it work for ESC."
371 :group 'org-startup
372 :type 'boolean)
374 (if (fboundp 'defvaralias)
375 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
377 (defcustom org-disputed-keys
378 '(([(shift up)] . [(meta p)])
379 ([(shift down)] . [(meta n)])
380 ([(shift left)] . [(meta -)])
381 ([(shift right)] . [(meta +)])
382 ([(control shift right)] . [(meta shift +)])
383 ([(control shift left)] . [(meta shift -)]))
384 "Keys for which Org-mode and other modes compete.
385 This is an alist, cars are the default keys, second element specifies
386 the alternative to use when `org-replace-disputed-keys' is t.
388 Keys can be specified in any syntax supported by `define-key'.
389 The value of this option takes effect only at Org-mode's startup,
390 therefore you'll have to restart Emacs to apply it after changing."
391 :group 'org-startup
392 :type 'alist)
394 (defun org-key (key)
395 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
396 Or return the original if not disputed."
397 (if org-replace-disputed-keys
398 (let* ((nkey (key-description key))
399 (x (org-find-if (lambda (x)
400 (equal (key-description (car x)) nkey))
401 org-disputed-keys)))
402 (if x (cdr x) key))
403 key))
405 (defun org-find-if (predicate seq)
406 (catch 'exit
407 (while seq
408 (if (funcall predicate (car seq))
409 (throw 'exit (car seq))
410 (pop seq)))))
412 (defun org-defkey (keymap key def)
413 "Define a key, possibly translated, as returned by `org-key'."
414 (define-key keymap (org-key key) def))
416 (defcustom org-ellipsis nil
417 "The ellipsis to use in the Org-mode outline.
418 When nil, just use the standard three dots. When a string, use that instead,
419 When a face, use the standard 3 dots, but with the specified face.
420 The change affects only Org-mode (which will then use its own display table).
421 Changing this requires executing `M-x org-mode' in a buffer to become
422 effective."
423 :group 'org-startup
424 :type '(choice (const :tag "Default" nil)
425 (face :tag "Face" :value org-warning)
426 (string :tag "String" :value "...#")))
428 (defvar org-display-table nil
429 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
431 (defgroup org-keywords nil
432 "Keywords in Org-mode."
433 :tag "Org Keywords"
434 :group 'org)
436 (defcustom org-deadline-string "DEADLINE:"
437 "String to mark deadline entries.
438 A deadline is this string, followed by a time stamp. Should be a word,
439 terminated by a colon. You can insert a schedule keyword and
440 a timestamp with \\[org-deadline].
441 Changes become only effective after restarting Emacs."
442 :group 'org-keywords
443 :type 'string)
445 (defcustom org-scheduled-string "SCHEDULED:"
446 "String to mark scheduled TODO entries.
447 A schedule is this string, followed by a time stamp. Should be a word,
448 terminated by a colon. You can insert a schedule keyword and
449 a timestamp with \\[org-schedule].
450 Changes become only effective after restarting Emacs."
451 :group 'org-keywords
452 :type 'string)
454 (defcustom org-closed-string "CLOSED:"
455 "String used as the prefix for timestamps logging closing a TODO entry."
456 :group 'org-keywords
457 :type 'string)
459 (defcustom org-clock-string "CLOCK:"
460 "String used as prefix for timestamps clocking work hours on an item."
461 :group 'org-keywords
462 :type 'string)
464 (defcustom org-comment-string "COMMENT"
465 "Entries starting with this keyword will never be exported.
466 An entry can be toggled between COMMENT and normal with
467 \\[org-toggle-comment].
468 Changes become only effective after restarting Emacs."
469 :group 'org-keywords
470 :type 'string)
472 (defcustom org-quote-string "QUOTE"
473 "Entries starting with this keyword will be exported in fixed-width font.
474 Quoting applies only to the text in the entry following the headline, and does
475 not extend beyond the next headline, even if that is lower level.
476 An entry can be toggled between QUOTE and normal with
477 \\[org-toggle-fixed-width-section]."
478 :group 'org-keywords
479 :type 'string)
481 (defconst org-repeat-re
482 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
483 "Regular expression for specifying repeated events.
484 After a match, group 1 contains the repeat expression.")
486 (defgroup org-structure nil
487 "Options concerning the general structure of Org-mode files."
488 :tag "Org Structure"
489 :group 'org)
491 (defgroup org-reveal-location nil
492 "Options about how to make context of a location visible."
493 :tag "Org Reveal Location"
494 :group 'org-structure)
496 (defconst org-context-choice
497 '(choice
498 (const :tag "Always" t)
499 (const :tag "Never" nil)
500 (repeat :greedy t :tag "Individual contexts"
501 (cons
502 (choice :tag "Context"
503 (const agenda)
504 (const org-goto)
505 (const occur-tree)
506 (const tags-tree)
507 (const link-search)
508 (const mark-goto)
509 (const bookmark-jump)
510 (const isearch)
511 (const default))
512 (boolean))))
513 "Contexts for the reveal options.")
515 (defcustom org-show-hierarchy-above '((default . t))
516 "Non-nil means, show full hierarchy when revealing a location.
517 Org-mode often shows locations in an org-mode file which might have
518 been invisible before. When this is set, the hierarchy of headings
519 above the exposed location is shown.
520 Turning this off for example for sparse trees makes them very compact.
521 Instead of t, this can also be an alist specifying this option for different
522 contexts. Valid contexts are
523 agenda when exposing an entry from the agenda
524 org-goto when using the command `org-goto' on key C-c C-j
525 occur-tree when using the command `org-occur' on key C-c /
526 tags-tree when constructing a sparse tree based on tags matches
527 link-search when exposing search matches associated with a link
528 mark-goto when exposing the jump goal of a mark
529 bookmark-jump when exposing a bookmark location
530 isearch when exiting from an incremental search
531 default default for all contexts not set explicitly"
532 :group 'org-reveal-location
533 :type org-context-choice)
535 (defcustom org-show-following-heading '((default . nil))
536 "Non-nil means, show following heading when revealing a location.
537 Org-mode often shows locations in an org-mode file which might have
538 been invisible before. When this is set, the heading following the
539 match is shown.
540 Turning this off for example for sparse trees makes them very compact,
541 but makes it harder to edit the location of the match. In such a case,
542 use the command \\[org-reveal] to show more context.
543 Instead of t, this can also be an alist specifying this option for different
544 contexts. See `org-show-hierarchy-above' for valid contexts."
545 :group 'org-reveal-location
546 :type org-context-choice)
548 (defcustom org-show-siblings '((default . nil) (isearch t))
549 "Non-nil means, show all sibling heading when revealing a location.
550 Org-mode often shows locations in an org-mode file which might have
551 been invisible before. When this is set, the sibling of the current entry
552 heading are all made visible. If `org-show-hierarchy-above' is t,
553 the same happens on each level of the hierarchy above the current entry.
555 By default this is on for the isearch context, off for all other contexts.
556 Turning this off for example for sparse trees makes them very compact,
557 but makes it harder to edit the location of the match. In such a case,
558 use the command \\[org-reveal] to show more context.
559 Instead of t, this can also be an alist specifying this option for different
560 contexts. See `org-show-hierarchy-above' for valid contexts."
561 :group 'org-reveal-location
562 :type org-context-choice)
564 (defcustom org-show-entry-below '((default . nil))
565 "Non-nil means, show the entry below a headline when revealing a location.
566 Org-mode often shows locations in an org-mode file which might have
567 been invisible before. When this is set, the text below the headline that is
568 exposed is also shown.
570 By default this is off for all contexts.
571 Instead of t, this can also be an alist specifying this option for different
572 contexts. See `org-show-hierarchy-above' for valid contexts."
573 :group 'org-reveal-location
574 :type org-context-choice)
576 (defcustom org-indirect-buffer-display 'other-window
577 "How should indirect tree buffers be displayed?
578 This applies to indirect buffers created with the commands
579 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
580 Valid values are:
581 current-window Display in the current window
582 other-window Just display in another window.
583 dedicated-frame Create one new frame, and re-use it each time.
584 new-frame Make a new frame each time. Note that in this case
585 previously-made indirect buffers are kept, and you need to
586 kill these buffers yourself."
587 :group 'org-structure
588 :group 'org-agenda-windows
589 :type '(choice
590 (const :tag "In current window" current-window)
591 (const :tag "In current frame, other window" other-window)
592 (const :tag "Each time a new frame" new-frame)
593 (const :tag "One dedicated frame" dedicated-frame)))
595 (defcustom org-use-speed-commands nil
596 "Non-nil means, activate single letter commands at beginning of a headline.
597 This may also be a function to test for appropriate locations where speed
598 commands should be active."
599 :group 'org-structure
600 :type '(choice
601 (const :tag "Never" nil)
602 (const :tag "At beginning of headline stars" t)
603 (function)))
605 (defcustom org-speed-commands-user nil
606 "Alist of additional speed commands.
607 This list will be checked before `org-speed-commands-default'
608 when the variable `org-use-speed-commands' is non-nil
609 and when the cursor is at the beginning of a headline.
610 The car if each entry is a string with a single letter, which must
611 be assigned to `self-insert-command' in the global map.
612 The cdr is either a command to be called interactively, a function
613 to be called, or a form to be evaluated.
614 An entry that is just a list with a single string will be interpreted
615 as a descriptive headline that will be added when listing the speed
616 copmmands in the Help buffer using the `?' speed command."
617 :group 'org-structure
618 :type '(repeat :value ("k" . ignore)
619 (choice :value ("k" . ignore)
620 (list :tag "Descriptive Headline" (string :tag "Headline"))
621 (cons :tag "Letter and Command"
622 (string :tag "Command letter")
623 (choice
624 (function)
625 (sexp))))))
627 (defgroup org-cycle nil
628 "Options concerning visibility cycling in Org-mode."
629 :tag "Org Cycle"
630 :group 'org-structure)
632 (defcustom org-cycle-skip-children-state-if-no-children t
633 "Non-nil means, skip CHILDREN state in entries that don't have any."
634 :group 'org-cycle
635 :type 'boolean)
637 (defcustom org-cycle-max-level nil
638 "Maximum level which should still be subject to visibility cycling.
639 Levels higher than this will, for cycling, be treated as text, not a headline.
640 When `org-odd-levels-only' is set, a value of N in this variable actually
641 means 2N-1 stars as the limiting headline.
642 When nil, cycle all levels.
643 Note that the limiting level of cycling is also influenced by
644 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
645 `org-inlinetask-min-level' is, cycling will be limited to levels one less
646 than its value."
647 :group 'org-cycle
648 :type '(choice
649 (const :tag "No limit" nil)
650 (integer :tag "Maximum level")))
652 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
653 "Names of drawers. Drawers are not opened by cycling on the headline above.
654 Drawers only open with a TAB on the drawer line itself. A drawer looks like
655 this:
656 :DRAWERNAME:
657 .....
658 :END:
659 The drawer \"PROPERTIES\" is special for capturing properties through
660 the property API.
662 Drawers can be defined on the per-file basis with a line like:
664 #+DRAWERS: HIDDEN STATE PROPERTIES"
665 :group 'org-structure
666 :group 'org-cycle
667 :type '(repeat (string :tag "Drawer Name")))
669 (defcustom org-hide-block-startup nil
670 "Non-nil means, , entering Org-mode will fold all blocks.
671 This can also be set in on a per-file basis with
673 #+STARTUP: hideblocks
674 #+STARTUP: showblocks"
675 :group 'org-startup
676 :group 'org-cycle
677 :type 'boolean)
679 (defcustom org-cycle-global-at-bob nil
680 "Cycle globally if cursor is at beginning of buffer and not at a headline.
681 This makes it possible to do global cycling without having to use S-TAB or
682 C-u TAB. For this special case to work, the first line of the buffer
683 must not be a headline - it may be empty or some other text. When used in
684 this way, `org-cycle-hook' is disables temporarily, to make sure the
685 cursor stays at the beginning of the buffer.
686 When this option is nil, don't do anything special at the beginning
687 of the buffer."
688 :group 'org-cycle
689 :type 'boolean)
691 (defcustom org-cycle-level-after-item/entry-creation t
692 "Non-nil means, cycle entry level or item indentation in new empty entries.
694 When the cursor is at the end of an empty headline, i.e with only stars
695 and maybe a TODO keyword, TAB will then switch the entry to become a child,
696 and then all possible anchestor states, before returning to the original state.
697 This makes data entry extremely fast: M-RET to create a new headline,
698 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
700 When the cursor is at the end of an empty plain list item, one TAB will
701 make it a subitem, two or more tabs will back up to make this an item
702 higher up in the item hierarchy."
703 :group 'org-cycle
704 :type 'boolean)
706 (defcustom org-cycle-emulate-tab t
707 "Where should `org-cycle' emulate TAB.
708 nil Never
709 white Only in completely white lines
710 whitestart Only at the beginning of lines, before the first non-white char
711 t Everywhere except in headlines
712 exc-hl-bol Everywhere except at the start of a headline
713 If TAB is used in a place where it does not emulate TAB, the current subtree
714 visibility is cycled."
715 :group 'org-cycle
716 :type '(choice (const :tag "Never" nil)
717 (const :tag "Only in completely white lines" white)
718 (const :tag "Before first char in a line" whitestart)
719 (const :tag "Everywhere except in headlines" t)
720 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
723 (defcustom org-cycle-separator-lines 2
724 "Number of empty lines needed to keep an empty line between collapsed trees.
725 If you leave an empty line between the end of a subtree and the following
726 headline, this empty line is hidden when the subtree is folded.
727 Org-mode will leave (exactly) one empty line visible if the number of
728 empty lines is equal or larger to the number given in this variable.
729 So the default 2 means, at least 2 empty lines after the end of a subtree
730 are needed to produce free space between a collapsed subtree and the
731 following headline.
733 If the number is negative, and the number of empty lines is at least -N,
734 all empty lines are shown.
736 Special case: when 0, never leave empty lines in collapsed view."
737 :group 'org-cycle
738 :type 'integer)
739 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
741 (defcustom org-pre-cycle-hook nil
742 "Hook that is run before visibility cycling is happening.
743 The function(s) in this hook must accept a single argument which indicates
744 the new state that will be set right after running this hook. The
745 argument is a symbol. Before a global state change, it can have the values
746 `overview', `content', or `all'. Before a local state change, it can have
747 the values `folded', `children', or `subtree'."
748 :group 'org-cycle
749 :type 'hook)
751 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
752 org-cycle-hide-drawers
753 org-cycle-show-empty-lines
754 org-optimize-window-after-visibility-change)
755 "Hook that is run after `org-cycle' has changed the buffer visibility.
756 The function(s) in this hook must accept a single argument which indicates
757 the new state that was set by the most recent `org-cycle' command. The
758 argument is a symbol. After a global state change, it can have the values
759 `overview', `content', or `all'. After a local state change, it can have
760 the values `folded', `children', or `subtree'."
761 :group 'org-cycle
762 :type 'hook)
764 (defgroup org-edit-structure nil
765 "Options concerning structure editing in Org-mode."
766 :tag "Org Edit Structure"
767 :group 'org-structure)
769 (defcustom org-odd-levels-only nil
770 "Non-nil means, skip even levels and only use odd levels for the outline.
771 This has the effect that two stars are being added/taken away in
772 promotion/demotion commands. It also influences how levels are
773 handled by the exporters.
774 Changing it requires restart of `font-lock-mode' to become effective
775 for fontification also in regions already fontified.
776 You may also set this on a per-file basis by adding one of the following
777 lines to the buffer:
779 #+STARTUP: odd
780 #+STARTUP: oddeven"
781 :group 'org-edit-structure
782 :group 'org-font-lock
783 :type 'boolean)
785 (defcustom org-adapt-indentation t
786 "Non-nil means, adapt indentation to outline node level.
788 When this variable is set, Org assumes that you write outlines by
789 indenting text in each node to align with the headline (after the stars).
790 The following issues are influenced by this variable:
792 - When this is set and the *entire* text in an entry is indented, the
793 indentation is increased by one space in a demotion command, and
794 decreased by one in a promotion command. If any line in the entry
795 body starts with text at column 0, indentation is not changed at all.
797 - Property drawers and planning information is inserted indented when
798 this variable s set. When nil, they will not be indented.
800 - TAB indents a line relative to context. The lines below a headline
801 will be indented when this variable is set.
803 Note that this is all about true indentation, by adding and removing
804 space characters. See also `org-indent.el' which does level-dependent
805 indentation in a virtual way, i.e. at display time in Emacs."
806 :group 'org-edit-structure
807 :type 'boolean)
809 (defcustom org-special-ctrl-a/e nil
810 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
812 When t, `C-a' will bring back the cursor to the beginning of the
813 headline text, i.e. after the stars and after a possible TODO keyword.
814 In an item, this will be the position after the bullet.
815 When the cursor is already at that position, another `C-a' will bring
816 it to the beginning of the line.
818 `C-e' will jump to the end of the headline, ignoring the presence of tags
819 in the headline. A second `C-e' will then jump to the true end of the
820 line, after any tags. This also means that, when this variable is
821 non-nil, `C-e' also will never jump beyond the end of the heading of a
822 folded section, i.e. not after the ellipses.
824 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
825 going to the true line boundary first. Only a directly following, identical
826 keypress will bring the cursor to the special positions.
828 This may also be a cons cell where the behavior for `C-a' and `C-e' is
829 set separately."
830 :group 'org-edit-structure
831 :type '(choice
832 (const :tag "off" nil)
833 (const :tag "on: after stars/bullet and before tags first" t)
834 (const :tag "reversed: true line boundary first" reversed)
835 (cons :tag "Set C-a and C-e separately"
836 (choice :tag "Special C-a"
837 (const :tag "off" nil)
838 (const :tag "on: after stars/bullet first" t)
839 (const :tag "reversed: before stars/bullet first" reversed))
840 (choice :tag "Special C-e"
841 (const :tag "off" nil)
842 (const :tag "on: before tags first" t)
843 (const :tag "reversed: after tags first" reversed)))))
844 (if (fboundp 'defvaralias)
845 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
847 (defcustom org-special-ctrl-k nil
848 "Non-nil means `C-k' will behave specially in headlines.
849 When nil, `C-k' will call the default `kill-line' command.
850 When t, the following will happen while the cursor is in the headline:
852 - When the cursor is at the beginning of a headline, kill the entire
853 line and possible the folded subtree below the line.
854 - When in the middle of the headline text, kill the headline up to the tags.
855 - When after the headline text, kill the tags."
856 :group 'org-edit-structure
857 :type 'boolean)
859 (defcustom org-yank-folded-subtrees t
860 "Non-nil means, when yanking subtrees, fold them.
861 If the kill is a single subtree, or a sequence of subtrees, i.e. if
862 it starts with a heading and all other headings in it are either children
863 or siblings, then fold all the subtrees. However, do this only if no
864 text after the yank would be swallowed into a folded tree by this action."
865 :group 'org-edit-structure
866 :type 'boolean)
868 (defcustom org-yank-adjusted-subtrees nil
869 "Non-nil means, when yanking subtrees, adjust the level.
870 With this setting, `org-paste-subtree' is used to insert the subtree, see
871 this function for details."
872 :group 'org-edit-structure
873 :type 'boolean)
875 (defcustom org-M-RET-may-split-line '((default . t))
876 "Non-nil means, M-RET will split the line at the cursor position.
877 When nil, it will go to the end of the line before making a
878 new line.
879 You may also set this option in a different way for different
880 contexts. Valid contexts are:
882 headline when creating a new headline
883 item when creating a new item
884 table in a table field
885 default the value to be used for all contexts not explicitly
886 customized"
887 :group 'org-structure
888 :group 'org-table
889 :type '(choice
890 (const :tag "Always" t)
891 (const :tag "Never" nil)
892 (repeat :greedy t :tag "Individual contexts"
893 (cons
894 (choice :tag "Context"
895 (const headline)
896 (const item)
897 (const table)
898 (const default))
899 (boolean)))))
902 (defcustom org-insert-heading-respect-content nil
903 "Non-nil means, insert new headings after the current subtree.
904 When nil, the new heading is created directly after the current line.
905 The commands \\[org-insert-heading-respect-content] and
906 \\[org-insert-todo-heading-respect-content] turn this variable on
907 for the duration of the command."
908 :group 'org-structure
909 :type 'boolean)
911 (defcustom org-blank-before-new-entry '((heading . auto)
912 (plain-list-item . auto))
913 "Should `org-insert-heading' leave a blank line before new heading/item?
914 The value is an alist, with `heading' and `plain-list-item' as car,
915 and a boolean flag as cdr. For plain lists, if the variable
916 `org-empty-line-terminates-plain-lists' is set, the setting here
917 is ignored and no empty line is inserted, to keep the list in tact."
918 :group 'org-edit-structure
919 :type '(list
920 (cons (const heading)
921 (choice (const :tag "Never" nil)
922 (const :tag "Always" t)
923 (const :tag "Auto" auto)))
924 (cons (const plain-list-item)
925 (choice (const :tag "Never" nil)
926 (const :tag "Always" t)
927 (const :tag "Auto" auto)))))
929 (defcustom org-insert-heading-hook nil
930 "Hook being run after inserting a new heading."
931 :group 'org-edit-structure
932 :type 'hook)
934 (defcustom org-enable-fixed-width-editor t
935 "Non-nil means, lines starting with \":\" are treated as fixed-width.
936 This currently only means, they are never auto-wrapped.
937 When nil, such lines will be treated like ordinary lines.
938 See also the QUOTE keyword."
939 :group 'org-edit-structure
940 :type 'boolean)
943 (defcustom org-goto-auto-isearch t
944 "Non-nil means, typing characters in org-goto starts incremental search."
945 :group 'org-edit-structure
946 :type 'boolean)
948 (defgroup org-sparse-trees nil
949 "Options concerning sparse trees in Org-mode."
950 :tag "Org Sparse Trees"
951 :group 'org-structure)
953 (defcustom org-highlight-sparse-tree-matches t
954 "Non-nil means, highlight all matches that define a sparse tree.
955 The highlights will automatically disappear the next time the buffer is
956 changed by an edit command."
957 :group 'org-sparse-trees
958 :type 'boolean)
960 (defcustom org-remove-highlights-with-change t
961 "Non-nil means, any change to the buffer will remove temporary highlights.
962 Such highlights are created by `org-occur' and `org-clock-display'.
963 When nil, `C-c C-c needs to be used to get rid of the highlights.
964 The highlights created by `org-preview-latex-fragment' always need
965 `C-c C-c' to be removed."
966 :group 'org-sparse-trees
967 :group 'org-time
968 :type 'boolean)
971 (defcustom org-occur-hook '(org-first-headline-recenter)
972 "Hook that is run after `org-occur' has constructed a sparse tree.
973 This can be used to recenter the window to show as much of the structure
974 as possible."
975 :group 'org-sparse-trees
976 :type 'hook)
978 (defgroup org-imenu-and-speedbar nil
979 "Options concerning imenu and speedbar in Org-mode."
980 :tag "Org Imenu and Speedbar"
981 :group 'org-structure)
983 (defcustom org-imenu-depth 2
984 "The maximum level for Imenu access to Org-mode headlines.
985 This also applied for speedbar access."
986 :group 'org-imenu-and-speedbar
987 :type 'integer)
989 (defgroup org-table nil
990 "Options concerning tables in Org-mode."
991 :tag "Org Table"
992 :group 'org)
994 (defcustom org-enable-table-editor 'optimized
995 "Non-nil means, lines starting with \"|\" are handled by the table editor.
996 When nil, such lines will be treated like ordinary lines.
998 When equal to the symbol `optimized', the table editor will be optimized to
999 do the following:
1000 - Automatic overwrite mode in front of whitespace in table fields.
1001 This makes the structure of the table stay in tact as long as the edited
1002 field does not exceed the column width.
1003 - Minimize the number of realigns. Normally, the table is aligned each time
1004 TAB or RET are pressed to move to another field. With optimization this
1005 happens only if changes to a field might have changed the column width.
1006 Optimization requires replacing the functions `self-insert-command',
1007 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1008 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1009 very good at guessing when a re-align will be necessary, but you can always
1010 force one with \\[org-ctrl-c-ctrl-c].
1012 If you would like to use the optimized version in Org-mode, but the
1013 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1015 This variable can be used to turn on and off the table editor during a session,
1016 but in order to toggle optimization, a restart is required.
1018 See also the variable `org-table-auto-blank-field'."
1019 :group 'org-table
1020 :type '(choice
1021 (const :tag "off" nil)
1022 (const :tag "on" t)
1023 (const :tag "on, optimized" optimized)))
1025 (defcustom org-self-insert-cluster-for-undo t
1026 "Non-nil means cluster self-insert commands for undo when possible.
1027 If this is set, then, like in the Emacs command loop, 20 consecutive
1028 characters will be undone together.
1029 This is configurable, because there is some impact on typing performance."
1030 :group 'org-table
1031 :type 'boolean)
1033 (defcustom org-table-tab-recognizes-table.el t
1034 "Non-nil means, TAB will automatically notice a table.el table.
1035 When it sees such a table, it moves point into it and - if necessary -
1036 calls `table-recognize-table'."
1037 :group 'org-table-editing
1038 :type 'boolean)
1040 (defgroup org-link nil
1041 "Options concerning links in Org-mode."
1042 :tag "Org Link"
1043 :group 'org)
1045 (defvar org-link-abbrev-alist-local nil
1046 "Buffer-local version of `org-link-abbrev-alist', which see.
1047 The value of this is taken from the #+LINK lines.")
1048 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1050 (defcustom org-link-abbrev-alist nil
1051 "Alist of link abbreviations.
1052 The car of each element is a string, to be replaced at the start of a link.
1053 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1054 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1056 [[linkkey:tag][description]]
1058 The 'linkkey' must be a word word, starting with a letter, followed
1059 by letters, numbers, '-' or '_'.
1061 If REPLACE is a string, the tag will simply be appended to create the link.
1062 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1063 the placeholder \"%h\" will cause a url-encoded version of the tag to
1064 be inserted at that point (see the function `url-hexify-string').
1066 REPLACE may also be a function that will be called with the tag as the
1067 only argument to create the link, which should be returned as a string.
1069 See the manual for examples."
1070 :group 'org-link
1071 :type '(repeat
1072 (cons
1073 (string :tag "Protocol")
1074 (choice
1075 (string :tag "Format")
1076 (function)))))
1078 (defcustom org-descriptive-links t
1079 "Non-nil means, hide link part and only show description of bracket links.
1080 Bracket links are like [[link][description]]. This variable sets the initial
1081 state in new org-mode buffers. The setting can then be toggled on a
1082 per-buffer basis from the Org->Hyperlinks menu."
1083 :group 'org-link
1084 :type 'boolean)
1086 (defcustom org-link-file-path-type 'adaptive
1087 "How the path name in file links should be stored.
1088 Valid values are:
1090 relative Relative to the current directory, i.e. the directory of the file
1091 into which the link is being inserted.
1092 absolute Absolute path, if possible with ~ for home directory.
1093 noabbrev Absolute path, no abbreviation of home directory.
1094 adaptive Use relative path for files in the current directory and sub-
1095 directories of it. For other files, use an absolute path."
1096 :group 'org-link
1097 :type '(choice
1098 (const relative)
1099 (const absolute)
1100 (const noabbrev)
1101 (const adaptive)))
1103 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1104 "Types of links that should be activated in Org-mode files.
1105 This is a list of symbols, each leading to the activation of a certain link
1106 type. In principle, it does not hurt to turn on most link types - there may
1107 be a small gain when turning off unused link types. The types are:
1109 bracket The recommended [[link][description]] or [[link]] links with hiding.
1110 angular Links in angular brackets that may contain whitespace like
1111 <bbdb:Carsten Dominik>.
1112 plain Plain links in normal text, no whitespace, like http://google.com.
1113 radio Text that is matched by a radio target, see manual for details.
1114 tag Tag settings in a headline (link to tag search).
1115 date Time stamps (link to calendar).
1116 footnote Footnote labels.
1118 Changing this variable requires a restart of Emacs to become effective."
1119 :group 'org-link
1120 :type '(set :greedy t
1121 (const :tag "Double bracket links (new style)" bracket)
1122 (const :tag "Angular bracket links (old style)" angular)
1123 (const :tag "Plain text links" plain)
1124 (const :tag "Radio target matches" radio)
1125 (const :tag "Tags" tag)
1126 (const :tag "Timestamps" date)
1127 (const :tag "Footnotes" footnote)))
1129 (defcustom org-make-link-description-function nil
1130 "Function to use to generate link descriptions from links. If
1131 nil the link location will be used. This function must take two
1132 parameters; the first is the link and the second the description
1133 org-insert-link has generated, and should return the description
1134 to use."
1135 :group 'org-link
1136 :type 'function)
1138 (defgroup org-link-store nil
1139 "Options concerning storing links in Org-mode."
1140 :tag "Org Store Link"
1141 :group 'org-link)
1143 (defcustom org-email-link-description-format "Email %c: %.30s"
1144 "Format of the description part of a link to an email or usenet message.
1145 The following %-escapes will be replaced by corresponding information:
1147 %F full \"From\" field
1148 %f name, taken from \"From\" field, address if no name
1149 %T full \"To\" field
1150 %t first name in \"To\" field, address if no name
1151 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1152 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1153 %s subject
1154 %m message-id.
1156 You may use normal field width specification between the % and the letter.
1157 This is for example useful to limit the length of the subject.
1159 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1160 :group 'org-link-store
1161 :type 'string)
1163 (defcustom org-from-is-user-regexp
1164 (let (r1 r2)
1165 (when (and user-mail-address (not (string= user-mail-address "")))
1166 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1167 (when (and user-full-name (not (string= user-full-name "")))
1168 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1169 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1170 "Regexp matched against the \"From:\" header of an email or usenet message.
1171 It should match if the message is from the user him/herself."
1172 :group 'org-link-store
1173 :type 'regexp)
1175 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1176 "Non-nil means, storing a link to an Org file will use entry IDs.
1178 Note that before this variable is even considered, org-id must be loaded,
1179 so please customize `org-modules' and turn it on.
1181 The variable can have the following values:
1183 t Create an ID if needed to make a link to the current entry.
1185 create-if-interactive
1186 If `org-store-link' is called directly (interactively, as a user
1187 command), do create an ID to support the link. But when doing the
1188 job for remember, only use the ID if it already exists. The
1189 purpose of this setting is to avoid proliferation of unwanted
1190 IDs, just because you happen to be in an Org file when you
1191 call `org-remember' that automatically and preemptively
1192 creates a link. If you do want to get an ID link in a remember
1193 template to an entry not having an ID, create it first by
1194 explicitly creating a link to it, using `C-c C-l' first.
1196 create-if-interactive-and-no-custom-id
1197 Like create-if-interactive, but do not create an ID if there is
1198 a CUSTOM_ID property defined in the entry. This is the default.
1200 use-existing
1201 Use existing ID, do not create one.
1203 nil Never use an ID to make a link, instead link using a text search for
1204 the headline text."
1205 :group 'org-link-store
1206 :type '(choice
1207 (const :tag "Create ID to make link" t)
1208 (const :tag "Create if storing link interactively"
1209 create-if-interactive)
1210 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1211 create-if-interactive-and-no-custom-id)
1212 (const :tag "Only use existing" use-existing)
1213 (const :tag "Do not use ID to create link" nil)))
1215 (defcustom org-context-in-file-links t
1216 "Non-nil means, file links from `org-store-link' contain context.
1217 A search string will be added to the file name with :: as separator and
1218 used to find the context when the link is activated by the command
1219 `org-open-at-point'.
1220 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1221 negates this setting for the duration of the command."
1222 :group 'org-link-store
1223 :type 'boolean)
1225 (defcustom org-keep-stored-link-after-insertion nil
1226 "Non-nil means, keep link in list for entire session.
1228 The command `org-store-link' adds a link pointing to the current
1229 location to an internal list. These links accumulate during a session.
1230 The command `org-insert-link' can be used to insert links into any
1231 Org-mode file (offering completion for all stored links). When this
1232 option is nil, every link which has been inserted once using \\[org-insert-link]
1233 will be removed from the list, to make completing the unused links
1234 more efficient."
1235 :group 'org-link-store
1236 :type 'boolean)
1238 (defgroup org-link-follow nil
1239 "Options concerning following links in Org-mode."
1240 :tag "Org Follow Link"
1241 :group 'org-link)
1243 (defcustom org-link-translation-function nil
1244 "Function to translate links with different syntax to Org syntax.
1245 This can be used to translate links created for example by the Planner
1246 or emacs-wiki packages to Org syntax.
1247 The function must accept two parameters, a TYPE containing the link
1248 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1249 which is everything after the link protocol. It should return a cons
1250 with possibly modified values of type and path.
1251 Org contains a function for this, so if you set this variable to
1252 `org-translate-link-from-planner', you should be able follow many
1253 links created by planner."
1254 :group 'org-link-follow
1255 :type 'function)
1257 (defcustom org-follow-link-hook nil
1258 "Hook that is run after a link has been followed."
1259 :group 'org-link-follow
1260 :type 'hook)
1262 (defcustom org-tab-follows-link nil
1263 "Non-nil means, on links TAB will follow the link.
1264 Needs to be set before org.el is loaded.
1265 This really should not be used, it does not make sense, and the
1266 implementation is bad."
1267 :group 'org-link-follow
1268 :type 'boolean)
1270 (defcustom org-return-follows-link nil
1271 "Non-nil means, on links RET will follow the link.
1272 Needs to be set before org.el is loaded."
1273 :group 'org-link-follow
1274 :type 'boolean)
1276 (defcustom org-mouse-1-follows-link
1277 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1278 "Non-nil means, mouse-1 on a link will follow the link.
1279 A longer mouse click will still set point. Does not work on XEmacs.
1280 Needs to be set before org.el is loaded."
1281 :group 'org-link-follow
1282 :type 'boolean)
1284 (defcustom org-mark-ring-length 4
1285 "Number of different positions to be recorded in the ring
1286 Changing this requires a restart of Emacs to work correctly."
1287 :group 'org-link-follow
1288 :type 'integer)
1290 (defcustom org-link-frame-setup
1291 '((vm . vm-visit-folder-other-frame)
1292 (gnus . gnus-other-frame)
1293 (file . find-file-other-window))
1294 "Setup the frame configuration for following links.
1295 When following a link with Emacs, it may often be useful to display
1296 this link in another window or frame. This variable can be used to
1297 set this up for the different types of links.
1298 For VM, use any of
1299 `vm-visit-folder'
1300 `vm-visit-folder-other-frame'
1301 For Gnus, use any of
1302 `gnus'
1303 `gnus-other-frame'
1304 `org-gnus-no-new-news'
1305 For FILE, use any of
1306 `find-file'
1307 `find-file-other-window'
1308 `find-file-other-frame'
1309 For the calendar, use the variable `calendar-setup'.
1310 For BBDB, it is currently only possible to display the matches in
1311 another window."
1312 :group 'org-link-follow
1313 :type '(list
1314 (cons (const vm)
1315 (choice
1316 (const vm-visit-folder)
1317 (const vm-visit-folder-other-window)
1318 (const vm-visit-folder-other-frame)))
1319 (cons (const gnus)
1320 (choice
1321 (const gnus)
1322 (const gnus-other-frame)
1323 (const org-gnus-no-new-news)))
1324 (cons (const file)
1325 (choice
1326 (const find-file)
1327 (const find-file-other-window)
1328 (const find-file-other-frame)))))
1330 (defcustom org-display-internal-link-with-indirect-buffer nil
1331 "Non-nil means, use indirect buffer to display infile links.
1332 Activating internal links (from one location in a file to another location
1333 in the same file) normally just jumps to the location. When the link is
1334 activated with a C-u prefix (or with mouse-3), the link is displayed in
1335 another window. When this option is set, the other window actually displays
1336 an indirect buffer clone of the current buffer, to avoid any visibility
1337 changes to the current buffer."
1338 :group 'org-link-follow
1339 :type 'boolean)
1341 (defcustom org-open-non-existing-files nil
1342 "Non-nil means, `org-open-file' will open non-existing files.
1343 When nil, an error will be generated.
1344 This variable applies only to external applications because they
1345 might choke on non-existing files. If the link is to a file that
1346 will be opened in Emacs, the variable is ignored."
1347 :group 'org-link-follow
1348 :type 'boolean)
1350 (defcustom org-open-directory-means-index-dot-org nil
1351 "Non-nil means, a link to a directory really means to index.org.
1352 When nil, following a directory link will run dired or open a finder/explorer
1353 window on that directory."
1354 :group 'org-link-follow
1355 :type 'boolean)
1357 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1358 "Function and arguments to call for following mailto links.
1359 This is a list with the first element being a lisp function, and the
1360 remaining elements being arguments to the function. In string arguments,
1361 %a will be replaced by the address, and %s will be replaced by the subject
1362 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1363 :group 'org-link-follow
1364 :type '(choice
1365 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1366 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1367 (const :tag "message-mail" (message-mail "%a" "%s"))
1368 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1370 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1371 "Non-nil means, ask for confirmation before executing shell links.
1372 Shell links can be dangerous: just think about a link
1374 [[shell:rm -rf ~/*][Google Search]]
1376 This link would show up in your Org-mode document as \"Google Search\",
1377 but really it would remove your entire home directory.
1378 Therefore we advise against setting this variable to nil.
1379 Just change it to `y-or-n-p' if you want to confirm with a
1380 single keystroke rather than having to type \"yes\"."
1381 :group 'org-link-follow
1382 :type '(choice
1383 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1384 (const :tag "with y-or-n (faster)" y-or-n-p)
1385 (const :tag "no confirmation (dangerous)" nil)))
1387 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1388 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1389 Elisp links can be dangerous: just think about a link
1391 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1393 This link would show up in your Org-mode document as \"Google Search\",
1394 but really it would remove your entire home directory.
1395 Therefore we advise against setting this variable to nil.
1396 Just change it to `y-or-n-p' if you want to confirm with a
1397 single keystroke rather than having to type \"yes\"."
1398 :group 'org-link-follow
1399 :type '(choice
1400 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1401 (const :tag "with y-or-n (faster)" y-or-n-p)
1402 (const :tag "no confirmation (dangerous)" nil)))
1404 (defconst org-file-apps-defaults-gnu
1405 '((remote . emacs)
1406 (system . mailcap)
1407 (t . mailcap))
1408 "Default file applications on a UNIX or GNU/Linux system.
1409 See `org-file-apps'.")
1411 (defconst org-file-apps-defaults-macosx
1412 '((remote . emacs)
1413 (t . "open %s")
1414 (system . "open %s")
1415 ("ps.gz" . "gv %s")
1416 ("eps.gz" . "gv %s")
1417 ("dvi" . "xdvi %s")
1418 ("fig" . "xfig %s"))
1419 "Default file applications on a MacOS X system.
1420 The system \"open\" is known as a default, but we use X11 applications
1421 for some files for which the OS does not have a good default.
1422 See `org-file-apps'.")
1424 (defconst org-file-apps-defaults-windowsnt
1425 (list
1426 '(remote . emacs)
1427 (cons t
1428 (list (if (featurep 'xemacs)
1429 'mswindows-shell-execute
1430 'w32-shell-execute)
1431 "open" 'file))
1432 (cons 'system
1433 (list (if (featurep 'xemacs)
1434 'mswindows-shell-execute
1435 'w32-shell-execute)
1436 "open" 'file)))
1437 "Default file applications on a Windows NT system.
1438 The system \"open\" is used for most files.
1439 See `org-file-apps'.")
1441 (defcustom org-file-apps
1443 (auto-mode . emacs)
1444 ("\\.mm\\'" . default)
1445 ("\\.x?html?\\'" . default)
1446 ("\\.pdf\\'" . default)
1448 "External applications for opening `file:path' items in a document.
1449 Org-mode uses system defaults for different file types, but
1450 you can use this variable to set the application for a given file
1451 extension. The entries in this list are cons cells where the car identifies
1452 files and the cdr the corresponding command. Possible values for the
1453 file identifier are
1454 \"regex\" Regular expression matched against the file name. For backward
1455 compatibility, this can also be a string with only alphanumeric
1456 characters, which is then interpreted as an extension.
1457 `directory' Matches a directory
1458 `remote' Matches a remote file, accessible through tramp or efs.
1459 Remote files most likely should be visited through Emacs
1460 because external applications cannot handle such paths.
1461 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1462 so all files Emacs knows how to handle. Using this with
1463 command `emacs' will open most files in Emacs. Beware that this
1464 will also open html files inside Emacs, unless you add
1465 (\"html\" . default) to the list as well.
1466 t Default for files not matched by any of the other options.
1467 `system' The system command to open files, like `open' on Windows
1468 and Mac OS X, and mailcap under GNU/Linux. This is the command
1469 that will be selected if you call `C-c C-o' with a double
1470 `C-u C-u' prefix.
1472 Possible values for the command are:
1473 `emacs' The file will be visited by the current Emacs process.
1474 `default' Use the default application for this file type, which is the
1475 association for t in the list, most likely in the system-specific
1476 part.
1477 This can be used to overrule an unwanted setting in the
1478 system-specific variable.
1479 `system' Use the system command for opening files, like \"open\".
1480 This command is specified by the entry whose car is `system'.
1481 Most likely, the system-specific version of this variable
1482 does define this command, but you can overrule/replace it
1483 here.
1484 string A command to be executed by a shell; %s will be replaced
1485 by the path to the file.
1486 sexp A Lisp form which will be evaluated. The file path will
1487 be available in the Lisp variable `file'.
1488 For more examples, see the system specific constants
1489 `org-file-apps-defaults-macosx'
1490 `org-file-apps-defaults-windowsnt'
1491 `org-file-apps-defaults-gnu'."
1492 :group 'org-link-follow
1493 :type '(repeat
1494 (cons (choice :value ""
1495 (string :tag "Extension")
1496 (const :tag "System command to open files" system)
1497 (const :tag "Default for unrecognized files" t)
1498 (const :tag "Remote file" remote)
1499 (const :tag "Links to a directory" directory)
1500 (const :tag "Any files that have Emacs modes"
1501 auto-mode))
1502 (choice :value ""
1503 (const :tag "Visit with Emacs" emacs)
1504 (const :tag "Use default" default)
1505 (const :tag "Use the system command" system)
1506 (string :tag "Command")
1507 (sexp :tag "Lisp form")))))
1509 (defgroup org-refile nil
1510 "Options concerning refiling entries in Org-mode."
1511 :tag "Org Refile"
1512 :group 'org)
1514 (defcustom org-directory "~/org"
1515 "Directory with org files.
1516 This is just a default location to look for Org files. There is no need
1517 at all to put your files into this directory. It is only used in the
1518 following situations:
1520 1. When a remember template specifies a target file that is not an
1521 absolute path. The path will then be interpreted relative to
1522 `org-directory'
1523 2. When a remember note is filed away in an interactive way (when exiting the
1524 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1525 with `org-directory' as the default path."
1526 :group 'org-refile
1527 :group 'org-remember
1528 :type 'directory)
1530 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1531 "Default target for storing notes.
1532 Used by the hooks for remember.el. This can be a string, or nil to mean
1533 the value of `remember-data-file'.
1534 You can set this on a per-template basis with the variable
1535 `org-remember-templates'."
1536 :group 'org-refile
1537 :group 'org-remember
1538 :type '(choice
1539 (const :tag "Default from remember-data-file" nil)
1540 file))
1542 (defcustom org-goto-interface 'outline
1543 "The default interface to be used for `org-goto'.
1544 Allowed values are:
1545 outline The interface shows an outline of the relevant file
1546 and the correct heading is found by moving through
1547 the outline or by searching with incremental search.
1548 outline-path-completion Headlines in the current buffer are offered via
1549 completion. This is the interface also used by
1550 the refile command."
1551 :group 'org-refile
1552 :type '(choice
1553 (const :tag "Outline" outline)
1554 (const :tag "Outline-path-completion" outline-path-completion)))
1556 (defcustom org-goto-max-level 5
1557 "Maximum level to be considered when running org-goto with refile interface."
1558 :group 'org-refile
1559 :type 'integer)
1561 (defcustom org-reverse-note-order nil
1562 "Non-nil means, store new notes at the beginning of a file or entry.
1563 When nil, new notes will be filed to the end of a file or entry.
1564 This can also be a list with cons cells of regular expressions that
1565 are matched against file names, and values."
1566 :group 'org-remember
1567 :group 'org-refile
1568 :type '(choice
1569 (const :tag "Reverse always" t)
1570 (const :tag "Reverse never" nil)
1571 (repeat :tag "By file name regexp"
1572 (cons regexp boolean))))
1574 (defcustom org-refile-targets nil
1575 "Targets for refiling entries with \\[org-refile].
1576 This is list of cons cells. Each cell contains:
1577 - a specification of the files to be considered, either a list of files,
1578 or a symbol whose function or variable value will be used to retrieve
1579 a file name or a list of file names. If you use `org-agenda-files' for
1580 that, all agenda files will be scanned for targets. Nil means, consider
1581 headings in the current buffer.
1582 - A specification of how to find candidate refile targets. This may be
1583 any of:
1584 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1585 This tag has to be present in all target headlines, inheritance will
1586 not be considered.
1587 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1588 todo keyword.
1589 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1590 headlines that are refiling targets.
1591 - a cons cell (:level . N). Any headline of level N is considered a target.
1592 Note that, when `org-odd-levels-only' is set, level corresponds to
1593 order in hierarchy, not to the number of stars.
1594 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1595 Note that, when `org-odd-levels-only' is set, level corresponds to
1596 order in hierarchy, not to the number of stars.
1598 You can set the variable `org-refile-target-verify-function' to a function
1599 to verify each headline found by the simple critery above.
1601 When this variable is nil, all top-level headlines in the current buffer
1602 are used, equivalent to the value `((nil . (:level . 1))'."
1603 :group 'org-refile
1604 :type '(repeat
1605 (cons
1606 (choice :value org-agenda-files
1607 (const :tag "All agenda files" org-agenda-files)
1608 (const :tag "Current buffer" nil)
1609 (function) (variable) (file))
1610 (choice :tag "Identify target headline by"
1611 (cons :tag "Specific tag" (const :value :tag) (string))
1612 (cons :tag "TODO keyword" (const :value :todo) (string))
1613 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1614 (cons :tag "Level number" (const :value :level) (integer))
1615 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1617 (defcustom org-refile-target-verify-function nil
1618 "Function to verify if the headline at point should be a refile target.
1619 The function will be called without arguments, with point at the
1620 beginning of the headline. It should return t and leave point
1621 where it is if the headline is a valid target for refiling.
1623 If the target should not be selected, the function must return nil.
1624 In addition to this, it may move point to a place from where the search
1625 should be continued. For example, the function may decide that the entire
1626 subtree of the current entry should be excluded and move point to the end
1627 of the subtree."
1628 :group 'org-refile
1629 :type 'function)
1631 (defcustom org-refile-use-outline-path nil
1632 "Non-nil means, provide refile targets as paths.
1633 So a level 3 headline will be available as level1/level2/level3.
1635 When the value is `file', also include the file name (without directory)
1636 into the path. In this case, you can also stop the completion after
1637 the file name, to get entries inserted as top level in the file.
1639 When `full-file-path', include the full file path."
1640 :group 'org-refile
1641 :type '(choice
1642 (const :tag "Not" nil)
1643 (const :tag "Yes" t)
1644 (const :tag "Start with file name" file)
1645 (const :tag "Start with full file path" full-file-path)))
1647 (defcustom org-outline-path-complete-in-steps t
1648 "Non-nil means, complete the outline path in hierarchical steps.
1649 When Org-mode uses the refile interface to select an outline path
1650 \(see variable `org-refile-use-outline-path'), the completion of
1651 the path can be done is a single go, or if can be done in steps down
1652 the headline hierarchy. Going in steps is probably the best if you
1653 do not use a special completion package like `ido' or `icicles'.
1654 However, when using these packages, going in one step can be very
1655 fast, while still showing the whole path to the entry."
1656 :group 'org-refile
1657 :type 'boolean)
1659 (defcustom org-refile-allow-creating-parent-nodes nil
1660 "Non-nil means, allow to create new nodes as refile targets.
1661 New nodes are then created by adding \"/new node name\" to the completion
1662 of an existing node. When the value of this variable is `confirm',
1663 new node creation must be confirmed by the user (recommended)
1664 When nil, the completion must match an existing entry.
1666 Note that, if the new heading is not seen by the criteria
1667 listed in `org-refile-targets', multiple instances of the same
1668 heading would be created by trying again to file under the new
1669 heading."
1670 :group 'org-refile
1671 :type '(choice
1672 (const :tag "Never" nil)
1673 (const :tag "Always" t)
1674 (const :tag "Prompt for confirmation" confirm)))
1676 (defgroup org-todo nil
1677 "Options concerning TODO items in Org-mode."
1678 :tag "Org TODO"
1679 :group 'org)
1681 (defgroup org-progress nil
1682 "Options concerning Progress logging in Org-mode."
1683 :tag "Org Progress"
1684 :group 'org-time)
1686 (defvar org-todo-interpretation-widgets
1688 (:tag "Sequence (cycling hits every state)" sequence)
1689 (:tag "Type (cycling directly to DONE)" type))
1690 "The available interpretation symbols for customizing
1691 `org-todo-keywords'.
1692 Interested libraries should add to this list.")
1694 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1695 "List of TODO entry keyword sequences and their interpretation.
1696 \\<org-mode-map>This is a list of sequences.
1698 Each sequence starts with a symbol, either `sequence' or `type',
1699 indicating if the keywords should be interpreted as a sequence of
1700 action steps, or as different types of TODO items. The first
1701 keywords are states requiring action - these states will select a headline
1702 for inclusion into the global TODO list Org-mode produces. If one of
1703 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1704 signify that no further action is necessary. If \"|\" is not found,
1705 the last keyword is treated as the only DONE state of the sequence.
1707 The command \\[org-todo] cycles an entry through these states, and one
1708 additional state where no keyword is present. For details about this
1709 cycling, see the manual.
1711 TODO keywords and interpretation can also be set on a per-file basis with
1712 the special #+SEQ_TODO and #+TYP_TODO lines.
1714 Each keyword can optionally specify a character for fast state selection
1715 \(in combination with the variable `org-use-fast-todo-selection')
1716 and specifiers for state change logging, using the same syntax
1717 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1718 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1719 indicates to record a time stamp each time this state is selected.
1721 Each keyword may also specify if a timestamp or a note should be
1722 recorded when entering or leaving the state, by adding additional
1723 characters in the parenthesis after the keyword. This looks like this:
1724 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1725 record only the time of the state change. With X and Y being either
1726 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1727 Y when leaving the state if and only if the *target* state does not
1728 define X. You may omit any of the fast-selection key or X or /Y,
1729 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1731 For backward compatibility, this variable may also be just a list
1732 of keywords - in this case the interpretation (sequence or type) will be
1733 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1734 :group 'org-todo
1735 :group 'org-keywords
1736 :type '(choice
1737 (repeat :tag "Old syntax, just keywords"
1738 (string :tag "Keyword"))
1739 (repeat :tag "New syntax"
1740 (cons
1741 (choice
1742 :tag "Interpretation"
1743 ;;Quick and dirty way to see
1744 ;;`org-todo-interpretations'. This takes the
1745 ;;place of item arguments
1746 :convert-widget
1747 (lambda (widget)
1748 (widget-put widget
1749 :args (mapcar
1750 #'(lambda (x)
1751 (widget-convert
1752 (cons 'const x)))
1753 org-todo-interpretation-widgets))
1754 widget))
1755 (repeat
1756 (string :tag "Keyword"))))))
1758 (defvar org-todo-keywords-1 nil
1759 "All TODO and DONE keywords active in a buffer.")
1760 (make-variable-buffer-local 'org-todo-keywords-1)
1761 (defvar org-todo-keywords-for-agenda nil)
1762 (defvar org-done-keywords-for-agenda nil)
1763 (defvar org-drawers-for-agenda nil)
1764 (defvar org-todo-keyword-alist-for-agenda nil)
1765 (defvar org-tag-alist-for-agenda nil)
1766 (defvar org-agenda-contributing-files nil)
1767 (defvar org-not-done-keywords nil)
1768 (make-variable-buffer-local 'org-not-done-keywords)
1769 (defvar org-done-keywords nil)
1770 (make-variable-buffer-local 'org-done-keywords)
1771 (defvar org-todo-heads nil)
1772 (make-variable-buffer-local 'org-todo-heads)
1773 (defvar org-todo-sets nil)
1774 (make-variable-buffer-local 'org-todo-sets)
1775 (defvar org-todo-log-states nil)
1776 (make-variable-buffer-local 'org-todo-log-states)
1777 (defvar org-todo-kwd-alist nil)
1778 (make-variable-buffer-local 'org-todo-kwd-alist)
1779 (defvar org-todo-key-alist nil)
1780 (make-variable-buffer-local 'org-todo-key-alist)
1781 (defvar org-todo-key-trigger nil)
1782 (make-variable-buffer-local 'org-todo-key-trigger)
1784 (defcustom org-todo-interpretation 'sequence
1785 "Controls how TODO keywords are interpreted.
1786 This variable is in principle obsolete and is only used for
1787 backward compatibility, if the interpretation of todo keywords is
1788 not given already in `org-todo-keywords'. See that variable for
1789 more information."
1790 :group 'org-todo
1791 :group 'org-keywords
1792 :type '(choice (const sequence)
1793 (const type)))
1795 (defcustom org-use-fast-todo-selection t
1796 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1797 This variable describes if and under what circumstances the cycling
1798 mechanism for TODO keywords will be replaced by a single-key, direct
1799 selection scheme.
1801 When nil, fast selection is never used.
1803 When the symbol `prefix', it will be used when `org-todo' is called with
1804 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1805 in an agenda buffer.
1807 When t, fast selection is used by default. In this case, the prefix
1808 argument forces cycling instead.
1810 In all cases, the special interface is only used if access keys have actually
1811 been assigned by the user, i.e. if keywords in the configuration are followed
1812 by a letter in parenthesis, like TODO(t)."
1813 :group 'org-todo
1814 :type '(choice
1815 (const :tag "Never" nil)
1816 (const :tag "By default" t)
1817 (const :tag "Only with C-u C-c C-t" prefix)))
1819 (defcustom org-provide-todo-statistics t
1820 "Non-nil means, update todo statistics after insert and toggle.
1821 ALL-HEADLINES means update todo statistics by including headlines
1822 with no TODO keyword as well, counting them as not done.
1823 A list of TODO keywords means the same, but skip keywords that are
1824 not in this list.
1826 When this is set, todo statistics is updated in the parent of the
1827 current entry each time a todo state is changed."
1828 :group 'org-todo
1829 :type '(choice
1830 (const :tag "Yes, only for TODO entries" t)
1831 (const :tag "Yes, including all entries" 'all-headlines)
1832 (repeat :tag "Yes, for TODOs in this list"
1833 (string :tag "TODO keyword"))
1834 (other :tag "No TODO statistics" nil)))
1836 (defcustom org-hierarchical-todo-statistics t
1837 "Non-nil means, TODO statistics covers just direct children.
1838 When nil, all entries in the subtree are considered.
1839 This has only an effect if `org-provide-todo-statistics' is set.
1840 To set this to nil for only a single subtree, use a COOKIE_DATA
1841 property and include the word \"recursive\" into the value."
1842 :group 'org-todo
1843 :type 'boolean)
1845 (defcustom org-after-todo-state-change-hook nil
1846 "Hook which is run after the state of a TODO item was changed.
1847 The new state (a string with a TODO keyword, or nil) is available in the
1848 Lisp variable `state'."
1849 :group 'org-todo
1850 :type 'hook)
1852 (defvar org-blocker-hook nil
1853 "Hook for functions that are allowed to block a state change.
1855 Each function gets as its single argument a property list, see
1856 `org-trigger-hook' for more information about this list.
1858 If any of the functions in this hook returns nil, the state change
1859 is blocked.")
1861 (defvar org-trigger-hook nil
1862 "Hook for functions that are triggered by a state change.
1864 Each function gets as its single argument a property list with at least
1865 the following elements:
1867 (:type type-of-change :position pos-at-entry-start
1868 :from old-state :to new-state)
1870 Depending on the type, more properties may be present.
1872 This mechanism is currently implemented for:
1874 TODO state changes
1875 ------------------
1876 :type todo-state-change
1877 :from previous state (keyword as a string), or nil, or a symbol
1878 'todo' or 'done', to indicate the general type of state.
1879 :to new state, like in :from")
1881 (defcustom org-enforce-todo-dependencies nil
1882 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1883 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1884 be blocked if any prior sibling is not yet done.
1885 Finally, if the parent is blocked because of ordered siblings of its own,
1886 the child will also be blocked.
1887 This variable needs to be set before org.el is loaded, and you need to
1888 restart Emacs after a change to make the change effective. The only way
1889 to change is while Emacs is running is through the customize interface."
1890 :set (lambda (var val)
1891 (set var val)
1892 (if val
1893 (add-hook 'org-blocker-hook
1894 'org-block-todo-from-children-or-siblings-or-parent)
1895 (remove-hook 'org-blocker-hook
1896 'org-block-todo-from-children-or-siblings-or-parent)))
1897 :group 'org-todo
1898 :type 'boolean)
1900 (defcustom org-enforce-todo-checkbox-dependencies nil
1901 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1902 When this is nil, checkboxes have no influence on switching TODO states.
1903 When non-nil, you first need to check off all check boxes before the TODO
1904 entry can be switched to DONE.
1905 This variable needs to be set before org.el is loaded, and you need to
1906 restart Emacs after a change to make the change effective. The only way
1907 to change is while Emacs is running is through the customize interface."
1908 :set (lambda (var val)
1909 (set var val)
1910 (if val
1911 (add-hook 'org-blocker-hook
1912 'org-block-todo-from-checkboxes)
1913 (remove-hook 'org-blocker-hook
1914 'org-block-todo-from-checkboxes)))
1915 :group 'org-todo
1916 :type 'boolean)
1918 (defcustom org-treat-insert-todo-heading-as-state-change nil
1919 "Non-nil means, inserting a TODO heading is treated as state change.
1920 So when the command \\[org-insert-todo-heading] is used, state change
1921 logging will apply if appropriate. When nil, the new TODO item will
1922 be inserted directly, and no logging will take place."
1923 :group 'org-todo
1924 :type 'boolean)
1926 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1927 "Non-nil means, switching TODO states with S-cursor counts as state change.
1928 This is the default behavior. However, setting this to nil allows a
1929 convenient way to select a TODO state and bypass any logging associated
1930 with that."
1931 :group 'org-todo
1932 :type 'boolean)
1934 (defcustom org-todo-state-tags-triggers nil
1935 "Tag changes that should be triggered by TODO state changes.
1936 This is a list. Each entry is
1938 (state-change (tag . flag) .......)
1940 State-change can be a string with a state, and empty string to indicate the
1941 state that has no TODO keyword, or it can be one of the symbols `todo'
1942 or `done', meaning any not-done or done state, respectively."
1943 :group 'org-todo
1944 :group 'org-tags
1945 :type '(repeat
1946 (cons (choice :tag "When changing to"
1947 (const :tag "Not-done state" todo)
1948 (const :tag "Done state" done)
1949 (string :tag "State"))
1950 (repeat
1951 (cons :tag "Tag action"
1952 (string :tag "Tag")
1953 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1955 (defcustom org-log-done nil
1956 "Information to record when a task moves to the DONE state.
1958 Possible values are:
1960 nil Don't add anything, just change the keyword
1961 time Add a time stamp to the task
1962 note Prompt for a note and add it with template `org-log-note-headings'
1964 This option can also be set with on a per-file-basis with
1966 #+STARTUP: nologdone
1967 #+STARTUP: logdone
1968 #+STARTUP: lognotedone
1970 You can have local logging settings for a subtree by setting the LOGGING
1971 property to one or more of these keywords."
1972 :group 'org-todo
1973 :group 'org-progress
1974 :type '(choice
1975 (const :tag "No logging" nil)
1976 (const :tag "Record CLOSED timestamp" time)
1977 (const :tag "Record CLOSED timestamp with note." note)))
1979 ;; Normalize old uses of org-log-done.
1980 (cond
1981 ((eq org-log-done t) (setq org-log-done 'time))
1982 ((and (listp org-log-done) (memq 'done org-log-done))
1983 (setq org-log-done 'note)))
1985 (defcustom org-log-reschedule nil
1986 "Information to record when the scheduling date of a tasks is modified.
1988 Possible values are:
1990 nil Don't add anything, just change the date
1991 time Add a time stamp to the task
1992 note Prompt for a note and add it with template `org-log-note-headings'
1994 This option can also be set with on a per-file-basis with
1996 #+STARTUP: nologreschedule
1997 #+STARTUP: logreschedule
1998 #+STARTUP: lognotereschedule"
1999 :group 'org-todo
2000 :group 'org-progress
2001 :type '(choice
2002 (const :tag "No logging" nil)
2003 (const :tag "Record timestamp" time)
2004 (const :tag "Record timestamp with note." note)))
2006 (defcustom org-log-redeadline nil
2007 "Information to record when the deadline date of a tasks is modified.
2009 Possible values are:
2011 nil Don't add anything, just change the date
2012 time Add a time stamp to the task
2013 note Prompt for a note and add it with template `org-log-note-headings'
2015 This option can also be set with on a per-file-basis with
2017 #+STARTUP: nologredeadline
2018 #+STARTUP: logredeadline
2019 #+STARTUP: lognoteredeadline
2021 You can have local logging settings for a subtree by setting the LOGGING
2022 property to one or more of these keywords."
2023 :group 'org-todo
2024 :group 'org-progress
2025 :type '(choice
2026 (const :tag "No logging" nil)
2027 (const :tag "Record timestamp" time)
2028 (const :tag "Record timestamp with note." note)))
2030 (defcustom org-log-note-clock-out nil
2031 "Non-nil means, record a note when clocking out of an item.
2032 This can also be configured on a per-file basis by adding one of
2033 the following lines anywhere in the buffer:
2035 #+STARTUP: lognoteclock-out
2036 #+STARTUP: nolognoteclock-out"
2037 :group 'org-todo
2038 :group 'org-progress
2039 :type 'boolean)
2041 (defcustom org-log-done-with-time t
2042 "Non-nil means, the CLOSED time stamp will contain date and time.
2043 When nil, only the date will be recorded."
2044 :group 'org-progress
2045 :type 'boolean)
2047 (defcustom org-log-note-headings
2048 '((done . "CLOSING NOTE %t")
2049 (state . "State %-12s from %-12S %t")
2050 (note . "Note taken on %t")
2051 (reschedule . "Rescheduled from %S on %t")
2052 (redeadline . "New deadline from %S on %t")
2053 (clock-out . ""))
2054 "Headings for notes added to entries.
2055 The value is an alist, with the car being a symbol indicating the note
2056 context, and the cdr is the heading to be used. The heading may also be the
2057 empty string.
2058 %t in the heading will be replaced by a time stamp.
2059 %s will be replaced by the new TODO state, in double quotes.
2060 %S will be replaced by the old TODO state, in double quotes.
2061 %u will be replaced by the user name.
2062 %U will be replaced by the full user name."
2063 :group 'org-todo
2064 :group 'org-progress
2065 :type '(list :greedy t
2066 (cons (const :tag "Heading when closing an item" done) string)
2067 (cons (const :tag
2068 "Heading when changing todo state (todo sequence only)"
2069 state) string)
2070 (cons (const :tag "Heading when just taking a note" note) string)
2071 (cons (const :tag "Heading when clocking out" clock-out) string)
2072 (cons (const :tag "Heading when rescheduling" reschedule) string)
2073 (cons (const :tag "Heading when changing deadline" redeadline) string)))
2075 (unless (assq 'note org-log-note-headings)
2076 (push '(note . "%t") org-log-note-headings))
2078 (defcustom org-log-into-drawer nil
2079 "Non-nil means, insert state change notes and time stamps into a drawer.
2080 When nil, state changes notes will be inserted after the headline and
2081 any scheduling and clock lines, but not inside a drawer.
2083 The value of this variable should be the name of the drawer to use.
2084 LOGBOOK is proposed at the default drawer for this purpose, you can
2085 also set this to a string to define the drawer of your choice.
2087 A value of t is also allowed, representing \"LOGBOOK\".
2089 If this variable is set, `org-log-state-notes-insert-after-drawers'
2090 will be ignored.
2092 You can set the property LOG_INTO_DRAWER to overrule this setting for
2093 a subtree."
2094 :group 'org-todo
2095 :group 'org-progress
2096 :type '(choice
2097 (const :tag "Not into a drawer" nil)
2098 (const :tag "LOGBOOK" t)
2099 (string :tag "Other")))
2101 (if (fboundp 'defvaralias)
2102 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2104 (defun org-log-into-drawer ()
2105 "Return the value of `org-log-into-drawer', but let properties overrule.
2106 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2107 used instead of the default value."
2108 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2109 (cond
2110 ((or (not p) (equal p "nil")) org-log-into-drawer)
2111 ((equal p "t") "LOGBOOK")
2112 (t p))))
2114 (defcustom org-log-state-notes-insert-after-drawers nil
2115 "Non-nil means, insert state change notes after any drawers in entry.
2116 Only the drawers that *immediately* follow the headline and the
2117 deadline/scheduled line are skipped.
2118 When nil, insert notes right after the heading and perhaps the line
2119 with deadline/scheduling if present.
2121 This variable will have no effect if `org-log-into-drawer' is
2122 set."
2123 :group 'org-todo
2124 :group 'org-progress
2125 :type 'boolean)
2127 (defcustom org-log-states-order-reversed t
2128 "Non-nil means, the latest state change note will be directly after heading.
2129 When nil, the notes will be orderer according to time."
2130 :group 'org-todo
2131 :group 'org-progress
2132 :type 'boolean)
2134 (defcustom org-log-repeat 'time
2135 "Non-nil means, record moving through the DONE state when triggering repeat.
2136 An auto-repeating task is immediately switched back to TODO when
2137 marked DONE. If you are not logging state changes (by adding \"@\"
2138 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2139 record a closing note, there will be no record of the task moving
2140 through DONE. This variable forces taking a note anyway.
2142 nil Don't force a record
2143 time Record a time stamp
2144 note Record a note
2146 This option can also be set with on a per-file-basis with
2148 #+STARTUP: logrepeat
2149 #+STARTUP: lognoterepeat
2150 #+STARTUP: nologrepeat
2152 You can have local logging settings for a subtree by setting the LOGGING
2153 property to one or more of these keywords."
2154 :group 'org-todo
2155 :group 'org-progress
2156 :type '(choice
2157 (const :tag "Don't force a record" nil)
2158 (const :tag "Force recording the DONE state" time)
2159 (const :tag "Force recording a note with the DONE state" note)))
2162 (defgroup org-priorities nil
2163 "Priorities in Org-mode."
2164 :tag "Org Priorities"
2165 :group 'org-todo)
2167 (defcustom org-enable-priority-commands t
2168 "Non-nil means, priority commands are active.
2169 When nil, these commands will be disabled, so that you never accidentally
2170 set a priority."
2171 :group 'org-priorities
2172 :type 'boolean)
2174 (defcustom org-highest-priority ?A
2175 "The highest priority of TODO items. A character like ?A, ?B etc.
2176 Must have a smaller ASCII number than `org-lowest-priority'."
2177 :group 'org-priorities
2178 :type 'character)
2180 (defcustom org-lowest-priority ?C
2181 "The lowest priority of TODO items. A character like ?A, ?B etc.
2182 Must have a larger ASCII number than `org-highest-priority'."
2183 :group 'org-priorities
2184 :type 'character)
2186 (defcustom org-default-priority ?B
2187 "The default priority of TODO items.
2188 This is the priority an item get if no explicit priority is given."
2189 :group 'org-priorities
2190 :type 'character)
2192 (defcustom org-priority-start-cycle-with-default t
2193 "Non-nil means, start with default priority when starting to cycle.
2194 When this is nil, the first step in the cycle will be (depending on the
2195 command used) one higher or lower that the default priority."
2196 :group 'org-priorities
2197 :type 'boolean)
2199 (defgroup org-time nil
2200 "Options concerning time stamps and deadlines in Org-mode."
2201 :tag "Org Time"
2202 :group 'org)
2204 (defcustom org-insert-labeled-timestamps-at-point nil
2205 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2206 When nil, these labeled time stamps are forces into the second line of an
2207 entry, just after the headline. When scheduling from the global TODO list,
2208 the time stamp will always be forced into the second line."
2209 :group 'org-time
2210 :type 'boolean)
2212 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2213 "Formats for `format-time-string' which are used for time stamps.
2214 It is not recommended to change this constant.")
2216 (defcustom org-time-stamp-rounding-minutes '(0 5)
2217 "Number of minutes to round time stamps to.
2218 These are two values, the first applies when first creating a time stamp.
2219 The second applies when changing it with the commands `S-up' and `S-down'.
2220 When changing the time stamp, this means that it will change in steps
2221 of N minutes, as given by the second value.
2223 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2224 numbers should be factors of 60, so for example 5, 10, 15.
2226 When this is larger than 1, you can still force an exact time-stamp by using
2227 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2228 and by using a prefix arg to `S-up/down' to specify the exact number
2229 of minutes to shift."
2230 :group 'org-time
2231 :get '(lambda (var) ; Make sure all entries have 5 elements
2232 (if (integerp (default-value var))
2233 (list (default-value var) 5)
2234 (default-value var)))
2235 :type '(list
2236 (integer :tag "when inserting times")
2237 (integer :tag "when modifying times")))
2239 ;; Normalize old customizations of this variable.
2240 (when (integerp org-time-stamp-rounding-minutes)
2241 (setq org-time-stamp-rounding-minutes
2242 (list org-time-stamp-rounding-minutes
2243 org-time-stamp-rounding-minutes)))
2245 (defcustom org-display-custom-times nil
2246 "Non-nil means, overlay custom formats over all time stamps.
2247 The formats are defined through the variable `org-time-stamp-custom-formats'.
2248 To turn this on on a per-file basis, insert anywhere in the file:
2249 #+STARTUP: customtime"
2250 :group 'org-time
2251 :set 'set-default
2252 :type 'sexp)
2253 (make-variable-buffer-local 'org-display-custom-times)
2255 (defcustom org-time-stamp-custom-formats
2256 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2257 "Custom formats for time stamps. See `format-time-string' for the syntax.
2258 These are overlayed over the default ISO format if the variable
2259 `org-display-custom-times' is set. Time like %H:%M should be at the
2260 end of the second format. The custom formats are also honored by export
2261 commands, if custom time display is turned on at the time of export."
2262 :group 'org-time
2263 :type 'sexp)
2265 (defun org-time-stamp-format (&optional long inactive)
2266 "Get the right format for a time string."
2267 (let ((f (if long (cdr org-time-stamp-formats)
2268 (car org-time-stamp-formats))))
2269 (if inactive
2270 (concat "[" (substring f 1 -1) "]")
2271 f)))
2273 (defcustom org-time-clocksum-format "%d:%02d"
2274 "The format string used when creating CLOCKSUM lines, or when
2275 org-mode generates a time duration."
2276 :group 'org-time
2277 :type 'string)
2279 (defcustom org-time-clocksum-use-fractional nil
2280 "If non-nil, \\[org-clock-display] uses fractional times.
2281 org-mode generates a time duration."
2282 :group 'org-time
2283 :type 'boolean)
2285 (defcustom org-time-clocksum-fractional-format "%.2f"
2286 "The format string used when creating CLOCKSUM lines, or when
2287 org-mode generates a time duration."
2288 :group 'org-time
2289 :type 'string)
2291 (defcustom org-deadline-warning-days 14
2292 "No. of days before expiration during which a deadline becomes active.
2293 This variable governs the display in sparse trees and in the agenda.
2294 When 0 or negative, it means use this number (the absolute value of it)
2295 even if a deadline has a different individual lead time specified.
2297 Custom commands can set this variable in the options section."
2298 :group 'org-time
2299 :group 'org-agenda-daily/weekly
2300 :type 'integer)
2302 (defcustom org-read-date-prefer-future t
2303 "Non-nil means, assume future for incomplete date input from user.
2304 This affects the following situations:
2305 1. The user gives a month but not a year.
2306 For example, if it is april and you enter \"feb 2\", this will be read
2307 as feb 2, *next* year. \"May 5\", however, will be this year.
2308 2. The user gives a day, but no month.
2309 For example, if today is the 15th, and you enter \"3\", Org-mode will
2310 read this as the third of *next* month. However, if you enter \"17\",
2311 it will be considered as *this* month.
2313 If you set this variable to the symbol `time', then also the following
2314 will work:
2316 3. If the user gives a time, but no day. If the time is before now,
2317 to will be interpreted as tomorrow.
2319 Currently none of this works for ISO week specifications.
2321 When this option is nil, the current day, month and year will always be
2322 used as defaults."
2323 :group 'org-time
2324 :type '(choice
2325 (const :tag "Never" nil)
2326 (const :tag "Check month and day" t)
2327 (const :tag "Check month, day, and time" time)))
2329 (defcustom org-read-date-display-live t
2330 "Non-nil means, display current interpretation of date prompt live.
2331 This display will be in an overlay, in the minibuffer."
2332 :group 'org-time
2333 :type 'boolean)
2335 (defcustom org-read-date-popup-calendar t
2336 "Non-nil means, pop up a calendar when prompting for a date.
2337 In the calendar, the date can be selected with mouse-1. However, the
2338 minibuffer will also be active, and you can simply enter the date as well.
2339 When nil, only the minibuffer will be available."
2340 :group 'org-time
2341 :type 'boolean)
2342 (if (fboundp 'defvaralias)
2343 (defvaralias 'org-popup-calendar-for-date-prompt
2344 'org-read-date-popup-calendar))
2346 (defcustom org-read-date-minibuffer-setup-hook nil
2347 "Hook to be used to set up keys for the date/time interface.
2348 Add key definitions to `minibuffer-local-map', which will be a temporary
2349 copy."
2350 :group 'org-time
2351 :type 'hook)
2353 (defcustom org-extend-today-until 0
2354 "The hour when your day really ends. Must be an integer.
2355 This has influence for the following applications:
2356 - When switching the agenda to \"today\". It it is still earlier than
2357 the time given here, the day recognized as TODAY is actually yesterday.
2358 - When a date is read from the user and it is still before the time given
2359 here, the current date and time will be assumed to be yesterday, 23:59.
2360 Also, timestamps inserted in remember templates follow this rule.
2362 IMPORTANT: This is a feature whose implementation is and likely will
2363 remain incomplete. Really, it is only here because past midnight seems to
2364 be the favorite working time of John Wiegley :-)"
2365 :group 'org-time
2366 :type 'integer)
2368 (defcustom org-edit-timestamp-down-means-later nil
2369 "Non-nil means, S-down will increase the time in a time stamp.
2370 When nil, S-up will increase."
2371 :group 'org-time
2372 :type 'boolean)
2374 (defcustom org-calendar-follow-timestamp-change t
2375 "Non-nil means, make the calendar window follow timestamp changes.
2376 When a timestamp is modified and the calendar window is visible, it will be
2377 moved to the new date."
2378 :group 'org-time
2379 :type 'boolean)
2381 (defgroup org-tags nil
2382 "Options concerning tags in Org-mode."
2383 :tag "Org Tags"
2384 :group 'org)
2386 (defcustom org-tag-alist nil
2387 "List of tags allowed in Org-mode files.
2388 When this list is nil, Org-mode will base TAG input on what is already in the
2389 buffer.
2390 The value of this variable is an alist, the car of each entry must be a
2391 keyword as a string, the cdr may be a character that is used to select
2392 that tag through the fast-tag-selection interface.
2393 See the manual for details."
2394 :group 'org-tags
2395 :type '(repeat
2396 (choice
2397 (cons (string :tag "Tag name")
2398 (character :tag "Access char"))
2399 (list :tag "Start radio group"
2400 (const :startgroup)
2401 (option (string :tag "Group description")))
2402 (list :tag "End radio group"
2403 (const :endgroup)
2404 (option (string :tag "Group description")))
2405 (const :tag "New line" (:newline)))))
2407 (defcustom org-tag-persistent-alist nil
2408 "List of tags that will always appear in all Org-mode files.
2409 This is in addition to any in buffer settings or customizations
2410 of `org-tag-alist'.
2411 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2412 The value of this variable is an alist, the car of each entry must be a
2413 keyword as a string, the cdr may be a character that is used to select
2414 that tag through the fast-tag-selection interface.
2415 See the manual for details.
2416 To disable these tags on a per-file basis, insert anywhere in the file:
2417 #+STARTUP: noptag"
2418 :group 'org-tags
2419 :type '(repeat
2420 (choice
2421 (cons (string :tag "Tag name")
2422 (character :tag "Access char"))
2423 (const :tag "Start radio group" (:startgroup))
2424 (const :tag "End radio group" (:endgroup))
2425 (const :tag "New line" (:newline)))))
2427 (defvar org-file-tags nil
2428 "List of tags that can be inherited by all entries in the file.
2429 The tags will be inherited if the variable `org-use-tag-inheritance'
2430 says they should be.
2431 This variable is populated from #+FILETAGS lines.")
2433 (defcustom org-use-fast-tag-selection 'auto
2434 "Non-nil means, use fast tag selection scheme.
2435 This is a special interface to select and deselect tags with single keys.
2436 When nil, fast selection is never used.
2437 When the symbol `auto', fast selection is used if and only if selection
2438 characters for tags have been configured, either through the variable
2439 `org-tag-alist' or through a #+TAGS line in the buffer.
2440 When t, fast selection is always used and selection keys are assigned
2441 automatically if necessary."
2442 :group 'org-tags
2443 :type '(choice
2444 (const :tag "Always" t)
2445 (const :tag "Never" nil)
2446 (const :tag "When selection characters are configured" 'auto)))
2448 (defcustom org-fast-tag-selection-single-key nil
2449 "Non-nil means, fast tag selection exits after first change.
2450 When nil, you have to press RET to exit it.
2451 During fast tag selection, you can toggle this flag with `C-c'.
2452 This variable can also have the value `expert'. In this case, the window
2453 displaying the tags menu is not even shown, until you press C-c again."
2454 :group 'org-tags
2455 :type '(choice
2456 (const :tag "No" nil)
2457 (const :tag "Yes" t)
2458 (const :tag "Expert" expert)))
2460 (defvar org-fast-tag-selection-include-todo nil
2461 "Non-nil means, fast tags selection interface will also offer TODO states.
2462 This is an undocumented feature, you should not rely on it.")
2464 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2465 "The column to which tags should be indented in a headline.
2466 If this number is positive, it specifies the column. If it is negative,
2467 it means that the tags should be flushright to that column. For example,
2468 -80 works well for a normal 80 character screen."
2469 :group 'org-tags
2470 :type 'integer)
2472 (defcustom org-auto-align-tags t
2473 "Non-nil means, realign tags after pro/demotion of TODO state change.
2474 These operations change the length of a headline and therefore shift
2475 the tags around. With this options turned on, after each such operation
2476 the tags are again aligned to `org-tags-column'."
2477 :group 'org-tags
2478 :type 'boolean)
2480 (defcustom org-use-tag-inheritance t
2481 "Non-nil means, tags in levels apply also for sublevels.
2482 When nil, only the tags directly given in a specific line apply there.
2483 This may also be a list of tags that should be inherited, or a regexp that
2484 matches tags that should be inherited. Additional control is possible
2485 with the variable `org-tags-exclude-from-inheritance' which gives an
2486 explicit list of tags to be excluded from inheritance., even if the value of
2487 `org-use-tag-inheritance' would select it for inheritance.
2489 If this option is t, a match early-on in a tree can lead to a large
2490 number of matches in the subtree when constructing the agenda or creating
2491 a sparse tree. If you only want to see the first match in a tree during
2492 a search, check out the variable `org-tags-match-list-sublevels'."
2493 :group 'org-tags
2494 :type '(choice
2495 (const :tag "Not" nil)
2496 (const :tag "Always" t)
2497 (repeat :tag "Specific tags" (string :tag "Tag"))
2498 (regexp :tag "Tags matched by regexp")))
2500 (defcustom org-tags-exclude-from-inheritance nil
2501 "List of tags that should never be inherited.
2502 This is a way to exclude a few tags from inheritance. For way to do
2503 the opposite, to actively allow inheritance for selected tags,
2504 see the variable `org-use-tag-inheritance'."
2505 :group 'org-tags
2506 :type '(repeat (string :tag "Tag")))
2508 (defun org-tag-inherit-p (tag)
2509 "Check if TAG is one that should be inherited."
2510 (cond
2511 ((member tag org-tags-exclude-from-inheritance) nil)
2512 ((eq org-use-tag-inheritance t) t)
2513 ((not org-use-tag-inheritance) nil)
2514 ((stringp org-use-tag-inheritance)
2515 (string-match org-use-tag-inheritance tag))
2516 ((listp org-use-tag-inheritance)
2517 (member tag org-use-tag-inheritance))
2518 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2520 (defcustom org-tags-match-list-sublevels t
2521 "Non-nil means list also sublevels of headlines matching a search.
2522 This variable applies to tags/property searches, and also to stuck
2523 projects because this search is based on a tags match as well.
2525 When set to the symbol `indented', sublevels are indented with
2526 leading dots.
2528 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2529 the sublevels of a headline matching a tag search often also match
2530 the same search. Listing all of them can create very long lists.
2531 Setting this variable to nil causes subtrees of a match to be skipped.
2533 This variable is semi-obsolete and probably should always be true. It
2534 is better to limit inheritance to certain tags using the variables
2535 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2536 :group 'org-tags
2537 :type '(choice
2538 (const :tag "No, don't list them" nil)
2539 (const :tag "Yes, do list them" t)
2540 (const :tag "List them, indented with leading dots" indented)))
2542 (defcustom org-tags-sort-function nil
2543 "When set, tags are sorted using this function as a comparator"
2544 :group 'org-tags
2545 :type '(choice
2546 (const :tag "No sorting" nil)
2547 (const :tag "Alphabetical" string<)
2548 (const :tag "Reverse alphabetical" string>)
2549 (function :tag "Custom function" nil)))
2551 (defvar org-tags-history nil
2552 "History of minibuffer reads for tags.")
2553 (defvar org-last-tags-completion-table nil
2554 "The last used completion table for tags.")
2555 (defvar org-after-tags-change-hook nil
2556 "Hook that is run after the tags in a line have changed.")
2558 (defgroup org-properties nil
2559 "Options concerning properties in Org-mode."
2560 :tag "Org Properties"
2561 :group 'org)
2563 (defcustom org-property-format "%-10s %s"
2564 "How property key/value pairs should be formatted by `indent-line'.
2565 When `indent-line' hits a property definition, it will format the line
2566 according to this format, mainly to make sure that the values are
2567 lined-up with respect to each other."
2568 :group 'org-properties
2569 :type 'string)
2571 (defcustom org-use-property-inheritance nil
2572 "Non-nil means, properties apply also for sublevels.
2574 This setting is chiefly used during property searches. Turning it on can
2575 cause significant overhead when doing a search, which is why it is not
2576 on by default.
2578 When nil, only the properties directly given in the current entry count.
2579 When t, every property is inherited. The value may also be a list of
2580 properties that should have inheritance, or a regular expression matching
2581 properties that should be inherited.
2583 However, note that some special properties use inheritance under special
2584 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2585 and the properties ending in \"_ALL\" when they are used as descriptor
2586 for valid values of a property.
2588 Note for programmers:
2589 When querying an entry with `org-entry-get', you can control if inheritance
2590 should be used. By default, `org-entry-get' looks only at the local
2591 properties. You can request inheritance by setting the inherit argument
2592 to t (to force inheritance) or to `selective' (to respect the setting
2593 in this variable)."
2594 :group 'org-properties
2595 :type '(choice
2596 (const :tag "Not" nil)
2597 (const :tag "Always" t)
2598 (repeat :tag "Specific properties" (string :tag "Property"))
2599 (regexp :tag "Properties matched by regexp")))
2601 (defun org-property-inherit-p (property)
2602 "Check if PROPERTY is one that should be inherited."
2603 (cond
2604 ((eq org-use-property-inheritance t) t)
2605 ((not org-use-property-inheritance) nil)
2606 ((stringp org-use-property-inheritance)
2607 (string-match org-use-property-inheritance property))
2608 ((listp org-use-property-inheritance)
2609 (member property org-use-property-inheritance))
2610 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2612 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2613 "The default column format, if no other format has been defined.
2614 This variable can be set on the per-file basis by inserting a line
2616 #+COLUMNS: %25ITEM ....."
2617 :group 'org-properties
2618 :type 'string)
2620 (defcustom org-columns-ellipses ".."
2621 "The ellipses to be used when a field in column view is truncated.
2622 When this is the empty string, as many characters as possible are shown,
2623 but then there will be no visual indication that the field has been truncated.
2624 When this is a string of length N, the last N characters of a truncated
2625 field are replaced by this string. If the column is narrower than the
2626 ellipses string, only part of the ellipses string will be shown."
2627 :group 'org-properties
2628 :type 'string)
2630 (defcustom org-columns-modify-value-for-display-function nil
2631 "Function that modifies values for display in column view.
2632 For example, it can be used to cut out a certain part from a time stamp.
2633 The function must take 2 arguments:
2635 column-title The title of the column (*not* the property name)
2636 value The value that should be modified.
2638 The function should return the value that should be displayed,
2639 or nil if the normal value should be used."
2640 :group 'org-properties
2641 :type 'function)
2643 (defcustom org-effort-property "Effort"
2644 "The property that is being used to keep track of effort estimates.
2645 Effort estimates given in this property need to have the format H:MM."
2646 :group 'org-properties
2647 :group 'org-progress
2648 :type '(string :tag "Property"))
2650 (defconst org-global-properties-fixed
2651 '(("VISIBILITY_ALL" . "folded children content all")
2652 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2653 "List of property/value pairs that can be inherited by any entry.
2655 These are fixed values, for the preset properties. The user variable
2656 that can be used to add to this list is `org-global-properties'.
2658 The entries in this list are cons cells where the car is a property
2659 name and cdr is a string with the value. If the value represents
2660 multiple items like an \"_ALL\" property, separate the items by
2661 spaces.")
2663 (defcustom org-global-properties nil
2664 "List of property/value pairs that can be inherited by any entry.
2666 This list will be combined with the constant `org-global-properties-fixed'.
2668 The entries in this list are cons cells where the car is a property
2669 name and cdr is a string with the value.
2671 You can set buffer-local values for the same purpose in the variable
2672 `org-file-properties' this by adding lines like
2674 #+PROPERTY: NAME VALUE"
2675 :group 'org-properties
2676 :type '(repeat
2677 (cons (string :tag "Property")
2678 (string :tag "Value"))))
2680 (defvar org-file-properties nil
2681 "List of property/value pairs that can be inherited by any entry.
2682 Valid for the current buffer.
2683 This variable is populated from #+PROPERTY lines.")
2684 (make-variable-buffer-local 'org-file-properties)
2686 (defgroup org-agenda nil
2687 "Options concerning agenda views in Org-mode."
2688 :tag "Org Agenda"
2689 :group 'org)
2691 (defvar org-category nil
2692 "Variable used by org files to set a category for agenda display.
2693 Such files should use a file variable to set it, for example
2695 # -*- mode: org; org-category: \"ELisp\"
2697 or contain a special line
2699 #+CATEGORY: ELisp
2701 If the file does not specify a category, then file's base name
2702 is used instead.")
2703 (make-variable-buffer-local 'org-category)
2704 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2706 (defcustom org-agenda-files nil
2707 "The files to be used for agenda display.
2708 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2709 \\[org-remove-file]. You can also use customize to edit the list.
2711 If an entry is a directory, all files in that directory that are matched by
2712 `org-agenda-file-regexp' will be part of the file list.
2714 If the value of the variable is not a list but a single file name, then
2715 the list of agenda files is actually stored and maintained in that file, one
2716 agenda file per line."
2717 :group 'org-agenda
2718 :type '(choice
2719 (repeat :tag "List of files and directories" file)
2720 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2722 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2723 "Regular expression to match files for `org-agenda-files'.
2724 If any element in the list in that variable contains a directory instead
2725 of a normal file, all files in that directory that are matched by this
2726 regular expression will be included."
2727 :group 'org-agenda
2728 :type 'regexp)
2730 (defcustom org-agenda-text-search-extra-files nil
2731 "List of extra files to be searched by text search commands.
2732 These files will be search in addition to the agenda files by the
2733 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2734 Note that these files will only be searched for text search commands,
2735 not for the other agenda views like todo lists, tag searches or the weekly
2736 agenda. This variable is intended to list notes and possibly archive files
2737 that should also be searched by these two commands.
2738 In fact, if the first element in the list is the symbol `agenda-archives',
2739 than all archive files of all agenda files will be added to the search
2740 scope."
2741 :group 'org-agenda
2742 :type '(set :greedy t
2743 (const :tag "Agenda Archives" agenda-archives)
2744 (repeat :inline t (file))))
2746 (if (fboundp 'defvaralias)
2747 (defvaralias 'org-agenda-multi-occur-extra-files
2748 'org-agenda-text-search-extra-files))
2750 (defcustom org-agenda-skip-unavailable-files nil
2751 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2752 A nil value means to remove them, after a query, from the list."
2753 :group 'org-agenda
2754 :type 'boolean)
2756 (defcustom org-calendar-to-agenda-key [?c]
2757 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2758 The command `org-calendar-goto-agenda' will be bound to this key. The
2759 default is the character `c' because then `c' can be used to switch back and
2760 forth between agenda and calendar."
2761 :group 'org-agenda
2762 :type 'sexp)
2764 (defcustom org-calendar-agenda-action-key [?k]
2765 "The key to be installed in `calendar-mode-map' for agenda-action.
2766 The command `org-agenda-action' will be bound to this key. The
2767 default is the character `k' because we use the same key in the agenda."
2768 :group 'org-agenda
2769 :type 'sexp)
2771 (defcustom org-calendar-insert-diary-entry-key [?i]
2772 "The key to be installed in `calendar-mode-map' for adding diary entries.
2773 This option is irrelevant until `org-agenda-diary-file' has been configured
2774 to point to an Org-mode file. When that is the case, the command
2775 `org-agenda-diary-entry' will be bound to the key given here, by default
2776 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2777 if you want to continue doing this, you need to change this to a different
2778 key."
2779 :group 'org-agenda
2780 :type 'sexp)
2782 (defcustom org-agenda-diary-file 'diary-file
2783 "File to which to add new entries with the `i' key in agenda and calendar.
2784 When this is the symbol `diary-file', the functionality in the Emacs
2785 calendar will be used to add entries to the `diary-file'. But when this
2786 points to a file, `org-agenda-diary-entry' will be used instead."
2787 :group 'org-agenda
2788 :type '(choice
2789 (const :tag "The standard Emacs diary file" diary-file)
2790 (file :tag "Special Org file diary entries")))
2792 (eval-after-load "calendar"
2793 '(progn
2794 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2795 'org-calendar-goto-agenda)
2796 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2797 'org-agenda-action)
2798 (add-hook 'calendar-mode-hook
2799 (lambda ()
2800 (unless (eq org-agenda-diary-file 'diary-file)
2801 (define-key calendar-mode-map
2802 org-calendar-insert-diary-entry-key
2803 'org-agenda-diary-entry))))))
2805 (defgroup org-latex nil
2806 "Options for embedding LaTeX code into Org-mode."
2807 :tag "Org LaTeX"
2808 :group 'org)
2810 (defcustom org-format-latex-options
2811 '(:foreground default :background default :scale 1.0
2812 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2813 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2814 "Options for creating images from LaTeX fragments.
2815 This is a property list with the following properties:
2816 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2817 `default' means use the foreground of the default face.
2818 :background the background color, or \"Transparent\".
2819 `default' means use the background of the default face.
2820 :scale a scaling factor for the size of the images.
2821 :html-foreground, :html-background, :html-scale
2822 the same numbers for HTML export.
2823 :matchers a list indicating which matchers should be used to
2824 find LaTeX fragments. Valid members of this list are:
2825 \"begin\" find environments
2826 \"$1\" find single characters surrounded by $.$
2827 \"$\" find math expressions surrounded by $...$
2828 \"$$\" find math expressions surrounded by $$....$$
2829 \"\\(\" find math expressions surrounded by \\(...\\)
2830 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2831 :group 'org-latex
2832 :type 'plist)
2834 (defcustom org-format-latex-header "\\documentclass{article}
2835 \\usepackage{amssymb}
2836 \\usepackage[usenames]{color}
2837 \\usepackage{amsmath}
2838 \\usepackage{latexsym}
2839 \\usepackage[mathscr]{eucal}
2840 \\pagestyle{empty} % do not remove
2841 % The settings below are copied from fullpage.sty
2842 \\setlength{\\textwidth}{\\paperwidth}
2843 \\addtolength{\\textwidth}{-3cm}
2844 \\setlength{\\oddsidemargin}{1.5cm}
2845 \\addtolength{\\oddsidemargin}{-2.54cm}
2846 \\setlength{\\evensidemargin}{\\oddsidemargin}
2847 \\setlength{\\textheight}{\\paperheight}
2848 \\addtolength{\\textheight}{-\\headheight}
2849 \\addtolength{\\textheight}{-\\headsep}
2850 \\addtolength{\\textheight}{-\\footskip}
2851 \\addtolength{\\textheight}{-3cm}
2852 \\setlength{\\topmargin}{1.5cm}
2853 \\addtolength{\\topmargin}{-2.54cm}"
2854 "The document header used for processing LaTeX fragments.
2855 It is imperative that this header make sure that no page number
2856 appears on the page."
2857 :group 'org-latex
2858 :type 'string)
2860 ;; The following variable is defined here because is it also used
2861 ;; when formatting latex fragments. Originally it was part of the
2862 ;; LaTeX exporter, which is why the name includes "export".
2863 (defcustom org-export-latex-packages-alist nil
2864 "Alist of packages to be inserted in the header.
2865 Each cell is of the format \( \"option\" . \"package\" \)."
2866 :group 'org-export-latex
2867 :type '(repeat
2868 (list
2869 (string :tag "option")
2870 (string :tag "package"))))
2872 (defgroup org-font-lock nil
2873 "Font-lock settings for highlighting in Org-mode."
2874 :tag "Org Font Lock"
2875 :group 'org)
2877 (defcustom org-level-color-stars-only nil
2878 "Non-nil means fontify only the stars in each headline.
2879 When nil, the entire headline is fontified.
2880 Changing it requires restart of `font-lock-mode' to become effective
2881 also in regions already fontified."
2882 :group 'org-font-lock
2883 :type 'boolean)
2885 (defcustom org-hide-leading-stars nil
2886 "Non-nil means, hide the first N-1 stars in a headline.
2887 This works by using the face `org-hide' for these stars. This
2888 face is white for a light background, and black for a dark
2889 background. You may have to customize the face `org-hide' to
2890 make this work.
2891 Changing it requires restart of `font-lock-mode' to become effective
2892 also in regions already fontified.
2893 You may also set this on a per-file basis by adding one of the following
2894 lines to the buffer:
2896 #+STARTUP: hidestars
2897 #+STARTUP: showstars"
2898 :group 'org-font-lock
2899 :type 'boolean)
2901 (defcustom org-fontify-done-headline nil
2902 "Non-nil means, change the face of a headline if it is marked DONE.
2903 Normally, only the TODO/DONE keyword indicates the state of a headline.
2904 When this is non-nil, the headline after the keyword is set to the
2905 `org-headline-done' as an additional indication."
2906 :group 'org-font-lock
2907 :type 'boolean)
2909 (defcustom org-fontify-emphasized-text t
2910 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2911 Changing this variable requires a restart of Emacs to take effect."
2912 :group 'org-font-lock
2913 :type 'boolean)
2915 (defcustom org-fontify-whole-heading-line nil
2916 "Non-nil means fontify the whole line for headings.
2917 This is useful when setting a background color for the
2918 org-level-* faces."
2919 :group 'org-font-lock
2920 :type 'boolean)
2922 (defcustom org-highlight-latex-fragments-and-specials nil
2923 "Non-nil means, fontify what is treated specially by the exporters."
2924 :group 'org-font-lock
2925 :type 'boolean)
2927 (defcustom org-hide-emphasis-markers nil
2928 "Non-nil mean font-lock should hide the emphasis marker characters."
2929 :group 'org-font-lock
2930 :type 'boolean)
2932 (defvar org-emph-re nil
2933 "Regular expression for matching emphasis.")
2934 (defvar org-verbatim-re nil
2935 "Regular expression for matching verbatim text.")
2936 (defvar org-emphasis-regexp-components) ; defined just below
2937 (defvar org-emphasis-alist) ; defined just below
2938 (defun org-set-emph-re (var val)
2939 "Set variable and compute the emphasis regular expression."
2940 (set var val)
2941 (when (and (boundp 'org-emphasis-alist)
2942 (boundp 'org-emphasis-regexp-components)
2943 org-emphasis-alist org-emphasis-regexp-components)
2944 (let* ((e org-emphasis-regexp-components)
2945 (pre (car e))
2946 (post (nth 1 e))
2947 (border (nth 2 e))
2948 (body (nth 3 e))
2949 (nl (nth 4 e))
2950 (body1 (concat body "*?"))
2951 (markers (mapconcat 'car org-emphasis-alist ""))
2952 (vmarkers (mapconcat
2953 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2954 org-emphasis-alist "")))
2955 ;; make sure special characters appear at the right position in the class
2956 (if (string-match "\\^" markers)
2957 (setq markers (concat (replace-match "" t t markers) "^")))
2958 (if (string-match "-" markers)
2959 (setq markers (concat (replace-match "" t t markers) "-")))
2960 (if (string-match "\\^" vmarkers)
2961 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2962 (if (string-match "-" vmarkers)
2963 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2964 (if (> nl 0)
2965 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2966 (int-to-string nl) "\\}")))
2967 ;; Make the regexp
2968 (setq org-emph-re
2969 (concat "\\([" pre "]\\|^\\)"
2970 "\\("
2971 "\\([" markers "]\\)"
2972 "\\("
2973 "[^" border "]\\|"
2974 "[^" border "]"
2975 body1
2976 "[^" border "]"
2977 "\\)"
2978 "\\3\\)"
2979 "\\([" post "]\\|$\\)"))
2980 (setq org-verbatim-re
2981 (concat "\\([" pre "]\\|^\\)"
2982 "\\("
2983 "\\([" vmarkers "]\\)"
2984 "\\("
2985 "[^" border "]\\|"
2986 "[^" border "]"
2987 body1
2988 "[^" border "]"
2989 "\\)"
2990 "\\3\\)"
2991 "\\([" post "]\\|$\\)")))))
2993 (defcustom org-emphasis-regexp-components
2994 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
2995 "Components used to build the regular expression for emphasis.
2996 This is a list with 6 entries. Terminology: In an emphasis string
2997 like \" *strong word* \", we call the initial space PREMATCH, the final
2998 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2999 and \"trong wor\" is the body. The different components in this variable
3000 specify what is allowed/forbidden in each part:
3002 pre Chars allowed as prematch. Beginning of line will be allowed too.
3003 post Chars allowed as postmatch. End of line will be allowed too.
3004 border The chars *forbidden* as border characters.
3005 body-regexp A regexp like \".\" to match a body character. Don't use
3006 non-shy groups here, and don't allow newline here.
3007 newline The maximum number of newlines allowed in an emphasis exp.
3009 Use customize to modify this, or restart Emacs after changing it."
3010 :group 'org-font-lock
3011 :set 'org-set-emph-re
3012 :type '(list
3013 (sexp :tag "Allowed chars in pre ")
3014 (sexp :tag "Allowed chars in post ")
3015 (sexp :tag "Forbidden chars in border ")
3016 (sexp :tag "Regexp for body ")
3017 (integer :tag "number of newlines allowed")
3018 (option (boolean :tag "Please ignore this button"))))
3020 (defcustom org-emphasis-alist
3021 `(("*" bold "<b>" "</b>")
3022 ("/" italic "<i>" "</i>")
3023 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3024 ("=" org-code "<code>" "</code>" verbatim)
3025 ("~" org-verbatim "<code>" "</code>" verbatim)
3026 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3027 "<del>" "</del>")
3029 "Special syntax for emphasized text.
3030 Text starting and ending with a special character will be emphasized, for
3031 example *bold*, _underlined_ and /italic/. This variable sets the marker
3032 characters, the face to be used by font-lock for highlighting in Org-mode
3033 Emacs buffers, and the HTML tags to be used for this.
3034 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3035 Use customize to modify this, or restart Emacs after changing it."
3036 :group 'org-font-lock
3037 :set 'org-set-emph-re
3038 :type '(repeat
3039 (list
3040 (string :tag "Marker character")
3041 (choice
3042 (face :tag "Font-lock-face")
3043 (plist :tag "Face property list"))
3044 (string :tag "HTML start tag")
3045 (string :tag "HTML end tag")
3046 (option (const verbatim)))))
3048 (defvar org-protecting-blocks
3049 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3050 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3051 This is needed for font-lock setup.")
3053 ;;; Miscellaneous options
3055 (defgroup org-completion nil
3056 "Completion in Org-mode."
3057 :tag "Org Completion"
3058 :group 'org)
3060 (defcustom org-completion-use-ido nil
3061 "Non-nil means, use ido completion wherever possible.
3062 Note that `ido-mode' must be active for this variable to be relevant.
3063 If you decide to turn this variable on, you might well want to turn off
3064 `org-outline-path-complete-in-steps'.
3065 See also `org-completion-use-iswitchb'."
3066 :group 'org-completion
3067 :type 'boolean)
3069 (defcustom org-completion-use-iswitchb nil
3070 "Non-nil means, use iswitchb completion wherever possible.
3071 Note that `iswitchb-mode' must be active for this variable to be relevant.
3072 If you decide to turn this variable on, you might well want to turn off
3073 `org-outline-path-complete-in-steps'.
3074 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3075 :group 'org-completion
3076 :type 'boolean)
3078 (defcustom org-completion-fallback-command 'hippie-expand
3079 "The expansion command called by \\[org-complete] in normal context.
3080 Normal means, no org-mode-specific context."
3081 :group 'org-completion
3082 :type 'function)
3084 ;;; Functions and variables from their packages
3085 ;; Declared here to avoid compiler warnings
3087 ;; XEmacs only
3088 (defvar outline-mode-menu-heading)
3089 (defvar outline-mode-menu-show)
3090 (defvar outline-mode-menu-hide)
3091 (defvar zmacs-regions) ; XEmacs regions
3093 ;; Emacs only
3094 (defvar mark-active)
3096 ;; Various packages
3097 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3098 (declare-function calendar-forward-day "cal-move" (arg))
3099 (declare-function calendar-goto-date "cal-move" (date))
3100 (declare-function calendar-goto-today "cal-move" ())
3101 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3102 (defvar calc-embedded-close-formula)
3103 (defvar calc-embedded-open-formula)
3104 (declare-function cdlatex-tab "ext:cdlatex" ())
3105 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3106 (defvar font-lock-unfontify-region-function)
3107 (declare-function iswitchb-read-buffer "iswitchb"
3108 (prompt &optional default require-match start matches-set))
3109 (defvar iswitchb-temp-buflist)
3110 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3111 (defvar org-agenda-tags-todo-honor-ignore-options)
3112 (declare-function org-agenda-skip "org-agenda" ())
3113 (declare-function
3114 org-format-agenda-item "org-agenda"
3115 (extra txt &optional category tags dotime noprefix remove-re habitp))
3116 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3117 (declare-function org-agenda-change-all-lines "org-agenda"
3118 (newhead hdmarker &optional fixface just-this))
3119 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3120 (declare-function org-agenda-maybe-redo "org-agenda" ())
3121 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3122 (beg end))
3123 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3124 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3125 "org-agenda" (&optional end))
3126 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3127 (declare-function org-indent-mode "org-indent" (&optional arg))
3128 (declare-function parse-time-string "parse-time" (string))
3129 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3130 (defvar remember-data-file)
3131 (defvar texmathp-why)
3132 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3133 (declare-function table--at-cell-p "table" (position &optional object at-column))
3135 (defvar w3m-current-url)
3136 (defvar w3m-current-title)
3138 (defvar org-latex-regexps)
3140 ;;; Autoload and prepare some org modules
3142 ;; Some table stuff that needs to be defined here, because it is used
3143 ;; by the functions setting up org-mode or checking for table context.
3145 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3146 "Detects an org-type or table-type table.")
3147 (defconst org-table-line-regexp "^[ \t]*|"
3148 "Detects an org-type table line.")
3149 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3150 "Detects an org-type table line.")
3151 (defconst org-table-hline-regexp "^[ \t]*|-"
3152 "Detects an org-type table hline.")
3153 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3154 "Detects a table-type table hline.")
3155 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3156 "Searching from within a table (any type) this finds the first line
3157 outside the table.")
3159 ;; Autoload the functions in org-table.el that are needed by functions here.
3161 (eval-and-compile
3162 (org-autoload "org-table"
3163 '(org-table-align org-table-begin org-table-blank-field
3164 org-table-convert org-table-convert-region org-table-copy-down
3165 org-table-copy-region org-table-create
3166 org-table-create-or-convert-from-region
3167 org-table-create-with-table.el org-table-current-dline
3168 org-table-cut-region org-table-delete-column org-table-edit-field
3169 org-table-edit-formulas org-table-end org-table-eval-formula
3170 org-table-export org-table-field-info
3171 org-table-get-stored-formulas org-table-goto-column
3172 org-table-hline-and-move org-table-import org-table-insert-column
3173 org-table-insert-hline org-table-insert-row org-table-iterate
3174 org-table-justify-field-maybe org-table-kill-row
3175 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3176 org-table-move-column org-table-move-column-left
3177 org-table-move-column-right org-table-move-row
3178 org-table-move-row-down org-table-move-row-up
3179 org-table-next-field org-table-next-row org-table-paste-rectangle
3180 org-table-previous-field org-table-recalculate
3181 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3182 org-table-toggle-coordinate-overlays
3183 org-table-toggle-formula-debugger org-table-wrap-region
3184 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3186 (defun org-at-table-p (&optional table-type)
3187 "Return t if the cursor is inside an org-type table.
3188 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3189 (if org-enable-table-editor
3190 (save-excursion
3191 (beginning-of-line 1)
3192 (looking-at (if table-type org-table-any-line-regexp
3193 org-table-line-regexp)))
3194 nil))
3195 (defsubst org-table-p () (org-at-table-p))
3197 (defun org-at-table.el-p ()
3198 "Return t if and only if we are at a table.el table."
3199 (and (org-at-table-p 'any)
3200 (save-excursion
3201 (goto-char (org-table-begin 'any))
3202 (looking-at org-table1-hline-regexp))))
3203 (defun org-table-recognize-table.el ()
3204 "If there is a table.el table nearby, recognize it and move into it."
3205 (if org-table-tab-recognizes-table.el
3206 (if (org-at-table.el-p)
3207 (progn
3208 (beginning-of-line 1)
3209 (if (looking-at org-table-dataline-regexp)
3211 (if (looking-at org-table1-hline-regexp)
3212 (progn
3213 (beginning-of-line 2)
3214 (if (looking-at org-table-any-border-regexp)
3215 (beginning-of-line -1)))))
3216 (if (re-search-forward "|" (org-table-end t) t)
3217 (progn
3218 (require 'table)
3219 (if (table--at-cell-p (point))
3221 (message "recognizing table.el table...")
3222 (table-recognize-table)
3223 (message "recognizing table.el table...done")))
3224 (error "This should not happen..."))
3226 nil)
3227 nil))
3229 (defun org-at-table-hline-p ()
3230 "Return t if the cursor is inside a hline in a table."
3231 (if org-enable-table-editor
3232 (save-excursion
3233 (beginning-of-line 1)
3234 (looking-at org-table-hline-regexp))
3235 nil))
3237 (defvar org-table-clean-did-remove-column nil)
3239 (defun org-table-map-tables (function)
3240 "Apply FUNCTION to the start of all tables in the buffer."
3241 (save-excursion
3242 (save-restriction
3243 (widen)
3244 (goto-char (point-min))
3245 (while (re-search-forward org-table-any-line-regexp nil t)
3246 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3247 (beginning-of-line 1)
3248 (when (looking-at org-table-line-regexp)
3249 (save-excursion (funcall function))
3250 (or (looking-at org-table-line-regexp)
3251 (forward-char 1)))
3252 (re-search-forward org-table-any-border-regexp nil 1))))
3253 (message "Mapping tables: done"))
3255 ;; Declare and autoload functions from org-exp.el & Co
3257 (declare-function org-default-export-plist "org-exp")
3258 (declare-function org-infile-export-plist "org-exp")
3259 (declare-function org-get-current-options "org-exp")
3260 (eval-and-compile
3261 (org-autoload "org-exp"
3262 '(org-export org-export-visible
3263 org-insert-export-options-template
3264 org-table-clean-before-export))
3265 (org-autoload "org-ascii"
3266 '(org-export-as-ascii org-export-ascii-preprocess
3267 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3268 org-export-region-as-ascii))
3269 (org-autoload "org-html"
3270 '(org-export-as-html-and-open
3271 org-export-as-html-batch org-export-as-html-to-buffer
3272 org-replace-region-by-html org-export-region-as-html
3273 org-export-as-html))
3274 (org-autoload "org-icalendar"
3275 '(org-export-icalendar-this-file
3276 org-export-icalendar-all-agenda-files
3277 org-export-icalendar-combine-agenda-files))
3278 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3280 ;; Declare and autoload functions from org-agenda.el
3282 (eval-and-compile
3283 (org-autoload "org-agenda"
3284 '(org-agenda org-agenda-list org-search-view
3285 org-todo-list org-tags-view org-agenda-list-stuck-projects
3286 org-diary org-agenda-to-appt
3287 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3289 ;; Autoload org-remember
3291 (eval-and-compile
3292 (org-autoload "org-remember"
3293 '(org-remember-insinuate org-remember-annotation
3294 org-remember-apply-template org-remember org-remember-handler)))
3296 ;; Autoload org-clock.el
3299 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3300 (beg end))
3301 (declare-function org-clock-update-mode-line "org-clock" ())
3302 (declare-function org-resolve-clocks "org-clock"
3303 (&optional also-non-dangling-p prompt last-valid))
3304 (defvar org-clock-start-time)
3305 (defvar org-clock-marker (make-marker)
3306 "Marker recording the last clock-in.")
3307 (defvar org-clock-hd-marker (make-marker)
3308 "Marker recording the last clock-in, but the headline position.")
3309 (defvar org-clock-heading ""
3310 "The heading of the current clock entry.")
3311 (defun org-clock-is-active ()
3312 "Return non-nil if clock is currently running.
3313 The return value is actually the clock marker."
3314 (marker-buffer org-clock-marker))
3316 (eval-and-compile
3317 (org-autoload
3318 "org-clock"
3319 '(org-clock-in org-clock-out org-clock-cancel
3320 org-clock-goto org-clock-sum org-clock-display
3321 org-clock-remove-overlays org-clock-report
3322 org-clocktable-shift org-dblock-write:clocktable
3323 org-get-clocktable org-resolve-clocks)))
3325 (defun org-clock-update-time-maybe ()
3326 "If this is a CLOCK line, update it and return t.
3327 Otherwise, return nil."
3328 (interactive)
3329 (save-excursion
3330 (beginning-of-line 1)
3331 (skip-chars-forward " \t")
3332 (when (looking-at org-clock-string)
3333 (let ((re (concat "[ \t]*" org-clock-string
3334 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3335 "\\([ \t]*=>.*\\)?\\)?"))
3336 ts te h m s neg)
3337 (cond
3338 ((not (looking-at re))
3339 nil)
3340 ((not (match-end 2))
3341 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3342 (> org-clock-marker (point))
3343 (<= org-clock-marker (point-at-eol)))
3344 ;; The clock is running here
3345 (setq org-clock-start-time
3346 (apply 'encode-time
3347 (org-parse-time-string (match-string 1))))
3348 (org-clock-update-mode-line)))
3350 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3351 (end-of-line 1)
3352 (setq ts (match-string 1)
3353 te (match-string 3))
3354 (setq s (- (org-float-time
3355 (apply 'encode-time (org-parse-time-string te)))
3356 (org-float-time
3357 (apply 'encode-time (org-parse-time-string ts))))
3358 neg (< s 0)
3359 s (abs s)
3360 h (floor (/ s 3600))
3361 s (- s (* 3600 h))
3362 m (floor (/ s 60))
3363 s (- s (* 60 s)))
3364 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3365 t))))))
3367 (defun org-check-running-clock ()
3368 "Check if the current buffer contains the running clock.
3369 If yes, offer to stop it and to save the buffer with the changes."
3370 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3371 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3372 (buffer-name))))
3373 (org-clock-out)
3374 (when (y-or-n-p "Save changed buffer?")
3375 (save-buffer))))
3377 (defun org-clocktable-try-shift (dir n)
3378 "Check if this line starts a clock table, if yes, shift the time block."
3379 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3380 (org-clocktable-shift dir n)))
3382 ;; Autoload org-timer.el
3384 (eval-and-compile
3385 (org-autoload
3386 "org-timer"
3387 '(org-timer-start org-timer org-timer-item
3388 org-timer-change-times-in-region
3389 org-timer-set-timer
3390 org-timer-reset-timers
3391 org-timer-show-remaining-time)))
3393 ;; Autoload org-feed.el
3395 (eval-and-compile
3396 (org-autoload
3397 "org-feed"
3398 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3401 ;; Autoload org-indent.el
3403 ;; Define the variable already here, to make sure we have it.
3404 (defvar org-indent-mode nil
3405 "Non-nil if Org-Indent mode is enabled.
3406 Use the command `org-indent-mode' to change this variable.")
3408 (eval-and-compile
3409 (org-autoload
3410 "org-indent"
3411 '(org-indent-mode)))
3413 ;; Autoload org-mobile.el
3415 (eval-and-compile
3416 (org-autoload
3417 "org-mobile"
3418 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3420 ;; Autoload archiving code
3421 ;; The stuff that is needed for cycling and tags has to be defined here.
3423 (defgroup org-archive nil
3424 "Options concerning archiving in Org-mode."
3425 :tag "Org Archive"
3426 :group 'org-structure)
3428 (defcustom org-archive-location "%s_archive::"
3429 "The location where subtrees should be archived.
3431 The value of this variable is a string, consisting of two parts,
3432 separated by a double-colon. The first part is a filename and
3433 the second part is a headline.
3435 When the filename is omitted, archiving happens in the same file.
3436 %s in the filename will be replaced by the current file
3437 name (without the directory part). Archiving to a different file
3438 is useful to keep archived entries from contributing to the
3439 Org-mode Agenda.
3441 The archived entries will be filed as subtrees of the specified
3442 headline. When the headline is omitted, the subtrees are simply
3443 filed away at the end of the file, as top-level entries. Also in
3444 the heading you can use %s to represent the file name, this can be
3445 useful when using the same archive for a number of different files.
3447 Here are a few examples:
3448 \"%s_archive::\"
3449 If the current file is Projects.org, archive in file
3450 Projects.org_archive, as top-level trees. This is the default.
3452 \"::* Archived Tasks\"
3453 Archive in the current file, under the top-level headline
3454 \"* Archived Tasks\".
3456 \"~/org/archive.org::\"
3457 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3459 \"~/org/archive.org::From %s\"
3460 Archive in file ~/org/archive.org (absolute path), under headlines
3461 \"From FILENAME\" where file name is the current file name.
3463 \"basement::** Finished Tasks\"
3464 Archive in file ./basement (relative path), as level 3 trees
3465 below the level 2 heading \"** Finished Tasks\".
3467 You may set this option on a per-file basis by adding to the buffer a
3468 line like
3470 #+ARCHIVE: basement::** Finished Tasks
3472 You may also define it locally for a subtree by setting an ARCHIVE property
3473 in the entry. If such a property is found in an entry, or anywhere up
3474 the hierarchy, it will be used."
3475 :group 'org-archive
3476 :type 'string)
3478 (defcustom org-archive-tag "ARCHIVE"
3479 "The tag that marks a subtree as archived.
3480 An archived subtree does not open during visibility cycling, and does
3481 not contribute to the agenda listings.
3482 After changing this, font-lock must be restarted in the relevant buffers to
3483 get the proper fontification."
3484 :group 'org-archive
3485 :group 'org-keywords
3486 :type 'string)
3488 (defcustom org-agenda-skip-archived-trees t
3489 "Non-nil means, the agenda will skip any items located in archived trees.
3490 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3491 variable is no longer recommended, you should leave it at the value t.
3492 Instead, use the key `v' to cycle the archives-mode in the agenda."
3493 :group 'org-archive
3494 :group 'org-agenda-skip
3495 :type 'boolean)
3497 (defcustom org-columns-skip-archived-trees t
3498 "Non-nil means, ignore archived trees when creating column view."
3499 :group 'org-archive
3500 :group 'org-properties
3501 :type 'boolean)
3503 (defcustom org-cycle-open-archived-trees nil
3504 "Non-nil means, `org-cycle' will open archived trees.
3505 An archived tree is a tree marked with the tag ARCHIVE.
3506 When nil, archived trees will stay folded. You can still open them with
3507 normal outline commands like `show-all', but not with the cycling commands."
3508 :group 'org-archive
3509 :group 'org-cycle
3510 :type 'boolean)
3512 (defcustom org-sparse-tree-open-archived-trees nil
3513 "Non-nil means sparse tree construction shows matches in archived trees.
3514 When nil, matches in these trees are highlighted, but the trees are kept in
3515 collapsed state."
3516 :group 'org-archive
3517 :group 'org-sparse-trees
3518 :type 'boolean)
3520 (defun org-cycle-hide-archived-subtrees (state)
3521 "Re-hide all archived subtrees after a visibility state change."
3522 (when (and (not org-cycle-open-archived-trees)
3523 (not (memq state '(overview folded))))
3524 (save-excursion
3525 (let* ((globalp (memq state '(contents all)))
3526 (beg (if globalp (point-min) (point)))
3527 (end (if globalp (point-max) (org-end-of-subtree t))))
3528 (org-hide-archived-subtrees beg end)
3529 (goto-char beg)
3530 (if (looking-at (concat ".*:" org-archive-tag ":"))
3531 (message "%s" (substitute-command-keys
3532 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3534 (defun org-force-cycle-archived ()
3535 "Cycle subtree even if it is archived."
3536 (interactive)
3537 (setq this-command 'org-cycle)
3538 (let ((org-cycle-open-archived-trees t))
3539 (call-interactively 'org-cycle)))
3541 (defun org-hide-archived-subtrees (beg end)
3542 "Re-hide all archived subtrees after a visibility state change."
3543 (save-excursion
3544 (let* ((re (concat ":" org-archive-tag ":")))
3545 (goto-char beg)
3546 (while (re-search-forward re end t)
3547 (and (org-on-heading-p) (org-flag-subtree t))
3548 (org-end-of-subtree t)))))
3550 (defun org-flag-subtree (flag)
3551 (save-excursion
3552 (org-back-to-heading t)
3553 (outline-end-of-heading)
3554 (outline-flag-region (point)
3555 (progn (org-end-of-subtree t) (point))
3556 flag)))
3558 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3560 (eval-and-compile
3561 (org-autoload "org-archive"
3562 '(org-add-archive-files org-archive-subtree
3563 org-archive-to-archive-sibling org-toggle-archive-tag
3564 org-archive-subtree-default
3565 org-archive-subtree-default-with-confirmation)))
3567 ;; Autoload Column View Code
3569 (declare-function org-columns-number-to-string "org-colview")
3570 (declare-function org-columns-get-format-and-top-level "org-colview")
3571 (declare-function org-columns-compute "org-colview")
3573 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3574 '(org-columns-number-to-string org-columns-get-format-and-top-level
3575 org-columns-compute org-agenda-columns org-columns-remove-overlays
3576 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3578 ;; Autoload ID code
3580 (declare-function org-id-store-link "org-id")
3581 (declare-function org-id-locations-load "org-id")
3582 (declare-function org-id-locations-save "org-id")
3583 (defvar org-id-track-globally)
3584 (org-autoload "org-id"
3585 '(org-id-get-create org-id-new org-id-copy org-id-get
3586 org-id-get-with-outline-path-completion
3587 org-id-get-with-outline-drilling
3588 org-id-goto org-id-find org-id-store-link))
3590 ;; Autoload Plotting Code
3592 (org-autoload "org-plot"
3593 '(org-plot/gnuplot))
3595 ;;; Variables for pre-computed regular expressions, all buffer local
3597 (defvar org-drawer-regexp nil
3598 "Matches first line of a hidden block.")
3599 (make-variable-buffer-local 'org-drawer-regexp)
3600 (defvar org-todo-regexp nil
3601 "Matches any of the TODO state keywords.")
3602 (make-variable-buffer-local 'org-todo-regexp)
3603 (defvar org-not-done-regexp nil
3604 "Matches any of the TODO state keywords except the last one.")
3605 (make-variable-buffer-local 'org-not-done-regexp)
3606 (defvar org-not-done-heading-regexp nil
3607 "Matches a TODO headline that is not done.")
3608 (make-variable-buffer-local 'org-not-done-regexp)
3609 (defvar org-todo-line-regexp nil
3610 "Matches a headline and puts TODO state into group 2 if present.")
3611 (make-variable-buffer-local 'org-todo-line-regexp)
3612 (defvar org-complex-heading-regexp nil
3613 "Matches a headline and puts everything into groups:
3614 group 1: the stars
3615 group 2: The todo keyword, maybe
3616 group 3: Priority cookie
3617 group 4: True headline
3618 group 5: Tags")
3619 (make-variable-buffer-local 'org-complex-heading-regexp)
3620 (defvar org-complex-heading-regexp-format nil)
3621 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3622 (defvar org-todo-line-tags-regexp nil
3623 "Matches a headline and puts TODO state into group 2 if present.
3624 Also put tags into group 4 if tags are present.")
3625 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3626 (defvar org-nl-done-regexp nil
3627 "Matches newline followed by a headline with the DONE keyword.")
3628 (make-variable-buffer-local 'org-nl-done-regexp)
3629 (defvar org-looking-at-done-regexp nil
3630 "Matches the DONE keyword a point.")
3631 (make-variable-buffer-local 'org-looking-at-done-regexp)
3632 (defvar org-ds-keyword-length 12
3633 "Maximum length of the Deadline and SCHEDULED keywords.")
3634 (make-variable-buffer-local 'org-ds-keyword-length)
3635 (defvar org-deadline-regexp nil
3636 "Matches the DEADLINE keyword.")
3637 (make-variable-buffer-local 'org-deadline-regexp)
3638 (defvar org-deadline-time-regexp nil
3639 "Matches the DEADLINE keyword together with a time stamp.")
3640 (make-variable-buffer-local 'org-deadline-time-regexp)
3641 (defvar org-deadline-line-regexp nil
3642 "Matches the DEADLINE keyword and the rest of the line.")
3643 (make-variable-buffer-local 'org-deadline-line-regexp)
3644 (defvar org-scheduled-regexp nil
3645 "Matches the SCHEDULED keyword.")
3646 (make-variable-buffer-local 'org-scheduled-regexp)
3647 (defvar org-scheduled-time-regexp nil
3648 "Matches the SCHEDULED keyword together with a time stamp.")
3649 (make-variable-buffer-local 'org-scheduled-time-regexp)
3650 (defvar org-closed-time-regexp nil
3651 "Matches the CLOSED keyword together with a time stamp.")
3652 (make-variable-buffer-local 'org-closed-time-regexp)
3654 (defvar org-keyword-time-regexp nil
3655 "Matches any of the 4 keywords, together with the time stamp.")
3656 (make-variable-buffer-local 'org-keyword-time-regexp)
3657 (defvar org-keyword-time-not-clock-regexp nil
3658 "Matches any of the 3 keywords, together with the time stamp.")
3659 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3660 (defvar org-maybe-keyword-time-regexp nil
3661 "Matches a timestamp, possibly preceeded by a keyword.")
3662 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3663 (defvar org-planning-or-clock-line-re nil
3664 "Matches a line with planning or clock info.")
3665 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3667 (defconst org-plain-time-of-day-regexp
3668 (concat
3669 "\\(\\<[012]?[0-9]"
3670 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3671 "\\(--?"
3672 "\\(\\<[012]?[0-9]"
3673 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3674 "\\)?")
3675 "Regular expression to match a plain time or time range.
3676 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3677 groups carry important information:
3678 0 the full match
3679 1 the first time, range or not
3680 8 the second time, if it is a range.")
3682 (defconst org-plain-time-extension-regexp
3683 (concat
3684 "\\(\\<[012]?[0-9]"
3685 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3686 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3687 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3688 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3689 groups carry important information:
3690 0 the full match
3691 7 hours of duration
3692 9 minutes of duration")
3694 (defconst org-stamp-time-of-day-regexp
3695 (concat
3696 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3697 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3698 "\\(--?"
3699 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3700 "Regular expression to match a timestamp time or time range.
3701 After a match, the following groups carry important information:
3702 0 the full match
3703 1 date plus weekday, for back referencing to make sure both times are on the same day
3704 2 the first time, range or not
3705 4 the second time, if it is a range.")
3707 (defconst org-startup-options
3708 '(("fold" org-startup-folded t)
3709 ("overview" org-startup-folded t)
3710 ("nofold" org-startup-folded nil)
3711 ("showall" org-startup-folded nil)
3712 ("showeverything" org-startup-folded showeverything)
3713 ("content" org-startup-folded content)
3714 ("indent" org-startup-indented t)
3715 ("noindent" org-startup-indented nil)
3716 ("hidestars" org-hide-leading-stars t)
3717 ("showstars" org-hide-leading-stars nil)
3718 ("odd" org-odd-levels-only t)
3719 ("oddeven" org-odd-levels-only nil)
3720 ("align" org-startup-align-all-tables t)
3721 ("noalign" org-startup-align-all-tables nil)
3722 ("customtime" org-display-custom-times t)
3723 ("logdone" org-log-done time)
3724 ("lognotedone" org-log-done note)
3725 ("nologdone" org-log-done nil)
3726 ("lognoteclock-out" org-log-note-clock-out t)
3727 ("nolognoteclock-out" org-log-note-clock-out nil)
3728 ("logrepeat" org-log-repeat state)
3729 ("lognoterepeat" org-log-repeat note)
3730 ("nologrepeat" org-log-repeat nil)
3731 ("logreschedule" org-log-reschedule time)
3732 ("lognotereschedule" org-log-reschedule note)
3733 ("nologreschedule" org-log-reschedule nil)
3734 ("logredeadline" org-log-redeadline time)
3735 ("lognoteredeadline" org-log-redeadline note)
3736 ("nologredeadline" org-log-redeadline nil)
3737 ("fninline" org-footnote-define-inline t)
3738 ("nofninline" org-footnote-define-inline nil)
3739 ("fnlocal" org-footnote-section nil)
3740 ("fnauto" org-footnote-auto-label t)
3741 ("fnprompt" org-footnote-auto-label nil)
3742 ("fnconfirm" org-footnote-auto-label confirm)
3743 ("fnplain" org-footnote-auto-label plain)
3744 ("fnadjust" org-footnote-auto-adjust t)
3745 ("nofnadjust" org-footnote-auto-adjust nil)
3746 ("constcgs" constants-unit-system cgs)
3747 ("constSI" constants-unit-system SI)
3748 ("noptag" org-tag-persistent-alist nil)
3749 ("hideblocks" org-hide-block-startup t)
3750 ("nohideblocks" org-hide-block-startup nil))
3751 "Variable associated with STARTUP options for org-mode.
3752 Each element is a list of three items: The startup options as written
3753 in the #+STARTUP line, the corresponding variable, and the value to
3754 set this variable to if the option is found. An optional forth element PUSH
3755 means to push this value onto the list in the variable.")
3757 (defun org-set-regexps-and-options ()
3758 "Precompute regular expressions for current buffer."
3759 (when (org-mode-p)
3760 (org-set-local 'org-todo-kwd-alist nil)
3761 (org-set-local 'org-todo-key-alist nil)
3762 (org-set-local 'org-todo-key-trigger nil)
3763 (org-set-local 'org-todo-keywords-1 nil)
3764 (org-set-local 'org-done-keywords nil)
3765 (org-set-local 'org-todo-heads nil)
3766 (org-set-local 'org-todo-sets nil)
3767 (org-set-local 'org-todo-log-states nil)
3768 (org-set-local 'org-file-properties nil)
3769 (org-set-local 'org-file-tags nil)
3770 (let ((re (org-make-options-regexp
3771 '("CATEGORY" "TODO" "COLUMNS"
3772 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3773 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3774 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3775 (splitre "[ \t]+")
3776 kwds kws0 kwsa key log value cat arch tags const links hw dws
3777 tail sep kws1 prio props ftags drawers
3778 ext-setup-or-nil setup-contents (start 0))
3779 (save-excursion
3780 (save-restriction
3781 (widen)
3782 (goto-char (point-min))
3783 (while (or (and ext-setup-or-nil
3784 (string-match re ext-setup-or-nil start)
3785 (setq start (match-end 0)))
3786 (and (setq ext-setup-or-nil nil start 0)
3787 (re-search-forward re nil t)))
3788 (setq key (upcase (match-string 1 ext-setup-or-nil))
3789 value (org-match-string-no-properties 2 ext-setup-or-nil))
3790 (cond
3791 ((equal key "CATEGORY")
3792 (if (string-match "[ \t]+$" value)
3793 (setq value (replace-match "" t t value)))
3794 (setq cat value))
3795 ((member key '("SEQ_TODO" "TODO"))
3796 (push (cons 'sequence (org-split-string value splitre)) kwds))
3797 ((equal key "TYP_TODO")
3798 (push (cons 'type (org-split-string value splitre)) kwds))
3799 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3800 ;; general TODO-like setup
3801 (push (cons (intern (downcase (match-string 1 key)))
3802 (org-split-string value splitre)) kwds))
3803 ((equal key "TAGS")
3804 (setq tags (append tags (if tags '("\\n") nil)
3805 (org-split-string value splitre))))
3806 ((equal key "COLUMNS")
3807 (org-set-local 'org-columns-default-format value))
3808 ((equal key "LINK")
3809 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3810 (push (cons (match-string 1 value)
3811 (org-trim (match-string 2 value)))
3812 links)))
3813 ((equal key "PRIORITIES")
3814 (setq prio (org-split-string value " +")))
3815 ((equal key "PROPERTY")
3816 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3817 (push (cons (match-string 1 value) (match-string 2 value))
3818 props)))
3819 ((equal key "FILETAGS")
3820 (when (string-match "\\S-" value)
3821 (setq ftags
3822 (append
3823 ftags
3824 (apply 'append
3825 (mapcar (lambda (x) (org-split-string x ":"))
3826 (org-split-string value)))))))
3827 ((equal key "DRAWERS")
3828 (setq drawers (org-split-string value splitre)))
3829 ((equal key "CONSTANTS")
3830 (setq const (append const (org-split-string value splitre))))
3831 ((equal key "STARTUP")
3832 (let ((opts (org-split-string value splitre))
3833 l var val)
3834 (while (setq l (pop opts))
3835 (when (setq l (assoc l org-startup-options))
3836 (setq var (nth 1 l) val (nth 2 l))
3837 (if (not (nth 3 l))
3838 (set (make-local-variable var) val)
3839 (if (not (listp (symbol-value var)))
3840 (set (make-local-variable var) nil))
3841 (set (make-local-variable var) (symbol-value var))
3842 (add-to-list var val))))))
3843 ((equal key "ARCHIVE")
3844 (string-match " *$" value)
3845 (setq arch (replace-match "" t t value))
3846 (remove-text-properties 0 (length arch)
3847 '(face t fontified t) arch))
3848 ((equal key "SETUPFILE")
3849 (setq setup-contents (org-file-contents
3850 (expand-file-name
3851 (org-remove-double-quotes value))
3852 'noerror))
3853 (if (not ext-setup-or-nil)
3854 (setq ext-setup-or-nil setup-contents start 0)
3855 (setq ext-setup-or-nil
3856 (concat (substring ext-setup-or-nil 0 start)
3857 "\n" setup-contents "\n"
3858 (substring ext-setup-or-nil start)))))
3859 ))))
3860 (when cat
3861 (org-set-local 'org-category (intern cat))
3862 (push (cons "CATEGORY" cat) props))
3863 (when prio
3864 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3865 (setq prio (mapcar 'string-to-char prio))
3866 (org-set-local 'org-highest-priority (nth 0 prio))
3867 (org-set-local 'org-lowest-priority (nth 1 prio))
3868 (org-set-local 'org-default-priority (nth 2 prio)))
3869 (and props (org-set-local 'org-file-properties (nreverse props)))
3870 (and ftags (org-set-local 'org-file-tags
3871 (mapcar 'org-add-prop-inherited ftags)))
3872 (and drawers (org-set-local 'org-drawers drawers))
3873 (and arch (org-set-local 'org-archive-location arch))
3874 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3875 ;; Process the TODO keywords
3876 (unless kwds
3877 ;; Use the global values as if they had been given locally.
3878 (setq kwds (default-value 'org-todo-keywords))
3879 (if (stringp (car kwds))
3880 (setq kwds (list (cons org-todo-interpretation
3881 (default-value 'org-todo-keywords)))))
3882 (setq kwds (reverse kwds)))
3883 (setq kwds (nreverse kwds))
3884 (let (inter kws kw)
3885 (while (setq kws (pop kwds))
3886 (let ((kws (or
3887 (run-hook-with-args-until-success
3888 'org-todo-setup-filter-hook kws)
3889 kws)))
3890 (setq inter (pop kws) sep (member "|" kws)
3891 kws0 (delete "|" (copy-sequence kws))
3892 kwsa nil
3893 kws1 (mapcar
3894 (lambda (x)
3895 ;; 1 2
3896 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3897 (progn
3898 (setq kw (match-string 1 x)
3899 key (and (match-end 2) (match-string 2 x))
3900 log (org-extract-log-state-settings x))
3901 (push (cons kw (and key (string-to-char key))) kwsa)
3902 (and log (push log org-todo-log-states))
3904 (error "Invalid TODO keyword %s" x)))
3905 kws0)
3906 kwsa (if kwsa (append '((:startgroup))
3907 (nreverse kwsa)
3908 '((:endgroup))))
3909 hw (car kws1)
3910 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3911 tail (list inter hw (car dws) (org-last dws))))
3912 (add-to-list 'org-todo-heads hw 'append)
3913 (push kws1 org-todo-sets)
3914 (setq org-done-keywords (append org-done-keywords dws nil))
3915 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3916 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3917 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3918 (setq org-todo-sets (nreverse org-todo-sets)
3919 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3920 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3921 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3922 ;; Process the constants
3923 (when const
3924 (let (e cst)
3925 (while (setq e (pop const))
3926 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3927 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3928 (setq org-table-formula-constants-local cst)))
3930 ;; Process the tags.
3931 (when tags
3932 (let (e tgs)
3933 (while (setq e (pop tags))
3934 (cond
3935 ((equal e "{") (push '(:startgroup) tgs))
3936 ((equal e "}") (push '(:endgroup) tgs))
3937 ((equal e "\\n") (push '(:newline) tgs))
3938 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3939 (push (cons (match-string 1 e)
3940 (string-to-char (match-string 2 e)))
3941 tgs))
3942 (t (push (list e) tgs))))
3943 (org-set-local 'org-tag-alist nil)
3944 (while (setq e (pop tgs))
3945 (or (and (stringp (car e))
3946 (assoc (car e) org-tag-alist))
3947 (push e org-tag-alist)))))
3949 ;; Compute the regular expressions and other local variables
3950 (if (not org-done-keywords)
3951 (setq org-done-keywords (and org-todo-keywords-1
3952 (list (org-last org-todo-keywords-1)))))
3953 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3954 (length org-scheduled-string)
3955 (length org-clock-string)
3956 (length org-closed-string)))
3957 org-drawer-regexp
3958 (concat "^[ \t]*:\\("
3959 (mapconcat 'regexp-quote org-drawers "\\|")
3960 "\\):[ \t]*$")
3961 org-not-done-keywords
3962 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3963 org-todo-regexp
3964 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3965 "\\|") "\\)\\>")
3966 org-not-done-regexp
3967 (concat "\\<\\("
3968 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3969 "\\)\\>")
3970 org-not-done-heading-regexp
3971 (concat "^\\(\\*+\\)[ \t]+\\("
3972 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3973 "\\)\\>")
3974 org-todo-line-regexp
3975 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3976 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3977 "\\)\\>\\)?[ \t]*\\(.*\\)")
3978 org-complex-heading-regexp
3979 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3980 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3981 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3982 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3983 org-complex-heading-regexp-format
3984 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3985 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3986 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
3987 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3988 org-nl-done-regexp
3989 (concat "\n\\*+[ \t]+"
3990 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3991 "\\)" "\\>")
3992 org-todo-line-tags-regexp
3993 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3994 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3995 (org-re
3996 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3997 org-looking-at-done-regexp
3998 (concat "^" "\\(?:"
3999 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4000 "\\>")
4001 org-deadline-regexp (concat "\\<" org-deadline-string)
4002 org-deadline-time-regexp
4003 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4004 org-deadline-line-regexp
4005 (concat "\\<\\(" org-deadline-string "\\).*")
4006 org-scheduled-regexp
4007 (concat "\\<" org-scheduled-string)
4008 org-scheduled-time-regexp
4009 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4010 org-closed-time-regexp
4011 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4012 org-keyword-time-regexp
4013 (concat "\\<\\(" org-scheduled-string
4014 "\\|" org-deadline-string
4015 "\\|" org-closed-string
4016 "\\|" org-clock-string "\\)"
4017 " *[[<]\\([^]>]+\\)[]>]")
4018 org-keyword-time-not-clock-regexp
4019 (concat "\\<\\(" org-scheduled-string
4020 "\\|" org-deadline-string
4021 "\\|" org-closed-string
4022 "\\)"
4023 " *[[<]\\([^]>]+\\)[]>]")
4024 org-maybe-keyword-time-regexp
4025 (concat "\\(\\<\\(" org-scheduled-string
4026 "\\|" org-deadline-string
4027 "\\|" org-closed-string
4028 "\\|" org-clock-string "\\)\\)?"
4029 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4030 org-planning-or-clock-line-re
4031 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4032 "\\|" org-deadline-string
4033 "\\|" org-closed-string "\\|" org-clock-string
4034 "\\)\\>\\)")
4036 (org-compute-latex-and-specials-regexp)
4037 (org-set-font-lock-defaults))))
4039 (defun org-file-contents (file &optional noerror)
4040 "Return the contents of FILE, as a string."
4041 (if (or (not file)
4042 (not (file-readable-p file)))
4043 (if noerror
4044 (progn
4045 (message "Cannot read file %s" file)
4046 (ding) (sit-for 2)
4048 (error "Cannot read file %s" file))
4049 (with-temp-buffer
4050 (insert-file-contents file)
4051 (buffer-string))))
4053 (defun org-extract-log-state-settings (x)
4054 "Extract the log state setting from a TODO keyword string.
4055 This will extract info from a string like \"WAIT(w@/!)\"."
4056 (let (kw key log1 log2)
4057 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4058 (setq kw (match-string 1 x)
4059 key (and (match-end 2) (match-string 2 x))
4060 log1 (and (match-end 3) (match-string 3 x))
4061 log2 (and (match-end 4) (match-string 4 x)))
4062 (and (or log1 log2)
4063 (list kw
4064 (and log1 (if (equal log1 "!") 'time 'note))
4065 (and log2 (if (equal log2 "!") 'time 'note)))))))
4067 (defun org-remove-keyword-keys (list)
4068 "Remove a pair of parenthesis at the end of each string in LIST."
4069 (mapcar (lambda (x)
4070 (if (string-match "(.*)$" x)
4071 (substring x 0 (match-beginning 0))
4073 list))
4075 ;; FIXME: this could be done much better, using second characters etc.
4076 (defun org-assign-fast-keys (alist)
4077 "Assign fast keys to a keyword-key alist.
4078 Respect keys that are already there."
4079 (let (new e k c c1 c2 (char ?a))
4080 (while (setq e (pop alist))
4081 (cond
4082 ((equal e '(:startgroup)) (push e new))
4083 ((equal e '(:endgroup)) (push e new))
4084 ((equal e '(:newline)) (push e new))
4086 (setq k (car e) c2 nil)
4087 (if (cdr e)
4088 (setq c (cdr e))
4089 ;; automatically assign a character.
4090 (setq c1 (string-to-char
4091 (downcase (substring
4092 k (if (= (string-to-char k) ?@) 1 0)))))
4093 (if (or (rassoc c1 new) (rassoc c1 alist))
4094 (while (or (rassoc char new) (rassoc char alist))
4095 (setq char (1+ char)))
4096 (setq c2 c1))
4097 (setq c (or c2 char)))
4098 (push (cons k c) new))))
4099 (nreverse new)))
4101 ;;; Some variables used in various places
4103 (defvar org-window-configuration nil
4104 "Used in various places to store a window configuration.")
4105 (defvar org-selected-window nil
4106 "Used in various places to store a window configuration.")
4107 (defvar org-finish-function nil
4108 "Function to be called when `C-c C-c' is used.
4109 This is for getting out of special buffers like remember.")
4112 ;; FIXME: Occasionally check by commenting these, to make sure
4113 ;; no other functions uses these, forgetting to let-bind them.
4114 (defvar entry)
4115 (defvar last-state)
4116 (defvar date)
4118 ;; Defined somewhere in this file, but used before definition.
4119 (defvar org-html-entities)
4120 (defvar org-struct-menu)
4121 (defvar org-org-menu)
4122 (defvar org-tbl-menu)
4124 ;;;; Define the Org-mode
4126 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4127 (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."))
4130 ;; We use a before-change function to check if a table might need
4131 ;; an update.
4132 (defvar org-table-may-need-update t
4133 "Indicates that a table might need an update.
4134 This variable is set by `org-before-change-function'.
4135 `org-table-align' sets it back to nil.")
4136 (defun org-before-change-function (beg end)
4137 "Every change indicates that a table might need an update."
4138 (setq org-table-may-need-update t))
4139 (defvar org-mode-map)
4140 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4141 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4142 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4143 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4144 (defvar org-table-buffer-is-an nil)
4145 (defconst org-outline-regexp "\\*+ ")
4147 ;;;###autoload
4148 (define-derived-mode org-mode outline-mode "Org"
4149 "Outline-based notes management and organizer, alias
4150 \"Carsten's outline-mode for keeping track of everything.\"
4152 Org-mode develops organizational tasks around a NOTES file which
4153 contains information about projects as plain text. Org-mode is
4154 implemented on top of outline-mode, which is ideal to keep the content
4155 of large files well structured. It supports ToDo items, deadlines and
4156 time stamps, which magically appear in the diary listing of the Emacs
4157 calendar. Tables are easily created with a built-in table editor.
4158 Plain text URL-like links connect to websites, emails (VM), Usenet
4159 messages (Gnus), BBDB entries, and any files related to the project.
4160 For printing and sharing of notes, an Org-mode file (or a part of it)
4161 can be exported as a structured ASCII or HTML file.
4163 The following commands are available:
4165 \\{org-mode-map}"
4167 ;; Get rid of Outline menus, they are not needed
4168 ;; Need to do this here because define-derived-mode sets up
4169 ;; the keymap so late. Still, it is a waste to call this each time
4170 ;; we switch another buffer into org-mode.
4171 (if (featurep 'xemacs)
4172 (when (boundp 'outline-mode-menu-heading)
4173 ;; Assume this is Greg's port, it used easymenu
4174 (easy-menu-remove outline-mode-menu-heading)
4175 (easy-menu-remove outline-mode-menu-show)
4176 (easy-menu-remove outline-mode-menu-hide))
4177 (define-key org-mode-map [menu-bar headings] 'undefined)
4178 (define-key org-mode-map [menu-bar hide] 'undefined)
4179 (define-key org-mode-map [menu-bar show] 'undefined))
4181 (org-load-modules-maybe)
4182 (easy-menu-add org-org-menu)
4183 (easy-menu-add org-tbl-menu)
4184 (org-install-agenda-files-menu)
4185 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4186 (org-add-to-invisibility-spec '(org-cwidth))
4187 (org-add-to-invisibility-spec '(org-hide-block . t))
4188 (when (featurep 'xemacs)
4189 (org-set-local 'line-move-ignore-invisible t))
4190 (org-set-local 'outline-regexp org-outline-regexp)
4191 (org-set-local 'outline-level 'org-outline-level)
4192 (when (and org-ellipsis
4193 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4194 (fboundp 'make-glyph-code))
4195 (unless org-display-table
4196 (setq org-display-table (make-display-table)))
4197 (set-display-table-slot
4198 org-display-table 4
4199 (vconcat (mapcar
4200 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4201 org-ellipsis)))
4202 (if (stringp org-ellipsis) org-ellipsis "..."))))
4203 (setq buffer-display-table org-display-table))
4204 (org-set-regexps-and-options)
4205 (when (and org-tag-faces (not org-tags-special-faces-re))
4206 ;; tag faces set outside customize.... force initialization.
4207 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4208 ;; Calc embedded
4209 (org-set-local 'calc-embedded-open-mode "# ")
4210 (modify-syntax-entry ?# "<")
4211 (modify-syntax-entry ?@ "w")
4212 (if org-startup-truncated (setq truncate-lines t))
4213 (org-set-local 'font-lock-unfontify-region-function
4214 'org-unfontify-region)
4215 ;; Activate before-change-function
4216 (org-set-local 'org-table-may-need-update t)
4217 (org-add-hook 'before-change-functions 'org-before-change-function nil
4218 'local)
4219 ;; Check for running clock before killing a buffer
4220 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4221 ;; Paragraphs and auto-filling
4222 (org-set-autofill-regexps)
4223 (setq indent-line-function 'org-indent-line-function)
4224 (org-update-radio-target-regexp)
4225 ;; Make sure dependence stuff works reliably, even for users who set it
4226 ;; too late :-(
4227 (if org-enforce-todo-dependencies
4228 (add-hook 'org-blocker-hook
4229 'org-block-todo-from-children-or-siblings-or-parent)
4230 (remove-hook 'org-blocker-hook
4231 'org-block-todo-from-children-or-siblings-or-parent))
4232 (if org-enforce-todo-checkbox-dependencies
4233 (add-hook 'org-blocker-hook
4234 'org-block-todo-from-checkboxes)
4235 (remove-hook 'org-blocker-hook
4236 'org-block-todo-from-checkboxes))
4238 ;; Comment characters
4239 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4240 (org-set-local 'comment-padding " ")
4242 ;; Align options lines
4243 (org-set-local
4244 'align-mode-rules-list
4245 '((org-in-buffer-settings
4246 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4247 (modes . '(org-mode)))))
4249 ;; Imenu
4250 (org-set-local 'imenu-create-index-function
4251 'org-imenu-get-tree)
4253 ;; Make isearch reveal context
4254 (if (or (featurep 'xemacs)
4255 (not (boundp 'outline-isearch-open-invisible-function)))
4256 ;; Emacs 21 and XEmacs make use of the hook
4257 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4258 ;; Emacs 22 deals with this through a special variable
4259 (org-set-local 'outline-isearch-open-invisible-function
4260 (lambda (&rest ignore) (org-show-context 'isearch))))
4262 ;; If empty file that did not turn on org-mode automatically, make it to.
4263 (if (and org-insert-mode-line-in-empty-file
4264 (interactive-p)
4265 (= (point-min) (point-max)))
4266 (insert "# -*- mode: org -*-\n\n"))
4268 (unless org-inhibit-startup
4269 (when org-startup-align-all-tables
4270 (let ((bmp (buffer-modified-p)))
4271 (org-table-map-tables 'org-table-align)
4272 (set-buffer-modified-p bmp)))
4273 (when org-startup-indented
4274 (require 'org-indent)
4275 (org-indent-mode 1))
4276 (org-set-startup-visibility)))
4278 (when (fboundp 'abbrev-table-put)
4279 (abbrev-table-put org-mode-abbrev-table
4280 :parents (list text-mode-abbrev-table)))
4282 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4284 (defun org-current-time ()
4285 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4286 (if (> (car org-time-stamp-rounding-minutes) 1)
4287 (let ((r (car org-time-stamp-rounding-minutes))
4288 (time (decode-time)))
4289 (apply 'encode-time
4290 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4291 (nthcdr 2 time))))
4292 (current-time)))
4294 ;;;; Font-Lock stuff, including the activators
4296 (defvar org-mouse-map (make-sparse-keymap))
4297 (org-defkey org-mouse-map
4298 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4299 (org-defkey org-mouse-map
4300 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4301 (when org-mouse-1-follows-link
4302 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4303 (when org-tab-follows-link
4304 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4305 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4307 (require 'font-lock)
4309 (defconst org-non-link-chars "]\t\n\r<>")
4310 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4311 "shell" "elisp"))
4312 (defvar org-link-types-re nil
4313 "Matches a link that has a url-like prefix like \"http:\"")
4314 (defvar org-link-re-with-space nil
4315 "Matches a link with spaces, optional angular brackets around it.")
4316 (defvar org-link-re-with-space2 nil
4317 "Matches a link with spaces, optional angular brackets around it.")
4318 (defvar org-link-re-with-space3 nil
4319 "Matches a link with spaces, only for internal part in bracket links.")
4320 (defvar org-angle-link-re nil
4321 "Matches link with angular brackets, spaces are allowed.")
4322 (defvar org-plain-link-re nil
4323 "Matches plain link, without spaces.")
4324 (defvar org-bracket-link-regexp nil
4325 "Matches a link in double brackets.")
4326 (defvar org-bracket-link-analytic-regexp nil
4327 "Regular expression used to analyze links.
4328 Here is what the match groups contain after a match:
4329 1: http:
4330 2: http
4331 3: path
4332 4: [desc]
4333 5: desc")
4334 (defvar org-bracket-link-analytic-regexp++ nil
4335 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4336 (defvar org-any-link-re nil
4337 "Regular expression matching any link.")
4339 (defun org-make-link-regexps ()
4340 "Update the link regular expressions.
4341 This should be called after the variable `org-link-types' has changed."
4342 (setq org-link-types-re
4343 (concat
4344 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4345 org-link-re-with-space
4346 (concat
4347 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4348 "\\([^" org-non-link-chars " ]"
4349 "[^" org-non-link-chars "]*"
4350 "[^" org-non-link-chars " ]\\)>?")
4351 org-link-re-with-space2
4352 (concat
4353 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4354 "\\([^" org-non-link-chars " ]"
4355 "[^\t\n\r]*"
4356 "[^" org-non-link-chars " ]\\)>?")
4357 org-link-re-with-space3
4358 (concat
4359 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4360 "\\([^" org-non-link-chars " ]"
4361 "[^\t\n\r]*\\)")
4362 org-angle-link-re
4363 (concat
4364 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4365 "\\([^" org-non-link-chars " ]"
4366 "[^" org-non-link-chars "]*"
4367 "\\)>")
4368 org-plain-link-re
4369 (concat
4370 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4371 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4372 org-bracket-link-regexp
4373 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4374 org-bracket-link-analytic-regexp
4375 (concat
4376 "\\[\\["
4377 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4378 "\\([^]]+\\)"
4379 "\\]"
4380 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4381 "\\]")
4382 org-bracket-link-analytic-regexp++
4383 (concat
4384 "\\[\\["
4385 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4386 "\\([^]]+\\)"
4387 "\\]"
4388 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4389 "\\]")
4390 org-any-link-re
4391 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4392 org-angle-link-re "\\)\\|\\("
4393 org-plain-link-re "\\)")))
4395 (org-make-link-regexps)
4397 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4398 "Regular expression for fast time stamp matching.")
4399 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4400 "Regular expression for fast time stamp matching.")
4401 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4402 "Regular expression matching time strings for analysis.
4403 This one does not require the space after the date, so it can be used
4404 on a string that terminates immediately after the date.")
4405 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4406 "Regular expression matching time strings for analysis.")
4407 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4408 "Regular expression matching time stamps, with groups.")
4409 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4410 "Regular expression matching time stamps (also [..]), with groups.")
4411 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4412 "Regular expression matching a time stamp range.")
4413 (defconst org-tr-regexp-both
4414 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4415 "Regular expression matching a time stamp range.")
4416 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4417 org-ts-regexp "\\)?")
4418 "Regular expression matching a time stamp or time stamp range.")
4419 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4420 org-ts-regexp-both "\\)?")
4421 "Regular expression matching a time stamp or time stamp range.
4422 The time stamps may be either active or inactive.")
4424 (defvar org-emph-face nil)
4426 (defun org-do-emphasis-faces (limit)
4427 "Run through the buffer and add overlays to links."
4428 (let (rtn a)
4429 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4430 (if (not (= (char-after (match-beginning 3))
4431 (char-after (match-beginning 4))))
4432 (progn
4433 (setq rtn t)
4434 (setq a (assoc (match-string 3) org-emphasis-alist))
4435 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4436 'face
4437 (nth 1 a))
4438 (and (nth 4 a)
4439 (org-remove-flyspell-overlays-in
4440 (match-beginning 0) (match-end 0)))
4441 (add-text-properties (match-beginning 2) (match-end 2)
4442 '(font-lock-multiline t))
4443 (when org-hide-emphasis-markers
4444 (add-text-properties (match-end 4) (match-beginning 5)
4445 '(invisible org-link))
4446 (add-text-properties (match-beginning 3) (match-end 3)
4447 '(invisible org-link)))))
4448 (backward-char 1))
4449 rtn))
4451 (defun org-emphasize (&optional char)
4452 "Insert or change an emphasis, i.e. a font like bold or italic.
4453 If there is an active region, change that region to a new emphasis.
4454 If there is no region, just insert the marker characters and position
4455 the cursor between them.
4456 CHAR should be either the marker character, or the first character of the
4457 HTML tag associated with that emphasis. If CHAR is a space, the means
4458 to remove the emphasis of the selected region.
4459 If char is not given (for example in an interactive call) it
4460 will be prompted for."
4461 (interactive)
4462 (let ((eal org-emphasis-alist) e det
4463 (erc org-emphasis-regexp-components)
4464 (prompt "")
4465 (string "") beg end move tag c s)
4466 (if (org-region-active-p)
4467 (setq beg (region-beginning) end (region-end)
4468 string (buffer-substring beg end))
4469 (setq move t))
4471 (while (setq e (pop eal))
4472 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4473 c (aref tag 0))
4474 (push (cons c (string-to-char (car e))) det)
4475 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4476 (substring tag 1)))))
4477 (setq det (nreverse det))
4478 (unless char
4479 (message "%s" (concat "Emphasis marker or tag:" prompt))
4480 (setq char (read-char-exclusive)))
4481 (setq char (or (cdr (assoc char det)) char))
4482 (if (equal char ?\ )
4483 (setq s "" move nil)
4484 (unless (assoc (char-to-string char) org-emphasis-alist)
4485 (error "No such emphasis marker: \"%c\"" char))
4486 (setq s (char-to-string char)))
4487 (while (and (> (length string) 1)
4488 (equal (substring string 0 1) (substring string -1))
4489 (assoc (substring string 0 1) org-emphasis-alist))
4490 (setq string (substring string 1 -1)))
4491 (setq string (concat s string s))
4492 (if beg (delete-region beg end))
4493 (unless (or (bolp)
4494 (string-match (concat "[" (nth 0 erc) "\n]")
4495 (char-to-string (char-before (point)))))
4496 (insert " "))
4497 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4498 (char-to-string (char-after (point))))
4499 (insert " ") (backward-char 1))
4500 (insert string)
4501 (and move (backward-char 1))))
4503 (defconst org-nonsticky-props
4504 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4506 (defsubst org-rear-nonsticky-at (pos)
4507 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4509 (defun org-activate-plain-links (limit)
4510 "Run through the buffer and add overlays to links."
4511 (catch 'exit
4512 (let (f)
4513 (if (re-search-forward org-plain-link-re limit t)
4514 (progn
4515 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4516 (setq f (get-text-property (match-beginning 0) 'face))
4517 (if (or (eq f 'org-tag)
4518 (and (listp f) (memq 'org-tag f)))
4520 (add-text-properties (match-beginning 0) (match-end 0)
4521 (list 'mouse-face 'highlight
4522 'face 'org-link
4523 'keymap org-mouse-map))
4524 (org-rear-nonsticky-at (match-end 0)))
4525 t)))))
4527 (defun org-activate-code (limit)
4528 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4529 (progn
4530 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4531 (remove-text-properties (match-beginning 0) (match-end 0)
4532 '(display t invisible t intangible t))
4533 t)))
4535 (defun org-fontify-meta-lines-and-blocks (limit)
4536 "Fontify #+ lines and blocks, in the correct ways."
4537 (let ((case-fold-search t))
4538 (if (re-search-forward
4539 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4540 limit t)
4541 (let ((beg (match-beginning 0))
4542 (beg1 (line-beginning-position 2))
4543 (dc1 (downcase (match-string 2)))
4544 (dc3 (downcase (match-string 3)))
4545 end end1 quoting block-type)
4546 (cond
4547 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4548 ;; a single line of backend-specific content
4549 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4550 (remove-text-properties (match-beginning 0) (match-end 0)
4551 '(display t invisible t intangible t))
4552 (add-text-properties (match-beginning 1) (match-end 3)
4553 '(font-lock-fontified t face org-meta-line))
4554 (add-text-properties (match-beginning 6) (match-end 6)
4555 '(font-lock-fontified t face org-block))
4557 ((and (match-end 4) (equal dc3 "begin"))
4558 ;; Truely a block
4559 (setq block-type (downcase (match-string 5))
4560 quoting (member block-type org-protecting-blocks))
4561 (when (re-search-forward
4562 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4563 nil t) ;; on purpose, we look further than LIMIT
4564 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4565 (when quoting
4566 (remove-text-properties beg end
4567 '(display t invisible t intangible t)))
4568 (add-text-properties
4569 beg end
4570 '(font-lock-fontified t font-lock-multiline t))
4571 (add-text-properties beg beg1 '(face org-meta-line))
4572 (add-text-properties end1 end '(face org-meta-line))
4573 (cond
4574 (quoting
4575 (add-text-properties beg1 end1 '(face org-block)))
4576 ((string= block-type "quote")
4577 (add-text-properties beg1 end1 '(face org-quote)))
4578 ((string= block-type "verse")
4579 (add-text-properties beg1 end1 '(face org-verse))))
4581 ((not (member (char-after beg) '(?\ ?\t)))
4582 ;; just any other in-buffer setting, but not indented
4583 (add-text-properties
4584 beg (match-end 0)
4585 '(font-lock-fontified t face org-meta-line))
4587 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4588 "orgtbl:" "tblfm:" "tblname:"))
4589 (and (match-end 4) (equal dc3 "attr")))
4590 (add-text-properties
4591 beg (match-end 0)
4592 '(font-lock-fontified t face org-meta-line))
4594 ((member dc3 '(" " ""))
4595 (add-text-properties
4596 beg (match-end 0)
4597 '(font-lock-fontified t face font-lock-comment-face)))
4598 (t nil))))))
4600 (defun org-activate-angle-links (limit)
4601 "Run through the buffer and add overlays to links."
4602 (if (re-search-forward org-angle-link-re limit t)
4603 (progn
4604 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4605 (add-text-properties (match-beginning 0) (match-end 0)
4606 (list 'mouse-face 'highlight
4607 'keymap org-mouse-map))
4608 (org-rear-nonsticky-at (match-end 0))
4609 t)))
4611 (defun org-activate-footnote-links (limit)
4612 "Run through the buffer and add overlays to links."
4613 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4614 limit t)
4615 (progn
4616 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4617 (add-text-properties (match-beginning 2) (match-end 2)
4618 (list 'mouse-face 'highlight
4619 'keymap org-mouse-map
4620 'help-echo
4621 (if (= (point-at-bol) (match-beginning 2))
4622 "Footnote definition"
4623 "Footnote reference")
4625 (org-rear-nonsticky-at (match-end 2))
4626 t)))
4628 (defun org-activate-bracket-links (limit)
4629 "Run through the buffer and add overlays to bracketed links."
4630 (if (re-search-forward org-bracket-link-regexp limit t)
4631 (let* ((help (concat "LINK: "
4632 (org-match-string-no-properties 1)))
4633 ;; FIXME: above we should remove the escapes.
4634 ;; but that requires another match, protecting match data,
4635 ;; a lot of overhead for font-lock.
4636 (ip (org-maybe-intangible
4637 (list 'invisible 'org-link
4638 'keymap org-mouse-map 'mouse-face 'highlight
4639 'font-lock-multiline t 'help-echo help)))
4640 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4641 'font-lock-multiline t 'help-echo help)))
4642 ;; We need to remove the invisible property here. Table narrowing
4643 ;; may have made some of this invisible.
4644 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4645 (remove-text-properties (match-beginning 0) (match-end 0)
4646 '(invisible nil))
4647 (if (match-end 3)
4648 (progn
4649 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4650 (org-rear-nonsticky-at (match-beginning 3))
4651 (add-text-properties (match-beginning 3) (match-end 3) vp)
4652 (org-rear-nonsticky-at (match-end 3))
4653 (add-text-properties (match-end 3) (match-end 0) ip)
4654 (org-rear-nonsticky-at (match-end 0)))
4655 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4656 (org-rear-nonsticky-at (match-beginning 1))
4657 (add-text-properties (match-beginning 1) (match-end 1) vp)
4658 (org-rear-nonsticky-at (match-end 1))
4659 (add-text-properties (match-end 1) (match-end 0) ip)
4660 (org-rear-nonsticky-at (match-end 0)))
4661 t)))
4663 (defun org-activate-dates (limit)
4664 "Run through the buffer and add overlays to dates."
4665 (if (re-search-forward org-tsr-regexp-both limit t)
4666 (progn
4667 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4668 (add-text-properties (match-beginning 0) (match-end 0)
4669 (list 'mouse-face 'highlight
4670 'keymap org-mouse-map))
4671 (org-rear-nonsticky-at (match-end 0))
4672 (when org-display-custom-times
4673 (if (match-end 3)
4674 (org-display-custom-time (match-beginning 3) (match-end 3)))
4675 (org-display-custom-time (match-beginning 1) (match-end 1)))
4676 t)))
4678 (defvar org-target-link-regexp nil
4679 "Regular expression matching radio targets in plain text.")
4680 (make-variable-buffer-local 'org-target-link-regexp)
4681 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4682 "Regular expression matching a link target.")
4683 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4684 "Regular expression matching a radio target.")
4685 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4686 "Regular expression matching any target.")
4688 (defun org-activate-target-links (limit)
4689 "Run through the buffer and add overlays to target matches."
4690 (when org-target-link-regexp
4691 (let ((case-fold-search t))
4692 (if (re-search-forward org-target-link-regexp limit t)
4693 (progn
4694 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4695 (add-text-properties (match-beginning 0) (match-end 0)
4696 (list 'mouse-face 'highlight
4697 'keymap org-mouse-map
4698 'help-echo "Radio target link"
4699 'org-linked-text t))
4700 (org-rear-nonsticky-at (match-end 0))
4701 t)))))
4703 (defun org-update-radio-target-regexp ()
4704 "Find all radio targets in this file and update the regular expression."
4705 (interactive)
4706 (when (memq 'radio org-activate-links)
4707 (setq org-target-link-regexp
4708 (org-make-target-link-regexp (org-all-targets 'radio)))
4709 (org-restart-font-lock)))
4711 (defun org-hide-wide-columns (limit)
4712 (let (s e)
4713 (setq s (text-property-any (point) (or limit (point-max))
4714 'org-cwidth t))
4715 (when s
4716 (setq e (next-single-property-change s 'org-cwidth))
4717 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4718 (goto-char e)
4719 t)))
4721 (defvar org-latex-and-specials-regexp nil
4722 "Regular expression for highlighting export special stuff.")
4723 (defvar org-match-substring-regexp)
4724 (defvar org-match-substring-with-braces-regexp)
4726 ;; This should be with the exporter code, but we also use if for font-locking
4727 (defconst org-export-html-special-string-regexps
4728 '(("\\\\-" . "&shy;")
4729 ("---\\([^-]\\)" . "&mdash;\\1")
4730 ("--\\([^-]\\)" . "&ndash;\\1")
4731 ("\\.\\.\\." . "&hellip;"))
4732 "Regular expressions for special string conversion.")
4735 (defun org-compute-latex-and-specials-regexp ()
4736 "Compute regular expression for stuff treated specially by exporters."
4737 (if (not org-highlight-latex-fragments-and-specials)
4738 (org-set-local 'org-latex-and-specials-regexp nil)
4739 (require 'org-exp)
4740 (let*
4741 ((matchers (plist-get org-format-latex-options :matchers))
4742 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4743 org-latex-regexps)))
4744 (options (org-combine-plists (org-default-export-plist)
4745 (org-infile-export-plist)))
4746 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4747 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4748 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4749 (org-export-html-expand (plist-get options :expand-quoted-html))
4750 (org-export-with-special-strings (plist-get options :special-strings))
4751 (re-sub
4752 (cond
4753 ((equal org-export-with-sub-superscripts '{})
4754 (list org-match-substring-with-braces-regexp))
4755 (org-export-with-sub-superscripts
4756 (list org-match-substring-regexp))
4757 (t nil)))
4758 (re-latex
4759 (if org-export-with-LaTeX-fragments
4760 (mapcar (lambda (x) (nth 1 x)) latexs)))
4761 (re-macros
4762 (if org-export-with-TeX-macros
4763 (list (concat "\\\\"
4764 (regexp-opt
4765 (append (mapcar 'car org-html-entities)
4766 (if (boundp 'org-latex-entities)
4767 (mapcar (lambda (x)
4768 (or (car-safe x) x))
4769 org-latex-entities)
4770 nil))
4771 'words))) ; FIXME
4773 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4774 (re-special (if org-export-with-special-strings
4775 (mapcar (lambda (x) (car x))
4776 org-export-html-special-string-regexps)))
4777 (re-rest
4778 (delq nil
4779 (list
4780 (if org-export-html-expand "@<[^>\n]+>")
4781 ))))
4782 (org-set-local
4783 'org-latex-and-specials-regexp
4784 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4785 re-rest) "\\|")))))
4787 (defun org-do-latex-and-special-faces (limit)
4788 "Run through the buffer and add overlays to links."
4789 (when org-latex-and-specials-regexp
4790 (let (rtn d)
4791 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4792 limit t))
4793 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4794 'face))
4795 '(org-code org-verbatim underline)))
4796 (progn
4797 (setq rtn t
4798 d (cond ((member (char-after (1+ (match-beginning 0)))
4799 '(?_ ?^)) 1)
4800 (t 0)))
4801 (font-lock-prepend-text-property
4802 (+ d (match-beginning 0)) (match-end 0)
4803 'face 'org-latex-and-export-specials)
4804 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4805 '(font-lock-multiline t)))))
4806 rtn)))
4808 (defun org-restart-font-lock ()
4809 "Restart font-lock-mode, to force refontification."
4810 (when (and (boundp 'font-lock-mode) font-lock-mode)
4811 (font-lock-mode -1)
4812 (font-lock-mode 1)))
4814 (defun org-all-targets (&optional radio)
4815 "Return a list of all targets in this file.
4816 With optional argument RADIO, only find radio targets."
4817 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4818 rtn)
4819 (save-excursion
4820 (goto-char (point-min))
4821 (while (re-search-forward re nil t)
4822 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4823 rtn)))
4825 (defun org-make-target-link-regexp (targets)
4826 "Make regular expression matching all strings in TARGETS.
4827 The regular expression finds the targets also if there is a line break
4828 between words."
4829 (and targets
4830 (concat
4831 "\\<\\("
4832 (mapconcat
4833 (lambda (x)
4834 (while (string-match " +" x)
4835 (setq x (replace-match "\\s-+" t t x)))
4837 targets
4838 "\\|")
4839 "\\)\\>")))
4841 (defun org-activate-tags (limit)
4842 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4843 (progn
4844 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4845 (add-text-properties (match-beginning 1) (match-end 1)
4846 (list 'mouse-face 'highlight
4847 'keymap org-mouse-map))
4848 (org-rear-nonsticky-at (match-end 1))
4849 t)))
4851 (defun org-outline-level ()
4852 "Compute the outline level of the heading at point.
4853 This function assumes that the cursor is at the beginning of a line matched
4854 by outline-regexp. Otherwise it returns garbage.
4855 If this is called at a normal headline, the level is the number of stars.
4856 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4857 For plain list items, if they are matched by `outline-regexp', this returns
4858 1000 plus the line indentation."
4859 (save-excursion
4860 (looking-at outline-regexp)
4861 (if (match-beginning 1)
4862 (+ (org-get-string-indentation (match-string 1)) 1000)
4863 (1- (- (match-end 0) (match-beginning 0))))))
4865 (defvar org-font-lock-keywords nil)
4867 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4868 "Regular expression matching a property line.")
4870 (defvar org-font-lock-hook nil
4871 "Functions to be called for special font lock stuff.")
4873 (defun org-font-lock-hook (limit)
4874 (run-hook-with-args 'org-font-lock-hook limit))
4876 (defun org-set-font-lock-defaults ()
4877 (let* ((em org-fontify-emphasized-text)
4878 (lk org-activate-links)
4879 (org-font-lock-extra-keywords
4880 (list
4881 ;; Call the hook
4882 '(org-font-lock-hook)
4883 ;; Headlines
4884 `(,(if org-fontify-whole-heading-line
4885 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4886 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4887 (1 (org-get-level-face 1))
4888 (2 (org-get-level-face 2))
4889 (3 (org-get-level-face 3)))
4890 ;; Table lines
4891 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4892 (1 'org-table t))
4893 ;; Table internals
4894 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4895 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4896 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4897 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4898 ;; Drawers
4899 (list org-drawer-regexp '(0 'org-special-keyword t))
4900 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4901 ;; Properties
4902 (list org-property-re
4903 '(1 'org-special-keyword t)
4904 '(3 'org-property-value t))
4905 ;; Links
4906 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4907 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4908 (if (memq 'plain lk) '(org-activate-plain-links))
4909 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4910 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4911 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4912 (if (memq 'footnote lk) '(org-activate-footnote-links
4913 (2 'org-footnote t)))
4914 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4915 '(org-hide-wide-columns (0 nil append))
4916 ;; TODO lines
4917 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4918 '(1 (org-get-todo-face 1) t))
4919 ;; DONE
4920 (if org-fontify-done-headline
4921 (list (concat "^[*]+ +\\<\\("
4922 (mapconcat 'regexp-quote org-done-keywords "\\|")
4923 "\\)\\(.*\\)")
4924 '(2 'org-headline-done t))
4925 nil)
4926 ;; Priorities
4927 '(org-font-lock-add-priority-faces)
4928 ;; Tags
4929 '(org-font-lock-add-tag-faces)
4930 ;; Special keywords
4931 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4932 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4933 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4934 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4935 ;; Emphasis
4936 (if em
4937 (if (featurep 'xemacs)
4938 '(org-do-emphasis-faces (0 nil append))
4939 '(org-do-emphasis-faces)))
4940 ;; Checkboxes
4941 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4942 2 'org-checkbox prepend)
4943 (if org-provide-checkbox-statistics
4944 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4945 (0 (org-get-checkbox-statistics-face) t)))
4946 ;; Description list items
4947 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4948 2 'bold prepend)
4949 ;; ARCHIVEd headings
4950 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4951 '(1 'org-archived prepend))
4952 ;; Specials
4953 '(org-do-latex-and-special-faces)
4954 ;; Code
4955 '(org-activate-code (1 'org-code t))
4956 ;; COMMENT
4957 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4958 "\\|" org-quote-string "\\)\\>")
4959 '(1 'org-special-keyword t))
4960 '("^#.*" (0 'font-lock-comment-face t))
4961 ;; Blocks and meta lines
4962 '(org-fontify-meta-lines-and-blocks)
4964 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4965 ;; Now set the full font-lock-keywords
4966 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4967 (org-set-local 'font-lock-defaults
4968 '(org-font-lock-keywords t nil nil backward-paragraph))
4969 (kill-local-variable 'font-lock-keywords) nil))
4971 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4972 "Fontify string S like in Org-mode"
4973 (with-temp-buffer
4974 (insert s)
4975 (let ((org-odd-levels-only odd-levels))
4976 (org-mode)
4977 (font-lock-fontify-buffer)
4978 (buffer-string))))
4980 (defvar org-m nil)
4981 (defvar org-l nil)
4982 (defvar org-f nil)
4983 (defun org-get-level-face (n)
4984 "Get the right face for match N in font-lock matching of headlines."
4985 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4986 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4987 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4988 (cond
4989 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4990 ((eq n 2) org-f)
4991 (t (if org-level-color-stars-only nil org-f))))
4993 (defun org-get-todo-face (kwd)
4994 "Get the right face for a TODO keyword KWD.
4995 If KWD is a number, get the corresponding match group."
4996 (if (numberp kwd) (setq kwd (match-string kwd)))
4997 (or (cdr (assoc kwd org-todo-keyword-faces))
4998 (and (member kwd org-done-keywords) 'org-done)
4999 'org-todo))
5001 (defun org-font-lock-add-tag-faces (limit)
5002 "Add the special tag faces."
5003 (when (and org-tag-faces org-tags-special-faces-re)
5004 (while (re-search-forward org-tags-special-faces-re limit t)
5005 (add-text-properties (match-beginning 1) (match-end 1)
5006 (list 'face (org-get-tag-face 1)
5007 'font-lock-fontified t))
5008 (backward-char 1))))
5010 (defun org-font-lock-add-priority-faces (limit)
5011 "Add the special priority faces."
5012 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5013 (add-text-properties
5014 (match-beginning 0) (match-end 0)
5015 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
5016 org-priority-faces))
5017 'org-special-keyword)
5018 'font-lock-fontified t))))
5020 (defun org-get-tag-face (kwd)
5021 "Get the right face for a TODO keyword KWD.
5022 If KWD is a number, get the corresponding match group."
5023 (if (numberp kwd) (setq kwd (match-string kwd)))
5024 (or (cdr (assoc kwd org-tag-faces))
5025 'org-tag))
5027 (defun org-unfontify-region (beg end &optional maybe_loudly)
5028 "Remove fontification and activation overlays from links."
5029 (font-lock-default-unfontify-region beg end)
5030 (let* ((buffer-undo-list t)
5031 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5032 (inhibit-modification-hooks t)
5033 deactivate-mark buffer-file-name buffer-file-truename)
5034 (remove-text-properties
5035 beg end
5036 (if org-indent-mode
5037 ;; also remove line-prefix and wrap-prefix properties
5038 '(mouse-face t keymap t org-linked-text t
5039 invisible t intangible t
5040 line-prefix t wrap-prefix t
5041 org-no-flyspell t)
5042 '(mouse-face t keymap t org-linked-text t
5043 invisible t intangible t
5044 org-no-flyspell t)))))
5046 ;;;; Visibility cycling, including org-goto and indirect buffer
5048 ;;; Cycling
5050 (defvar org-cycle-global-status nil)
5051 (make-variable-buffer-local 'org-cycle-global-status)
5052 (defvar org-cycle-subtree-status nil)
5053 (make-variable-buffer-local 'org-cycle-subtree-status)
5055 ;;;###autoload
5057 (defvar org-inlinetask-min-level)
5059 (defun org-cycle (&optional arg)
5060 "TAB-action and visibility cycling for Org-mode.
5062 This is the command invoked in Org-mode by the TAB key. Its main purpose
5063 is outline visibility cycling, but it also invokes other actions
5064 in special contexts.
5066 - When this function is called with a prefix argument, rotate the entire
5067 buffer through 3 states (global cycling)
5068 1. OVERVIEW: Show only top-level headlines.
5069 2. CONTENTS: Show all headlines of all levels, but no body text.
5070 3. SHOW ALL: Show everything.
5071 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5072 determined by the variable `org-startup-folded', and by any VISIBILITY
5073 properties in the buffer.
5074 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5075 including any drawers.
5077 - When inside a table, re-align the table and move to the next field.
5079 - When point is at the beginning of a headline, rotate the subtree started
5080 by this line through 3 different states (local cycling)
5081 1. FOLDED: Only the main headline is shown.
5082 2. CHILDREN: The main headline and the direct children are shown.
5083 From this state, you can move to one of the children
5084 and zoom in further.
5085 3. SUBTREE: Show the entire subtree, including body text.
5086 If there is no subtree, switch directly from CHILDREN to FOLDED.
5088 - When there is a numeric prefix, go up to a heading with level ARG, do
5089 a `show-subtree' and return to the previous cursor position. If ARG
5090 is negative, go up that many levels.
5092 - When point is not at the beginning of a headline, execute the global
5093 binding for TAB, which is re-indenting the line. See the option
5094 `org-cycle-emulate-tab' for details.
5096 - Special case: if point is at the beginning of the buffer and there is
5097 no headline in line 1, this function will act as if called with prefix arg.
5098 But only if also the variable `org-cycle-global-at-bob' is t."
5099 (interactive "P")
5100 (org-load-modules-maybe)
5101 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5102 (and org-cycle-level-after-item/entry-creation
5103 (or (org-cycle-level)
5104 (org-cycle-item-indentation))))
5105 (let* ((limit-level
5106 (or org-cycle-max-level
5107 (and (boundp 'org-inlinetask-min-level)
5108 org-inlinetask-min-level
5109 (1- org-inlinetask-min-level))))
5110 (nstars (and limit-level
5111 (if org-odd-levels-only
5112 (and limit-level (1- (* limit-level 2)))
5113 limit-level)))
5114 (outline-regexp
5115 (cond
5116 ((not (org-mode-p)) outline-regexp)
5117 ((or (eq org-cycle-include-plain-lists 'integrate)
5118 (and org-cycle-include-plain-lists (org-at-item-p)))
5119 (concat "\\(?:\\*"
5120 (if nstars (format "\\{1,%d\\}" nstars) "+")
5121 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5122 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5123 (bob-special (and org-cycle-global-at-bob (bobp)
5124 (not (looking-at outline-regexp))))
5125 (org-cycle-hook
5126 (if bob-special
5127 (delq 'org-optimize-window-after-visibility-change
5128 (copy-sequence org-cycle-hook))
5129 org-cycle-hook))
5130 (pos (point)))
5132 (if (or bob-special (equal arg '(4)))
5133 ;; special case: use global cycling
5134 (setq arg t))
5136 (cond
5138 ((equal arg '(16))
5139 (org-set-startup-visibility)
5140 (message "Startup visibility, plus VISIBILITY properties"))
5142 ((equal arg '(64))
5143 (show-all)
5144 (message "Entire buffer visible, including drawers"))
5146 ((org-at-table-p 'any)
5147 ;; Enter the table or move to the next field in the table
5148 (or (org-table-recognize-table.el)
5149 (progn
5150 (if arg (org-table-edit-field t)
5151 (org-table-justify-field-maybe)
5152 (call-interactively 'org-table-next-field)))))
5154 ((run-hook-with-args-until-success
5155 'org-tab-after-check-for-table-hook))
5157 ((eq arg t) ;; Global cycling
5158 (org-cycle-internal-global))
5160 ((and org-drawers org-drawer-regexp
5161 (save-excursion
5162 (beginning-of-line 1)
5163 (looking-at org-drawer-regexp)))
5164 ;; Toggle block visibility
5165 (org-flag-drawer
5166 (not (get-char-property (match-end 0) 'invisible))))
5168 ((integerp arg)
5169 ;; Show-subtree, ARG levels up from here.
5170 (save-excursion
5171 (org-back-to-heading)
5172 (outline-up-heading (if (< arg 0) (- arg)
5173 (- (funcall outline-level) arg)))
5174 (org-show-subtree)))
5176 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5177 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5179 (org-cycle-internal-local))
5181 ;; TAB emulation and template completion
5182 (buffer-read-only (org-back-to-heading))
5184 ((run-hook-with-args-until-success
5185 'org-tab-after-check-for-cycling-hook))
5187 ((org-try-structure-completion))
5189 ((org-try-cdlatex-tab))
5191 ((run-hook-with-args-until-success
5192 'org-tab-before-tab-emulation-hook))
5194 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5195 (or (not (bolp))
5196 (not (looking-at outline-regexp))))
5197 (call-interactively (global-key-binding "\t")))
5199 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5200 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5201 (or (and (eq org-cycle-emulate-tab 'white)
5202 (= (match-end 0) (point-at-eol)))
5203 (and (eq org-cycle-emulate-tab 'whitestart)
5204 (>= (match-end 0) pos))))
5206 (eq org-cycle-emulate-tab t))
5207 (call-interactively (global-key-binding "\t")))
5209 (t (save-excursion
5210 (org-back-to-heading)
5211 (org-cycle)))))))
5213 (defun org-cycle-internal-global ()
5214 "Do the global cycling action."
5215 (cond
5216 ((and (eq last-command this-command)
5217 (eq org-cycle-global-status 'overview))
5218 ;; We just created the overview - now do table of contents
5219 ;; This can be slow in very large buffers, so indicate action
5220 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5221 (message "CONTENTS...")
5222 (org-content)
5223 (message "CONTENTS...done")
5224 (setq org-cycle-global-status 'contents)
5225 (run-hook-with-args 'org-cycle-hook 'contents))
5227 ((and (eq last-command this-command)
5228 (eq org-cycle-global-status 'contents))
5229 ;; We just showed the table of contents - now show everything
5230 (run-hook-with-args 'org-pre-cycle-hook 'all)
5231 (show-all)
5232 (message "SHOW ALL")
5233 (setq org-cycle-global-status 'all)
5234 (run-hook-with-args 'org-cycle-hook 'all))
5237 ;; Default action: go to overview
5238 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5239 (org-overview)
5240 (message "OVERVIEW")
5241 (setq org-cycle-global-status 'overview)
5242 (run-hook-with-args 'org-cycle-hook 'overview))))
5244 (defun org-cycle-internal-local ()
5245 "Do the local cycling action."
5246 (org-back-to-heading)
5247 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5248 ;; First, some boundaries
5249 (save-excursion
5250 (org-back-to-heading)
5251 (setq level (funcall outline-level))
5252 (save-excursion
5253 (beginning-of-line 2)
5254 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5255 ; XEmacs does not have `next-single-char-property-change'
5256 ; I'm not sure about Emacs 21.
5257 (while (and (not (eobp)) ;; this is like `next-line'
5258 (get-char-property (1- (point)) 'invisible))
5259 (beginning-of-line 2))
5260 (while (and (not (eobp)) ;; this is like `next-line'
5261 (get-char-property (1- (point)) 'invisible))
5262 (goto-char (next-single-char-property-change (point) 'invisible))
5263 ;;;??? (or (bolp) (beginning-of-line 2))))
5264 (and (eolp) (beginning-of-line 2))))
5265 (setq eol (point)))
5266 (outline-end-of-heading) (setq eoh (point))
5267 (save-excursion
5268 (outline-next-heading)
5269 (setq has-children (and (org-at-heading-p t)
5270 (> (funcall outline-level) level))))
5271 (org-end-of-subtree t)
5272 (unless (eobp)
5273 (skip-chars-forward " \t\n")
5274 (beginning-of-line 1) ; in case this is an item
5276 (setq eos (if (eobp) (point) (1- (point)))))
5277 ;; Find out what to do next and set `this-command'
5278 (cond
5279 ((= eos eoh)
5280 ;; Nothing is hidden behind this heading
5281 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5282 (message "EMPTY ENTRY")
5283 (setq org-cycle-subtree-status nil)
5284 (save-excursion
5285 (goto-char eos)
5286 (outline-next-heading)
5287 (if (org-invisible-p) (org-flag-heading nil))))
5288 ((and (or (>= eol eos)
5289 (not (string-match "\\S-" (buffer-substring eol eos))))
5290 (or has-children
5291 (not (setq children-skipped
5292 org-cycle-skip-children-state-if-no-children))))
5293 ;; Entire subtree is hidden in one line: children view
5294 (run-hook-with-args 'org-pre-cycle-hook 'children)
5295 (org-show-entry)
5296 (show-children)
5297 (message "CHILDREN")
5298 (save-excursion
5299 (goto-char eos)
5300 (outline-next-heading)
5301 (if (org-invisible-p) (org-flag-heading nil)))
5302 (setq org-cycle-subtree-status 'children)
5303 (run-hook-with-args 'org-cycle-hook 'children))
5304 ((or children-skipped
5305 (and (eq last-command this-command)
5306 (eq org-cycle-subtree-status 'children)))
5307 ;; We just showed the children, or no children are there,
5308 ;; now show everything.
5309 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5310 (org-show-subtree)
5311 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5312 (setq org-cycle-subtree-status 'subtree)
5313 (run-hook-with-args 'org-cycle-hook 'subtree))
5315 ;; Default action: hide the subtree.
5316 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5317 (hide-subtree)
5318 (message "FOLDED")
5319 (setq org-cycle-subtree-status 'folded)
5320 (run-hook-with-args 'org-cycle-hook 'folded)))))
5322 ;;;###autoload
5323 (defun org-global-cycle (&optional arg)
5324 "Cycle the global visibility. For details see `org-cycle'.
5325 With C-u prefix arg, switch to startup visibility.
5326 With a numeric prefix, show all headlines up to that level."
5327 (interactive "P")
5328 (let ((org-cycle-include-plain-lists
5329 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5330 (cond
5331 ((integerp arg)
5332 (show-all)
5333 (hide-sublevels arg)
5334 (setq org-cycle-global-status 'contents))
5335 ((equal arg '(4))
5336 (org-set-startup-visibility)
5337 (message "Startup visibility, plus VISIBILITY properties."))
5339 (org-cycle '(4))))))
5341 (defun org-set-startup-visibility ()
5342 "Set the visibility required by startup options and properties."
5343 (cond
5344 ((eq org-startup-folded t)
5345 (org-cycle '(4)))
5346 ((eq org-startup-folded 'content)
5347 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5348 (org-cycle '(4)) (org-cycle '(4)))))
5349 (unless (eq org-startup-folded 'showeverything)
5350 (if org-hide-block-startup (org-hide-block-all))
5351 (org-set-visibility-according-to-property 'no-cleanup)
5352 (org-cycle-hide-archived-subtrees 'all)
5353 (org-cycle-hide-drawers 'all)
5354 (org-cycle-show-empty-lines 'all)))
5356 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5357 "Switch subtree visibilities according to :VISIBILITY: property."
5358 (interactive)
5359 (let (org-show-entry-below state)
5360 (save-excursion
5361 (goto-char (point-min))
5362 (while (re-search-forward
5363 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5364 nil t)
5365 (setq state (match-string 1))
5366 (save-excursion
5367 (org-back-to-heading t)
5368 (hide-subtree)
5369 (org-reveal)
5370 (cond
5371 ((equal state '("fold" "folded"))
5372 (hide-subtree))
5373 ((equal state "children")
5374 (org-show-hidden-entry)
5375 (show-children))
5376 ((equal state "content")
5377 (save-excursion
5378 (save-restriction
5379 (org-narrow-to-subtree)
5380 (org-content))))
5381 ((member state '("all" "showall"))
5382 (show-subtree)))))
5383 (unless no-cleanup
5384 (org-cycle-hide-archived-subtrees 'all)
5385 (org-cycle-hide-drawers 'all)
5386 (org-cycle-show-empty-lines 'all)))))
5388 (defun org-overview ()
5389 "Switch to overview mode, showing only top-level headlines.
5390 Really, this shows all headlines with level equal or greater than the level
5391 of the first headline in the buffer. This is important, because if the
5392 first headline is not level one, then (hide-sublevels 1) gives confusing
5393 results."
5394 (interactive)
5395 (let ((level (save-excursion
5396 (goto-char (point-min))
5397 (if (re-search-forward (concat "^" outline-regexp) nil t)
5398 (progn
5399 (goto-char (match-beginning 0))
5400 (funcall outline-level))))))
5401 (and level (hide-sublevels level))))
5403 (defun org-content (&optional arg)
5404 "Show all headlines in the buffer, like a table of contents.
5405 With numerical argument N, show content up to level N."
5406 (interactive "P")
5407 (save-excursion
5408 ;; Visit all headings and show their offspring
5409 (and (integerp arg) (org-overview))
5410 (goto-char (point-max))
5411 (catch 'exit
5412 (while (and (progn (condition-case nil
5413 (outline-previous-visible-heading 1)
5414 (error (goto-char (point-min))))
5416 (looking-at outline-regexp))
5417 (if (integerp arg)
5418 (show-children (1- arg))
5419 (show-branches))
5420 (if (bobp) (throw 'exit nil))))))
5423 (defun org-optimize-window-after-visibility-change (state)
5424 "Adjust the window after a change in outline visibility.
5425 This function is the default value of the hook `org-cycle-hook'."
5426 (when (get-buffer-window (current-buffer))
5427 (cond
5428 ((eq state 'content) nil)
5429 ((eq state 'all) nil)
5430 ((eq state 'folded) nil)
5431 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5432 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5434 (defun org-remove-empty-overlays-at (pos)
5435 "Remove outline overlays that do not contain non-white stuff."
5436 (mapc
5437 (lambda (o)
5438 (and (eq 'outline (org-overlay-get o 'invisible))
5439 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5440 (org-overlay-end o))))
5441 (org-delete-overlay o)))
5442 (org-overlays-at pos)))
5444 (defun org-clean-visibility-after-subtree-move ()
5445 "Fix visibility issues after moving a subtree."
5446 ;; First, find a reasonable region to look at:
5447 ;; Start two siblings above, end three below
5448 (let* ((beg (save-excursion
5449 (and (org-get-last-sibling)
5450 (org-get-last-sibling))
5451 (point)))
5452 (end (save-excursion
5453 (and (org-get-next-sibling)
5454 (org-get-next-sibling)
5455 (org-get-next-sibling))
5456 (if (org-at-heading-p)
5457 (point-at-eol)
5458 (point))))
5459 (level (looking-at "\\*+"))
5460 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5461 (save-excursion
5462 (save-restriction
5463 (narrow-to-region beg end)
5464 (when re
5465 ;; Properly fold already folded siblings
5466 (goto-char (point-min))
5467 (while (re-search-forward re nil t)
5468 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5469 (hide-entry))))
5470 (org-cycle-show-empty-lines 'overview)
5471 (org-cycle-hide-drawers 'overview)))))
5473 (defun org-cycle-show-empty-lines (state)
5474 "Show empty lines above all visible headlines.
5475 The region to be covered depends on STATE when called through
5476 `org-cycle-hook'. Lisp program can use t for STATE to get the
5477 entire buffer covered. Note that an empty line is only shown if there
5478 are at least `org-cycle-separator-lines' empty lines before the headline."
5479 (when (not (= org-cycle-separator-lines 0))
5480 (save-excursion
5481 (let* ((n (abs org-cycle-separator-lines))
5482 (re (cond
5483 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5484 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5485 (t (let ((ns (number-to-string (- n 2))))
5486 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5487 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5488 beg end b e)
5489 (cond
5490 ((memq state '(overview contents t))
5491 (setq beg (point-min) end (point-max)))
5492 ((memq state '(children folded))
5493 (setq beg (point) end (progn (org-end-of-subtree t t)
5494 (beginning-of-line 2)
5495 (point)))))
5496 (when beg
5497 (goto-char beg)
5498 (while (re-search-forward re end t)
5499 (unless (get-char-property (match-end 1) 'invisible)
5500 (setq e (match-end 1))
5501 (if (< org-cycle-separator-lines 0)
5502 (setq b (save-excursion
5503 (goto-char (match-beginning 0))
5504 (org-back-over-empty-lines)
5505 (if (save-excursion
5506 (goto-char (max (point-min) (1- (point))))
5507 (org-on-heading-p))
5508 (1- (point))
5509 (point))))
5510 (setq b (match-beginning 1)))
5511 (outline-flag-region b e nil)))))))
5512 ;; Never hide empty lines at the end of the file.
5513 (save-excursion
5514 (goto-char (point-max))
5515 (outline-previous-heading)
5516 (outline-end-of-heading)
5517 (if (and (looking-at "[ \t\n]+")
5518 (= (match-end 0) (point-max)))
5519 (outline-flag-region (point) (match-end 0) nil))))
5521 (defun org-show-empty-lines-in-parent ()
5522 "Move to the parent and re-show empty lines before visible headlines."
5523 (save-excursion
5524 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5525 (org-cycle-show-empty-lines context))))
5527 (defun org-files-list ()
5528 "Return `org-agenda-files' list, plus all open org-mode files.
5529 This is useful for operations that need to scan all of a user's
5530 open and agenda-wise Org files."
5531 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5532 (dolist (buf (buffer-list))
5533 (with-current-buffer buf
5534 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5535 (let ((file (expand-file-name (buffer-file-name))))
5536 (unless (member file files)
5537 (push file files))))))
5538 files))
5540 (defsubst org-entry-beginning-position ()
5541 "Return the beginning position of the current entry."
5542 (save-excursion (outline-back-to-heading t) (point)))
5544 (defsubst org-entry-end-position ()
5545 "Return the end position of the current entry."
5546 (save-excursion (outline-next-heading) (point)))
5548 (defun org-cycle-hide-drawers (state)
5549 "Re-hide all drawers after a visibility state change."
5550 (when (and (org-mode-p)
5551 (not (memq state '(overview folded contents))))
5552 (save-excursion
5553 (let* ((globalp (memq state '(contents all)))
5554 (beg (if globalp (point-min) (point)))
5555 (end (if globalp (point-max)
5556 (if (eq state 'children)
5557 (save-excursion (outline-next-heading) (point))
5558 (org-end-of-subtree t)))))
5559 (goto-char beg)
5560 (while (re-search-forward org-drawer-regexp end t)
5561 (org-flag-drawer t))))))
5563 (defun org-flag-drawer (flag)
5564 (save-excursion
5565 (beginning-of-line 1)
5566 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5567 (let ((b (match-end 0))
5568 (outline-regexp org-outline-regexp))
5569 (if (re-search-forward
5570 "^[ \t]*:END:"
5571 (save-excursion (outline-next-heading) (point)) t)
5572 (outline-flag-region b (point-at-eol) flag)
5573 (error ":END: line missing at position %s" b))))))
5575 (defun org-subtree-end-visible-p ()
5576 "Is the end of the current subtree visible?"
5577 (pos-visible-in-window-p
5578 (save-excursion (org-end-of-subtree t) (point))))
5580 (defun org-first-headline-recenter (&optional N)
5581 "Move cursor to the first headline and recenter the headline.
5582 Optional argument N means, put the headline into the Nth line of the window."
5583 (goto-char (point-min))
5584 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5585 (beginning-of-line)
5586 (recenter (prefix-numeric-value N))))
5588 ;;; Folding of blocks
5590 (defconst org-block-regexp
5592 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5593 "Regular expression for hiding blocks.")
5595 (defvar org-hide-block-overlays nil
5596 "Overlays hiding blocks.")
5597 (make-variable-buffer-local 'org-hide-block-overlays)
5599 (defun org-block-map (function &optional start end)
5600 "Call func at the head of all source blocks in the current
5601 buffer. Optional arguments START and END can be used to limit
5602 the range."
5603 (let ((start (or start (point-min)))
5604 (end (or end (point-max))))
5605 (save-excursion
5606 (goto-char start)
5607 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5608 (save-excursion
5609 (save-match-data
5610 (goto-char (match-beginning 0))
5611 (funcall function)))))))
5613 (defun org-hide-block-toggle-all ()
5614 "Toggle the visibility of all blocks in the current buffer."
5615 (org-block-map #'org-hide-block-toggle))
5617 (defun org-hide-block-all ()
5618 "Fold all blocks in the current buffer."
5619 (interactive)
5620 (org-show-block-all)
5621 (org-block-map #'org-hide-block-toggle-maybe))
5623 (defun org-show-block-all ()
5624 "Unfold all blocks in the current buffer."
5625 (mapc 'org-delete-overlay org-hide-block-overlays)
5626 (setq org-hide-block-overlays nil))
5628 (defun org-hide-block-toggle-maybe ()
5629 "Toggle visibility of block at point."
5630 (interactive)
5631 (let ((case-fold-search t))
5632 (if (save-excursion
5633 (beginning-of-line 1)
5634 (looking-at org-block-regexp))
5635 (progn (org-hide-block-toggle)
5636 t) ;; to signal that we took action
5637 nil))) ;; to signal that we did not
5639 (defun org-hide-block-toggle (&optional force)
5640 "Toggle the visibility of the current block."
5641 (interactive)
5642 (save-excursion
5643 (beginning-of-line)
5644 (if (re-search-forward org-block-regexp nil t)
5645 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5646 (end (match-end 0)) ;; end of entire body
5648 (if (memq t (mapcar (lambda (overlay)
5649 (eq (org-overlay-get overlay 'invisible)
5650 'org-hide-block))
5651 (org-overlays-at start)))
5652 (if (or (not force) (eq force 'off))
5653 (mapc (lambda (ov)
5654 (when (member ov org-hide-block-overlays)
5655 (setq org-hide-block-overlays
5656 (delq ov org-hide-block-overlays)))
5657 (when (eq (org-overlay-get ov 'invisible)
5658 'org-hide-block)
5659 (org-delete-overlay ov)))
5660 (org-overlays-at start)))
5661 (setq ov (org-make-overlay start end))
5662 (org-overlay-put ov 'invisible 'org-hide-block)
5663 ;; make the block accessible to isearch
5664 (org-overlay-put
5665 ov 'isearch-open-invisible
5666 (lambda (ov)
5667 (when (member ov org-hide-block-overlays)
5668 (setq org-hide-block-overlays
5669 (delq ov org-hide-block-overlays)))
5670 (when (eq (org-overlay-get ov 'invisible)
5671 'org-hide-block)
5672 (org-delete-overlay ov))))
5673 (push ov org-hide-block-overlays)))
5674 (error "Not looking at a source block"))))
5676 ;; org-tab-after-check-for-cycling-hook
5677 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5678 ;; Remove overlays when changing major mode
5679 (add-hook 'org-mode-hook
5680 (lambda () (org-add-hook 'change-major-mode-hook
5681 'org-show-block-all 'append 'local)))
5683 ;;; Org-goto
5685 (defvar org-goto-window-configuration nil)
5686 (defvar org-goto-marker nil)
5687 (defvar org-goto-map
5688 (let ((map (make-sparse-keymap)))
5689 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5690 (while (setq cmd (pop cmds))
5691 (substitute-key-definition cmd cmd map global-map)))
5692 (suppress-keymap map)
5693 (org-defkey map "\C-m" 'org-goto-ret)
5694 (org-defkey map [(return)] 'org-goto-ret)
5695 (org-defkey map [(left)] 'org-goto-left)
5696 (org-defkey map [(right)] 'org-goto-right)
5697 (org-defkey map [(control ?g)] 'org-goto-quit)
5698 (org-defkey map "\C-i" 'org-cycle)
5699 (org-defkey map [(tab)] 'org-cycle)
5700 (org-defkey map [(down)] 'outline-next-visible-heading)
5701 (org-defkey map [(up)] 'outline-previous-visible-heading)
5702 (if org-goto-auto-isearch
5703 (if (fboundp 'define-key-after)
5704 (define-key-after map [t] 'org-goto-local-auto-isearch)
5705 nil)
5706 (org-defkey map "q" 'org-goto-quit)
5707 (org-defkey map "n" 'outline-next-visible-heading)
5708 (org-defkey map "p" 'outline-previous-visible-heading)
5709 (org-defkey map "f" 'outline-forward-same-level)
5710 (org-defkey map "b" 'outline-backward-same-level)
5711 (org-defkey map "u" 'outline-up-heading))
5712 (org-defkey map "/" 'org-occur)
5713 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5714 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5715 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5716 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5717 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5718 map))
5720 (defconst org-goto-help
5721 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5722 RET=jump to location [Q]uit and return to previous location
5723 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5725 (defvar org-goto-start-pos) ; dynamically scoped parameter
5727 ;; FIXME: Docstring does not mention both interfaces
5728 (defun org-goto (&optional alternative-interface)
5729 "Look up a different location in the current file, keeping current visibility.
5731 When you want look-up or go to a different location in a document, the
5732 fastest way is often to fold the entire buffer and then dive into the tree.
5733 This method has the disadvantage, that the previous location will be folded,
5734 which may not be what you want.
5736 This command works around this by showing a copy of the current buffer
5737 in an indirect buffer, in overview mode. You can dive into the tree in
5738 that copy, use org-occur and incremental search to find a location.
5739 When pressing RET or `Q', the command returns to the original buffer in
5740 which the visibility is still unchanged. After RET is will also jump to
5741 the location selected in the indirect buffer and expose the
5742 the headline hierarchy above."
5743 (interactive "P")
5744 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5745 (org-refile-use-outline-path t)
5746 (org-refile-target-verify-function nil)
5747 (interface
5748 (if (not alternative-interface)
5749 org-goto-interface
5750 (if (eq org-goto-interface 'outline)
5751 'outline-path-completion
5752 'outline)))
5753 (org-goto-start-pos (point))
5754 (selected-point
5755 (if (eq interface 'outline)
5756 (car (org-get-location (current-buffer) org-goto-help))
5757 (nth 3 (org-refile-get-location "Goto: ")))))
5758 (if selected-point
5759 (progn
5760 (org-mark-ring-push org-goto-start-pos)
5761 (goto-char selected-point)
5762 (if (or (org-invisible-p) (org-invisible-p2))
5763 (org-show-context 'org-goto)))
5764 (message "Quit"))))
5766 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5767 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5768 (defvar org-goto-local-auto-isearch-map) ; defined below
5770 (defun org-get-location (buf help)
5771 "Let the user select a location in the Org-mode buffer BUF.
5772 This function uses a recursive edit. It returns the selected position
5773 or nil."
5774 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5775 (isearch-hide-immediately nil)
5776 (isearch-search-fun-function
5777 (lambda () 'org-goto-local-search-headings))
5778 (org-goto-selected-point org-goto-exit-command))
5779 (save-excursion
5780 (save-window-excursion
5781 (delete-other-windows)
5782 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5783 (switch-to-buffer
5784 (condition-case nil
5785 (make-indirect-buffer (current-buffer) "*org-goto*")
5786 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5787 (with-output-to-temp-buffer "*Help*"
5788 (princ help))
5789 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5790 (setq buffer-read-only nil)
5791 (let ((org-startup-truncated t)
5792 (org-startup-folded nil)
5793 (org-startup-align-all-tables nil))
5794 (org-mode)
5795 (org-overview))
5796 (setq buffer-read-only t)
5797 (if (and (boundp 'org-goto-start-pos)
5798 (integer-or-marker-p org-goto-start-pos))
5799 (let ((org-show-hierarchy-above t)
5800 (org-show-siblings t)
5801 (org-show-following-heading t))
5802 (goto-char org-goto-start-pos)
5803 (and (org-invisible-p) (org-show-context)))
5804 (goto-char (point-min)))
5805 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5806 (message "Select location and press RET")
5807 (use-local-map org-goto-map)
5808 (recursive-edit)
5810 (kill-buffer "*org-goto*")
5811 (cons org-goto-selected-point org-goto-exit-command)))
5813 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5814 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5815 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5816 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5818 (defun org-goto-local-search-headings (string bound noerror)
5819 "Search and make sure that any matches are in headlines."
5820 (catch 'return
5821 (while (if isearch-forward
5822 (search-forward string bound noerror)
5823 (search-backward string bound noerror))
5824 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5825 (and (member :headline context)
5826 (not (member :tags context))))
5827 (throw 'return (point))))))
5829 (defun org-goto-local-auto-isearch ()
5830 "Start isearch."
5831 (interactive)
5832 (goto-char (point-min))
5833 (let ((keys (this-command-keys)))
5834 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5835 (isearch-mode t)
5836 (isearch-process-search-char (string-to-char keys)))))
5838 (defun org-goto-ret (&optional arg)
5839 "Finish `org-goto' by going to the new location."
5840 (interactive "P")
5841 (setq org-goto-selected-point (point)
5842 org-goto-exit-command 'return)
5843 (throw 'exit nil))
5845 (defun org-goto-left ()
5846 "Finish `org-goto' by going to the new location."
5847 (interactive)
5848 (if (org-on-heading-p)
5849 (progn
5850 (beginning-of-line 1)
5851 (setq org-goto-selected-point (point)
5852 org-goto-exit-command 'left)
5853 (throw 'exit nil))
5854 (error "Not on a heading")))
5856 (defun org-goto-right ()
5857 "Finish `org-goto' by going to the new location."
5858 (interactive)
5859 (if (org-on-heading-p)
5860 (progn
5861 (setq org-goto-selected-point (point)
5862 org-goto-exit-command 'right)
5863 (throw 'exit nil))
5864 (error "Not on a heading")))
5866 (defun org-goto-quit ()
5867 "Finish `org-goto' without cursor motion."
5868 (interactive)
5869 (setq org-goto-selected-point nil)
5870 (setq org-goto-exit-command 'quit)
5871 (throw 'exit nil))
5873 ;;; Indirect buffer display of subtrees
5875 (defvar org-indirect-dedicated-frame nil
5876 "This is the frame being used for indirect tree display.")
5877 (defvar org-last-indirect-buffer nil)
5879 (defun org-tree-to-indirect-buffer (&optional arg)
5880 "Create indirect buffer and narrow it to current subtree.
5881 With numerical prefix ARG, go up to this level and then take that tree.
5882 If ARG is negative, go up that many levels.
5883 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5884 indirect buffer previously made with this command, to avoid proliferation of
5885 indirect buffers. However, when you call the command with a `C-u' prefix, or
5886 when `org-indirect-buffer-display' is `new-frame', the last buffer
5887 is kept so that you can work with several indirect buffers at the same time.
5888 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5889 requests that a new frame be made for the new buffer, so that the dedicated
5890 frame is not changed."
5891 (interactive "P")
5892 (let ((cbuf (current-buffer))
5893 (cwin (selected-window))
5894 (pos (point))
5895 beg end level heading ibuf)
5896 (save-excursion
5897 (org-back-to-heading t)
5898 (when (numberp arg)
5899 (setq level (org-outline-level))
5900 (if (< arg 0) (setq arg (+ level arg)))
5901 (while (> (setq level (org-outline-level)) arg)
5902 (outline-up-heading 1 t)))
5903 (setq beg (point)
5904 heading (org-get-heading))
5905 (org-end-of-subtree t t) (setq end (point)))
5906 (if (and (buffer-live-p org-last-indirect-buffer)
5907 (not (eq org-indirect-buffer-display 'new-frame))
5908 (not arg))
5909 (kill-buffer org-last-indirect-buffer))
5910 (setq ibuf (org-get-indirect-buffer cbuf)
5911 org-last-indirect-buffer ibuf)
5912 (cond
5913 ((or (eq org-indirect-buffer-display 'new-frame)
5914 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5915 (select-frame (make-frame))
5916 (delete-other-windows)
5917 (switch-to-buffer ibuf)
5918 (org-set-frame-title heading))
5919 ((eq org-indirect-buffer-display 'dedicated-frame)
5920 (raise-frame
5921 (select-frame (or (and org-indirect-dedicated-frame
5922 (frame-live-p org-indirect-dedicated-frame)
5923 org-indirect-dedicated-frame)
5924 (setq org-indirect-dedicated-frame (make-frame)))))
5925 (delete-other-windows)
5926 (switch-to-buffer ibuf)
5927 (org-set-frame-title (concat "Indirect: " heading)))
5928 ((eq org-indirect-buffer-display 'current-window)
5929 (switch-to-buffer ibuf))
5930 ((eq org-indirect-buffer-display 'other-window)
5931 (pop-to-buffer ibuf))
5932 (t (error "Invalid value")))
5933 (if (featurep 'xemacs)
5934 (save-excursion (org-mode) (turn-on-font-lock)))
5935 (narrow-to-region beg end)
5936 (show-all)
5937 (goto-char pos)
5938 (and (window-live-p cwin) (select-window cwin))))
5940 (defun org-get-indirect-buffer (&optional buffer)
5941 (setq buffer (or buffer (current-buffer)))
5942 (let ((n 1) (base (buffer-name buffer)) bname)
5943 (while (buffer-live-p
5944 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5945 (setq n (1+ n)))
5946 (condition-case nil
5947 (make-indirect-buffer buffer bname 'clone)
5948 (error (make-indirect-buffer buffer bname)))))
5950 (defun org-set-frame-title (title)
5951 "Set the title of the current frame to the string TITLE."
5952 ;; FIXME: how to name a single frame in XEmacs???
5953 (unless (featurep 'xemacs)
5954 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5956 ;;;; Structure editing
5958 ;;; Inserting headlines
5960 (defun org-previous-line-empty-p ()
5961 (save-excursion
5962 (and (not (bobp))
5963 (or (beginning-of-line 0) t)
5964 (save-match-data
5965 (looking-at "[ \t]*$")))))
5967 (defun org-insert-heading (&optional force-heading)
5968 "Insert a new heading or item with same depth at point.
5969 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5970 If point is at the beginning of a headline, insert a sibling before the
5971 current headline. If point is not at the beginning, do not split the line,
5972 but create the new headline after the current line."
5973 (interactive "P")
5974 (if (= (buffer-size) 0)
5975 (insert "\n* ")
5976 (when (or force-heading (not (org-insert-item)))
5977 (let* ((empty-line-p nil)
5978 (head (save-excursion
5979 (condition-case nil
5980 (progn
5981 (org-back-to-heading)
5982 (setq empty-line-p (org-previous-line-empty-p))
5983 (match-string 0))
5984 (error "*"))))
5985 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5986 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5987 pos hide-previous previous-pos)
5988 (cond
5989 ((and (org-on-heading-p) (bolp)
5990 (or (bobp)
5991 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5992 ;; insert before the current line
5993 (open-line (if blank 2 1)))
5994 ((and (bolp)
5995 (not org-insert-heading-respect-content)
5996 (or (bobp)
5997 (save-excursion
5998 (backward-char 1) (not (org-invisible-p)))))
5999 ;; insert right here
6000 nil)
6002 ;; somewhere in the line
6003 (save-excursion
6004 (setq previous-pos (point-at-bol))
6005 (end-of-line)
6006 (setq hide-previous (org-invisible-p)))
6007 (and org-insert-heading-respect-content (org-show-subtree))
6008 (let ((split
6009 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6010 (save-excursion
6011 (let ((p (point)))
6012 (goto-char (point-at-bol))
6013 (and (looking-at org-complex-heading-regexp)
6014 (> p (match-beginning 4)))))))
6015 tags pos)
6016 (cond
6017 (org-insert-heading-respect-content
6018 (org-end-of-subtree nil t)
6019 (or (bolp) (newline))
6020 (or (org-previous-line-empty-p)
6021 (and blank (newline)))
6022 (open-line 1))
6023 ((org-on-heading-p)
6024 (when hide-previous
6025 (show-children)
6026 (org-show-entry))
6027 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6028 (setq tags (and (match-end 2) (match-string 2)))
6029 (and (match-end 1)
6030 (delete-region (match-beginning 1) (match-end 1)))
6031 (setq pos (point-at-bol))
6032 (or split (end-of-line 1))
6033 (delete-horizontal-space)
6034 (newline (if blank 2 1))
6035 (when tags
6036 (save-excursion
6037 (goto-char pos)
6038 (end-of-line 1)
6039 (insert " " tags)
6040 (org-set-tags nil 'align))))
6042 (or split (end-of-line 1))
6043 (newline (if blank 2 1)))))))
6044 (insert head) (just-one-space)
6045 (setq pos (point))
6046 (end-of-line 1)
6047 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6048 (when (and org-insert-heading-respect-content hide-previous)
6049 (save-excursion
6050 (goto-char previous-pos)
6051 (hide-subtree)))
6052 (run-hooks 'org-insert-heading-hook)))))
6054 (defun org-get-heading (&optional no-tags)
6055 "Return the heading of the current entry, without the stars."
6056 (save-excursion
6057 (org-back-to-heading t)
6058 (if (looking-at
6059 (if no-tags
6060 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6061 "\\*+[ \t]+\\([^\r\n]*\\)"))
6062 (match-string 1) "")))
6064 (defun org-heading-components ()
6065 "Return the components of the current heading.
6066 This is a list with the following elements:
6067 - the level as an integer
6068 - the reduced level, different if `org-odd-levels-only' is set.
6069 - the TODO keyword, or nil
6070 - the priority character, like ?A, or nil if no priority is given
6071 - the headline text itself, or the tags string if no headline text
6072 - the tags string, or nil."
6073 (save-excursion
6074 (org-back-to-heading t)
6075 (if (looking-at org-complex-heading-regexp)
6076 (list (length (match-string 1))
6077 (org-reduced-level (length (match-string 1)))
6078 (org-match-string-no-properties 2)
6079 (and (match-end 3) (aref (match-string 3) 2))
6080 (org-match-string-no-properties 4)
6081 (org-match-string-no-properties 5)))))
6083 (defun org-get-entry ()
6084 "Get the entry text, after heading, entire subtree."
6085 (save-excursion
6086 (org-back-to-heading t)
6087 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6089 (defun org-insert-heading-after-current ()
6090 "Insert a new heading with same level as current, after current subtree."
6091 (interactive)
6092 (org-back-to-heading)
6093 (org-insert-heading)
6094 (org-move-subtree-down)
6095 (end-of-line 1))
6097 (defun org-insert-heading-respect-content ()
6098 (interactive)
6099 (let ((org-insert-heading-respect-content t))
6100 (org-insert-heading t)))
6102 (defun org-insert-todo-heading-respect-content (&optional force-state)
6103 (interactive "P")
6104 (let ((org-insert-heading-respect-content t))
6105 (org-insert-todo-heading force-state t)))
6107 (defun org-insert-todo-heading (arg &optional force-heading)
6108 "Insert a new heading with the same level and TODO state as current heading.
6109 If the heading has no TODO state, or if the state is DONE, use the first
6110 state (TODO by default). Also with prefix arg, force first state."
6111 (interactive "P")
6112 (when (or force-heading (not (org-insert-item 'checkbox)))
6113 (org-insert-heading force-heading)
6114 (save-excursion
6115 (org-back-to-heading)
6116 (outline-previous-heading)
6117 (looking-at org-todo-line-regexp))
6118 (let*
6119 ((new-mark-x
6120 (if (or arg
6121 (not (match-beginning 2))
6122 (member (match-string 2) org-done-keywords))
6123 (car org-todo-keywords-1)
6124 (match-string 2)))
6125 (new-mark
6127 (run-hook-with-args-until-success
6128 'org-todo-get-default-hook new-mark-x nil)
6129 new-mark-x)))
6130 (beginning-of-line 1)
6131 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6132 (if org-treat-insert-todo-heading-as-state-change
6133 (org-todo new-mark)
6134 (insert new-mark " "))))
6135 (when org-provide-todo-statistics
6136 (org-update-parent-todo-statistics))))
6138 (defun org-insert-subheading (arg)
6139 "Insert a new subheading and demote it.
6140 Works for outline headings and for plain lists alike."
6141 (interactive "P")
6142 (org-insert-heading arg)
6143 (cond
6144 ((org-on-heading-p) (org-do-demote))
6145 ((org-at-item-p) (org-indent-item 1))))
6147 (defun org-insert-todo-subheading (arg)
6148 "Insert a new subheading with TODO keyword or checkbox and demote it.
6149 Works for outline headings and for plain lists alike."
6150 (interactive "P")
6151 (org-insert-todo-heading arg)
6152 (cond
6153 ((org-on-heading-p) (org-do-demote))
6154 ((org-at-item-p) (org-indent-item 1))))
6156 ;;; Promotion and Demotion
6158 (defvar org-after-demote-entry-hook nil
6159 "Hook run after an entry has been demoted.
6160 The cursor will be at the beginning of the entry.
6161 When a subtree is being demoted, the hook will be called for each node.")
6163 (defvar org-after-promote-entry-hook nil
6164 "Hook run after an entry has been promoted.
6165 The cursor will be at the beginning of the entry.
6166 When a subtree is being promoted, the hook will be called for each node.")
6168 (defun org-promote-subtree ()
6169 "Promote the entire subtree.
6170 See also `org-promote'."
6171 (interactive)
6172 (save-excursion
6173 (org-map-tree 'org-promote))
6174 (org-fix-position-after-promote))
6176 (defun org-demote-subtree ()
6177 "Demote the entire subtree. See `org-demote'.
6178 See also `org-promote'."
6179 (interactive)
6180 (save-excursion
6181 (org-map-tree 'org-demote))
6182 (org-fix-position-after-promote))
6185 (defun org-do-promote ()
6186 "Promote the current heading higher up the tree.
6187 If the region is active in `transient-mark-mode', promote all headings
6188 in the region."
6189 (interactive)
6190 (save-excursion
6191 (if (org-region-active-p)
6192 (org-map-region 'org-promote (region-beginning) (region-end))
6193 (org-promote)))
6194 (org-fix-position-after-promote))
6196 (defun org-do-demote ()
6197 "Demote the current heading lower down the tree.
6198 If the region is active in `transient-mark-mode', demote all headings
6199 in the region."
6200 (interactive)
6201 (save-excursion
6202 (if (org-region-active-p)
6203 (org-map-region 'org-demote (region-beginning) (region-end))
6204 (org-demote)))
6205 (org-fix-position-after-promote))
6207 (defun org-fix-position-after-promote ()
6208 "Make sure that after pro/demotion cursor position is right."
6209 (let ((pos (point)))
6210 (when (save-excursion
6211 (beginning-of-line 1)
6212 (looking-at org-todo-line-regexp)
6213 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6214 (cond ((eobp) (insert " "))
6215 ((eolp) (insert " "))
6216 ((equal (char-after) ?\ ) (forward-char 1))))))
6218 (defun org-current-level ()
6219 "Return the level of the current entry, or nil if before the first headline.
6220 The level is the number of stars at the beginning of the headline."
6221 (save-excursion
6222 (condition-case nil
6223 (progn
6224 (org-back-to-heading t)
6225 (funcall outline-level))
6226 (error nil))))
6228 (defun org-reduced-level (l)
6229 "Compute the effective level of a heading.
6230 This takes into account the setting of `org-odd-levels-only'."
6231 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6233 (defun org-get-valid-level (level &optional change)
6234 "Rectify a level change under the influence of `org-odd-levels-only'
6235 LEVEL is a current level, CHANGE is by how much the level should be
6236 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6237 even level numbers will become the next higher odd number."
6238 (if org-odd-levels-only
6239 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6240 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6241 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6242 (max 1 (+ level (or change 0)))))
6244 (if (boundp 'define-obsolete-function-alias)
6245 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6246 (define-obsolete-function-alias 'org-get-legal-level
6247 'org-get-valid-level)
6248 (define-obsolete-function-alias 'org-get-legal-level
6249 'org-get-valid-level "23.1")))
6251 (defun org-promote ()
6252 "Promote the current heading higher up the tree.
6253 If the region is active in `transient-mark-mode', promote all headings
6254 in the region."
6255 (org-back-to-heading t)
6256 (let* ((level (save-match-data (funcall outline-level)))
6257 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6258 (diff (abs (- level (length up-head) -1))))
6259 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6260 (replace-match up-head nil t)
6261 ;; Fixup tag positioning
6262 (and org-auto-align-tags (org-set-tags nil t))
6263 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6264 (run-hooks 'org-after-promote-entry-hook)))
6266 (defun org-demote ()
6267 "Demote the current heading lower down the tree.
6268 If the region is active in `transient-mark-mode', demote all headings
6269 in the region."
6270 (org-back-to-heading t)
6271 (let* ((level (save-match-data (funcall outline-level)))
6272 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6273 (diff (abs (- level (length down-head) -1))))
6274 (replace-match down-head nil t)
6275 ;; Fixup tag positioning
6276 (and org-auto-align-tags (org-set-tags nil t))
6277 (if org-adapt-indentation (org-fixup-indentation diff))
6278 (run-hooks 'org-after-demote-entry-hook)))
6280 (defvar org-tab-ind-state nil)
6282 (defun org-cycle-level ()
6283 (let ((org-adapt-indentation nil))
6284 (when (and (looking-at "[ \t]*$")
6285 (looking-back
6286 (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp "\\)?[ \t]*")))
6287 (setq this-command 'org-cycle-level)
6288 (if (eq last-command 'org-cycle-level)
6289 (condition-case nil
6290 (progn (org-do-promote)
6291 (if (equal org-tab-ind-state (org-current-level))
6292 (org-do-promote)))
6293 (error
6294 (progn
6295 (save-excursion
6296 (beginning-of-line 1)
6297 (and (looking-at "\\*+")
6298 (replace-match
6299 (make-string org-tab-ind-state ?*))))
6300 (setq this-command 'org-cycle))))
6301 (setq org-tab-ind-state (- (match-end 1) (match-beginning 1)))
6302 (org-do-demote))
6303 t)))
6305 (defun org-map-tree (fun)
6306 "Call FUN for every heading underneath the current one."
6307 (org-back-to-heading)
6308 (let ((level (funcall outline-level)))
6309 (save-excursion
6310 (funcall fun)
6311 (while (and (progn
6312 (outline-next-heading)
6313 (> (funcall outline-level) level))
6314 (not (eobp)))
6315 (funcall fun)))))
6317 (defun org-map-region (fun beg end)
6318 "Call FUN for every heading between BEG and END."
6319 (let ((org-ignore-region t))
6320 (save-excursion
6321 (setq end (copy-marker end))
6322 (goto-char beg)
6323 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6324 (< (point) end))
6325 (funcall fun))
6326 (while (and (progn
6327 (outline-next-heading)
6328 (< (point) end))
6329 (not (eobp)))
6330 (funcall fun)))))
6332 (defun org-fixup-indentation (diff)
6333 "Change the indentation in the current entry by DIFF
6334 However, if any line in the current entry has no indentation, or if it
6335 would end up with no indentation after the change, nothing at all is done."
6336 (save-excursion
6337 (let ((end (save-excursion (outline-next-heading)
6338 (point-marker)))
6339 (prohibit (if (> diff 0)
6340 "^\\S-"
6341 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6342 col)
6343 (unless (save-excursion (end-of-line 1)
6344 (re-search-forward prohibit end t))
6345 (while (and (< (point) end)
6346 (re-search-forward "^[ \t]+" end t))
6347 (goto-char (match-end 0))
6348 (setq col (current-column))
6349 (if (< diff 0) (replace-match ""))
6350 (org-indent-to-column (+ diff col))))
6351 (move-marker end nil))))
6353 (defun org-convert-to-odd-levels ()
6354 "Convert an org-mode file with all levels allowed to one with odd levels.
6355 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6356 level 5 etc."
6357 (interactive)
6358 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6359 (let ((outline-regexp org-outline-regexp)
6360 (outline-level 'org-outline-level)
6361 (org-odd-levels-only nil) n)
6362 (save-excursion
6363 (goto-char (point-min))
6364 (while (re-search-forward "^\\*\\*+ " nil t)
6365 (setq n (- (length (match-string 0)) 2))
6366 (while (>= (setq n (1- n)) 0)
6367 (org-demote))
6368 (end-of-line 1))))))
6370 (defun org-convert-to-oddeven-levels ()
6371 "Convert an org-mode file with only odd levels to one with odd and even levels.
6372 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6373 section with an even level, conversion would destroy the structure of the file. An error
6374 is signaled in this case."
6375 (interactive)
6376 (goto-char (point-min))
6377 ;; First check if there are no even levels
6378 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6379 (org-show-context t)
6380 (error "Not all levels are odd in this file. Conversion not possible"))
6381 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6382 (let ((outline-regexp org-outline-regexp)
6383 (outline-level 'org-outline-level)
6384 (org-odd-levels-only nil) n)
6385 (save-excursion
6386 (goto-char (point-min))
6387 (while (re-search-forward "^\\*\\*+ " nil t)
6388 (setq n (/ (1- (length (match-string 0))) 2))
6389 (while (>= (setq n (1- n)) 0)
6390 (org-promote))
6391 (end-of-line 1))))))
6393 (defun org-tr-level (n)
6394 "Make N odd if required."
6395 (if org-odd-levels-only (1+ (/ n 2)) n))
6397 ;;; Vertical tree motion, cutting and pasting of subtrees
6399 (defun org-move-subtree-up (&optional arg)
6400 "Move the current subtree up past ARG headlines of the same level."
6401 (interactive "p")
6402 (org-move-subtree-down (- (prefix-numeric-value arg))))
6404 (defun org-move-subtree-down (&optional arg)
6405 "Move the current subtree down past ARG headlines of the same level."
6406 (interactive "p")
6407 (setq arg (prefix-numeric-value arg))
6408 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6409 'org-get-last-sibling))
6410 (ins-point (make-marker))
6411 (cnt (abs arg))
6412 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6413 ;; Select the tree
6414 (org-back-to-heading)
6415 (setq beg0 (point))
6416 (save-excursion
6417 (setq ne-beg (org-back-over-empty-lines))
6418 (setq beg (point)))
6419 (save-match-data
6420 (save-excursion (outline-end-of-heading)
6421 (setq folded (org-invisible-p)))
6422 (outline-end-of-subtree))
6423 (outline-next-heading)
6424 (setq ne-end (org-back-over-empty-lines))
6425 (setq end (point))
6426 (goto-char beg0)
6427 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6428 ;; include less whitespace
6429 (save-excursion
6430 (goto-char beg)
6431 (forward-line (- ne-beg ne-end))
6432 (setq beg (point))))
6433 ;; Find insertion point, with error handling
6434 (while (> cnt 0)
6435 (or (and (funcall movfunc) (looking-at outline-regexp))
6436 (progn (goto-char beg0)
6437 (error "Cannot move past superior level or buffer limit")))
6438 (setq cnt (1- cnt)))
6439 (if (> arg 0)
6440 ;; Moving forward - still need to move over subtree
6441 (progn (org-end-of-subtree t t)
6442 (save-excursion
6443 (org-back-over-empty-lines)
6444 (or (bolp) (newline)))))
6445 (setq ne-ins (org-back-over-empty-lines))
6446 (move-marker ins-point (point))
6447 (setq txt (buffer-substring beg end))
6448 (org-save-markers-in-region beg end)
6449 (delete-region beg end)
6450 (org-remove-empty-overlays-at beg)
6451 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6452 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6453 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6454 (let ((bbb (point)))
6455 (insert-before-markers txt)
6456 (org-reinstall-markers-in-region bbb)
6457 (move-marker ins-point bbb))
6458 (or (bolp) (insert "\n"))
6459 (setq ins-end (point))
6460 (goto-char ins-point)
6461 (org-skip-whitespace)
6462 (when (and (< arg 0)
6463 (org-first-sibling-p)
6464 (> ne-ins ne-beg))
6465 ;; Move whitespace back to beginning
6466 (save-excursion
6467 (goto-char ins-end)
6468 (let ((kill-whole-line t))
6469 (kill-line (- ne-ins ne-beg)) (point)))
6470 (insert (make-string (- ne-ins ne-beg) ?\n)))
6471 (move-marker ins-point nil)
6472 (if folded
6473 (hide-subtree)
6474 (org-show-entry)
6475 (show-children)
6476 (org-cycle-hide-drawers 'children))
6477 (org-clean-visibility-after-subtree-move)))
6479 (defvar org-subtree-clip ""
6480 "Clipboard for cut and paste of subtrees.
6481 This is actually only a copy of the kill, because we use the normal kill
6482 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6484 (defvar org-subtree-clip-folded nil
6485 "Was the last copied subtree folded?
6486 This is used to fold the tree back after pasting.")
6488 (defun org-cut-subtree (&optional n)
6489 "Cut the current subtree into the clipboard.
6490 With prefix arg N, cut this many sequential subtrees.
6491 This is a short-hand for marking the subtree and then cutting it."
6492 (interactive "p")
6493 (org-copy-subtree n 'cut))
6495 (defun org-copy-subtree (&optional n cut force-store-markers)
6496 "Cut the current subtree into the clipboard.
6497 With prefix arg N, cut this many sequential subtrees.
6498 This is a short-hand for marking the subtree and then copying it.
6499 If CUT is non-nil, actually cut the subtree.
6500 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6501 of some markers in the region, even if CUT is non-nil. This is
6502 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6503 (interactive "p")
6504 (let (beg end folded (beg0 (point)))
6505 (if (interactive-p)
6506 (org-back-to-heading nil) ; take what looks like a subtree
6507 (org-back-to-heading t)) ; take what is really there
6508 (org-back-over-empty-lines)
6509 (setq beg (point))
6510 (skip-chars-forward " \t\r\n")
6511 (save-match-data
6512 (save-excursion (outline-end-of-heading)
6513 (setq folded (org-invisible-p)))
6514 (condition-case nil
6515 (org-forward-same-level (1- n) t)
6516 (error nil))
6517 (org-end-of-subtree t t))
6518 (org-back-over-empty-lines)
6519 (setq end (point))
6520 (goto-char beg0)
6521 (when (> end beg)
6522 (setq org-subtree-clip-folded folded)
6523 (when (or cut force-store-markers)
6524 (org-save-markers-in-region beg end))
6525 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6526 (setq org-subtree-clip (current-kill 0))
6527 (message "%s: Subtree(s) with %d characters"
6528 (if cut "Cut" "Copied")
6529 (length org-subtree-clip)))))
6531 (defun org-paste-subtree (&optional level tree for-yank)
6532 "Paste the clipboard as a subtree, with modification of headline level.
6533 The entire subtree is promoted or demoted in order to match a new headline
6534 level.
6536 If the cursor is at the beginning of a headline, the same level as
6537 that headline is used to paste the tree
6539 If not, the new level is derived from the *visible* headings
6540 before and after the insertion point, and taken to be the inferior headline
6541 level of the two. So if the previous visible heading is level 3 and the
6542 next is level 4 (or vice versa), level 4 will be used for insertion.
6543 This makes sure that the subtree remains an independent subtree and does
6544 not swallow low level entries.
6546 You can also force a different level, either by using a numeric prefix
6547 argument, or by inserting the heading marker by hand. For example, if the
6548 cursor is after \"*****\", then the tree will be shifted to level 5.
6550 If optional TREE is given, use this text instead of the kill ring.
6552 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6553 move back over whitespace before inserting, and move point to the end of
6554 the inserted text when done."
6555 (interactive "P")
6556 (setq tree (or tree (and kill-ring (current-kill 0))))
6557 (unless (org-kill-is-subtree-p tree)
6558 (error "%s"
6559 (substitute-command-keys
6560 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6561 (let* ((visp (not (org-invisible-p)))
6562 (txt tree)
6563 (^re (concat "^\\(" outline-regexp "\\)"))
6564 (re (concat "\\(" outline-regexp "\\)"))
6565 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6567 (old-level (if (string-match ^re txt)
6568 (- (match-end 0) (match-beginning 0) 1)
6569 -1))
6570 (force-level (cond (level (prefix-numeric-value level))
6571 ((and (looking-at "[ \t]*$")
6572 (string-match
6573 ^re_ (buffer-substring
6574 (point-at-bol) (point))))
6575 (- (match-end 1) (match-beginning 1)))
6576 ((and (bolp)
6577 (looking-at org-outline-regexp))
6578 (- (match-end 0) (point) 1))
6579 (t nil)))
6580 (previous-level (save-excursion
6581 (condition-case nil
6582 (progn
6583 (outline-previous-visible-heading 1)
6584 (if (looking-at re)
6585 (- (match-end 0) (match-beginning 0) 1)
6587 (error 1))))
6588 (next-level (save-excursion
6589 (condition-case nil
6590 (progn
6591 (or (looking-at outline-regexp)
6592 (outline-next-visible-heading 1))
6593 (if (looking-at re)
6594 (- (match-end 0) (match-beginning 0) 1)
6596 (error 1))))
6597 (new-level (or force-level (max previous-level next-level)))
6598 (shift (if (or (= old-level -1)
6599 (= new-level -1)
6600 (= old-level new-level))
6602 (- new-level old-level)))
6603 (delta (if (> shift 0) -1 1))
6604 (func (if (> shift 0) 'org-demote 'org-promote))
6605 (org-odd-levels-only nil)
6606 beg end newend)
6607 ;; Remove the forced level indicator
6608 (if force-level
6609 (delete-region (point-at-bol) (point)))
6610 ;; Paste
6611 (beginning-of-line 1)
6612 (unless for-yank (org-back-over-empty-lines))
6613 (setq beg (point))
6614 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6615 (insert-before-markers txt)
6616 (unless (string-match "\n\\'" txt) (insert "\n"))
6617 (setq newend (point))
6618 (org-reinstall-markers-in-region beg)
6619 (setq end (point))
6620 (goto-char beg)
6621 (skip-chars-forward " \t\n\r")
6622 (setq beg (point))
6623 (if (and (org-invisible-p) visp)
6624 (save-excursion (outline-show-heading)))
6625 ;; Shift if necessary
6626 (unless (= shift 0)
6627 (save-restriction
6628 (narrow-to-region beg end)
6629 (while (not (= shift 0))
6630 (org-map-region func (point-min) (point-max))
6631 (setq shift (+ delta shift)))
6632 (goto-char (point-min))
6633 (setq newend (point-max))))
6634 (when (or (interactive-p) for-yank)
6635 (message "Clipboard pasted as level %d subtree" new-level))
6636 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6637 kill-ring
6638 (eq org-subtree-clip (current-kill 0))
6639 org-subtree-clip-folded)
6640 ;; The tree was folded before it was killed/copied
6641 (hide-subtree))
6642 (and for-yank (goto-char newend))))
6644 (defun org-kill-is-subtree-p (&optional txt)
6645 "Check if the current kill is an outline subtree, or a set of trees.
6646 Returns nil if kill does not start with a headline, or if the first
6647 headline level is not the largest headline level in the tree.
6648 So this will actually accept several entries of equal levels as well,
6649 which is OK for `org-paste-subtree'.
6650 If optional TXT is given, check this string instead of the current kill."
6651 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6652 (start-level (and kill
6653 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6654 org-outline-regexp "\\)")
6655 kill)
6656 (- (match-end 2) (match-beginning 2) 1)))
6657 (re (concat "^" org-outline-regexp))
6658 (start (1+ (or (match-beginning 2) -1))))
6659 (if (not start-level)
6660 (progn
6661 nil) ;; does not even start with a heading
6662 (catch 'exit
6663 (while (setq start (string-match re kill (1+ start)))
6664 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6665 (throw 'exit nil)))
6666 t))))
6668 (defvar org-markers-to-move nil
6669 "Markers that should be moved with a cut-and-paste operation.
6670 Those markers are stored together with their positions relative to
6671 the start of the region.")
6673 (defun org-save-markers-in-region (beg end)
6674 "Check markers in region.
6675 If these markers are between BEG and END, record their position relative
6676 to BEG, so that after moving the block of text, we can put the markers back
6677 into place.
6678 This function gets called just before an entry or tree gets cut from the
6679 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6680 called immediately, to move the markers with the entries."
6681 (setq org-markers-to-move nil)
6682 (when (featurep 'org-clock)
6683 (org-clock-save-markers-for-cut-and-paste beg end))
6684 (when (featurep 'org-agenda)
6685 (org-agenda-save-markers-for-cut-and-paste beg end)))
6687 (defun org-check-and-save-marker (marker beg end)
6688 "Check if MARKER is between BEG and END.
6689 If yes, remember the marker and the distance to BEG."
6690 (when (and (marker-buffer marker)
6691 (equal (marker-buffer marker) (current-buffer)))
6692 (if (and (>= marker beg) (< marker end))
6693 (push (cons marker (- marker beg)) org-markers-to-move))))
6695 (defun org-reinstall-markers-in-region (beg)
6696 "Move all remembered markers to their position relative to BEG."
6697 (mapc (lambda (x)
6698 (move-marker (car x) (+ beg (cdr x))))
6699 org-markers-to-move)
6700 (setq org-markers-to-move nil))
6702 (defun org-narrow-to-subtree ()
6703 "Narrow buffer to the current subtree."
6704 (interactive)
6705 (save-excursion
6706 (save-match-data
6707 (narrow-to-region
6708 (progn (org-back-to-heading t) (point))
6709 (progn (org-end-of-subtree t t) (point))))))
6711 (defun org-clone-subtree-with-time-shift (n &optional shift)
6712 "Clone the task (subtree) at point N times.
6713 The clones will be inserted as siblings.
6715 In interactive use, the user will be prompted for the number of clones
6716 to be produced, and for a time SHIFT, which may be a repeater as used
6717 in time stamps, for example `+3d'.
6719 When a valid repeater is given and the entry contains any time stamps,
6720 the clones will become a sequence in time, with time stamps in the
6721 subtree shifted for each clone produced. If SHIFT is nil or the
6722 empty string, time stamps will be left alone.
6724 If the original subtree did contain time stamps with a repeater,
6725 the following will happen:
6726 - the repeater will be removed in each clone
6727 - an additional clone will be produced, with the current, unshifted
6728 date(s) in the entry.
6729 - the original entry will be placed *after* all the clones, with
6730 repeater intact.
6731 - the start days in the repeater in the original entry will be shifted
6732 to past the last clone.
6733 I this way you can spell out a number of instances of a repeating task,
6734 and still retain the repeater to cover future instances of the task."
6735 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6736 (let (beg end template task
6737 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6738 (if (not (and (integerp n) (> n 0)))
6739 (error "Invalid number of replications %s" n))
6740 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6741 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6742 shift)))
6743 (error "Invalid shift specification %s" shift))
6744 (when doshift
6745 (setq shift-n (string-to-number (match-string 1 shift))
6746 shift-what (cdr (assoc (match-string 2 shift)
6747 '(("d" . day) ("w" . week)
6748 ("m" . month) ("y" . year))))))
6749 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6750 (setq nmin 1 nmax n)
6751 (org-back-to-heading t)
6752 (setq beg (point))
6753 (org-end-of-subtree t t)
6754 (or (bolp) (insert "\n"))
6755 (setq end (point))
6756 (setq template (buffer-substring beg end))
6757 (when (and doshift
6758 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6759 (delete-region beg end)
6760 (setq end beg)
6761 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6762 (goto-char end)
6763 (loop for n from nmin to nmax do
6764 (if (not doshift)
6765 (setq task template)
6766 (with-temp-buffer
6767 (insert template)
6768 (org-mode)
6769 (goto-char (point-min))
6770 (while (re-search-forward org-ts-regexp-both nil t)
6771 (org-timestamp-change (* n shift-n) shift-what))
6772 (unless (= n n-no-remove)
6773 (goto-char (point-min))
6774 (while (re-search-forward org-ts-regexp nil t)
6775 (save-excursion
6776 (goto-char (match-beginning 0))
6777 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6778 (delete-region (match-beginning 1) (match-end 1))))))
6779 (setq task (buffer-string))))
6780 (insert task))
6781 (goto-char beg)))
6783 ;;; Outline Sorting
6785 (defun org-sort (with-case)
6786 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6787 Optional argument WITH-CASE means sort case-sensitively.
6788 With a double prefix argument, also remove duplicate entries."
6789 (interactive "P")
6790 (if (org-at-table-p)
6791 (org-call-with-arg 'org-table-sort-lines with-case)
6792 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6794 (defun org-sort-remove-invisible (s)
6795 (remove-text-properties 0 (length s) org-rm-props s)
6796 (while (string-match org-bracket-link-regexp s)
6797 (setq s (replace-match (if (match-end 2)
6798 (match-string 3 s)
6799 (match-string 1 s)) t t s)))
6802 (defvar org-priority-regexp) ; defined later in the file
6804 (defvar org-after-sorting-entries-or-items-hook nil
6805 "Hook that is run after a bunch of entries or items have been sorted.
6806 When children are sorted, the cursor is in the parent line when this
6807 hook gets called. When a region or a plain list is sorted, the cursor
6808 will be in the first entry of the sorted region/list.")
6810 (defun org-sort-entries-or-items
6811 (&optional with-case sorting-type getkey-func compare-func property)
6812 "Sort entries on a certain level of an outline tree, or plain list items.
6813 If there is an active region, the entries in the region are sorted.
6814 Else, if the cursor is before the first entry, sort the top-level items.
6815 Else, the children of the entry at point are sorted.
6816 If the cursor is at the first item in a plain list, the list items will be
6817 sorted.
6819 Sorting can be alphabetically, numerically, by date/time as given by
6820 a time stamp, by a property or by priority.
6822 The command prompts for the sorting type unless it has been given to the
6823 function through the SORTING-TYPE argument, which needs to a character,
6824 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6825 precise meaning of each character:
6827 n Numerically, by converting the beginning of the entry/item to a number.
6828 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6829 t By date/time, either the first active time stamp in the entry, or, if
6830 none exist, by the first inactive one.
6831 In items, only the first line will be checked.
6832 s By the scheduled date/time.
6833 d By deadline date/time.
6834 c By creation time, which is assumed to be the first inactive time stamp
6835 at the beginning of a line.
6836 p By priority according to the cookie.
6837 r By the value of a property.
6839 Capital letters will reverse the sort order.
6841 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6842 called with point at the beginning of the record. It must return either
6843 a string or a number that should serve as the sorting key for that record.
6845 Comparing entries ignores case by default. However, with an optional argument
6846 WITH-CASE, the sorting considers case as well."
6847 (interactive "P")
6848 (let ((case-func (if with-case 'identity 'downcase))
6849 start beg end stars re re2
6850 txt what tmp plain-list-p)
6851 ;; Find beginning and end of region to sort
6852 (cond
6853 ((org-region-active-p)
6854 ;; we will sort the region
6855 (setq end (region-end)
6856 what "region")
6857 (goto-char (region-beginning))
6858 (if (not (org-on-heading-p)) (outline-next-heading))
6859 (setq start (point)))
6860 ((org-at-item-p)
6861 ;; we will sort this plain list
6862 (org-beginning-of-item-list) (setq start (point))
6863 (org-end-of-item-list)
6864 (or (bolp) (insert "\n"))
6865 (setq end (point))
6866 (goto-char start)
6867 (setq plain-list-p t
6868 what "plain list"))
6869 ((or (org-on-heading-p)
6870 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6871 ;; we will sort the children of the current headline
6872 (org-back-to-heading)
6873 (setq start (point)
6874 end (progn (org-end-of-subtree t t)
6875 (or (bolp) (insert "\n"))
6876 (org-back-over-empty-lines)
6877 (point))
6878 what "children")
6879 (goto-char start)
6880 (show-subtree)
6881 (outline-next-heading))
6883 ;; we will sort the top-level entries in this file
6884 (goto-char (point-min))
6885 (or (org-on-heading-p) (outline-next-heading))
6886 (setq start (point))
6887 (goto-char (point-max))
6888 (beginning-of-line 1)
6889 (when (looking-at ".*?\\S-")
6890 ;; File ends in a non-white line
6891 (end-of-line 1)
6892 (insert "\n"))
6893 (setq end (point-max))
6894 (setq what "top-level")
6895 (goto-char start)
6896 (show-all)))
6898 (setq beg (point))
6899 (if (>= beg end) (error "Nothing to sort"))
6901 (unless plain-list-p
6902 (looking-at "\\(\\*+\\)")
6903 (setq stars (match-string 1)
6904 re (concat "^" (regexp-quote stars) " +")
6905 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6906 txt (buffer-substring beg end))
6907 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6908 (if (and (not (equal stars "*")) (string-match re2 txt))
6909 (error "Region to sort contains a level above the first entry")))
6911 (unless sorting-type
6912 (message
6913 (if plain-list-p
6914 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6915 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6916 [t]ime [s]cheduled [d]eadline [c]reated
6917 A/N/T/S/D/C/P/O/F means reversed:")
6918 what)
6919 (setq sorting-type (read-char-exclusive))
6921 (and (= (downcase sorting-type) ?f)
6922 (setq getkey-func
6923 (org-icompleting-read "Sort using function: "
6924 obarray 'fboundp t nil nil))
6925 (setq getkey-func (intern getkey-func)))
6927 (and (= (downcase sorting-type) ?r)
6928 (setq property
6929 (org-icompleting-read "Property: "
6930 (mapcar 'list (org-buffer-property-keys t))
6931 nil t))))
6933 (message "Sorting entries...")
6935 (save-restriction
6936 (narrow-to-region start end)
6938 (let ((dcst (downcase sorting-type))
6939 (case-fold-search nil)
6940 (now (current-time)))
6941 (sort-subr
6942 (/= dcst sorting-type)
6943 ;; This function moves to the beginning character of the "record" to
6944 ;; be sorted.
6945 (if plain-list-p
6946 (lambda nil
6947 (if (org-at-item-p) t (goto-char (point-max))))
6948 (lambda nil
6949 (if (re-search-forward re nil t)
6950 (goto-char (match-beginning 0))
6951 (goto-char (point-max)))))
6952 ;; This function moves to the last character of the "record" being
6953 ;; sorted.
6954 (if plain-list-p
6955 'org-end-of-item
6956 (lambda nil
6957 (save-match-data
6958 (condition-case nil
6959 (outline-forward-same-level 1)
6960 (error
6961 (goto-char (point-max)))))))
6963 ;; This function returns the value that gets sorted against.
6964 (if plain-list-p
6965 (lambda nil
6966 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6967 (cond
6968 ((= dcst ?n)
6969 (string-to-number (buffer-substring (match-end 0)
6970 (point-at-eol))))
6971 ((= dcst ?a)
6972 (buffer-substring (match-end 0) (point-at-eol)))
6973 ((= dcst ?t)
6974 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6975 (re-search-forward org-ts-regexp-both
6976 (point-at-eol) t))
6977 (org-time-string-to-seconds (match-string 0))
6978 (org-float-time now)))
6979 ((= dcst ?f)
6980 (if getkey-func
6981 (progn
6982 (setq tmp (funcall getkey-func))
6983 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6984 tmp)
6985 (error "Invalid key function `%s'" getkey-func)))
6986 (t (error "Invalid sorting type `%c'" sorting-type)))))
6987 (lambda nil
6988 (cond
6989 ((= dcst ?n)
6990 (if (looking-at org-complex-heading-regexp)
6991 (string-to-number (match-string 4))
6992 nil))
6993 ((= dcst ?a)
6994 (if (looking-at org-complex-heading-regexp)
6995 (funcall case-func (match-string 4))
6996 nil))
6997 ((= dcst ?t)
6998 (let ((end (save-excursion (outline-next-heading) (point))))
6999 (if (or (re-search-forward org-ts-regexp end t)
7000 (re-search-forward org-ts-regexp-both end t))
7001 (org-time-string-to-seconds (match-string 0))
7002 (org-float-time now))))
7003 ((= dcst ?c)
7004 (let ((end (save-excursion (outline-next-heading) (point))))
7005 (if (re-search-forward
7006 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7007 end t)
7008 (org-time-string-to-seconds (match-string 0))
7009 (org-float-time now))))
7010 ((= dcst ?s)
7011 (let ((end (save-excursion (outline-next-heading) (point))))
7012 (if (re-search-forward org-scheduled-time-regexp end t)
7013 (org-time-string-to-seconds (match-string 1))
7014 (org-float-time now))))
7015 ((= dcst ?d)
7016 (let ((end (save-excursion (outline-next-heading) (point))))
7017 (if (re-search-forward org-deadline-time-regexp end t)
7018 (org-time-string-to-seconds (match-string 1))
7019 (org-float-time now))))
7020 ((= dcst ?p)
7021 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7022 (string-to-char (match-string 2))
7023 org-default-priority))
7024 ((= dcst ?r)
7025 (or (org-entry-get nil property) ""))
7026 ((= dcst ?o)
7027 (if (looking-at org-complex-heading-regexp)
7028 (- 9999 (length (member (match-string 2)
7029 org-todo-keywords-1)))))
7030 ((= dcst ?f)
7031 (if getkey-func
7032 (progn
7033 (setq tmp (funcall getkey-func))
7034 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7035 tmp)
7036 (error "Invalid key function `%s'" getkey-func)))
7037 (t (error "Invalid sorting type `%c'" sorting-type)))))
7039 (cond
7040 ((= dcst ?a) 'string<)
7041 ((= dcst ?f) compare-func)
7042 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7043 (t nil)))))
7044 (run-hooks 'org-after-sorting-entries-or-items-hook)
7045 (message "Sorting entries...done")))
7047 (defun org-do-sort (table what &optional with-case sorting-type)
7048 "Sort TABLE of WHAT according to SORTING-TYPE.
7049 The user will be prompted for the SORTING-TYPE if the call to this
7050 function does not specify it. WHAT is only for the prompt, to indicate
7051 what is being sorted. The sorting key will be extracted from
7052 the car of the elements of the table.
7053 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7054 (unless sorting-type
7055 (message
7056 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7057 what)
7058 (setq sorting-type (read-char-exclusive)))
7059 (let ((dcst (downcase sorting-type))
7060 extractfun comparefun)
7061 ;; Define the appropriate functions
7062 (cond
7063 ((= dcst ?n)
7064 (setq extractfun 'string-to-number
7065 comparefun (if (= dcst sorting-type) '< '>)))
7066 ((= dcst ?a)
7067 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7068 (lambda(x) (downcase (org-sort-remove-invisible x))))
7069 comparefun (if (= dcst sorting-type)
7070 'string<
7071 (lambda (a b) (and (not (string< a b))
7072 (not (string= a b)))))))
7073 ((= dcst ?t)
7074 (setq extractfun
7075 (lambda (x)
7076 (if (or (string-match org-ts-regexp x)
7077 (string-match org-ts-regexp-both x))
7078 (org-float-time
7079 (org-time-string-to-time (match-string 0 x)))
7081 comparefun (if (= dcst sorting-type) '< '>)))
7082 (t (error "Invalid sorting type `%c'" sorting-type)))
7084 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7085 table)
7086 (lambda (a b) (funcall comparefun (car a) (car b))))))
7089 ;;; The orgstruct minor mode
7091 ;; Define a minor mode which can be used in other modes in order to
7092 ;; integrate the org-mode structure editing commands.
7094 ;; This is really a hack, because the org-mode structure commands use
7095 ;; keys which normally belong to the major mode. Here is how it
7096 ;; works: The minor mode defines all the keys necessary to operate the
7097 ;; structure commands, but wraps the commands into a function which
7098 ;; tests if the cursor is currently at a headline or a plain list
7099 ;; item. If that is the case, the structure command is used,
7100 ;; temporarily setting many Org-mode variables like regular
7101 ;; expressions for filling etc. However, when any of those keys is
7102 ;; used at a different location, function uses `key-binding' to look
7103 ;; up if the key has an associated command in another currently active
7104 ;; keymap (minor modes, major mode, global), and executes that
7105 ;; command. There might be problems if any of the keys is otherwise
7106 ;; used as a prefix key.
7108 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7109 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7110 ;; addresses this by checking explicitly for both bindings.
7112 (defvar orgstruct-mode-map (make-sparse-keymap)
7113 "Keymap for the minor `orgstruct-mode'.")
7115 (defvar org-local-vars nil
7116 "List of local variables, for use by `orgstruct-mode'")
7118 ;;;###autoload
7119 (define-minor-mode orgstruct-mode
7120 "Toggle the minor more `orgstruct-mode'.
7121 This mode is for using Org-mode structure commands in other modes.
7122 The following key behave as if Org-mode was active, if the cursor
7123 is on a headline, or on a plain list item (both in the definition
7124 of Org-mode).
7126 M-up Move entry/item up
7127 M-down Move entry/item down
7128 M-left Promote
7129 M-right Demote
7130 M-S-up Move entry/item up
7131 M-S-down Move entry/item down
7132 M-S-left Promote subtree
7133 M-S-right Demote subtree
7134 M-q Fill paragraph and items like in Org-mode
7135 C-c ^ Sort entries
7136 C-c - Cycle list bullet
7137 TAB Cycle item visibility
7138 M-RET Insert new heading/item
7139 S-M-RET Insert new TODO heading / Checkbox item
7140 C-c C-c Set tags / toggle checkbox"
7141 nil " OrgStruct" nil
7142 (org-load-modules-maybe)
7143 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7145 ;;;###autoload
7146 (defun turn-on-orgstruct ()
7147 "Unconditionally turn on `orgstruct-mode'."
7148 (orgstruct-mode 1))
7150 (defun orgstruct++-mode (&optional arg)
7151 "Toggle `orgstruct-mode', the enhanced version of it.
7152 In addition to setting orgstruct-mode, this also exports all indentation
7153 and autofilling variables from org-mode into the buffer. It will also
7154 recognize item context in multiline items.
7155 Note that turning off orgstruct-mode will *not* remove the
7156 indentation/paragraph settings. This can only be done by refreshing the
7157 major mode, for example with \\[normal-mode]."
7158 (interactive "P")
7159 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7160 (if (< arg 1)
7161 (orgstruct-mode -1)
7162 (orgstruct-mode 1)
7163 (let (var val)
7164 (mapc
7165 (lambda (x)
7166 (when (string-match
7167 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7168 (symbol-name (car x)))
7169 (setq var (car x) val (nth 1 x))
7170 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7171 org-local-vars)
7172 (org-set-local 'orgstruct-is-++ t))))
7174 (defvar orgstruct-is-++ nil
7175 "Is orgstruct-mode in ++ version in the current-buffer?")
7176 (make-variable-buffer-local 'orgstruct-is-++)
7178 ;;;###autoload
7179 (defun turn-on-orgstruct++ ()
7180 "Unconditionally turn on `orgstruct++-mode'."
7181 (orgstruct++-mode 1))
7183 (defun orgstruct-error ()
7184 "Error when there is no default binding for a structure key."
7185 (interactive)
7186 (error "This key has no function outside structure elements"))
7188 (defun orgstruct-setup ()
7189 "Setup orgstruct keymaps."
7190 (let ((nfunc 0)
7191 (bindings
7192 (list
7193 '([(meta up)] org-metaup)
7194 '([(meta down)] org-metadown)
7195 '([(meta left)] org-metaleft)
7196 '([(meta right)] org-metaright)
7197 '([(meta shift up)] org-shiftmetaup)
7198 '([(meta shift down)] org-shiftmetadown)
7199 '([(meta shift left)] org-shiftmetaleft)
7200 '([(meta shift right)] org-shiftmetaright)
7201 '([?\e (up)] org-metaup)
7202 '([?\e (down)] org-metadown)
7203 '([?\e (left)] org-metaleft)
7204 '([?\e (right)] org-metaright)
7205 '([?\e (shift up)] org-shiftmetaup)
7206 '([?\e (shift down)] org-shiftmetadown)
7207 '([?\e (shift left)] org-shiftmetaleft)
7208 '([?\e (shift right)] org-shiftmetaright)
7209 '([(shift up)] org-shiftup)
7210 '([(shift down)] org-shiftdown)
7211 '([(shift left)] org-shiftleft)
7212 '([(shift right)] org-shiftright)
7213 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7214 '("\M-q" fill-paragraph)
7215 '("\C-c^" org-sort)
7216 '("\C-c-" org-cycle-list-bullet)))
7217 elt key fun cmd)
7218 (while (setq elt (pop bindings))
7219 (setq nfunc (1+ nfunc))
7220 (setq key (org-key (car elt))
7221 fun (nth 1 elt)
7222 cmd (orgstruct-make-binding fun nfunc key))
7223 (org-defkey orgstruct-mode-map key cmd))
7225 ;; Special treatment needed for TAB and RET
7226 (org-defkey orgstruct-mode-map [(tab)]
7227 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7228 (org-defkey orgstruct-mode-map "\C-i"
7229 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7231 (org-defkey orgstruct-mode-map "\M-\C-m"
7232 (orgstruct-make-binding 'org-insert-heading 105
7233 "\M-\C-m" [(meta return)]))
7234 (org-defkey orgstruct-mode-map [(meta return)]
7235 (orgstruct-make-binding 'org-insert-heading 106
7236 [(meta return)] "\M-\C-m"))
7238 (org-defkey orgstruct-mode-map [(shift meta return)]
7239 (orgstruct-make-binding 'org-insert-todo-heading 107
7240 [(meta return)] "\M-\C-m"))
7242 (org-defkey orgstruct-mode-map "\e\C-m"
7243 (orgstruct-make-binding 'org-insert-heading 108
7244 "\e\C-m" [?\e (return)]))
7245 (org-defkey orgstruct-mode-map [?\e (return)]
7246 (orgstruct-make-binding 'org-insert-heading 109
7247 [?\e (return)] "\e\C-m"))
7248 (org-defkey orgstruct-mode-map [?\e (shift return)]
7249 (orgstruct-make-binding 'org-insert-todo-heading 110
7250 [?\e (return)] "\e\C-m"))
7252 (unless org-local-vars
7253 (setq org-local-vars (org-get-local-variables)))
7257 (defun orgstruct-make-binding (fun n &rest keys)
7258 "Create a function for binding in the structure minor mode.
7259 FUN is the command to call inside a table. N is used to create a unique
7260 command name. KEYS are keys that should be checked in for a command
7261 to execute outside of tables."
7262 (eval
7263 (list 'defun
7264 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7265 '(arg)
7266 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7267 "Outside of structure, run the binding of `"
7268 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7269 "'.")
7270 '(interactive "p")
7271 (list 'if
7272 `(org-context-p 'headline 'item
7273 (and orgstruct-is-++
7274 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7275 'item-body))
7276 (list 'org-run-like-in-org-mode (list 'quote fun))
7277 (list 'let '(orgstruct-mode)
7278 (list 'call-interactively
7279 (append '(or)
7280 (mapcar (lambda (k)
7281 (list 'key-binding k))
7282 keys)
7283 '('orgstruct-error))))))))
7285 (defun org-context-p (&rest contexts)
7286 "Check if local context is any of CONTEXTS.
7287 Possible values in the list of contexts are `table', `headline', and `item'."
7288 (let ((pos (point)))
7289 (goto-char (point-at-bol))
7290 (prog1 (or (and (memq 'table contexts)
7291 (looking-at "[ \t]*|"))
7292 (and (memq 'headline contexts)
7293 ;;????????? (looking-at "\\*+"))
7294 (looking-at outline-regexp))
7295 (and (memq 'item contexts)
7296 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7297 (and (memq 'item-body contexts)
7298 (org-in-item-p)))
7299 (goto-char pos))))
7301 (defun org-get-local-variables ()
7302 "Return a list of all local variables in an org-mode buffer."
7303 (let (varlist)
7304 (with-current-buffer (get-buffer-create "*Org tmp*")
7305 (erase-buffer)
7306 (org-mode)
7307 (setq varlist (buffer-local-variables)))
7308 (kill-buffer "*Org tmp*")
7309 (delq nil
7310 (mapcar
7311 (lambda (x)
7312 (setq x
7313 (if (symbolp x)
7314 (list x)
7315 (list (car x) (list 'quote (cdr x)))))
7316 (if (string-match
7317 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7318 (symbol-name (car x)))
7319 x nil))
7320 varlist))))
7322 ;;;###autoload
7323 (defun org-run-like-in-org-mode (cmd)
7324 "Run a command, pretending that the current buffer is in Org-mode.
7325 This will temporarily bind local variables that are typically bound in
7326 Org-mode to the values they have in Org-mode, and then interactively
7327 call CMD."
7328 (org-load-modules-maybe)
7329 (unless org-local-vars
7330 (setq org-local-vars (org-get-local-variables)))
7331 (eval (list 'let org-local-vars
7332 (list 'call-interactively (list 'quote cmd)))))
7334 ;;;; Archiving
7336 (defun org-get-category (&optional pos)
7337 "Get the category applying to position POS."
7338 (get-text-property (or pos (point)) 'org-category))
7340 (defun org-refresh-category-properties ()
7341 "Refresh category text properties in the buffer."
7342 (let ((def-cat (cond
7343 ((null org-category)
7344 (if buffer-file-name
7345 (file-name-sans-extension
7346 (file-name-nondirectory buffer-file-name))
7347 "???"))
7348 ((symbolp org-category) (symbol-name org-category))
7349 (t org-category)))
7350 beg end cat pos optionp)
7351 (org-unmodified
7352 (save-excursion
7353 (save-restriction
7354 (widen)
7355 (goto-char (point-min))
7356 (put-text-property (point) (point-max) 'org-category def-cat)
7357 (while (re-search-forward
7358 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7359 (setq pos (match-end 0)
7360 optionp (equal (char-after (match-beginning 0)) ?#)
7361 cat (org-trim (match-string 2)))
7362 (if optionp
7363 (setq beg (point-at-bol) end (point-max))
7364 (org-back-to-heading t)
7365 (setq beg (point) end (org-end-of-subtree t t)))
7366 (put-text-property beg end 'org-category cat)
7367 (goto-char pos)))))))
7370 ;;;; Link Stuff
7372 ;;; Link abbreviations
7374 (defun org-link-expand-abbrev (link)
7375 "Apply replacements as defined in `org-link-abbrev-alist."
7376 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7377 (let* ((key (match-string 1 link))
7378 (as (or (assoc key org-link-abbrev-alist-local)
7379 (assoc key org-link-abbrev-alist)))
7380 (tag (and (match-end 2) (match-string 3 link)))
7381 rpl)
7382 (if (not as)
7383 link
7384 (setq rpl (cdr as))
7385 (cond
7386 ((symbolp rpl) (funcall rpl tag))
7387 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7388 ((string-match "%h" rpl)
7389 (replace-match (url-hexify-string (or tag "")) t t rpl))
7390 (t (concat rpl tag)))))
7391 link))
7393 ;;; Storing and inserting links
7395 (defvar org-insert-link-history nil
7396 "Minibuffer history for links inserted with `org-insert-link'.")
7398 (defvar org-stored-links nil
7399 "Contains the links stored with `org-store-link'.")
7401 (defvar org-store-link-plist nil
7402 "Plist with info about the most recently link created with `org-store-link'.")
7404 (defvar org-link-protocols nil
7405 "Link protocols added to Org-mode using `org-add-link-type'.")
7407 (defvar org-store-link-functions nil
7408 "List of functions that are called to create and store a link.
7409 Each function will be called in turn until one returns a non-nil
7410 value. Each function should check if it is responsible for creating
7411 this link (for example by looking at the major mode).
7412 If not, it must exit and return nil.
7413 If yes, it should return a non-nil value after a calling
7414 `org-store-link-props' with a list of properties and values.
7415 Special properties are:
7417 :type The link prefix. like \"http\". This must be given.
7418 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7419 This is obligatory as well.
7420 :description Optional default description for the second pair
7421 of brackets in an Org-mode link. The user can still change
7422 this when inserting this link into an Org-mode buffer.
7424 In addition to these, any additional properties can be specified
7425 and then used in remember templates.")
7427 (defun org-add-link-type (type &optional follow export)
7428 "Add TYPE to the list of `org-link-types'.
7429 Re-compute all regular expressions depending on `org-link-types'
7431 FOLLOW and EXPORT are two functions.
7433 FOLLOW should take the link path as the single argument and do whatever
7434 is necessary to follow the link, for example find a file or display
7435 a mail message.
7437 EXPORT should format the link path for export to one of the export formats.
7438 It should be a function accepting three arguments:
7440 path the path of the link, the text after the prefix (like \"http:\")
7441 desc the description of the link, if any, nil if there was no description
7442 format the export format, a symbol like `html' or `latex'.
7444 The function may use the FORMAT information to return different values
7445 depending on the format. The return value will be put literally into
7446 the exported file.
7447 Org-mode has a built-in default for exporting links. If you are happy with
7448 this default, there is no need to define an export function for the link
7449 type. For a simple example of an export function, see `org-bbdb.el'."
7450 (add-to-list 'org-link-types type t)
7451 (org-make-link-regexps)
7452 (if (assoc type org-link-protocols)
7453 (setcdr (assoc type org-link-protocols) (list follow export))
7454 (push (list type follow export) org-link-protocols)))
7456 (defvar org-agenda-buffer-name)
7458 ;;;###autoload
7459 (defun org-store-link (arg)
7460 "\\<org-mode-map>Store an org-link to the current location.
7461 This link is added to `org-stored-links' and can later be inserted
7462 into an org-buffer with \\[org-insert-link].
7464 For some link types, a prefix arg is interpreted:
7465 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7466 For file links, arg negates `org-context-in-file-links'."
7467 (interactive "P")
7468 (org-load-modules-maybe)
7469 (setq org-store-link-plist nil) ; reset
7470 (let ((outline-regexp (org-get-limited-outline-regexp))
7471 link cpltxt desc description search txt custom-id)
7472 (cond
7474 ((run-hook-with-args-until-success 'org-store-link-functions)
7475 (setq link (plist-get org-store-link-plist :link)
7476 desc (or (plist-get org-store-link-plist :description) link)))
7478 ((equal (buffer-name) "*Org Edit Src Example*")
7479 (let (label gc)
7480 (while (or (not label)
7481 (save-excursion
7482 (save-restriction
7483 (widen)
7484 (goto-char (point-min))
7485 (re-search-forward
7486 (regexp-quote (format org-coderef-label-format label))
7487 nil t))))
7488 (when label (message "Label exists already") (sit-for 2))
7489 (setq label (read-string "Code line label: " label)))
7490 (end-of-line 1)
7491 (setq link (format org-coderef-label-format label))
7492 (setq gc (- 79 (length link)))
7493 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7494 (insert link)
7495 (setq link (concat "(" label ")") desc nil)))
7497 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7498 ;; We are in the agenda, link to referenced location
7499 (let ((m (or (get-text-property (point) 'org-hd-marker)
7500 (get-text-property (point) 'org-marker))))
7501 (when m
7502 (org-with-point-at m
7503 (call-interactively 'org-store-link)))))
7505 ((eq major-mode 'calendar-mode)
7506 (let ((cd (calendar-cursor-to-date)))
7507 (setq link
7508 (format-time-string
7509 (car org-time-stamp-formats)
7510 (apply 'encode-time
7511 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7512 nil nil nil))))
7513 (org-store-link-props :type "calendar" :date cd)))
7515 ((eq major-mode 'w3-mode)
7516 (setq cpltxt (if (and (buffer-name)
7517 (not (string-match "Untitled" (buffer-name))))
7518 (buffer-name)
7519 (url-view-url t))
7520 link (org-make-link (url-view-url t)))
7521 (org-store-link-props :type "w3" :url (url-view-url t)))
7523 ((eq major-mode 'w3m-mode)
7524 (setq cpltxt (or w3m-current-title w3m-current-url)
7525 link (org-make-link w3m-current-url))
7526 (org-store-link-props :type "w3m" :url (url-view-url t)))
7528 ((setq search (run-hook-with-args-until-success
7529 'org-create-file-search-functions))
7530 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7531 "::" search))
7532 (setq cpltxt (or description link)))
7534 ((eq major-mode 'image-mode)
7535 (setq cpltxt (concat "file:"
7536 (abbreviate-file-name buffer-file-name))
7537 link (org-make-link cpltxt))
7538 (org-store-link-props :type "image" :file buffer-file-name))
7540 ((eq major-mode 'dired-mode)
7541 ;; link to the file in the current line
7542 (setq cpltxt (concat "file:"
7543 (abbreviate-file-name
7544 (expand-file-name
7545 (dired-get-filename nil t))))
7546 link (org-make-link cpltxt)))
7548 ((and buffer-file-name (org-mode-p))
7549 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7550 (cond
7551 ((org-in-regexp "<<\\(.*?\\)>>")
7552 (setq cpltxt
7553 (concat "file:"
7554 (abbreviate-file-name buffer-file-name)
7555 "::" (match-string 1))
7556 link (org-make-link cpltxt)))
7557 ((and (featurep 'org-id)
7558 (or (eq org-link-to-org-use-id t)
7559 (and (eq org-link-to-org-use-id 'create-if-interactive)
7560 (interactive-p))
7561 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7562 (interactive-p)
7563 (not custom-id))
7564 (and org-link-to-org-use-id
7565 (condition-case nil
7566 (org-entry-get nil "ID")
7567 (error nil)))))
7568 ;; We can make a link using the ID.
7569 (setq link (condition-case nil
7570 (prog1 (org-id-store-link)
7571 (setq desc (plist-get org-store-link-plist
7572 :description)))
7573 (error
7574 ;; probably before first headline, link to file only
7575 (concat "file:"
7576 (abbreviate-file-name buffer-file-name))))))
7578 ;; Just link to current headline
7579 (setq cpltxt (concat "file:"
7580 (abbreviate-file-name buffer-file-name)))
7581 ;; Add a context search string
7582 (when (org-xor org-context-in-file-links arg)
7583 (setq txt (cond
7584 ((org-on-heading-p) nil)
7585 ((org-region-active-p)
7586 (buffer-substring (region-beginning) (region-end)))
7587 (t nil)))
7588 (when (or (null txt) (string-match "\\S-" txt))
7589 (setq cpltxt
7590 (concat cpltxt "::"
7591 (condition-case nil
7592 (org-make-org-heading-search-string txt)
7593 (error "")))
7594 desc (or (nth 4 (ignore-errors
7595 (org-heading-components))) "NONE"))))
7596 (if (string-match "::\\'" cpltxt)
7597 (setq cpltxt (substring cpltxt 0 -2)))
7598 (setq link (org-make-link cpltxt)))))
7600 ((buffer-file-name (buffer-base-buffer))
7601 ;; Just link to this file here.
7602 (setq cpltxt (concat "file:"
7603 (abbreviate-file-name
7604 (buffer-file-name (buffer-base-buffer)))))
7605 ;; Add a context string
7606 (when (org-xor org-context-in-file-links arg)
7607 (setq txt (if (org-region-active-p)
7608 (buffer-substring (region-beginning) (region-end))
7609 (buffer-substring (point-at-bol) (point-at-eol))))
7610 ;; Only use search option if there is some text.
7611 (when (string-match "\\S-" txt)
7612 (setq cpltxt
7613 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7614 desc "NONE")))
7615 (setq link (org-make-link cpltxt)))
7617 ((interactive-p)
7618 (error "Cannot link to a buffer which is not visiting a file"))
7620 (t (setq link nil)))
7622 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7623 (setq link (or link cpltxt)
7624 desc (or desc cpltxt))
7625 (if (equal desc "NONE") (setq desc nil))
7627 (if (and (or (interactive-p) executing-kbd-macro) link)
7628 (progn
7629 (setq org-stored-links
7630 (cons (list link desc) org-stored-links))
7631 (message "Stored: %s" (or desc link))
7632 (when custom-id
7633 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7634 "::#" custom-id))
7635 (setq org-stored-links
7636 (cons (list link desc) org-stored-links))))
7637 (and link (org-make-link-string link desc)))))
7639 (defun org-store-link-props (&rest plist)
7640 "Store link properties, extract names and addresses."
7641 (let (x adr)
7642 (when (setq x (plist-get plist :from))
7643 (setq adr (mail-extract-address-components x))
7644 (setq plist (plist-put plist :fromname (car adr)))
7645 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7646 (when (setq x (plist-get plist :to))
7647 (setq adr (mail-extract-address-components x))
7648 (setq plist (plist-put plist :toname (car adr)))
7649 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7650 (let ((from (plist-get plist :from))
7651 (to (plist-get plist :to)))
7652 (when (and from to org-from-is-user-regexp)
7653 (setq plist
7654 (plist-put plist :fromto
7655 (if (string-match org-from-is-user-regexp from)
7656 (concat "to %t")
7657 (concat "from %f"))))))
7658 (setq org-store-link-plist plist))
7660 (defun org-add-link-props (&rest plist)
7661 "Add these properties to the link property list."
7662 (let (key value)
7663 (while plist
7664 (setq key (pop plist) value (pop plist))
7665 (setq org-store-link-plist
7666 (plist-put org-store-link-plist key value)))))
7668 (defun org-email-link-description (&optional fmt)
7669 "Return the description part of an email link.
7670 This takes information from `org-store-link-plist' and formats it
7671 according to FMT (default from `org-email-link-description-format')."
7672 (setq fmt (or fmt org-email-link-description-format))
7673 (let* ((p org-store-link-plist)
7674 (to (plist-get p :toaddress))
7675 (from (plist-get p :fromaddress))
7676 (table
7677 (list
7678 (cons "%c" (plist-get p :fromto))
7679 (cons "%F" (plist-get p :from))
7680 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7681 (cons "%T" (plist-get p :to))
7682 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7683 (cons "%s" (plist-get p :subject))
7684 (cons "%m" (plist-get p :message-id)))))
7685 (when (string-match "%c" fmt)
7686 ;; Check if the user wrote this message
7687 (if (and org-from-is-user-regexp from to
7688 (save-match-data (string-match org-from-is-user-regexp from)))
7689 (setq fmt (replace-match "to %t" t t fmt))
7690 (setq fmt (replace-match "from %f" t t fmt))))
7691 (org-replace-escapes fmt table)))
7693 (defun org-make-org-heading-search-string (&optional string heading)
7694 "Make search string for STRING or current headline."
7695 (interactive)
7696 (let ((s (or string (org-get-heading))))
7697 (unless (and string (not heading))
7698 ;; We are using a headline, clean up garbage in there.
7699 (if (string-match org-todo-regexp s)
7700 (setq s (replace-match "" t t s)))
7701 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7702 (setq s (replace-match "" t t s)))
7703 (setq s (org-trim s))
7704 (if (string-match (concat "^\\(" org-quote-string "\\|"
7705 org-comment-string "\\)") s)
7706 (setq s (replace-match "" t t s)))
7707 (while (string-match org-ts-regexp s)
7708 (setq s (replace-match "" t t s))))
7709 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7710 (setq s (replace-match " " t t s)))
7711 (or string (setq s (concat "*" s))) ; Add * for headlines
7712 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7714 (defun org-make-link (&rest strings)
7715 "Concatenate STRINGS."
7716 (apply 'concat strings))
7718 (defun org-make-link-string (link &optional description)
7719 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7720 (unless (string-match "\\S-" link)
7721 (error "Empty link"))
7722 (when (and description
7723 (stringp description)
7724 (not (string-match "\\S-" description)))
7725 (setq description nil))
7726 (when (stringp description)
7727 ;; Remove brackets from the description, they are fatal.
7728 (while (string-match "\\[" description)
7729 (setq description (replace-match "{" t t description)))
7730 (while (string-match "\\]" description)
7731 (setq description (replace-match "}" t t description))))
7732 (when (equal (org-link-escape link) description)
7733 ;; No description needed, it is identical
7734 (setq description nil))
7735 (when (and (not description)
7736 (not (equal link (org-link-escape link))))
7737 (setq description (org-extract-attributes link)))
7738 (concat "[[" (org-link-escape link) "]"
7739 (if description (concat "[" description "]") "")
7740 "]"))
7742 (defconst org-link-escape-chars
7743 '((?\ . "%20")
7744 (?\[ . "%5B")
7745 (?\] . "%5D")
7746 (?\340 . "%E0") ; `a
7747 (?\342 . "%E2") ; ^a
7748 (?\347 . "%E7") ; ,c
7749 (?\350 . "%E8") ; `e
7750 (?\351 . "%E9") ; 'e
7751 (?\352 . "%EA") ; ^e
7752 (?\356 . "%EE") ; ^i
7753 (?\364 . "%F4") ; ^o
7754 (?\371 . "%F9") ; `u
7755 (?\373 . "%FB") ; ^u
7756 (?\; . "%3B")
7757 (?? . "%3F")
7758 (?= . "%3D")
7759 (?+ . "%2B")
7761 "Association list of escapes for some characters problematic in links.
7762 This is the list that is used for internal purposes.")
7764 (defvar org-url-encoding-use-url-hexify nil)
7766 (defconst org-link-escape-chars-browser
7767 '((?\ . "%20")) ; 32 for the SPC char
7768 "Association list of escapes for some characters problematic in links.
7769 This is the list that is used before handing over to the browser.")
7771 (defun org-link-escape (text &optional table)
7772 "Escape characters in TEXT that are problematic for links."
7773 (if org-url-encoding-use-url-hexify
7774 (url-hexify-string text)
7775 (setq table (or table org-link-escape-chars))
7776 (when text
7777 (let ((re (mapconcat (lambda (x) (regexp-quote
7778 (char-to-string (car x))))
7779 table "\\|")))
7780 (while (string-match re text)
7781 (setq text
7782 (replace-match
7783 (cdr (assoc (string-to-char (match-string 0 text))
7784 table))
7785 t t text)))
7786 text))))
7788 (defun org-link-unescape (text &optional table)
7789 "Reverse the action of `org-link-escape'."
7790 (if org-url-encoding-use-url-hexify
7791 (url-unhex-string text)
7792 (setq table (or table org-link-escape-chars))
7793 (when text
7794 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7795 table "\\|")))
7796 (while (string-match re text)
7797 (setq text
7798 (replace-match
7799 (char-to-string (car (rassoc (match-string 0 text) table)))
7800 t t text)))
7801 text))))
7803 (defun org-xor (a b)
7804 "Exclusive or."
7805 (if a (not b) b))
7807 (defun org-fixup-message-id-for-http (s)
7808 "Replace special characters in a message id, so it can be used in an http query."
7809 (while (string-match "<" s)
7810 (setq s (replace-match "%3C" t t s)))
7811 (while (string-match ">" s)
7812 (setq s (replace-match "%3E" t t s)))
7813 (while (string-match "@" s)
7814 (setq s (replace-match "%40" t t s)))
7817 ;;;###autoload
7818 (defun org-insert-link-global ()
7819 "Insert a link like Org-mode does.
7820 This command can be called in any mode to insert a link in Org-mode syntax."
7821 (interactive)
7822 (org-load-modules-maybe)
7823 (org-run-like-in-org-mode 'org-insert-link))
7825 (defun org-insert-link (&optional complete-file link-location)
7826 "Insert a link. At the prompt, enter the link.
7828 Completion can be used to insert any of the link protocol prefixes like
7829 http or ftp in use.
7831 The history can be used to select a link previously stored with
7832 `org-store-link'. When the empty string is entered (i.e. if you just
7833 press RET at the prompt), the link defaults to the most recently
7834 stored link. As SPC triggers completion in the minibuffer, you need to
7835 use M-SPC or C-q SPC to force the insertion of a space character.
7837 You will also be prompted for a description, and if one is given, it will
7838 be displayed in the buffer instead of the link.
7840 If there is already a link at point, this command will allow you to edit link
7841 and description parts.
7843 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7844 be selected using completion. The path to the file will be relative to the
7845 current directory if the file is in the current directory or a subdirectory.
7846 Otherwise, the link will be the absolute path as completed in the minibuffer
7847 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7848 option `org-link-file-path-type'.
7850 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7851 the current directory or below.
7853 With three \\[universal-argument] prefixes, negate the meaning of
7854 `org-keep-stored-link-after-insertion'.
7856 If `org-make-link-description-function' is non-nil, this function will be
7857 called with the link target, and the result will be the default
7858 link description.
7860 If the LINK-LOCATION parameter is non-nil, this value will be
7861 used as the link location instead of reading one interactively."
7862 (interactive "P")
7863 (let* ((wcf (current-window-configuration))
7864 (region (if (org-region-active-p)
7865 (buffer-substring (region-beginning) (region-end))))
7866 (remove (and region (list (region-beginning) (region-end))))
7867 (desc region)
7868 tmphist ; byte-compile incorrectly complains about this
7869 (link link-location)
7870 entry file all-prefixes)
7871 (cond
7872 (link-location) ; specified by arg, just use it.
7873 ((org-in-regexp org-bracket-link-regexp 1)
7874 ;; We do have a link at point, and we are going to edit it.
7875 (setq remove (list (match-beginning 0) (match-end 0)))
7876 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7877 (setq link (read-string "Link: "
7878 (org-link-unescape
7879 (org-match-string-no-properties 1)))))
7880 ((or (org-in-regexp org-angle-link-re)
7881 (org-in-regexp org-plain-link-re))
7882 ;; Convert to bracket link
7883 (setq remove (list (match-beginning 0) (match-end 0))
7884 link (read-string "Link: "
7885 (org-remove-angle-brackets (match-string 0)))))
7886 ((member complete-file '((4) (16)))
7887 ;; Completing read for file names.
7888 (setq link (org-file-complete-link complete-file)))
7890 ;; Read link, with completion for stored links.
7891 (with-output-to-temp-buffer "*Org Links*"
7892 (princ "Insert a link.
7893 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7894 (when org-stored-links
7895 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7896 (princ (mapconcat
7897 (lambda (x)
7898 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7899 (reverse org-stored-links) "\n"))))
7900 (let ((cw (selected-window)))
7901 (select-window (get-buffer-window "*Org Links*"))
7902 (setq truncate-lines t)
7903 (unless (pos-visible-in-window-p (point-max))
7904 (org-fit-window-to-buffer))
7905 (and (window-live-p cw) (select-window cw)))
7906 ;; Fake a link history, containing the stored links.
7907 (setq tmphist (append (mapcar 'car org-stored-links)
7908 org-insert-link-history))
7909 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7910 (mapcar 'car org-link-abbrev-alist)
7911 org-link-types))
7912 (unwind-protect
7913 (progn
7914 (setq link
7915 (let ((org-completion-use-ido nil)
7916 (org-completion-use-iswitchb nil))
7917 (org-completing-read
7918 "Link: "
7919 (append
7920 (mapcar (lambda (x) (list (concat x ":")))
7921 all-prefixes)
7922 (mapcar 'car org-stored-links))
7923 nil nil nil
7924 'tmphist
7925 (car (car org-stored-links)))))
7926 (if (or (member link all-prefixes)
7927 (and (equal ":" (substring link -1))
7928 (member (substring link 0 -1) all-prefixes)
7929 (setq link (substring link 0 -1))))
7930 (setq link (org-link-try-special-completion link))))
7931 (set-window-configuration wcf)
7932 (kill-buffer "*Org Links*"))
7933 (setq entry (assoc link org-stored-links))
7934 (or entry (push link org-insert-link-history))
7935 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7936 (not org-keep-stored-link-after-insertion))
7937 (setq org-stored-links (delq (assoc link org-stored-links)
7938 org-stored-links)))
7939 (setq desc (or desc (nth 1 entry)))))
7941 (if (string-match org-plain-link-re link)
7942 ;; URL-like link, normalize the use of angular brackets.
7943 (setq link (org-make-link (org-remove-angle-brackets link))))
7945 ;; Check if we are linking to the current file with a search option
7946 ;; If yes, simplify the link by using only the search option.
7947 (when (and buffer-file-name
7948 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7949 (let* ((path (match-string 1 link))
7950 (case-fold-search nil)
7951 (search (match-string 2 link)))
7952 (save-match-data
7953 (if (equal (file-truename buffer-file-name) (file-truename path))
7954 ;; We are linking to this same file, with a search option
7955 (setq link search)))))
7957 ;; Check if we can/should use a relative path. If yes, simplify the link
7958 (when (string-match "^file:\\(.*\\)" link)
7959 (let* ((path (match-string 1 link))
7960 (origpath path)
7961 (case-fold-search nil))
7962 (cond
7963 ((or (eq org-link-file-path-type 'absolute)
7964 (equal complete-file '(16)))
7965 (setq path (abbreviate-file-name (expand-file-name path))))
7966 ((eq org-link-file-path-type 'noabbrev)
7967 (setq path (expand-file-name path)))
7968 ((eq org-link-file-path-type 'relative)
7969 (setq path (file-relative-name path)))
7971 (save-match-data
7972 (if (string-match (concat "^" (regexp-quote
7973 (file-name-as-directory
7974 (expand-file-name "."))))
7975 (expand-file-name path))
7976 ;; We are linking a file with relative path name.
7977 (setq path (substring (expand-file-name path)
7978 (match-end 0)))
7979 (setq path (abbreviate-file-name (expand-file-name path)))))))
7980 (setq link (concat "file:" path))
7981 (if (equal desc origpath)
7982 (setq desc path))))
7984 (if org-make-link-description-function
7985 (setq desc (funcall org-make-link-description-function link desc)))
7987 (setq desc (read-string "Description: " desc))
7988 (unless (string-match "\\S-" desc) (setq desc nil))
7989 (if remove (apply 'delete-region remove))
7990 (insert (org-make-link-string link desc))))
7992 (defun org-link-try-special-completion (type)
7993 "If there is completion support for link type TYPE, offer it."
7994 (let ((fun (intern (concat "org-" type "-complete-link"))))
7995 (if (functionp fun)
7996 (funcall fun)
7997 (read-string "Link (no completion support): " (concat type ":")))))
7999 (defun org-file-complete-link (&optional arg)
8000 "Create a file link using completion."
8001 (let (file link)
8002 (setq file (read-file-name "File: "))
8003 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8004 (pwd1 (file-name-as-directory (abbreviate-file-name
8005 (expand-file-name ".")))))
8006 (cond
8007 ((equal arg '(16))
8008 (setq link (org-make-link
8009 "file:"
8010 (abbreviate-file-name (expand-file-name file)))))
8011 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8012 (setq link (org-make-link "file:" (match-string 1 file))))
8013 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8014 (expand-file-name file))
8015 (setq link (org-make-link
8016 "file:" (match-string 1 (expand-file-name file)))))
8017 (t (setq link (org-make-link "file:" file)))))
8018 link))
8020 (defun org-completing-read (&rest args)
8021 "Completing-read with SPACE being a normal character."
8022 (let ((minibuffer-local-completion-map
8023 (copy-keymap minibuffer-local-completion-map)))
8024 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8025 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8026 (apply 'org-icompleting-read args)))
8028 (defun org-completing-read-no-i (&rest args)
8029 (let (org-completion-use-ido org-completion-use-iswitchb)
8030 (apply 'org-completing-read args)))
8032 (defun org-iswitchb-completing-read (prompt choices &rest args)
8033 "Use iswitch as a completing-read replacement to choose from choices.
8034 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8035 from."
8036 (let* ((iswitchb-use-virtual-buffers nil)
8037 (iswitchb-make-buflist-hook
8038 (lambda ()
8039 (setq iswitchb-temp-buflist choices))))
8040 (iswitchb-read-buffer prompt)))
8042 (defun org-icompleting-read (&rest args)
8043 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8044 (org-without-partial-completion
8045 (if (and org-completion-use-ido
8046 (fboundp 'ido-completing-read)
8047 (boundp 'ido-mode) ido-mode
8048 (listp (second args)))
8049 (let ((ido-enter-matching-directory nil))
8050 (apply 'ido-completing-read (concat (car args))
8051 (if (consp (car (nth 1 args)))
8052 (mapcar (lambda (x) (car x)) (nth 1 args))
8053 (nth 1 args))
8054 (cddr args)))
8055 (if (and org-completion-use-iswitchb
8056 (boundp 'iswitchb-mode) iswitchb-mode
8057 (listp (second args)))
8058 (apply 'org-iswitchb-completing-read (concat (car args))
8059 (if (consp (car (nth 1 args)))
8060 (mapcar (lambda (x) (car x)) (nth 1 args))
8061 (nth 1 args))
8062 (cddr args))
8063 (apply 'completing-read args)))))
8065 (defun org-extract-attributes (s)
8066 "Extract the attributes cookie from a string and set as text property."
8067 (let (a attr (start 0) key value)
8068 (save-match-data
8069 (when (string-match "{{\\([^}]+\\)}}$" s)
8070 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8071 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8072 (setq key (match-string 1 a) value (match-string 2 a)
8073 start (match-end 0)
8074 attr (plist-put attr (intern key) value))))
8075 (org-add-props s nil 'org-attr attr))
8078 (defun org-extract-attributes-from-string (tag)
8079 (let (key value attr)
8080 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8081 (setq key (match-string 1 tag) value (match-string 2 tag)
8082 tag (replace-match "" t t tag)
8083 attr (plist-put attr (intern key) value)))
8084 (cons tag attr)))
8086 (defun org-attributes-to-string (plist)
8087 "Format a property list into an HTML attribute list."
8088 (let ((s "") key value)
8089 (while plist
8090 (setq key (pop plist) value (pop plist))
8091 (and value
8092 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8095 ;;; Opening/following a link
8097 (defvar org-link-search-failed nil)
8099 (defun org-next-link ()
8100 "Move forward to the next link.
8101 If the link is in hidden text, expose it."
8102 (interactive)
8103 (when (and org-link-search-failed (eq this-command last-command))
8104 (goto-char (point-min))
8105 (message "Link search wrapped back to beginning of buffer"))
8106 (setq org-link-search-failed nil)
8107 (let* ((pos (point))
8108 (ct (org-context))
8109 (a (assoc :link ct)))
8110 (if a (goto-char (nth 2 a)))
8111 (if (re-search-forward org-any-link-re nil t)
8112 (progn
8113 (goto-char (match-beginning 0))
8114 (if (org-invisible-p) (org-show-context)))
8115 (goto-char pos)
8116 (setq org-link-search-failed t)
8117 (error "No further link found"))))
8119 (defun org-previous-link ()
8120 "Move backward to the previous link.
8121 If the link is in hidden text, expose it."
8122 (interactive)
8123 (when (and org-link-search-failed (eq this-command last-command))
8124 (goto-char (point-max))
8125 (message "Link search wrapped back to end of buffer"))
8126 (setq org-link-search-failed nil)
8127 (let* ((pos (point))
8128 (ct (org-context))
8129 (a (assoc :link ct)))
8130 (if a (goto-char (nth 1 a)))
8131 (if (re-search-backward org-any-link-re nil t)
8132 (progn
8133 (goto-char (match-beginning 0))
8134 (if (org-invisible-p) (org-show-context)))
8135 (goto-char pos)
8136 (setq org-link-search-failed t)
8137 (error "No further link found"))))
8139 (defun org-translate-link (s)
8140 "Translate a link string if a translation function has been defined."
8141 (if (and org-link-translation-function
8142 (fboundp org-link-translation-function)
8143 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8144 (progn
8145 (setq s (funcall org-link-translation-function
8146 (match-string 1) (match-string 2)))
8147 (concat (car s) ":" (cdr s)))
8150 (defun org-translate-link-from-planner (type path)
8151 "Translate a link from Emacs Planner syntax so that Org can follow it.
8152 This is still an experimental function, your mileage may vary."
8153 (cond
8154 ((member type '("http" "https" "news" "ftp"))
8155 ;; standard Internet links are the same.
8156 nil)
8157 ((and (equal type "irc") (string-match "^//" path))
8158 ;; Planner has two / at the beginning of an irc link, we have 1.
8159 ;; We should have zero, actually....
8160 (setq path (substring path 1)))
8161 ((and (equal type "lisp") (string-match "^/" path))
8162 ;; Planner has a slash, we do not.
8163 (setq type "elisp" path (substring path 1)))
8164 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8165 ;; A typical message link. Planner has the id after the final slash,
8166 ;; we separate it with a hash mark
8167 (setq path (concat (match-string 1 path) "#"
8168 (org-remove-angle-brackets (match-string 2 path)))))
8170 (cons type path))
8172 (defun org-find-file-at-mouse (ev)
8173 "Open file link or URL at mouse."
8174 (interactive "e")
8175 (mouse-set-point ev)
8176 (org-open-at-point 'in-emacs))
8178 (defun org-open-at-mouse (ev)
8179 "Open file link or URL at mouse."
8180 (interactive "e")
8181 (mouse-set-point ev)
8182 (if (eq major-mode 'org-agenda-mode)
8183 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8184 (org-open-at-point))
8186 (defvar org-window-config-before-follow-link nil
8187 "The window configuration before following a link.
8188 This is saved in case the need arises to restore it.")
8190 (defvar org-open-link-marker (make-marker)
8191 "Marker pointing to the location where `org-open-at-point; was called.")
8193 ;;;###autoload
8194 (defun org-open-at-point-global ()
8195 "Follow a link like Org-mode does.
8196 This command can be called in any mode to follow a link that has
8197 Org-mode syntax."
8198 (interactive)
8199 (org-run-like-in-org-mode 'org-open-at-point))
8201 ;;;###autoload
8202 (defun org-open-link-from-string (s &optional arg reference-buffer)
8203 "Open a link in the string S, as if it was in Org-mode."
8204 (interactive "sLink: \nP")
8205 (let ((reference-buffer (or reference-buffer (current-buffer))))
8206 (with-temp-buffer
8207 (let ((org-inhibit-startup t))
8208 (org-mode)
8209 (insert s)
8210 (goto-char (point-min))
8211 (org-open-at-point arg reference-buffer)))))
8213 (defun org-open-at-point (&optional in-emacs reference-buffer)
8214 "Open link at or after point.
8215 If there is no link at point, this function will search forward up to
8216 the end of the current line.
8217 Normally, files will be opened by an appropriate application. If the
8218 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8219 With a double prefix argument, try to open outside of Emacs, in the
8220 application the system uses for this file type."
8221 (interactive "P")
8222 (org-load-modules-maybe)
8223 (move-marker org-open-link-marker (point))
8224 (setq org-window-config-before-follow-link (current-window-configuration))
8225 (org-remove-occur-highlights nil nil t)
8226 (cond
8227 ((and (org-on-heading-p)
8228 (not (org-in-regexp
8229 (concat org-plain-link-re "\\|"
8230 org-bracket-link-regexp "\\|"
8231 org-angle-link-re "\\|"
8232 "[ \t]:[^ \t\n]+:[ \t]*$"))))
8233 (or (org-offer-links-in-entry in-emacs)
8234 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8235 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8236 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8237 (org-footnote-action))
8239 (let (type path link line search (pos (point)))
8240 (catch 'match
8241 (save-excursion
8242 (skip-chars-forward "^]\n\r")
8243 (when (org-in-regexp org-bracket-link-regexp)
8244 (setq link (org-extract-attributes
8245 (org-link-unescape (org-match-string-no-properties 1))))
8246 (while (string-match " *\n *" link)
8247 (setq link (replace-match " " t t link)))
8248 (setq link (org-link-expand-abbrev link))
8249 (cond
8250 ((or (file-name-absolute-p link)
8251 (string-match "^\\.\\.?/" link))
8252 (setq type "file" path link))
8253 ((string-match org-link-re-with-space3 link)
8254 (setq type (match-string 1 link) path (match-string 2 link)))
8255 (t (setq type "thisfile" path link)))
8256 (throw 'match t)))
8258 (when (get-text-property (point) 'org-linked-text)
8259 (setq type "thisfile"
8260 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8261 (1+ (point)) (point))
8262 path (buffer-substring
8263 (previous-single-property-change pos 'org-linked-text)
8264 (next-single-property-change pos 'org-linked-text)))
8265 (throw 'match t))
8267 (save-excursion
8268 (when (or (org-in-regexp org-angle-link-re)
8269 (org-in-regexp org-plain-link-re))
8270 (setq type (match-string 1) path (match-string 2))
8271 (throw 'match t)))
8272 (save-excursion
8273 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8274 (setq type "tags"
8275 path (match-string 1))
8276 (while (string-match ":" path)
8277 (setq path (replace-match "+" t t path)))
8278 (throw 'match t)))
8279 (when (org-in-regexp "<\\([^><\n]+\\)>")
8280 (setq type "tree-match"
8281 path (match-string 1))
8282 (throw 'match t)))
8283 (unless path
8284 (error "No link found"))
8286 ;; switch back to reference buffer
8287 ;; needed when if called in a temporary buffer through
8288 ;; org-open-link-from-string
8289 (with-current-buffer (or reference-buffer (current-buffer))
8291 ;; Remove any trailing spaces in path
8292 (if (string-match " +\\'" path)
8293 (setq path (replace-match "" t t path)))
8294 (if (and org-link-translation-function
8295 (fboundp org-link-translation-function))
8296 ;; Check if we need to translate the link
8297 (let ((tmp (funcall org-link-translation-function type path)))
8298 (setq type (car tmp) path (cdr tmp))))
8300 (cond
8302 ((assoc type org-link-protocols)
8303 (funcall (nth 1 (assoc type org-link-protocols)) path))
8305 ((equal type "mailto")
8306 (let ((cmd (car org-link-mailto-program))
8307 (args (cdr org-link-mailto-program)) args1
8308 (address path) (subject "") a)
8309 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8310 (setq address (match-string 1 path)
8311 subject (org-link-escape (match-string 2 path))))
8312 (while args
8313 (cond
8314 ((not (stringp (car args))) (push (pop args) args1))
8315 (t (setq a (pop args))
8316 (if (string-match "%a" a)
8317 (setq a (replace-match address t t a)))
8318 (if (string-match "%s" a)
8319 (setq a (replace-match subject t t a)))
8320 (push a args1))))
8321 (apply cmd (nreverse args1))))
8323 ((member type '("http" "https" "ftp" "news"))
8324 (browse-url (concat type ":" (org-link-escape
8325 path org-link-escape-chars-browser))))
8327 ((member type '("message"))
8328 (browse-url (concat type ":" path)))
8330 ((string= type "tags")
8331 (org-tags-view in-emacs path))
8332 ((string= type "thisfile")
8333 (if in-emacs
8334 (switch-to-buffer-other-window
8335 (org-get-buffer-for-internal-link (current-buffer)))
8336 (org-mark-ring-push))
8337 (let ((cmd `(org-link-search
8338 ,path
8339 ,(cond ((equal in-emacs '(4)) 'occur)
8340 ((equal in-emacs '(16)) 'org-occur)
8341 (t nil))
8342 ,pos)))
8343 (condition-case nil (eval cmd)
8344 (error (progn (widen) (eval cmd))))))
8346 ((string= type "tree-match")
8347 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8349 ((string= type "file")
8350 (if (string-match "::\\([0-9]+\\)\\'" path)
8351 (setq line (string-to-number (match-string 1 path))
8352 path (substring path 0 (match-beginning 0)))
8353 (if (string-match "::\\(.+\\)\\'" path)
8354 (setq search (match-string 1 path)
8355 path (substring path 0 (match-beginning 0)))))
8356 (if (string-match "[*?{]" (file-name-nondirectory path))
8357 (dired path)
8358 (org-open-file path in-emacs line search)))
8360 ((string= type "news")
8361 (require 'org-gnus)
8362 (org-gnus-follow-link path))
8364 ((string= type "shell")
8365 (let ((cmd path))
8366 (if (or (not org-confirm-shell-link-function)
8367 (funcall org-confirm-shell-link-function
8368 (format "Execute \"%s\" in shell? "
8369 (org-add-props cmd nil
8370 'face 'org-warning))))
8371 (progn
8372 (message "Executing %s" cmd)
8373 (shell-command cmd))
8374 (error "Abort"))))
8376 ((string= type "elisp")
8377 (let ((cmd path))
8378 (if (or (not org-confirm-elisp-link-function)
8379 (funcall org-confirm-elisp-link-function
8380 (format "Execute \"%s\" as elisp? "
8381 (org-add-props cmd nil
8382 'face 'org-warning))))
8383 (message "%s => %s" cmd
8384 (if (equal (string-to-char cmd) ?\()
8385 (eval (read cmd))
8386 (call-interactively (read cmd))))
8387 (error "Abort"))))
8390 (browse-url-at-point)))))))
8391 (move-marker org-open-link-marker nil)
8392 (run-hook-with-args 'org-follow-link-hook))
8394 (defun org-offer-links-in-entry (&optional nth zero)
8395 "Offer links in the current entry and follow the selected link.
8396 If there is only one link, follow it immediately as well.
8397 If NTH is an integer, immediately pick the NTH link found.
8398 If ZERO is a string, check also this string for a link, and if
8399 there is one, offer it as link number zero."
8400 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8401 "\\(" org-angle-link-re "\\)\\|"
8402 "\\(" org-plain-link-re "\\)"))
8403 (cnt ?0)
8404 (in-emacs (if (integerp nth) nil nth))
8405 have-zero end links link c)
8406 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8407 (push (match-string 0 zero) links)
8408 (setq cnt (1- cnt) have-zero t))
8409 (save-excursion
8410 (org-back-to-heading t)
8411 (setq end (save-excursion (outline-next-heading) (point)))
8412 (while (re-search-forward re end t)
8413 (push (match-string 0) links))
8414 (setq links (org-uniquify (reverse links))))
8416 (cond
8417 ((null links)
8418 (message "No links"))
8419 ((equal (length links) 1)
8420 (setq link (car links)))
8421 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8422 (setq link (nth (if have-zero nth (1- nth)) links)))
8423 (t ; we have to select a link
8424 (save-excursion
8425 (save-window-excursion
8426 (delete-other-windows)
8427 (with-output-to-temp-buffer "*Select Link*"
8428 (mapc (lambda (l)
8429 (if (not (string-match org-bracket-link-regexp l))
8430 (princ (format "[%c] %s\n" (incf cnt)
8431 (org-remove-angle-brackets l)))
8432 (if (match-end 3)
8433 (princ (format "[%c] %s (%s)\n" (incf cnt)
8434 (match-string 3 l) (match-string 1 l)))
8435 (princ (format "[%c] %s\n" (incf cnt)
8436 (match-string 1 l))))))
8437 links))
8438 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8439 (message "Select link to open:")
8440 (setq c (read-char-exclusive))
8441 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8442 (when (equal c ?q) (error "Abort"))
8443 (setq nth (- c ?0))
8444 (if have-zero (setq nth (1+ nth)))
8445 (unless (and (integerp nth) (>= (length links) nth))
8446 (error "Invalid link selection"))
8447 (setq link (nth (1- nth) links))))
8448 (if link
8449 (progn (org-open-link-from-string link in-emacs (current-buffer)) t)
8450 nil)))
8452 ;;;; Time estimates
8454 (defun org-get-effort (&optional pom)
8455 "Get the effort estimate for the current entry."
8456 (org-entry-get pom org-effort-property))
8458 ;;; File search
8460 (defvar org-create-file-search-functions nil
8461 "List of functions to construct the right search string for a file link.
8462 These functions are called in turn with point at the location to
8463 which the link should point.
8465 A function in the hook should first test if it would like to
8466 handle this file type, for example by checking the major-mode or
8467 the file extension. If it decides not to handle this file, it
8468 should just return nil to give other functions a chance. If it
8469 does handle the file, it must return the search string to be used
8470 when following the link. The search string will be part of the
8471 file link, given after a double colon, and `org-open-at-point'
8472 will automatically search for it. If special measures must be
8473 taken to make the search successful, another function should be
8474 added to the companion hook `org-execute-file-search-functions',
8475 which see.
8477 A function in this hook may also use `setq' to set the variable
8478 `description' to provide a suggestion for the descriptive text to
8479 be used for this link when it gets inserted into an Org-mode
8480 buffer with \\[org-insert-link].")
8482 (defvar org-execute-file-search-functions nil
8483 "List of functions to execute a file search triggered by a link.
8485 Functions added to this hook must accept a single argument, the
8486 search string that was part of the file link, the part after the
8487 double colon. The function must first check if it would like to
8488 handle this search, for example by checking the major-mode or the
8489 file extension. If it decides not to handle this search, it
8490 should just return nil to give other functions a chance. If it
8491 does handle the search, it must return a non-nil value to keep
8492 other functions from trying.
8494 Each function can access the current prefix argument through the
8495 variable `current-prefix-argument'. Note that a single prefix is
8496 used to force opening a link in Emacs, so it may be good to only
8497 use a numeric or double prefix to guide the search function.
8499 In case this is needed, a function in this hook can also restore
8500 the window configuration before `org-open-at-point' was called using:
8502 (set-window-configuration org-window-config-before-follow-link)")
8504 (defun org-link-search (s &optional type avoid-pos)
8505 "Search for a link search option.
8506 If S is surrounded by forward slashes, it is interpreted as a
8507 regular expression. In org-mode files, this will create an `org-occur'
8508 sparse tree. In ordinary files, `occur' will be used to list matches.
8509 If the current buffer is in `dired-mode', grep will be used to search
8510 in all files. If AVOID-POS is given, ignore matches near that position."
8511 (let ((case-fold-search t)
8512 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8513 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8514 (append '(("") (" ") ("\t") ("\n"))
8515 org-emphasis-alist)
8516 "\\|") "\\)"))
8517 (pos (point))
8518 (pre nil) (post nil)
8519 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8520 (cond
8521 ;; First check if there are any special
8522 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8523 ;; Now try the builtin stuff
8524 ((and (equal (string-to-char s0) ?#)
8525 (> (length s0) 1)
8526 (save-excursion
8527 (goto-char (point-min))
8528 (and
8529 (re-search-forward
8530 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8531 (setq type 'dedicated
8532 pos (match-beginning 0))))
8533 ;; There is an exact target for this
8534 (goto-char pos)
8535 (org-back-to-heading t)))
8536 ((save-excursion
8537 (goto-char (point-min))
8538 (and
8539 (re-search-forward
8540 (concat "<<" (regexp-quote s0) ">>") nil t)
8541 (setq type 'dedicated
8542 pos (match-beginning 0))))
8543 ;; There is an exact target for this
8544 (goto-char pos))
8545 ((and (string-match "^(\\(.*\\))$" s0)
8546 (save-excursion
8547 (goto-char (point-min))
8548 (and
8549 (re-search-forward
8550 (concat "[^[]" (regexp-quote
8551 (format org-coderef-label-format
8552 (match-string 1 s0))))
8553 nil t)
8554 (setq type 'dedicated
8555 pos (1+ (match-beginning 0))))))
8556 ;; There is a coderef target for this
8557 (goto-char pos))
8558 ((string-match "^/\\(.*\\)/$" s)
8559 ;; A regular expression
8560 (cond
8561 ((org-mode-p)
8562 (org-occur (match-string 1 s)))
8563 ;;((eq major-mode 'dired-mode)
8564 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8565 (t (org-do-occur (match-string 1 s)))))
8567 ;; A normal search strings
8568 (when (equal (string-to-char s) ?*)
8569 ;; Anchor on headlines, post may include tags.
8570 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8571 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8572 s (substring s 1)))
8573 (remove-text-properties
8574 0 (length s)
8575 '(face nil mouse-face nil keymap nil fontified nil) s)
8576 ;; Make a series of regular expressions to find a match
8577 (setq words (org-split-string s "[ \n\r\t]+")
8579 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8580 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8581 "\\)" markers)
8582 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8583 re2a (concat "[ \t\r\n]" re2a_)
8584 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8585 re4 (concat "[^a-zA-Z_]" re4_)
8587 re1 (concat pre re2 post)
8588 re3 (concat pre (if pre re4_ re4) post)
8589 re5 (concat pre ".*" re4)
8590 re2 (concat pre re2)
8591 re2a (concat pre (if pre re2a_ re2a))
8592 re4 (concat pre (if pre re4_ re4))
8593 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8594 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8595 re5 "\\)"
8597 (cond
8598 ((eq type 'org-occur) (org-occur reall))
8599 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8600 (t (goto-char (point-min))
8601 (setq type 'fuzzy)
8602 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8603 (org-search-not-self 1 re1 nil t)
8604 (org-search-not-self 1 re2 nil t)
8605 (org-search-not-self 1 re2a nil t)
8606 (org-search-not-self 1 re3 nil t)
8607 (org-search-not-self 1 re4 nil t)
8608 (org-search-not-self 1 re5 nil t)
8610 (goto-char (match-beginning 1))
8611 (goto-char pos)
8612 (error "No match")))))
8614 ;; Normal string-search
8615 (goto-char (point-min))
8616 (if (search-forward s nil t)
8617 (goto-char (match-beginning 0))
8618 (error "No match"))))
8619 (and (org-mode-p) (org-show-context 'link-search))
8620 type))
8622 (defun org-search-not-self (group &rest args)
8623 "Execute `re-search-forward', but only accept matches that do not
8624 enclose the position of `org-open-link-marker'."
8625 (let ((m org-open-link-marker))
8626 (catch 'exit
8627 (while (apply 're-search-forward args)
8628 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8629 (goto-char (match-end group))
8630 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8631 (> (match-beginning 0) (marker-position m))
8632 (< (match-end 0) (marker-position m)))
8633 (save-match-data
8634 (or (not (org-in-regexp
8635 org-bracket-link-analytic-regexp 1))
8636 (not (match-end 4)) ; no description
8637 (and (<= (match-beginning 4) (point))
8638 (>= (match-end 4) (point))))))
8639 (throw 'exit (point))))))))
8641 (defun org-get-buffer-for-internal-link (buffer)
8642 "Return a buffer to be used for displaying the link target of internal links."
8643 (cond
8644 ((not org-display-internal-link-with-indirect-buffer)
8645 buffer)
8646 ((string-match "(Clone)$" (buffer-name buffer))
8647 (message "Buffer is already a clone, not making another one")
8648 ;; we also do not modify visibility in this case
8649 buffer)
8650 (t ; make a new indirect buffer for displaying the link
8651 (let* ((bn (buffer-name buffer))
8652 (ibn (concat bn "(Clone)"))
8653 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8654 (with-current-buffer ib (org-overview))
8655 ib))))
8657 (defun org-do-occur (regexp &optional cleanup)
8658 "Call the Emacs command `occur'.
8659 If CLEANUP is non-nil, remove the printout of the regular expression
8660 in the *Occur* buffer. This is useful if the regex is long and not useful
8661 to read."
8662 (occur regexp)
8663 (when cleanup
8664 (let ((cwin (selected-window)) win beg end)
8665 (when (setq win (get-buffer-window "*Occur*"))
8666 (select-window win))
8667 (goto-char (point-min))
8668 (when (re-search-forward "match[a-z]+" nil t)
8669 (setq beg (match-end 0))
8670 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8671 (setq end (1- (match-beginning 0)))))
8672 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8673 (goto-char (point-min))
8674 (select-window cwin))))
8676 ;;; The mark ring for links jumps
8678 (defvar org-mark-ring nil
8679 "Mark ring for positions before jumps in Org-mode.")
8680 (defvar org-mark-ring-last-goto nil
8681 "Last position in the mark ring used to go back.")
8682 ;; Fill and close the ring
8683 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8684 (loop for i from 1 to org-mark-ring-length do
8685 (push (make-marker) org-mark-ring))
8686 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8687 org-mark-ring)
8689 (defun org-mark-ring-push (&optional pos buffer)
8690 "Put the current position or POS into the mark ring and rotate it."
8691 (interactive)
8692 (setq pos (or pos (point)))
8693 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8694 (move-marker (car org-mark-ring)
8695 (or pos (point))
8696 (or buffer (current-buffer)))
8697 (message "%s"
8698 (substitute-command-keys
8699 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8701 (defun org-mark-ring-goto (&optional n)
8702 "Jump to the previous position in the mark ring.
8703 With prefix arg N, jump back that many stored positions. When
8704 called several times in succession, walk through the entire ring.
8705 Org-mode commands jumping to a different position in the current file,
8706 or to another Org-mode file, automatically push the old position
8707 onto the ring."
8708 (interactive "p")
8709 (let (p m)
8710 (if (eq last-command this-command)
8711 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8712 (setq p org-mark-ring))
8713 (setq org-mark-ring-last-goto p)
8714 (setq m (car p))
8715 (switch-to-buffer (marker-buffer m))
8716 (goto-char m)
8717 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8719 (defun org-remove-angle-brackets (s)
8720 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8721 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8723 (defun org-add-angle-brackets (s)
8724 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8725 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8727 (defun org-remove-double-quotes (s)
8728 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8729 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8732 ;;; Following specific links
8734 (defun org-follow-timestamp-link ()
8735 (cond
8736 ((org-at-date-range-p t)
8737 (let ((org-agenda-start-on-weekday)
8738 (t1 (match-string 1))
8739 (t2 (match-string 2)))
8740 (setq t1 (time-to-days (org-time-string-to-time t1))
8741 t2 (time-to-days (org-time-string-to-time t2)))
8742 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8743 ((org-at-timestamp-p t)
8744 (org-agenda-list nil (time-to-days (org-time-string-to-time
8745 (substring (match-string 1) 0 10)))
8747 (t (error "This should not happen"))))
8750 ;;; Following file links
8751 (defvar org-wait nil)
8752 (defun org-open-file (path &optional in-emacs line search)
8753 "Open the file at PATH.
8754 First, this expands any special file name abbreviations. Then the
8755 configuration variable `org-file-apps' is checked if it contains an
8756 entry for this file type, and if yes, the corresponding command is launched.
8758 If no application is found, Emacs simply visits the file.
8760 With optional prefix argument IN-EMACS, Emacs will visit the file.
8761 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8762 and o use an external application to visit the file.
8764 Optional LINE specifies a line to go to, optional SEARCH a string to
8765 search for. If LINE or SEARCH is given, the file will always be
8766 opened in Emacs.
8767 If the file does not exist, an error is thrown."
8768 (setq in-emacs (or in-emacs line search))
8769 (let* ((file (if (equal path "")
8770 buffer-file-name
8771 (substitute-in-file-name (expand-file-name path))))
8772 (apps (append org-file-apps (org-default-apps)))
8773 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8774 (dirp (if remp nil (file-directory-p file)))
8775 (file (if (and dirp org-open-directory-means-index-dot-org)
8776 (concat (file-name-as-directory file) "index.org")
8777 file))
8778 (a-m-a-p (assq 'auto-mode apps))
8779 (dfile (downcase file))
8780 (old-buffer (current-buffer))
8781 (old-pos (point))
8782 (old-mode major-mode)
8783 ext cmd)
8784 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8785 (setq ext (match-string 1 dfile))
8786 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8787 (setq ext (match-string 1 dfile))))
8788 (cond
8789 ((equal in-emacs '(16))
8790 (setq cmd (cdr (assoc 'system apps))))
8791 (in-emacs (setq cmd 'emacs))
8793 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8794 (and dirp (cdr (assoc 'directory apps)))
8795 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8796 'string-match)
8797 (cdr (assoc ext apps))
8798 (cdr (assoc t apps))))))
8799 (when (eq cmd 'system)
8800 (setq cmd (cdr (assoc 'system apps))))
8801 (when (eq cmd 'default)
8802 (setq cmd (cdr (assoc t apps))))
8803 (when (eq cmd 'mailcap)
8804 (require 'mailcap)
8805 (mailcap-parse-mailcaps)
8806 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8807 (command (mailcap-mime-info mime-type)))
8808 (if (stringp command)
8809 (setq cmd command)
8810 (setq cmd 'emacs))))
8811 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8812 (not (file-exists-p file))
8813 (not org-open-non-existing-files))
8814 (error "No such file: %s" file))
8815 (cond
8816 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8817 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8818 (while (string-match "['\"]%s['\"]" cmd)
8819 (setq cmd (replace-match "%s" t t cmd)))
8820 (while (string-match "%s" cmd)
8821 (setq cmd (replace-match
8822 (save-match-data
8823 (shell-quote-argument
8824 (convert-standard-filename file)))
8825 t t cmd)))
8826 (save-window-excursion
8827 (start-process-shell-command cmd nil cmd)
8828 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8830 ((or (stringp cmd)
8831 (eq cmd 'emacs))
8832 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8833 (widen)
8834 (if line (org-goto-line line)
8835 (if search (org-link-search search))))
8836 ((consp cmd)
8837 (let ((file (convert-standard-filename file)))
8838 (eval cmd)))
8839 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8840 (and (org-mode-p) (eq old-mode 'org-mode)
8841 (or (not (equal old-buffer (current-buffer)))
8842 (not (equal old-pos (point))))
8843 (org-mark-ring-push old-pos old-buffer))))
8845 (defun org-default-apps ()
8846 "Return the default applications for this operating system."
8847 (cond
8848 ((eq system-type 'darwin)
8849 org-file-apps-defaults-macosx)
8850 ((eq system-type 'windows-nt)
8851 org-file-apps-defaults-windowsnt)
8852 (t org-file-apps-defaults-gnu)))
8854 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8855 "Convert extensions to regular expressions in the cars of LIST.
8856 Also, weed out any non-string entries, because the return value is used
8857 only for regexp matching.
8858 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8859 point to the symbol `emacs', indicating that the file should
8860 be opened in Emacs."
8861 (append
8862 (delq nil
8863 (mapcar (lambda (x)
8864 (if (not (stringp (car x)))
8866 (if (string-match "\\W" (car x))
8868 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8869 list))
8870 (if add-auto-mode
8871 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8873 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8874 (defun org-file-remote-p (file)
8875 "Test whether FILE specifies a location on a remote system.
8876 Return non-nil if the location is indeed remote.
8878 For example, the filename \"/user@host:/foo\" specifies a location
8879 on the system \"/user@host:\"."
8880 (cond ((fboundp 'file-remote-p)
8881 (file-remote-p file))
8882 ((fboundp 'tramp-handle-file-remote-p)
8883 (tramp-handle-file-remote-p file))
8884 ((and (boundp 'ange-ftp-name-format)
8885 (string-match (car ange-ftp-name-format) file))
8887 (t nil)))
8890 ;;;; Refiling
8892 (defun org-get-org-file ()
8893 "Read a filename, with default directory `org-directory'."
8894 (let ((default (or org-default-notes-file remember-data-file)))
8895 (read-file-name (format "File name [%s]: " default)
8896 (file-name-as-directory org-directory)
8897 default)))
8899 (defun org-notes-order-reversed-p ()
8900 "Check if the current file should receive notes in reversed order."
8901 (cond
8902 ((not org-reverse-note-order) nil)
8903 ((eq t org-reverse-note-order) t)
8904 ((not (listp org-reverse-note-order)) nil)
8905 (t (catch 'exit
8906 (let ((all org-reverse-note-order)
8907 entry)
8908 (while (setq entry (pop all))
8909 (if (string-match (car entry) buffer-file-name)
8910 (throw 'exit (cdr entry))))
8911 nil)))))
8913 (defvar org-refile-target-table nil
8914 "The list of refile targets, created by `org-refile'.")
8916 (defvar org-agenda-new-buffers nil
8917 "Buffers created to visit agenda files.")
8919 (defun org-get-refile-targets (&optional default-buffer)
8920 "Produce a table with refile targets."
8921 (let ((case-fold-search nil)
8922 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8923 (entries (or org-refile-targets '((nil . (:level . 1)))))
8924 targets txt re files f desc descre fast-path-p level pos0)
8925 (message "Getting targets...")
8926 (with-current-buffer (or default-buffer (current-buffer))
8927 (while (setq entry (pop entries))
8928 (setq files (car entry) desc (cdr entry))
8929 (setq fast-path-p nil)
8930 (cond
8931 ((null files) (setq files (list (current-buffer))))
8932 ((eq files 'org-agenda-files)
8933 (setq files (org-agenda-files 'unrestricted)))
8934 ((and (symbolp files) (fboundp files))
8935 (setq files (funcall files)))
8936 ((and (symbolp files) (boundp files))
8937 (setq files (symbol-value files))))
8938 (if (stringp files) (setq files (list files)))
8939 (cond
8940 ((eq (car desc) :tag)
8941 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8942 ((eq (car desc) :todo)
8943 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8944 ((eq (car desc) :regexp)
8945 (setq descre (cdr desc)))
8946 ((eq (car desc) :level)
8947 (setq descre (concat "^\\*\\{" (number-to-string
8948 (if org-odd-levels-only
8949 (1- (* 2 (cdr desc)))
8950 (cdr desc)))
8951 "\\}[ \t]")))
8952 ((eq (car desc) :maxlevel)
8953 (setq fast-path-p t)
8954 (setq descre (concat "^\\*\\{1," (number-to-string
8955 (if org-odd-levels-only
8956 (1- (* 2 (cdr desc)))
8957 (cdr desc)))
8958 "\\}[ \t]")))
8959 (t (error "Bad refiling target description %s" desc)))
8960 (while (setq f (pop files))
8961 (with-current-buffer
8962 (if (bufferp f) f (org-get-agenda-file-buffer f))
8963 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8964 (setq f (expand-file-name f))
8965 (if (eq org-refile-use-outline-path 'file)
8966 (push (list (file-name-nondirectory f) f nil nil) targets))
8967 (save-excursion
8968 (save-restriction
8969 (widen)
8970 (goto-char (point-min))
8971 (while (re-search-forward descre nil t)
8972 (goto-char (setq pos0 (point-at-bol)))
8973 (catch 'next
8974 (when org-refile-target-verify-function
8975 (save-match-data
8976 (or (funcall org-refile-target-verify-function)
8977 (throw 'next t))))
8978 (when (looking-at org-complex-heading-regexp)
8979 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8980 txt (org-link-display-format (match-string 4))
8981 re (concat "^" (regexp-quote
8982 (buffer-substring (match-beginning 1)
8983 (match-end 4)))))
8984 (if (match-end 5) (setq re (concat re "[ \t]+"
8985 (regexp-quote
8986 (match-string 5)))))
8987 (setq re (concat re "[ \t]*$"))
8988 (when org-refile-use-outline-path
8989 (setq txt (mapconcat 'org-protect-slash
8990 (append
8991 (if (eq org-refile-use-outline-path 'file)
8992 (list (file-name-nondirectory
8993 (buffer-file-name (buffer-base-buffer))))
8994 (if (eq org-refile-use-outline-path 'full-file-path)
8995 (list (buffer-file-name (buffer-base-buffer)))))
8996 (org-get-outline-path fast-path-p level txt)
8997 (list txt))
8998 "/")))
8999 (push (list txt f re (point)) targets)))
9000 (when (= (point) pos0)
9001 ;; verification function has not moved point
9002 (goto-char (point-at-eol))))))))))
9003 (message "Getting targets...done")
9004 (nreverse targets)))
9006 (defun org-protect-slash (s)
9007 (while (string-match "/" s)
9008 (setq s (replace-match "\\" t t s)))
9011 (defvar org-olpa (make-vector 20 nil))
9013 (defun org-get-outline-path (&optional fastp level heading)
9014 "Return the outline path to the current entry, as a list.
9015 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9016 routine which makes outline path derivations for an entire file,
9017 avoiding backtracing."
9018 (if fastp
9019 (progn
9020 (if (> level 19)
9021 (error "Outline path failure, more than 19 levels"))
9022 (loop for i from level upto 19 do
9023 (aset org-olpa i nil))
9024 (prog1
9025 (delq nil (append org-olpa nil))
9026 (aset org-olpa level heading)))
9027 (let (rtn)
9028 (save-excursion
9029 (save-restriction
9030 (widen)
9031 (while (org-up-heading-safe)
9032 (when (looking-at org-complex-heading-regexp)
9033 (push (org-match-string-no-properties 4) rtn)))
9034 rtn)))))
9036 (defun org-format-outline-path (path &optional width prefix)
9037 "Format the outlie path PATH for display.
9038 Width is the maximum number of characters that is available.
9039 Prefix is a prefix to be included in the returned string,
9040 such as the file name."
9041 (setq width (or width 79))
9042 (if prefix (setq width (- width (length prefix))))
9043 (if (not path)
9044 (or prefix "")
9045 (let* ((nsteps (length path))
9046 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9047 (maxwidth (if (<= total-width width)
9048 10000 ;; everything fits
9049 ;; we need to shorten the level headings
9050 (/ (- width nsteps) nsteps)))
9051 (org-odd-levels-only nil)
9052 (n 0)
9053 (total (1+ (length prefix))))
9054 (setq maxwidth (max maxwidth 10))
9055 (concat prefix
9056 (mapconcat
9057 (lambda (h)
9058 (setq n (1+ n))
9059 (if (and (= n nsteps) (< maxwidth 10000))
9060 (setq maxwidth (- total-width total)))
9061 (if (< (length h) maxwidth)
9062 (progn (setq total (+ total (length h) 1)) h)
9063 (setq h (substring h 0 (- maxwidth 2))
9064 total (+ total maxwidth 1))
9065 (if (string-match "[ \t]+\\'" h)
9066 (setq h (substring h 0 (match-beginning 0))))
9067 (setq h (concat h "..")))
9068 (org-add-props h nil 'face
9069 (nth (% (1- n) org-n-level-faces)
9070 org-level-faces))
9072 path "/")))))
9074 (defun org-display-outline-path (&optional file current)
9075 "Display the current outline path in the echo area."
9076 (interactive "P")
9077 (let ((bfn (buffer-file-name (buffer-base-buffer)))
9078 (path (and (org-mode-p) (org-get-outline-path))))
9079 (if current (setq path (append path
9080 (save-excursion
9081 (org-back-to-heading t)
9082 (if (looking-at org-complex-heading-regexp)
9083 (list (match-string 4)))))))
9084 (message "%s"
9085 (org-format-outline-path
9086 path
9087 (1- (frame-width))
9088 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9090 (defvar org-refile-history nil
9091 "History for refiling operations.")
9093 (defvar org-after-refile-insert-hook nil
9094 "Hook run after `org-refile' has inserted its stuff at the new location.
9095 Note that this is still *before* the stuff will be removed from
9096 the *old* location.")
9098 (defun org-refile (&optional goto default-buffer rfloc)
9099 "Move the entry at point to another heading.
9100 The list of target headings is compiled using the information in
9101 `org-refile-targets', which see. This list is created before each use
9102 and will therefore always be up-to-date.
9104 At the target location, the entry is filed as a subitem of the target heading.
9105 Depending on `org-reverse-note-order', the new subitem will either be the
9106 first or the last subitem.
9108 If there is an active region, all entries in that region will be moved.
9109 However, the region must fulfil the requirement that the first heading
9110 is the first one sets the top-level of the moved text - at most siblings
9111 below it are allowed.
9113 With prefix arg GOTO, the command will only visit the target location,
9114 not actually move anything.
9115 With a double prefix `C-u C-u', go to the location where the last refiling
9116 operation has put the subtree.
9117 With a prefix argument of `2', refile to the running clock.
9119 RFLOC can be a refile location obtained in a different way.
9121 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9122 (interactive "P")
9123 (let* ((cbuf (current-buffer))
9124 (regionp (org-region-active-p))
9125 (region-start (and regionp (region-beginning)))
9126 (region-end (and regionp (region-end)))
9127 (region-length (and regionp (- region-end region-start)))
9128 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9129 pos it nbuf file re level reversed)
9130 (setq last-command nil)
9131 (when regionp
9132 (goto-char region-start)
9133 (or (bolp) (goto-char (point-at-bol)))
9134 (setq region-start (point))
9135 (unless (org-kill-is-subtree-p
9136 (buffer-substring region-start region-end))
9137 (error "The region is not a (sequence of) subtree(s)")))
9138 (if (equal goto '(16))
9139 (org-refile-goto-last-stored)
9140 (when (or
9141 (and (equal goto 2)
9142 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9143 (prog1
9144 (setq it (list (or org-clock-heading "running clock")
9145 (buffer-file-name
9146 (marker-buffer org-clock-hd-marker))
9148 (marker-position org-clock-hd-marker)))
9149 (setq goto nil)))
9150 (setq it (or rfloc
9151 (save-excursion
9152 (org-refile-get-location
9153 (if goto "Goto: " "Refile to: ") default-buffer
9154 org-refile-allow-creating-parent-nodes)))))
9155 (setq file (nth 1 it)
9156 re (nth 2 it)
9157 pos (nth 3 it))
9158 (if (and (not goto)
9160 (equal (buffer-file-name) file)
9161 (if regionp
9162 (and (>= pos region-start)
9163 (<= pos region-end))
9164 (and (>= pos (point))
9165 (< pos (save-excursion
9166 (org-end-of-subtree t t))))))
9167 (error "Cannot refile to position inside the tree or region"))
9169 (setq nbuf (or (find-buffer-visiting file)
9170 (find-file-noselect file)))
9171 (if goto
9172 (progn
9173 (switch-to-buffer nbuf)
9174 (goto-char pos)
9175 (org-show-context 'org-goto))
9176 (if regionp
9177 (progn
9178 (org-kill-new (buffer-substring region-start region-end))
9179 (org-save-markers-in-region region-start region-end))
9180 (org-copy-subtree 1 nil t))
9181 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9182 (find-file-noselect file)))
9183 (setq reversed (org-notes-order-reversed-p))
9184 (save-excursion
9185 (save-restriction
9186 (widen)
9187 (if pos
9188 (progn
9189 (goto-char pos)
9190 (looking-at outline-regexp)
9191 (setq level (org-get-valid-level (funcall outline-level) 1))
9192 (goto-char
9193 (if reversed
9194 (or (outline-next-heading) (point-max))
9195 (or (save-excursion (org-get-next-sibling))
9196 (org-end-of-subtree t t)
9197 (point-max)))))
9198 (setq level 1)
9199 (if (not reversed)
9200 (goto-char (point-max))
9201 (goto-char (point-min))
9202 (or (outline-next-heading) (goto-char (point-max)))))
9203 (if (not (bolp)) (newline))
9204 (bookmark-set "org-refile-last-stored")
9205 (org-paste-subtree level)
9206 (if (fboundp 'deactivate-mark) (deactivate-mark))
9207 (run-hooks 'org-after-refile-insert-hook))))
9208 (if regionp
9209 (delete-region (point) (+ (point) region-length))
9210 (org-cut-subtree))
9211 (when (featurep 'org-inlinetask)
9212 (org-inlinetask-remove-END-maybe))
9213 (setq org-markers-to-move nil)
9214 (message "Refiled to \"%s\"" (car it))))))
9215 (org-reveal))
9217 (defun org-refile-goto-last-stored ()
9218 "Go to the location where the last refile was stored."
9219 (interactive)
9220 (bookmark-jump "org-refile-last-stored")
9221 (message "This is the location of the last refile"))
9223 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9224 "Prompt the user for a refile location, using PROMPT."
9225 (let ((org-refile-targets org-refile-targets)
9226 (org-refile-use-outline-path org-refile-use-outline-path))
9227 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9228 (unless org-refile-target-table
9229 (error "No refile targets"))
9230 (let* ((cbuf (current-buffer))
9231 (partial-completion-mode nil)
9232 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9233 (cfunc (if (and org-refile-use-outline-path
9234 org-outline-path-complete-in-steps)
9235 'org-olpath-completing-read
9236 'org-icompleting-read))
9237 (extra (if org-refile-use-outline-path "/" ""))
9238 (filename (and cfn (expand-file-name cfn)))
9239 (tbl (mapcar
9240 (lambda (x)
9241 (if (and (not (member org-refile-use-outline-path
9242 '(file full-file-path)))
9243 (not (equal filename (nth 1 x))))
9244 (cons (concat (car x) extra " ("
9245 (file-name-nondirectory (nth 1 x)) ")")
9246 (cdr x))
9247 (cons (concat (car x) extra) (cdr x))))
9248 org-refile-target-table))
9249 (completion-ignore-case t)
9250 pa answ parent-target child parent old-hist)
9251 (setq old-hist org-refile-history)
9252 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9253 nil 'org-refile-history))
9254 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9255 (if pa
9256 (progn
9257 (when (or (not org-refile-history)
9258 (not (eq old-hist org-refile-history))
9259 (not (equal (car pa) (car org-refile-history))))
9260 (setq org-refile-history
9261 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9262 org-refile-history
9263 (cdr org-refile-history))))
9264 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9265 (pop org-refile-history)))
9267 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9268 (setq parent (match-string 1 answ)
9269 child (match-string 2 answ))
9270 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
9271 (when (and parent-target
9272 (or (eq new-nodes t)
9273 (and (eq new-nodes 'confirm)
9274 (y-or-n-p (format "Create new node \"%s\"? " child)))))
9275 (org-refile-new-child parent-target child))))))
9277 (defun org-refile-new-child (parent-target child)
9278 "Use refile target PARENT-TARGET to add new CHILD below it."
9279 (unless parent-target
9280 (error "Cannot find parent for new node"))
9281 (let ((file (nth 1 parent-target))
9282 (pos (nth 3 parent-target))
9283 level)
9284 (with-current-buffer (or (find-buffer-visiting file)
9285 (find-file-noselect file))
9286 (save-excursion
9287 (save-restriction
9288 (widen)
9289 (if pos
9290 (goto-char pos)
9291 (goto-char (point-max))
9292 (if (not (bolp)) (newline)))
9293 (when (looking-at outline-regexp)
9294 (setq level (funcall outline-level))
9295 (org-end-of-subtree t t))
9296 (org-back-over-empty-lines)
9297 (insert "\n" (make-string
9298 (if pos (org-get-valid-level level 1) 1) ?*)
9299 " " child "\n")
9300 (beginning-of-line 0)
9301 (list (concat (car parent-target) "/" child) file "" (point)))))))
9303 (defun org-olpath-completing-read (prompt collection &rest args)
9304 "Read an outline path like a file name."
9305 (let ((thetable collection)
9306 (org-completion-use-ido nil) ; does not work with ido.
9307 (org-completion-use-iswitchb nil)) ; or iswitchb
9308 (apply
9309 'org-icompleting-read prompt
9310 (lambda (string predicate &optional flag)
9311 (let (rtn r f (l (length string)))
9312 (cond
9313 ((eq flag nil)
9314 ;; try completion
9315 (try-completion string thetable))
9316 ((eq flag t)
9317 ;; all-completions
9318 (setq rtn (all-completions string thetable predicate))
9319 (mapcar
9320 (lambda (x)
9321 (setq r (substring x l))
9322 (if (string-match " ([^)]*)$" x)
9323 (setq f (match-string 0 x))
9324 (setq f ""))
9325 (if (string-match "/" r)
9326 (concat string (substring r 0 (match-end 0)) f)
9328 rtn))
9329 ((eq flag 'lambda)
9330 ;; exact match?
9331 (assoc string thetable)))
9333 args)))
9335 ;;;; Dynamic blocks
9337 (defun org-find-dblock (name)
9338 "Find the first dynamic block with name NAME in the buffer.
9339 If not found, stay at current position and return nil."
9340 (let (pos)
9341 (save-excursion
9342 (goto-char (point-min))
9343 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9344 nil t)
9345 (match-beginning 0))))
9346 (if pos (goto-char pos))
9347 pos))
9349 (defconst org-dblock-start-re
9350 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9351 "Matches the start line of a dynamic block, with parameters.")
9353 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9354 "Matches the end of a dynamic block.")
9356 (defun org-create-dblock (plist)
9357 "Create a dynamic block section, with parameters taken from PLIST.
9358 PLIST must contain a :name entry which is used as name of the block."
9359 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9360 (end-of-line 1)
9361 (newline))
9362 (let ((col (current-column))
9363 (name (plist-get plist :name)))
9364 (insert "#+BEGIN: " name)
9365 (while plist
9366 (if (eq (car plist) :name)
9367 (setq plist (cddr plist))
9368 (insert " " (prin1-to-string (pop plist)))))
9369 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9370 (beginning-of-line -2)))
9372 (defun org-prepare-dblock ()
9373 "Prepare dynamic block for refresh.
9374 This empties the block, puts the cursor at the insert position and returns
9375 the property list including an extra property :name with the block name."
9376 (unless (looking-at org-dblock-start-re)
9377 (error "Not at a dynamic block"))
9378 (let* ((begdel (1+ (match-end 0)))
9379 (name (org-no-properties (match-string 1)))
9380 (params (append (list :name name)
9381 (read (concat "(" (match-string 3) ")")))))
9382 (save-excursion
9383 (beginning-of-line 1)
9384 (skip-chars-forward " \t")
9385 (setq params (plist-put params :indentation-column (current-column))))
9386 (unless (re-search-forward org-dblock-end-re nil t)
9387 (error "Dynamic block not terminated"))
9388 (setq params
9389 (append params
9390 (list :content (buffer-substring
9391 begdel (match-beginning 0)))))
9392 (delete-region begdel (match-beginning 0))
9393 (goto-char begdel)
9394 (open-line 1)
9395 params))
9397 (defun org-map-dblocks (&optional command)
9398 "Apply COMMAND to all dynamic blocks in the current buffer.
9399 If COMMAND is not given, use `org-update-dblock'."
9400 (let ((cmd (or command 'org-update-dblock))
9401 pos)
9402 (save-excursion
9403 (goto-char (point-min))
9404 (while (re-search-forward org-dblock-start-re nil t)
9405 (goto-char (setq pos (match-beginning 0)))
9406 (condition-case nil
9407 (funcall cmd)
9408 (error (message "Error during update of dynamic block")))
9409 (goto-char pos)
9410 (unless (re-search-forward org-dblock-end-re nil t)
9411 (error "Dynamic block not terminated"))))))
9413 (defun org-dblock-update (&optional arg)
9414 "User command for updating dynamic blocks.
9415 Update the dynamic block at point. With prefix ARG, update all dynamic
9416 blocks in the buffer."
9417 (interactive "P")
9418 (if arg
9419 (org-update-all-dblocks)
9420 (or (looking-at org-dblock-start-re)
9421 (org-beginning-of-dblock))
9422 (org-update-dblock)))
9424 (defun org-update-dblock ()
9425 "Update the dynamic block at point
9426 This means to empty the block, parse for parameters and then call
9427 the correct writing function."
9428 (save-window-excursion
9429 (let* ((pos (point))
9430 (line (org-current-line))
9431 (params (org-prepare-dblock))
9432 (name (plist-get params :name))
9433 (indent (plist-get params :indentation-column))
9434 (cmd (intern (concat "org-dblock-write:" name))))
9435 (message "Updating dynamic block `%s' at line %d..." name line)
9436 (funcall cmd params)
9437 (message "Updating dynamic block `%s' at line %d...done" name line)
9438 (goto-char pos)
9439 (when (and indent (> indent 0))
9440 (setq indent (make-string indent ?\ ))
9441 (save-excursion
9442 (org-beginning-of-dblock)
9443 (forward-line 1)
9444 (while (not (looking-at org-dblock-end-re))
9445 (insert indent)
9446 (beginning-of-line 2))
9447 (when (looking-at org-dblock-end-re)
9448 (and (looking-at "[ \t]+")
9449 (replace-match ""))
9450 (insert indent)))))))
9452 (defun org-beginning-of-dblock ()
9453 "Find the beginning of the dynamic block at point.
9454 Error if there is no such block at point."
9455 (let ((pos (point))
9456 beg)
9457 (end-of-line 1)
9458 (if (and (re-search-backward org-dblock-start-re nil t)
9459 (setq beg (match-beginning 0))
9460 (re-search-forward org-dblock-end-re nil t)
9461 (> (match-end 0) pos))
9462 (goto-char beg)
9463 (goto-char pos)
9464 (error "Not in a dynamic block"))))
9466 (defun org-update-all-dblocks ()
9467 "Update all dynamic blocks in the buffer.
9468 This function can be used in a hook."
9469 (when (org-mode-p)
9470 (org-map-dblocks 'org-update-dblock)))
9473 ;;;; Completion
9475 (defconst org-additional-option-like-keywords
9476 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9477 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9478 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "LATEX_CLASS:" "ATTR_LaTeX"
9479 "BEGIN:" "END:"
9480 "ORGTBL" "TBLFM:" "TBLNAME:"
9481 "BEGIN_EXAMPLE" "END_EXAMPLE"
9482 "BEGIN_QUOTE" "END_QUOTE"
9483 "BEGIN_VERSE" "END_VERSE"
9484 "BEGIN_CENTER" "END_CENTER"
9485 "BEGIN_SRC" "END_SRC"
9486 "CATEGORY" "COLUMNS"
9487 "CAPTION" "LABEL"
9488 "SETUPFILE"
9489 "BIND"
9490 "MACRO"))
9492 (defcustom org-structure-template-alist
9494 ("s" "#+begin_src ?\n\n#+end_src"
9495 "<src lang=\"?\">\n\n</src>")
9496 ("e" "#+begin_example\n?\n#+end_example"
9497 "<example>\n?\n</example>")
9498 ("q" "#+begin_quote\n?\n#+end_quote"
9499 "<quote>\n?\n</quote>")
9500 ("v" "#+begin_verse\n?\n#+end_verse"
9501 "<verse>\n?\n/verse>")
9502 ("c" "#+begin_center\n?\n#+end_center"
9503 "<center>\n?\n/center>")
9504 ("l" "#+begin_latex\n?\n#+end_latex"
9505 "<literal style=\"latex\">\n?\n</literal>")
9506 ("L" "#+latex: "
9507 "<literal style=\"latex\">?</literal>")
9508 ("h" "#+begin_html\n?\n#+end_html"
9509 "<literal style=\"html\">\n?\n</literal>")
9510 ("H" "#+html: "
9511 "<literal style=\"html\">?</literal>")
9512 ("a" "#+begin_ascii\n?\n#+end_ascii")
9513 ("A" "#+ascii: ")
9514 ("i" "#+include %file ?"
9515 "<include file=%file markup=\"?\">")
9517 "Structure completion elements.
9518 This is a list of abbreviation keys and values. The value gets inserted
9519 it you type @samp{.} followed by the key and then the completion key,
9520 usually `M-TAB'. %file will be replaced by a file name after prompting
9521 for the file using completion.
9522 There are two templates for each key, the first uses the original Org syntax,
9523 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9524 the default when the /org-mtags.el/ module has been loaded. See also the
9525 variable `org-mtags-prefer-muse-templates'.
9526 This is an experimental feature, it is undecided if it is going to stay in."
9527 :group 'org-completion
9528 :type '(repeat
9529 (string :tag "Key")
9530 (string :tag "Template")
9531 (string :tag "Muse Template")))
9533 (defun org-try-structure-completion ()
9534 "Try to complete a structure template before point.
9535 This looks for strings like \"<e\" on an otherwise empty line and
9536 expands them."
9537 (let ((l (buffer-substring (point-at-bol) (point)))
9539 (when (and (looking-at "[ \t]*$")
9540 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9541 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9542 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9543 (match-beginning 1)) a)
9544 t)))
9546 (defun org-complete-expand-structure-template (start cell)
9547 "Expand a structure template."
9548 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9549 (rpl (nth (if musep 2 1) cell))
9550 (ind ""))
9551 (delete-region start (point))
9552 (when (string-match "\\`#\\+" rpl)
9553 (cond
9554 ((bolp))
9555 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9556 (setq ind (buffer-substring (point-at-bol) (point))))
9557 (t (newline))))
9558 (setq start (point))
9559 (if (string-match "%file" rpl)
9560 (setq rpl (replace-match
9561 (concat
9562 "\""
9563 (save-match-data
9564 (abbreviate-file-name (read-file-name "Include file: ")))
9565 "\"")
9566 t t rpl)))
9567 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9568 (concat "\n" ind)))
9569 (insert rpl)
9570 (if (re-search-backward "\\?" start t) (delete-char 1))))
9573 (defun org-complete (&optional arg)
9574 "Perform completion on word at point.
9575 At the beginning of a headline, this completes TODO keywords as given in
9576 `org-todo-keywords'.
9577 If the current word is preceded by a backslash, completes the TeX symbols
9578 that are supported for HTML support.
9579 If the current word is preceded by \"#+\", completes special words for
9580 setting file options.
9581 In the line after \"#+STARTUP:, complete valid keywords.\"
9582 At all other locations, this simply calls the value of
9583 `org-completion-fallback-command'."
9584 (interactive "P")
9585 (org-without-partial-completion
9586 (catch 'exit
9587 (let* ((a nil)
9588 (end (point))
9589 (beg1 (save-excursion
9590 (skip-chars-backward (org-re "[:alnum:]_@"))
9591 (point)))
9592 (beg (save-excursion
9593 (skip-chars-backward "a-zA-Z0-9_:$")
9594 (point)))
9595 (confirm (lambda (x) (stringp (car x))))
9596 (searchhead (equal (char-before beg) ?*))
9597 (struct
9598 (when (and (member (char-before beg1) '(?. ?<))
9599 (setq a (assoc (buffer-substring beg1 (point))
9600 org-structure-template-alist)))
9601 (org-complete-expand-structure-template (1- beg1) a)
9602 (throw 'exit t)))
9603 (tag (and (equal (char-before beg1) ?:)
9604 (equal (char-after (point-at-bol)) ?*)))
9605 (prop (and (equal (char-before beg1) ?:)
9606 (not (equal (char-after (point-at-bol)) ?*))))
9607 (texp (equal (char-before beg) ?\\))
9608 (link (equal (char-before beg) ?\[))
9609 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9610 beg)
9611 "#+"))
9612 (startup (string-match "^#\\+STARTUP:.*"
9613 (buffer-substring (point-at-bol) (point))))
9614 (completion-ignore-case opt)
9615 (type nil)
9616 (tbl nil)
9617 (table (cond
9618 (opt
9619 (setq type :opt)
9620 (require 'org-exp)
9621 (append
9622 (delq nil
9623 (mapcar
9624 (lambda (x)
9625 (if (string-match
9626 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9627 (cons (match-string 2 x)
9628 (match-string 1 x))))
9629 (org-split-string (org-get-current-options) "\n")))
9630 (mapcar 'list org-additional-option-like-keywords)))
9631 (startup
9632 (setq type :startup)
9633 org-startup-options)
9634 (link (append org-link-abbrev-alist-local
9635 org-link-abbrev-alist))
9636 (texp
9637 (setq type :tex)
9638 org-html-entities)
9639 ((string-match "\\`\\*+[ \t]+\\'"
9640 (buffer-substring (point-at-bol) beg))
9641 (setq type :todo)
9642 (mapcar 'list org-todo-keywords-1))
9643 (searchhead
9644 (setq type :searchhead)
9645 (save-excursion
9646 (goto-char (point-min))
9647 (while (re-search-forward org-todo-line-regexp nil t)
9648 (push (list
9649 (org-make-org-heading-search-string
9650 (match-string 3) t))
9651 tbl)))
9652 tbl)
9653 (tag (setq type :tag beg beg1)
9654 (or org-tag-alist (org-get-buffer-tags)))
9655 (prop (setq type :prop beg beg1)
9656 (mapcar 'list (org-buffer-property-keys nil t t)))
9657 (t (progn
9658 (call-interactively org-completion-fallback-command)
9659 (throw 'exit nil)))))
9660 (pattern (buffer-substring-no-properties beg end))
9661 (completion (try-completion pattern table confirm)))
9662 (cond ((eq completion t)
9663 (if (not (assoc (upcase pattern) table))
9664 (message "Already complete")
9665 (if (and (equal type :opt)
9666 (not (member (car (assoc (upcase pattern) table))
9667 org-additional-option-like-keywords)))
9668 (insert (substring (cdr (assoc (upcase pattern) table))
9669 (length pattern)))
9670 (if (memq type '(:tag :prop)) (insert ":")))))
9671 ((null completion)
9672 (message "Can't find completion for \"%s\"" pattern)
9673 (ding))
9674 ((not (string= pattern completion))
9675 (delete-region beg end)
9676 (if (string-match " +$" completion)
9677 (setq completion (replace-match "" t t completion)))
9678 (insert completion)
9679 (if (get-buffer-window "*Completions*")
9680 (delete-window (get-buffer-window "*Completions*")))
9681 (if (assoc completion table)
9682 (if (eq type :todo) (insert " ")
9683 (if (memq type '(:tag :prop)) (insert ":"))))
9684 (if (and (equal type :opt) (assoc completion table))
9685 (message "%s" (substitute-command-keys
9686 "Press \\[org-complete] again to insert example settings"))))
9688 (message "Making completion list...")
9689 (let ((list (sort (all-completions pattern table confirm)
9690 'string<)))
9691 (with-output-to-temp-buffer "*Completions*"
9692 (condition-case nil
9693 ;; Protection needed for XEmacs and emacs 21
9694 (display-completion-list list pattern)
9695 (error (display-completion-list list)))))
9696 (message "Making completion list...%s" "done")))))))
9698 ;;;; TODO, DEADLINE, Comments
9700 (defun org-toggle-comment ()
9701 "Change the COMMENT state of an entry."
9702 (interactive)
9703 (save-excursion
9704 (org-back-to-heading)
9705 (let (case-fold-search)
9706 (if (looking-at (concat outline-regexp
9707 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9708 (replace-match "" t t nil 1)
9709 (if (looking-at outline-regexp)
9710 (progn
9711 (goto-char (match-end 0))
9712 (insert org-comment-string " ")))))))
9714 (defvar org-last-todo-state-is-todo nil
9715 "This is non-nil when the last TODO state change led to a TODO state.
9716 If the last change removed the TODO tag or switched to DONE, then
9717 this is nil.")
9719 (defvar org-setting-tags nil) ; dynamically skipped
9721 (defun org-parse-local-options (string var)
9722 "Parse STRING for startup setting relevant for variable VAR."
9723 (let ((rtn (symbol-value var))
9724 e opts)
9725 (save-match-data
9726 (if (or (not string) (not (string-match "\\S-" string)))
9728 (setq opts (delq nil (mapcar (lambda (x)
9729 (setq e (assoc x org-startup-options))
9730 (if (eq (nth 1 e) var) e nil))
9731 (org-split-string string "[ \t]+"))))
9732 (if (not opts)
9734 (setq rtn nil)
9735 (while (setq e (pop opts))
9736 (if (not (nth 3 e))
9737 (setq rtn (nth 2 e))
9738 (if (not (listp rtn)) (setq rtn nil))
9739 (push (nth 2 e) rtn)))
9740 rtn)))))
9742 (defvar org-todo-setup-filter-hook nil
9743 "Hook for functions that pre-filter todo specs.
9745 Each function takes a todo spec and returns either `nil' or the spec
9746 transformed into canonical form." )
9748 (defvar org-todo-get-default-hook nil
9749 "Hook for functions that get a default item for todo.
9751 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9752 `nil' or a string to be used for the todo mark." )
9754 (defvar org-agenda-headline-snapshot-before-repeat)
9756 (defun org-todo (&optional arg)
9757 "Change the TODO state of an item.
9758 The state of an item is given by a keyword at the start of the heading,
9759 like
9760 *** TODO Write paper
9761 *** DONE Call mom
9763 The different keywords are specified in the variable `org-todo-keywords'.
9764 By default the available states are \"TODO\" and \"DONE\".
9765 So for this example: when the item starts with TODO, it is changed to DONE.
9766 When it starts with DONE, the DONE is removed. And when neither TODO nor
9767 DONE are present, add TODO at the beginning of the heading.
9769 With C-u prefix arg, use completion to determine the new state.
9770 With numeric prefix arg, switch to that state.
9771 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9772 With a triple C-u prefix, circumvent any state blocking.
9774 For calling through lisp, arg is also interpreted in the following way:
9775 'none -> empty state
9776 \"\"(empty string) -> switch to empty state
9777 'done -> switch to DONE
9778 'nextset -> switch to the next set of keywords
9779 'previousset -> switch to the previous set of keywords
9780 \"WAITING\" -> switch to the specified keyword, but only if it
9781 really is a member of `org-todo-keywords'."
9782 (interactive "P")
9783 (if (equal arg '(16)) (setq arg 'nextset))
9784 (let ((org-blocker-hook org-blocker-hook)
9785 (case-fold-search nil))
9786 (when (equal arg '(64))
9787 (setq arg nil org-blocker-hook nil))
9788 (when (and org-blocker-hook
9789 (or org-inhibit-blocking
9790 (org-entry-get nil "NOBLOCKING")))
9791 (setq org-blocker-hook nil))
9792 (save-excursion
9793 (catch 'exit
9794 (org-back-to-heading t)
9795 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9796 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9797 (looking-at " *"))
9798 (let* ((match-data (match-data))
9799 (startpos (point-at-bol))
9800 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9801 (org-log-done org-log-done)
9802 (org-log-repeat org-log-repeat)
9803 (org-todo-log-states org-todo-log-states)
9804 (this (match-string 1))
9805 (hl-pos (match-beginning 0))
9806 (head (org-get-todo-sequence-head this))
9807 (ass (assoc head org-todo-kwd-alist))
9808 (interpret (nth 1 ass))
9809 (done-word (nth 3 ass))
9810 (final-done-word (nth 4 ass))
9811 (last-state (or this ""))
9812 (completion-ignore-case t)
9813 (member (member this org-todo-keywords-1))
9814 (tail (cdr member))
9815 (state (cond
9816 ((and org-todo-key-trigger
9817 (or (and (equal arg '(4))
9818 (eq org-use-fast-todo-selection 'prefix))
9819 (and (not arg) org-use-fast-todo-selection
9820 (not (eq org-use-fast-todo-selection
9821 'prefix)))))
9822 ;; Use fast selection
9823 (org-fast-todo-selection))
9824 ((and (equal arg '(4))
9825 (or (not org-use-fast-todo-selection)
9826 (not org-todo-key-trigger)))
9827 ;; Read a state with completion
9828 (org-icompleting-read
9829 "State: " (mapcar (lambda(x) (list x))
9830 org-todo-keywords-1)
9831 nil t))
9832 ((eq arg 'right)
9833 (if this
9834 (if tail (car tail) nil)
9835 (car org-todo-keywords-1)))
9836 ((eq arg 'left)
9837 (if (equal member org-todo-keywords-1)
9839 (if this
9840 (nth (- (length org-todo-keywords-1)
9841 (length tail) 2)
9842 org-todo-keywords-1)
9843 (org-last org-todo-keywords-1))))
9844 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9845 (setq arg nil))) ; hack to fall back to cycling
9846 (arg
9847 ;; user or caller requests a specific state
9848 (cond
9849 ((equal arg "") nil)
9850 ((eq arg 'none) nil)
9851 ((eq arg 'done) (or done-word (car org-done-keywords)))
9852 ((eq arg 'nextset)
9853 (or (car (cdr (member head org-todo-heads)))
9854 (car org-todo-heads)))
9855 ((eq arg 'previousset)
9856 (let ((org-todo-heads (reverse org-todo-heads)))
9857 (or (car (cdr (member head org-todo-heads)))
9858 (car org-todo-heads))))
9859 ((car (member arg org-todo-keywords-1)))
9860 ((stringp arg)
9861 (error "State `%s' not valid in this file" arg))
9862 ((nth (1- (prefix-numeric-value arg))
9863 org-todo-keywords-1))))
9864 ((null member) (or head (car org-todo-keywords-1)))
9865 ((equal this final-done-word) nil) ;; -> make empty
9866 ((null tail) nil) ;; -> first entry
9867 ((memq interpret '(type priority))
9868 (if (eq this-command last-command)
9869 (car tail)
9870 (if (> (length tail) 0)
9871 (or done-word (car org-done-keywords))
9872 nil)))
9874 (car tail))))
9875 (state (or
9876 (run-hook-with-args-until-success
9877 'org-todo-get-default-hook state last-state)
9878 state))
9879 (next (if state (concat " " state " ") " "))
9880 (change-plist (list :type 'todo-state-change :from this :to state
9881 :position startpos))
9882 dolog now-done-p)
9883 (when org-blocker-hook
9884 (setq org-last-todo-state-is-todo
9885 (not (member this org-done-keywords)))
9886 (unless (save-excursion
9887 (save-match-data
9888 (run-hook-with-args-until-failure
9889 'org-blocker-hook change-plist)))
9890 (if (interactive-p)
9891 (error "TODO state change from %s to %s blocked" this state)
9892 ;; fail silently
9893 (message "TODO state change from %s to %s blocked" this state)
9894 (throw 'exit nil))))
9895 (store-match-data match-data)
9896 (replace-match next t t)
9897 (unless (pos-visible-in-window-p hl-pos)
9898 (message "TODO state changed to %s" (org-trim next)))
9899 (unless head
9900 (setq head (org-get-todo-sequence-head state)
9901 ass (assoc head org-todo-kwd-alist)
9902 interpret (nth 1 ass)
9903 done-word (nth 3 ass)
9904 final-done-word (nth 4 ass)))
9905 (when (memq arg '(nextset previousset))
9906 (message "Keyword-Set %d/%d: %s"
9907 (- (length org-todo-sets) -1
9908 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9909 (length org-todo-sets)
9910 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9911 (setq org-last-todo-state-is-todo
9912 (not (member state org-done-keywords)))
9913 (setq now-done-p (and (member state org-done-keywords)
9914 (not (member this org-done-keywords))))
9915 (and logging (org-local-logging logging))
9916 (when (and (or org-todo-log-states org-log-done)
9917 (not (eq org-inhibit-logging t))
9918 (not (memq arg '(nextset previousset))))
9919 ;; we need to look at recording a time and note
9920 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9921 (nth 2 (assoc this org-todo-log-states))))
9922 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9923 (setq dolog 'time))
9924 (when (and state
9925 (member state org-not-done-keywords)
9926 (not (member this org-not-done-keywords)))
9927 ;; This is now a todo state and was not one before
9928 ;; If there was a CLOSED time stamp, get rid of it.
9929 (org-add-planning-info nil nil 'closed))
9930 (when (and now-done-p org-log-done)
9931 ;; It is now done, and it was not done before
9932 (org-add-planning-info 'closed (org-current-time))
9933 (if (and (not dolog) (eq 'note org-log-done))
9934 (org-add-log-setup 'done state this 'findpos 'note)))
9935 (when (and state dolog)
9936 ;; This is a non-nil state, and we need to log it
9937 (org-add-log-setup 'state state this 'findpos dolog)))
9938 ;; Fixup tag positioning
9939 (org-todo-trigger-tag-changes state)
9940 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9941 (when org-provide-todo-statistics
9942 (org-update-parent-todo-statistics))
9943 (run-hooks 'org-after-todo-state-change-hook)
9944 (if (and arg (not (member state org-done-keywords)))
9945 (setq head (org-get-todo-sequence-head state)))
9946 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9947 ;; Do we need to trigger a repeat?
9948 (when now-done-p
9949 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9950 ;; This is for the agenda, take a snapshot of the headline.
9951 (save-match-data
9952 (setq org-agenda-headline-snapshot-before-repeat
9953 (org-get-heading))))
9954 (org-auto-repeat-maybe state))
9955 ;; Fixup cursor location if close to the keyword
9956 (if (and (outline-on-heading-p)
9957 (not (bolp))
9958 (save-excursion (beginning-of-line 1)
9959 (looking-at org-todo-line-regexp))
9960 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9961 (progn
9962 (goto-char (or (match-end 2) (match-end 1)))
9963 (and (looking-at " ") (just-one-space))))
9964 (when org-trigger-hook
9965 (save-excursion
9966 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9968 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9969 "Block turning an entry into a TODO, using the hierarchy.
9970 This checks whether the current task should be blocked from state
9971 changes. Such blocking occurs when:
9973 1. The task has children which are not all in a completed state.
9975 2. A task has a parent with the property :ORDERED:, and there
9976 are siblings prior to the current task with incomplete
9977 status.
9979 3. The parent of the task is blocked because it has siblings that should
9980 be done first, or is child of a block grandparent TODO entry."
9982 (catch 'dont-block
9983 ;; If this is not a todo state change, or if this entry is already DONE,
9984 ;; do not block
9985 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9986 (member (plist-get change-plist :from)
9987 (cons 'done org-done-keywords))
9988 (member (plist-get change-plist :to)
9989 (cons 'todo org-not-done-keywords))
9990 (not (plist-get change-plist :to)))
9991 (throw 'dont-block t))
9992 ;; If this task has children, and any are undone, it's blocked
9993 (save-excursion
9994 (org-back-to-heading t)
9995 (let ((this-level (funcall outline-level)))
9996 (outline-next-heading)
9997 (let ((child-level (funcall outline-level)))
9998 (while (and (not (eobp))
9999 (> child-level this-level))
10000 ;; this todo has children, check whether they are all
10001 ;; completed
10002 (if (and (not (org-entry-is-done-p))
10003 (org-entry-is-todo-p))
10004 (throw 'dont-block nil))
10005 (outline-next-heading)
10006 (setq child-level (funcall outline-level))))))
10007 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10008 ;; any previous siblings are undone, it's blocked
10009 (save-excursion
10010 (org-back-to-heading t)
10011 (let* ((pos (point))
10012 (parent-pos (and (org-up-heading-safe) (point))))
10013 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10014 (when (and (org-entry-get (point) "ORDERED")
10015 (forward-line 1)
10016 (re-search-forward org-not-done-heading-regexp pos t))
10017 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10018 ;; Search further up the hierarchy, to see if an anchestor is blocked
10019 (while t
10020 (goto-char parent-pos)
10021 (if (not (looking-at org-not-done-heading-regexp))
10022 (throw 'dont-block t)) ; do not block, parent is not a TODO
10023 (setq pos (point))
10024 (setq parent-pos (and (org-up-heading-safe) (point)))
10025 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10026 (when (and (org-entry-get (point) "ORDERED")
10027 (forward-line 1)
10028 (re-search-forward org-not-done-heading-regexp pos t))
10029 (throw 'dont-block nil))))))) ; block, older sibling not done.
10031 (defcustom org-track-ordered-property-with-tag nil
10032 "Should the ORDERED property also be shown as a tag?
10033 The ORDERED property decides if an entry should require subtasks to be
10034 completed in sequence. Since a property is not very visible, setting
10035 this option means that toggling the ORDERED property with the command
10036 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10037 not relevant for the behavior, but it makes things more visible.
10039 Note that toggling the tag with tags commands will not change the property
10040 and therefore not influence behavior!
10042 This can be t, meaning the tag ORDERED should be used, It can also be a
10043 string to select a different tag for this task."
10044 :group 'org-todo
10045 :type '(choice
10046 (const :tag "No tracking" nil)
10047 (const :tag "Track with ORDERED tag" t)
10048 (string :tag "Use other tag")))
10050 (defun org-toggle-ordered-property ()
10051 "Toggle the ORDERED property of the current entry.
10052 For better visibility, you can track the value of this property with a tag.
10053 See variable `org-track-ordered-property-with-tag'."
10054 (interactive)
10055 (let* ((t1 org-track-ordered-property-with-tag)
10056 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10057 (save-excursion
10058 (org-back-to-heading)
10059 (if (org-entry-get nil "ORDERED")
10060 (progn
10061 (org-delete-property "ORDERED")
10062 (and tag (org-toggle-tag tag 'off))
10063 (message "Subtasks can be completed in arbitrary order"))
10064 (org-entry-put nil "ORDERED" "t")
10065 (and tag (org-toggle-tag tag 'on))
10066 (message "Subtasks must be completed in sequence")))))
10068 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10069 (defun org-block-todo-from-checkboxes (change-plist)
10070 "Block turning an entry into a TODO, using checkboxes.
10071 This checks whether the current task should be blocked from state
10072 changes because there are unchecked boxes in this entry."
10073 (catch 'dont-block
10074 ;; If this is not a todo state change, or if this entry is already DONE,
10075 ;; do not block
10076 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10077 (member (plist-get change-plist :from)
10078 (cons 'done org-done-keywords))
10079 (member (plist-get change-plist :to)
10080 (cons 'todo org-not-done-keywords))
10081 (not (plist-get change-plist :to)))
10082 (throw 'dont-block t))
10083 ;; If this task has checkboxes that are not checked, it's blocked
10084 (save-excursion
10085 (org-back-to-heading t)
10086 (let ((beg (point)) end)
10087 (outline-next-heading)
10088 (setq end (point))
10089 (goto-char beg)
10090 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10091 end t)
10092 (progn
10093 (if (boundp 'org-blocked-by-checkboxes)
10094 (setq org-blocked-by-checkboxes t))
10095 (throw 'dont-block nil)))))
10096 t)) ; do not block
10098 (defun org-update-statistics-cookies (all)
10099 "Update the statistics cookie, either from TODO or from checkboxes.
10100 This should be called with the cursor in a line with a statistics cookie."
10101 (interactive "P")
10102 (if all
10103 (progn
10104 (org-update-checkbox-count 'all)
10105 (org-map-entries 'org-update-parent-todo-statistics))
10106 (if (not (org-on-heading-p))
10107 (org-update-checkbox-count)
10108 (let ((pos (move-marker (make-marker) (point)))
10109 end l1 l2)
10110 (ignore-errors (org-back-to-heading t))
10111 (if (not (org-on-heading-p))
10112 (org-update-checkbox-count)
10113 (setq l1 (org-outline-level))
10114 (setq end (save-excursion
10115 (outline-next-heading)
10116 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10117 (point)))
10118 (if (and (save-excursion (re-search-forward
10119 "^[ \t]*[-+*] \\[[- X]\\]" end t))
10120 (not (save-excursion (re-search-forward
10121 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10122 (org-update-checkbox-count)
10123 (if (and l2 (> l2 l1))
10124 (progn
10125 (goto-char end)
10126 (org-update-parent-todo-statistics))
10127 (error "No data for statistics cookie"))))
10128 (goto-char pos)
10129 (move-marker pos nil)))))
10131 (defvar org-entry-property-inherited-from) ;; defined below
10132 (defun org-update-parent-todo-statistics ()
10133 "Update any statistics cookie in the parent of the current headline.
10134 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10135 the entire subtree and this will travel up the hierarchy and update
10136 statistics everywhere."
10137 (interactive)
10138 (let* ((lim 0) prop
10139 (recursive (or (not org-hierarchical-todo-statistics)
10140 (string-match
10141 "\\<recursive\\>"
10142 (or (setq prop (org-entry-get
10143 nil "COOKIE_DATA" 'inherit)) ""))))
10144 (lim (or (and prop (marker-position
10145 org-entry-property-inherited-from))
10146 lim))
10147 (first t)
10148 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10149 level ltoggle l1 new ndel
10150 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10151 (catch 'exit
10152 (save-excursion
10153 (beginning-of-line 1)
10154 (if (org-at-heading-p)
10155 (setq ltoggle (funcall outline-level))
10156 (error "This should not happen"))
10157 (while (and (setq level (org-up-heading-safe))
10158 (or recursive first)
10159 (>= (point) lim))
10160 (setq first nil cookie-present nil)
10161 (unless (and level
10162 (not (string-match
10163 "\\<checkbox\\>"
10164 (downcase
10165 (or (org-entry-get
10166 nil "COOKIE_DATA")
10167 "")))))
10168 (throw 'exit nil))
10169 (while (re-search-forward box-re (point-at-eol) t)
10170 (setq cnt-all 0 cnt-done 0 cookie-present t)
10171 (setq is-percent (match-end 2))
10172 (save-match-data
10173 (unless (outline-next-heading) (throw 'exit nil))
10174 (while (and (looking-at org-complex-heading-regexp)
10175 (> (setq l1 (length (match-string 1))) level))
10176 (setq kwd (and (or recursive (= l1 ltoggle))
10177 (match-string 2)))
10178 (if (or (eq org-provide-todo-statistics 'all-headlines)
10179 (and (listp org-provide-todo-statistics)
10180 (or (member kwd org-provide-todo-statistics)
10181 (member kwd org-done-keywords))))
10182 (setq cnt-all (1+ cnt-all))
10183 (if (eq org-provide-todo-statistics t)
10184 (and kwd (setq cnt-all (1+ cnt-all)))))
10185 (and (member kwd org-done-keywords)
10186 (setq cnt-done (1+ cnt-done)))
10187 (outline-next-heading)))
10188 (setq new
10189 (if is-percent
10190 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10191 (format "[%d/%d]" cnt-done cnt-all))
10192 ndel (- (match-end 0) (match-beginning 0)))
10193 (goto-char (match-beginning 0))
10194 (insert new)
10195 (delete-region (point) (+ (point) ndel)))
10196 (when cookie-present
10197 (run-hook-with-args 'org-after-todo-statistics-hook
10198 cnt-done (- cnt-all cnt-done))))))
10199 (run-hooks 'org-todo-statistics-hook)))
10201 (defvar org-after-todo-statistics-hook nil
10202 "Hook that is called after a TODO statistics cookie has been updated.
10203 Each function is called with two arguments: the number of not-done entries
10204 and the number of done entries.
10206 For example, the following function, when added to this hook, will switch
10207 an entry to DONE when all children are done, and back to TODO when new
10208 entries are set to a TODO status. Note that this hook is only called
10209 when there is a statistics cookie in the headline!
10211 (defun org-summary-todo (n-done n-not-done)
10212 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10213 (let (org-log-done org-log-states) ; turn off logging
10214 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10217 (defvar org-todo-statistics-hook nil
10218 "Hook that is run whenever Org thinks TODO statistics should be updated.
10219 This hook runs even if there is no statistics cookie present, in which case
10220 `org-after-todo-statistics-hook' would not run.")
10222 (defun org-todo-trigger-tag-changes (state)
10223 "Apply the changes defined in `org-todo-state-tags-triggers'."
10224 (let ((l org-todo-state-tags-triggers)
10225 changes)
10226 (when (or (not state) (equal state ""))
10227 (setq changes (append changes (cdr (assoc "" l)))))
10228 (when (and (stringp state) (> (length state) 0))
10229 (setq changes (append changes (cdr (assoc state l)))))
10230 (when (member state org-not-done-keywords)
10231 (setq changes (append changes (cdr (assoc 'todo l)))))
10232 (when (member state org-done-keywords)
10233 (setq changes (append changes (cdr (assoc 'done l)))))
10234 (dolist (c changes)
10235 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10237 (defun org-local-logging (value)
10238 "Get logging settings from a property VALUE."
10239 (let* (words w a)
10240 ;; directly set the variables, they are already local.
10241 (setq org-log-done nil
10242 org-log-repeat nil
10243 org-todo-log-states nil)
10244 (setq words (org-split-string value))
10245 (while (setq w (pop words))
10246 (cond
10247 ((setq a (assoc w org-startup-options))
10248 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10249 (set (nth 1 a) (nth 2 a))))
10250 ((setq a (org-extract-log-state-settings w))
10251 (and (member (car a) org-todo-keywords-1)
10252 (push a org-todo-log-states)))))))
10254 (defun org-get-todo-sequence-head (kwd)
10255 "Return the head of the TODO sequence to which KWD belongs.
10256 If KWD is not set, check if there is a text property remembering the
10257 right sequence."
10258 (let (p)
10259 (cond
10260 ((not kwd)
10261 (or (get-text-property (point-at-bol) 'org-todo-head)
10262 (progn
10263 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10264 nil (point-at-eol)))
10265 (get-text-property p 'org-todo-head))))
10266 ((not (member kwd org-todo-keywords-1))
10267 (car org-todo-keywords-1))
10268 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10270 (defun org-fast-todo-selection ()
10271 "Fast TODO keyword selection with single keys.
10272 Returns the new TODO keyword, or nil if no state change should occur."
10273 (let* ((fulltable org-todo-key-alist)
10274 (done-keywords org-done-keywords) ;; needed for the faces.
10275 (maxlen (apply 'max (mapcar
10276 (lambda (x)
10277 (if (stringp (car x)) (string-width (car x)) 0))
10278 fulltable)))
10279 (expert nil)
10280 (fwidth (+ maxlen 3 1 3))
10281 (ncol (/ (- (window-width) 4) fwidth))
10282 tg cnt e c tbl
10283 groups ingroup)
10284 (save-excursion
10285 (save-window-excursion
10286 (if expert
10287 (set-buffer (get-buffer-create " *Org todo*"))
10288 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10289 (erase-buffer)
10290 (org-set-local 'org-done-keywords done-keywords)
10291 (setq tbl fulltable cnt 0)
10292 (while (setq e (pop tbl))
10293 (cond
10294 ((equal e '(:startgroup))
10295 (push '() groups) (setq ingroup t)
10296 (when (not (= cnt 0))
10297 (setq cnt 0)
10298 (insert "\n"))
10299 (insert "{ "))
10300 ((equal e '(:endgroup))
10301 (setq ingroup nil cnt 0)
10302 (insert "}\n"))
10303 ((equal e '(:newline))
10304 (when (not (= cnt 0))
10305 (setq cnt 0)
10306 (insert "\n")
10307 (setq e (car tbl))
10308 (while (equal (car tbl) '(:newline))
10309 (insert "\n")
10310 (setq tbl (cdr tbl)))))
10312 (setq tg (car e) c (cdr e))
10313 (if ingroup (push tg (car groups)))
10314 (setq tg (org-add-props tg nil 'face
10315 (org-get-todo-face tg)))
10316 (if (and (= cnt 0) (not ingroup)) (insert " "))
10317 (insert "[" c "] " tg (make-string
10318 (- fwidth 4 (length tg)) ?\ ))
10319 (when (= (setq cnt (1+ cnt)) ncol)
10320 (insert "\n")
10321 (if ingroup (insert " "))
10322 (setq cnt 0)))))
10323 (insert "\n")
10324 (goto-char (point-min))
10325 (if (not expert) (org-fit-window-to-buffer))
10326 (message "[a-z..]:Set [SPC]:clear")
10327 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10328 (cond
10329 ((or (= c ?\C-g)
10330 (and (= c ?q) (not (rassoc c fulltable))))
10331 (setq quit-flag t))
10332 ((= c ?\ ) nil)
10333 ((setq e (rassoc c fulltable) tg (car e))
10335 (t (setq quit-flag t)))))))
10337 (defun org-entry-is-todo-p ()
10338 (member (org-get-todo-state) org-not-done-keywords))
10340 (defun org-entry-is-done-p ()
10341 (member (org-get-todo-state) org-done-keywords))
10343 (defun org-get-todo-state ()
10344 (save-excursion
10345 (org-back-to-heading t)
10346 (and (looking-at org-todo-line-regexp)
10347 (match-end 2)
10348 (match-string 2))))
10350 (defun org-at-date-range-p (&optional inactive-ok)
10351 "Is the cursor inside a date range?"
10352 (interactive)
10353 (save-excursion
10354 (catch 'exit
10355 (let ((pos (point)))
10356 (skip-chars-backward "^[<\r\n")
10357 (skip-chars-backward "<[")
10358 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10359 (>= (match-end 0) pos)
10360 (throw 'exit t))
10361 (skip-chars-backward "^<[\r\n")
10362 (skip-chars-backward "<[")
10363 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10364 (>= (match-end 0) pos)
10365 (throw 'exit t)))
10366 nil)))
10368 (defun org-get-repeat (&optional tagline)
10369 "Check if there is a deadline/schedule with repeater in this entry."
10370 (save-match-data
10371 (save-excursion
10372 (org-back-to-heading t)
10373 (and (re-search-forward (if tagline
10374 (concat tagline "\\s-*" org-repeat-re)
10375 org-repeat-re)
10376 (org-entry-end-position) t)
10377 (match-string-no-properties 1)))))
10379 (defvar org-last-changed-timestamp)
10380 (defvar org-last-inserted-timestamp)
10381 (defvar org-log-post-message)
10382 (defvar org-log-note-purpose)
10383 (defvar org-log-note-how)
10384 (defvar org-log-note-extra)
10385 (defun org-auto-repeat-maybe (done-word)
10386 "Check if the current headline contains a repeated deadline/schedule.
10387 If yes, set TODO state back to what it was and change the base date
10388 of repeating deadline/scheduled time stamps to new date.
10389 This function is run automatically after each state change to a DONE state."
10390 ;; last-state is dynamically scoped into this function
10391 (let* ((repeat (org-get-repeat))
10392 (aa (assoc last-state org-todo-kwd-alist))
10393 (interpret (nth 1 aa))
10394 (head (nth 2 aa))
10395 (whata '(("d" . day) ("m" . month) ("y" . year)))
10396 (msg "Entry repeats: ")
10397 (org-log-done nil)
10398 (org-todo-log-states nil)
10399 (nshiftmax 10) (nshift 0)
10400 re type n what ts time)
10401 (when repeat
10402 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10403 (org-todo (if (eq interpret 'type) last-state head))
10404 (org-entry-put nil "LAST_REPEAT" (format-time-string
10405 (org-time-stamp-format t t)))
10406 (when org-log-repeat
10407 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10408 (memq 'org-add-log-note post-command-hook))
10409 ;; OK, we are already setup for some record
10410 (if (eq org-log-repeat 'note)
10411 ;; make sure we take a note, not only a time stamp
10412 (setq org-log-note-how 'note))
10413 ;; Set up for taking a record
10414 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10415 last-state
10416 'findpos org-log-repeat)))
10417 (org-back-to-heading t)
10418 (org-add-planning-info nil nil 'closed)
10419 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10420 org-deadline-time-regexp "\\)\\|\\("
10421 org-ts-regexp "\\)"))
10422 (while (re-search-forward
10423 re (save-excursion (outline-next-heading) (point)) t)
10424 (setq type (if (match-end 1) org-scheduled-string
10425 (if (match-end 3) org-deadline-string "Plain:"))
10426 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10427 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10428 (setq n (string-to-number (match-string 2 ts))
10429 what (match-string 3 ts))
10430 (if (equal what "w") (setq n (* n 7) what "d"))
10431 ;; Preparation, see if we need to modify the start date for the change
10432 (when (match-end 1)
10433 (setq time (save-match-data (org-time-string-to-time ts)))
10434 (cond
10435 ((equal (match-string 1 ts) ".")
10436 ;; Shift starting date to today
10437 (org-timestamp-change
10438 (- (time-to-days (current-time)) (time-to-days time))
10439 'day))
10440 ((equal (match-string 1 ts) "+")
10441 (while (or (= nshift 0)
10442 (<= (time-to-days time) (time-to-days (current-time))))
10443 (when (= (incf nshift) nshiftmax)
10444 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10445 (error "Abort")))
10446 (org-timestamp-change n (cdr (assoc what whata)))
10447 (org-at-timestamp-p t)
10448 (setq ts (match-string 1))
10449 (setq time (save-match-data (org-time-string-to-time ts))))
10450 (org-timestamp-change (- n) (cdr (assoc what whata)))
10451 ;; rematch, so that we have everything in place for the real shift
10452 (org-at-timestamp-p t)
10453 (setq ts (match-string 1))
10454 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10455 (org-timestamp-change n (cdr (assoc what whata)))
10456 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10457 (setq org-log-post-message msg)
10458 (message "%s" msg))))
10460 (defun org-show-todo-tree (arg)
10461 "Make a compact tree which shows all headlines marked with TODO.
10462 The tree will show the lines where the regexp matches, and all higher
10463 headlines above the match.
10464 With a \\[universal-argument] prefix, prompt for a regexp to match.
10465 With a numeric prefix N, construct a sparse tree for the Nth element
10466 of `org-todo-keywords-1'."
10467 (interactive "P")
10468 (let ((case-fold-search nil)
10469 (kwd-re
10470 (cond ((null arg) org-not-done-regexp)
10471 ((equal arg '(4))
10472 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10473 (mapcar 'list org-todo-keywords-1))))
10474 (concat "\\("
10475 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10476 "\\)\\>")))
10477 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10478 (regexp-quote (nth (1- (prefix-numeric-value arg))
10479 org-todo-keywords-1)))
10480 (t (error "Invalid prefix argument: %s" arg)))))
10481 (message "%d TODO entries found"
10482 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10484 (defun org-deadline (&optional remove time)
10485 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10486 With argument REMOVE, remove any deadline from the item.
10487 When TIME is set, it should be an internal time specification, and the
10488 scheduling will use the corresponding date."
10489 (interactive "P")
10490 (let ((old-date (org-entry-get nil "DEADLINE")))
10491 (if remove
10492 (progn
10493 (org-remove-timestamp-with-keyword org-deadline-string)
10494 (message "Item no longer has a deadline."))
10495 (if (org-get-repeat)
10496 (error "Cannot change deadline on task with repeater, please do that by hand")
10497 (org-add-planning-info 'deadline time 'closed)
10498 (when (and old-date org-log-redeadline
10499 (not (equal old-date
10500 (substring org-last-inserted-timestamp 1 -1))))
10501 (org-add-log-setup 'redeadline nil old-date 'findpos
10502 org-log-redeadline))
10503 (message "Deadline on %s" org-last-inserted-timestamp)))))
10505 (defun org-schedule (&optional remove time)
10506 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10507 With argument REMOVE, remove any scheduling date from the item.
10508 When TIME is set, it should be an internal time specification, and the
10509 scheduling will use the corresponding date."
10510 (interactive "P")
10511 (let ((old-date (org-entry-get nil "SCHEDULED")))
10512 (if remove
10513 (progn
10514 (org-remove-timestamp-with-keyword org-scheduled-string)
10515 (message "Item is no longer scheduled."))
10516 (if (org-get-repeat)
10517 (error "Cannot reschedule task with repeater, please do that by hand")
10518 (org-add-planning-info 'scheduled time 'closed)
10519 (when (and old-date org-log-reschedule
10520 (not (equal old-date
10521 (substring org-last-inserted-timestamp 1 -1))))
10522 (org-add-log-setup 'reschedule nil old-date 'findpos
10523 org-log-reschedule))
10524 (message "Scheduled to %s" org-last-inserted-timestamp)))))
10526 (defun org-get-scheduled-time (pom &optional inherit)
10527 "Get the scheduled time as a time tuple, of a format suitable
10528 for calling org-schedule with, or if there is no scheduling,
10529 returns nil."
10530 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10531 (when time
10532 (apply 'encode-time (org-parse-time-string time)))))
10534 (defun org-get-deadline-time (pom &optional inherit)
10535 "Get the deadine as a time tuple, of a format suitable for
10536 calling org-deadline with, or if there is no scheduling, returns
10537 nil."
10538 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10539 (when time
10540 (apply 'encode-time (org-parse-time-string time)))))
10542 (defun org-remove-timestamp-with-keyword (keyword)
10543 "Remove all time stamps with KEYWORD in the current entry."
10544 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10545 beg)
10546 (save-excursion
10547 (org-back-to-heading t)
10548 (setq beg (point))
10549 (outline-next-heading)
10550 (while (re-search-backward re beg t)
10551 (replace-match "")
10552 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10553 (equal (char-before) ?\ ))
10554 (backward-delete-char 1)
10555 (if (string-match "^[ \t]*$" (buffer-substring
10556 (point-at-bol) (point-at-eol)))
10557 (delete-region (point-at-bol)
10558 (min (point-max) (1+ (point-at-eol))))))))))
10560 (defun org-add-planning-info (what &optional time &rest remove)
10561 "Insert new timestamp with keyword in the line directly after the headline.
10562 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10563 If non is given, the user is prompted for a date.
10564 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10565 be removed."
10566 (interactive)
10567 (let (org-time-was-given org-end-time-was-given ts
10568 end default-time default-input)
10570 (catch 'exit
10571 (when (and (not time) (memq what '(scheduled deadline)))
10572 ;; Try to get a default date/time from existing timestamp
10573 (save-excursion
10574 (org-back-to-heading t)
10575 (setq end (save-excursion (outline-next-heading) (point)))
10576 (when (re-search-forward (if (eq what 'scheduled)
10577 org-scheduled-time-regexp
10578 org-deadline-time-regexp)
10579 end t)
10580 (setq ts (match-string 1)
10581 default-time
10582 (apply 'encode-time (org-parse-time-string ts))
10583 default-input (and ts (org-get-compact-tod ts))))))
10584 (when what
10585 ;; If necessary, get the time from the user
10586 (setq time (or time (org-read-date nil 'to-time nil nil
10587 default-time default-input))))
10589 (when (and org-insert-labeled-timestamps-at-point
10590 (member what '(scheduled deadline)))
10591 (insert
10592 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10593 (org-insert-time-stamp time org-time-was-given
10594 nil nil nil (list org-end-time-was-given))
10595 (setq what nil))
10596 (save-excursion
10597 (save-restriction
10598 (let (col list elt ts buffer-invisibility-spec)
10599 (org-back-to-heading t)
10600 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10601 (goto-char (match-end 1))
10602 (setq col (current-column))
10603 (goto-char (match-end 0))
10604 (if (eobp) (insert "\n") (forward-char 1))
10605 (when (and (not what)
10606 (not (looking-at
10607 (concat "[ \t]*"
10608 org-keyword-time-not-clock-regexp))))
10609 ;; Nothing to add, nothing to remove...... :-)
10610 (throw 'exit nil))
10611 (if (and (not (looking-at outline-regexp))
10612 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10613 "[^\r\n]*"))
10614 (not (equal (match-string 1) org-clock-string)))
10615 (narrow-to-region (match-beginning 0) (match-end 0))
10616 (insert-before-markers "\n")
10617 (backward-char 1)
10618 (narrow-to-region (point) (point))
10619 (and org-adapt-indentation (org-indent-to-column col)))
10620 ;; Check if we have to remove something.
10621 (setq list (cons what remove))
10622 (while list
10623 (setq elt (pop list))
10624 (goto-char (point-min))
10625 (when (or (and (eq elt 'scheduled)
10626 (re-search-forward org-scheduled-time-regexp nil t))
10627 (and (eq elt 'deadline)
10628 (re-search-forward org-deadline-time-regexp nil t))
10629 (and (eq elt 'closed)
10630 (re-search-forward org-closed-time-regexp nil t)))
10631 (replace-match "")
10632 (if (looking-at "--+<[^>]+>") (replace-match ""))
10633 (skip-chars-backward " ")
10634 (if (looking-at " +") (replace-match ""))))
10635 (goto-char (point-max))
10636 (and org-adapt-indentation (bolp) (org-indent-to-column col))
10637 (when what
10638 (insert
10639 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10640 (cond ((eq what 'scheduled) org-scheduled-string)
10641 ((eq what 'deadline) org-deadline-string)
10642 ((eq what 'closed) org-closed-string))
10643 " ")
10644 (setq ts (org-insert-time-stamp
10645 time
10646 (or org-time-was-given
10647 (and (eq what 'closed) org-log-done-with-time))
10648 (eq what 'closed)
10649 nil nil (list org-end-time-was-given)))
10650 (end-of-line 1))
10651 (goto-char (point-min))
10652 (widen)
10653 (if (and (looking-at "[ \t]+\n")
10654 (equal (char-before) ?\n))
10655 (delete-region (1- (point)) (point-at-eol)))
10656 ts))))))
10658 (defvar org-log-note-marker (make-marker))
10659 (defvar org-log-note-purpose nil)
10660 (defvar org-log-note-state nil)
10661 (defvar org-log-note-previous-state nil)
10662 (defvar org-log-note-how nil)
10663 (defvar org-log-note-extra nil)
10664 (defvar org-log-note-window-configuration nil)
10665 (defvar org-log-note-return-to (make-marker))
10666 (defvar org-log-post-message nil
10667 "Message to be displayed after a log note has been stored.
10668 The auto-repeater uses this.")
10670 (defun org-add-note ()
10671 "Add a note to the current entry.
10672 This is done in the same way as adding a state change note."
10673 (interactive)
10674 (org-add-log-setup 'note nil nil 'findpos nil))
10676 (defvar org-property-end-re)
10677 (defun org-add-log-setup (&optional purpose state prev-state
10678 findpos how &optional extra)
10679 "Set up the post command hook to take a note.
10680 If this is about to TODO state change, the new state is expected in STATE.
10681 When FINDPOS is non-nil, find the correct position for the note in
10682 the current entry. If not, assume that it can be inserted at point.
10683 HOW is an indicator what kind of note should be created.
10684 EXTRA is additional text that will be inserted into the notes buffer."
10685 (let* ((org-log-into-drawer (org-log-into-drawer))
10686 (drawer (cond ((stringp org-log-into-drawer)
10687 org-log-into-drawer)
10688 (org-log-into-drawer "LOGBOOK")
10689 (t nil))))
10690 (save-restriction
10691 (save-excursion
10692 (when findpos
10693 (org-back-to-heading t)
10694 (narrow-to-region (point) (save-excursion
10695 (outline-next-heading) (point)))
10696 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10697 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10698 "[^\r\n]*\\)?"))
10699 (goto-char (match-end 0))
10700 (cond
10701 (drawer
10702 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10703 nil t)
10704 (progn
10705 (goto-char (match-end 0))
10706 (or org-log-states-order-reversed
10707 (and (re-search-forward org-property-end-re nil t)
10708 (goto-char (1- (match-beginning 0))))))
10709 (insert "\n:" drawer ":\n:END:")
10710 (beginning-of-line 0)
10711 (org-indent-line-function)
10712 (beginning-of-line 2)
10713 (org-indent-line-function)
10714 (end-of-line 0)))
10715 ((and org-log-state-notes-insert-after-drawers
10716 (save-excursion
10717 (forward-line) (looking-at org-drawer-regexp)))
10718 (forward-line)
10719 (while (looking-at org-drawer-regexp)
10720 (goto-char (match-end 0))
10721 (re-search-forward org-property-end-re (point-max) t)
10722 (forward-line))
10723 (forward-line -1)))
10724 (unless org-log-states-order-reversed
10725 (and (= (char-after) ?\n) (forward-char 1))
10726 (org-skip-over-state-notes)
10727 (skip-chars-backward " \t\n\r")))
10728 (move-marker org-log-note-marker (point))
10729 (setq org-log-note-purpose purpose
10730 org-log-note-state state
10731 org-log-note-previous-state prev-state
10732 org-log-note-how how
10733 org-log-note-extra extra)
10734 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10736 (defun org-skip-over-state-notes ()
10737 "Skip past the list of State notes in an entry."
10738 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10739 (while (looking-at "[ \t]*- State")
10740 (condition-case nil
10741 (org-next-item)
10742 (error (org-end-of-item)))))
10744 (defun org-add-log-note (&optional purpose)
10745 "Pop up a window for taking a note, and add this note later at point."
10746 (remove-hook 'post-command-hook 'org-add-log-note)
10747 (setq org-log-note-window-configuration (current-window-configuration))
10748 (delete-other-windows)
10749 (move-marker org-log-note-return-to (point))
10750 (switch-to-buffer (marker-buffer org-log-note-marker))
10751 (goto-char org-log-note-marker)
10752 (org-switch-to-buffer-other-window "*Org Note*")
10753 (erase-buffer)
10754 (if (memq org-log-note-how '(time state))
10755 (let (current-prefix-arg) (org-store-log-note))
10756 (let ((org-inhibit-startup t)) (org-mode))
10757 (insert (format "# Insert note for %s.
10758 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10759 (cond
10760 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10761 ((eq org-log-note-purpose 'done) "closed todo item")
10762 ((eq org-log-note-purpose 'state)
10763 (format "state change from \"%s\" to \"%s\""
10764 (or org-log-note-previous-state "")
10765 (or org-log-note-state "")))
10766 ((eq org-log-note-purpose 'reschedule)
10767 "rescheduling")
10768 ((eq org-log-note-purpose 'redeadline)
10769 "changing deadline")
10770 ((eq org-log-note-purpose 'note)
10771 "this entry")
10772 (t (error "This should not happen")))))
10773 (if org-log-note-extra (insert org-log-note-extra))
10774 (org-set-local 'org-finish-function 'org-store-log-note)))
10776 (defvar org-note-abort nil) ; dynamically scoped
10777 (defun org-store-log-note ()
10778 "Finish taking a log note, and insert it to where it belongs."
10779 (let ((txt (buffer-string))
10780 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10781 lines ind)
10782 (kill-buffer (current-buffer))
10783 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10784 (setq txt (replace-match "" t t txt)))
10785 (if (string-match "\\s-+\\'" txt)
10786 (setq txt (replace-match "" t t txt)))
10787 (setq lines (org-split-string txt "\n"))
10788 (when (and note (string-match "\\S-" note))
10789 (setq note
10790 (org-replace-escapes
10791 note
10792 (list (cons "%u" (user-login-name))
10793 (cons "%U" user-full-name)
10794 (cons "%t" (format-time-string
10795 (org-time-stamp-format 'long 'inactive)
10796 (current-time)))
10797 (cons "%s" (if org-log-note-state
10798 (concat "\"" org-log-note-state "\"")
10799 ""))
10800 (cons "%S" (if org-log-note-previous-state
10801 (concat "\"" org-log-note-previous-state "\"")
10802 "\"\"")))))
10803 (if lines (setq note (concat note " \\\\")))
10804 (push note lines))
10805 (when (or current-prefix-arg org-note-abort)
10806 (when org-log-into-drawer
10807 (org-remove-empty-drawer-at
10808 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10809 org-log-note-marker))
10810 (setq lines nil))
10811 (when lines
10812 (with-current-buffer (marker-buffer org-log-note-marker)
10813 (save-excursion
10814 (goto-char org-log-note-marker)
10815 (move-marker org-log-note-marker nil)
10816 (end-of-line 1)
10817 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10818 (insert "- " (pop lines))
10819 (org-indent-line-function)
10820 (beginning-of-line 1)
10821 (looking-at "[ \t]*")
10822 (setq ind (concat (match-string 0) " "))
10823 (end-of-line 1)
10824 (while lines (insert "\n" ind (pop lines)))
10825 (message "Note stored")
10826 (org-back-to-heading t)
10827 (org-cycle-hide-drawers 'children)))))
10828 (set-window-configuration org-log-note-window-configuration)
10829 (with-current-buffer (marker-buffer org-log-note-return-to)
10830 (goto-char org-log-note-return-to))
10831 (move-marker org-log-note-return-to nil)
10832 (and org-log-post-message (message "%s" org-log-post-message)))
10834 (defun org-remove-empty-drawer-at (drawer pos)
10835 "Remove an empty drawer DRAWER at position POS.
10836 POS may also be a marker."
10837 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10838 (save-excursion
10839 (save-restriction
10840 (widen)
10841 (goto-char pos)
10842 (if (org-in-regexp
10843 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10844 (replace-match ""))))))
10846 (defun org-sparse-tree (&optional arg)
10847 "Create a sparse tree, prompt for the details.
10848 This command can create sparse trees. You first need to select the type
10849 of match used to create the tree:
10851 t Show entries with a specific TODO keyword.
10852 m Show entries selected by a tags/property match.
10853 p Enter a property name and its value (both with completion on existing
10854 names/values) and show entries with that property.
10855 / Show entries matching a regular expression (`r' can be used as well)
10856 d Show deadlines due within `org-deadline-warning-days'.
10857 b Show deadlines and scheduled items before a date.
10858 a Show deadlines and scheduled items after a date."
10859 (interactive "P")
10860 (let (ans kwd value)
10861 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10862 (setq ans (read-char-exclusive))
10863 (cond
10864 ((equal ans ?d)
10865 (call-interactively 'org-check-deadlines))
10866 ((equal ans ?b)
10867 (call-interactively 'org-check-before-date))
10868 ((equal ans ?a)
10869 (call-interactively 'org-check-after-date))
10870 ((equal ans ?t)
10871 (org-show-todo-tree '(4)))
10872 ((member ans '(?T ?m))
10873 (call-interactively 'org-match-sparse-tree))
10874 ((member ans '(?p ?P))
10875 (setq kwd (org-icompleting-read "Property: "
10876 (mapcar 'list (org-buffer-property-keys))))
10877 (setq value (org-icompleting-read "Value: "
10878 (mapcar 'list (org-property-values kwd))))
10879 (unless (string-match "\\`{.*}\\'" value)
10880 (setq value (concat "\"" value "\"")))
10881 (org-match-sparse-tree arg (concat kwd "=" value)))
10882 ((member ans '(?r ?R ?/))
10883 (call-interactively 'org-occur))
10884 (t (error "No such sparse tree command \"%c\"" ans)))))
10886 (defvar org-occur-highlights nil
10887 "List of overlays used for occur matches.")
10888 (make-variable-buffer-local 'org-occur-highlights)
10889 (defvar org-occur-parameters nil
10890 "Parameters of the active org-occur calls.
10891 This is a list, each call to org-occur pushes as cons cell,
10892 containing the regular expression and the callback, onto the list.
10893 The list can contain several entries if `org-occur' has been called
10894 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10895 will only contain one set of parameters. When the highlights are
10896 removed (for example with `C-c C-c', or with the next edit (depending
10897 on `org-remove-highlights-with-change'), this variable is emptied
10898 as well.")
10899 (make-variable-buffer-local 'org-occur-parameters)
10901 (defun org-occur (regexp &optional keep-previous callback)
10902 "Make a compact tree which shows all matches of REGEXP.
10903 The tree will show the lines where the regexp matches, and all higher
10904 headlines above the match. It will also show the heading after the match,
10905 to make sure editing the matching entry is easy.
10906 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10907 call to `org-occur' will be kept, to allow stacking of calls to this
10908 command.
10909 If CALLBACK is non-nil, it is a function which is called to confirm
10910 that the match should indeed be shown."
10911 (interactive "sRegexp: \nP")
10912 (when (equal regexp "")
10913 (error "Regexp cannot be empty"))
10914 (unless keep-previous
10915 (org-remove-occur-highlights nil nil t))
10916 (push (cons regexp callback) org-occur-parameters)
10917 (let ((cnt 0))
10918 (save-excursion
10919 (goto-char (point-min))
10920 (if (or (not keep-previous) ; do not want to keep
10921 (not org-occur-highlights)) ; no previous matches
10922 ;; hide everything
10923 (org-overview))
10924 (while (re-search-forward regexp nil t)
10925 (when (or (not callback)
10926 (save-match-data (funcall callback)))
10927 (setq cnt (1+ cnt))
10928 (when org-highlight-sparse-tree-matches
10929 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10930 (org-show-context 'occur-tree))))
10931 (when org-remove-highlights-with-change
10932 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10933 nil 'local))
10934 (unless org-sparse-tree-open-archived-trees
10935 (org-hide-archived-subtrees (point-min) (point-max)))
10936 (run-hooks 'org-occur-hook)
10937 (if (interactive-p)
10938 (message "%d match(es) for regexp %s" cnt regexp))
10939 cnt))
10941 (defun org-show-context (&optional key)
10942 "Make sure point and context and visible.
10943 How much context is shown depends upon the variables
10944 `org-show-hierarchy-above', `org-show-following-heading'. and
10945 `org-show-siblings'."
10946 (let ((heading-p (org-on-heading-p t))
10947 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10948 (following-p (org-get-alist-option org-show-following-heading key))
10949 (entry-p (org-get-alist-option org-show-entry-below key))
10950 (siblings-p (org-get-alist-option org-show-siblings key)))
10951 (catch 'exit
10952 ;; Show heading or entry text
10953 (if (and heading-p (not entry-p))
10954 (org-flag-heading nil) ; only show the heading
10955 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10956 (org-show-hidden-entry))) ; show entire entry
10957 (when following-p
10958 ;; Show next sibling, or heading below text
10959 (save-excursion
10960 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10961 (org-flag-heading nil))))
10962 (when siblings-p (org-show-siblings))
10963 (when hierarchy-p
10964 ;; show all higher headings, possibly with siblings
10965 (save-excursion
10966 (while (and (condition-case nil
10967 (progn (org-up-heading-all 1) t)
10968 (error nil))
10969 (not (bobp)))
10970 (org-flag-heading nil)
10971 (when siblings-p (org-show-siblings))))))))
10973 (defun org-reveal (&optional siblings)
10974 "Show current entry, hierarchy above it, and the following headline.
10975 This can be used to show a consistent set of context around locations
10976 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10977 not t for the search context.
10979 With optional argument SIBLINGS, on each level of the hierarchy all
10980 siblings are shown. This repairs the tree structure to what it would
10981 look like when opened with hierarchical calls to `org-cycle'."
10982 (interactive "P")
10983 (let ((org-show-hierarchy-above t)
10984 (org-show-following-heading t)
10985 (org-show-siblings (if siblings t org-show-siblings)))
10986 (org-show-context nil)))
10988 (defun org-highlight-new-match (beg end)
10989 "Highlight from BEG to END and mark the highlight is an occur headline."
10990 (let ((ov (org-make-overlay beg end)))
10991 (org-overlay-put ov 'face 'secondary-selection)
10992 (push ov org-occur-highlights)))
10994 (defun org-remove-occur-highlights (&optional beg end noremove)
10995 "Remove the occur highlights from the buffer.
10996 BEG and END are ignored. If NOREMOVE is nil, remove this function
10997 from the `before-change-functions' in the current buffer."
10998 (interactive)
10999 (unless org-inhibit-highlight-removal
11000 (mapc 'org-delete-overlay org-occur-highlights)
11001 (setq org-occur-highlights nil)
11002 (setq org-occur-parameters nil)
11003 (unless noremove
11004 (remove-hook 'before-change-functions
11005 'org-remove-occur-highlights 'local))))
11007 ;;;; Priorities
11009 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11010 "Regular expression matching the priority indicator.")
11012 (defvar org-remove-priority-next-time nil)
11014 (defun org-priority-up ()
11015 "Increase the priority of the current item."
11016 (interactive)
11017 (org-priority 'up))
11019 (defun org-priority-down ()
11020 "Decrease the priority of the current item."
11021 (interactive)
11022 (org-priority 'down))
11024 (defun org-priority (&optional action)
11025 "Change the priority of an item by ARG.
11026 ACTION can be `set', `up', `down', or a character."
11027 (interactive)
11028 (unless org-enable-priority-commands
11029 (error "Priority commands are disabled"))
11030 (setq action (or action 'set))
11031 (let (current new news have remove)
11032 (save-excursion
11033 (org-back-to-heading t)
11034 (if (looking-at org-priority-regexp)
11035 (setq current (string-to-char (match-string 2))
11036 have t)
11037 (setq current org-default-priority))
11038 (cond
11039 ((eq action 'remove)
11040 (setq remove t new ?\ ))
11041 ((or (eq action 'set)
11042 (if (featurep 'xemacs) (characterp action) (integerp action)))
11043 (if (not (eq action 'set))
11044 (setq new action)
11045 (message "Priority %c-%c, SPC to remove: "
11046 org-highest-priority org-lowest-priority)
11047 (setq new (read-char-exclusive)))
11048 (if (and (= (upcase org-highest-priority) org-highest-priority)
11049 (= (upcase org-lowest-priority) org-lowest-priority))
11050 (setq new (upcase new)))
11051 (cond ((equal new ?\ ) (setq remove t))
11052 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11053 (error "Priority must be between `%c' and `%c'"
11054 org-highest-priority org-lowest-priority))))
11055 ((eq action 'up)
11056 (if (and (not have) (eq last-command this-command))
11057 (setq new org-lowest-priority)
11058 (setq new (if (and org-priority-start-cycle-with-default (not have))
11059 org-default-priority (1- current)))))
11060 ((eq action 'down)
11061 (if (and (not have) (eq last-command this-command))
11062 (setq new org-highest-priority)
11063 (setq new (if (and org-priority-start-cycle-with-default (not have))
11064 org-default-priority (1+ current)))))
11065 (t (error "Invalid action")))
11066 (if (or (< (upcase new) org-highest-priority)
11067 (> (upcase new) org-lowest-priority))
11068 (setq remove t))
11069 (setq news (format "%c" new))
11070 (if have
11071 (if remove
11072 (replace-match "" t t nil 1)
11073 (replace-match news t t nil 2))
11074 (if remove
11075 (error "No priority cookie found in line")
11076 (let ((case-fold-search nil))
11077 (looking-at org-todo-line-regexp))
11078 (if (match-end 2)
11079 (progn
11080 (goto-char (match-end 2))
11081 (insert " [#" news "]"))
11082 (goto-char (match-beginning 3))
11083 (insert "[#" news "] "))))
11084 (org-preserve-lc (org-set-tags nil 'align)))
11085 (if remove
11086 (message "Priority removed")
11087 (message "Priority of current item set to %s" news))))
11089 (defun org-get-priority (s)
11090 "Find priority cookie and return priority."
11091 (save-match-data
11092 (if (not (string-match org-priority-regexp s))
11093 (* 1000 (- org-lowest-priority org-default-priority))
11094 (* 1000 (- org-lowest-priority
11095 (string-to-char (match-string 2 s)))))))
11097 ;;;; Tags
11099 (defvar org-agenda-archives-mode)
11100 (defvar org-map-continue-from nil
11101 "Position from where mapping should continue.
11102 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11104 (defvar org-scanner-tags nil
11105 "The current tag list while the tags scanner is running.")
11106 (defvar org-trust-scanner-tags nil
11107 "Should `org-get-tags-at' use the tags fro the scanner.
11108 This is for internal dynamical scoping only.
11109 When this is non-nil, the function `org-get-tags-at' will return the value
11110 of `org-scanner-tags' instead of building the list by itself. This
11111 can lead to large speed-ups when the tags scanner is used in a file with
11112 many entries, and when the list of tags is retrieved, for example to
11113 obtain a list of properties. Building the tags list for each entry in such
11114 a file becomes an N^2 operation - but with this variable set, it scales
11115 as N.")
11117 (defun org-scan-tags (action matcher &optional todo-only)
11118 "Scan headline tags with inheritance and produce output ACTION.
11120 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11121 or `agenda' to produce an entry list for an agenda view. It can also be
11122 a Lisp form or a function that should be called at each matched headline, in
11123 this case the return value is a list of all return values from these calls.
11125 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11126 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11127 only lines with a TODO keyword are included in the output."
11128 (require 'org-agenda)
11129 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11130 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11131 (org-re
11132 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11133 (props (list 'face 'default
11134 'done-face 'org-agenda-done
11135 'undone-face 'default
11136 'mouse-face 'highlight
11137 'org-not-done-regexp org-not-done-regexp
11138 'org-todo-regexp org-todo-regexp
11139 'help-echo
11140 (format "mouse-2 or RET jump to org file %s"
11141 (abbreviate-file-name
11142 (or (buffer-file-name (buffer-base-buffer))
11143 (buffer-name (buffer-base-buffer)))))))
11144 (case-fold-search nil)
11145 (org-map-continue-from nil)
11146 lspos tags tags-list
11147 (tags-alist (list (cons 0 org-file-tags)))
11148 (llast 0) rtn rtn1 level category i txt
11149 todo marker entry priority)
11150 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11151 (setq action (list 'lambda nil action)))
11152 (save-excursion
11153 (goto-char (point-min))
11154 (when (eq action 'sparse-tree)
11155 (org-overview)
11156 (org-remove-occur-highlights))
11157 (while (re-search-forward re nil t)
11158 (catch :skip
11159 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11160 tags (if (match-end 4) (org-match-string-no-properties 4)))
11161 (goto-char (setq lspos (match-beginning 0)))
11162 (setq level (org-reduced-level (funcall outline-level))
11163 category (org-get-category))
11164 (setq i llast llast level)
11165 ;; remove tag lists from same and sublevels
11166 (while (>= i level)
11167 (when (setq entry (assoc i tags-alist))
11168 (setq tags-alist (delete entry tags-alist)))
11169 (setq i (1- i)))
11170 ;; add the next tags
11171 (when tags
11172 (setq tags (org-split-string tags ":")
11173 tags-alist
11174 (cons (cons level tags) tags-alist)))
11175 ;; compile tags for current headline
11176 (setq tags-list
11177 (if org-use-tag-inheritance
11178 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11179 tags)
11180 org-scanner-tags tags-list)
11181 (when org-use-tag-inheritance
11182 (setcdr (car tags-alist)
11183 (mapcar (lambda (x)
11184 (setq x (copy-sequence x))
11185 (org-add-prop-inherited x))
11186 (cdar tags-alist))))
11187 (when (and tags org-use-tag-inheritance
11188 (or (not (eq t org-use-tag-inheritance))
11189 org-tags-exclude-from-inheritance))
11190 ;; selective inheritance, remove uninherited ones
11191 (setcdr (car tags-alist)
11192 (org-remove-uniherited-tags (cdar tags-alist))))
11193 (when (and (or (not todo-only)
11194 (and (member todo org-not-done-keywords)
11195 (or (not org-agenda-tags-todo-honor-ignore-options)
11196 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11197 (let ((case-fold-search t)) (eval matcher))
11199 (not (member org-archive-tag tags-list))
11200 ;; we have an archive tag, should we use this anyway?
11201 (or (not org-agenda-skip-archived-trees)
11202 (and (eq action 'agenda) org-agenda-archives-mode))))
11203 (unless (eq action 'sparse-tree) (org-agenda-skip))
11205 ;; select this headline
11207 (cond
11208 ((eq action 'sparse-tree)
11209 (and org-highlight-sparse-tree-matches
11210 (org-get-heading) (match-end 0)
11211 (org-highlight-new-match
11212 (match-beginning 0) (match-beginning 1)))
11213 (org-show-context 'tags-tree))
11214 ((eq action 'agenda)
11215 (setq txt (org-format-agenda-item
11217 (concat
11218 (if (eq org-tags-match-list-sublevels 'indented)
11219 (make-string (1- level) ?.) "")
11220 (org-get-heading))
11221 category
11222 tags-list
11224 priority (org-get-priority txt))
11225 (goto-char lspos)
11226 (setq marker (org-agenda-new-marker))
11227 (org-add-props txt props
11228 'org-marker marker 'org-hd-marker marker 'org-category category
11229 'todo-state todo
11230 'priority priority 'type "tagsmatch")
11231 (push txt rtn))
11232 ((functionp action)
11233 (setq org-map-continue-from nil)
11234 (save-excursion
11235 (setq rtn1 (funcall action))
11236 (push rtn1 rtn)))
11237 (t (error "Invalid action")))
11239 ;; if we are to skip sublevels, jump to end of subtree
11240 (unless org-tags-match-list-sublevels
11241 (org-end-of-subtree t)
11242 (backward-char 1))))
11243 ;; Get the correct position from where to continue
11244 (if org-map-continue-from
11245 (goto-char org-map-continue-from)
11246 (and (= (point) lspos) (end-of-line 1)))))
11247 (when (and (eq action 'sparse-tree)
11248 (not org-sparse-tree-open-archived-trees))
11249 (org-hide-archived-subtrees (point-min) (point-max)))
11250 (nreverse rtn)))
11252 (defun org-remove-uniherited-tags (tags)
11253 "Remove all tags that are not inherited from the list TAGS."
11254 (cond
11255 ((eq org-use-tag-inheritance t)
11256 (if org-tags-exclude-from-inheritance
11257 (org-delete-all org-tags-exclude-from-inheritance tags)
11258 tags))
11259 ((not org-use-tag-inheritance) nil)
11260 ((stringp org-use-tag-inheritance)
11261 (delq nil (mapcar
11262 (lambda (x)
11263 (if (and (string-match org-use-tag-inheritance x)
11264 (not (member x org-tags-exclude-from-inheritance)))
11265 x nil))
11266 tags)))
11267 ((listp org-use-tag-inheritance)
11268 (delq nil (mapcar
11269 (lambda (x)
11270 (if (member x org-use-tag-inheritance) x nil))
11271 tags)))))
11273 (defvar todo-only) ;; dynamically scoped
11275 (defun org-match-sparse-tree (&optional todo-only match)
11276 "Create a sparse tree according to tags string MATCH.
11277 MATCH can contain positive and negative selection of tags, like
11278 \"+WORK+URGENT-WITHBOSS\".
11279 If optional argument TODO-ONLY is non-nil, only select lines that are
11280 also TODO lines."
11281 (interactive "P")
11282 (org-prepare-agenda-buffers (list (current-buffer)))
11283 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11285 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11287 (defvar org-cached-props nil)
11288 (defun org-cached-entry-get (pom property)
11289 (if (or (eq t org-use-property-inheritance)
11290 (and (stringp org-use-property-inheritance)
11291 (string-match org-use-property-inheritance property))
11292 (and (listp org-use-property-inheritance)
11293 (member property org-use-property-inheritance)))
11294 ;; Caching is not possible, check it directly
11295 (org-entry-get pom property 'inherit)
11296 ;; Get all properties, so that we can do complicated checks easily
11297 (cdr (assoc property (or org-cached-props
11298 (setq org-cached-props
11299 (org-entry-properties pom)))))))
11301 (defun org-global-tags-completion-table (&optional files)
11302 "Return the list of all tags in all agenda buffer/files."
11303 (save-excursion
11304 (org-uniquify
11305 (delq nil
11306 (apply 'append
11307 (mapcar
11308 (lambda (file)
11309 (set-buffer (find-file-noselect file))
11310 (append (org-get-buffer-tags)
11311 (mapcar (lambda (x) (if (stringp (car-safe x))
11312 (list (car-safe x)) nil))
11313 org-tag-alist)))
11314 (if (and files (car files))
11315 files
11316 (org-agenda-files))))))))
11318 (defun org-make-tags-matcher (match)
11319 "Create the TAGS//TODO matcher form for the selection string MATCH."
11320 ;; todo-only is scoped dynamically into this function, and the function
11321 ;; may change it if the matcher asks for it.
11322 (unless match
11323 ;; Get a new match request, with completion
11324 (let ((org-last-tags-completion-table
11325 (org-global-tags-completion-table)))
11326 (setq match (org-completing-read-no-i
11327 "Match: " 'org-tags-completion-function nil nil nil
11328 'org-tags-history))))
11330 ;; Parse the string and create a lisp form
11331 (let ((match0 match)
11332 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11333 minus tag mm
11334 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11335 orterms term orlist re-p str-p level-p level-op time-p
11336 prop-p pn pv po cat-p gv rest)
11337 (if (string-match "/+" match)
11338 ;; match contains also a todo-matching request
11339 (progn
11340 (setq tagsmatch (substring match 0 (match-beginning 0))
11341 todomatch (substring match (match-end 0)))
11342 (if (string-match "^!" todomatch)
11343 (setq todo-only t todomatch (substring todomatch 1)))
11344 (if (string-match "^\\s-*$" todomatch)
11345 (setq todomatch nil)))
11346 ;; only matching tags
11347 (setq tagsmatch match todomatch nil))
11349 ;; Make the tags matcher
11350 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11351 (setq tagsmatcher t)
11352 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11353 (while (setq term (pop orterms))
11354 (while (and (equal (substring term -1) "\\") orterms)
11355 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11356 (while (string-match re term)
11357 (setq rest (substring term (match-end 0))
11358 minus (and (match-end 1)
11359 (equal (match-string 1 term) "-"))
11360 tag (match-string 2 term)
11361 re-p (equal (string-to-char tag) ?{)
11362 level-p (match-end 4)
11363 prop-p (match-end 5)
11364 mm (cond
11365 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11366 (level-p
11367 (setq level-op (org-op-to-function (match-string 3 term)))
11368 `(,level-op level ,(string-to-number
11369 (match-string 4 term))))
11370 (prop-p
11371 (setq pn (match-string 5 term)
11372 po (match-string 6 term)
11373 pv (match-string 7 term)
11374 cat-p (equal pn "CATEGORY")
11375 re-p (equal (string-to-char pv) ?{)
11376 str-p (equal (string-to-char pv) ?\")
11377 time-p (save-match-data
11378 (string-match "^\"[[<].*[]>]\"$" pv))
11379 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11380 (if time-p (setq pv (org-matcher-time pv)))
11381 (setq po (org-op-to-function po (if time-p 'time str-p)))
11382 (cond
11383 ((equal pn "CATEGORY")
11384 (setq gv '(get-text-property (point) 'org-category)))
11385 ((equal pn "TODO")
11386 (setq gv 'todo))
11388 (setq gv `(org-cached-entry-get nil ,pn))))
11389 (if re-p
11390 (if (eq po 'org<>)
11391 `(not (string-match ,pv (or ,gv "")))
11392 `(string-match ,pv (or ,gv "")))
11393 (if str-p
11394 `(,po (or ,gv "") ,pv)
11395 `(,po (string-to-number (or ,gv ""))
11396 ,(string-to-number pv) ))))
11397 (t `(member ,tag tags-list)))
11398 mm (if minus (list 'not mm) mm)
11399 term rest)
11400 (push mm tagsmatcher))
11401 (push (if (> (length tagsmatcher) 1)
11402 (cons 'and tagsmatcher)
11403 (car tagsmatcher))
11404 orlist)
11405 (setq tagsmatcher nil))
11406 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11407 (setq tagsmatcher
11408 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11409 ;; Make the todo matcher
11410 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11411 (setq todomatcher t)
11412 (setq orterms (org-split-string todomatch "|") orlist nil)
11413 (while (setq term (pop orterms))
11414 (while (string-match re term)
11415 (setq minus (and (match-end 1)
11416 (equal (match-string 1 term) "-"))
11417 kwd (match-string 2 term)
11418 re-p (equal (string-to-char kwd) ?{)
11419 term (substring term (match-end 0))
11420 mm (if re-p
11421 `(string-match ,(substring kwd 1 -1) todo)
11422 (list 'equal 'todo kwd))
11423 mm (if minus (list 'not mm) mm))
11424 (push mm todomatcher))
11425 (push (if (> (length todomatcher) 1)
11426 (cons 'and todomatcher)
11427 (car todomatcher))
11428 orlist)
11429 (setq todomatcher nil))
11430 (setq todomatcher (if (> (length orlist) 1)
11431 (cons 'or orlist) (car orlist))))
11433 ;; Return the string and lisp forms of the matcher
11434 (setq matcher (if todomatcher
11435 (list 'and tagsmatcher todomatcher)
11436 tagsmatcher))
11437 (cons match0 matcher)))
11439 (defun org-op-to-function (op &optional stringp)
11440 "Turn an operator into the appropriate function."
11441 (setq op
11442 (cond
11443 ((equal op "<" ) '(< string< org-time<))
11444 ((equal op ">" ) '(> org-string> org-time>))
11445 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11446 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11447 ((member op '("=" "==")) '(= string= org-time=))
11448 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11449 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11451 (defun org<> (a b) (not (= a b)))
11452 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11453 (defun org-string>= (a b) (not (string< a b)))
11454 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11455 (defun org-string<> (a b) (not (string= a b)))
11456 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11457 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11458 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11459 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11460 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11461 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11462 (defun org-2ft (s)
11463 "Convert S to a floating point time.
11464 If S is already a number, just return it. If it is a string, parse
11465 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11466 (cond
11467 ((numberp s) s)
11468 ((stringp s)
11469 (condition-case nil
11470 (float-time (apply 'encode-time (org-parse-time-string s)))
11471 (error 0.)))
11472 (t 0.)))
11474 (defun org-time-today ()
11475 "Time in seconds today at 0:00.
11476 Returns the float number of seconds since the beginning of the
11477 epoch to the beginning of today (00:00)."
11478 (float-time (apply 'encode-time
11479 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11481 (defun org-matcher-time (s)
11482 "Interpret a time comparison value."
11483 (save-match-data
11484 (cond
11485 ((string= s "<now>") (float-time))
11486 ((string= s "<today>") (org-time-today))
11487 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11488 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11489 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11490 (+ (org-time-today)
11491 (* (string-to-number (match-string 1 s))
11492 (cdr (assoc (match-string 2 s)
11493 '(("d" . 86400.0) ("w" . 604800.0)
11494 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11495 (t (org-2ft s)))))
11497 (defun org-match-any-p (re list)
11498 "Does re match any element of list?"
11499 (setq list (mapcar (lambda (x) (string-match re x)) list))
11500 (delq nil list))
11502 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11503 (defvar org-tags-overlay (org-make-overlay 1 1))
11504 (org-detach-overlay org-tags-overlay)
11506 (defun org-get-local-tags-at (&optional pos)
11507 "Get a list of tags defined in the current headline."
11508 (org-get-tags-at pos 'local))
11510 (defun org-get-local-tags ()
11511 "Get a list of tags defined in the current headline."
11512 (org-get-tags-at nil 'local))
11514 (defun org-get-tags-at (&optional pos local)
11515 "Get a list of all headline tags applicable at POS.
11516 POS defaults to point. If tags are inherited, the list contains
11517 the targets in the same sequence as the headlines appear, i.e.
11518 the tags of the current headline come last.
11519 When LOCAL is non-nil, only return tags from the current headline,
11520 ignore inherited ones."
11521 (interactive)
11522 (if (and org-trust-scanner-tags
11523 (or (not pos) (equal pos (point)))
11524 (not local))
11525 org-scanner-tags
11526 (let (tags ltags lastpos parent)
11527 (save-excursion
11528 (save-restriction
11529 (widen)
11530 (goto-char (or pos (point)))
11531 (save-match-data
11532 (catch 'done
11533 (condition-case nil
11534 (progn
11535 (org-back-to-heading t)
11536 (while (not (equal lastpos (point)))
11537 (setq lastpos (point))
11538 (when (looking-at
11539 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11540 (setq ltags (org-split-string
11541 (org-match-string-no-properties 1) ":"))
11542 (when parent
11543 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11544 (setq tags (append
11545 (if parent
11546 (org-remove-uniherited-tags ltags)
11547 ltags)
11548 tags)))
11549 (or org-use-tag-inheritance (throw 'done t))
11550 (if local (throw 'done t))
11551 (or (org-up-heading-safe) (error nil))
11552 (setq parent t)))
11553 (error nil)))))
11554 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11556 (defun org-add-prop-inherited (s)
11557 (add-text-properties 0 (length s) '(inherited t) s)
11560 (defun org-toggle-tag (tag &optional onoff)
11561 "Toggle the tag TAG for the current line.
11562 If ONOFF is `on' or `off', don't toggle but set to this state."
11563 (let (res current)
11564 (save-excursion
11565 (org-back-to-heading t)
11566 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11567 (point-at-eol) t)
11568 (progn
11569 (setq current (match-string 1))
11570 (replace-match ""))
11571 (setq current ""))
11572 (setq current (nreverse (org-split-string current ":")))
11573 (cond
11574 ((eq onoff 'on)
11575 (setq res t)
11576 (or (member tag current) (push tag current)))
11577 ((eq onoff 'off)
11578 (or (not (member tag current)) (setq current (delete tag current))))
11579 (t (if (member tag current)
11580 (setq current (delete tag current))
11581 (setq res t)
11582 (push tag current))))
11583 (end-of-line 1)
11584 (if current
11585 (progn
11586 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11587 (org-set-tags nil t))
11588 (delete-horizontal-space))
11589 (run-hooks 'org-after-tags-change-hook))
11590 res))
11592 (defun org-align-tags-here (to-col)
11593 ;; Assumes that this is a headline
11594 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11595 (beginning-of-line 1)
11596 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11597 (< pos (match-beginning 2)))
11598 (progn
11599 (setq tags-l (- (match-end 2) (match-beginning 2)))
11600 (goto-char (match-beginning 1))
11601 (insert " ")
11602 (delete-region (point) (1+ (match-beginning 2)))
11603 (setq ncol (max (1+ (current-column))
11604 (1+ col)
11605 (if (> to-col 0)
11606 to-col
11607 (- (abs to-col) tags-l))))
11608 (setq p (point))
11609 (insert (make-string (- ncol (current-column)) ?\ ))
11610 (setq ncol (current-column))
11611 (when indent-tabs-mode (tabify p (point-at-eol)))
11612 (org-move-to-column (min ncol col) t))
11613 (goto-char pos))))
11615 (defun org-set-tags-command (&optional arg just-align)
11616 "Call the set-tags command for the current entry."
11617 (interactive "P")
11618 (if (org-on-heading-p)
11619 (org-set-tags arg just-align)
11620 (save-excursion
11621 (org-back-to-heading t)
11622 (org-set-tags arg just-align))))
11624 (defun org-set-tags-to (data)
11625 "Set the tags of the current entry to DATA, replacing the current tags.
11626 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11627 If DATA is nil or the empty string, any tags will be removed."
11628 (interactive "sTags: ")
11629 (setq data
11630 (cond
11631 ((eq data nil) "")
11632 ((equal data "") "")
11633 ((stringp data)
11634 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11635 ":"))
11636 ((listp data)
11637 (concat ":" (mapconcat 'identity data ":") ":"))
11638 (t nil)))
11639 (when data
11640 (save-excursion
11641 (org-back-to-heading t)
11642 (when (looking-at org-complex-heading-regexp)
11643 (if (match-end 5)
11644 (progn
11645 (goto-char (match-beginning 5))
11646 (insert data)
11647 (delete-region (point) (point-at-eol))
11648 (org-set-tags nil 'align))
11649 (goto-char (point-at-eol))
11650 (insert " " data)
11651 (org-set-tags nil 'align)))
11652 (beginning-of-line 1)
11653 (if (looking-at ".*?\\([ \t]+\\)$")
11654 (delete-region (match-beginning 1) (match-end 1))))))
11656 (defun org-set-tags (&optional arg just-align)
11657 "Set the tags for the current headline.
11658 With prefix ARG, realign all tags in headings in the current buffer."
11659 (interactive "P")
11660 (let* ((re (concat "^" outline-regexp))
11661 (current (org-get-tags-string))
11662 (col (current-column))
11663 (org-setting-tags t)
11664 table current-tags inherited-tags ; computed below when needed
11665 tags p0 c0 c1 rpl)
11666 (if arg
11667 (save-excursion
11668 (goto-char (point-min))
11669 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11670 (while (re-search-forward re nil t)
11671 (org-set-tags nil t)
11672 (end-of-line 1)))
11673 (message "All tags realigned to column %d" org-tags-column))
11674 (if just-align
11675 (setq tags current)
11676 ;; Get a new set of tags from the user
11677 (save-excursion
11678 (setq table (append org-tag-persistent-alist
11679 (or org-tag-alist (org-get-buffer-tags)))
11680 org-last-tags-completion-table table
11681 current-tags (org-split-string current ":")
11682 inherited-tags (nreverse
11683 (nthcdr (length current-tags)
11684 (nreverse (org-get-tags-at))))
11685 tags
11686 (if (or (eq t org-use-fast-tag-selection)
11687 (and org-use-fast-tag-selection
11688 (delq nil (mapcar 'cdr table))))
11689 (org-fast-tag-selection
11690 current-tags inherited-tags table
11691 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11692 (let ((org-add-colon-after-tag-completion t))
11693 (org-trim
11694 (org-without-partial-completion
11695 (org-icompleting-read "Tags: " 'org-tags-completion-function
11696 nil nil current 'org-tags-history)))))))
11697 (while (string-match "[-+&]+" tags)
11698 ;; No boolean logic, just a list
11699 (setq tags (replace-match ":" t t tags))))
11701 (if org-tags-sort-function
11702 (setq tags (mapconcat 'identity
11703 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11704 org-tags-sort-function) ":")))
11706 (if (string-match "\\`[\t ]*\\'" tags)
11707 (setq tags "")
11708 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11709 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11711 ;; Insert new tags at the correct column
11712 (beginning-of-line 1)
11713 (cond
11714 ((and (equal current "") (equal tags "")))
11715 ((re-search-forward
11716 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11717 (point-at-eol) t)
11718 (if (equal tags "")
11719 (setq rpl "")
11720 (goto-char (match-beginning 0))
11721 (setq c0 (current-column) p0 (point)
11722 c1 (max (1+ c0) (if (> org-tags-column 0)
11723 org-tags-column
11724 (- (- org-tags-column) (length tags))))
11725 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11726 (replace-match rpl t t)
11727 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11728 tags)
11729 (t (error "Tags alignment failed")))
11730 (org-move-to-column col)
11731 (unless just-align
11732 (run-hooks 'org-after-tags-change-hook)))))
11734 (defun org-change-tag-in-region (beg end tag off)
11735 "Add or remove TAG for each entry in the region.
11736 This works in the agenda, and also in an org-mode buffer."
11737 (interactive
11738 (list (region-beginning) (region-end)
11739 (let ((org-last-tags-completion-table
11740 (if (org-mode-p)
11741 (org-get-buffer-tags)
11742 (org-global-tags-completion-table))))
11743 (org-icompleting-read
11744 "Tag: " 'org-tags-completion-function nil nil nil
11745 'org-tags-history))
11746 (progn
11747 (message "[s]et or [r]emove? ")
11748 (equal (read-char-exclusive) ?r))))
11749 (if (fboundp 'deactivate-mark) (deactivate-mark))
11750 (let ((agendap (equal major-mode 'org-agenda-mode))
11751 l1 l2 m buf pos newhead (cnt 0))
11752 (goto-char end)
11753 (setq l2 (1- (org-current-line)))
11754 (goto-char beg)
11755 (setq l1 (org-current-line))
11756 (loop for l from l1 to l2 do
11757 (org-goto-line l)
11758 (setq m (get-text-property (point) 'org-hd-marker))
11759 (when (or (and (org-mode-p) (org-on-heading-p))
11760 (and agendap m))
11761 (setq buf (if agendap (marker-buffer m) (current-buffer))
11762 pos (if agendap m (point)))
11763 (with-current-buffer buf
11764 (save-excursion
11765 (save-restriction
11766 (goto-char pos)
11767 (setq cnt (1+ cnt))
11768 (org-toggle-tag tag (if off 'off 'on))
11769 (setq newhead (org-get-heading)))))
11770 (and agendap (org-agenda-change-all-lines newhead m))))
11771 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11773 (defun org-tags-completion-function (string predicate &optional flag)
11774 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11775 (confirm (lambda (x) (stringp (car x)))))
11776 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11777 (setq s1 (match-string 1 string)
11778 s2 (match-string 2 string))
11779 (setq s1 "" s2 string))
11780 (cond
11781 ((eq flag nil)
11782 ;; try completion
11783 (setq rtn (try-completion s2 ctable confirm))
11784 (if (stringp rtn)
11785 (setq rtn
11786 (concat s1 s2 (substring rtn (length s2))
11787 (if (and org-add-colon-after-tag-completion
11788 (assoc rtn ctable))
11789 ":" ""))))
11790 rtn)
11791 ((eq flag t)
11792 ;; all-completions
11793 (all-completions s2 ctable confirm)
11795 ((eq flag 'lambda)
11796 ;; exact match?
11797 (assoc s2 ctable)))
11800 (defun org-fast-tag-insert (kwd tags face &optional end)
11801 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11802 (insert (format "%-12s" (concat kwd ":"))
11803 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11804 (or end "")))
11806 (defun org-fast-tag-show-exit (flag)
11807 (save-excursion
11808 (org-goto-line 3)
11809 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11810 (replace-match ""))
11811 (when flag
11812 (end-of-line 1)
11813 (org-move-to-column (- (window-width) 19) t)
11814 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11816 (defun org-set-current-tags-overlay (current prefix)
11817 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11818 (if (featurep 'xemacs)
11819 (org-overlay-display org-tags-overlay (concat prefix s)
11820 'secondary-selection)
11821 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11822 (org-overlay-display org-tags-overlay (concat prefix s)))))
11824 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11825 "Fast tag selection with single keys.
11826 CURRENT is the current list of tags in the headline, INHERITED is the
11827 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11828 possibly with grouping information. TODO-TABLE is a similar table with
11829 TODO keywords, should these have keys assigned to them.
11830 If the keys are nil, a-z are automatically assigned.
11831 Returns the new tags string, or nil to not change the current settings."
11832 (let* ((fulltable (append table todo-table))
11833 (maxlen (apply 'max (mapcar
11834 (lambda (x)
11835 (if (stringp (car x)) (string-width (car x)) 0))
11836 fulltable)))
11837 (buf (current-buffer))
11838 (expert (eq org-fast-tag-selection-single-key 'expert))
11839 (buffer-tags nil)
11840 (fwidth (+ maxlen 3 1 3))
11841 (ncol (/ (- (window-width) 4) fwidth))
11842 (i-face 'org-done)
11843 (c-face 'org-todo)
11844 tg cnt e c char c1 c2 ntable tbl rtn
11845 ov-start ov-end ov-prefix
11846 (exit-after-next org-fast-tag-selection-single-key)
11847 (done-keywords org-done-keywords)
11848 groups ingroup)
11849 (save-excursion
11850 (beginning-of-line 1)
11851 (if (looking-at
11852 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11853 (setq ov-start (match-beginning 1)
11854 ov-end (match-end 1)
11855 ov-prefix "")
11856 (setq ov-start (1- (point-at-eol))
11857 ov-end (1+ ov-start))
11858 (skip-chars-forward "^\n\r")
11859 (setq ov-prefix
11860 (concat
11861 (buffer-substring (1- (point)) (point))
11862 (if (> (current-column) org-tags-column)
11864 (make-string (- org-tags-column (current-column)) ?\ ))))))
11865 (org-move-overlay org-tags-overlay ov-start ov-end)
11866 (save-window-excursion
11867 (if expert
11868 (set-buffer (get-buffer-create " *Org tags*"))
11869 (delete-other-windows)
11870 (split-window-vertically)
11871 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11872 (erase-buffer)
11873 (org-set-local 'org-done-keywords done-keywords)
11874 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11875 (org-fast-tag-insert "Current" current c-face "\n\n")
11876 (org-fast-tag-show-exit exit-after-next)
11877 (org-set-current-tags-overlay current ov-prefix)
11878 (setq tbl fulltable char ?a cnt 0)
11879 (while (setq e (pop tbl))
11880 (cond
11881 ((equal (car e) :startgroup)
11882 (push '() groups) (setq ingroup t)
11883 (when (not (= cnt 0))
11884 (setq cnt 0)
11885 (insert "\n"))
11886 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
11887 ((equal (car e) :endgroup)
11888 (setq ingroup nil cnt 0)
11889 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
11890 ((equal e '(:newline))
11891 (when (not (= cnt 0))
11892 (setq cnt 0)
11893 (insert "\n")
11894 (setq e (car tbl))
11895 (while (equal (car tbl) '(:newline))
11896 (insert "\n")
11897 (setq tbl (cdr tbl)))))
11899 (setq tg (copy-sequence (car e)) c2 nil)
11900 (if (cdr e)
11901 (setq c (cdr e))
11902 ;; automatically assign a character.
11903 (setq c1 (string-to-char
11904 (downcase (substring
11905 tg (if (= (string-to-char tg) ?@) 1 0)))))
11906 (if (or (rassoc c1 ntable) (rassoc c1 table))
11907 (while (or (rassoc char ntable) (rassoc char table))
11908 (setq char (1+ char)))
11909 (setq c2 c1))
11910 (setq c (or c2 char)))
11911 (if ingroup (push tg (car groups)))
11912 (setq tg (org-add-props tg nil 'face
11913 (cond
11914 ((not (assoc tg table))
11915 (org-get-todo-face tg))
11916 ((member tg current) c-face)
11917 ((member tg inherited) i-face)
11918 (t nil))))
11919 (if (and (= cnt 0) (not ingroup)) (insert " "))
11920 (insert "[" c "] " tg (make-string
11921 (- fwidth 4 (length tg)) ?\ ))
11922 (push (cons tg c) ntable)
11923 (when (= (setq cnt (1+ cnt)) ncol)
11924 (insert "\n")
11925 (if ingroup (insert " "))
11926 (setq cnt 0)))))
11927 (setq ntable (nreverse ntable))
11928 (insert "\n")
11929 (goto-char (point-min))
11930 (if (not expert) (org-fit-window-to-buffer))
11931 (setq rtn
11932 (catch 'exit
11933 (while t
11934 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
11935 (if (not groups) "no " "")
11936 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11937 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11938 (cond
11939 ((= c ?\r) (throw 'exit t))
11940 ((= c ?!)
11941 (setq groups (not groups))
11942 (goto-char (point-min))
11943 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11944 ((= c ?\C-c)
11945 (if (not expert)
11946 (org-fast-tag-show-exit
11947 (setq exit-after-next (not exit-after-next)))
11948 (setq expert nil)
11949 (delete-other-windows)
11950 (split-window-vertically)
11951 (org-switch-to-buffer-other-window " *Org tags*")
11952 (org-fit-window-to-buffer)))
11953 ((or (= c ?\C-g)
11954 (and (= c ?q) (not (rassoc c ntable))))
11955 (org-detach-overlay org-tags-overlay)
11956 (setq quit-flag t))
11957 ((= c ?\ )
11958 (setq current nil)
11959 (if exit-after-next (setq exit-after-next 'now)))
11960 ((= c ?\t)
11961 (condition-case nil
11962 (setq tg (org-icompleting-read
11963 "Tag: "
11964 (or buffer-tags
11965 (with-current-buffer buf
11966 (org-get-buffer-tags)))))
11967 (quit (setq tg "")))
11968 (when (string-match "\\S-" tg)
11969 (add-to-list 'buffer-tags (list tg))
11970 (if (member tg current)
11971 (setq current (delete tg current))
11972 (push tg current)))
11973 (if exit-after-next (setq exit-after-next 'now)))
11974 ((setq e (rassoc c todo-table) tg (car e))
11975 (with-current-buffer buf
11976 (save-excursion (org-todo tg)))
11977 (if exit-after-next (setq exit-after-next 'now)))
11978 ((setq e (rassoc c ntable) tg (car e))
11979 (if (member tg current)
11980 (setq current (delete tg current))
11981 (loop for g in groups do
11982 (if (member tg g)
11983 (mapc (lambda (x)
11984 (setq current (delete x current)))
11985 g)))
11986 (push tg current))
11987 (if exit-after-next (setq exit-after-next 'now))))
11989 ;; Create a sorted list
11990 (setq current
11991 (sort current
11992 (lambda (a b)
11993 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11994 (if (eq exit-after-next 'now) (throw 'exit t))
11995 (goto-char (point-min))
11996 (beginning-of-line 2)
11997 (delete-region (point) (point-at-eol))
11998 (org-fast-tag-insert "Current" current c-face)
11999 (org-set-current-tags-overlay current ov-prefix)
12000 (while (re-search-forward
12001 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12002 (setq tg (match-string 1))
12003 (add-text-properties
12004 (match-beginning 1) (match-end 1)
12005 (list 'face
12006 (cond
12007 ((member tg current) c-face)
12008 ((member tg inherited) i-face)
12009 (t (get-text-property (match-beginning 1) 'face))))))
12010 (goto-char (point-min)))))
12011 (org-detach-overlay org-tags-overlay)
12012 (if rtn
12013 (mapconcat 'identity current ":")
12014 nil))))
12016 (defun org-get-tags-string ()
12017 "Get the TAGS string in the current headline."
12018 (unless (org-on-heading-p t)
12019 (error "Not on a heading"))
12020 (save-excursion
12021 (beginning-of-line 1)
12022 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12023 (org-match-string-no-properties 1)
12024 "")))
12026 (defun org-get-tags ()
12027 "Get the list of tags specified in the current headline."
12028 (org-split-string (org-get-tags-string) ":"))
12030 (defun org-get-buffer-tags ()
12031 "Get a table of all tags used in the buffer, for completion."
12032 (let (tags)
12033 (save-excursion
12034 (goto-char (point-min))
12035 (while (re-search-forward
12036 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12037 (when (equal (char-after (point-at-bol 0)) ?*)
12038 (mapc (lambda (x) (add-to-list 'tags x))
12039 (org-split-string (org-match-string-no-properties 1) ":")))))
12040 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12041 (mapcar 'list tags)))
12043 ;;;; The mapping API
12045 ;;;###autoload
12046 (defun org-map-entries (func &optional match scope &rest skip)
12047 "Call FUNC at each headline selected by MATCH in SCOPE.
12049 FUNC is a function or a lisp form. The function will be called without
12050 arguments, with the cursor positioned at the beginning of the headline.
12051 The return values of all calls to the function will be collected and
12052 returned as a list.
12054 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12055 does not need to preserve point. After evaluation, the cursor will be
12056 moved to the end of the line (presumably of the headline of the
12057 processed entry) and search continues from there. Under some
12058 circumstances, this may not produce the wanted results. For example,
12059 if you have removed (e.g. archived) the current (sub)tree it could
12060 mean that the next entry will be skipped entirely. In such cases, you
12061 can specify the position from where search should continue by making
12062 FUNC set the variable `org-map-continue-from' to the desired buffer
12063 position.
12065 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12066 Only headlines that are matched by this query will be considered during
12067 the iteration. When MATCH is nil or t, all headlines will be
12068 visited by the iteration.
12070 SCOPE determines the scope of this command. It can be any of:
12072 nil The current buffer, respecting the restriction if any
12073 tree The subtree started with the entry at point
12074 file The current buffer, without restriction
12075 file-with-archives
12076 The current buffer, and any archives associated with it
12077 agenda All agenda files
12078 agenda-with-archives
12079 All agenda files with any archive files associated with them
12080 \(file1 file2 ...)
12081 If this is a list, all files in the list will be scanned
12083 The remaining args are treated as settings for the skipping facilities of
12084 the scanner. The following items can be given here:
12086 archive skip trees with the archive tag.
12087 comment skip trees with the COMMENT keyword
12088 function or Emacs Lisp form:
12089 will be used as value for `org-agenda-skip-function', so whenever
12090 the function returns t, FUNC will not be called for that
12091 entry and search will continue from the point where the
12092 function leaves it.
12094 If your function needs to retrieve the tags including inherited tags
12095 at the *current* entry, you can use the value of the variable
12096 `org-scanner-tags' which will be much faster than getting the value
12097 with `org-get-tags-at'. If your function gets properties with
12098 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12099 to t around the call to `org-entry-properties' to get the same speedup.
12100 Note that if your function moves around to retrieve tags and properties at
12101 a *different* entry, you cannot use these techniques."
12102 (let* ((org-agenda-archives-mode nil) ; just to make sure
12103 (org-agenda-skip-archived-trees (memq 'archive skip))
12104 (org-agenda-skip-comment-trees (memq 'comment skip))
12105 (org-agenda-skip-function
12106 (car (org-delete-all '(comment archive) skip)))
12107 (org-tags-match-list-sublevels t)
12108 matcher file res
12109 org-todo-keywords-for-agenda
12110 org-done-keywords-for-agenda
12111 org-todo-keyword-alist-for-agenda
12112 org-drawers-for-agenda
12113 org-tag-alist-for-agenda)
12115 (cond
12116 ((eq match t) (setq matcher t))
12117 ((eq match nil) (setq matcher t))
12118 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12120 (save-excursion
12121 (save-restriction
12122 (when (eq scope 'tree)
12123 (org-back-to-heading t)
12124 (org-narrow-to-subtree)
12125 (setq scope nil))
12127 (if (not scope)
12128 (progn
12129 (org-prepare-agenda-buffers
12130 (list (buffer-file-name (current-buffer))))
12131 (setq res (org-scan-tags func matcher)))
12132 ;; Get the right scope
12133 (cond
12134 ((and scope (listp scope) (symbolp (car scope)))
12135 (setq scope (eval scope)))
12136 ((eq scope 'agenda)
12137 (setq scope (org-agenda-files t)))
12138 ((eq scope 'agenda-with-archives)
12139 (setq scope (org-agenda-files t))
12140 (setq scope (org-add-archive-files scope)))
12141 ((eq scope 'file)
12142 (setq scope (list (buffer-file-name))))
12143 ((eq scope 'file-with-archives)
12144 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12145 (org-prepare-agenda-buffers scope)
12146 (while (setq file (pop scope))
12147 (with-current-buffer (org-find-base-buffer-visiting file)
12148 (save-excursion
12149 (save-restriction
12150 (widen)
12151 (goto-char (point-min))
12152 (setq res (append res (org-scan-tags func matcher))))))))))
12153 res))
12155 ;;;; Properties
12157 ;;; Setting and retrieving properties
12159 (defconst org-special-properties
12160 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12161 "TIMESTAMP" "TIMESTAMP_IA")
12162 "The special properties valid in Org-mode.
12164 These are properties that are not defined in the property drawer,
12165 but in some other way.")
12167 (defconst org-default-properties
12168 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12169 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12170 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12171 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12172 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12173 "CLOCK_MODELINE_TOTAL" "STYLE")
12174 "Some properties that are used by Org-mode for various purposes.
12175 Being in this list makes sure that they are offered for completion.")
12177 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12178 "Regular expression matching the first line of a property drawer.")
12180 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12181 "Regular expression matching the first line of a property drawer.")
12183 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12184 "Regular expression matching the first line of a property drawer.")
12186 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12187 "Regular expression matching the first line of a property drawer.")
12189 (defconst org-property-drawer-re
12190 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12191 org-property-end-re "\\)\n?")
12192 "Matches an entire property drawer.")
12194 (defconst org-clock-drawer-re
12195 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12196 org-property-end-re "\\)\n?")
12197 "Matches an entire clock drawer.")
12199 (defun org-property-action ()
12200 "Do an action on properties."
12201 (interactive)
12202 (let (c)
12203 (org-at-property-p)
12204 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12205 (setq c (read-char-exclusive))
12206 (cond
12207 ((equal c ?s)
12208 (call-interactively 'org-set-property))
12209 ((equal c ?d)
12210 (call-interactively 'org-delete-property))
12211 ((equal c ?D)
12212 (call-interactively 'org-delete-property-globally))
12213 ((equal c ?c)
12214 (call-interactively 'org-compute-property-at-point))
12215 (t (error "No such property action %c" c)))))
12217 (defun org-set-effort (&optional value)
12218 "Set the effort property of the current entry.
12219 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12220 allowed value."
12221 (interactive "P")
12222 (if (equal value 0) (setq value 10))
12223 (let* ((completion-ignore-case t)
12224 (prop org-effort-property)
12225 (cur (org-entry-get nil prop))
12226 (allowed (org-property-get-allowed-values nil prop 'table))
12227 (existing (mapcar 'list (org-property-values prop)))
12229 (val (cond
12230 ((stringp value) value)
12231 ((and allowed (integerp value))
12232 (or (car (nth (1- value) allowed))
12233 (car (org-last allowed))))
12234 (allowed
12235 (message "Select 1-9,0, [RET%s]: %s"
12236 (if cur (concat "=" cur) "")
12237 (mapconcat 'car allowed " "))
12238 (setq rpl (read-char-exclusive))
12239 (if (equal rpl ?\r)
12241 (setq rpl (- rpl ?0))
12242 (if (equal rpl 0) (setq rpl 10))
12243 (if (and (> rpl 0) (<= rpl (length allowed)))
12244 (car (nth (1- rpl) allowed))
12245 (org-completing-read "Effort: " allowed nil))))
12247 (let (org-completion-use-ido org-completion-use-iswitchb)
12248 (org-completing-read
12249 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12250 (concat "[" cur "]") "")
12251 ": ")
12252 existing nil nil "" nil cur))))))
12253 (unless (equal (org-entry-get nil prop) val)
12254 (org-entry-put nil prop val))
12255 (message "%s is now %s" prop val)))
12257 (defun org-at-property-p ()
12258 "Is the cursor in a property line?"
12259 ;; FIXME: Does not check if we are actually in the drawer.
12260 ;; FIXME: also returns true on any drawers.....
12261 ;; This is used by C-c C-c for property action.
12262 (save-excursion
12263 (beginning-of-line 1)
12264 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
12266 (defun org-get-property-block (&optional beg end force)
12267 "Return the (beg . end) range of the body of the property drawer.
12268 BEG and END can be beginning and end of subtree, if not given
12269 they will be found.
12270 If the drawer does not exist and FORCE is non-nil, create the drawer."
12271 (catch 'exit
12272 (save-excursion
12273 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12274 (end (or end (progn (outline-next-heading) (point)))))
12275 (goto-char beg)
12276 (if (re-search-forward org-property-start-re end t)
12277 (setq beg (1+ (match-end 0)))
12278 (if force
12279 (save-excursion
12280 (org-insert-property-drawer)
12281 (setq end (progn (outline-next-heading) (point))))
12282 (throw 'exit nil))
12283 (goto-char beg)
12284 (if (re-search-forward org-property-start-re end t)
12285 (setq beg (1+ (match-end 0)))))
12286 (if (re-search-forward org-property-end-re end t)
12287 (setq end (match-beginning 0))
12288 (or force (throw 'exit nil))
12289 (goto-char beg)
12290 (setq end beg)
12291 (org-indent-line-function)
12292 (insert ":END:\n"))
12293 (cons beg end)))))
12295 (defun org-entry-properties (&optional pom which)
12296 "Get all properties of the entry at point-or-marker POM.
12297 This includes the TODO keyword, the tags, time strings for deadline,
12298 scheduled, and clocking, and any additional properties defined in the
12299 entry. The return value is an alist, keys may occur multiple times
12300 if the property key was used several times.
12301 POM may also be nil, in which case the current entry is used.
12302 If WHICH is nil or `all', get all properties. If WHICH is
12303 `special' or `standard', only get that subclass."
12304 (setq which (or which 'all))
12305 (org-with-point-at pom
12306 (let ((clockstr (substring org-clock-string 0 -1))
12307 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
12308 beg end range props sum-props key value string clocksum)
12309 (save-excursion
12310 (when (condition-case nil
12311 (and (org-mode-p) (org-back-to-heading t))
12312 (error nil))
12313 (setq beg (point))
12314 (setq sum-props (get-text-property (point) 'org-summaries))
12315 (setq clocksum (get-text-property (point) :org-clock-minutes))
12316 (outline-next-heading)
12317 (setq end (point))
12318 (when (memq which '(all special))
12319 ;; Get the special properties, like TODO and tags
12320 (goto-char beg)
12321 (when (and (looking-at org-todo-line-regexp) (match-end 2))
12322 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12323 (when (looking-at org-priority-regexp)
12324 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12325 (when (and (setq value (org-get-tags-string))
12326 (string-match "\\S-" value))
12327 (push (cons "TAGS" value) props))
12328 (when (setq value (org-get-tags-at))
12329 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
12330 props))
12331 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12332 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12333 string (if (equal key clockstr)
12334 (org-no-properties
12335 (org-trim
12336 (buffer-substring
12337 (match-beginning 3) (goto-char (point-at-eol)))))
12338 (substring (org-match-string-no-properties 3) 1 -1)))
12339 (unless key
12340 (if (= (char-after (match-beginning 3)) ?\[)
12341 (setq key "TIMESTAMP_IA")
12342 (setq key "TIMESTAMP")))
12343 (when (or (equal key clockstr) (not (assoc key props)))
12344 (push (cons key string) props)))
12348 (when (memq which '(all standard))
12349 ;; Get the standard properties, like :PROP: ...
12350 (setq range (org-get-property-block beg end))
12351 (when range
12352 (goto-char (car range))
12353 (while (re-search-forward
12354 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12355 (cdr range) t)
12356 (setq key (org-match-string-no-properties 1)
12357 value (org-trim (or (org-match-string-no-properties 2) "")))
12358 (unless (member key excluded)
12359 (push (cons key (or value "")) props)))))
12360 (if clocksum
12361 (push (cons "CLOCKSUM"
12362 (org-columns-number-to-string (/ (float clocksum) 60.)
12363 'add_times))
12364 props))
12365 (unless (assoc "CATEGORY" props)
12366 (setq value (or (org-get-category)
12367 (progn (org-refresh-category-properties)
12368 (org-get-category))))
12369 (push (cons "CATEGORY" value) props))
12370 (append sum-props (nreverse props)))))))
12372 (defun org-entry-get (pom property &optional inherit)
12373 "Get value of PROPERTY for entry at point-or-marker POM.
12374 If INHERIT is non-nil and the entry does not have the property,
12375 then also check higher levels of the hierarchy.
12376 If INHERIT is the symbol `selective', use inheritance only if the setting
12377 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12378 If the property is present but empty, the return value is the empty string.
12379 If the property is not present at all, nil is returned."
12380 (org-with-point-at pom
12381 (if (and inherit (if (eq inherit 'selective)
12382 (org-property-inherit-p property)
12384 (org-entry-get-with-inheritance property)
12385 (if (member property org-special-properties)
12386 ;; We need a special property. Use brute force, get all properties.
12387 (cdr (assoc property (org-entry-properties nil 'special)))
12388 (let ((range (org-get-property-block)))
12389 (if (and range
12390 (goto-char (car range))
12391 (re-search-forward
12392 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12393 (cdr range) t))
12394 ;; Found the property, return it.
12395 (if (match-end 1)
12396 (org-match-string-no-properties 1)
12397 "")))))))
12399 (defun org-property-or-variable-value (var &optional inherit)
12400 "Check if there is a property fixing the value of VAR.
12401 If yes, return this value. If not, return the current value of the variable."
12402 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12403 (if (and prop (stringp prop) (string-match "\\S-" prop))
12404 (read prop)
12405 (symbol-value var))))
12407 (defun org-entry-delete (pom property)
12408 "Delete the property PROPERTY from entry at point-or-marker POM."
12409 (org-with-point-at pom
12410 (if (member property org-special-properties)
12411 nil ; cannot delete these properties.
12412 (let ((range (org-get-property-block)))
12413 (if (and range
12414 (goto-char (car range))
12415 (re-search-forward
12416 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12417 (cdr range) t))
12418 (progn
12419 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12421 nil)))))
12423 ;; Multi-values properties are properties that contain multiple values
12424 ;; These values are assumed to be single words, separated by whitespace.
12425 (defun org-entry-add-to-multivalued-property (pom property value)
12426 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12427 (let* ((old (org-entry-get pom property))
12428 (values (and old (org-split-string old "[ \t]"))))
12429 (setq value (org-entry-protect-space value))
12430 (unless (member value values)
12431 (setq values (cons value values))
12432 (org-entry-put pom property
12433 (mapconcat 'identity values " ")))))
12435 (defun org-entry-remove-from-multivalued-property (pom property value)
12436 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12437 (let* ((old (org-entry-get pom property))
12438 (values (and old (org-split-string old "[ \t]"))))
12439 (setq value (org-entry-protect-space value))
12440 (when (member value values)
12441 (setq values (delete value values))
12442 (org-entry-put pom property
12443 (mapconcat 'identity values " ")))))
12445 (defun org-entry-member-in-multivalued-property (pom property value)
12446 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12447 (let* ((old (org-entry-get pom property))
12448 (values (and old (org-split-string old "[ \t]"))))
12449 (setq value (org-entry-protect-space value))
12450 (member value values)))
12452 (defun org-entry-get-multivalued-property (pom property)
12453 "Return a list of values in a multivalued property."
12454 (let* ((value (org-entry-get pom property))
12455 (values (and value (org-split-string value "[ \t]"))))
12456 (mapcar 'org-entry-restore-space values)))
12458 (defun org-entry-put-multivalued-property (pom property &rest values)
12459 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12460 VALUES should be a list of strings. Spaces will be protected."
12461 (org-entry-put pom property
12462 (mapconcat 'org-entry-protect-space values " "))
12463 (let* ((value (org-entry-get pom property))
12464 (values (and value (org-split-string value "[ \t]"))))
12465 (mapcar 'org-entry-restore-space values)))
12467 (defun org-entry-protect-space (s)
12468 "Protect spaces and newline in string S."
12469 (while (string-match " " s)
12470 (setq s (replace-match "%20" t t s)))
12471 (while (string-match "\n" s)
12472 (setq s (replace-match "%0A" t t s)))
12475 (defun org-entry-restore-space (s)
12476 "Restore spaces and newline in string S."
12477 (while (string-match "%20" s)
12478 (setq s (replace-match " " t t s)))
12479 (while (string-match "%0A" s)
12480 (setq s (replace-match "\n" t t s)))
12483 (defvar org-entry-property-inherited-from (make-marker)
12484 "Marker pointing to the entry from where a property was inherited.
12485 Each call to `org-entry-get-with-inheritance' will set this marker to the
12486 location of the entry where the inheritance search matched. If there was
12487 no match, the marker will point nowhere.
12488 Note that also `org-entry-get' calls this function, if the INHERIT flag
12489 is set.")
12491 (defun org-entry-get-with-inheritance (property)
12492 "Get entry property, and search higher levels if not present."
12493 (move-marker org-entry-property-inherited-from nil)
12494 (let (tmp)
12495 (save-excursion
12496 (save-restriction
12497 (widen)
12498 (catch 'ex
12499 (while t
12500 (when (setq tmp (org-entry-get nil property))
12501 (org-back-to-heading t)
12502 (move-marker org-entry-property-inherited-from (point))
12503 (throw 'ex tmp))
12504 (or (org-up-heading-safe) (throw 'ex nil)))))
12505 (or tmp
12506 (cdr (assoc property org-file-properties))
12507 (cdr (assoc property org-global-properties))
12508 (cdr (assoc property org-global-properties-fixed))))))
12510 (defun org-entry-put (pom property value)
12511 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12512 (org-with-point-at pom
12513 (org-back-to-heading t)
12514 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12515 range)
12516 (cond
12517 ((equal property "TODO")
12518 (when (and (stringp value) (string-match "\\S-" value)
12519 (not (member value org-todo-keywords-1)))
12520 (error "\"%s\" is not a valid TODO state" value))
12521 (if (or (not value)
12522 (not (string-match "\\S-" value)))
12523 (setq value 'none))
12524 (org-todo value)
12525 (org-set-tags nil 'align))
12526 ((equal property "PRIORITY")
12527 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12528 (string-to-char value) ?\ ))
12529 (org-set-tags nil 'align))
12530 ((equal property "SCHEDULED")
12531 (if (re-search-forward org-scheduled-time-regexp end t)
12532 (cond
12533 ((eq value 'earlier) (org-timestamp-change -1 'day))
12534 ((eq value 'later) (org-timestamp-change 1 'day))
12535 (t (call-interactively 'org-schedule)))
12536 (call-interactively 'org-schedule)))
12537 ((equal property "DEADLINE")
12538 (if (re-search-forward org-deadline-time-regexp end t)
12539 (cond
12540 ((eq value 'earlier) (org-timestamp-change -1 'day))
12541 ((eq value 'later) (org-timestamp-change 1 'day))
12542 (t (call-interactively 'org-deadline)))
12543 (call-interactively 'org-deadline)))
12544 ((member property org-special-properties)
12545 (error "The %s property can not yet be set with `org-entry-put'"
12546 property))
12547 (t ; a non-special property
12548 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12549 (setq range (org-get-property-block beg end 'force))
12550 (goto-char (car range))
12551 (if (re-search-forward
12552 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12553 (progn
12554 (delete-region (match-beginning 1) (match-end 1))
12555 (goto-char (match-beginning 1)))
12556 (goto-char (cdr range))
12557 (insert "\n")
12558 (backward-char 1)
12559 (org-indent-line-function)
12560 (insert ":" property ":"))
12561 (and value (insert " " value))
12562 (org-indent-line-function)))))))
12564 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12565 "Get all property keys in the current buffer.
12566 With INCLUDE-SPECIALS, also list the special properties that reflect things
12567 like tags and TODO state.
12568 With INCLUDE-DEFAULTS, also include properties that has special meaning
12569 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12570 With INCLUDE-COLUMNS, also include property names given in COLUMN
12571 formats in the current buffer."
12572 (let (rtn range cfmt s p)
12573 (save-excursion
12574 (save-restriction
12575 (widen)
12576 (goto-char (point-min))
12577 (while (re-search-forward org-property-start-re nil t)
12578 (setq range (org-get-property-block))
12579 (goto-char (car range))
12580 (while (re-search-forward
12581 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12582 (cdr range) t)
12583 (add-to-list 'rtn (org-match-string-no-properties 1)))
12584 (outline-next-heading))))
12586 (when include-specials
12587 (setq rtn (append org-special-properties rtn)))
12589 (when include-defaults
12590 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12591 (add-to-list 'rtn org-effort-property))
12593 (when include-columns
12594 (save-excursion
12595 (save-restriction
12596 (widen)
12597 (goto-char (point-min))
12598 (while (re-search-forward
12599 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12600 nil t)
12601 (setq cfmt (match-string 2) s 0)
12602 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12603 cfmt s)
12604 (setq s (match-end 0)
12605 p (match-string 1 cfmt))
12606 (unless (or (equal p "ITEM")
12607 (member p org-special-properties))
12608 (add-to-list 'rtn (match-string 1 cfmt))))))))
12610 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12612 (defun org-property-values (key)
12613 "Return a list of all values of property KEY."
12614 (save-excursion
12615 (save-restriction
12616 (widen)
12617 (goto-char (point-min))
12618 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12619 values)
12620 (while (re-search-forward re nil t)
12621 (add-to-list 'values (org-trim (match-string 1))))
12622 (delete "" values)))))
12624 (defun org-insert-property-drawer ()
12625 "Insert a property drawer into the current entry."
12626 (interactive)
12627 (org-back-to-heading t)
12628 (looking-at outline-regexp)
12629 (let ((indent (if org-adapt-indentation
12630 (- (match-end 0)(match-beginning 0))
12632 (beg (point))
12633 (re (concat "^[ \t]*" org-keyword-time-regexp))
12634 end hiddenp)
12635 (outline-next-heading)
12636 (setq end (point))
12637 (goto-char beg)
12638 (while (re-search-forward re end t))
12639 (setq hiddenp (org-invisible-p))
12640 (end-of-line 1)
12641 (and (equal (char-after) ?\n) (forward-char 1))
12642 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12643 (if (member (match-string 1) '("CLOCK:" ":END:"))
12644 ;; just skip this line
12645 (beginning-of-line 2)
12646 ;; Drawer start, find the end
12647 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12648 (beginning-of-line 1)))
12649 (org-skip-over-state-notes)
12650 (skip-chars-backward " \t\n\r")
12651 (if (eq (char-before) ?*) (forward-char 1))
12652 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12653 (beginning-of-line 0)
12654 (org-indent-to-column indent)
12655 (beginning-of-line 2)
12656 (org-indent-to-column indent)
12657 (beginning-of-line 0)
12658 (if hiddenp
12659 (save-excursion
12660 (org-back-to-heading t)
12661 (hide-entry))
12662 (org-flag-drawer t))))
12664 (defun org-set-property (property value)
12665 "In the current entry, set PROPERTY to VALUE.
12666 When called interactively, this will prompt for a property name, offering
12667 completion on existing and default properties. And then it will prompt
12668 for a value, offering completion either on allowed values (via an inherited
12669 xxx_ALL property) or on existing values in other instances of this property
12670 in the current file."
12671 (interactive
12672 (let* ((completion-ignore-case t)
12673 (keys (org-buffer-property-keys nil t t))
12674 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12675 (prop (if (member prop0 keys)
12676 prop0
12677 (or (cdr (assoc (downcase prop0)
12678 (mapcar (lambda (x) (cons (downcase x) x))
12679 keys)))
12680 prop0)))
12681 (cur (org-entry-get nil prop))
12682 (allowed (org-property-get-allowed-values nil prop 'table))
12683 (existing (mapcar 'list (org-property-values prop)))
12684 (val (if allowed
12685 (org-completing-read "Value: " allowed nil 'req-match)
12686 (let (org-completion-use-ido org-completion-use-iswitchb)
12687 (org-completing-read
12688 (concat "Value " (if (and cur (string-match "\\S-" cur))
12689 (concat "[" cur "]") "")
12690 ": ")
12691 existing nil nil "" nil cur)))))
12692 (list prop (if (equal val "") cur val))))
12693 (unless (equal (org-entry-get nil property) value)
12694 (org-entry-put nil property value)))
12696 (defun org-delete-property (property)
12697 "In the current entry, delete PROPERTY."
12698 (interactive
12699 (let* ((completion-ignore-case t)
12700 (prop (org-icompleting-read
12701 "Property: " (org-entry-properties nil 'standard))))
12702 (list prop)))
12703 (message "Property %s %s" property
12704 (if (org-entry-delete nil property)
12705 "deleted"
12706 "was not present in the entry")))
12708 (defun org-delete-property-globally (property)
12709 "Remove PROPERTY globally, from all entries."
12710 (interactive
12711 (let* ((completion-ignore-case t)
12712 (prop (org-icompleting-read
12713 "Globally remove property: "
12714 (mapcar 'list (org-buffer-property-keys)))))
12715 (list prop)))
12716 (save-excursion
12717 (save-restriction
12718 (widen)
12719 (goto-char (point-min))
12720 (let ((cnt 0))
12721 (while (re-search-forward
12722 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12723 nil t)
12724 (setq cnt (1+ cnt))
12725 (replace-match ""))
12726 (message "Property \"%s\" removed from %d entries" property cnt)))))
12728 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12730 (defun org-compute-property-at-point ()
12731 "Compute the property at point.
12732 This looks for an enclosing column format, extracts the operator and
12733 then applies it to the property in the column format's scope."
12734 (interactive)
12735 (unless (org-at-property-p)
12736 (error "Not at a property"))
12737 (let ((prop (org-match-string-no-properties 2)))
12738 (org-columns-get-format-and-top-level)
12739 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12740 (error "No operator defined for property %s" prop))
12741 (org-columns-compute prop)))
12743 (defun org-property-get-allowed-values (pom property &optional table)
12744 "Get allowed values for the property PROPERTY.
12745 When TABLE is non-nil, return an alist that can directly be used for
12746 completion."
12747 (let (vals)
12748 (cond
12749 ((equal property "TODO")
12750 (setq vals (org-with-point-at pom
12751 (append org-todo-keywords-1 '("")))))
12752 ((equal property "PRIORITY")
12753 (let ((n org-lowest-priority))
12754 (while (>= n org-highest-priority)
12755 (push (char-to-string n) vals)
12756 (setq n (1- n)))))
12757 ((member property org-special-properties))
12759 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12761 (when (and vals (string-match "\\S-" vals))
12762 (setq vals (car (read-from-string (concat "(" vals ")"))))
12763 (setq vals (mapcar (lambda (x)
12764 (cond ((stringp x) x)
12765 ((numberp x) (number-to-string x))
12766 ((symbolp x) (symbol-name x))
12767 (t "???")))
12768 vals)))))
12769 (if table (mapcar 'list vals) vals)))
12771 (defun org-property-previous-allowed-value (&optional previous)
12772 "Switch to the next allowed value for this property."
12773 (interactive)
12774 (org-property-next-allowed-value t))
12776 (defun org-property-next-allowed-value (&optional previous)
12777 "Switch to the next allowed value for this property."
12778 (interactive)
12779 (unless (org-at-property-p)
12780 (error "Not at a property"))
12781 (let* ((key (match-string 2))
12782 (value (match-string 3))
12783 (allowed (or (org-property-get-allowed-values (point) key)
12784 (and (member value '("[ ]" "[-]" "[X]"))
12785 '("[ ]" "[X]"))))
12786 nval)
12787 (unless allowed
12788 (error "Allowed values for this property have not been defined"))
12789 (if previous (setq allowed (reverse allowed)))
12790 (if (member value allowed)
12791 (setq nval (car (cdr (member value allowed)))))
12792 (setq nval (or nval (car allowed)))
12793 (if (equal nval value)
12794 (error "Only one allowed value for this property"))
12795 (org-at-property-p)
12796 (replace-match (concat " :" key ": " nval) t t)
12797 (org-indent-line-function)
12798 (beginning-of-line 1)
12799 (skip-chars-forward " \t")))
12801 (defun org-find-entry-with-id (ident)
12802 "Locate the entry that contains the ID property with exact value IDENT.
12803 IDENT can be a string, a symbol or a number, this function will search for
12804 the string representation of it.
12805 Return the position where this entry starts, or nil if there is no such entry."
12806 (interactive "sID: ")
12807 (let ((id (cond
12808 ((stringp ident) ident)
12809 ((symbol-name ident) (symbol-name ident))
12810 ((numberp ident) (number-to-string ident))
12811 (t (error "IDENT %s must be a string, symbol or number" ident))))
12812 (case-fold-search nil))
12813 (save-excursion
12814 (save-restriction
12815 (widen)
12816 (goto-char (point-min))
12817 (when (re-search-forward
12818 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12819 nil t)
12820 (org-back-to-heading t)
12821 (point))))))
12823 ;;;; Timestamps
12825 (defvar org-last-changed-timestamp nil)
12826 (defvar org-last-inserted-timestamp nil
12827 "The last time stamp inserted with `org-insert-time-stamp'.")
12828 (defvar org-time-was-given) ; dynamically scoped parameter
12829 (defvar org-end-time-was-given) ; dynamically scoped parameter
12830 (defvar org-ts-what) ; dynamically scoped parameter
12832 (defun org-time-stamp (arg &optional inactive)
12833 "Prompt for a date/time and insert a time stamp.
12834 If the user specifies a time like HH:MM, or if this command is called
12835 with a prefix argument, the time stamp will contain date and time.
12836 Otherwise, only the date will be included. All parts of a date not
12837 specified by the user will be filled in from the current date/time.
12838 So if you press just return without typing anything, the time stamp
12839 will represent the current date/time. If there is already a timestamp
12840 at the cursor, it will be modified."
12841 (interactive "P")
12842 (let* ((ts nil)
12843 (default-time
12844 ;; Default time is either today, or, when entering a range,
12845 ;; the range start.
12846 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12847 (save-excursion
12848 (re-search-backward
12849 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12850 (- (point) 20) t)))
12851 (apply 'encode-time (org-parse-time-string (match-string 1)))
12852 (current-time)))
12853 (default-input (and ts (org-get-compact-tod ts)))
12854 org-time-was-given org-end-time-was-given time)
12855 (cond
12856 ((and (org-at-timestamp-p t)
12857 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12858 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12859 (insert "--")
12860 (setq time (let ((this-command this-command))
12861 (org-read-date arg 'totime nil nil
12862 default-time default-input)))
12863 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12864 ((org-at-timestamp-p t)
12865 (setq time (let ((this-command this-command))
12866 (org-read-date arg 'totime nil nil default-time default-input)))
12867 (when (org-at-timestamp-p t) ; just to get the match data
12868 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12869 (replace-match "")
12870 (setq org-last-changed-timestamp
12871 (org-insert-time-stamp
12872 time (or org-time-was-given arg)
12873 inactive nil nil (list org-end-time-was-given))))
12874 (message "Timestamp updated"))
12876 (setq time (let ((this-command this-command))
12877 (org-read-date arg 'totime nil nil default-time default-input)))
12878 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12879 nil nil (list org-end-time-was-given))))))
12881 ;; FIXME: can we use this for something else, like computing time differences?
12882 (defun org-get-compact-tod (s)
12883 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12884 (let* ((t1 (match-string 1 s))
12885 (h1 (string-to-number (match-string 2 s)))
12886 (m1 (string-to-number (match-string 3 s)))
12887 (t2 (and (match-end 4) (match-string 5 s)))
12888 (h2 (and t2 (string-to-number (match-string 6 s))))
12889 (m2 (and t2 (string-to-number (match-string 7 s))))
12890 dh dm)
12891 (if (not t2)
12893 (setq dh (- h2 h1) dm (- m2 m1))
12894 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12895 (concat t1 "+" (number-to-string dh)
12896 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12898 (defun org-time-stamp-inactive (&optional arg)
12899 "Insert an inactive time stamp.
12900 An inactive time stamp is enclosed in square brackets instead of angle
12901 brackets. It is inactive in the sense that it does not trigger agenda entries,
12902 does not link to the calendar and cannot be changed with the S-cursor keys.
12903 So these are more for recording a certain time/date."
12904 (interactive "P")
12905 (org-time-stamp arg 'inactive))
12907 (defvar org-date-ovl (org-make-overlay 1 1))
12908 (org-overlay-put org-date-ovl 'face 'org-warning)
12909 (org-detach-overlay org-date-ovl)
12911 (defvar org-ans1) ; dynamically scoped parameter
12912 (defvar org-ans2) ; dynamically scoped parameter
12914 (defvar org-plain-time-of-day-regexp) ; defined below
12916 (defvar org-overriding-default-time nil) ; dynamically scoped
12917 (defvar org-read-date-overlay nil)
12918 (defvar org-dcst nil) ; dynamically scoped
12919 (defvar org-read-date-history nil)
12920 (defvar org-read-date-final-answer nil)
12922 (defun org-read-date (&optional with-time to-time from-string prompt
12923 default-time default-input)
12924 "Read a date, possibly a time, and make things smooth for the user.
12925 The prompt will suggest to enter an ISO date, but you can also enter anything
12926 which will at least partially be understood by `parse-time-string'.
12927 Unrecognized parts of the date will default to the current day, month, year,
12928 hour and minute. If this command is called to replace a timestamp at point,
12929 of to enter the second timestamp of a range, the default time is taken from the
12930 existing stamp. For example,
12931 3-2-5 --> 2003-02-05
12932 feb 15 --> currentyear-02-15
12933 sep 12 9 --> 2009-09-12
12934 12:45 --> today 12:45
12935 22 sept 0:34 --> currentyear-09-22 0:34
12936 12 --> currentyear-currentmonth-12
12937 Fri --> nearest Friday (today or later)
12938 etc.
12940 Furthermore you can specify a relative date by giving, as the *first* thing
12941 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12942 change in days weeks, months, years.
12943 With a single plus or minus, the date is relative to today. With a double
12944 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12945 +4d --> four days from today
12946 +4 --> same as above
12947 +2w --> two weeks from today
12948 ++5 --> five days from default date
12950 The function understands only English month and weekday abbreviations,
12951 but this can be configured with the variables `parse-time-months' and
12952 `parse-time-weekdays'.
12954 While prompting, a calendar is popped up - you can also select the
12955 date with the mouse (button 1). The calendar shows a period of three
12956 months. To scroll it to other months, use the keys `>' and `<'.
12957 If you don't like the calendar, turn it off with
12958 \(setq org-read-date-popup-calendar nil)
12960 With optional argument TO-TIME, the date will immediately be converted
12961 to an internal time.
12962 With an optional argument WITH-TIME, the prompt will suggest to also
12963 insert a time. Note that when WITH-TIME is not set, you can still
12964 enter a time, and this function will inform the calling routine about
12965 this change. The calling routine may then choose to change the format
12966 used to insert the time stamp into the buffer to include the time.
12967 With optional argument FROM-STRING, read from this string instead from
12968 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12969 the time/date that is used for everything that is not specified by the
12970 user."
12971 (require 'parse-time)
12972 (let* ((org-time-stamp-rounding-minutes
12973 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12974 (org-dcst org-display-custom-times)
12975 (ct (org-current-time))
12976 (def (or org-overriding-default-time default-time ct))
12977 (defdecode (decode-time def))
12978 (dummy (progn
12979 (when (< (nth 2 defdecode) org-extend-today-until)
12980 (setcar (nthcdr 2 defdecode) -1)
12981 (setcar (nthcdr 1 defdecode) 59)
12982 (setq def (apply 'encode-time defdecode)
12983 defdecode (decode-time def)))))
12984 (calendar-frame-setup nil)
12985 (calendar-move-hook nil)
12986 (calendar-view-diary-initially-flag nil)
12987 (view-diary-entries-initially nil)
12988 (calendar-view-holidays-initially-flag nil)
12989 (view-calendar-holidays-initially nil)
12990 (timestr (format-time-string
12991 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12992 (prompt (concat (if prompt (concat prompt " ") "")
12993 (format "Date+time [%s]: " timestr)))
12994 ans (org-ans0 "") org-ans1 org-ans2 final)
12996 (cond
12997 (from-string (setq ans from-string))
12998 (org-read-date-popup-calendar
12999 (save-excursion
13000 (save-window-excursion
13001 (calendar)
13002 (calendar-forward-day (- (time-to-days def)
13003 (calendar-absolute-from-gregorian
13004 (calendar-current-date))))
13005 (org-eval-in-calendar nil t)
13006 (let* ((old-map (current-local-map))
13007 (map (copy-keymap calendar-mode-map))
13008 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13009 (org-defkey map (kbd "RET") 'org-calendar-select)
13010 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
13011 'org-calendar-select-mouse)
13012 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
13013 'org-calendar-select-mouse)
13014 (org-defkey minibuffer-local-map [(meta shift left)]
13015 (lambda () (interactive)
13016 (org-eval-in-calendar '(calendar-backward-month 1))))
13017 (org-defkey minibuffer-local-map [(meta shift right)]
13018 (lambda () (interactive)
13019 (org-eval-in-calendar '(calendar-forward-month 1))))
13020 (org-defkey minibuffer-local-map [(meta shift up)]
13021 (lambda () (interactive)
13022 (org-eval-in-calendar '(calendar-backward-year 1))))
13023 (org-defkey minibuffer-local-map [(meta shift down)]
13024 (lambda () (interactive)
13025 (org-eval-in-calendar '(calendar-forward-year 1))))
13026 (org-defkey minibuffer-local-map [?\e (shift left)]
13027 (lambda () (interactive)
13028 (org-eval-in-calendar '(calendar-backward-month 1))))
13029 (org-defkey minibuffer-local-map [?\e (shift right)]
13030 (lambda () (interactive)
13031 (org-eval-in-calendar '(calendar-forward-month 1))))
13032 (org-defkey minibuffer-local-map [?\e (shift up)]
13033 (lambda () (interactive)
13034 (org-eval-in-calendar '(calendar-backward-year 1))))
13035 (org-defkey minibuffer-local-map [?\e (shift down)]
13036 (lambda () (interactive)
13037 (org-eval-in-calendar '(calendar-forward-year 1))))
13038 (org-defkey minibuffer-local-map [(shift up)]
13039 (lambda () (interactive)
13040 (org-eval-in-calendar '(calendar-backward-week 1))))
13041 (org-defkey minibuffer-local-map [(shift down)]
13042 (lambda () (interactive)
13043 (org-eval-in-calendar '(calendar-forward-week 1))))
13044 (org-defkey minibuffer-local-map [(shift left)]
13045 (lambda () (interactive)
13046 (org-eval-in-calendar '(calendar-backward-day 1))))
13047 (org-defkey minibuffer-local-map [(shift right)]
13048 (lambda () (interactive)
13049 (org-eval-in-calendar '(calendar-forward-day 1))))
13050 (org-defkey minibuffer-local-map ">"
13051 (lambda () (interactive)
13052 (org-eval-in-calendar '(scroll-calendar-left 1))))
13053 (org-defkey minibuffer-local-map "<"
13054 (lambda () (interactive)
13055 (org-eval-in-calendar '(scroll-calendar-right 1))))
13056 (run-hooks 'org-read-date-minibuffer-setup-hook)
13057 (unwind-protect
13058 (progn
13059 (use-local-map map)
13060 (add-hook 'post-command-hook 'org-read-date-display)
13061 (setq org-ans0 (read-string prompt default-input
13062 'org-read-date-history nil))
13063 ;; org-ans0: from prompt
13064 ;; org-ans1: from mouse click
13065 ;; org-ans2: from calendar motion
13066 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13067 (remove-hook 'post-command-hook 'org-read-date-display)
13068 (use-local-map old-map)
13069 (when org-read-date-overlay
13070 (org-delete-overlay org-read-date-overlay)
13071 (setq org-read-date-overlay nil)))))))
13073 (t ; Naked prompt only
13074 (unwind-protect
13075 (setq ans (read-string prompt default-input
13076 'org-read-date-history timestr))
13077 (when org-read-date-overlay
13078 (org-delete-overlay org-read-date-overlay)
13079 (setq org-read-date-overlay nil)))))
13081 (setq final (org-read-date-analyze ans def defdecode))
13082 (setq org-read-date-final-answer ans)
13084 (if to-time
13085 (apply 'encode-time final)
13086 (if (and (boundp 'org-time-was-given) org-time-was-given)
13087 (format "%04d-%02d-%02d %02d:%02d"
13088 (nth 5 final) (nth 4 final) (nth 3 final)
13089 (nth 2 final) (nth 1 final))
13090 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13092 (defvar def)
13093 (defvar defdecode)
13094 (defvar with-time)
13095 (defvar org-read-date-analyze-futurep nil)
13096 (defun org-read-date-display ()
13097 "Display the current date prompt interpretation in the minibuffer."
13098 (when org-read-date-display-live
13099 (when org-read-date-overlay
13100 (org-delete-overlay org-read-date-overlay))
13101 (let ((p (point)))
13102 (end-of-line 1)
13103 (while (not (equal (buffer-substring
13104 (max (point-min) (- (point) 4)) (point))
13105 " "))
13106 (insert " "))
13107 (goto-char p))
13108 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13109 " " (or org-ans1 org-ans2)))
13110 (org-end-time-was-given nil)
13111 (f (org-read-date-analyze ans def defdecode))
13112 (fmts (if org-dcst
13113 org-time-stamp-custom-formats
13114 org-time-stamp-formats))
13115 (fmt (if (or with-time
13116 (and (boundp 'org-time-was-given) org-time-was-given))
13117 (cdr fmts)
13118 (car fmts)))
13119 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13120 (when (and org-end-time-was-given
13121 (string-match org-plain-time-of-day-regexp txt))
13122 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13123 org-end-time-was-given
13124 (substring txt (match-end 0)))))
13125 (when org-read-date-analyze-futurep
13126 (setq txt (concat txt " (=>F)")))
13127 (setq org-read-date-overlay
13128 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13129 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13131 (defun org-read-date-analyze (ans def defdecode)
13132 "Analyse the combined answer of the date prompt."
13133 ;; FIXME: cleanup and comment
13134 (let (delta deltan deltaw deltadef year month day
13135 hour minute second wday pm h2 m2 tl wday1
13136 iso-year iso-weekday iso-week iso-year iso-date futurep)
13137 (setq org-read-date-analyze-futurep nil)
13138 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13139 (setq ans "+0"))
13141 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13142 (setq ans (replace-match "" t t ans)
13143 deltan (car delta)
13144 deltaw (nth 1 delta)
13145 deltadef (nth 2 delta)))
13147 ;; Check if there is an iso week date in there
13148 ;; If yes, store the info and postpone interpreting it until the rest
13149 ;; of the parsing is done
13150 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13151 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
13152 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
13153 iso-week (string-to-number (match-string 2 ans)))
13154 (setq ans (replace-match "" t t ans)))
13156 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
13157 (when (string-match
13158 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13159 (setq year (if (match-end 2)
13160 (string-to-number (match-string 2 ans))
13161 (string-to-number (format-time-string "%Y")))
13162 month (string-to-number (match-string 3 ans))
13163 day (string-to-number (match-string 4 ans)))
13164 (if (< year 100) (setq year (+ 2000 year)))
13165 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13166 t nil ans)))
13167 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13168 ;; If there is a time with am/pm, and *no* time without it, we convert
13169 ;; so that matching will be successful.
13170 (loop for i from 1 to 2 do ; twice, for end time as well
13171 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13172 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13173 (setq hour (string-to-number (match-string 1 ans))
13174 minute (if (match-end 3)
13175 (string-to-number (match-string 3 ans))
13177 pm (equal ?p
13178 (string-to-char (downcase (match-string 4 ans)))))
13179 (if (and (= hour 12) (not pm))
13180 (setq hour 0)
13181 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13182 (setq ans (replace-match (format "%02d:%02d" hour minute)
13183 t t ans))))
13185 ;; Check if a time range is given as a duration
13186 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13187 (setq hour (string-to-number (match-string 1 ans))
13188 h2 (+ hour (string-to-number (match-string 3 ans)))
13189 minute (string-to-number (match-string 2 ans))
13190 m2 (+ minute (if (match-end 5) (string-to-number
13191 (match-string 5 ans))0)))
13192 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13193 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13194 t t ans)))
13196 ;; Check if there is a time range
13197 (when (boundp 'org-end-time-was-given)
13198 (setq org-time-was-given nil)
13199 (when (and (string-match org-plain-time-of-day-regexp ans)
13200 (match-end 8))
13201 (setq org-end-time-was-given (match-string 8 ans))
13202 (setq ans (concat (substring ans 0 (match-beginning 7))
13203 (substring ans (match-end 7))))))
13205 (setq tl (parse-time-string ans)
13206 day (or (nth 3 tl) (nth 3 defdecode))
13207 month (or (nth 4 tl)
13208 (if (and org-read-date-prefer-future
13209 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
13210 (prog1 (1+ (nth 4 defdecode)) (setq futurep t))
13211 (nth 4 defdecode)))
13212 year (or (nth 5 tl)
13213 (if (and org-read-date-prefer-future
13214 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
13215 (prog1 (1+ (nth 5 defdecode)) (setq futurep t))
13216 (nth 5 defdecode)))
13217 hour (or (nth 2 tl) (nth 2 defdecode))
13218 minute (or (nth 1 tl) (nth 1 defdecode))
13219 second (or (nth 0 tl) 0)
13220 wday (nth 6 tl))
13222 (when (and (eq org-read-date-prefer-future 'time)
13223 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13224 (equal day (nth 3 defdecode))
13225 (equal month (nth 4 defdecode))
13226 (equal year (nth 5 defdecode))
13227 (nth 2 tl)
13228 (or (< (nth 2 tl) (nth 2 defdecode))
13229 (and (= (nth 2 tl) (nth 2 defdecode))
13230 (nth 1 tl)
13231 (< (nth 1 tl) (nth 1 defdecode)))))
13232 (setq day (1+ day)
13233 futurep t))
13235 ;; Special date definitions below
13236 (cond
13237 (iso-week
13238 ;; There was an iso week
13239 (setq futurep nil)
13240 (setq year (or iso-year year)
13241 day (or iso-weekday wday 1)
13242 wday nil ; to make sure that the trigger below does not match
13243 iso-date (calendar-gregorian-from-absolute
13244 (calendar-absolute-from-iso
13245 (list iso-week day year))))
13246 ; FIXME: Should we also push ISO weeks into the future?
13247 ; (when (and org-read-date-prefer-future
13248 ; (not iso-year)
13249 ; (< (calendar-absolute-from-gregorian iso-date)
13250 ; (time-to-days (current-time))))
13251 ; (setq year (1+ year)
13252 ; iso-date (calendar-gregorian-from-absolute
13253 ; (calendar-absolute-from-iso
13254 ; (list iso-week day year)))))
13255 (setq month (car iso-date)
13256 year (nth 2 iso-date)
13257 day (nth 1 iso-date)))
13258 (deltan
13259 (setq futurep nil)
13260 (unless deltadef
13261 (let ((now (decode-time (current-time))))
13262 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13263 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13264 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13265 ((equal deltaw "m") (setq month (+ month deltan)))
13266 ((equal deltaw "y") (setq year (+ year deltan)))))
13267 ((and wday (not (nth 3 tl)))
13268 (setq futurep nil)
13269 ;; Weekday was given, but no day, so pick that day in the week
13270 ;; on or after the derived date.
13271 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13272 (unless (equal wday wday1)
13273 (setq day (+ day (% (- wday wday1 -7) 7))))))
13274 (if (and (boundp 'org-time-was-given)
13275 (nth 2 tl))
13276 (setq org-time-was-given t))
13277 (if (< year 100) (setq year (+ 2000 year)))
13278 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13279 (setq org-read-date-analyze-futurep futurep)
13280 (list second minute hour day month year)))
13282 (defvar parse-time-weekdays)
13284 (defun org-read-date-get-relative (s today default)
13285 "Check string S for special relative date string.
13286 TODAY and DEFAULT are internal times, for today and for a default.
13287 Return shift list (N what def-flag)
13288 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13289 N is the number of WHATs to shift.
13290 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13291 the DEFAULT date rather than TODAY."
13292 (when (and
13293 (string-match
13294 (concat
13295 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13296 "\\([0-9]+\\)?"
13297 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13298 "\\([ \t]\\|$\\)") s)
13299 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13300 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13301 (string-to-char (substring (match-string 1 s) -1))
13302 ?+))
13303 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13304 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13305 (what (if (match-end 3) (match-string 3 s) "d"))
13306 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13307 (date (if rel default today))
13308 (wday (nth 6 (decode-time date)))
13309 delta)
13310 (if wday1
13311 (progn
13312 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13313 (if (= dir ?-) (setq delta (- delta 7)))
13314 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13315 (list delta "d" rel))
13316 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13318 (defun org-eval-in-calendar (form &optional keepdate)
13319 "Eval FORM in the calendar window and return to current window.
13320 Also, store the cursor date in variable org-ans2."
13321 (let ((sf (selected-frame))
13322 (sw (selected-window)))
13323 (select-window (get-buffer-window "*Calendar*" t))
13324 (eval form)
13325 (when (and (not keepdate) (calendar-cursor-to-date))
13326 (let* ((date (calendar-cursor-to-date))
13327 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13328 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13329 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13330 (select-window sw)
13331 (org-select-frame-set-input-focus sf)))
13333 (defun org-calendar-select ()
13334 "Return to `org-read-date' with the date currently selected.
13335 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13336 (interactive)
13337 (when (calendar-cursor-to-date)
13338 (let* ((date (calendar-cursor-to-date))
13339 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13340 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13341 (if (active-minibuffer-window) (exit-minibuffer))))
13343 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13344 "Insert a date stamp for the date given by the internal TIME.
13345 WITH-HM means, use the stamp format that includes the time of the day.
13346 INACTIVE means use square brackets instead of angular ones, so that the
13347 stamp will not contribute to the agenda.
13348 PRE and POST are optional strings to be inserted before and after the
13349 stamp.
13350 The command returns the inserted time stamp."
13351 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13352 stamp)
13353 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13354 (insert-before-markers (or pre ""))
13355 (insert-before-markers (setq stamp (format-time-string fmt time)))
13356 (when (listp extra)
13357 (setq extra (car extra))
13358 (if (and (stringp extra)
13359 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13360 (setq extra (format "-%02d:%02d"
13361 (string-to-number (match-string 1 extra))
13362 (string-to-number (match-string 2 extra))))
13363 (setq extra nil)))
13364 (when extra
13365 (backward-char 1)
13366 (insert-before-markers extra)
13367 (forward-char 1))
13368 (insert-before-markers (or post ""))
13369 (setq org-last-inserted-timestamp stamp)))
13371 (defun org-toggle-time-stamp-overlays ()
13372 "Toggle the use of custom time stamp formats."
13373 (interactive)
13374 (setq org-display-custom-times (not org-display-custom-times))
13375 (unless org-display-custom-times
13376 (let ((p (point-min)) (bmp (buffer-modified-p)))
13377 (while (setq p (next-single-property-change p 'display))
13378 (if (and (get-text-property p 'display)
13379 (eq (get-text-property p 'face) 'org-date))
13380 (remove-text-properties
13381 p (setq p (next-single-property-change p 'display))
13382 '(display t))))
13383 (set-buffer-modified-p bmp)))
13384 (if (featurep 'xemacs)
13385 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13386 (org-restart-font-lock)
13387 (setq org-table-may-need-update t)
13388 (if org-display-custom-times
13389 (message "Time stamps are overlayed with custom format")
13390 (message "Time stamp overlays removed")))
13392 (defun org-display-custom-time (beg end)
13393 "Overlay modified time stamp format over timestamp between BEG and END."
13394 (let* ((ts (buffer-substring beg end))
13395 t1 w1 with-hm tf time str w2 (off 0))
13396 (save-match-data
13397 (setq t1 (org-parse-time-string ts t))
13398 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13399 (setq off (- (match-end 0) (match-beginning 0)))))
13400 (setq end (- end off))
13401 (setq w1 (- end beg)
13402 with-hm (and (nth 1 t1) (nth 2 t1))
13403 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13404 time (org-fix-decoded-time t1)
13405 str (org-add-props
13406 (format-time-string
13407 (substring tf 1 -1) (apply 'encode-time time))
13408 nil 'mouse-face 'highlight)
13409 w2 (length str))
13410 (if (not (= w2 w1))
13411 (add-text-properties (1+ beg) (+ 2 beg)
13412 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13413 (if (featurep 'xemacs)
13414 (progn
13415 (put-text-property beg end 'invisible t)
13416 (put-text-property beg end 'end-glyph (make-glyph str)))
13417 (put-text-property beg end 'display str))))
13419 (defun org-translate-time (string)
13420 "Translate all timestamps in STRING to custom format.
13421 But do this only if the variable `org-display-custom-times' is set."
13422 (when org-display-custom-times
13423 (save-match-data
13424 (let* ((start 0)
13425 (re org-ts-regexp-both)
13426 t1 with-hm inactive tf time str beg end)
13427 (while (setq start (string-match re string start))
13428 (setq beg (match-beginning 0)
13429 end (match-end 0)
13430 t1 (save-match-data
13431 (org-parse-time-string (substring string beg end) t))
13432 with-hm (and (nth 1 t1) (nth 2 t1))
13433 inactive (equal (substring string beg (1+ beg)) "[")
13434 tf (funcall (if with-hm 'cdr 'car)
13435 org-time-stamp-custom-formats)
13436 time (org-fix-decoded-time t1)
13437 str (format-time-string
13438 (concat
13439 (if inactive "[" "<") (substring tf 1 -1)
13440 (if inactive "]" ">"))
13441 (apply 'encode-time time))
13442 string (replace-match str t t string)
13443 start (+ start (length str)))))))
13444 string)
13446 (defun org-fix-decoded-time (time)
13447 "Set 0 instead of nil for the first 6 elements of time.
13448 Don't touch the rest."
13449 (let ((n 0))
13450 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13452 (defun org-days-to-time (timestamp-string)
13453 "Difference between TIMESTAMP-STRING and now in days."
13454 (- (time-to-days (org-time-string-to-time timestamp-string))
13455 (time-to-days (current-time))))
13457 (defun org-deadline-close (timestamp-string &optional ndays)
13458 "Is the time in TIMESTAMP-STRING close to the current date?"
13459 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13460 (and (< (org-days-to-time timestamp-string) ndays)
13461 (not (org-entry-is-done-p))))
13463 (defun org-get-wdays (ts)
13464 "Get the deadline lead time appropriate for timestring TS."
13465 (cond
13466 ((<= org-deadline-warning-days 0)
13467 ;; 0 or negative, enforce this value no matter what
13468 (- org-deadline-warning-days))
13469 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13470 ;; lead time is specified.
13471 (floor (* (string-to-number (match-string 1 ts))
13472 (cdr (assoc (match-string 2 ts)
13473 '(("d" . 1) ("w" . 7)
13474 ("m" . 30.4) ("y" . 365.25)))))))
13475 ;; go for the default.
13476 (t org-deadline-warning-days)))
13478 (defun org-calendar-select-mouse (ev)
13479 "Return to `org-read-date' with the date currently selected.
13480 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13481 (interactive "e")
13482 (mouse-set-point ev)
13483 (when (calendar-cursor-to-date)
13484 (let* ((date (calendar-cursor-to-date))
13485 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13486 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13487 (if (active-minibuffer-window) (exit-minibuffer))))
13489 (defun org-check-deadlines (ndays)
13490 "Check if there are any deadlines due or past due.
13491 A deadline is considered due if it happens within `org-deadline-warning-days'
13492 days from today's date. If the deadline appears in an entry marked DONE,
13493 it is not shown. The prefix arg NDAYS can be used to test that many
13494 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13495 (interactive "P")
13496 (let* ((org-warn-days
13497 (cond
13498 ((equal ndays '(4)) 100000)
13499 (ndays (prefix-numeric-value ndays))
13500 (t (abs org-deadline-warning-days))))
13501 (case-fold-search nil)
13502 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13503 (callback
13504 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13506 (message "%d deadlines past-due or due within %d days"
13507 (org-occur regexp nil callback)
13508 org-warn-days)))
13510 (defun org-check-before-date (date)
13511 "Check if there are deadlines or scheduled entries before DATE."
13512 (interactive (list (org-read-date)))
13513 (let ((case-fold-search nil)
13514 (regexp (concat "\\<\\(" org-deadline-string
13515 "\\|" org-scheduled-string
13516 "\\) *<\\([^>]+\\)>"))
13517 (callback
13518 (lambda () (time-less-p
13519 (org-time-string-to-time (match-string 2))
13520 (org-time-string-to-time date)))))
13521 (message "%d entries before %s"
13522 (org-occur regexp nil callback) date)))
13524 (defun org-check-after-date (date)
13525 "Check if there are deadlines or scheduled entries after DATE."
13526 (interactive (list (org-read-date)))
13527 (let ((case-fold-search nil)
13528 (regexp (concat "\\<\\(" org-deadline-string
13529 "\\|" org-scheduled-string
13530 "\\) *<\\([^>]+\\)>"))
13531 (callback
13532 (lambda () (not
13533 (time-less-p
13534 (org-time-string-to-time (match-string 2))
13535 (org-time-string-to-time date))))))
13536 (message "%d entries after %s"
13537 (org-occur regexp nil callback) date)))
13539 (defun org-evaluate-time-range (&optional to-buffer)
13540 "Evaluate a time range by computing the difference between start and end.
13541 Normally the result is just printed in the echo area, but with prefix arg
13542 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13543 If the time range is actually in a table, the result is inserted into the
13544 next column.
13545 For time difference computation, a year is assumed to be exactly 365
13546 days in order to avoid rounding problems."
13547 (interactive "P")
13549 (org-clock-update-time-maybe)
13550 (save-excursion
13551 (unless (org-at-date-range-p t)
13552 (goto-char (point-at-bol))
13553 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13554 (if (not (org-at-date-range-p t))
13555 (error "Not at a time-stamp range, and none found in current line")))
13556 (let* ((ts1 (match-string 1))
13557 (ts2 (match-string 2))
13558 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13559 (match-end (match-end 0))
13560 (time1 (org-time-string-to-time ts1))
13561 (time2 (org-time-string-to-time ts2))
13562 (t1 (org-float-time time1))
13563 (t2 (org-float-time time2))
13564 (diff (abs (- t2 t1)))
13565 (negative (< (- t2 t1) 0))
13566 ;; (ys (floor (* 365 24 60 60)))
13567 (ds (* 24 60 60))
13568 (hs (* 60 60))
13569 (fy "%dy %dd %02d:%02d")
13570 (fy1 "%dy %dd")
13571 (fd "%dd %02d:%02d")
13572 (fd1 "%dd")
13573 (fh "%02d:%02d")
13574 y d h m align)
13575 (if havetime
13576 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13578 d (floor (/ diff ds)) diff (mod diff ds)
13579 h (floor (/ diff hs)) diff (mod diff hs)
13580 m (floor (/ diff 60)))
13581 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13583 d (floor (+ (/ diff ds) 0.5))
13584 h 0 m 0))
13585 (if (not to-buffer)
13586 (message "%s" (org-make-tdiff-string y d h m))
13587 (if (org-at-table-p)
13588 (progn
13589 (goto-char match-end)
13590 (setq align t)
13591 (and (looking-at " *|") (goto-char (match-end 0))))
13592 (goto-char match-end))
13593 (if (looking-at
13594 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13595 (replace-match ""))
13596 (if negative (insert " -"))
13597 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13598 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13599 (insert " " (format fh h m))))
13600 (if align (org-table-align))
13601 (message "Time difference inserted")))))
13603 (defun org-make-tdiff-string (y d h m)
13604 (let ((fmt "")
13605 (l nil))
13606 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13607 l (push y l)))
13608 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13609 l (push d l)))
13610 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13611 l (push h l)))
13612 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13613 l (push m l)))
13614 (apply 'format fmt (nreverse l))))
13616 (defun org-time-string-to-time (s)
13617 (apply 'encode-time (org-parse-time-string s)))
13618 (defun org-time-string-to-seconds (s)
13619 (org-float-time (org-time-string-to-time s)))
13621 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13622 "Convert a time stamp to an absolute day number.
13623 If there is a specifyer for a cyclic time stamp, get the closest date to
13624 DAYNR.
13625 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13626 the variable date is bound by the calendar when this is called."
13627 (cond
13628 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13629 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13630 daynr
13631 (+ daynr 1000)))
13632 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13633 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13634 (time-to-days (current-time))) (match-string 0 s)
13635 prefer show-all))
13636 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13638 (defun org-days-to-iso-week (days)
13639 "Return the iso week number."
13640 (require 'cal-iso)
13641 (car (calendar-iso-from-absolute days)))
13643 (defun org-small-year-to-year (year)
13644 "Convert 2-digit years into 4-digit years.
13645 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13646 The year 2000 cannot be abbreviated. Any year larger than 99
13647 is returned unchanged."
13648 (if (< year 38)
13649 (setq year (+ 2000 year))
13650 (if (< year 100)
13651 (setq year (+ 1900 year))))
13652 year)
13654 (defun org-time-from-absolute (d)
13655 "Return the time corresponding to date D.
13656 D may be an absolute day number, or a calendar-type list (month day year)."
13657 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13658 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13660 (defun org-calendar-holiday ()
13661 "List of holidays, for Diary display in Org-mode."
13662 (require 'holidays)
13663 (let ((hl (funcall
13664 (if (fboundp 'calendar-check-holidays)
13665 'calendar-check-holidays 'check-calendar-holidays) date)))
13666 (if hl (mapconcat 'identity hl "; "))))
13668 (defun org-diary-sexp-entry (sexp entry date)
13669 "Process a SEXP diary ENTRY for DATE."
13670 (require 'diary-lib)
13671 (let ((result (if calendar-debug-sexp
13672 (let ((stack-trace-on-error t))
13673 (eval (car (read-from-string sexp))))
13674 (condition-case nil
13675 (eval (car (read-from-string sexp)))
13676 (error
13677 (beep)
13678 (message "Bad sexp at line %d in %s: %s"
13679 (org-current-line)
13680 (buffer-file-name) sexp)
13681 (sleep-for 2))))))
13682 (cond ((stringp result) result)
13683 ((and (consp result)
13684 (stringp (cdr result))) (cdr result))
13685 (result entry)
13686 (t nil))))
13688 (defun org-diary-to-ical-string (frombuf)
13689 "Get iCalendar entries from diary entries in buffer FROMBUF.
13690 This uses the icalendar.el library."
13691 (let* ((tmpdir (if (featurep 'xemacs)
13692 (temp-directory)
13693 temporary-file-directory))
13694 (tmpfile (make-temp-name
13695 (expand-file-name "orgics" tmpdir)))
13696 buf rtn b e)
13697 (with-current-buffer frombuf
13698 (icalendar-export-region (point-min) (point-max) tmpfile)
13699 (setq buf (find-buffer-visiting tmpfile))
13700 (set-buffer buf)
13701 (goto-char (point-min))
13702 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13703 (setq b (match-beginning 0)))
13704 (goto-char (point-max))
13705 (if (re-search-backward "^END:VEVENT" nil t)
13706 (setq e (match-end 0)))
13707 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13708 (kill-buffer buf)
13709 (delete-file tmpfile)
13710 rtn))
13712 (defun org-closest-date (start current change prefer show-all)
13713 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13714 When PREFER is `past' return a date that is either CURRENT or past.
13715 When PREFER is `future', return a date that is either CURRENT or future.
13716 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13717 ;; Make the proper lists from the dates
13718 (catch 'exit
13719 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13720 dn dw sday cday n1 n2 n0
13721 d m y y1 y2 date1 date2 nmonths nm ny m2)
13723 (setq start (org-date-to-gregorian start)
13724 current (org-date-to-gregorian
13725 (if show-all
13726 current
13727 (time-to-days (current-time))))
13728 sday (calendar-absolute-from-gregorian start)
13729 cday (calendar-absolute-from-gregorian current))
13731 (if (<= cday sday) (throw 'exit sday))
13733 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13734 (setq dn (string-to-number (match-string 1 change))
13735 dw (cdr (assoc (match-string 2 change) a1)))
13736 (error "Invalid change specifyer: %s" change))
13737 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13738 (cond
13739 ((eq dw 'day)
13740 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13741 n2 (+ n1 dn)))
13742 ((eq dw 'year)
13743 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13744 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13745 (setq date1 (list m d y1)
13746 n1 (calendar-absolute-from-gregorian date1)
13747 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13748 n2 (calendar-absolute-from-gregorian date2)))
13749 ((eq dw 'month)
13750 ;; approx number of month between the two dates
13751 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13752 ;; How often does dn fit in there?
13753 (setq d (nth 1 start) m (car start) y (nth 2 start)
13754 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13755 m (+ m nm)
13756 ny (floor (/ m 12))
13757 y (+ y ny)
13758 m (- m (* ny 12)))
13759 (while (> m 12) (setq m (- m 12) y (1+ y)))
13760 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13761 (setq m2 (+ m dn) y2 y)
13762 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13763 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13764 (while (<= n2 cday)
13765 (setq n1 n2 m m2 y y2)
13766 (setq m2 (+ m dn) y2 y)
13767 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13768 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13769 ;; Make sure n1 is the earlier date
13770 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13771 (if show-all
13772 (cond
13773 ((eq prefer 'past) (if (= cday n2) n2 n1))
13774 ((eq prefer 'future) (if (= cday n1) n1 n2))
13775 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13776 (cond
13777 ((eq prefer 'past) (if (= cday n2) n2 n1))
13778 ((eq prefer 'future) (if (= cday n1) n1 n2))
13779 (t (if (= cday n1) n1 n2)))))))
13781 (defun org-date-to-gregorian (date)
13782 "Turn any specification of DATE into a gregorian date for the calendar."
13783 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13784 ((and (listp date) (= (length date) 3)) date)
13785 ((stringp date)
13786 (setq date (org-parse-time-string date))
13787 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13788 ((listp date)
13789 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13791 (defun org-parse-time-string (s &optional nodefault)
13792 "Parse the standard Org-mode time string.
13793 This should be a lot faster than the normal `parse-time-string'.
13794 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13795 hour and minute fields will be nil if not given."
13796 (if (string-match org-ts-regexp0 s)
13797 (list 0
13798 (if (or (match-beginning 8) (not nodefault))
13799 (string-to-number (or (match-string 8 s) "0")))
13800 (if (or (match-beginning 7) (not nodefault))
13801 (string-to-number (or (match-string 7 s) "0")))
13802 (string-to-number (match-string 4 s))
13803 (string-to-number (match-string 3 s))
13804 (string-to-number (match-string 2 s))
13805 nil nil nil)
13806 (error "Not a standard Org-mode time string: %s" s)))
13808 (defun org-timestamp-up (&optional arg)
13809 "Increase the date item at the cursor by one.
13810 If the cursor is on the year, change the year. If it is on the month or
13811 the day, change that.
13812 With prefix ARG, change by that many units."
13813 (interactive "p")
13814 (org-timestamp-change (prefix-numeric-value arg)))
13816 (defun org-timestamp-down (&optional arg)
13817 "Decrease the date item at the cursor by one.
13818 If the cursor is on the year, change the year. If it is on the month or
13819 the day, change that.
13820 With prefix ARG, change by that many units."
13821 (interactive "p")
13822 (org-timestamp-change (- (prefix-numeric-value arg))))
13824 (defun org-timestamp-up-day (&optional arg)
13825 "Increase the date in the time stamp by one day.
13826 With prefix ARG, change that many days."
13827 (interactive "p")
13828 (if (and (not (org-at-timestamp-p t))
13829 (org-on-heading-p))
13830 (org-todo 'up)
13831 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13833 (defun org-timestamp-down-day (&optional arg)
13834 "Decrease the date in the time stamp by one day.
13835 With prefix ARG, change that many days."
13836 (interactive "p")
13837 (if (and (not (org-at-timestamp-p t))
13838 (org-on-heading-p))
13839 (org-todo 'down)
13840 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13842 (defun org-at-timestamp-p (&optional inactive-ok)
13843 "Determine if the cursor is in or at a timestamp."
13844 (interactive)
13845 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13846 (pos (point))
13847 (ans (or (looking-at tsr)
13848 (save-excursion
13849 (skip-chars-backward "^[<\n\r\t")
13850 (if (> (point) (point-min)) (backward-char 1))
13851 (and (looking-at tsr)
13852 (> (- (match-end 0) pos) -1))))))
13853 (and ans
13854 (boundp 'org-ts-what)
13855 (setq org-ts-what
13856 (cond
13857 ((= pos (match-beginning 0)) 'bracket)
13858 ((= pos (1- (match-end 0))) 'bracket)
13859 ((org-pos-in-match-range pos 2) 'year)
13860 ((org-pos-in-match-range pos 3) 'month)
13861 ((org-pos-in-match-range pos 7) 'hour)
13862 ((org-pos-in-match-range pos 8) 'minute)
13863 ((or (org-pos-in-match-range pos 4)
13864 (org-pos-in-match-range pos 5)) 'day)
13865 ((and (> pos (or (match-end 8) (match-end 5)))
13866 (< pos (match-end 0)))
13867 (- pos (or (match-end 8) (match-end 5))))
13868 (t 'day))))
13869 ans))
13871 (defun org-toggle-timestamp-type ()
13872 "Toggle the type (<active> or [inactive]) of a time stamp."
13873 (interactive)
13874 (when (org-at-timestamp-p t)
13875 (let ((beg (match-beginning 0)) (end (match-end 0))
13876 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13877 (save-excursion
13878 (goto-char beg)
13879 (while (re-search-forward "[][<>]" end t)
13880 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13881 t t)))
13882 (message "Timestamp is now %sactive"
13883 (if (equal (char-after beg) ?<) "" "in")))))
13885 (defun org-timestamp-change (n &optional what)
13886 "Change the date in the time stamp at point.
13887 The date will be changed by N times WHAT. WHAT can be `day', `month',
13888 `year', `minute', `second'. If WHAT is not given, the cursor position
13889 in the timestamp determines what will be changed."
13890 (let ((pos (point))
13891 with-hm inactive
13892 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13893 org-ts-what
13894 extra rem
13895 ts time time0)
13896 (if (not (org-at-timestamp-p t))
13897 (error "Not at a timestamp"))
13898 (if (and (not what) (eq org-ts-what 'bracket))
13899 (org-toggle-timestamp-type)
13900 (if (and (not what) (not (eq org-ts-what 'day))
13901 org-display-custom-times
13902 (get-text-property (point) 'display)
13903 (not (get-text-property (1- (point)) 'display)))
13904 (setq org-ts-what 'day))
13905 (setq org-ts-what (or what org-ts-what)
13906 inactive (= (char-after (match-beginning 0)) ?\[)
13907 ts (match-string 0))
13908 (replace-match "")
13909 (if (string-match
13910 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
13912 (setq extra (match-string 1 ts)))
13913 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13914 (setq with-hm t))
13915 (setq time0 (org-parse-time-string ts))
13916 (when (and (eq org-ts-what 'minute)
13917 (eq current-prefix-arg nil))
13918 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13919 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13920 (setcar (cdr time0) (+ (nth 1 time0)
13921 (if (> n 0) (- rem) (- dm rem))))))
13922 (setq time
13923 (encode-time (or (car time0) 0)
13924 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13925 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13926 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13927 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13928 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13929 (nthcdr 6 time0)))
13930 (when (and (member org-ts-what '(hour minute))
13931 extra
13932 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13933 (setq extra (org-modify-ts-extra
13934 extra
13935 (if (eq org-ts-what 'hour) 2 5)
13936 n dm)))
13937 (when (integerp org-ts-what)
13938 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13939 (if (eq what 'calendar)
13940 (let ((cal-date (org-get-date-from-calendar)))
13941 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13942 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13943 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13944 (setcar time0 (or (car time0) 0))
13945 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13946 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13947 (setq time (apply 'encode-time time0))))
13948 (setq org-last-changed-timestamp
13949 (org-insert-time-stamp time with-hm inactive nil nil extra))
13950 (org-clock-update-time-maybe)
13951 (goto-char pos)
13952 ;; Try to recenter the calendar window, if any
13953 (if (and org-calendar-follow-timestamp-change
13954 (get-buffer-window "*Calendar*" t)
13955 (memq org-ts-what '(day month year)))
13956 (org-recenter-calendar (time-to-days time))))))
13958 (defun org-modify-ts-extra (s pos n dm)
13959 "Change the different parts of the lead-time and repeat fields in timestamp."
13960 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13961 ng h m new rem)
13962 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13963 (cond
13964 ((or (org-pos-in-match-range pos 2)
13965 (org-pos-in-match-range pos 3))
13966 (setq m (string-to-number (match-string 3 s))
13967 h (string-to-number (match-string 2 s)))
13968 (if (org-pos-in-match-range pos 2)
13969 (setq h (+ h n))
13970 (setq n (* dm (org-no-warnings (signum n))))
13971 (when (not (= 0 (setq rem (% m dm))))
13972 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13973 (setq m (+ m n)))
13974 (if (< m 0) (setq m (+ m 60) h (1- h)))
13975 (if (> m 59) (setq m (- m 60) h (1+ h)))
13976 (setq h (min 24 (max 0 h)))
13977 (setq ng 1 new (format "-%02d:%02d" h m)))
13978 ((org-pos-in-match-range pos 6)
13979 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13980 ((org-pos-in-match-range pos 5)
13981 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13983 ((org-pos-in-match-range pos 9)
13984 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13985 ((org-pos-in-match-range pos 8)
13986 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13988 (when ng
13989 (setq s (concat
13990 (substring s 0 (match-beginning ng))
13992 (substring s (match-end ng))))))
13995 (defun org-recenter-calendar (date)
13996 "If the calendar is visible, recenter it to DATE."
13997 (let* ((win (selected-window))
13998 (cwin (get-buffer-window "*Calendar*" t))
13999 (calendar-move-hook nil))
14000 (when cwin
14001 (select-window cwin)
14002 (calendar-goto-date (if (listp date) date
14003 (calendar-gregorian-from-absolute date)))
14004 (select-window win))))
14006 (defun org-goto-calendar (&optional arg)
14007 "Go to the Emacs calendar at the current date.
14008 If there is a time stamp in the current line, go to that date.
14009 A prefix ARG can be used to force the current date."
14010 (interactive "P")
14011 (let ((tsr org-ts-regexp) diff
14012 (calendar-move-hook nil)
14013 (calendar-view-holidays-initially-flag nil)
14014 (view-calendar-holidays-initially nil)
14015 (calendar-view-diary-initially-flag nil)
14016 (view-diary-entries-initially nil))
14017 (if (or (org-at-timestamp-p)
14018 (save-excursion
14019 (beginning-of-line 1)
14020 (looking-at (concat ".*" tsr))))
14021 (let ((d1 (time-to-days (current-time)))
14022 (d2 (time-to-days
14023 (org-time-string-to-time (match-string 1)))))
14024 (setq diff (- d2 d1))))
14025 (calendar)
14026 (calendar-goto-today)
14027 (if (and diff (not arg)) (calendar-forward-day diff))))
14029 (defun org-get-date-from-calendar ()
14030 "Return a list (month day year) of date at point in calendar."
14031 (with-current-buffer "*Calendar*"
14032 (save-match-data
14033 (calendar-cursor-to-date))))
14035 (defun org-date-from-calendar ()
14036 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14037 If there is already a time stamp at the cursor position, update it."
14038 (interactive)
14039 (if (org-at-timestamp-p t)
14040 (org-timestamp-change 0 'calendar)
14041 (let ((cal-date (org-get-date-from-calendar)))
14042 (org-insert-time-stamp
14043 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14045 (defun org-minutes-to-hh:mm-string (m)
14046 "Compute H:MM from a number of minutes."
14047 (let ((h (/ m 60)))
14048 (setq m (- m (* 60 h)))
14049 (format org-time-clocksum-format h m)))
14051 (defun org-hh:mm-string-to-minutes (s)
14052 "Convert a string H:MM to a number of minutes.
14053 If the string is just a number, interpret it as minutes.
14054 In fact, the first hh:mm or number in the string will be taken,
14055 there can be extra stuff in the string.
14056 If no number is found, the return value is 0."
14057 (cond
14058 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14059 (+ (* (string-to-number (match-string 1 s)) 60)
14060 (string-to-number (match-string 2 s))))
14061 ((string-match "\\([0-9]+\\)" s)
14062 (string-to-number (match-string 1 s)))
14063 (t 0)))
14065 ;;;; Files
14067 (defun org-save-all-org-buffers ()
14068 "Save all Org-mode buffers without user confirmation."
14069 (interactive)
14070 (message "Saving all Org-mode buffers...")
14071 (save-some-buffers t 'org-mode-p)
14072 (when (featurep 'org-id) (org-id-locations-save))
14073 (message "Saving all Org-mode buffers... done"))
14075 (defun org-revert-all-org-buffers ()
14076 "Revert all Org-mode buffers.
14077 Prompt for confirmation when there are unsaved changes.
14078 Be sure you know what you are doing before letting this function
14079 overwrite your changes.
14081 This function is useful in a setup where one tracks org files
14082 with a version control system, to revert on one machine after pulling
14083 changes from another. I believe the procedure must be like this:
14085 1. M-x org-save-all-org-buffers
14086 2. Pull changes from the other machine, resolve conflicts
14087 3. M-x org-revert-all-org-buffers"
14088 (interactive)
14089 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14090 (error "Abort"))
14091 (save-excursion
14092 (save-window-excursion
14093 (mapc
14094 (lambda (b)
14095 (when (and (with-current-buffer b (org-mode-p))
14096 (with-current-buffer b buffer-file-name))
14097 (switch-to-buffer b)
14098 (revert-buffer t 'no-confirm)))
14099 (buffer-list))
14100 (when (and (featurep 'org-id) org-id-track-globally)
14101 (org-id-locations-load)))))
14103 ;;;; Agenda files
14105 ;;;###autoload
14106 (defun org-iswitchb (&optional arg)
14107 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14108 With a prefix argument, restrict available to files.
14109 With two prefix arguments, restrict available buffers to agenda files."
14110 (interactive "P")
14111 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14112 ((equal arg '(16)) (org-buffer-list 'agenda))
14113 (t (org-buffer-list)))))
14114 (switch-to-buffer
14115 (org-icompleting-read "Org buffer: "
14116 (mapcar 'list (mapcar 'buffer-name blist))
14117 nil t))))
14119 ;;;###autoload
14120 (defalias 'org-ido-switchb 'org-iswitchb)
14122 (defun org-buffer-list (&optional predicate exclude-tmp)
14123 "Return a list of Org buffers.
14124 PREDICATE can be `export', `files' or `agenda'.
14126 export restrict the list to Export buffers.
14127 files restrict the list to buffers visiting Org files.
14128 agenda restrict the list to buffers visiting agenda files.
14130 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14131 (let* ((bfn nil)
14132 (agenda-files (and (eq predicate 'agenda)
14133 (mapcar 'file-truename (org-agenda-files t))))
14134 (filter
14135 (cond
14136 ((eq predicate 'files)
14137 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14138 ((eq predicate 'export)
14139 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14140 ((eq predicate 'agenda)
14141 (lambda (b)
14142 (with-current-buffer b
14143 (and (eq major-mode 'org-mode)
14144 (setq bfn (buffer-file-name b))
14145 (member (file-truename bfn) agenda-files)))))
14146 (t (lambda (b) (with-current-buffer b
14147 (or (eq major-mode 'org-mode)
14148 (string-match "\*Org .*Export"
14149 (buffer-name b)))))))))
14150 (delq nil
14151 (mapcar
14152 (lambda(b)
14153 (if (and (funcall filter b)
14154 (or (not exclude-tmp)
14155 (not (string-match "tmp" (buffer-name b)))))
14157 nil))
14158 (buffer-list)))))
14160 (defun org-agenda-files (&optional unrestricted archives)
14161 "Get the list of agenda files.
14162 Optional UNRESTRICTED means return the full list even if a restriction
14163 is currently in place.
14164 When ARCHIVES is t, include all archive files hat are really being
14165 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14166 `org-agenda-archives-mode' is t."
14167 (let ((files
14168 (cond
14169 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14170 ((stringp org-agenda-files) (org-read-agenda-file-list))
14171 ((listp org-agenda-files) org-agenda-files)
14172 (t (error "Invalid value of `org-agenda-files'")))))
14173 (setq files (apply 'append
14174 (mapcar (lambda (f)
14175 (if (file-directory-p f)
14176 (directory-files
14177 f t org-agenda-file-regexp)
14178 (list f)))
14179 files)))
14180 (when org-agenda-skip-unavailable-files
14181 (setq files (delq nil
14182 (mapcar (function
14183 (lambda (file)
14184 (and (file-readable-p file) file)))
14185 files))))
14186 (when (or (eq archives t)
14187 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14188 (setq files (org-add-archive-files files)))
14189 files))
14191 (defun org-edit-agenda-file-list ()
14192 "Edit the list of agenda files.
14193 Depending on setup, this either uses customize to edit the variable
14194 `org-agenda-files', or it visits the file that is holding the list. In the
14195 latter case, the buffer is set up in a way that saving it automatically kills
14196 the buffer and restores the previous window configuration."
14197 (interactive)
14198 (if (stringp org-agenda-files)
14199 (let ((cw (current-window-configuration)))
14200 (find-file org-agenda-files)
14201 (org-set-local 'org-window-configuration cw)
14202 (org-add-hook 'after-save-hook
14203 (lambda ()
14204 (set-window-configuration
14205 (prog1 org-window-configuration
14206 (kill-buffer (current-buffer))))
14207 (org-install-agenda-files-menu)
14208 (message "New agenda file list installed"))
14209 nil 'local)
14210 (message "%s" (substitute-command-keys
14211 "Edit list and finish with \\[save-buffer]")))
14212 (customize-variable 'org-agenda-files)))
14214 (defun org-store-new-agenda-file-list (list)
14215 "Set new value for the agenda file list and save it correctly."
14216 (if (stringp org-agenda-files)
14217 (let ((f org-agenda-files) b)
14218 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14219 (with-temp-file f
14220 (insert (mapconcat 'identity list "\n") "\n")))
14221 (let ((org-mode-hook nil) (org-inhibit-startup t)
14222 (org-insert-mode-line-in-empty-file nil))
14223 (setq org-agenda-files list)
14224 (customize-save-variable 'org-agenda-files org-agenda-files))))
14226 (defun org-read-agenda-file-list ()
14227 "Read the list of agenda files from a file."
14228 (when (file-directory-p org-agenda-files)
14229 (error "`org-agenda-files' cannot be a single directory"))
14230 (when (stringp org-agenda-files)
14231 (with-temp-buffer
14232 (insert-file-contents org-agenda-files)
14233 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14236 ;;;###autoload
14237 (defun org-cycle-agenda-files ()
14238 "Cycle through the files in `org-agenda-files'.
14239 If the current buffer visits an agenda file, find the next one in the list.
14240 If the current buffer does not, find the first agenda file."
14241 (interactive)
14242 (let* ((fs (org-agenda-files t))
14243 (files (append fs (list (car fs))))
14244 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14245 file)
14246 (unless files (error "No agenda files"))
14247 (catch 'exit
14248 (while (setq file (pop files))
14249 (if (equal (file-truename file) tcf)
14250 (when (car files)
14251 (find-file (car files))
14252 (throw 'exit t))))
14253 (find-file (car fs)))
14254 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14256 (defun org-agenda-file-to-front (&optional to-end)
14257 "Move/add the current file to the top of the agenda file list.
14258 If the file is not present in the list, it is added to the front. If it is
14259 present, it is moved there. With optional argument TO-END, add/move to the
14260 end of the list."
14261 (interactive "P")
14262 (let ((org-agenda-skip-unavailable-files nil)
14263 (file-alist (mapcar (lambda (x)
14264 (cons (file-truename x) x))
14265 (org-agenda-files t)))
14266 (ctf (file-truename buffer-file-name))
14267 x had)
14268 (setq x (assoc ctf file-alist) had x)
14270 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14271 (if to-end
14272 (setq file-alist (append (delq x file-alist) (list x)))
14273 (setq file-alist (cons x (delq x file-alist))))
14274 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14275 (org-install-agenda-files-menu)
14276 (message "File %s to %s of agenda file list"
14277 (if had "moved" "added") (if to-end "end" "front"))))
14279 (defun org-remove-file (&optional file)
14280 "Remove current file from the list of files in variable `org-agenda-files'.
14281 These are the files which are being checked for agenda entries.
14282 Optional argument FILE means, use this file instead of the current."
14283 (interactive)
14284 (let* ((org-agenda-skip-unavailable-files nil)
14285 (file (or file buffer-file-name))
14286 (true-file (file-truename file))
14287 (afile (abbreviate-file-name file))
14288 (files (delq nil (mapcar
14289 (lambda (x)
14290 (if (equal true-file
14291 (file-truename x))
14292 nil x))
14293 (org-agenda-files t)))))
14294 (if (not (= (length files) (length (org-agenda-files t))))
14295 (progn
14296 (org-store-new-agenda-file-list files)
14297 (org-install-agenda-files-menu)
14298 (message "Removed file: %s" afile))
14299 (message "File was not in list: %s (not removed)" afile))))
14301 (defun org-file-menu-entry (file)
14302 (vector file (list 'find-file file) t))
14304 (defun org-check-agenda-file (file)
14305 "Make sure FILE exists. If not, ask user what to do."
14306 (when (not (file-exists-p file))
14307 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14308 (abbreviate-file-name file))
14309 (let ((r (downcase (read-char-exclusive))))
14310 (cond
14311 ((equal r ?r)
14312 (org-remove-file file)
14313 (throw 'nextfile t))
14314 (t (error "Abort"))))))
14316 (defun org-get-agenda-file-buffer (file)
14317 "Get a buffer visiting FILE. If the buffer needs to be created, add
14318 it to the list of buffers which might be released later."
14319 (let ((buf (org-find-base-buffer-visiting file)))
14320 (if buf
14321 buf ; just return it
14322 ;; Make a new buffer and remember it
14323 (setq buf (find-file-noselect file))
14324 (if buf (push buf org-agenda-new-buffers))
14325 buf)))
14327 (defun org-release-buffers (blist)
14328 "Release all buffers in list, asking the user for confirmation when needed.
14329 When a buffer is unmodified, it is just killed. When modified, it is saved
14330 \(if the user agrees) and then killed."
14331 (let (buf file)
14332 (while (setq buf (pop blist))
14333 (setq file (buffer-file-name buf))
14334 (when (and (buffer-modified-p buf)
14335 file
14336 (y-or-n-p (format "Save file %s? " file)))
14337 (with-current-buffer buf (save-buffer)))
14338 (kill-buffer buf))))
14340 (defun org-prepare-agenda-buffers (files)
14341 "Create buffers for all agenda files, protect archived trees and comments."
14342 (interactive)
14343 (let ((pa '(:org-archived t))
14344 (pc '(:org-comment t))
14345 (pall '(:org-archived t :org-comment t))
14346 (inhibit-read-only t)
14347 (rea (concat ":" org-archive-tag ":"))
14348 bmp file re)
14349 (save-excursion
14350 (save-restriction
14351 (while (setq file (pop files))
14352 (catch 'nextfile
14353 (if (bufferp file)
14354 (set-buffer file)
14355 (org-check-agenda-file file)
14356 (set-buffer (org-get-agenda-file-buffer file)))
14357 (widen)
14358 (setq bmp (buffer-modified-p))
14359 (org-refresh-category-properties)
14360 (setq org-todo-keywords-for-agenda
14361 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14362 (setq org-done-keywords-for-agenda
14363 (append org-done-keywords-for-agenda org-done-keywords))
14364 (setq org-todo-keyword-alist-for-agenda
14365 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14366 (setq org-drawers-for-agenda
14367 (append org-drawers-for-agenda org-drawers))
14368 (setq org-tag-alist-for-agenda
14369 (append org-tag-alist-for-agenda org-tag-alist))
14371 (save-excursion
14372 (remove-text-properties (point-min) (point-max) pall)
14373 (when org-agenda-skip-archived-trees
14374 (goto-char (point-min))
14375 (while (re-search-forward rea nil t)
14376 (if (org-on-heading-p t)
14377 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14378 (goto-char (point-min))
14379 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14380 (while (re-search-forward re nil t)
14381 (add-text-properties
14382 (match-beginning 0) (org-end-of-subtree t) pc)))
14383 (set-buffer-modified-p bmp)))))
14384 (setq org-todo-keyword-alist-for-agenda
14385 (org-uniquify org-todo-keyword-alist-for-agenda)
14386 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14388 ;;;; Embedded LaTeX
14390 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14391 "Keymap for the minor `org-cdlatex-mode'.")
14393 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14394 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14395 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14396 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14397 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14399 (defvar org-cdlatex-texmathp-advice-is-done nil
14400 "Flag remembering if we have applied the advice to texmathp already.")
14402 (define-minor-mode org-cdlatex-mode
14403 "Toggle the minor `org-cdlatex-mode'.
14404 This mode supports entering LaTeX environment and math in LaTeX fragments
14405 in Org-mode.
14406 \\{org-cdlatex-mode-map}"
14407 nil " OCDL" nil
14408 (when org-cdlatex-mode (require 'cdlatex))
14409 (unless org-cdlatex-texmathp-advice-is-done
14410 (setq org-cdlatex-texmathp-advice-is-done t)
14411 (defadvice texmathp (around org-math-always-on activate)
14412 "Always return t in org-mode buffers.
14413 This is because we want to insert math symbols without dollars even outside
14414 the LaTeX math segments. If Orgmode thinks that point is actually inside
14415 an embedded LaTeX fragment, let texmathp do its job.
14416 \\[org-cdlatex-mode-map]"
14417 (interactive)
14418 (let (p)
14419 (cond
14420 ((not (org-mode-p)) ad-do-it)
14421 ((eq this-command 'cdlatex-math-symbol)
14422 (setq ad-return-value t
14423 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14425 (let ((p (org-inside-LaTeX-fragment-p)))
14426 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14427 (setq ad-return-value t
14428 texmathp-why '("Org-mode embedded math" . 0))
14429 (if p ad-do-it)))))))))
14431 (defun turn-on-org-cdlatex ()
14432 "Unconditionally turn on `org-cdlatex-mode'."
14433 (org-cdlatex-mode 1))
14435 (defun org-inside-LaTeX-fragment-p ()
14436 "Test if point is inside a LaTeX fragment.
14437 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14438 sequence appearing also before point.
14439 Even though the matchers for math are configurable, this function assumes
14440 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14441 delimiters are skipped when they have been removed by customization.
14442 The return value is nil, or a cons cell with the delimiter and
14443 and the position of this delimiter.
14445 This function does a reasonably good job, but can locally be fooled by
14446 for example currency specifications. For example it will assume being in
14447 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14448 fragments that are properly closed, but during editing, we have to live
14449 with the uncertainty caused by missing closing delimiters. This function
14450 looks only before point, not after."
14451 (catch 'exit
14452 (let ((pos (point))
14453 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14454 (lim (progn
14455 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14456 (point)))
14457 dd-on str (start 0) m re)
14458 (goto-char pos)
14459 (when dodollar
14460 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14461 re (nth 1 (assoc "$" org-latex-regexps)))
14462 (while (string-match re str start)
14463 (cond
14464 ((= (match-end 0) (length str))
14465 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14466 ((= (match-end 0) (- (length str) 5))
14467 (throw 'exit nil))
14468 (t (setq start (match-end 0))))))
14469 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14470 (goto-char pos)
14471 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14472 (and (match-beginning 2) (throw 'exit nil))
14473 ;; count $$
14474 (while (re-search-backward "\\$\\$" lim t)
14475 (setq dd-on (not dd-on)))
14476 (goto-char pos)
14477 (if dd-on (cons "$$" m))))))
14480 (defun org-try-cdlatex-tab ()
14481 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14482 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14483 - inside a LaTeX fragment, or
14484 - after the first word in a line, where an abbreviation expansion could
14485 insert a LaTeX environment."
14486 (when org-cdlatex-mode
14487 (cond
14488 ((save-excursion
14489 (skip-chars-backward "a-zA-Z0-9*")
14490 (skip-chars-backward " \t")
14491 (bolp))
14492 (cdlatex-tab) t)
14493 ((org-inside-LaTeX-fragment-p)
14494 (cdlatex-tab) t)
14495 (t nil))))
14497 (defun org-cdlatex-underscore-caret (&optional arg)
14498 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14499 Revert to the normal definition outside of these fragments."
14500 (interactive "P")
14501 (if (org-inside-LaTeX-fragment-p)
14502 (call-interactively 'cdlatex-sub-superscript)
14503 (let (org-cdlatex-mode)
14504 (call-interactively (key-binding (vector last-input-event))))))
14506 (defun org-cdlatex-math-modify (&optional arg)
14507 "Execute `cdlatex-math-modify' in LaTeX fragments.
14508 Revert to the normal definition outside of these fragments."
14509 (interactive "P")
14510 (if (org-inside-LaTeX-fragment-p)
14511 (call-interactively 'cdlatex-math-modify)
14512 (let (org-cdlatex-mode)
14513 (call-interactively (key-binding (vector last-input-event))))))
14515 (defvar org-latex-fragment-image-overlays nil
14516 "List of overlays carrying the images of latex fragments.")
14517 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14519 (defun org-remove-latex-fragment-image-overlays ()
14520 "Remove all overlays with LaTeX fragment images in current buffer."
14521 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14522 (setq org-latex-fragment-image-overlays nil))
14524 (defun org-preview-latex-fragment (&optional subtree)
14525 "Preview the LaTeX fragment at point, or all locally or globally.
14526 If the cursor is in a LaTeX fragment, create the image and overlay
14527 it over the source code. If there is no fragment at point, display
14528 all fragments in the current text, from one headline to the next. With
14529 prefix SUBTREE, display all fragments in the current subtree. With a
14530 double prefix `C-u C-u', or when the cursor is before the first headline,
14531 display all fragments in the buffer.
14532 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14533 (interactive "P")
14534 (org-remove-latex-fragment-image-overlays)
14535 (save-excursion
14536 (save-restriction
14537 (let (beg end at msg)
14538 (cond
14539 ((or (equal subtree '(16))
14540 (not (save-excursion
14541 (re-search-backward (concat "^" outline-regexp) nil t))))
14542 (setq beg (point-min) end (point-max)
14543 msg "Creating images for buffer...%s"))
14544 ((equal subtree '(4))
14545 (org-back-to-heading)
14546 (setq beg (point) end (org-end-of-subtree t)
14547 msg "Creating images for subtree...%s"))
14549 (if (setq at (org-inside-LaTeX-fragment-p))
14550 (goto-char (max (point-min) (- (cdr at) 2)))
14551 (org-back-to-heading))
14552 (setq beg (point) end (progn (outline-next-heading) (point))
14553 msg (if at "Creating image...%s"
14554 "Creating images for entry...%s"))))
14555 (message msg "")
14556 (narrow-to-region beg end)
14557 (goto-char beg)
14558 (org-format-latex
14559 (concat "ltxpng/" (file-name-sans-extension
14560 (file-name-nondirectory
14561 buffer-file-name)))
14562 default-directory 'overlays msg at 'forbuffer)
14563 (message msg "done. Use `C-c C-c' to remove images.")))))
14565 (defvar org-latex-regexps
14566 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14567 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14568 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14569 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14570 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14571 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14572 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14573 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14574 "Regular expressions for matching embedded LaTeX.")
14576 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14577 "Replace LaTeX fragments with links to an image, and produce images.
14578 Some of the options can be changed using the variable
14579 `org-format-latex-options'."
14580 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14581 (let* ((prefixnodir (file-name-nondirectory prefix))
14582 (absprefix (expand-file-name prefix dir))
14583 (todir (file-name-directory absprefix))
14584 (opt org-format-latex-options)
14585 (matchers (plist-get opt :matchers))
14586 (re-list org-latex-regexps)
14587 (cnt 0) txt hash link beg end re e checkdir
14588 executables-checked
14589 m n block linkfile movefile ov)
14590 ;; Check the different regular expressions
14591 (while (setq e (pop re-list))
14592 (setq m (car e) re (nth 1 e) n (nth 2 e)
14593 block (if (nth 3 e) "\n\n" ""))
14594 (when (member m matchers)
14595 (goto-char (point-min))
14596 (while (re-search-forward re nil t)
14597 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14598 (not (get-text-property (match-beginning n)
14599 'org-protected))
14600 (or (not overlays)
14601 (not (eq (get-char-property (match-beginning n)
14602 'org-overlay-type)
14603 'org-latex-overlay))))
14604 (setq txt (match-string n)
14605 beg (match-beginning n) end (match-end n)
14606 cnt (1+ cnt)
14607 link (concat block "[[file:" linkfile "]]" block))
14608 (let (print-length print-level) ; make sure full list is printed
14609 (setq hash (sha1 (prin1-to-string
14610 (list org-format-latex-header
14611 org-export-latex-packages-alist
14612 org-format-latex-options
14613 forbuffer txt)))
14614 linkfile (format "%s_%s.png" prefix hash)
14615 movefile (format "%s_%s.png" absprefix hash)))
14616 (if msg (message msg cnt))
14617 (goto-char beg)
14618 (unless checkdir ; make sure the directory exists
14619 (setq checkdir t)
14620 (or (file-directory-p todir) (make-directory todir)))
14622 (unless executables-checked
14623 (org-check-external-command
14624 "latex" "needed to convert LaTeX fragments to images")
14625 (org-check-external-command
14626 "dvipng" "needed to convert LaTeX fragments to images")
14627 (setq executables-checked t))
14629 (unless (file-exists-p movefile)
14630 (org-create-formula-image
14631 txt movefile opt forbuffer))
14632 (if overlays
14633 (progn
14634 (mapc (lambda (o)
14635 (if (eq (org-overlay-get o 'org-overlay-type)
14636 'org-latex-overlay)
14637 (org-delete-overlay o)))
14638 (org-overlays-in beg end))
14639 (setq ov (org-make-overlay beg end))
14640 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14641 (if (featurep 'xemacs)
14642 (progn
14643 (org-overlay-put ov 'invisible t)
14644 (org-overlay-put
14645 ov 'end-glyph
14646 (make-glyph (vector 'png :file movefile))))
14647 (org-overlay-put
14648 ov 'display
14649 (list 'image :type 'png :file movefile :ascent 'center)))
14650 (push ov org-latex-fragment-image-overlays)
14651 (goto-char end))
14652 (delete-region beg end)
14653 (insert link))))))))
14655 ;; This function borrows from Ganesh Swami's latex2png.el
14656 (defun org-create-formula-image (string tofile options buffer)
14657 "This calls dvipng."
14658 (require 'org-latex)
14659 (let* ((tmpdir (if (featurep 'xemacs)
14660 (temp-directory)
14661 temporary-file-directory))
14662 (texfilebase (make-temp-name
14663 (expand-file-name "orgtex" tmpdir)))
14664 (texfile (concat texfilebase ".tex"))
14665 (dvifile (concat texfilebase ".dvi"))
14666 (pngfile (concat texfilebase ".png"))
14667 (fnh (if (featurep 'xemacs)
14668 (font-height (get-face-font 'default))
14669 (face-attribute 'default :height nil)))
14670 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14671 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14672 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14673 "Black"))
14674 (bg (or (plist-get options (if buffer :background :html-background))
14675 "Transparent")))
14676 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14677 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14678 (with-temp-file texfile
14679 (insert org-format-latex-header
14680 (if org-export-latex-packages-alist
14681 (concat "\n"
14682 (mapconcat (lambda(p)
14683 (if (equal "" (car p))
14684 (format "\\usepackage{%s}" (cadr p))
14685 (format "\\usepackage[%s]{%s}"
14686 (car p) (cadr p))))
14687 org-export-latex-packages-alist "\n"))
14689 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14690 (let ((dir default-directory))
14691 (condition-case nil
14692 (progn
14693 (cd tmpdir)
14694 (call-process "latex" nil nil nil texfile))
14695 (error nil))
14696 (cd dir))
14697 (if (not (file-exists-p dvifile))
14698 (progn (message "Failed to create dvi file from %s" texfile) nil)
14699 (condition-case nil
14700 (call-process "dvipng" nil nil nil
14701 "-fg" fg "-bg" bg
14702 "-D" dpi
14703 ;;"-x" scale "-y" scale
14704 "-T" "tight"
14705 "-o" pngfile
14706 dvifile)
14707 (error nil))
14708 (if (not (file-exists-p pngfile))
14709 (progn (message "Failed to create png file from %s" texfile) nil)
14710 ;; Use the requested file name and clean up
14711 (copy-file pngfile tofile 'replace)
14712 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14713 (delete-file (concat texfilebase e)))
14714 pngfile))))
14716 (defun org-dvipng-color (attr)
14717 "Return an rgb color specification for dvipng."
14718 (apply 'format "rgb %s %s %s"
14719 (mapcar 'org-normalize-color
14720 (color-values (face-attribute 'default attr nil)))))
14722 (defun org-normalize-color (value)
14723 "Return string to be used as color value for an RGB component."
14724 (format "%g" (/ value 65535.0)))
14726 ;;;; Key bindings
14728 ;; Make `C-c C-x' a prefix key
14729 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14731 ;; TAB key with modifiers
14732 (org-defkey org-mode-map "\C-i" 'org-cycle)
14733 (org-defkey org-mode-map [(tab)] 'org-cycle)
14734 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14735 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14736 (org-defkey org-mode-map "\M-\t" 'org-complete)
14737 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14738 ;; The following line is necessary under Suse GNU/Linux
14739 (unless (featurep 'xemacs)
14740 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14741 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14742 (define-key org-mode-map [backtab] 'org-shifttab)
14744 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14745 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14746 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14748 ;; Cursor keys with modifiers
14749 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14750 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14751 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14752 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14754 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14755 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14756 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14757 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14759 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14760 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14761 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14762 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14764 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14765 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14767 ;;; Extra keys for tty access.
14768 ;; We only set them when really needed because otherwise the
14769 ;; menus don't show the simple keys
14771 (when (or org-use-extra-keys
14772 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14773 (not window-system))
14774 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14775 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14776 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14777 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14778 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14779 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14780 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14781 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14782 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14783 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14784 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14785 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14786 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14787 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14788 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14789 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14790 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14791 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14792 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14793 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14794 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14795 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14796 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14797 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14798 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14799 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14800 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14801 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14803 ;; All the other keys
14805 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14806 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14807 (if (boundp 'narrow-map)
14808 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14809 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14810 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14811 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14812 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14813 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14814 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
14815 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14816 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14817 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14818 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14819 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14820 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14821 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14822 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14823 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14824 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14825 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14826 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14827 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14828 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14829 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14830 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14831 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14832 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14833 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14834 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14835 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14836 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14837 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14838 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14839 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14840 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14841 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14842 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14843 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14844 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14845 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14846 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14847 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14848 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14849 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14850 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14851 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14852 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14853 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14854 (org-defkey org-mode-map "\C-c^" 'org-sort)
14855 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14856 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14857 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
14858 (org-defkey org-mode-map "\C-m" 'org-return)
14859 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14860 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14861 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14862 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14863 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14864 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14865 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14866 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14867 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14868 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14869 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14870 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14871 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14872 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14873 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14874 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14875 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14876 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
14877 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
14878 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14879 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14881 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14882 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14883 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14884 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14886 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14887 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14888 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14889 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14890 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14891 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14892 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14893 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14894 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14895 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14896 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14897 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
14898 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14899 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14900 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14902 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14903 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14904 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14905 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14907 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14909 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14911 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14912 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14914 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14917 (when (featurep 'xemacs)
14918 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14921 (defconst org-speed-commands-default
14923 ("Outline Navigation")
14924 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
14925 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
14926 ("f" . (org-speed-move-safe 'org-forward-same-level))
14927 ("b" . (org-speed-move-safe 'org-backward-same-level))
14928 ("u" . (org-speed-move-safe 'outline-up-heading))
14929 ("j" . org-goto)
14930 ("g" . (org-refile t))
14931 ("Outline Visibility")
14932 ("c" . org-cycle)
14933 ("C" . org-shifttab)
14934 (" " . org-display-outline-path)
14935 ("Outline Structure Editing")
14936 ("U" . org-shiftmetaup)
14937 ("D" . org-shiftmetadown)
14938 ("r" . org-metaright)
14939 ("l" . org-metaleft)
14940 ("R" . org-shiftmetaright)
14941 ("L" . org-shiftmetaleft)
14942 ("i" . (progn (forward-char 1) (call-interactively
14943 'org-insert-heading-respect-content)))
14944 ("^" . org-sort)
14945 ("w" . org-refile)
14946 ("a" . org-archive-subtree-default-with-confirmation)
14947 ("." . outline-mark-subtree)
14948 ("Clock Commands")
14949 ("I" . org-clock-in)
14950 ("O" . org-clock-out)
14951 ("Meta Data Editing")
14952 ("t" . org-todo)
14953 ("0" . (org-priority ?\ ))
14954 ("1" . (org-priority ?A))
14955 ("2" . (org-priority ?B))
14956 ("3" . (org-priority ?C))
14957 (";" . org-set-tags-command)
14958 ("e" . org-set-effort)
14959 ("Agenda Views etc")
14960 ("v" . org-agenda)
14961 ("/" . org-sparse-tree)
14962 ("Misc")
14963 ("o" . org-open-at-point)
14964 ("?" . org-speed-command-help)
14966 "The default speed commands.")
14968 (defun org-print-speed-command (e)
14969 (if (> (length (car e)) 1)
14970 (progn
14971 (princ "\n")
14972 (princ (car e))
14973 (princ "\n")
14974 (princ (make-string (length (car e)) ?-))
14975 (princ "\n"))
14976 (princ (car e))
14977 (princ " ")
14978 (if (symbolp (cdr e))
14979 (princ (symbol-name (cdr e)))
14980 (prin1 (cdr e)))
14981 (princ "\n")))
14983 (defun org-speed-command-help ()
14984 "Show the available speed commands."
14985 (interactive)
14986 (if (not org-use-speed-commands)
14987 (error "Speed commands are not activated, customize `org-use-speed-commands'")
14988 (with-output-to-temp-buffer "*Help*"
14989 (princ "User-defined Speed commands\n===========================\n")
14990 (mapc 'org-print-speed-command org-speed-commands-user)
14991 (princ "\n")
14992 (princ "Built-in Speed commands\n=======================\n")
14993 (mapc 'org-print-speed-command org-speed-commands-default))
14994 (with-current-buffer "*Help*"
14995 (setq truncate-lines t))))
14997 (defun org-speed-move-safe (cmd)
14998 "Execute CMD, but make sure that the cursor always ends up in a headline.
14999 If not, return to the original position and throw an error."
15000 (interactive)
15001 (let ((pos (point)))
15002 (call-interactively cmd)
15003 (unless (and (bolp) (org-on-heading-p))
15004 (goto-char pos)
15005 (error "Boundary reached while executing %s" cmd))))
15007 (defvar org-self-insert-command-undo-counter 0)
15009 (defvar org-table-auto-blank-field) ; defined in org-table.el
15010 (defvar org-speed-command nil)
15011 (defun org-self-insert-command (N)
15012 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15013 If the cursor is in a table looking at whitespace, the whitespace is
15014 overwritten, and the table is not marked as requiring realignment."
15015 (interactive "p")
15016 (cond
15017 ((and org-use-speed-commands
15018 (or (and (bolp) (looking-at outline-regexp))
15019 (and (functionp org-use-speed-commands)
15020 (funcall org-use-speed-commands)))
15021 (setq
15022 org-speed-command
15023 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15024 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15025 (cond
15026 ((commandp org-speed-command)
15027 (setq this-command org-speed-command)
15028 (call-interactively org-speed-command))
15029 ((functionp org-speed-command)
15030 (funcall org-speed-command))
15031 ((and org-speed-command (listp org-speed-command))
15032 (eval org-speed-command))
15033 (t (let (org-use-speed-commands)
15034 (call-interactively 'org-self-insert-command)))))
15035 ((and
15036 (org-table-p)
15037 (progn
15038 ;; check if we blank the field, and if that triggers align
15039 (and (featurep 'org-table) org-table-auto-blank-field
15040 (member last-command
15041 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15042 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15043 ;; got extra space, this field does not determine column width
15044 (let (org-table-may-need-update) (org-table-blank-field))
15045 ;; no extra space, this field may determine column width
15046 (org-table-blank-field)))
15048 (eq N 1)
15049 (looking-at "[^|\n]* |"))
15050 (let (org-table-may-need-update)
15051 (goto-char (1- (match-end 0)))
15052 (delete-backward-char 1)
15053 (goto-char (match-beginning 0))
15054 (self-insert-command N)))
15056 (setq org-table-may-need-update t)
15057 (self-insert-command N)
15058 (org-fix-tags-on-the-fly)
15059 (if org-self-insert-cluster-for-undo
15060 (if (not (eq last-command 'org-self-insert-command))
15061 (setq org-self-insert-command-undo-counter 1)
15062 (if (>= org-self-insert-command-undo-counter 20)
15063 (setq org-self-insert-command-undo-counter 1)
15064 (and (> org-self-insert-command-undo-counter 0)
15065 buffer-undo-list
15066 (not (cadr buffer-undo-list)) ; remove nil entry
15067 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15068 (setq org-self-insert-command-undo-counter
15069 (1+ org-self-insert-command-undo-counter))))))))
15071 (defun org-fix-tags-on-the-fly ()
15072 (when (and (equal (char-after (point-at-bol)) ?*)
15073 (org-on-heading-p))
15074 (org-align-tags-here org-tags-column)))
15076 (defun org-delete-backward-char (N)
15077 "Like `delete-backward-char', insert whitespace at field end in tables.
15078 When deleting backwards, in tables this function will insert whitespace in
15079 front of the next \"|\" separator, to keep the table aligned. The table will
15080 still be marked for re-alignment if the field did fill the entire column,
15081 because, in this case the deletion might narrow the column."
15082 (interactive "p")
15083 (if (and (org-table-p)
15084 (eq N 1)
15085 (string-match "|" (buffer-substring (point-at-bol) (point)))
15086 (looking-at ".*?|"))
15087 (let ((pos (point))
15088 (noalign (looking-at "[^|\n\r]* |"))
15089 (c org-table-may-need-update))
15090 (backward-delete-char N)
15091 (skip-chars-forward "^|")
15092 (insert " ")
15093 (goto-char (1- pos))
15094 ;; noalign: if there were two spaces at the end, this field
15095 ;; does not determine the width of the column.
15096 (if noalign (setq org-table-may-need-update c)))
15097 (backward-delete-char N)
15098 (org-fix-tags-on-the-fly)))
15100 (defun org-delete-char (N)
15101 "Like `delete-char', but insert whitespace at field end in tables.
15102 When deleting characters, in tables this function will insert whitespace in
15103 front of the next \"|\" separator, to keep the table aligned. The table will
15104 still be marked for re-alignment if the field did fill the entire column,
15105 because, in this case the deletion might narrow the column."
15106 (interactive "p")
15107 (if (and (org-table-p)
15108 (not (bolp))
15109 (not (= (char-after) ?|))
15110 (eq N 1))
15111 (if (looking-at ".*?|")
15112 (let ((pos (point))
15113 (noalign (looking-at "[^|\n\r]* |"))
15114 (c org-table-may-need-update))
15115 (replace-match (concat
15116 (substring (match-string 0) 1 -1)
15117 " |"))
15118 (goto-char pos)
15119 ;; noalign: if there were two spaces at the end, this field
15120 ;; does not determine the width of the column.
15121 (if noalign (setq org-table-may-need-update c)))
15122 (delete-char N))
15123 (delete-char N)
15124 (org-fix-tags-on-the-fly)))
15126 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15127 (put 'org-self-insert-command 'delete-selection t)
15128 (put 'orgtbl-self-insert-command 'delete-selection t)
15129 (put 'org-delete-char 'delete-selection 'supersede)
15130 (put 'org-delete-backward-char 'delete-selection 'supersede)
15131 (put 'org-yank 'delete-selection 'yank)
15133 ;; Make `flyspell-mode' delay after some commands
15134 (put 'org-self-insert-command 'flyspell-delayed t)
15135 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15136 (put 'org-delete-char 'flyspell-delayed t)
15137 (put 'org-delete-backward-char 'flyspell-delayed t)
15139 ;; Make pabbrev-mode expand after org-mode commands
15140 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15141 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15143 ;; How to do this: Measure non-white length of current string
15144 ;; If equal to column width, we should realign.
15146 (defun org-remap (map &rest commands)
15147 "In MAP, remap the functions given in COMMANDS.
15148 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15149 (let (new old)
15150 (while commands
15151 (setq old (pop commands) new (pop commands))
15152 (if (fboundp 'command-remapping)
15153 (org-defkey map (vector 'remap old) new)
15154 (substitute-key-definition old new map global-map)))))
15156 (when (eq org-enable-table-editor 'optimized)
15157 ;; If the user wants maximum table support, we need to hijack
15158 ;; some standard editing functions
15159 (org-remap org-mode-map
15160 'self-insert-command 'org-self-insert-command
15161 'delete-char 'org-delete-char
15162 'delete-backward-char 'org-delete-backward-char)
15163 (org-defkey org-mode-map "|" 'org-force-self-insert))
15165 (defvar org-ctrl-c-ctrl-c-hook nil
15166 "Hook for functions attaching themselves to `C-c C-c'.
15167 This can be used to add additional functionality to the C-c C-c key which
15168 executes context-dependent commands.
15169 Each function will be called with no arguments. The function must check
15170 if the context is appropriate for it to act. If yes, it should do its
15171 thing and then return a non-nil value. If the context is wrong,
15172 just do nothing and return nil.")
15174 (defvar org-tab-first-hook nil
15175 "Hook for functions to attach themselves to TAB.
15176 See `org-ctrl-c-ctrl-c-hook' for more information.
15177 This hook runs as the first action when TAB is pressed, even before
15178 `org-cycle' messes around with the `outline-regexp' to cater for
15179 inline tasks and plain list item folding.
15180 If any function in this hook returns t, not other actions like table
15181 field motion visibility cycling will be done.")
15183 (defvar org-tab-after-check-for-table-hook nil
15184 "Hook for functions to attach themselves to TAB.
15185 See `org-ctrl-c-ctrl-c-hook' for more information.
15186 This hook runs after it has been established that the cursor is not in a
15187 table, but before checking if the cursor is in a headline or if global cycling
15188 should be done.
15189 If any function in this hook returns t, not other actions like visibility
15190 cycling will be done.")
15192 (defvar org-tab-after-check-for-cycling-hook nil
15193 "Hook for functions to attach themselves to TAB.
15194 See `org-ctrl-c-ctrl-c-hook' for more information.
15195 This hook runs after it has been established that not table field motion and
15196 not visibility should be done because of current context. This is probably
15197 the place where a package like yasnippets can hook in.")
15199 (defvar org-tab-before-tab-emulation-hook nil
15200 "Hook for functions to attach themselves to TAB.
15201 See `org-ctrl-c-ctrl-c-hook' for more information.
15202 This hook runs after every other options for TAB have been exhausted, but
15203 before indentation and \t insertion takes place.")
15205 (defvar org-metaleft-hook nil
15206 "Hook for functions attaching themselves to `M-left'.
15207 See `org-ctrl-c-ctrl-c-hook' for more information.")
15208 (defvar org-metaright-hook nil
15209 "Hook for functions attaching themselves to `M-right'.
15210 See `org-ctrl-c-ctrl-c-hook' for more information.")
15211 (defvar org-metaup-hook nil
15212 "Hook for functions attaching themselves to `M-up'.
15213 See `org-ctrl-c-ctrl-c-hook' for more information.")
15214 (defvar org-metadown-hook nil
15215 "Hook for functions attaching themselves to `M-down'.
15216 See `org-ctrl-c-ctrl-c-hook' for more information.")
15217 (defvar org-shiftmetaleft-hook nil
15218 "Hook for functions attaching themselves to `M-S-left'.
15219 See `org-ctrl-c-ctrl-c-hook' for more information.")
15220 (defvar org-shiftmetaright-hook nil
15221 "Hook for functions attaching themselves to `M-S-right'.
15222 See `org-ctrl-c-ctrl-c-hook' for more information.")
15223 (defvar org-shiftmetaup-hook nil
15224 "Hook for functions attaching themselves to `M-S-up'.
15225 See `org-ctrl-c-ctrl-c-hook' for more information.")
15226 (defvar org-shiftmetadown-hook nil
15227 "Hook for functions attaching themselves to `M-S-down'.
15228 See `org-ctrl-c-ctrl-c-hook' for more information.")
15229 (defvar org-metareturn-hook nil
15230 "Hook for functions attaching themselves to `M-RET'.
15231 See `org-ctrl-c-ctrl-c-hook' for more information.")
15233 (defun org-modifier-cursor-error ()
15234 "Throw an error, a modified cursor command was applied in wrong context."
15235 (error "This command is active in special context like tables, headlines or items"))
15237 (defun org-shiftselect-error ()
15238 "Throw an error because Shift-Cursor command was applied in wrong context."
15239 (if (and (boundp 'shift-select-mode) shift-select-mode)
15240 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15241 (error "This command works only in special context like headlines or timestamps")))
15243 (defun org-call-for-shift-select (cmd)
15244 (let ((this-command-keys-shift-translated t))
15245 (call-interactively cmd)))
15247 (defun org-shifttab (&optional arg)
15248 "Global visibility cycling or move to previous table field.
15249 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15250 on context.
15251 See the individual commands for more information."
15252 (interactive "P")
15253 (cond
15254 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15255 ((integerp arg)
15256 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15257 (message "Content view to level: %d" arg)
15258 (org-content (prefix-numeric-value arg2))
15259 (setq org-cycle-global-status 'overview)))
15260 (t (call-interactively 'org-global-cycle))))
15262 (defun org-shiftmetaleft ()
15263 "Promote subtree or delete table column.
15264 Calls `org-promote-subtree', `org-outdent-item',
15265 or `org-table-delete-column', depending on context.
15266 See the individual commands for more information."
15267 (interactive)
15268 (cond
15269 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15270 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15271 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15272 ((org-at-item-p) (call-interactively 'org-outdent-item))
15273 (t (org-modifier-cursor-error))))
15275 (defun org-shiftmetaright ()
15276 "Demote subtree or insert table column.
15277 Calls `org-demote-subtree', `org-indent-item',
15278 or `org-table-insert-column', depending on context.
15279 See the individual commands for more information."
15280 (interactive)
15281 (cond
15282 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15283 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15284 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15285 ((org-at-item-p) (call-interactively 'org-indent-item))
15286 (t (org-modifier-cursor-error))))
15288 (defun org-shiftmetaup (&optional arg)
15289 "Move subtree up or kill table row.
15290 Calls `org-move-subtree-up' or `org-table-kill-row' or
15291 `org-move-item-up' depending on context. See the individual commands
15292 for more information."
15293 (interactive "P")
15294 (cond
15295 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15296 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15297 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15298 ((org-at-item-p) (call-interactively 'org-move-item-up))
15299 (t (org-modifier-cursor-error))))
15301 (defun org-shiftmetadown (&optional arg)
15302 "Move subtree down or insert table row.
15303 Calls `org-move-subtree-down' or `org-table-insert-row' or
15304 `org-move-item-down', depending on context. See the individual
15305 commands for more information."
15306 (interactive "P")
15307 (cond
15308 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15309 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15310 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15311 ((org-at-item-p) (call-interactively 'org-move-item-down))
15312 (t (org-modifier-cursor-error))))
15314 (defun org-metaleft (&optional arg)
15315 "Promote heading or move table column to left.
15316 Calls `org-do-promote' or `org-table-move-column', depending on context.
15317 With no specific context, calls the Emacs default `backward-word'.
15318 See the individual commands for more information."
15319 (interactive "P")
15320 (cond
15321 ((run-hook-with-args-until-success 'org-metaleft-hook))
15322 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15323 ((or (org-on-heading-p)
15324 (and (org-region-active-p)
15325 (save-excursion
15326 (goto-char (region-beginning))
15327 (org-on-heading-p))))
15328 (call-interactively 'org-do-promote))
15329 ((or (org-at-item-p)
15330 (and (org-region-active-p)
15331 (save-excursion
15332 (goto-char (region-beginning))
15333 (org-at-item-p))))
15334 (call-interactively 'org-outdent-item))
15335 (t (call-interactively 'backward-word))))
15337 (defun org-metaright (&optional arg)
15338 "Demote subtree or move table column to right.
15339 Calls `org-do-demote' or `org-table-move-column', depending on context.
15340 With no specific context, calls the Emacs default `forward-word'.
15341 See the individual commands for more information."
15342 (interactive "P")
15343 (cond
15344 ((run-hook-with-args-until-success 'org-metaright-hook))
15345 ((org-at-table-p) (call-interactively 'org-table-move-column))
15346 ((or (org-on-heading-p)
15347 (and (org-region-active-p)
15348 (save-excursion
15349 (goto-char (region-beginning))
15350 (org-on-heading-p))))
15351 (call-interactively 'org-do-demote))
15352 ((or (org-at-item-p)
15353 (and (org-region-active-p)
15354 (save-excursion
15355 (goto-char (region-beginning))
15356 (org-at-item-p))))
15357 (call-interactively 'org-indent-item))
15358 (t (call-interactively 'forward-word))))
15360 (defun org-metaup (&optional arg)
15361 "Move subtree up or move table row up.
15362 Calls `org-move-subtree-up' or `org-table-move-row' or
15363 `org-move-item-up', depending on context. See the individual commands
15364 for more information."
15365 (interactive "P")
15366 (cond
15367 ((run-hook-with-args-until-success 'org-metaup-hook))
15368 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15369 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15370 ((org-at-item-p) (call-interactively 'org-move-item-up))
15371 (t (transpose-lines 1) (beginning-of-line -1))))
15373 (defun org-metadown (&optional arg)
15374 "Move subtree down or move table row down.
15375 Calls `org-move-subtree-down' or `org-table-move-row' or
15376 `org-move-item-down', depending on context. See the individual
15377 commands for more information."
15378 (interactive "P")
15379 (cond
15380 ((run-hook-with-args-until-success 'org-metadown-hook))
15381 ((org-at-table-p) (call-interactively 'org-table-move-row))
15382 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15383 ((org-at-item-p) (call-interactively 'org-move-item-down))
15384 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15386 (defun org-shiftup (&optional arg)
15387 "Increase item in timestamp or increase priority of current headline.
15388 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15389 depending on context. See the individual commands for more information."
15390 (interactive "P")
15391 (cond
15392 ((and org-support-shift-select (org-region-active-p))
15393 (org-call-for-shift-select 'previous-line))
15394 ((org-at-timestamp-p t)
15395 (call-interactively (if org-edit-timestamp-down-means-later
15396 'org-timestamp-down 'org-timestamp-up)))
15397 ((and (not (eq org-support-shift-select 'always))
15398 org-enable-priority-commands
15399 (org-on-heading-p))
15400 (call-interactively 'org-priority-up))
15401 ((and (not org-support-shift-select) (org-at-item-p))
15402 (call-interactively 'org-previous-item))
15403 ((org-clocktable-try-shift 'up arg))
15404 (org-support-shift-select
15405 (org-call-for-shift-select 'previous-line))
15406 (t (org-shiftselect-error))))
15408 (defun org-shiftdown (&optional arg)
15409 "Decrease item in timestamp or decrease priority of current headline.
15410 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15411 depending on context. See the individual commands for more information."
15412 (interactive "P")
15413 (cond
15414 ((and org-support-shift-select (org-region-active-p))
15415 (org-call-for-shift-select 'next-line))
15416 ((org-at-timestamp-p t)
15417 (call-interactively (if org-edit-timestamp-down-means-later
15418 'org-timestamp-up 'org-timestamp-down)))
15419 ((and (not (eq org-support-shift-select 'always))
15420 org-enable-priority-commands
15421 (org-on-heading-p))
15422 (call-interactively 'org-priority-down))
15423 ((and (not org-support-shift-select) (org-at-item-p))
15424 (call-interactively 'org-next-item))
15425 ((org-clocktable-try-shift 'down arg))
15426 (org-support-shift-select
15427 (org-call-for-shift-select 'next-line))
15428 (t (org-shiftselect-error))))
15430 (defun org-shiftright (&optional arg)
15431 "Cycle the thing at point or in the current line, depending on context.
15432 Depending on context, this does one of the following:
15434 - switch a timestamp at point one day into the future
15435 - on a headline, switch to the next TODO keyword.
15436 - on an item, switch entire list to the next bullet type
15437 - on a property line, switch to the next allowed value
15438 - on a clocktable definition line, move time block into the future"
15439 (interactive "P")
15440 (cond
15441 ((and org-support-shift-select (org-region-active-p))
15442 (org-call-for-shift-select 'forward-char))
15443 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15444 ((and (not (eq org-support-shift-select 'always))
15445 (org-on-heading-p))
15446 (let ((org-inhibit-logging
15447 (not org-treat-S-cursor-todo-selection-as-state-change))
15448 (org-inhibit-blocking
15449 (not org-treat-S-cursor-todo-selection-as-state-change)))
15450 (org-call-with-arg 'org-todo 'right)))
15451 ((or (and org-support-shift-select
15452 (not (eq org-support-shift-select 'always))
15453 (org-at-item-bullet-p))
15454 (and (not org-support-shift-select) (org-at-item-p)))
15455 (org-call-with-arg 'org-cycle-list-bullet nil))
15456 ((and (not (eq org-support-shift-select 'always))
15457 (org-at-property-p))
15458 (call-interactively 'org-property-next-allowed-value))
15459 ((org-clocktable-try-shift 'right arg))
15460 (org-support-shift-select
15461 (org-call-for-shift-select 'forward-char))
15462 (t (org-shiftselect-error))))
15464 (defun org-shiftleft (&optional arg)
15465 "Cycle the thing at point or in the current line, depending on context.
15466 Depending on context, this does one of the following:
15468 - switch a timestamp at point one day into the past
15469 - on a headline, switch to the previous TODO keyword.
15470 - on an item, switch entire list to the previous bullet type
15471 - on a property line, switch to the previous allowed value
15472 - on a clocktable definition line, move time block into the past"
15473 (interactive "P")
15474 (cond
15475 ((and org-support-shift-select (org-region-active-p))
15476 (org-call-for-shift-select 'backward-char))
15477 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15478 ((and (not (eq org-support-shift-select 'always))
15479 (org-on-heading-p))
15480 (let ((org-inhibit-logging
15481 (not org-treat-S-cursor-todo-selection-as-state-change))
15482 (org-inhibit-blocking
15483 (not org-treat-S-cursor-todo-selection-as-state-change)))
15484 (org-call-with-arg 'org-todo 'left)))
15485 ((or (and org-support-shift-select
15486 (not (eq org-support-shift-select 'always))
15487 (org-at-item-bullet-p))
15488 (and (not org-support-shift-select) (org-at-item-p)))
15489 (org-call-with-arg 'org-cycle-list-bullet 'previous))
15490 ((and (not (eq org-support-shift-select 'always))
15491 (org-at-property-p))
15492 (call-interactively 'org-property-previous-allowed-value))
15493 ((org-clocktable-try-shift 'left arg))
15494 (org-support-shift-select
15495 (org-call-for-shift-select 'backward-char))
15496 (t (org-shiftselect-error))))
15498 (defun org-shiftcontrolright ()
15499 "Switch to next TODO set."
15500 (interactive)
15501 (cond
15502 ((and org-support-shift-select (org-region-active-p))
15503 (org-call-for-shift-select 'forward-word))
15504 ((and (not (eq org-support-shift-select 'always))
15505 (org-on-heading-p))
15506 (org-call-with-arg 'org-todo 'nextset))
15507 (org-support-shift-select
15508 (org-call-for-shift-select 'forward-word))
15509 (t (org-shiftselect-error))))
15511 (defun org-shiftcontrolleft ()
15512 "Switch to previous TODO set."
15513 (interactive)
15514 (cond
15515 ((and org-support-shift-select (org-region-active-p))
15516 (org-call-for-shift-select 'backward-word))
15517 ((and (not (eq org-support-shift-select 'always))
15518 (org-on-heading-p))
15519 (org-call-with-arg 'org-todo 'previousset))
15520 (org-support-shift-select
15521 (org-call-for-shift-select 'backward-word))
15522 (t (org-shiftselect-error))))
15524 (defun org-ctrl-c-ret ()
15525 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15526 (interactive)
15527 (cond
15528 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15529 (t (call-interactively 'org-insert-heading))))
15531 (defun org-copy-special ()
15532 "Copy region in table or copy current subtree.
15533 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15534 See the individual commands for more information."
15535 (interactive)
15536 (call-interactively
15537 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15539 (defun org-cut-special ()
15540 "Cut region in table or cut current subtree.
15541 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15542 See the individual commands for more information."
15543 (interactive)
15544 (call-interactively
15545 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15547 (defun org-paste-special (arg)
15548 "Paste rectangular region into table, or past subtree relative to level.
15549 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15550 See the individual commands for more information."
15551 (interactive "P")
15552 (if (org-at-table-p)
15553 (org-table-paste-rectangle)
15554 (org-paste-subtree arg)))
15556 (defun org-edit-special ()
15557 "Call a special editor for the stuff at point.
15558 When at a table, call the formula editor with `org-table-edit-formulas'.
15559 When at the first line of an src example, call `org-edit-src-code'.
15560 When in an #+include line, visit the include file. Otherwise call
15561 `ffap' to visit the file at point."
15562 (interactive)
15563 (cond
15564 ((org-at-table-p)
15565 (call-interactively 'org-table-edit-formulas))
15566 ((save-excursion
15567 (beginning-of-line 1)
15568 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
15569 (find-file (org-trim (match-string 1))))
15570 ((org-edit-src-code))
15571 ((org-edit-fixed-width-region))
15572 (t (call-interactively 'ffap))))
15575 (defun org-ctrl-c-ctrl-c (&optional arg)
15576 "Set tags in headline, or update according to changed information at point.
15578 This command does many different things, depending on context:
15580 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15581 this is what we do.
15583 - If the cursor is on a statistics cookie, update it.
15585 - If the cursor is in a headline, prompt for tags and insert them
15586 into the current line, aligned to `org-tags-column'. When called
15587 with prefix arg, realign all tags in the current buffer.
15589 - If the cursor is in one of the special #+KEYWORD lines, this
15590 triggers scanning the buffer for these lines and updating the
15591 information.
15593 - If the cursor is inside a table, realign the table. This command
15594 works even if the automatic table editor has been turned off.
15596 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15597 the entire table.
15599 - If the cursor is at a footnote reference or definition, jump to
15600 the corresponding definition or references, respectively.
15602 - If the cursor is a the beginning of a dynamic block, update it.
15604 - If the cursor is inside a table created by the table.el package,
15605 activate that table.
15607 - If the current buffer is a remember buffer, close note and file
15608 it. A prefix argument of 1 files to the default location
15609 without further interaction. A prefix argument of 2 files to
15610 the currently clocking task.
15612 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15613 links in this buffer.
15615 - If the cursor is on a numbered item in a plain list, renumber the
15616 ordered list.
15618 - If the cursor is on a checkbox, toggle it."
15619 (interactive "P")
15620 (let ((org-enable-table-editor t))
15621 (cond
15622 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15623 org-occur-highlights
15624 org-latex-fragment-image-overlays)
15625 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15626 (org-remove-occur-highlights)
15627 (org-remove-latex-fragment-image-overlays)
15628 (message "Temporary highlights/overlays removed from current buffer"))
15629 ((and (local-variable-p 'org-finish-function (current-buffer))
15630 (fboundp org-finish-function))
15631 (funcall org-finish-function))
15632 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15633 ((org-at-property-p)
15634 (call-interactively 'org-property-action))
15635 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15636 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15637 (or (org-on-heading-p) (org-at-item-p)))
15638 (call-interactively 'org-update-statistics-cookies))
15639 ((org-on-heading-p) (call-interactively 'org-set-tags))
15640 ((org-at-table.el-p)
15641 (require 'table)
15642 (beginning-of-line 1)
15643 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15644 (call-interactively 'table-recognize-table))
15645 ((org-at-table-p)
15646 (org-table-maybe-eval-formula)
15647 (if arg
15648 (call-interactively 'org-table-recalculate)
15649 (org-table-maybe-recalculate-line))
15650 (call-interactively 'org-table-align))
15651 ((or (org-footnote-at-reference-p)
15652 (org-footnote-at-definition-p))
15653 (call-interactively 'org-footnote-action))
15654 ((org-at-item-checkbox-p)
15655 (call-interactively 'org-toggle-checkbox))
15656 ((org-at-item-p)
15657 (if arg
15658 (call-interactively 'org-toggle-checkbox)
15659 (call-interactively 'org-maybe-renumber-ordered-list)))
15660 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15661 ;; Dynamic block
15662 (beginning-of-line 1)
15663 (save-excursion (org-update-dblock)))
15664 ((save-excursion
15665 (beginning-of-line 1)
15666 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15667 (cond
15668 ((equal (match-string 1) "TBLFM")
15669 ;; Recalculate the table before this line
15670 (save-excursion
15671 (beginning-of-line 1)
15672 (skip-chars-backward " \r\n\t")
15673 (if (org-at-table-p)
15674 (org-call-with-arg 'org-table-recalculate (or arg t)))))
15676 ; (org-set-regexps-and-options)
15677 ; (org-restart-font-lock)
15678 (let ((org-inhibit-startup t)) (org-mode-restart))
15679 (message "Local setup has been refreshed"))))
15680 ((org-clock-update-time-maybe))
15681 (t (error "C-c C-c can do nothing useful at this location")))))
15683 (defun org-mode-restart ()
15684 "Restart Org-mode, to scan again for special lines.
15685 Also updates the keyword regular expressions."
15686 (interactive)
15687 (org-mode)
15688 (message "Org-mode restarted"))
15690 (defun org-kill-note-or-show-branches ()
15691 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15692 (interactive)
15693 (if (not org-finish-function)
15694 (call-interactively 'show-branches)
15695 (let ((org-note-abort t))
15696 (funcall org-finish-function))))
15698 (defun org-return (&optional indent)
15699 "Goto next table row or insert a newline.
15700 Calls `org-table-next-row' or `newline', depending on context.
15701 See the individual commands for more information."
15702 (interactive)
15703 (cond
15704 ((bobp) (if indent (newline-and-indent) (newline)))
15705 ((org-at-table-p)
15706 (org-table-justify-field-maybe)
15707 (call-interactively 'org-table-next-row))
15708 ((and org-return-follows-link
15709 (eq (get-text-property (point) 'face) 'org-link))
15710 (call-interactively 'org-open-at-point))
15711 ((and (org-at-heading-p)
15712 (looking-at
15713 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15714 (org-show-entry)
15715 (end-of-line 1)
15716 (newline))
15717 (t (if indent (newline-and-indent) (newline)))))
15719 (defun org-return-indent ()
15720 "Goto next table row or insert a newline and indent.
15721 Calls `org-table-next-row' or `newline-and-indent', depending on
15722 context. See the individual commands for more information."
15723 (interactive)
15724 (org-return t))
15726 (defun org-ctrl-c-star ()
15727 "Compute table, or change heading status of lines.
15728 Calls `org-table-recalculate' or `org-toggle-heading',
15729 depending on context."
15730 (interactive)
15731 (cond
15732 ((org-at-table-p)
15733 (call-interactively 'org-table-recalculate))
15735 ;; Convert all lines in region to list items
15736 (call-interactively 'org-toggle-heading))))
15738 (defun org-ctrl-c-minus ()
15739 "Insert separator line in table or modify bullet status of line.
15740 Also turns a plain line or a region of lines into list items.
15741 Calls `org-table-insert-hline', `org-toggle-item', or
15742 `org-cycle-list-bullet', depending on context."
15743 (interactive)
15744 (cond
15745 ((org-at-table-p)
15746 (call-interactively 'org-table-insert-hline))
15747 ((org-region-active-p)
15748 (call-interactively 'org-toggle-item))
15749 ((org-in-item-p)
15750 (call-interactively 'org-cycle-list-bullet))
15752 (call-interactively 'org-toggle-item))))
15754 (defun org-toggle-item ()
15755 "Convert headings or normal lines to items, items to normal lines.
15756 If there is no active region, only the current line is considered.
15758 If the first line in the region is a headline, convert all headlines to items.
15760 If the first line in the region is an item, convert all items to normal lines.
15762 If the first line is normal text, add an item bullet to each line."
15763 (interactive)
15764 (let (l2 l beg end)
15765 (if (org-region-active-p)
15766 (setq beg (region-beginning) end (region-end))
15767 (setq beg (point-at-bol)
15768 end (min (1+ (point-at-eol)) (point-max))))
15769 (save-excursion
15770 (goto-char end)
15771 (setq l2 (org-current-line))
15772 (goto-char beg)
15773 (beginning-of-line 1)
15774 (setq l (1- (org-current-line)))
15775 (if (org-at-item-p)
15776 ;; We already have items, de-itemize
15777 (while (< (setq l (1+ l)) l2)
15778 (when (org-at-item-p)
15779 (goto-char (match-beginning 2))
15780 (delete-region (match-beginning 2) (match-end 2))
15781 (and (looking-at "[ \t]+") (replace-match "")))
15782 (beginning-of-line 2))
15783 (if (org-on-heading-p)
15784 ;; Headings, convert to items
15785 (while (< (setq l (1+ l)) l2)
15786 (if (looking-at org-outline-regexp)
15787 (replace-match "- " t t))
15788 (beginning-of-line 2))
15789 ;; normal lines, turn them into items
15790 (while (< (setq l (1+ l)) l2)
15791 (unless (org-at-item-p)
15792 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15793 (replace-match "\\1- \\2")))
15794 (beginning-of-line 2)))))))
15796 (defun org-toggle-heading (&optional nstars)
15797 "Convert headings to normal text, or items or text to headings.
15798 If there is no active region, only the current line is considered.
15800 If the first line is a heading, remove the stars from all headlines
15801 in the region.
15803 If the first line is a plain list item, turn all plain list items
15804 into headings.
15806 If the first line is a normal line, turn each and every line in the
15807 region into a heading.
15809 When converting a line into a heading, the number of stars is chosen
15810 such that the lines become children of the current entry. However,
15811 when a prefix argument is given, its value determines the number of
15812 stars to add."
15813 (interactive "P")
15814 (let (l2 l itemp beg end)
15815 (if (org-region-active-p)
15816 (setq beg (region-beginning) end (region-end))
15817 (setq beg (point-at-bol)
15818 end (min (1+ (point-at-eol)) (point-max))))
15819 (save-excursion
15820 (goto-char end)
15821 (setq l2 (org-current-line))
15822 (goto-char beg)
15823 (beginning-of-line 1)
15824 (setq l (1- (org-current-line)))
15825 (if (org-on-heading-p)
15826 ;; We already have headlines, de-star them
15827 (while (< (setq l (1+ l)) l2)
15828 (when (org-on-heading-p t)
15829 (and (looking-at outline-regexp) (replace-match "")))
15830 (beginning-of-line 2))
15831 (setq itemp (org-at-item-p))
15832 (let* ((stars
15833 (if nstars
15834 (make-string (prefix-numeric-value current-prefix-arg)
15836 (save-excursion
15837 (if (re-search-backward org-complex-heading-regexp nil t)
15838 (match-string 1) ""))))
15839 (add-stars (cond (nstars "")
15840 ((equal stars "") "*")
15841 (org-odd-levels-only "**")
15842 (t "*")))
15843 (rpl (concat stars add-stars " ")))
15844 (while (< (setq l (1+ l)) l2)
15845 (if itemp
15846 (and (org-at-item-p) (replace-match rpl t t))
15847 (unless (org-on-heading-p)
15848 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15849 (replace-match (concat rpl (match-string 2))))))
15850 (beginning-of-line 2)))))))
15852 (defun org-meta-return (&optional arg)
15853 "Insert a new heading or wrap a region in a table.
15854 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15855 See the individual commands for more information."
15856 (interactive "P")
15857 (cond
15858 ((run-hook-with-args-until-success 'org-metareturn-hook))
15859 ((org-at-table-p)
15860 (call-interactively 'org-table-wrap-region))
15861 (t (call-interactively 'org-insert-heading))))
15863 ;;; Menu entries
15865 ;; Define the Org-mode menus
15866 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15867 '("Tbl"
15868 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15869 ["Next Field" org-cycle (org-at-table-p)]
15870 ["Previous Field" org-shifttab (org-at-table-p)]
15871 ["Next Row" org-return (org-at-table-p)]
15872 "--"
15873 ["Blank Field" org-table-blank-field (org-at-table-p)]
15874 ["Edit Field" org-table-edit-field (org-at-table-p)]
15875 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15876 "--"
15877 ("Column"
15878 ["Move Column Left" org-metaleft (org-at-table-p)]
15879 ["Move Column Right" org-metaright (org-at-table-p)]
15880 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15881 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15882 ("Row"
15883 ["Move Row Up" org-metaup (org-at-table-p)]
15884 ["Move Row Down" org-metadown (org-at-table-p)]
15885 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15886 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15887 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15888 "--"
15889 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15890 ("Rectangle"
15891 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15892 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15893 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15894 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15895 "--"
15896 ("Calculate"
15897 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15898 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15899 ["Edit Formulas" org-edit-special (org-at-table-p)]
15900 "--"
15901 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15902 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15903 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15904 "--"
15905 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15906 "--"
15907 ["Sum Column/Rectangle" org-table-sum
15908 (or (org-at-table-p) (org-region-active-p))]
15909 ["Which Column?" org-table-current-column (org-at-table-p)])
15910 ["Debug Formulas"
15911 org-table-toggle-formula-debugger
15912 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15913 ["Show Col/Row Numbers"
15914 org-table-toggle-coordinate-overlays
15915 :style toggle
15916 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15917 "--"
15918 ["Create" org-table-create (and (not (org-at-table-p))
15919 org-enable-table-editor)]
15920 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15921 ["Import from File" org-table-import (not (org-at-table-p))]
15922 ["Export to File" org-table-export (org-at-table-p)]
15923 "--"
15924 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15926 (easy-menu-define org-org-menu org-mode-map "Org menu"
15927 '("Org"
15928 ("Show/Hide"
15929 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15930 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15931 ["Sparse Tree..." org-sparse-tree t]
15932 ["Reveal Context" org-reveal t]
15933 ["Show All" show-all t]
15934 "--"
15935 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15936 "--"
15937 ["New Heading" org-insert-heading t]
15938 ("Navigate Headings"
15939 ["Up" outline-up-heading t]
15940 ["Next" outline-next-visible-heading t]
15941 ["Previous" outline-previous-visible-heading t]
15942 ["Next Same Level" outline-forward-same-level t]
15943 ["Previous Same Level" outline-backward-same-level t]
15944 "--"
15945 ["Jump" org-goto t])
15946 ("Edit Structure"
15947 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15948 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15949 "--"
15950 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15951 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15952 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15953 "--"
15954 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15955 "--"
15956 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15957 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15958 ["Demote Heading" org-metaright (not (org-at-table-p))]
15959 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15960 "--"
15961 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15962 "--"
15963 ["Convert to odd levels" org-convert-to-odd-levels t]
15964 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15965 ("Editing"
15966 ["Emphasis..." org-emphasize t]
15967 ["Edit Source Example" org-edit-special t]
15968 "--"
15969 ["Footnote new/jump" org-footnote-action t]
15970 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15971 ("Archive"
15972 ["Archive (default method)" org-archive-subtree-default t]
15973 "--"
15974 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
15975 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15976 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
15978 "--"
15979 ("Hyperlinks"
15980 ["Store Link (Global)" org-store-link t]
15981 ["Find existing link to here" org-occur-link-in-agenda-files t]
15982 ["Insert Link" org-insert-link t]
15983 ["Follow Link" org-open-at-point t]
15984 "--"
15985 ["Next link" org-next-link t]
15986 ["Previous link" org-previous-link t]
15987 "--"
15988 ["Descriptive Links"
15989 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15990 :style radio
15991 :selected (member '(org-link) buffer-invisibility-spec)]
15992 ["Literal Links"
15993 (progn
15994 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15995 :style radio
15996 :selected (not (member '(org-link) buffer-invisibility-spec))])
15997 "--"
15998 ("TODO Lists"
15999 ["TODO/DONE/-" org-todo t]
16000 ("Select keyword"
16001 ["Next keyword" org-shiftright (org-on-heading-p)]
16002 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16003 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
16004 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
16005 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
16006 ["Show TODO Tree" org-show-todo-tree t]
16007 ["Global TODO list" org-todo-list t]
16008 "--"
16009 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
16010 :selected org-enforce-todo-dependencies :style toggle :active t]
16011 "Settings for tree at point"
16012 ["Do Children sequentially" org-toggle-ordered-property :style radio
16013 :selected (ignore-errors (org-entry-get nil "ORDERED"))
16014 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16015 ["Do Children parallel" org-toggle-ordered-property :style radio
16016 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
16017 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16018 "--"
16019 ["Set Priority" org-priority t]
16020 ["Priority Up" org-shiftup t]
16021 ["Priority Down" org-shiftdown t]
16022 "--"
16023 ["Get news from all feeds" org-feed-update-all t]
16024 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16025 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16026 ("TAGS and Properties"
16027 ["Set Tags" org-set-tags-command t]
16028 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16029 "--"
16030 ["Set property" org-set-property t]
16031 ["Column view of properties" org-columns t]
16032 ["Insert Column View DBlock" org-insert-columns-dblock t])
16033 ("Dates and Scheduling"
16034 ["Timestamp" org-time-stamp t]
16035 ["Timestamp (inactive)" org-time-stamp-inactive t]
16036 ("Change Date"
16037 ["1 Day Later" org-shiftright t]
16038 ["1 Day Earlier" org-shiftleft t]
16039 ["1 ... Later" org-shiftup t]
16040 ["1 ... Earlier" org-shiftdown t])
16041 ["Compute Time Range" org-evaluate-time-range t]
16042 ["Schedule Item" org-schedule t]
16043 ["Deadline" org-deadline t]
16044 "--"
16045 ["Custom time format" org-toggle-time-stamp-overlays
16046 :style radio :selected org-display-custom-times]
16047 "--"
16048 ["Goto Calendar" org-goto-calendar t]
16049 ["Date from Calendar" org-date-from-calendar t]
16050 "--"
16051 ["Start/Restart Timer" org-timer-start t]
16052 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16053 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16054 ["Insert Timer String" org-timer t]
16055 ["Insert Timer Item" org-timer-item t])
16056 ("Logging work"
16057 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16058 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16059 ["Clock out" org-clock-out t]
16060 ["Clock cancel" org-clock-cancel t]
16061 "--"
16062 ["Mark as default task" org-clock-mark-default-task t]
16063 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16064 ["Goto running clock" org-clock-goto t]
16065 "--"
16066 ["Display times" org-clock-display t]
16067 ["Create clock table" org-clock-report t]
16068 "--"
16069 ["Record DONE time"
16070 (progn (setq org-log-done (not org-log-done))
16071 (message "Switching to %s will %s record a timestamp"
16072 (car org-done-keywords)
16073 (if org-log-done "automatically" "not")))
16074 :style toggle :selected org-log-done])
16075 "--"
16076 ["Agenda Command..." org-agenda t]
16077 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16078 ("File List for Agenda")
16079 ("Special views current file"
16080 ["TODO Tree" org-show-todo-tree t]
16081 ["Check Deadlines" org-check-deadlines t]
16082 ["Timeline" org-timeline t]
16083 ["Tags/Property tree" org-match-sparse-tree t])
16084 "--"
16085 ["Export/Publish..." org-export t]
16086 ("LaTeX"
16087 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16088 :selected org-cdlatex-mode]
16089 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16090 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16091 ["Modify math symbol" org-cdlatex-math-modify
16092 (org-inside-LaTeX-fragment-p)]
16093 ["Insert citation" org-reftex-citation t]
16094 "--"
16095 ["Export LaTeX fragments as images"
16096 (if (featurep 'org-exp)
16097 (setq org-export-with-LaTeX-fragments
16098 (not org-export-with-LaTeX-fragments))
16099 (require 'org-exp))
16100 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16101 org-export-with-LaTeX-fragments)])
16102 "--"
16103 ("MobileOrg"
16104 ["Push Files and Views" org-mobile-push t]
16105 ["Get Captured and Flagged" org-mobile-pull t]
16106 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16107 "--"
16108 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16109 "--"
16110 ("Documentation"
16111 ["Show Version" org-version t]
16112 ["Info Documentation" org-info t])
16113 ("Customize"
16114 ["Browse Org Group" org-customize t]
16115 "--"
16116 ["Expand This Menu" org-create-customize-menu
16117 (fboundp 'customize-menu-create)])
16118 ["Send bug report" org-submit-bug-report t]
16119 "--"
16120 ("Refresh/Reload"
16121 ["Refresh setup current buffer" org-mode-restart t]
16122 ["Reload Org (after update)" org-reload t]
16123 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16126 (defun org-info (&optional node)
16127 "Read documentation for Org-mode in the info system.
16128 With optional NODE, go directly to that node."
16129 (interactive)
16130 (info (format "(org)%s" (or node ""))))
16132 ;;;###autoload
16133 (defun org-submit-bug-report ()
16134 "Submit a bug report on Org-mode via mail.
16136 Don't hesitate to report any problems or inaccurate documentation.
16138 If you don't have setup sending mail from (X)Emacs, please copy the
16139 output buffer into your mail program, as it gives us important
16140 information about your Org-mode version and configuration."
16141 (interactive)
16142 (require 'reporter)
16143 (org-load-modules-maybe)
16144 (org-require-autoloaded-modules)
16145 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16146 (reporter-submit-bug-report
16147 "emacs-orgmode@gnu.org"
16148 (org-version)
16149 (let (list)
16150 (save-window-excursion
16151 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16152 (delete-other-windows)
16153 (erase-buffer)
16154 (insert "You are about to submit a bug report to the Org-mode mailing list.
16156 We would like to add your full Org-mode and Outline configuration to the
16157 bug report. This greatly simplifies the work of the maintainer and
16158 other experts on the mailing list.
16160 HOWEVER, some variables you have customized may contain private
16161 information. The names of customers, colleagues, or friends, might
16162 appear in the form of file names, tags, todo states, or search strings.
16163 If you answer yes to the prompt, you might want to check and remove
16164 such private information before sending the email.")
16165 (add-text-properties (point-min) (point-max) '(face org-warning))
16166 (when (yes-or-no-p "Include your Org-mode configuration ")
16167 (mapatoms
16168 (lambda (v)
16169 (and (boundp v)
16170 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16171 (or (and (symbol-value v)
16172 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16173 (and
16174 (get v 'custom-type) (get v 'standard-value)
16175 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16176 (push v list)))))
16177 (kill-buffer (get-buffer "*Warn about privacy*"))
16178 list))
16179 nil nil
16180 "Remember to cover the basics, that is, what you expected to happen and
16181 what in fact did happen. You don't know how to make a good report? See
16183 http://orgmode.org/manual/Feedback.html#Feedback
16185 Your bug report will be posted to the Org-mode mailing list.
16186 ------------------------------------------------------------------------")
16187 (save-excursion
16188 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16189 (replace-match "\\1Bug: \\3 [\\2]")))))
16192 (defun org-install-agenda-files-menu ()
16193 (let ((bl (buffer-list)))
16194 (save-excursion
16195 (while bl
16196 (set-buffer (pop bl))
16197 (if (org-mode-p) (setq bl nil)))
16198 (when (org-mode-p)
16199 (easy-menu-change
16200 '("Org") "File List for Agenda"
16201 (append
16202 (list
16203 ["Edit File List" (org-edit-agenda-file-list) t]
16204 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16205 ["Remove Current File from List" org-remove-file t]
16206 ["Cycle through agenda files" org-cycle-agenda-files t]
16207 ["Occur in all agenda files" org-occur-in-agenda-files t]
16208 "--")
16209 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16211 ;;;; Documentation
16213 ;;;###autoload
16214 (defun org-require-autoloaded-modules ()
16215 (interactive)
16216 (mapc 'require
16217 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16218 org-docbook org-exp org-html org-icalendar
16219 org-id org-latex
16220 org-publish org-remember org-table
16221 org-timer org-xoxo)))
16223 ;;;###autoload
16224 (defun org-reload (&optional uncompiled)
16225 "Reload all org lisp files.
16226 With prefix arg UNCOMPILED, load the uncompiled versions."
16227 (interactive "P")
16228 (require 'find-func)
16229 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16230 (dir-org (file-name-directory (org-find-library-name "org")))
16231 (dir-org-contrib (ignore-errors
16232 (file-name-directory
16233 (org-find-library-name "org-contribdir"))))
16234 (files
16235 (append (directory-files dir-org t file-re)
16236 (and dir-org-contrib
16237 (directory-files dir-org-contrib t file-re))))
16238 (remove-re (concat (if (featurep 'xemacs)
16239 "org-colview" "org-colview-xemacs")
16240 "\\'")))
16241 (setq files (mapcar 'file-name-sans-extension files))
16242 (setq files (mapcar
16243 (lambda (x) (if (string-match remove-re x) nil x))
16244 files))
16245 (setq files (delq nil files))
16246 (mapc
16247 (lambda (f)
16248 (when (featurep (intern (file-name-nondirectory f)))
16249 (if (and (not uncompiled)
16250 (file-exists-p (concat f ".elc")))
16251 (load (concat f ".elc") nil nil t)
16252 (load (concat f ".el") nil nil t))))
16253 files))
16254 (org-version))
16256 ;;;###autoload
16257 (defun org-customize ()
16258 "Call the customize function with org as argument."
16259 (interactive)
16260 (org-load-modules-maybe)
16261 (org-require-autoloaded-modules)
16262 (customize-browse 'org))
16264 (defun org-create-customize-menu ()
16265 "Create a full customization menu for Org-mode, insert it into the menu."
16266 (interactive)
16267 (org-load-modules-maybe)
16268 (org-require-autoloaded-modules)
16269 (if (fboundp 'customize-menu-create)
16270 (progn
16271 (easy-menu-change
16272 '("Org") "Customize"
16273 `(["Browse Org group" org-customize t]
16274 "--"
16275 ,(customize-menu-create 'org)
16276 ["Set" Custom-set t]
16277 ["Save" Custom-save t]
16278 ["Reset to Current" Custom-reset-current t]
16279 ["Reset to Saved" Custom-reset-saved t]
16280 ["Reset to Standard Settings" Custom-reset-standard t]))
16281 (message "\"Org\"-menu now contains full customization menu"))
16282 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16284 ;;;; Miscellaneous stuff
16286 ;;; Generally useful functions
16288 (defun org-get-at-bol (property)
16289 "Get text property PROPERTY at beginning of line."
16290 (get-text-property (point-at-bol) property))
16292 (defun org-find-text-property-in-string (prop s)
16293 "Return the first non-nil value of property PROP in string S."
16294 (or (get-text-property 0 prop s)
16295 (get-text-property (or (next-single-property-change 0 prop s) 0)
16296 prop s)))
16298 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16299 "Display the given MESSAGE as a warning."
16300 (if (fboundp 'display-warning)
16301 (display-warning 'org message
16302 (if (featurep 'xemacs)
16303 'warning
16304 :warning))
16305 (let ((buf (get-buffer-create "*Org warnings*")))
16306 (with-current-buffer buf
16307 (goto-char (point-max))
16308 (insert "Warning (Org): " message)
16309 (unless (bolp)
16310 (newline)))
16311 (display-buffer buf)
16312 (sit-for 0))))
16314 (defun org-in-commented-line ()
16315 "Is point in a line starting with `#'?"
16316 (equal (char-after (point-at-bol)) ?#))
16318 (defun org-in-verbatim-emphasis ()
16319 (save-match-data
16320 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16322 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16323 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16324 (if (and marker (marker-buffer marker)
16325 (buffer-live-p (marker-buffer marker)))
16326 (progn
16327 (switch-to-buffer (marker-buffer marker))
16328 (if (or (> marker (point-max)) (< marker (point-min)))
16329 (widen))
16330 (goto-char marker)
16331 (org-show-context 'org-goto))
16332 (if bookmark
16333 (bookmark-jump bookmark)
16334 (error "Cannot find location"))))
16336 (defun org-quote-csv-field (s)
16337 "Quote field for inclusion in CSV material."
16338 (if (string-match "[\",]" s)
16339 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16342 (defun org-plist-delete (plist property)
16343 "Delete PROPERTY from PLIST.
16344 This is in contrast to merely setting it to 0."
16345 (let (p)
16346 (while plist
16347 (if (not (eq property (car plist)))
16348 (setq p (plist-put p (car plist) (nth 1 plist))))
16349 (setq plist (cddr plist)))
16352 (defun org-force-self-insert (N)
16353 "Needed to enforce self-insert under remapping."
16354 (interactive "p")
16355 (self-insert-command N))
16357 (defun org-string-width (s)
16358 "Compute width of string, ignoring invisible characters.
16359 This ignores character with invisibility property `org-link', and also
16360 characters with property `org-cwidth', because these will become invisible
16361 upon the next fontification round."
16362 (let (b l)
16363 (when (or (eq t buffer-invisibility-spec)
16364 (assq 'org-link buffer-invisibility-spec))
16365 (while (setq b (text-property-any 0 (length s)
16366 'invisible 'org-link s))
16367 (setq s (concat (substring s 0 b)
16368 (substring s (or (next-single-property-change
16369 b 'invisible s) (length s)))))))
16370 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16371 (setq s (concat (substring s 0 b)
16372 (substring s (or (next-single-property-change
16373 b 'org-cwidth s) (length s))))))
16374 (setq l (string-width s) b -1)
16375 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16376 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16379 (defun org-get-indentation (&optional line)
16380 "Get the indentation of the current line, interpreting tabs.
16381 When LINE is given, assume it represents a line and compute its indentation."
16382 (if line
16383 (if (string-match "^ *" (org-remove-tabs line))
16384 (match-end 0))
16385 (save-excursion
16386 (beginning-of-line 1)
16387 (skip-chars-forward " \t")
16388 (current-column))))
16390 (defun org-remove-tabs (s &optional width)
16391 "Replace tabulators in S with spaces.
16392 Assumes that s is a single line, starting in column 0."
16393 (setq width (or width tab-width))
16394 (while (string-match "\t" s)
16395 (setq s (replace-match
16396 (make-string
16397 (- (* width (/ (+ (match-beginning 0) width) width))
16398 (match-beginning 0)) ?\ )
16399 t t s)))
16402 (defun org-fix-indentation (line ind)
16403 "Fix indentation in LINE.
16404 IND is a cons cell with target and minimum indentation.
16405 If the current indentation in LINE is smaller than the minimum,
16406 leave it alone. If it is larger than ind, set it to the target."
16407 (let* ((l (org-remove-tabs line))
16408 (i (org-get-indentation l))
16409 (i1 (car ind)) (i2 (cdr ind)))
16410 (if (>= i i2) (setq l (substring line i2)))
16411 (if (> i1 0)
16412 (concat (make-string i1 ?\ ) l)
16413 l)))
16415 (defun org-remove-indentation (code &optional n)
16416 "Remove the maximum common indentation from the lines in CODE.
16417 N may optionally be the number of spaces to remove."
16418 (with-temp-buffer
16419 (insert code)
16420 (org-do-remove-indentation n)
16421 (buffer-string)))
16423 (defun org-do-remove-indentation (&optional n)
16424 "Remove the maximum common indentation from the buffer."
16425 (untabify (point-min) (point-max))
16426 (let ((min 10000) re)
16427 (if n
16428 (setq min n)
16429 (goto-char (point-min))
16430 (while (re-search-forward "^ *[^ \n]" nil t)
16431 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16432 (unless (or (= min 0) (= min 10000))
16433 (setq re (format "^ \\{%d\\}" min))
16434 (goto-char (point-min))
16435 (while (re-search-forward re nil t)
16436 (replace-match "")
16437 (end-of-line 1))
16438 min)))
16440 (defun org-fill-template (template alist)
16441 "Find each %key of ALIST in TEMPLATE and replace it."
16442 (let (entry key value)
16443 (setq alist (sort (copy-sequence alist)
16444 (lambda (a b) (< (length (car a)) (length (car b))))))
16445 (while (setq entry (pop alist))
16446 (setq template
16447 (replace-regexp-in-string
16448 (concat "%" (regexp-quote (car entry)))
16449 (cdr entry) template t t)))
16450 template))
16452 (defun org-base-buffer (buffer)
16453 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16454 (if (not buffer)
16455 buffer
16456 (or (buffer-base-buffer buffer)
16457 buffer)))
16459 (defun org-trim (s)
16460 "Remove whitespace at beginning and end of string."
16461 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
16462 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
16465 (defun org-wrap (string &optional width lines)
16466 "Wrap string to either a number of lines, or a width in characters.
16467 If WIDTH is non-nil, the string is wrapped to that width, however many lines
16468 that costs. If there is a word longer than WIDTH, the text is actually
16469 wrapped to the length of that word.
16470 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
16471 many lines, whatever width that takes.
16472 The return value is a list of lines, without newlines at the end."
16473 (let* ((words (org-split-string string "[ \t\n]+"))
16474 (maxword (apply 'max (mapcar 'org-string-width words)))
16475 w ll)
16476 (cond (width
16477 (org-do-wrap words (max maxword width)))
16478 (lines
16479 (setq w maxword)
16480 (setq ll (org-do-wrap words maxword))
16481 (if (<= (length ll) lines)
16483 (setq ll words)
16484 (while (> (length ll) lines)
16485 (setq w (1+ w))
16486 (setq ll (org-do-wrap words w)))
16487 ll))
16488 (t (error "Cannot wrap this")))))
16490 (defun org-do-wrap (words width)
16491 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
16492 (let (lines line)
16493 (while words
16494 (setq line (pop words))
16495 (while (and words (< (+ (length line) (length (car words))) width))
16496 (setq line (concat line " " (pop words))))
16497 (setq lines (push line lines)))
16498 (nreverse lines)))
16500 (defun org-split-string (string &optional separators)
16501 "Splits STRING into substrings at SEPARATORS.
16502 No empty strings are returned if there are matches at the beginning
16503 and end of string."
16504 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
16505 (start 0)
16506 notfirst
16507 (list nil))
16508 (while (and (string-match rexp string
16509 (if (and notfirst
16510 (= start (match-beginning 0))
16511 (< start (length string)))
16512 (1+ start) start))
16513 (< (match-beginning 0) (length string)))
16514 (setq notfirst t)
16515 (or (eq (match-beginning 0) 0)
16516 (and (eq (match-beginning 0) (match-end 0))
16517 (eq (match-beginning 0) start))
16518 (setq list
16519 (cons (substring string start (match-beginning 0))
16520 list)))
16521 (setq start (match-end 0)))
16522 (or (eq start (length string))
16523 (setq list
16524 (cons (substring string start)
16525 list)))
16526 (nreverse list)))
16528 (defun org-quote-vert (s)
16529 "Replace \"|\" with \"\\vert\"."
16530 (while (string-match "|" s)
16531 (setq s (replace-match "\\vert" t t s)))
16534 (defun org-uuidgen-p (s)
16535 "Is S an ID created by UUIDGEN?"
16536 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16538 (defun org-context ()
16539 "Return a list of contexts of the current cursor position.
16540 If several contexts apply, all are returned.
16541 Each context entry is a list with a symbol naming the context, and
16542 two positions indicating start and end of the context. Possible
16543 contexts are:
16545 :headline anywhere in a headline
16546 :headline-stars on the leading stars in a headline
16547 :todo-keyword on a TODO keyword (including DONE) in a headline
16548 :tags on the TAGS in a headline
16549 :priority on the priority cookie in a headline
16550 :item on the first line of a plain list item
16551 :item-bullet on the bullet/number of a plain list item
16552 :checkbox on the checkbox in a plain list item
16553 :table in an org-mode table
16554 :table-special on a special filed in a table
16555 :table-table in a table.el table
16556 :link on a hyperlink
16557 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16558 :target on a <<target>>
16559 :radio-target on a <<<radio-target>>>
16560 :latex-fragment on a LaTeX fragment
16561 :latex-preview on a LaTeX fragment with overlayed preview image
16563 This function expects the position to be visible because it uses font-lock
16564 faces as a help to recognize the following contexts: :table-special, :link,
16565 and :keyword."
16566 (let* ((f (get-text-property (point) 'face))
16567 (faces (if (listp f) f (list f)))
16568 (p (point)) clist o)
16569 ;; First the large context
16570 (cond
16571 ((org-on-heading-p t)
16572 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16573 (when (progn
16574 (beginning-of-line 1)
16575 (looking-at org-todo-line-tags-regexp))
16576 (push (org-point-in-group p 1 :headline-stars) clist)
16577 (push (org-point-in-group p 2 :todo-keyword) clist)
16578 (push (org-point-in-group p 4 :tags) clist))
16579 (goto-char p)
16580 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
16581 (if (looking-at "\\[#[A-Z0-9]\\]")
16582 (push (org-point-in-group p 0 :priority) clist)))
16584 ((org-at-item-p)
16585 (push (org-point-in-group p 2 :item-bullet) clist)
16586 (push (list :item (point-at-bol)
16587 (save-excursion (org-end-of-item) (point)))
16588 clist)
16589 (and (org-at-item-checkbox-p)
16590 (push (org-point-in-group p 0 :checkbox) clist)))
16592 ((org-at-table-p)
16593 (push (list :table (org-table-begin) (org-table-end)) clist)
16594 (if (memq 'org-formula faces)
16595 (push (list :table-special
16596 (previous-single-property-change p 'face)
16597 (next-single-property-change p 'face)) clist)))
16598 ((org-at-table-p 'any)
16599 (push (list :table-table) clist)))
16600 (goto-char p)
16602 ;; Now the small context
16603 (cond
16604 ((org-at-timestamp-p)
16605 (push (org-point-in-group p 0 :timestamp) clist))
16606 ((memq 'org-link faces)
16607 (push (list :link
16608 (previous-single-property-change p 'face)
16609 (next-single-property-change p 'face)) clist))
16610 ((memq 'org-special-keyword faces)
16611 (push (list :keyword
16612 (previous-single-property-change p 'face)
16613 (next-single-property-change p 'face)) clist))
16614 ((org-on-target-p)
16615 (push (org-point-in-group p 0 :target) clist)
16616 (goto-char (1- (match-beginning 0)))
16617 (if (looking-at org-radio-target-regexp)
16618 (push (org-point-in-group p 0 :radio-target) clist))
16619 (goto-char p))
16620 ((setq o (car (delq nil
16621 (mapcar
16622 (lambda (x)
16623 (if (memq x org-latex-fragment-image-overlays) x))
16624 (org-overlays-at (point))))))
16625 (push (list :latex-fragment
16626 (org-overlay-start o) (org-overlay-end o)) clist)
16627 (push (list :latex-preview
16628 (org-overlay-start o) (org-overlay-end o)) clist))
16629 ((org-inside-LaTeX-fragment-p)
16630 ;; FIXME: positions wrong.
16631 (push (list :latex-fragment (point) (point)) clist)))
16633 (setq clist (nreverse (delq nil clist)))
16634 clist))
16636 ;; FIXME: Compare with at-regexp-p Do we need both?
16637 (defun org-in-regexp (re &optional nlines visually)
16638 "Check if point is inside a match of regexp.
16639 Normally only the current line is checked, but you can include NLINES extra
16640 lines both before and after point into the search.
16641 If VISUALLY is set, require that the cursor is not after the match but
16642 really on, so that the block visually is on the match."
16643 (catch 'exit
16644 (let ((pos (point))
16645 (eol (point-at-eol (+ 1 (or nlines 0))))
16646 (inc (if visually 1 0)))
16647 (save-excursion
16648 (beginning-of-line (- 1 (or nlines 0)))
16649 (while (re-search-forward re eol t)
16650 (if (and (<= (match-beginning 0) pos)
16651 (>= (+ inc (match-end 0)) pos))
16652 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16654 (defun org-at-regexp-p (regexp)
16655 "Is point inside a match of REGEXP in the current line?"
16656 (catch 'exit
16657 (save-excursion
16658 (let ((pos (point)) (end (point-at-eol)))
16659 (beginning-of-line 1)
16660 (while (re-search-forward regexp end t)
16661 (if (and (<= (match-beginning 0) pos)
16662 (>= (match-end 0) pos))
16663 (throw 'exit t)))
16664 nil))))
16666 (defun org-occur-in-agenda-files (regexp &optional nlines)
16667 "Call `multi-occur' with buffers for all agenda files."
16668 (interactive "sOrg-files matching: \np")
16669 (let* ((files (org-agenda-files))
16670 (tnames (mapcar 'file-truename files))
16671 (extra org-agenda-text-search-extra-files)
16673 (when (eq (car extra) 'agenda-archives)
16674 (setq extra (cdr extra))
16675 (setq files (org-add-archive-files files)))
16676 (while (setq f (pop extra))
16677 (unless (member (file-truename f) tnames)
16678 (add-to-list 'files f 'append)
16679 (add-to-list 'tnames (file-truename f) 'append)))
16680 (multi-occur
16681 (mapcar (lambda (x)
16682 (with-current-buffer
16683 (or (get-file-buffer x) (find-file-noselect x))
16684 (widen)
16685 (current-buffer)))
16686 files)
16687 regexp)))
16689 (if (boundp 'occur-mode-find-occurrence-hook)
16690 ;; Emacs 23
16691 (add-hook 'occur-mode-find-occurrence-hook
16692 (lambda ()
16693 (when (org-mode-p)
16694 (org-reveal))))
16695 ;; Emacs 22
16696 (defadvice occur-mode-goto-occurrence
16697 (after org-occur-reveal activate)
16698 (and (org-mode-p) (org-reveal)))
16699 (defadvice occur-mode-goto-occurrence-other-window
16700 (after org-occur-reveal activate)
16701 (and (org-mode-p) (org-reveal)))
16702 (defadvice occur-mode-display-occurrence
16703 (after org-occur-reveal activate)
16704 (when (org-mode-p)
16705 (let ((pos (occur-mode-find-occurrence)))
16706 (with-current-buffer (marker-buffer pos)
16707 (save-excursion
16708 (goto-char pos)
16709 (org-reveal)))))))
16711 (defun org-occur-link-in-agenda-files ()
16712 "Create a link and search for it in the agendas.
16713 The link is not stored in `org-stored-links', it is just created
16714 for the search purpose."
16715 (interactive)
16716 (let ((link (condition-case nil
16717 (org-store-link nil)
16718 (error "Unable to create a link to here"))))
16719 (org-occur-in-agenda-files (regexp-quote link))))
16721 (defun org-uniquify (list)
16722 "Remove duplicate elements from LIST."
16723 (let (res)
16724 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16725 res))
16727 (defun org-delete-all (elts list)
16728 "Remove all elements in ELTS from LIST."
16729 (while elts
16730 (setq list (delete (pop elts) list)))
16731 list)
16733 (defun org-back-over-empty-lines ()
16734 "Move backwards over whitespace, to the beginning of the first empty line.
16735 Returns the number of empty lines passed."
16736 (let ((pos (point)))
16737 (skip-chars-backward " \t\n\r")
16738 (beginning-of-line 2)
16739 (goto-char (min (point) pos))
16740 (count-lines (point) pos)))
16742 (defun org-skip-whitespace ()
16743 (skip-chars-forward " \t\n\r"))
16745 (defun org-point-in-group (point group &optional context)
16746 "Check if POINT is in match-group GROUP.
16747 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16748 match. If the match group does ot exist or point is not inside it,
16749 return nil."
16750 (and (match-beginning group)
16751 (>= point (match-beginning group))
16752 (<= point (match-end group))
16753 (if context
16754 (list context (match-beginning group) (match-end group))
16755 t)))
16757 (defun org-switch-to-buffer-other-window (&rest args)
16758 "Switch to buffer in a second window on the current frame.
16759 In particular, do not allow pop-up frames."
16760 (let (pop-up-frames special-display-buffer-names special-display-regexps
16761 special-display-function)
16762 (apply 'switch-to-buffer-other-window args)))
16764 (defun org-combine-plists (&rest plists)
16765 "Create a single property list from all plists in PLISTS.
16766 The process starts by copying the first list, and then setting properties
16767 from the other lists. Settings in the last list are the most significant
16768 ones and overrule settings in the other lists."
16769 (let ((rtn (copy-sequence (pop plists)))
16770 p v ls)
16771 (while plists
16772 (setq ls (pop plists))
16773 (while ls
16774 (setq p (pop ls) v (pop ls))
16775 (setq rtn (plist-put rtn p v))))
16776 rtn))
16778 (defun org-move-line-down (arg)
16779 "Move the current line down. With prefix argument, move it past ARG lines."
16780 (interactive "p")
16781 (let ((col (current-column))
16782 beg end pos)
16783 (beginning-of-line 1) (setq beg (point))
16784 (beginning-of-line 2) (setq end (point))
16785 (beginning-of-line (+ 1 arg))
16786 (setq pos (move-marker (make-marker) (point)))
16787 (insert (delete-and-extract-region beg end))
16788 (goto-char pos)
16789 (org-move-to-column col)))
16791 (defun org-move-line-up (arg)
16792 "Move the current line up. With prefix argument, move it past ARG lines."
16793 (interactive "p")
16794 (let ((col (current-column))
16795 beg end pos)
16796 (beginning-of-line 1) (setq beg (point))
16797 (beginning-of-line 2) (setq end (point))
16798 (beginning-of-line (- arg))
16799 (setq pos (move-marker (make-marker) (point)))
16800 (insert (delete-and-extract-region beg end))
16801 (goto-char pos)
16802 (org-move-to-column col)))
16804 (defun org-replace-escapes (string table)
16805 "Replace %-escapes in STRING with values in TABLE.
16806 TABLE is an association list with keys like \"%a\" and string values.
16807 The sequences in STRING may contain normal field width and padding information,
16808 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
16809 so values can contain further %-escapes if they are define later in TABLE."
16810 (let ((case-fold-search nil)
16811 e re rpl)
16812 (while (setq e (pop table))
16813 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
16814 (while (string-match re string)
16815 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
16816 (cdr e)))
16817 (setq string (replace-match rpl t t string))))
16818 string))
16821 (defun org-sublist (list start end)
16822 "Return a section of LIST, from START to END.
16823 Counting starts at 1."
16824 (let (rtn (c start))
16825 (setq list (nthcdr (1- start) list))
16826 (while (and list (<= c end))
16827 (push (pop list) rtn)
16828 (setq c (1+ c)))
16829 (nreverse rtn)))
16831 (defun org-find-base-buffer-visiting (file)
16832 "Like `find-buffer-visiting' but always return the base buffer and
16833 not an indirect buffer."
16834 (let ((buf (or (get-file-buffer file)
16835 (find-buffer-visiting file))))
16836 (if buf
16837 (or (buffer-base-buffer buf) buf)
16838 nil)))
16840 (defun org-image-file-name-regexp (&optional extensions)
16841 "Return regexp matching the file names of images.
16842 If EXTENSIONS is given, only match these."
16843 (if (and (not extensions) (fboundp 'image-file-name-regexp))
16844 (image-file-name-regexp)
16845 (let ((image-file-name-extensions
16846 (or extensions
16847 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16848 "xbm" "xpm" "pbm" "pgm" "ppm"))))
16849 (concat "\\."
16850 (regexp-opt (nconc (mapcar 'upcase
16851 image-file-name-extensions)
16852 image-file-name-extensions)
16854 "\\'"))))
16856 (defun org-file-image-p (file &optional extensions)
16857 "Return non-nil if FILE is an image."
16858 (save-match-data
16859 (string-match (org-image-file-name-regexp extensions) file)))
16861 (defun org-get-cursor-date ()
16862 "Return the date at cursor in as a time.
16863 This works in the calendar and in the agenda, anywhere else it just
16864 returns the current time."
16865 (let (date day defd)
16866 (cond
16867 ((eq major-mode 'calendar-mode)
16868 (setq date (calendar-cursor-to-date)
16869 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16870 ((eq major-mode 'org-agenda-mode)
16871 (setq day (get-text-property (point) 'day))
16872 (if day
16873 (setq date (calendar-gregorian-from-absolute day)
16874 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
16875 (nth 2 date))))))
16876 (or defd (current-time))))
16878 (defvar org-agenda-action-marker (make-marker)
16879 "Marker pointing to the entry for the next agenda action.")
16881 (defun org-mark-entry-for-agenda-action ()
16882 "Mark the current entry as target of an agenda action.
16883 Agenda actions are actions executed from the agenda with the key `k',
16884 which make use of the date at the cursor."
16885 (interactive)
16886 (move-marker org-agenda-action-marker
16887 (save-excursion (org-back-to-heading t) (point))
16888 (current-buffer))
16889 (message
16890 "Entry marked for action; press `k' at desired date in agenda or calendar"))
16892 ;;; Paragraph filling stuff.
16893 ;; We want this to be just right, so use the full arsenal.
16895 (defun org-indent-line-function ()
16896 "Indent line like previous, but further if previous was headline or item."
16897 (interactive)
16898 (let* ((pos (point))
16899 (itemp (org-at-item-p))
16900 (case-fold-search t)
16901 (org-drawer-regexp (or org-drawer-regexp "\000"))
16902 column bpos bcol tpos tcol bullet btype bullet-type)
16903 ;; Find the previous relevant line
16904 (beginning-of-line 1)
16905 (cond
16906 ((looking-at "#") (setq column 0))
16907 ((looking-at "\\*+ ") (setq column 0))
16908 ((and (looking-at "[ \t]*:END:")
16909 (save-excursion (re-search-backward org-drawer-regexp nil t)))
16910 (save-excursion
16911 (goto-char (1- (match-beginning 1)))
16912 (setq column (current-column))))
16913 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
16914 (save-excursion
16915 (re-search-backward
16916 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
16917 (setq column (org-get-indentation (match-string 0))))
16919 (beginning-of-line 0)
16920 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
16921 (not (looking-at "[ \t]*:END:"))
16922 (not (looking-at org-drawer-regexp)))
16923 (beginning-of-line 0))
16924 (cond
16925 ((looking-at "\\*+[ \t]+")
16926 (if (not org-adapt-indentation)
16927 (setq column 0)
16928 (goto-char (match-end 0))
16929 (setq column (current-column))))
16930 ((looking-at org-drawer-regexp)
16931 (goto-char (1- (match-beginning 1)))
16932 (setq column (current-column)))
16933 ((looking-at "\\([ \t]*\\):END:")
16934 (goto-char (match-end 1))
16935 (setq column (current-column)))
16936 ((org-in-item-p)
16937 (org-beginning-of-item)
16938 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
16939 (setq bpos (match-beginning 1) tpos (match-end 0)
16940 bcol (progn (goto-char bpos) (current-column))
16941 tcol (progn (goto-char tpos) (current-column))
16942 bullet (match-string 1)
16943 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
16944 (if (> tcol (+ bcol org-description-max-indent))
16945 (setq tcol (+ bcol 5)))
16946 (if (not itemp)
16947 (setq column tcol)
16948 (goto-char pos)
16949 (beginning-of-line 1)
16950 (if (looking-at "\\S-")
16951 (progn
16952 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
16953 (setq bullet (match-string 1)
16954 btype (if (string-match "[0-9]" bullet) "n" bullet))
16955 (setq column (if (equal btype bullet-type) bcol tcol)))
16956 (setq column (org-get-indentation)))))
16957 (t (setq column (org-get-indentation))))))
16958 (goto-char pos)
16959 (if (<= (current-column) (current-indentation))
16960 (org-indent-line-to column)
16961 (save-excursion (org-indent-line-to column)))
16962 (setq column (current-column))
16963 (beginning-of-line 1)
16964 (if (looking-at
16965 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16966 (replace-match (concat (match-string 1)
16967 (format org-property-format
16968 (match-string 2) (match-string 3)))
16969 t t))
16970 (org-move-to-column column)))
16972 (defun org-set-autofill-regexps ()
16973 (interactive)
16974 ;; In the paragraph separator we include headlines, because filling
16975 ;; text in a line directly attached to a headline would otherwise
16976 ;; fill the headline as well.
16977 (org-set-local 'comment-start-skip "^#+[ \t]*")
16978 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
16979 ;; The paragraph starter includes hand-formatted lists.
16980 (org-set-local
16981 'paragraph-start
16982 (concat
16983 "\f" "\\|"
16984 "[ ]*$" "\\|"
16985 "\\*+ " "\\|"
16986 "[ \t]*#" "\\|"
16987 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16988 "[ \t]*[:|]" "\\|"
16989 "\\$\\$" "\\|"
16990 "\\\\\\(begin\\|end\\|[][]\\)"))
16991 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16992 ;; But only if the user has not turned off tables or fixed-width regions
16993 (org-set-local
16994 'auto-fill-inhibit-regexp
16995 (concat "\\*+ \\|#\\+"
16996 "\\|[ \t]*" org-keyword-time-regexp
16997 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16998 (concat
16999 "\\|[ \t]*["
17000 (if org-enable-table-editor "|" "")
17001 (if org-enable-fixed-width-editor ":" "")
17002 "]"))))
17003 ;; We use our own fill-paragraph function, to make sure that tables
17004 ;; and fixed-width regions are not wrapped. That function will pass
17005 ;; through to `fill-paragraph' when appropriate.
17006 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17007 ; Adaptive filling: To get full control, first make sure that
17008 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17009 (org-set-local 'adaptive-fill-regexp "\000")
17010 (org-set-local 'adaptive-fill-function
17011 'org-adaptive-fill-function)
17012 (org-set-local
17013 'align-mode-rules-list
17014 '((org-in-buffer-settings
17015 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
17016 (modes . '(org-mode))))))
17018 (defun org-fill-paragraph (&optional justify)
17019 "Re-align a table, pass through to fill-paragraph if no table."
17020 (let ((table-p (org-at-table-p))
17021 (table.el-p (org-at-table.el-p)))
17022 (cond ((and (equal (char-after (point-at-bol)) ?*)
17023 (save-excursion (goto-char (point-at-bol))
17024 (looking-at outline-regexp)))
17025 t) ; skip headlines
17026 (table.el-p t) ; skip table.el tables
17027 (table-p (org-table-align) t) ; align org-mode tables
17028 (t nil)))) ; call paragraph-fill
17030 ;; For reference, this is the default value of adaptive-fill-regexp
17031 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17033 (defun org-adaptive-fill-function ()
17034 "Return a fill prefix for org-mode files.
17035 In particular, this makes sure hanging paragraphs for hand-formatted lists
17036 work correctly."
17037 (cond ((looking-at "#[ \t]+")
17038 (match-string 0))
17039 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17040 (save-excursion
17041 (if (> (match-end 1) (+ (match-beginning 1)
17042 org-description-max-indent))
17043 (goto-char (+ (match-beginning 1) 5))
17044 (goto-char (match-end 0)))
17045 (make-string (current-column) ?\ )))
17046 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
17047 (save-excursion
17048 (goto-char (match-end 0))
17049 (make-string (current-column) ?\ )))
17050 (t nil)))
17052 ;;; Other stuff.
17054 (defun org-toggle-fixed-width-section (arg)
17055 "Toggle the fixed-width export.
17056 If there is no active region, the QUOTE keyword at the current headline is
17057 inserted or removed. When present, it causes the text between this headline
17058 and the next to be exported as fixed-width text, and unmodified.
17059 If there is an active region, this command adds or removes a colon as the
17060 first character of this line. If the first character of a line is a colon,
17061 this line is also exported in fixed-width font."
17062 (interactive "P")
17063 (let* ((cc 0)
17064 (regionp (org-region-active-p))
17065 (beg (if regionp (region-beginning) (point)))
17066 (end (if regionp (region-end)))
17067 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17068 (case-fold-search nil)
17069 (re "[ \t]*\\(: \\)")
17070 off)
17071 (if regionp
17072 (save-excursion
17073 (goto-char beg)
17074 (setq cc (current-column))
17075 (beginning-of-line 1)
17076 (setq off (looking-at re))
17077 (while (> nlines 0)
17078 (setq nlines (1- nlines))
17079 (beginning-of-line 1)
17080 (cond
17081 (arg
17082 (org-move-to-column cc t)
17083 (insert ": \n")
17084 (forward-line -1))
17085 ((and off (looking-at re))
17086 (replace-match "" t t nil 1))
17087 ((not off) (org-move-to-column cc t) (insert ": ")))
17088 (forward-line 1)))
17089 (save-excursion
17090 (org-back-to-heading)
17091 (if (looking-at (concat outline-regexp
17092 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17093 (replace-match "" t t nil 1)
17094 (if (looking-at outline-regexp)
17095 (progn
17096 (goto-char (match-end 0))
17097 (insert org-quote-string " "))))))))
17099 (defun org-reftex-citation ()
17100 "Use reftex-citation to insert a citation into the buffer.
17101 This looks for a line like
17103 #+BIBLIOGRAPHY: foo plain option:-d
17105 and derives from it that foo.bib is the bibliography file relevant
17106 for this document. It then installs the necessary environment for RefTeX
17107 to work in this buffer and calls `reftex-citation' to insert a citation
17108 into the buffer.
17110 Export of such citations to both LaTeX and HTML is handled by the contributed
17111 package org-exp-bibtex by Taru Karttunen."
17112 (interactive)
17113 (let ((reftex-docstruct-symbol 'rds)
17114 (reftex-cite-format "\\cite{%l}")
17115 rds bib)
17116 (save-excursion
17117 (save-restriction
17118 (widen)
17119 (let ((case-fold-search t)
17120 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17121 (if (not (save-excursion
17122 (or (re-search-forward re nil t)
17123 (re-search-backward re nil t))))
17124 (error "No bibliography defined in file")
17125 (setq bib (concat (match-string 1) ".bib")
17126 rds (list (list 'bib bib)))))))
17127 (call-interactively 'reftex-citation)))
17129 ;;;; Functions extending outline functionality
17131 (defun org-beginning-of-line (&optional arg)
17132 "Go to the beginning of the current line. If that is invisible, continue
17133 to a visible line beginning. This makes the function of C-a more intuitive.
17134 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17135 first attempt, and only move to after the tags when the cursor is already
17136 beyond the end of the headline."
17137 (interactive "P")
17138 (let ((pos (point))
17139 (special (if (consp org-special-ctrl-a/e)
17140 (car org-special-ctrl-a/e)
17141 org-special-ctrl-a/e))
17142 refpos)
17143 (if (org-bound-and-true-p line-move-visual)
17144 (beginning-of-visual-line 1)
17145 (beginning-of-line 1))
17146 (if (and arg (fboundp 'move-beginning-of-line))
17147 (call-interactively 'move-beginning-of-line)
17148 (if (bobp)
17150 (backward-char 1)
17151 (if (org-invisible-p)
17152 (while (and (not (bobp)) (org-invisible-p))
17153 (backward-char 1)
17154 (beginning-of-line 1))
17155 (forward-char 1))))
17156 (when special
17157 (cond
17158 ((and (looking-at org-complex-heading-regexp)
17159 (= (char-after (match-end 1)) ?\ ))
17160 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17161 (point-at-eol)))
17162 (goto-char
17163 (if (eq special t)
17164 (cond ((> pos refpos) refpos)
17165 ((= pos (point)) refpos)
17166 (t (point)))
17167 (cond ((> pos (point)) (point))
17168 ((not (eq last-command this-command)) (point))
17169 (t refpos)))))
17170 ((org-at-item-p)
17171 (goto-char
17172 (if (eq special t)
17173 (cond ((> pos (match-end 4)) (match-end 4))
17174 ((= pos (point)) (match-end 4))
17175 (t (point)))
17176 (cond ((> pos (point)) (point))
17177 ((not (eq last-command this-command)) (point))
17178 (t (match-end 4))))))))
17179 (org-no-warnings
17180 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17182 (defun org-end-of-line (&optional arg)
17183 "Go to the end of the line.
17184 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17185 first attempt, and only move to after the tags when the cursor is already
17186 beyond the end of the headline."
17187 (interactive "P")
17188 (let ((special (if (consp org-special-ctrl-a/e)
17189 (cdr org-special-ctrl-a/e)
17190 org-special-ctrl-a/e)))
17191 (if (or (not special)
17192 (not (org-on-heading-p))
17193 arg)
17194 (call-interactively
17195 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17196 ((fboundp 'move-end-of-line) 'move-end-of-line)
17197 (t 'end-of-line)))
17198 (let ((pos (point)))
17199 (beginning-of-line 1)
17200 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17201 (if (eq special t)
17202 (if (or (< pos (match-beginning 1))
17203 (= pos (match-end 0)))
17204 (goto-char (match-beginning 1))
17205 (goto-char (match-end 0)))
17206 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17207 (goto-char (match-end 0))
17208 (goto-char (match-beginning 1))))
17209 (call-interactively (if (fboundp 'move-end-of-line)
17210 'move-end-of-line
17211 'end-of-line)))))
17212 (org-no-warnings
17213 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17215 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17216 (define-key org-mode-map "\C-e" 'org-end-of-line)
17217 (define-key org-mode-map [home] 'org-beginning-of-line)
17218 (define-key org-mode-map [end] 'org-end-of-line)
17220 (defun org-backward-sentence (&optional arg)
17221 "Go to beginning of sentence, or beginning of table field.
17222 This will call `backward-sentence' or `org-table-beginning-of-field',
17223 depending on context."
17224 (interactive "P")
17225 (cond
17226 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17227 (t (call-interactively 'backward-sentence))))
17229 (defun org-forward-sentence (&optional arg)
17230 "Go to end of sentence, or end of table field.
17231 This will call `forward-sentence' or `org-table-end-of-field',
17232 depending on context."
17233 (interactive "P")
17234 (cond
17235 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17236 (t (call-interactively 'forward-sentence))))
17238 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17239 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17241 (defun org-kill-line (&optional arg)
17242 "Kill line, to tags or end of line."
17243 (interactive "P")
17244 (cond
17245 ((or (not org-special-ctrl-k)
17246 (bolp)
17247 (not (org-on-heading-p)))
17248 (call-interactively 'kill-line))
17249 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17250 (kill-region (point) (match-beginning 1))
17251 (org-set-tags nil t))
17252 (t (kill-region (point) (point-at-eol)))))
17254 (define-key org-mode-map "\C-k" 'org-kill-line)
17256 (defun org-yank (&optional arg)
17257 "Yank. If the kill is a subtree, treat it specially.
17258 This command will look at the current kill and check if is a single
17259 subtree, or a series of subtrees[1]. If it passes the test, and if the
17260 cursor is at the beginning of a line or after the stars of a currently
17261 empty headline, then the yank is handled specially. How exactly depends
17262 on the value of the following variables, both set by default.
17264 org-yank-folded-subtrees
17265 When set, the subtree(s) will be folded after insertion, but only
17266 if doing so would now swallow text after the yanked text.
17268 org-yank-adjusted-subtrees
17269 When set, the subtree will be promoted or demoted in order to
17270 fit into the local outline tree structure, which means that the level
17271 will be adjusted so that it becomes the smaller one of the two
17272 *visible* surrounding headings.
17274 Any prefix to this command will cause `yank' to be called directly with
17275 no special treatment. In particular, a simple `C-u' prefix will just
17276 plainly yank the text as it is.
17278 \[1] The test checks if the first non-white line is a heading
17279 and if there are no other headings with fewer stars."
17280 (interactive "P")
17281 (org-yank-generic 'yank arg))
17283 (defun org-yank-generic (command arg)
17284 "Perform some yank-like command.
17286 This function implements the behavior described in the `org-yank'
17287 documentation. However, it has been generalized to work for any
17288 interactive command with similar behavior."
17290 ;; pretend to be command COMMAND
17291 (setq this-command command)
17293 (if arg
17294 (call-interactively command)
17296 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17297 (and (org-kill-is-subtree-p)
17298 (or (bolp)
17299 (and (looking-at "[ \t]*$")
17300 (string-match
17301 "\\`\\*+\\'"
17302 (buffer-substring (point-at-bol) (point)))))))
17303 swallowp)
17304 (cond
17305 ((and subtreep org-yank-folded-subtrees)
17306 (let ((beg (point))
17307 end)
17308 (if (and subtreep org-yank-adjusted-subtrees)
17309 (org-paste-subtree nil nil 'for-yank)
17310 (call-interactively command))
17312 (setq end (point))
17313 (goto-char beg)
17314 (when (and (bolp) subtreep
17315 (not (setq swallowp
17316 (org-yank-folding-would-swallow-text beg end))))
17317 (or (looking-at outline-regexp)
17318 (re-search-forward (concat "^" outline-regexp) end t))
17319 (while (and (< (point) end) (looking-at outline-regexp))
17320 (hide-subtree)
17321 (org-cycle-show-empty-lines 'folded)
17322 (condition-case nil
17323 (outline-forward-same-level 1)
17324 (error (goto-char end)))))
17325 (when swallowp
17326 (message
17327 "Inserted text not folded because that would swallow text"))
17329 (goto-char end)
17330 (skip-chars-forward " \t\n\r")
17331 (beginning-of-line 1)
17332 (push-mark beg 'nomsg)))
17333 ((and subtreep org-yank-adjusted-subtrees)
17334 (let ((beg (point-at-bol)))
17335 (org-paste-subtree nil nil 'for-yank)
17336 (push-mark beg 'nomsg)))
17338 (call-interactively command))))))
17340 (defun org-yank-folding-would-swallow-text (beg end)
17341 "Would hide-subtree at BEG swallow any text after END?"
17342 (let (level)
17343 (save-excursion
17344 (goto-char beg)
17345 (when (or (looking-at outline-regexp)
17346 (re-search-forward (concat "^" outline-regexp) end t))
17347 (setq level (org-outline-level)))
17348 (goto-char end)
17349 (skip-chars-forward " \t\r\n\v\f")
17350 (if (or (eobp)
17351 (and (bolp) (looking-at org-outline-regexp)
17352 (<= (org-outline-level) level)))
17353 nil ; Nothing would be swallowed
17354 t)))) ; something would swallow
17356 (define-key org-mode-map "\C-y" 'org-yank)
17358 (defun org-invisible-p ()
17359 "Check if point is at a character currently not visible."
17360 ;; Early versions of noutline don't have `outline-invisible-p'.
17361 (if (fboundp 'outline-invisible-p)
17362 (outline-invisible-p)
17363 (get-char-property (point) 'invisible)))
17365 (defun org-invisible-p2 ()
17366 "Check if point is at a character currently not visible."
17367 (save-excursion
17368 (if (and (eolp) (not (bobp))) (backward-char 1))
17369 ;; Early versions of noutline don't have `outline-invisible-p'.
17370 (if (fboundp 'outline-invisible-p)
17371 (outline-invisible-p)
17372 (get-char-property (point) 'invisible))))
17374 (defun org-back-to-heading (&optional invisible-ok)
17375 "Call `outline-back-to-heading', but provide a better error message."
17376 (condition-case nil
17377 (outline-back-to-heading invisible-ok)
17378 (error (error "Before first headline at position %d in buffer %s"
17379 (point) (current-buffer)))))
17381 (defun org-before-first-heading-p ()
17382 "Before first heading?"
17383 (save-excursion
17384 (null (re-search-backward "^\\*+ " nil t))))
17386 (defun org-on-heading-p (&optional ignored)
17387 (outline-on-heading-p t))
17388 (defun org-at-heading-p (&optional ignored)
17389 (outline-on-heading-p t))
17391 (defun org-at-heading-or-item-p ()
17392 (or (org-on-heading-p) (org-at-item-p)))
17394 (defun org-on-target-p ()
17395 (or (org-in-regexp org-radio-target-regexp)
17396 (org-in-regexp org-target-regexp)))
17398 (defun org-up-heading-all (arg)
17399 "Move to the heading line of which the present line is a subheading.
17400 This function considers both visible and invisible heading lines.
17401 With argument, move up ARG levels."
17402 (if (fboundp 'outline-up-heading-all)
17403 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17404 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17406 (defun org-up-heading-safe ()
17407 "Move to the heading line of which the present line is a subheading.
17408 This version will not throw an error. It will return the level of the
17409 headline found, or nil if no higher level is found.
17411 Also, this function will be a lot faster than `outline-up-heading',
17412 because it relies on stars being the outline starters. This can really
17413 make a significant difference in outlines with very many siblings."
17414 (let (start-level re)
17415 (org-back-to-heading t)
17416 (setq start-level (funcall outline-level))
17417 (if (equal start-level 1)
17419 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17420 (if (re-search-backward re nil t)
17421 (funcall outline-level)))))
17423 (defun org-first-sibling-p ()
17424 "Is this heading the first child of its parents?"
17425 (interactive)
17426 (let ((re (concat "^" outline-regexp))
17427 level l)
17428 (unless (org-at-heading-p t)
17429 (error "Not at a heading"))
17430 (setq level (funcall outline-level))
17431 (save-excursion
17432 (if (not (re-search-backward re nil t))
17434 (setq l (funcall outline-level))
17435 (< l level)))))
17437 (defun org-goto-sibling (&optional previous)
17438 "Goto the next sibling, even if it is invisible.
17439 When PREVIOUS is set, go to the previous sibling instead. Returns t
17440 when a sibling was found. When none is found, return nil and don't
17441 move point."
17442 (let ((fun (if previous 're-search-backward 're-search-forward))
17443 (pos (point))
17444 (re (concat "^" outline-regexp))
17445 level l)
17446 (when (condition-case nil (org-back-to-heading t) (error nil))
17447 (setq level (funcall outline-level))
17448 (catch 'exit
17449 (or previous (forward-char 1))
17450 (while (funcall fun re nil t)
17451 (setq l (funcall outline-level))
17452 (when (< l level) (goto-char pos) (throw 'exit nil))
17453 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17454 (goto-char pos)
17455 nil))))
17457 (defun org-show-siblings ()
17458 "Show all siblings of the current headline."
17459 (save-excursion
17460 (while (org-goto-sibling) (org-flag-heading nil)))
17461 (save-excursion
17462 (while (org-goto-sibling 'previous)
17463 (org-flag-heading nil))))
17465 (defun org-show-hidden-entry ()
17466 "Show an entry where even the heading is hidden."
17467 (save-excursion
17468 (org-show-entry)))
17470 (defun org-flag-heading (flag &optional entry)
17471 "Flag the current heading. FLAG non-nil means make invisible.
17472 When ENTRY is non-nil, show the entire entry."
17473 (save-excursion
17474 (org-back-to-heading t)
17475 ;; Check if we should show the entire entry
17476 (if entry
17477 (progn
17478 (org-show-entry)
17479 (save-excursion
17480 (and (outline-next-heading)
17481 (org-flag-heading nil))))
17482 (outline-flag-region (max (point-min) (1- (point)))
17483 (save-excursion (outline-end-of-heading) (point))
17484 flag))))
17486 (defun org-get-next-sibling ()
17487 "Move to next heading of the same level, and return point.
17488 If there is no such heading, return nil.
17489 This is like outline-next-sibling, but invisible headings are ok."
17490 (let ((level (funcall outline-level)))
17491 (outline-next-heading)
17492 (while (and (not (eobp)) (> (funcall outline-level) level))
17493 (outline-next-heading))
17494 (if (or (eobp) (< (funcall outline-level) level))
17496 (point))))
17498 (defun org-get-last-sibling ()
17499 "Move to previous heading of the same level, and return point.
17500 If there is no such heading, return nil."
17501 (let ((opoint (point))
17502 (level (funcall outline-level)))
17503 (outline-previous-heading)
17504 (when (and (/= (point) opoint) (outline-on-heading-p t))
17505 (while (and (> (funcall outline-level) level)
17506 (not (bobp)))
17507 (outline-previous-heading))
17508 (if (< (funcall outline-level) level)
17510 (point)))))
17512 (defun org-end-of-subtree (&optional invisible-OK to-heading)
17513 ;; This contains an exact copy of the original function, but it uses
17514 ;; `org-back-to-heading', to make it work also in invisible
17515 ;; trees. And is uses an invisible-OK argument.
17516 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
17517 ;; Furthermore, when used inside Org, finding the end of a large subtree
17518 ;; with many children and grandchildren etc, this can be much faster
17519 ;; than the outline version.
17520 (org-back-to-heading invisible-OK)
17521 (let ((first t)
17522 (level (funcall outline-level)))
17523 (if (and (org-mode-p) (< level 1000))
17524 ;; A true heading (not a plain list item), in Org-mode
17525 ;; This means we can easily find the end by looking
17526 ;; only for the right number of stars. Using a regexp to do
17527 ;; this is so much faster than using a Lisp loop.
17528 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
17529 (forward-char 1)
17530 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
17531 ;; something else, do it the slow way
17532 (while (and (not (eobp))
17533 (or first (> (funcall outline-level) level)))
17534 (setq first nil)
17535 (outline-next-heading)))
17536 (unless to-heading
17537 (if (memq (preceding-char) '(?\n ?\^M))
17538 (progn
17539 ;; Go to end of line before heading
17540 (forward-char -1)
17541 (if (memq (preceding-char) '(?\n ?\^M))
17542 ;; leave blank line before heading
17543 (forward-char -1))))))
17544 (point))
17546 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
17547 "Use Org version in org-mode, for dramatic speed-up."
17548 (if (eq major-mode 'org-mode)
17549 (progn
17550 (org-end-of-subtree nil t)
17551 (unless (eobp) (backward-char 1)))
17552 ad-do-it))
17554 (defun org-forward-same-level (arg &optional invisible-ok)
17555 "Move forward to the arg'th subheading at same level as this one.
17556 Stop at the first and last subheadings of a superior heading."
17557 (interactive "p")
17558 (org-back-to-heading invisible-ok)
17559 (org-on-heading-p)
17560 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17561 (re (format "^\\*\\{1,%d\\} " level))
17563 (forward-char 1)
17564 (while (> arg 0)
17565 (while (and (re-search-forward re nil 'move)
17566 (setq l (- (match-end 0) (match-beginning 0) 1))
17567 (= l level)
17568 (not invisible-ok)
17569 (org-invisible-p))
17570 (if (< l level) (setq arg 1)))
17571 (setq arg (1- arg)))
17572 (beginning-of-line 1)))
17574 (defun org-backward-same-level (arg &optional invisible-ok)
17575 "Move backward to the arg'th subheading at same level as this one.
17576 Stop at the first and last subheadings of a superior heading."
17577 (interactive "p")
17578 (org-back-to-heading)
17579 (org-on-heading-p)
17580 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17581 (re (format "^\\*\\{1,%d\\} " level))
17583 (while (> arg 0)
17584 (while (and (re-search-backward re nil 'move)
17585 (setq l (- (match-end 0) (match-beginning 0) 1))
17586 (= l level)
17587 (not invisible-ok)
17588 (org-invisible-p))
17589 (if (< l level) (setq arg 1)))
17590 (setq arg (1- arg)))))
17592 (defun org-show-subtree ()
17593 "Show everything after this heading at deeper levels."
17594 (outline-flag-region
17595 (point)
17596 (save-excursion
17597 (org-end-of-subtree t t))
17598 nil))
17600 (defun org-show-entry ()
17601 "Show the body directly following this heading.
17602 Show the heading too, if it is currently invisible."
17603 (interactive)
17604 (save-excursion
17605 (condition-case nil
17606 (progn
17607 (org-back-to-heading t)
17608 (outline-flag-region
17609 (max (point-min) (1- (point)))
17610 (save-excursion
17611 (if (re-search-forward
17612 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17613 (match-beginning 1)
17614 (point-max)))
17615 nil)
17616 (org-cycle-hide-drawers 'children))
17617 (error nil))))
17619 (defun org-make-options-regexp (kwds &optional extra)
17620 "Make a regular expression for keyword lines."
17621 (concat
17623 "#?[ \t]*\\+\\("
17624 (mapconcat 'regexp-quote kwds "\\|")
17625 (if extra (concat "\\|" extra))
17626 "\\):[ \t]*"
17627 "\\(.*\\)"))
17629 ;; Make isearch reveal the necessary context
17630 (defun org-isearch-end ()
17631 "Reveal context after isearch exits."
17632 (when isearch-success ; only if search was successful
17633 (if (featurep 'xemacs)
17634 ;; Under XEmacs, the hook is run in the correct place,
17635 ;; we directly show the context.
17636 (org-show-context 'isearch)
17637 ;; In Emacs the hook runs *before* restoring the overlays.
17638 ;; So we have to use a one-time post-command-hook to do this.
17639 ;; (Emacs 22 has a special variable, see function `org-mode')
17640 (unless (and (boundp 'isearch-mode-end-hook-quit)
17641 isearch-mode-end-hook-quit)
17642 ;; Only when the isearch was not quitted.
17643 (org-add-hook 'post-command-hook 'org-isearch-post-command
17644 'append 'local)))))
17646 (defun org-isearch-post-command ()
17647 "Remove self from hook, and show context."
17648 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17649 (org-show-context 'isearch))
17652 ;;;; Integration with and fixes for other packages
17654 ;;; Imenu support
17656 (defvar org-imenu-markers nil
17657 "All markers currently used by Imenu.")
17658 (make-variable-buffer-local 'org-imenu-markers)
17660 (defun org-imenu-new-marker (&optional pos)
17661 "Return a new marker for use by Imenu, and remember the marker."
17662 (let ((m (make-marker)))
17663 (move-marker m (or pos (point)))
17664 (push m org-imenu-markers)
17667 (defun org-imenu-get-tree ()
17668 "Produce the index for Imenu."
17669 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17670 (setq org-imenu-markers nil)
17671 (let* ((n org-imenu-depth)
17672 (re (concat "^" outline-regexp))
17673 (subs (make-vector (1+ n) nil))
17674 (last-level 0)
17675 m level head)
17676 (save-excursion
17677 (save-restriction
17678 (widen)
17679 (goto-char (point-max))
17680 (while (re-search-backward re nil t)
17681 (setq level (org-reduced-level (funcall outline-level)))
17682 (when (<= level n)
17683 (looking-at org-complex-heading-regexp)
17684 (setq head (org-link-display-format
17685 (org-match-string-no-properties 4))
17686 m (org-imenu-new-marker))
17687 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17688 (if (>= level last-level)
17689 (push (cons head m) (aref subs level))
17690 (push (cons head (aref subs (1+ level))) (aref subs level))
17691 (loop for i from (1+ level) to n do (aset subs i nil)))
17692 (setq last-level level)))))
17693 (aref subs 1)))
17695 (eval-after-load "imenu"
17696 '(progn
17697 (add-hook 'imenu-after-jump-hook
17698 (lambda ()
17699 (if (eq major-mode 'org-mode)
17700 (org-show-context 'org-goto))))))
17702 (defun org-link-display-format (link)
17703 "Replace a link with either the description, or the link target
17704 if no description is present"
17705 (save-match-data
17706 (if (string-match org-bracket-link-analytic-regexp link)
17707 (replace-match (if (match-end 5)
17708 (match-string 5 link)
17709 (concat (match-string 1 link)
17710 (match-string 3 link)))
17711 nil t link)
17712 link)))
17714 ;; Speedbar support
17716 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17717 "Overlay marking the agenda restriction line in speedbar.")
17718 (org-overlay-put org-speedbar-restriction-lock-overlay
17719 'face 'org-agenda-restriction-lock)
17720 (org-overlay-put org-speedbar-restriction-lock-overlay
17721 'help-echo "Agendas are currently limited to this item.")
17722 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17724 (defun org-speedbar-set-agenda-restriction ()
17725 "Restrict future agenda commands to the location at point in speedbar.
17726 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17727 (interactive)
17728 (require 'org-agenda)
17729 (let (p m tp np dir txt)
17730 (cond
17731 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17732 'org-imenu t))
17733 (setq m (get-text-property p 'org-imenu-marker))
17734 (with-current-buffer (marker-buffer m)
17735 (goto-char m)
17736 (org-agenda-set-restriction-lock 'subtree)))
17737 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17738 'speedbar-function 'speedbar-find-file))
17739 (setq tp (previous-single-property-change
17740 (1+ p) 'speedbar-function)
17741 np (next-single-property-change
17742 tp 'speedbar-function)
17743 dir (speedbar-line-directory)
17744 txt (buffer-substring-no-properties (or tp (point-min))
17745 (or np (point-max))))
17746 (with-current-buffer (find-file-noselect
17747 (let ((default-directory dir))
17748 (expand-file-name txt)))
17749 (unless (org-mode-p)
17750 (error "Cannot restrict to non-Org-mode file"))
17751 (org-agenda-set-restriction-lock 'file)))
17752 (t (error "Don't know how to restrict Org-mode's agenda")))
17753 (org-move-overlay org-speedbar-restriction-lock-overlay
17754 (point-at-bol) (point-at-eol))
17755 (setq current-prefix-arg nil)
17756 (org-agenda-maybe-redo)))
17758 (eval-after-load "speedbar"
17759 '(progn
17760 (speedbar-add-supported-extension ".org")
17761 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
17762 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
17763 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
17764 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17765 (add-hook 'speedbar-visiting-tag-hook
17766 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
17769 ;;; Fixes and Hacks for problems with other packages
17771 ;; Make flyspell not check words in links, to not mess up our keymap
17772 (defun org-mode-flyspell-verify ()
17773 "Don't let flyspell put overlays at active buttons."
17774 (and (not (get-text-property (point) 'keymap))
17775 (not (get-text-property (point) 'org-no-flyspell))))
17777 (defun org-remove-flyspell-overlays-in (beg end)
17778 "Remove flyspell overlays in region."
17779 (and (org-bound-and-true-p flyspell-mode)
17780 (fboundp 'flyspell-delete-region-overlays)
17781 (flyspell-delete-region-overlays beg end))
17782 (add-text-properties beg end '(org-no-flyspell t)))
17784 ;; Make `bookmark-jump' shows the jump location if it was hidden.
17785 (eval-after-load "bookmark"
17786 '(if (boundp 'bookmark-after-jump-hook)
17787 ;; We can use the hook
17788 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17789 ;; Hook not available, use advice
17790 (defadvice bookmark-jump (after org-make-visible activate)
17791 "Make the position visible."
17792 (org-bookmark-jump-unhide))))
17794 ;; Make sure saveplace shows the location if it was hidden
17795 (eval-after-load "saveplace"
17796 '(defadvice save-place-find-file-hook (after org-make-visible activate)
17797 "Make the position visible."
17798 (org-bookmark-jump-unhide)))
17800 ;; Make sure ecb shows the location if it was hidden
17801 (eval-after-load "ecb"
17802 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
17803 "Make hierarchy visible when jumping into location from ECB tree buffer."
17804 (if (eq major-mode 'org-mode)
17805 (org-show-context))))
17807 (defun org-bookmark-jump-unhide ()
17808 "Unhide the current position, to show the bookmark location."
17809 (and (org-mode-p)
17810 (or (org-invisible-p)
17811 (save-excursion (goto-char (max (point-min) (1- (point))))
17812 (org-invisible-p)))
17813 (org-show-context 'bookmark-jump)))
17815 ;; Make session.el ignore our circular variable
17816 (eval-after-load "session"
17817 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17819 ;;;; Experimental code
17821 (defun org-closed-in-range ()
17822 "Sparse tree of items closed in a certain time range.
17823 Still experimental, may disappear in the future."
17824 (interactive)
17825 ;; Get the time interval from the user.
17826 (let* ((time1 (org-float-time
17827 (org-read-date nil 'to-time nil "Starting date: ")))
17828 (time2 (org-float-time
17829 (org-read-date nil 'to-time nil "End date:")))
17830 ;; callback function
17831 (callback (lambda ()
17832 (let ((time
17833 (org-float-time
17834 (apply 'encode-time
17835 (org-parse-time-string
17836 (match-string 1))))))
17837 ;; check if time in interval
17838 (and (>= time time1) (<= time time2))))))
17839 ;; make tree, check each match with the callback
17840 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
17842 ;;;; Finish up
17844 (provide 'org)
17846 (run-hooks 'org-load-hook)
17848 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17850 ;;; org.el ends here