Fix issue with truncate-lines and visual-line-mode
[org-mode/org-jambu.git] / lisp / org.el
blobf597dd72448a8dd6522f4a1d7b536482ceda7828
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, 2011
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: 7.5
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))
77 (require 'calendar)
79 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
80 (when (fboundp 'defvaralias)
81 (unless (boundp 'calendar-view-holidays-initially-flag)
82 (defvaralias 'calendar-view-holidays-initially-flag
83 'view-calendar-holidays-initially))
84 (unless (boundp 'calendar-view-diary-initially-flag)
85 (defvaralias 'calendar-view-diary-initially-flag
86 'view-diary-entries-initially))
87 (unless (boundp 'diary-fancy-buffer)
88 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
90 (require 'outline) (require 'noutline)
91 ;; Other stuff we need.
92 (require 'time-date)
93 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
94 (require 'easymenu)
95 (require 'overlay)
97 (require 'org-macs)
98 (require 'org-entities)
99 (require 'org-compat)
100 (require 'org-faces)
101 (require 'org-list)
102 (require 'org-pcomplete)
103 (require 'org-src)
104 (require 'org-footnote)
106 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
107 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
108 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
110 ;; babel
111 (require 'ob)
112 (require 'ob-table)
113 (require 'ob-lob)
114 (require 'ob-ref)
115 (require 'ob-tangle)
116 (require 'ob-comint)
117 (require 'ob-keys)
119 ;; load languages based on value of `org-babel-load-languages'
120 (defvar org-babel-load-languages)
121 ;;;###autoload
122 (defun org-babel-do-load-languages (sym value)
123 "Load the languages defined in `org-babel-load-languages'."
124 (set-default sym value)
125 (mapc (lambda (pair)
126 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
127 (if active
128 (progn
129 (require (intern (concat "ob-" lang))))
130 (progn
131 (funcall 'fmakunbound
132 (intern (concat "org-babel-execute:" lang)))
133 (funcall 'fmakunbound
134 (intern (concat "org-babel-expand-body:" lang)))))))
135 org-babel-load-languages))
137 (defcustom org-babel-load-languages '((emacs-lisp . t))
138 "Languages which can be evaluated in Org-mode buffers.
139 This list can be used to load support for any of the languages
140 below, note that each language will depend on a different set of
141 system executables and/or Emacs modes. When a language is
142 \"loaded\", then code blocks in that language can be evaluated
143 with `org-babel-execute-src-block' bound by default to C-c
144 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
145 be set to remove code block evaluation from the C-c C-c
146 keybinding. By default only Emacs Lisp (which has no
147 requirements) is loaded."
148 :group 'org-babel
149 :set 'org-babel-do-load-languages
150 :type '(alist :tag "Babel Languages"
151 :key-type
152 (choice
153 (const :tag "Awk" awk)
154 (const :tag "C" C)
155 (const :tag "R" R)
156 (const :tag "Asymptote" asymptote)
157 (const :tag "Calc" calc)
158 (const :tag "Clojure" clojure)
159 (const :tag "CSS" css)
160 (const :tag "Ditaa" ditaa)
161 (const :tag "Dot" dot)
162 (const :tag "Emacs Lisp" emacs-lisp)
163 (const :tag "Gnuplot" gnuplot)
164 (const :tag "Haskell" haskell)
165 (const :tag "Javascript" js)
166 (const :tag "Latex" latex)
167 (const :tag "Ledger" ledger)
168 (const :tag "Maxima" maxima)
169 (const :tag "Matlab" matlab)
170 (const :tag "Mscgen" mscgen)
171 (const :tag "Ocaml" ocaml)
172 (const :tag "Octave" octave)
173 (const :tag "Org" org)
174 (const :tag "Perl" perl)
175 (const :tag "PlantUML" plantuml)
176 (const :tag "Python" python)
177 (const :tag "Ruby" ruby)
178 (const :tag "Sass" sass)
179 (const :tag "Scheme" scheme)
180 (const :tag "Screen" screen)
181 (const :tag "Shell Script" sh)
182 (const :tag "Sql" sql)
183 (const :tag "Sqlite" sqlite))
184 :value-type (boolean :tag "Activate" :value t)))
186 ;;;; Customization variables
187 (defcustom org-clone-delete-id nil
188 "Remove ID property of clones of a subtree.
189 When non-nil, clones of a subtree don't inherit the ID property.
190 Otherwise they inherit the ID property with a new unique
191 identifier."
192 :type 'boolean
193 :group 'org-id)
195 ;;; Version
197 (defconst org-version "7.5"
198 "The version number of the file org.el.")
200 (defun org-version (&optional here)
201 "Show the org-mode version in the echo area.
202 With prefix arg HERE, insert it at point."
203 (interactive "P")
204 (let* ((origin default-directory)
205 (version org-version)
206 (git-version)
207 (dir (concat (file-name-directory (locate-library "org")) "../" )))
208 (when (and (file-exists-p (expand-file-name ".git" dir))
209 (executable-find "git"))
210 (unwind-protect
211 (progn
212 (cd dir)
213 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
214 (with-current-buffer "*Shell Command Output*"
215 (goto-char (point-min))
216 (setq git-version (buffer-substring (point) (point-at-eol))))
217 (subst-char-in-string ?- ?. git-version t)
218 (when (string-match "\\S-"
219 (shell-command-to-string
220 "git diff-index --name-only HEAD --"))
221 (setq git-version (concat git-version ".dirty")))
222 (setq version (concat version " (" git-version ")"))))
223 (cd origin)))
224 (setq version (format "Org-mode version %s" version))
225 (if here (insert version))
226 (message version)))
228 ;;; Compatibility constants
230 ;;; The custom variables
232 (defgroup org nil
233 "Outline-based notes management and organizer."
234 :tag "Org"
235 :group 'outlines
236 :group 'calendar)
238 (defcustom org-mode-hook nil
239 "Mode hook for Org-mode, run after the mode was turned on."
240 :group 'org
241 :type 'hook)
243 (defcustom org-load-hook nil
244 "Hook that is run after org.el has been loaded."
245 :group 'org
246 :type 'hook)
248 (defvar org-modules) ; defined below
249 (defvar org-modules-loaded nil
250 "Have the modules been loaded already?")
252 (defun org-load-modules-maybe (&optional force)
253 "Load all extensions listed in `org-modules'."
254 (when (or force (not org-modules-loaded))
255 (mapc (lambda (ext)
256 (condition-case nil (require ext)
257 (error (message "Problems while trying to load feature `%s'" ext))))
258 org-modules)
259 (setq org-modules-loaded t)))
261 (defun org-set-modules (var value)
262 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
263 (set var value)
264 (when (featurep 'org)
265 (org-load-modules-maybe 'force)))
267 (when (org-bound-and-true-p org-modules)
268 (let ((a (member 'org-infojs org-modules)))
269 (and a (setcar a 'org-jsinfo))))
271 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
272 "Modules that should always be loaded together with org.el.
273 If a description starts with <C>, the file is not part of Emacs
274 and loading it will require that you have downloaded and properly installed
275 the org-mode distribution.
277 You can also use this system to load external packages (i.e. neither Org
278 core modules, nor modules from the CONTRIB directory). Just add symbols
279 to the end of the list. If the package is called org-xyz.el, then you need
280 to add the symbol `xyz', and the package must have a call to
282 (provide 'org-xyz)"
283 :group 'org
284 :set 'org-set-modules
285 :type
286 '(set :greedy t
287 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
288 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
289 (const :tag " crypt: Encryption of subtrees" org-crypt)
290 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
291 (const :tag " docview: Links to doc-view buffers" org-docview)
292 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
293 (const :tag " id: Global IDs for identifying entries" org-id)
294 (const :tag " info: Links to Info nodes" org-info)
295 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
296 (const :tag " habit: Track your consistency with habits" org-habit)
297 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
298 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
299 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
300 (const :tag " mew Links to Mew folders/messages" org-mew)
301 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
302 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
303 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
304 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
305 (const :tag " vm: Links to VM folders/messages" org-vm)
306 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
307 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
308 (const :tag " mouse: Additional mouse support" org-mouse)
309 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
311 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
312 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
313 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
314 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
315 (const :tag "C collector: Collect properties into tables" org-collector)
316 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
317 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
318 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
319 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
320 (const :tag "C eval: Include command output as text" org-eval)
321 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
322 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
323 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
324 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
325 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
327 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
329 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
330 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
331 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
332 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
333 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
334 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
335 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
336 (const :tag "C mtags: Support for muse-like tags" org-mtags)
337 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
338 (const :tag "C registry: A registry for Org-mode links" org-registry)
339 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
340 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
341 (const :tag "C secretary: Team management with org-mode" org-secretary)
342 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
343 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
344 (const :tag "C track: Keep up with Org-mode development" org-track)
345 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
346 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
347 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
349 (defcustom org-support-shift-select nil
350 "Non-nil means make shift-cursor commands select text when possible.
352 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
353 selecting a region, or enlarge regions started in this way.
354 In Org-mode, in special contexts, these same keys are used for other
355 purposes, important enough to compete with shift selection. Org tries
356 to balance these needs by supporting `shift-select-mode' outside these
357 special contexts, under control of this variable.
359 The default of this variable is nil, to avoid confusing behavior. Shifted
360 cursor keys will then execute Org commands in the following contexts:
361 - on a headline, changing TODO state (left/right) and priority (up/down)
362 - on a time stamp, changing the time
363 - in a plain list item, changing the bullet type
364 - in a property definition line, switching between allowed values
365 - in the BEGIN line of a clock table (changing the time block).
366 Outside these contexts, the commands will throw an error.
368 When this variable is t and the cursor is not in a special context,
369 Org-mode will support shift-selection for making and enlarging regions.
370 To make this more effective, the bullet cycling will no longer happen
371 anywhere in an item line, but only if the cursor is exactly on the bullet.
373 If you set this variable to the symbol `always', then the keys
374 will not be special in headlines, property lines, and item lines, to make
375 shift selection work there as well. If this is what you want, you can
376 use the following alternative commands: `C-c C-t' and `C-c ,' to
377 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
378 TODO sets, `C-c -' to cycle item bullet types, and properties can be
379 edited by hand or in column view.
381 However, when the cursor is on a timestamp, shift-cursor commands
382 will still edit the time stamp - this is just too good to give up.
384 XEmacs user should have this variable set to nil, because shift-select-mode
385 is Emacs 23 only."
386 :group 'org
387 :type '(choice
388 (const :tag "Never" nil)
389 (const :tag "When outside special context" t)
390 (const :tag "Everywhere except timestamps" always)))
392 (defgroup org-startup nil
393 "Options concerning startup of Org-mode."
394 :tag "Org Startup"
395 :group 'org)
397 (defcustom org-startup-folded t
398 "Non-nil means entering Org-mode will switch to OVERVIEW.
399 This can also be configured on a per-file basis by adding one of
400 the following lines anywhere in the buffer:
402 #+STARTUP: fold (or `overview', this is equivalent)
403 #+STARTUP: nofold (or `showall', this is equivalent)
404 #+STARTUP: content
405 #+STARTUP: showeverything"
406 :group 'org-startup
407 :type '(choice
408 (const :tag "nofold: show all" nil)
409 (const :tag "fold: overview" t)
410 (const :tag "content: all headlines" content)
411 (const :tag "show everything, even drawers" showeverything)))
413 (defcustom org-startup-truncated t
414 "Non-nil means entering Org-mode will set `truncate-lines'.
415 This is useful since some lines containing links can be very long and
416 uninteresting. Also tables look terrible when wrapped."
417 :group 'org-startup
418 :type 'boolean)
420 (defcustom org-startup-indented nil
421 "Non-nil means turn on `org-indent-mode' on startup.
422 This can also be configured on a per-file basis by adding one of
423 the following lines anywhere in the buffer:
425 #+STARTUP: indent
426 #+STARTUP: noindent"
427 :group 'org-structure
428 :type '(choice
429 (const :tag "Not" nil)
430 (const :tag "Globally (slow on startup in large files)" t)))
432 (defcustom org-use-sub-superscripts t
433 "Non-nil means interpret \"_\" and \"^\" for export.
434 When this option is turned on, you can use TeX-like syntax for sub- and
435 superscripts. Several characters after \"_\" or \"^\" will be
436 considered as a single item - so grouping with {} is normally not
437 needed. For example, the following things will be parsed as single
438 sub- or superscripts.
440 10^24 or 10^tau several digits will be considered 1 item.
441 10^-12 or 10^-tau a leading sign with digits or a word
442 x^2-y^3 will be read as x^2 - y^3, because items are
443 terminated by almost any nonword/nondigit char.
444 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
446 Still, ambiguity is possible - so when in doubt use {} to enclose the
447 sub/superscript. If you set this variable to the symbol `{}',
448 the braces are *required* in order to trigger interpretations as
449 sub/superscript. This can be helpful in documents that need \"_\"
450 frequently in plain text.
452 Not all export backends support this, but HTML does.
454 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
455 :group 'org-startup
456 :group 'org-export-translation
457 :type '(choice
458 (const :tag "Always interpret" t)
459 (const :tag "Only with braces" {})
460 (const :tag "Never interpret" nil)))
462 (if (fboundp 'defvaralias)
463 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
466 (defcustom org-startup-with-beamer-mode nil
467 "Non-nil means turn on `org-beamer-mode' on startup.
468 This can also be configured on a per-file basis by adding one of
469 the following lines anywhere in the buffer:
471 #+STARTUP: beamer"
472 :group 'org-startup
473 :type 'boolean)
475 (defcustom org-startup-align-all-tables nil
476 "Non-nil means align all tables when visiting a file.
477 This is useful when the column width in tables is forced with <N> cookies
478 in table fields. Such tables will look correct only after the first re-align.
479 This can also be configured on a per-file basis by adding one of
480 the following lines anywhere in the buffer:
481 #+STARTUP: align
482 #+STARTUP: noalign"
483 :group 'org-startup
484 :type 'boolean)
486 (defcustom org-startup-with-inline-images nil
487 "Non-nil means show inline images when loading a new Org file.
488 This can also be configured on a per-file basis by adding one of
489 the following lines anywhere in the buffer:
490 #+STARTUP: inlineimages
491 #+STARTUP: noinlineimages"
492 :group 'org-startup
493 :type 'boolean)
495 (defcustom org-insert-mode-line-in-empty-file nil
496 "Non-nil means insert the first line setting Org-mode in empty files.
497 When the function `org-mode' is called interactively in an empty file, this
498 normally means that the file name does not automatically trigger Org-mode.
499 To ensure that the file will always be in Org-mode in the future, a
500 line enforcing Org-mode will be inserted into the buffer, if this option
501 has been set."
502 :group 'org-startup
503 :type 'boolean)
505 (defcustom org-replace-disputed-keys nil
506 "Non-nil means use alternative key bindings for some keys.
507 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
508 These keys are also used by other packages like shift-selection-mode'
509 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
510 If you want to use Org-mode together with one of these other modes,
511 or more generally if you would like to move some Org-mode commands to
512 other keys, set this variable and configure the keys with the variable
513 `org-disputed-keys'.
515 This option is only relevant at load-time of Org-mode, and must be set
516 *before* org.el is loaded. Changing it requires a restart of Emacs to
517 become effective."
518 :group 'org-startup
519 :type 'boolean)
521 (defcustom org-use-extra-keys nil
522 "Non-nil means use extra key sequence definitions for certain commands.
523 This happens automatically if you run XEmacs or if `window-system'
524 is nil. This variable lets you do the same manually. You must
525 set it before loading org.
527 Example: on Carbon Emacs 22 running graphically, with an external
528 keyboard on a Powerbook, the default way of setting M-left might
529 not work for either Alt or ESC. Setting this variable will make
530 it work for ESC."
531 :group 'org-startup
532 :type 'boolean)
534 (if (fboundp 'defvaralias)
535 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
537 (defcustom org-disputed-keys
538 '(([(shift up)] . [(meta p)])
539 ([(shift down)] . [(meta n)])
540 ([(shift left)] . [(meta -)])
541 ([(shift right)] . [(meta +)])
542 ([(control shift right)] . [(meta shift +)])
543 ([(control shift left)] . [(meta shift -)]))
544 "Keys for which Org-mode and other modes compete.
545 This is an alist, cars are the default keys, second element specifies
546 the alternative to use when `org-replace-disputed-keys' is t.
548 Keys can be specified in any syntax supported by `define-key'.
549 The value of this option takes effect only at Org-mode's startup,
550 therefore you'll have to restart Emacs to apply it after changing."
551 :group 'org-startup
552 :type 'alist)
554 (defun org-key (key)
555 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
556 Or return the original if not disputed.
557 Also apply the translations defined in `org-xemacs-key-equivalents'."
558 (when org-replace-disputed-keys
559 (let* ((nkey (key-description key))
560 (x (org-find-if (lambda (x)
561 (equal (key-description (car x)) nkey))
562 org-disputed-keys)))
563 (setq key (if x (cdr x) key))))
564 (when (featurep 'xemacs)
565 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
566 key)
568 (defun org-find-if (predicate seq)
569 (catch 'exit
570 (while seq
571 (if (funcall predicate (car seq))
572 (throw 'exit (car seq))
573 (pop seq)))))
575 (defun org-defkey (keymap key def)
576 "Define a key, possibly translated, as returned by `org-key'."
577 (define-key keymap (org-key key) def))
579 (defcustom org-ellipsis nil
580 "The ellipsis to use in the Org-mode outline.
581 When nil, just use the standard three dots. When a string, use that instead,
582 When a face, use the standard 3 dots, but with the specified face.
583 The change affects only Org-mode (which will then use its own display table).
584 Changing this requires executing `M-x org-mode' in a buffer to become
585 effective."
586 :group 'org-startup
587 :type '(choice (const :tag "Default" nil)
588 (face :tag "Face" :value org-warning)
589 (string :tag "String" :value "...#")))
591 (defvar org-display-table nil
592 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
594 (defgroup org-keywords nil
595 "Keywords in Org-mode."
596 :tag "Org Keywords"
597 :group 'org)
599 (defcustom org-deadline-string "DEADLINE:"
600 "String to mark deadline entries.
601 A deadline is this string, followed by a time stamp. Should be a word,
602 terminated by a colon. You can insert a schedule keyword and
603 a timestamp with \\[org-deadline].
604 Changes become only effective after restarting Emacs."
605 :group 'org-keywords
606 :type 'string)
608 (defcustom org-scheduled-string "SCHEDULED:"
609 "String to mark scheduled TODO entries.
610 A schedule is this string, followed by a time stamp. Should be a word,
611 terminated by a colon. You can insert a schedule keyword and
612 a timestamp with \\[org-schedule].
613 Changes become only effective after restarting Emacs."
614 :group 'org-keywords
615 :type 'string)
617 (defcustom org-closed-string "CLOSED:"
618 "String used as the prefix for timestamps logging closing a TODO entry."
619 :group 'org-keywords
620 :type 'string)
622 (defcustom org-clock-string "CLOCK:"
623 "String used as prefix for timestamps clocking work hours on an item."
624 :group 'org-keywords
625 :type 'string)
627 (defcustom org-comment-string "COMMENT"
628 "Entries starting with this keyword will never be exported.
629 An entry can be toggled between COMMENT and normal with
630 \\[org-toggle-comment].
631 Changes become only effective after restarting Emacs."
632 :group 'org-keywords
633 :type 'string)
635 (defcustom org-quote-string "QUOTE"
636 "Entries starting with this keyword will be exported in fixed-width font.
637 Quoting applies only to the text in the entry following the headline, and does
638 not extend beyond the next headline, even if that is lower level.
639 An entry can be toggled between QUOTE and normal with
640 \\[org-toggle-fixed-width-section]."
641 :group 'org-keywords
642 :type 'string)
644 (defconst org-repeat-re
645 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
646 "Regular expression for specifying repeated events.
647 After a match, group 1 contains the repeat expression.")
649 (defgroup org-structure nil
650 "Options concerning the general structure of Org-mode files."
651 :tag "Org Structure"
652 :group 'org)
654 (defgroup org-reveal-location nil
655 "Options about how to make context of a location visible."
656 :tag "Org Reveal Location"
657 :group 'org-structure)
659 (defconst org-context-choice
660 '(choice
661 (const :tag "Always" t)
662 (const :tag "Never" nil)
663 (repeat :greedy t :tag "Individual contexts"
664 (cons
665 (choice :tag "Context"
666 (const agenda)
667 (const org-goto)
668 (const occur-tree)
669 (const tags-tree)
670 (const link-search)
671 (const mark-goto)
672 (const bookmark-jump)
673 (const isearch)
674 (const default))
675 (boolean))))
676 "Contexts for the reveal options.")
678 (defcustom org-show-hierarchy-above '((default . t))
679 "Non-nil means show full hierarchy when revealing a location.
680 Org-mode often shows locations in an org-mode file which might have
681 been invisible before. When this is set, the hierarchy of headings
682 above the exposed location is shown.
683 Turning this off for example for sparse trees makes them very compact.
684 Instead of t, this can also be an alist specifying this option for different
685 contexts. Valid contexts are
686 agenda when exposing an entry from the agenda
687 org-goto when using the command `org-goto' on key C-c C-j
688 occur-tree when using the command `org-occur' on key C-c /
689 tags-tree when constructing a sparse tree based on tags matches
690 link-search when exposing search matches associated with a link
691 mark-goto when exposing the jump goal of a mark
692 bookmark-jump when exposing a bookmark location
693 isearch when exiting from an incremental search
694 default default for all contexts not set explicitly"
695 :group 'org-reveal-location
696 :type org-context-choice)
698 (defcustom org-show-following-heading '((default . nil))
699 "Non-nil means show following heading when revealing a location.
700 Org-mode often shows locations in an org-mode file which might have
701 been invisible before. When this is set, the heading following the
702 match is shown.
703 Turning this off for example for sparse trees makes them very compact,
704 but makes it harder to edit the location of the match. In such a case,
705 use the command \\[org-reveal] to show more context.
706 Instead of t, this can also be an alist specifying this option for different
707 contexts. See `org-show-hierarchy-above' for valid contexts."
708 :group 'org-reveal-location
709 :type org-context-choice)
711 (defcustom org-show-siblings '((default . nil) (isearch t))
712 "Non-nil means show all sibling heading when revealing a location.
713 Org-mode often shows locations in an org-mode file which might have
714 been invisible before. When this is set, the sibling of the current entry
715 heading are all made visible. If `org-show-hierarchy-above' is t,
716 the same happens on each level of the hierarchy above the current entry.
718 By default this is on for the isearch context, off for all other contexts.
719 Turning this off for example for sparse trees makes them very compact,
720 but makes it harder to edit the location of the match. In such a case,
721 use the command \\[org-reveal] to show more context.
722 Instead of t, this can also be an alist specifying this option for different
723 contexts. See `org-show-hierarchy-above' for valid contexts."
724 :group 'org-reveal-location
725 :type org-context-choice)
727 (defcustom org-show-entry-below '((default . nil))
728 "Non-nil means show the entry below a headline when revealing a location.
729 Org-mode often shows locations in an org-mode file which might have
730 been invisible before. When this is set, the text below the headline that is
731 exposed is also shown.
733 By default this is off for all contexts.
734 Instead of t, this can also be an alist specifying this option for different
735 contexts. See `org-show-hierarchy-above' for valid contexts."
736 :group 'org-reveal-location
737 :type org-context-choice)
739 (defcustom org-indirect-buffer-display 'other-window
740 "How should indirect tree buffers be displayed?
741 This applies to indirect buffers created with the commands
742 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
743 Valid values are:
744 current-window Display in the current window
745 other-window Just display in another window.
746 dedicated-frame Create one new frame, and re-use it each time.
747 new-frame Make a new frame each time. Note that in this case
748 previously-made indirect buffers are kept, and you need to
749 kill these buffers yourself."
750 :group 'org-structure
751 :group 'org-agenda-windows
752 :type '(choice
753 (const :tag "In current window" current-window)
754 (const :tag "In current frame, other window" other-window)
755 (const :tag "Each time a new frame" new-frame)
756 (const :tag "One dedicated frame" dedicated-frame)))
758 (defcustom org-use-speed-commands nil
759 "Non-nil means activate single letter commands at beginning of a headline.
760 This may also be a function to test for appropriate locations where speed
761 commands should be active."
762 :group 'org-structure
763 :type '(choice
764 (const :tag "Never" nil)
765 (const :tag "At beginning of headline stars" t)
766 (function)))
768 (defcustom org-speed-commands-user nil
769 "Alist of additional speed commands.
770 This list will be checked before `org-speed-commands-default'
771 when the variable `org-use-speed-commands' is non-nil
772 and when the cursor is at the beginning of a headline.
773 The car if each entry is a string with a single letter, which must
774 be assigned to `self-insert-command' in the global map.
775 The cdr is either a command to be called interactively, a function
776 to be called, or a form to be evaluated.
777 An entry that is just a list with a single string will be interpreted
778 as a descriptive headline that will be added when listing the speed
779 commands in the Help buffer using the `?' speed command."
780 :group 'org-structure
781 :type '(repeat :value ("k" . ignore)
782 (choice :value ("k" . ignore)
783 (list :tag "Descriptive Headline" (string :tag "Headline"))
784 (cons :tag "Letter and Command"
785 (string :tag "Command letter")
786 (choice
787 (function)
788 (sexp))))))
790 (defgroup org-cycle nil
791 "Options concerning visibility cycling in Org-mode."
792 :tag "Org Cycle"
793 :group 'org-structure)
795 (defcustom org-cycle-skip-children-state-if-no-children t
796 "Non-nil means skip CHILDREN state in entries that don't have any."
797 :group 'org-cycle
798 :type 'boolean)
800 (defcustom org-cycle-max-level nil
801 "Maximum level which should still be subject to visibility cycling.
802 Levels higher than this will, for cycling, be treated as text, not a headline.
803 When `org-odd-levels-only' is set, a value of N in this variable actually
804 means 2N-1 stars as the limiting headline.
805 When nil, cycle all levels.
806 Note that the limiting level of cycling is also influenced by
807 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
808 `org-inlinetask-min-level' is, cycling will be limited to levels one less
809 than its value."
810 :group 'org-cycle
811 :type '(choice
812 (const :tag "No limit" nil)
813 (integer :tag "Maximum level")))
815 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
816 "Names of drawers. Drawers are not opened by cycling on the headline above.
817 Drawers only open with a TAB on the drawer line itself. A drawer looks like
818 this:
819 :DRAWERNAME:
820 .....
821 :END:
822 The drawer \"PROPERTIES\" is special for capturing properties through
823 the property API.
825 Drawers can be defined on the per-file basis with a line like:
827 #+DRAWERS: HIDDEN STATE PROPERTIES"
828 :group 'org-structure
829 :group 'org-cycle
830 :type '(repeat (string :tag "Drawer Name")))
832 (defcustom org-hide-block-startup nil
833 "Non-nil means entering Org-mode will fold all blocks.
834 This can also be set in on a per-file basis with
836 #+STARTUP: hideblocks
837 #+STARTUP: showblocks"
838 :group 'org-startup
839 :group 'org-cycle
840 :type 'boolean)
842 (defcustom org-cycle-global-at-bob nil
843 "Cycle globally if cursor is at beginning of buffer and not at a headline.
844 This makes it possible to do global cycling without having to use S-TAB or
845 \\[universal-argument] TAB. For this special case to work, the first line \
846 of the buffer
847 must not be a headline - it may be empty or some other text. When used in
848 this way, `org-cycle-hook' is disables temporarily, to make sure the
849 cursor stays at the beginning of the buffer.
850 When this option is nil, don't do anything special at the beginning
851 of the buffer."
852 :group 'org-cycle
853 :type 'boolean)
855 (defcustom org-cycle-level-after-item/entry-creation t
856 "Non-nil means cycle entry level or item indentation in new empty entries.
858 When the cursor is at the end of an empty headline, i.e with only stars
859 and maybe a TODO keyword, TAB will then switch the entry to become a child,
860 and then all possible ancestor states, before returning to the original state.
861 This makes data entry extremely fast: M-RET to create a new headline,
862 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
864 When the cursor is at the end of an empty plain list item, one TAB will
865 make it a subitem, two or more tabs will back up to make this an item
866 higher up in the item hierarchy."
867 :group 'org-cycle
868 :type 'boolean)
870 (defcustom org-cycle-emulate-tab t
871 "Where should `org-cycle' emulate TAB.
872 nil Never
873 white Only in completely white lines
874 whitestart Only at the beginning of lines, before the first non-white char
875 t Everywhere except in headlines
876 exc-hl-bol Everywhere except at the start of a headline
877 If TAB is used in a place where it does not emulate TAB, the current subtree
878 visibility is cycled."
879 :group 'org-cycle
880 :type '(choice (const :tag "Never" nil)
881 (const :tag "Only in completely white lines" white)
882 (const :tag "Before first char in a line" whitestart)
883 (const :tag "Everywhere except in headlines" t)
884 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
887 (defcustom org-cycle-separator-lines 2
888 "Number of empty lines needed to keep an empty line between collapsed trees.
889 If you leave an empty line between the end of a subtree and the following
890 headline, this empty line is hidden when the subtree is folded.
891 Org-mode will leave (exactly) one empty line visible if the number of
892 empty lines is equal or larger to the number given in this variable.
893 So the default 2 means at least 2 empty lines after the end of a subtree
894 are needed to produce free space between a collapsed subtree and the
895 following headline.
897 If the number is negative, and the number of empty lines is at least -N,
898 all empty lines are shown.
900 Special case: when 0, never leave empty lines in collapsed view."
901 :group 'org-cycle
902 :type 'integer)
903 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
905 (defcustom org-pre-cycle-hook nil
906 "Hook that is run before visibility cycling is happening.
907 The function(s) in this hook must accept a single argument which indicates
908 the new state that will be set right after running this hook. The
909 argument is a symbol. Before a global state change, it can have the values
910 `overview', `content', or `all'. Before a local state change, it can have
911 the values `folded', `children', or `subtree'."
912 :group 'org-cycle
913 :type 'hook)
915 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
916 org-cycle-hide-drawers
917 org-cycle-show-empty-lines
918 org-optimize-window-after-visibility-change)
919 "Hook that is run after `org-cycle' has changed the buffer visibility.
920 The function(s) in this hook must accept a single argument which indicates
921 the new state that was set by the most recent `org-cycle' command. The
922 argument is a symbol. After a global state change, it can have the values
923 `overview', `content', or `all'. After a local state change, it can have
924 the values `folded', `children', or `subtree'."
925 :group 'org-cycle
926 :type 'hook)
928 (defgroup org-edit-structure nil
929 "Options concerning structure editing in Org-mode."
930 :tag "Org Edit Structure"
931 :group 'org-structure)
933 (defcustom org-odd-levels-only nil
934 "Non-nil means skip even levels and only use odd levels for the outline.
935 This has the effect that two stars are being added/taken away in
936 promotion/demotion commands. It also influences how levels are
937 handled by the exporters.
938 Changing it requires restart of `font-lock-mode' to become effective
939 for fontification also in regions already fontified.
940 You may also set this on a per-file basis by adding one of the following
941 lines to the buffer:
943 #+STARTUP: odd
944 #+STARTUP: oddeven"
945 :group 'org-edit-structure
946 :group 'org-appearance
947 :type 'boolean)
949 (defcustom org-adapt-indentation t
950 "Non-nil means adapt indentation to outline node level.
952 When this variable is set, Org assumes that you write outlines by
953 indenting text in each node to align with the headline (after the stars).
954 The following issues are influenced by this variable:
956 - When this is set and the *entire* text in an entry is indented, the
957 indentation is increased by one space in a demotion command, and
958 decreased by one in a promotion command. If any line in the entry
959 body starts with text at column 0, indentation is not changed at all.
961 - Property drawers and planning information is inserted indented when
962 this variable s set. When nil, they will not be indented.
964 - TAB indents a line relative to context. The lines below a headline
965 will be indented when this variable is set.
967 Note that this is all about true indentation, by adding and removing
968 space characters. See also `org-indent.el' which does level-dependent
969 indentation in a virtual way, i.e. at display time in Emacs."
970 :group 'org-edit-structure
971 :type 'boolean)
973 (defcustom org-special-ctrl-a/e nil
974 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
976 When t, `C-a' will bring back the cursor to the beginning of the
977 headline text, i.e. after the stars and after a possible TODO keyword.
978 In an item, this will be the position after the bullet.
979 When the cursor is already at that position, another `C-a' will bring
980 it to the beginning of the line.
982 `C-e' will jump to the end of the headline, ignoring the presence of tags
983 in the headline. A second `C-e' will then jump to the true end of the
984 line, after any tags. This also means that, when this variable is
985 non-nil, `C-e' also will never jump beyond the end of the heading of a
986 folded section, i.e. not after the ellipses.
988 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
989 going to the true line boundary first. Only a directly following, identical
990 keypress will bring the cursor to the special positions.
992 This may also be a cons cell where the behavior for `C-a' and `C-e' is
993 set separately."
994 :group 'org-edit-structure
995 :type '(choice
996 (const :tag "off" nil)
997 (const :tag "on: after stars/bullet and before tags first" t)
998 (const :tag "reversed: true line boundary first" reversed)
999 (cons :tag "Set C-a and C-e separately"
1000 (choice :tag "Special C-a"
1001 (const :tag "off" nil)
1002 (const :tag "on: after stars/bullet first" t)
1003 (const :tag "reversed: before stars/bullet first" reversed))
1004 (choice :tag "Special C-e"
1005 (const :tag "off" nil)
1006 (const :tag "on: before tags first" t)
1007 (const :tag "reversed: after tags first" reversed)))))
1008 (if (fboundp 'defvaralias)
1009 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1011 (defcustom org-special-ctrl-k nil
1012 "Non-nil means `C-k' will behave specially in headlines.
1013 When nil, `C-k' will call the default `kill-line' command.
1014 When t, the following will happen while the cursor is in the headline:
1016 - When the cursor is at the beginning of a headline, kill the entire
1017 line and possible the folded subtree below the line.
1018 - When in the middle of the headline text, kill the headline up to the tags.
1019 - When after the headline text, kill the tags."
1020 :group 'org-edit-structure
1021 :type 'boolean)
1023 (defcustom org-ctrl-k-protect-subtree nil
1024 "Non-nil means, do not delete a hidden subtree with C-k.
1025 When set to the symbol `error', simply throw an error when C-k is
1026 used to kill (part-of) a headline that has hidden text behind it.
1027 Any other non-nil value will result in a query to the user, if it is
1028 OK to kill that hidden subtree. When nil, kill without remorse."
1029 :group 'org-edit-structure
1030 :type '(choice
1031 (const :tag "Do not protect hidden subtrees" nil)
1032 (const :tag "Protect hidden subtrees with a security query" t)
1033 (const :tag "Never kill a hidden subtree with C-k" error)))
1035 (defcustom org-yank-folded-subtrees t
1036 "Non-nil means when yanking subtrees, fold them.
1037 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1038 it starts with a heading and all other headings in it are either children
1039 or siblings, then fold all the subtrees. However, do this only if no
1040 text after the yank would be swallowed into a folded tree by this action."
1041 :group 'org-edit-structure
1042 :type 'boolean)
1044 (defcustom org-yank-adjusted-subtrees nil
1045 "Non-nil means when yanking subtrees, adjust the level.
1046 With this setting, `org-paste-subtree' is used to insert the subtree, see
1047 this function for details."
1048 :group 'org-edit-structure
1049 :type 'boolean)
1051 (defcustom org-M-RET-may-split-line '((default . t))
1052 "Non-nil means M-RET will split the line at the cursor position.
1053 When nil, it will go to the end of the line before making a
1054 new line.
1055 You may also set this option in a different way for different
1056 contexts. Valid contexts are:
1058 headline when creating a new headline
1059 item when creating a new item
1060 table in a table field
1061 default the value to be used for all contexts not explicitly
1062 customized"
1063 :group 'org-structure
1064 :group 'org-table
1065 :type '(choice
1066 (const :tag "Always" t)
1067 (const :tag "Never" nil)
1068 (repeat :greedy t :tag "Individual contexts"
1069 (cons
1070 (choice :tag "Context"
1071 (const headline)
1072 (const item)
1073 (const table)
1074 (const default))
1075 (boolean)))))
1078 (defcustom org-insert-heading-respect-content nil
1079 "Non-nil means insert new headings after the current subtree.
1080 When nil, the new heading is created directly after the current line.
1081 The commands \\[org-insert-heading-respect-content] and
1082 \\[org-insert-todo-heading-respect-content] turn this variable on
1083 for the duration of the command."
1084 :group 'org-structure
1085 :type 'boolean)
1087 (defcustom org-blank-before-new-entry '((heading . auto)
1088 (plain-list-item . auto))
1089 "Should `org-insert-heading' leave a blank line before new heading/item?
1090 The value is an alist, with `heading' and `plain-list-item' as car,
1091 and a boolean flag as cdr. The cdr may also be the symbol `auto', and then
1092 Org will look at the surrounding headings/items and try to make an
1093 intelligent decision whether to insert a blank line or not.
1095 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1096 set, the setting here is ignored and no empty line is inserted, to avoid
1097 breaking the list structure."
1098 :group 'org-edit-structure
1099 :type '(list
1100 (cons (const heading)
1101 (choice (const :tag "Never" nil)
1102 (const :tag "Always" t)
1103 (const :tag "Auto" auto)))
1104 (cons (const plain-list-item)
1105 (choice (const :tag "Never" nil)
1106 (const :tag "Always" t)
1107 (const :tag "Auto" auto)))))
1109 (defcustom org-insert-heading-hook nil
1110 "Hook being run after inserting a new heading."
1111 :group 'org-edit-structure
1112 :type 'hook)
1114 (defcustom org-enable-fixed-width-editor t
1115 "Non-nil means lines starting with \":\" are treated as fixed-width.
1116 This currently only means they are never auto-wrapped.
1117 When nil, such lines will be treated like ordinary lines.
1118 See also the QUOTE keyword."
1119 :group 'org-edit-structure
1120 :type 'boolean)
1122 (defcustom org-goto-auto-isearch t
1123 "Non-nil means typing characters in `org-goto' starts incremental search."
1124 :group 'org-edit-structure
1125 :type 'boolean)
1127 (defgroup org-sparse-trees nil
1128 "Options concerning sparse trees in Org-mode."
1129 :tag "Org Sparse Trees"
1130 :group 'org-structure)
1132 (defcustom org-highlight-sparse-tree-matches t
1133 "Non-nil means highlight all matches that define a sparse tree.
1134 The highlights will automatically disappear the next time the buffer is
1135 changed by an edit command."
1136 :group 'org-sparse-trees
1137 :type 'boolean)
1139 (defcustom org-remove-highlights-with-change t
1140 "Non-nil means any change to the buffer will remove temporary highlights.
1141 Such highlights are created by `org-occur' and `org-clock-display'.
1142 When nil, `C-c C-c needs to be used to get rid of the highlights.
1143 The highlights created by `org-preview-latex-fragment' always need
1144 `C-c C-c' to be removed."
1145 :group 'org-sparse-trees
1146 :group 'org-time
1147 :type 'boolean)
1150 (defcustom org-occur-hook '(org-first-headline-recenter)
1151 "Hook that is run after `org-occur' has constructed a sparse tree.
1152 This can be used to recenter the window to show as much of the structure
1153 as possible."
1154 :group 'org-sparse-trees
1155 :type 'hook)
1157 (defgroup org-imenu-and-speedbar nil
1158 "Options concerning imenu and speedbar in Org-mode."
1159 :tag "Org Imenu and Speedbar"
1160 :group 'org-structure)
1162 (defcustom org-imenu-depth 2
1163 "The maximum level for Imenu access to Org-mode headlines.
1164 This also applied for speedbar access."
1165 :group 'org-imenu-and-speedbar
1166 :type 'integer)
1168 (defgroup org-table nil
1169 "Options concerning tables in Org-mode."
1170 :tag "Org Table"
1171 :group 'org)
1173 (defcustom org-enable-table-editor 'optimized
1174 "Non-nil means lines starting with \"|\" are handled by the table editor.
1175 When nil, such lines will be treated like ordinary lines.
1177 When equal to the symbol `optimized', the table editor will be optimized to
1178 do the following:
1179 - Automatic overwrite mode in front of whitespace in table fields.
1180 This makes the structure of the table stay in tact as long as the edited
1181 field does not exceed the column width.
1182 - Minimize the number of realigns. Normally, the table is aligned each time
1183 TAB or RET are pressed to move to another field. With optimization this
1184 happens only if changes to a field might have changed the column width.
1185 Optimization requires replacing the functions `self-insert-command',
1186 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1187 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1188 very good at guessing when a re-align will be necessary, but you can always
1189 force one with \\[org-ctrl-c-ctrl-c].
1191 If you would like to use the optimized version in Org-mode, but the
1192 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1194 This variable can be used to turn on and off the table editor during a session,
1195 but in order to toggle optimization, a restart is required.
1197 See also the variable `org-table-auto-blank-field'."
1198 :group 'org-table
1199 :type '(choice
1200 (const :tag "off" nil)
1201 (const :tag "on" t)
1202 (const :tag "on, optimized" optimized)))
1204 (defcustom org-self-insert-cluster-for-undo t
1205 "Non-nil means cluster self-insert commands for undo when possible.
1206 If this is set, then, like in the Emacs command loop, 20 consecutive
1207 characters will be undone together.
1208 This is configurable, because there is some impact on typing performance."
1209 :group 'org-table
1210 :type 'boolean)
1212 (defcustom org-table-tab-recognizes-table.el t
1213 "Non-nil means TAB will automatically notice a table.el table.
1214 When it sees such a table, it moves point into it and - if necessary -
1215 calls `table-recognize-table'."
1216 :group 'org-table-editing
1217 :type 'boolean)
1219 (defgroup org-link nil
1220 "Options concerning links in Org-mode."
1221 :tag "Org Link"
1222 :group 'org)
1224 (defvar org-link-abbrev-alist-local nil
1225 "Buffer-local version of `org-link-abbrev-alist', which see.
1226 The value of this is taken from the #+LINK lines.")
1227 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1229 (defcustom org-link-abbrev-alist nil
1230 "Alist of link abbreviations.
1231 The car of each element is a string, to be replaced at the start of a link.
1232 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1233 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1235 [[linkkey:tag][description]]
1237 The 'linkkey' must be a word word, starting with a letter, followed
1238 by letters, numbers, '-' or '_'.
1240 If REPLACE is a string, the tag will simply be appended to create the link.
1241 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1242 the placeholder \"%h\" will cause a url-encoded version of the tag to
1243 be inserted at that point (see the function `url-hexify-string').
1245 REPLACE may also be a function that will be called with the tag as the
1246 only argument to create the link, which should be returned as a string.
1248 See the manual for examples."
1249 :group 'org-link
1250 :type '(repeat
1251 (cons
1252 (string :tag "Protocol")
1253 (choice
1254 (string :tag "Format")
1255 (function)))))
1257 (defcustom org-descriptive-links t
1258 "Non-nil means hide link part and only show description of bracket links.
1259 Bracket links are like [[link][description]]. This variable sets the initial
1260 state in new org-mode buffers. The setting can then be toggled on a
1261 per-buffer basis from the Org->Hyperlinks menu."
1262 :group 'org-link
1263 :type 'boolean)
1265 (defcustom org-link-file-path-type 'adaptive
1266 "How the path name in file links should be stored.
1267 Valid values are:
1269 relative Relative to the current directory, i.e. the directory of the file
1270 into which the link is being inserted.
1271 absolute Absolute path, if possible with ~ for home directory.
1272 noabbrev Absolute path, no abbreviation of home directory.
1273 adaptive Use relative path for files in the current directory and sub-
1274 directories of it. For other files, use an absolute path."
1275 :group 'org-link
1276 :type '(choice
1277 (const relative)
1278 (const absolute)
1279 (const noabbrev)
1280 (const adaptive)))
1282 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1283 "Types of links that should be activated in Org-mode files.
1284 This is a list of symbols, each leading to the activation of a certain link
1285 type. In principle, it does not hurt to turn on most link types - there may
1286 be a small gain when turning off unused link types. The types are:
1288 bracket The recommended [[link][description]] or [[link]] links with hiding.
1289 angle Links in angular brackets that may contain whitespace like
1290 <bbdb:Carsten Dominik>.
1291 plain Plain links in normal text, no whitespace, like http://google.com.
1292 radio Text that is matched by a radio target, see manual for details.
1293 tag Tag settings in a headline (link to tag search).
1294 date Time stamps (link to calendar).
1295 footnote Footnote labels.
1297 Changing this variable requires a restart of Emacs to become effective."
1298 :group 'org-link
1299 :type '(set :greedy t
1300 (const :tag "Double bracket links" bracket)
1301 (const :tag "Angular bracket links" angle)
1302 (const :tag "Plain text links" plain)
1303 (const :tag "Radio target matches" radio)
1304 (const :tag "Tags" tag)
1305 (const :tag "Timestamps" date)
1306 (const :tag "Footnotes" footnote)))
1308 (defcustom org-make-link-description-function nil
1309 "Function to use to generate link descriptions from links.
1310 If nil the link location will be used. This function must take
1311 two parameters; the first is the link and the second the
1312 description `org-insert-link' has generated, and should return the
1313 description to use."
1314 :group 'org-link
1315 :type 'function)
1317 (defgroup org-link-store nil
1318 "Options concerning storing links in Org-mode."
1319 :tag "Org Store Link"
1320 :group 'org-link)
1322 (defcustom org-email-link-description-format "Email %c: %.30s"
1323 "Format of the description part of a link to an email or usenet message.
1324 The following %-escapes will be replaced by corresponding information:
1326 %F full \"From\" field
1327 %f name, taken from \"From\" field, address if no name
1328 %T full \"To\" field
1329 %t first name in \"To\" field, address if no name
1330 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1331 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1332 %s subject
1333 %d date
1334 %m message-id.
1336 You may use normal field width specification between the % and the letter.
1337 This is for example useful to limit the length of the subject.
1339 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1340 :group 'org-link-store
1341 :type 'string)
1343 (defcustom org-from-is-user-regexp
1344 (let (r1 r2)
1345 (when (and user-mail-address (not (string= user-mail-address "")))
1346 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1347 (when (and user-full-name (not (string= user-full-name "")))
1348 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1349 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1350 "Regexp matched against the \"From:\" header of an email or usenet message.
1351 It should match if the message is from the user him/herself."
1352 :group 'org-link-store
1353 :type 'regexp)
1355 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1356 "Non-nil means storing a link to an Org file will use entry IDs.
1358 Note that before this variable is even considered, org-id must be loaded,
1359 so please customize `org-modules' and turn it on.
1361 The variable can have the following values:
1363 t Create an ID if needed to make a link to the current entry.
1365 create-if-interactive
1366 If `org-store-link' is called directly (interactively, as a user
1367 command), do create an ID to support the link. But when doing the
1368 job for remember, only use the ID if it already exists. The
1369 purpose of this setting is to avoid proliferation of unwanted
1370 IDs, just because you happen to be in an Org file when you
1371 call `org-remember' that automatically and preemptively
1372 creates a link. If you do want to get an ID link in a remember
1373 template to an entry not having an ID, create it first by
1374 explicitly creating a link to it, using `C-c C-l' first.
1376 create-if-interactive-and-no-custom-id
1377 Like create-if-interactive, but do not create an ID if there is
1378 a CUSTOM_ID property defined in the entry. This is the default.
1380 use-existing
1381 Use existing ID, do not create one.
1383 nil Never use an ID to make a link, instead link using a text search for
1384 the headline text."
1385 :group 'org-link-store
1386 :type '(choice
1387 (const :tag "Create ID to make link" t)
1388 (const :tag "Create if storing link interactively"
1389 create-if-interactive)
1390 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1391 create-if-interactive-and-no-custom-id)
1392 (const :tag "Only use existing" use-existing)
1393 (const :tag "Do not use ID to create link" nil)))
1395 (defcustom org-context-in-file-links t
1396 "Non-nil means file links from `org-store-link' contain context.
1397 A search string will be added to the file name with :: as separator and
1398 used to find the context when the link is activated by the command
1399 `org-open-at-point'. When this option is t, the entire active region
1400 will be placed in the search string of the file link. If set to a
1401 positive integer, only the first n lines of context will be stored.
1403 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1404 negates this setting for the duration of the command."
1405 :group 'org-link-store
1406 :type '(choice boolean integer))
1408 (defcustom org-keep-stored-link-after-insertion nil
1409 "Non-nil means keep link in list for entire session.
1411 The command `org-store-link' adds a link pointing to the current
1412 location to an internal list. These links accumulate during a session.
1413 The command `org-insert-link' can be used to insert links into any
1414 Org-mode file (offering completion for all stored links). When this
1415 option is nil, every link which has been inserted once using \\[org-insert-link]
1416 will be removed from the list, to make completing the unused links
1417 more efficient."
1418 :group 'org-link-store
1419 :type 'boolean)
1421 (defgroup org-link-follow nil
1422 "Options concerning following links in Org-mode."
1423 :tag "Org Follow Link"
1424 :group 'org-link)
1426 (defcustom org-link-translation-function nil
1427 "Function to translate links with different syntax to Org syntax.
1428 This can be used to translate links created for example by the Planner
1429 or emacs-wiki packages to Org syntax.
1430 The function must accept two parameters, a TYPE containing the link
1431 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1432 which is everything after the link protocol. It should return a cons
1433 with possibly modified values of type and path.
1434 Org contains a function for this, so if you set this variable to
1435 `org-translate-link-from-planner', you should be able follow many
1436 links created by planner."
1437 :group 'org-link-follow
1438 :type 'function)
1440 (defcustom org-follow-link-hook nil
1441 "Hook that is run after a link has been followed."
1442 :group 'org-link-follow
1443 :type 'hook)
1445 (defcustom org-tab-follows-link nil
1446 "Non-nil means on links TAB will follow the link.
1447 Needs to be set before org.el is loaded.
1448 This really should not be used, it does not make sense, and the
1449 implementation is bad."
1450 :group 'org-link-follow
1451 :type 'boolean)
1453 (defcustom org-return-follows-link nil
1454 "Non-nil means on links RET will follow the link."
1455 :group 'org-link-follow
1456 :type 'boolean)
1458 (defcustom org-mouse-1-follows-link
1459 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1460 "Non-nil means mouse-1 on a link will follow the link.
1461 A longer mouse click will still set point. Does not work on XEmacs.
1462 Needs to be set before org.el is loaded."
1463 :group 'org-link-follow
1464 :type 'boolean)
1466 (defcustom org-mark-ring-length 4
1467 "Number of different positions to be recorded in the ring.
1468 Changing this requires a restart of Emacs to work correctly."
1469 :group 'org-link-follow
1470 :type 'integer)
1472 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1473 "Non-nil means internal links in Org files must exactly match a headline.
1474 When nil, the link search tries to match a phrase with all words
1475 in the search text."
1476 :group 'org-link-follow
1477 :type '(choice
1478 (const :tag "Use fuzy text search" nil)
1479 (const :tag "Match only exact headline" t)
1480 (const :tag "Match extact headline or query to create it"
1481 query-to-create)))
1483 (defcustom org-link-frame-setup
1484 '((vm . vm-visit-folder-other-frame)
1485 (gnus . org-gnus-no-new-news)
1486 (file . find-file-other-window)
1487 (wl . wl-other-frame))
1488 "Setup the frame configuration for following links.
1489 When following a link with Emacs, it may often be useful to display
1490 this link in another window or frame. This variable can be used to
1491 set this up for the different types of links.
1492 For VM, use any of
1493 `vm-visit-folder'
1494 `vm-visit-folder-other-window'
1495 `vm-visit-folder-other-frame'
1496 For Gnus, use any of
1497 `gnus'
1498 `gnus-other-frame'
1499 `org-gnus-no-new-news'
1500 For FILE, use any of
1501 `find-file'
1502 `find-file-other-window'
1503 `find-file-other-frame'
1504 For Wanderlust use any of
1505 `wl'
1506 `wl-other-frame'
1507 For the calendar, use the variable `calendar-setup'.
1508 For BBDB, it is currently only possible to display the matches in
1509 another window."
1510 :group 'org-link-follow
1511 :type '(list
1512 (cons (const vm)
1513 (choice
1514 (const vm-visit-folder)
1515 (const vm-visit-folder-other-window)
1516 (const vm-visit-folder-other-frame)))
1517 (cons (const gnus)
1518 (choice
1519 (const gnus)
1520 (const gnus-other-frame)
1521 (const org-gnus-no-new-news)))
1522 (cons (const file)
1523 (choice
1524 (const find-file)
1525 (const find-file-other-window)
1526 (const find-file-other-frame)))
1527 (cons (const wl)
1528 (choice
1529 (const wl)
1530 (const wl-other-frame)))))
1532 (defcustom org-display-internal-link-with-indirect-buffer nil
1533 "Non-nil means use indirect buffer to display infile links.
1534 Activating internal links (from one location in a file to another location
1535 in the same file) normally just jumps to the location. When the link is
1536 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1537 is displayed in
1538 another window. When this option is set, the other window actually displays
1539 an indirect buffer clone of the current buffer, to avoid any visibility
1540 changes to the current buffer."
1541 :group 'org-link-follow
1542 :type 'boolean)
1544 (defcustom org-open-non-existing-files nil
1545 "Non-nil means `org-open-file' will open non-existing files.
1546 When nil, an error will be generated.
1547 This variable applies only to external applications because they
1548 might choke on non-existing files. If the link is to a file that
1549 will be opened in Emacs, the variable is ignored."
1550 :group 'org-link-follow
1551 :type 'boolean)
1553 (defcustom org-open-directory-means-index-dot-org nil
1554 "Non-nil means a link to a directory really means to index.org.
1555 When nil, following a directory link will run dired or open a finder/explorer
1556 window on that directory."
1557 :group 'org-link-follow
1558 :type 'boolean)
1560 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1561 "Function and arguments to call for following mailto links.
1562 This is a list with the first element being a Lisp function, and the
1563 remaining elements being arguments to the function. In string arguments,
1564 %a will be replaced by the address, and %s will be replaced by the subject
1565 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1566 :group 'org-link-follow
1567 :type '(choice
1568 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1569 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1570 (const :tag "message-mail" (message-mail "%a" "%s"))
1571 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1573 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1574 "Non-nil means ask for confirmation before executing shell links.
1575 Shell links can be dangerous: just think about a link
1577 [[shell:rm -rf ~/*][Google Search]]
1579 This link would show up in your Org-mode document as \"Google Search\",
1580 but really it would remove your entire home directory.
1581 Therefore we advise against setting this variable to nil.
1582 Just change it to `y-or-n-p' if you want to confirm with a
1583 single keystroke rather than having to type \"yes\"."
1584 :group 'org-link-follow
1585 :type '(choice
1586 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1587 (const :tag "with y-or-n (faster)" y-or-n-p)
1588 (const :tag "no confirmation (dangerous)" nil)))
1589 (put 'org-confirm-shell-link-function
1590 'safe-local-variable
1591 '(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1593 (defcustom org-confirm-shell-link-not-regexp ""
1594 "A regexp to skip confirmation for shell links."
1595 :group 'org-link-follow
1596 :type 'regexp)
1598 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1599 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1600 Elisp links can be dangerous: just think about a link
1602 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1604 This link would show up in your Org-mode document as \"Google Search\",
1605 but really it would remove your entire home directory.
1606 Therefore we advise against setting this variable to nil.
1607 Just change it to `y-or-n-p' if you want to confirm with a
1608 single keystroke rather than having to type \"yes\"."
1609 :group 'org-link-follow
1610 :type '(choice
1611 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1612 (const :tag "with y-or-n (faster)" y-or-n-p)
1613 (const :tag "no confirmation (dangerous)" nil)))
1614 (put 'org-confirm-shell-link-function
1615 'safe-local-variable
1616 '(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1618 (defcustom org-confirm-elisp-link-not-regexp ""
1619 "A regexp to skip confirmation for Elisp links."
1620 :group 'org-link-follow
1621 :type 'regexp)
1623 (defconst org-file-apps-defaults-gnu
1624 '((remote . emacs)
1625 (system . mailcap)
1626 (t . mailcap))
1627 "Default file applications on a UNIX or GNU/Linux system.
1628 See `org-file-apps'.")
1630 (defconst org-file-apps-defaults-macosx
1631 '((remote . emacs)
1632 (t . "open %s")
1633 (system . "open %s")
1634 ("ps.gz" . "gv %s")
1635 ("eps.gz" . "gv %s")
1636 ("dvi" . "xdvi %s")
1637 ("fig" . "xfig %s"))
1638 "Default file applications on a MacOS X system.
1639 The system \"open\" is known as a default, but we use X11 applications
1640 for some files for which the OS does not have a good default.
1641 See `org-file-apps'.")
1643 (defconst org-file-apps-defaults-windowsnt
1644 (list
1645 '(remote . emacs)
1646 (cons t
1647 (list (if (featurep 'xemacs)
1648 'mswindows-shell-execute
1649 'w32-shell-execute)
1650 "open" 'file))
1651 (cons 'system
1652 (list (if (featurep 'xemacs)
1653 'mswindows-shell-execute
1654 'w32-shell-execute)
1655 "open" 'file)))
1656 "Default file applications on a Windows NT system.
1657 The system \"open\" is used for most files.
1658 See `org-file-apps'.")
1660 (defcustom org-file-apps
1662 (auto-mode . emacs)
1663 ("\\.mm\\'" . default)
1664 ("\\.x?html?\\'" . default)
1665 ("\\.pdf\\'" . default)
1667 "External applications for opening `file:path' items in a document.
1668 Org-mode uses system defaults for different file types, but
1669 you can use this variable to set the application for a given file
1670 extension. The entries in this list are cons cells where the car identifies
1671 files and the cdr the corresponding command. Possible values for the
1672 file identifier are
1673 \"string\" A string as a file identifier can be interpreted in different
1674 ways, depending on its contents:
1676 - Alphanumeric characters only:
1677 Match links with this file extension.
1678 Example: (\"pdf\" . \"evince %s\")
1679 to open PDFs with evince.
1681 - Regular expression: Match links where the
1682 filename matches the regexp. If you want to
1683 use groups here, use shy groups.
1685 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1686 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1687 to open *.html and *.xhtml with firefox.
1689 - Regular expression which contains (non-shy) groups:
1690 Match links where the whole link, including \"::\", and
1691 anything after that, matches the regexp.
1692 In a custom command string, %1, %2, etc. are replaced with
1693 the parts of the link that were matched by the groups.
1694 For backwards compatibility, if a command string is given
1695 that does not use any of the group matches, this case is
1696 handled identically to the second one (i.e. match against
1697 file name only).
1698 In a custom lisp form, you can access the group matches with
1699 (match-string n link).
1701 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1702 to open [[file:document.pdf::5]] with evince at page 5.
1704 `directory' Matches a directory
1705 `remote' Matches a remote file, accessible through tramp or efs.
1706 Remote files most likely should be visited through Emacs
1707 because external applications cannot handle such paths.
1708 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1709 so all files Emacs knows how to handle. Using this with
1710 command `emacs' will open most files in Emacs. Beware that this
1711 will also open html files inside Emacs, unless you add
1712 (\"html\" . default) to the list as well.
1713 t Default for files not matched by any of the other options.
1714 `system' The system command to open files, like `open' on Windows
1715 and Mac OS X, and mailcap under GNU/Linux. This is the command
1716 that will be selected if you call `C-c C-o' with a double
1717 \\[universal-argument] \\[universal-argument] prefix.
1719 Possible values for the command are:
1720 `emacs' The file will be visited by the current Emacs process.
1721 `default' Use the default application for this file type, which is the
1722 association for t in the list, most likely in the system-specific
1723 part.
1724 This can be used to overrule an unwanted setting in the
1725 system-specific variable.
1726 `system' Use the system command for opening files, like \"open\".
1727 This command is specified by the entry whose car is `system'.
1728 Most likely, the system-specific version of this variable
1729 does define this command, but you can overrule/replace it
1730 here.
1731 string A command to be executed by a shell; %s will be replaced
1732 by the path to the file.
1733 sexp A Lisp form which will be evaluated. The file path will
1734 be available in the Lisp variable `file'.
1735 For more examples, see the system specific constants
1736 `org-file-apps-defaults-macosx'
1737 `org-file-apps-defaults-windowsnt'
1738 `org-file-apps-defaults-gnu'."
1739 :group 'org-link-follow
1740 :type '(repeat
1741 (cons (choice :value ""
1742 (string :tag "Extension")
1743 (const :tag "System command to open files" system)
1744 (const :tag "Default for unrecognized files" t)
1745 (const :tag "Remote file" remote)
1746 (const :tag "Links to a directory" directory)
1747 (const :tag "Any files that have Emacs modes"
1748 auto-mode))
1749 (choice :value ""
1750 (const :tag "Visit with Emacs" emacs)
1751 (const :tag "Use default" default)
1752 (const :tag "Use the system command" system)
1753 (string :tag "Command")
1754 (sexp :tag "Lisp form")))))
1758 (defgroup org-refile nil
1759 "Options concerning refiling entries in Org-mode."
1760 :tag "Org Refile"
1761 :group 'org)
1763 (defcustom org-directory "~/org"
1764 "Directory with org files.
1765 This is just a default location to look for Org files. There is no need
1766 at all to put your files into this directory. It is only used in the
1767 following situations:
1769 1. When a remember template specifies a target file that is not an
1770 absolute path. The path will then be interpreted relative to
1771 `org-directory'
1772 2. When a remember note is filed away in an interactive way (when exiting the
1773 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1774 with `org-directory' as the default path."
1775 :group 'org-refile
1776 :group 'org-remember
1777 :type 'directory)
1779 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1780 "Default target for storing notes.
1781 Used as a fall back file for org-remember.el and org-capture.el, for
1782 templates that do not specify a target file."
1783 :group 'org-refile
1784 :group 'org-remember
1785 :type '(choice
1786 (const :tag "Default from remember-data-file" nil)
1787 file))
1789 (defcustom org-goto-interface 'outline
1790 "The default interface to be used for `org-goto'.
1791 Allowed values are:
1792 outline The interface shows an outline of the relevant file
1793 and the correct heading is found by moving through
1794 the outline or by searching with incremental search.
1795 outline-path-completion Headlines in the current buffer are offered via
1796 completion. This is the interface also used by
1797 the refile command."
1798 :group 'org-refile
1799 :type '(choice
1800 (const :tag "Outline" outline)
1801 (const :tag "Outline-path-completion" outline-path-completion)))
1803 (defcustom org-goto-max-level 5
1804 "Maximum target level when running `org-goto' with refile interface."
1805 :group 'org-refile
1806 :type 'integer)
1808 (defcustom org-reverse-note-order nil
1809 "Non-nil means store new notes at the beginning of a file or entry.
1810 When nil, new notes will be filed to the end of a file or entry.
1811 This can also be a list with cons cells of regular expressions that
1812 are matched against file names, and values."
1813 :group 'org-remember
1814 :group 'org-refile
1815 :type '(choice
1816 (const :tag "Reverse always" t)
1817 (const :tag "Reverse never" nil)
1818 (repeat :tag "By file name regexp"
1819 (cons regexp boolean))))
1821 (defcustom org-log-refile nil
1822 "Information to record when a task is refiled.
1824 Possible values are:
1826 nil Don't add anything
1827 time Add a time stamp to the task
1828 note Prompt for a note and add it with template `org-log-note-headings'
1830 This option can also be set with on a per-file-basis with
1832 #+STARTUP: nologrefile
1833 #+STARTUP: logrefile
1834 #+STARTUP: lognoterefile
1836 You can have local logging settings for a subtree by setting the LOGGING
1837 property to one or more of these keywords.
1839 When bulk-refiling from the agenda, the value `note' is forbidden and
1840 will temporarily be changed to `time'."
1841 :group 'org-refile
1842 :group 'org-progress
1843 :type '(choice
1844 (const :tag "No logging" nil)
1845 (const :tag "Record timestamp" time)
1846 (const :tag "Record timestamp with note." note)))
1848 (defcustom org-refile-targets nil
1849 "Targets for refiling entries with \\[org-refile].
1850 This is list of cons cells. Each cell contains:
1851 - a specification of the files to be considered, either a list of files,
1852 or a symbol whose function or variable value will be used to retrieve
1853 a file name or a list of file names. If you use `org-agenda-files' for
1854 that, all agenda files will be scanned for targets. Nil means consider
1855 headings in the current buffer.
1856 - A specification of how to find candidate refile targets. This may be
1857 any of:
1858 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1859 This tag has to be present in all target headlines, inheritance will
1860 not be considered.
1861 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1862 todo keyword.
1863 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1864 headlines that are refiling targets.
1865 - a cons cell (:level . N). Any headline of level N is considered a target.
1866 Note that, when `org-odd-levels-only' is set, level corresponds to
1867 order in hierarchy, not to the number of stars.
1868 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1869 Note that, when `org-odd-levels-only' is set, level corresponds to
1870 order in hierarchy, not to the number of stars.
1872 You can set the variable `org-refile-target-verify-function' to a function
1873 to verify each headline found by the simple criteria above.
1875 When this variable is nil, all top-level headlines in the current buffer
1876 are used, equivalent to the value `((nil . (:level . 1))'."
1877 :group 'org-refile
1878 :type '(repeat
1879 (cons
1880 (choice :value org-agenda-files
1881 (const :tag "All agenda files" org-agenda-files)
1882 (const :tag "Current buffer" nil)
1883 (function) (variable) (file))
1884 (choice :tag "Identify target headline by"
1885 (cons :tag "Specific tag" (const :value :tag) (string))
1886 (cons :tag "TODO keyword" (const :value :todo) (string))
1887 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1888 (cons :tag "Level number" (const :value :level) (integer))
1889 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1891 (defcustom org-refile-target-verify-function nil
1892 "Function to verify if the headline at point should be a refile target.
1893 The function will be called without arguments, with point at the
1894 beginning of the headline. It should return t and leave point
1895 where it is if the headline is a valid target for refiling.
1897 If the target should not be selected, the function must return nil.
1898 In addition to this, it may move point to a place from where the search
1899 should be continued. For example, the function may decide that the entire
1900 subtree of the current entry should be excluded and move point to the end
1901 of the subtree."
1902 :group 'org-refile
1903 :type 'function)
1905 (defcustom org-refile-use-cache nil
1906 "Non-nil means cache refile targets to speed up the process.
1907 The cache for a particular file will be updated automatically when
1908 the buffer has been killed, or when any of the marker used for flagging
1909 refile targets no longer points at a live buffer.
1910 If you have added new entries to a buffer that might themselves be targets,
1911 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1912 find that easier, `C-u C-u C-u C-c C-w'."
1913 :group 'org-refile
1914 :type 'boolean)
1916 (defcustom org-refile-use-outline-path nil
1917 "Non-nil means provide refile targets as paths.
1918 So a level 3 headline will be available as level1/level2/level3.
1920 When the value is `file', also include the file name (without directory)
1921 into the path. In this case, you can also stop the completion after
1922 the file name, to get entries inserted as top level in the file.
1924 When `full-file-path', include the full file path."
1925 :group 'org-refile
1926 :type '(choice
1927 (const :tag "Not" nil)
1928 (const :tag "Yes" t)
1929 (const :tag "Start with file name" file)
1930 (const :tag "Start with full file path" full-file-path)))
1932 (defcustom org-outline-path-complete-in-steps t
1933 "Non-nil means complete the outline path in hierarchical steps.
1934 When Org-mode uses the refile interface to select an outline path
1935 \(see variable `org-refile-use-outline-path'), the completion of
1936 the path can be done is a single go, or if can be done in steps down
1937 the headline hierarchy. Going in steps is probably the best if you
1938 do not use a special completion package like `ido' or `icicles'.
1939 However, when using these packages, going in one step can be very
1940 fast, while still showing the whole path to the entry."
1941 :group 'org-refile
1942 :type 'boolean)
1944 (defcustom org-refile-allow-creating-parent-nodes nil
1945 "Non-nil means allow to create new nodes as refile targets.
1946 New nodes are then created by adding \"/new node name\" to the completion
1947 of an existing node. When the value of this variable is `confirm',
1948 new node creation must be confirmed by the user (recommended)
1949 When nil, the completion must match an existing entry.
1951 Note that, if the new heading is not seen by the criteria
1952 listed in `org-refile-targets', multiple instances of the same
1953 heading would be created by trying again to file under the new
1954 heading."
1955 :group 'org-refile
1956 :type '(choice
1957 (const :tag "Never" nil)
1958 (const :tag "Always" t)
1959 (const :tag "Prompt for confirmation" confirm)))
1961 (defgroup org-todo nil
1962 "Options concerning TODO items in Org-mode."
1963 :tag "Org TODO"
1964 :group 'org)
1966 (defgroup org-progress nil
1967 "Options concerning Progress logging in Org-mode."
1968 :tag "Org Progress"
1969 :group 'org-time)
1971 (defvar org-todo-interpretation-widgets
1973 (:tag "Sequence (cycling hits every state)" sequence)
1974 (:tag "Type (cycling directly to DONE)" type))
1975 "The available interpretation symbols for customizing `org-todo-keywords'.
1976 Interested libraries should add to this list.")
1978 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1979 "List of TODO entry keyword sequences and their interpretation.
1980 \\<org-mode-map>This is a list of sequences.
1982 Each sequence starts with a symbol, either `sequence' or `type',
1983 indicating if the keywords should be interpreted as a sequence of
1984 action steps, or as different types of TODO items. The first
1985 keywords are states requiring action - these states will select a headline
1986 for inclusion into the global TODO list Org-mode produces. If one of
1987 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
1988 signify that no further action is necessary. If \"|\" is not found,
1989 the last keyword is treated as the only DONE state of the sequence.
1991 The command \\[org-todo] cycles an entry through these states, and one
1992 additional state where no keyword is present. For details about this
1993 cycling, see the manual.
1995 TODO keywords and interpretation can also be set on a per-file basis with
1996 the special #+SEQ_TODO and #+TYP_TODO lines.
1998 Each keyword can optionally specify a character for fast state selection
1999 \(in combination with the variable `org-use-fast-todo-selection')
2000 and specifiers for state change logging, using the same syntax
2001 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2002 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2003 indicates to record a time stamp each time this state is selected.
2005 Each keyword may also specify if a timestamp or a note should be
2006 recorded when entering or leaving the state, by adding additional
2007 characters in the parenthesis after the keyword. This looks like this:
2008 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2009 record only the time of the state change. With X and Y being either
2010 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2011 Y when leaving the state if and only if the *target* state does not
2012 define X. You may omit any of the fast-selection key or X or /Y,
2013 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2015 For backward compatibility, this variable may also be just a list
2016 of keywords - in this case the interpretation (sequence or type) will be
2017 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2018 :group 'org-todo
2019 :group 'org-keywords
2020 :type '(choice
2021 (repeat :tag "Old syntax, just keywords"
2022 (string :tag "Keyword"))
2023 (repeat :tag "New syntax"
2024 (cons
2025 (choice
2026 :tag "Interpretation"
2027 ;;Quick and dirty way to see
2028 ;;`org-todo-interpretations'. This takes the
2029 ;;place of item arguments
2030 :convert-widget
2031 (lambda (widget)
2032 (widget-put widget
2033 :args (mapcar
2034 #'(lambda (x)
2035 (widget-convert
2036 (cons 'const x)))
2037 org-todo-interpretation-widgets))
2038 widget))
2039 (repeat
2040 (string :tag "Keyword"))))))
2042 (defvar org-todo-keywords-1 nil
2043 "All TODO and DONE keywords active in a buffer.")
2044 (make-variable-buffer-local 'org-todo-keywords-1)
2045 (defvar org-todo-keywords-for-agenda nil)
2046 (defvar org-done-keywords-for-agenda nil)
2047 (defvar org-drawers-for-agenda nil)
2048 (defvar org-todo-keyword-alist-for-agenda nil)
2049 (defvar org-tag-alist-for-agenda nil)
2050 (defvar org-agenda-contributing-files nil)
2051 (defvar org-not-done-keywords nil)
2052 (make-variable-buffer-local 'org-not-done-keywords)
2053 (defvar org-done-keywords nil)
2054 (make-variable-buffer-local 'org-done-keywords)
2055 (defvar org-todo-heads nil)
2056 (make-variable-buffer-local 'org-todo-heads)
2057 (defvar org-todo-sets nil)
2058 (make-variable-buffer-local 'org-todo-sets)
2059 (defvar org-todo-log-states nil)
2060 (make-variable-buffer-local 'org-todo-log-states)
2061 (defvar org-todo-kwd-alist nil)
2062 (make-variable-buffer-local 'org-todo-kwd-alist)
2063 (defvar org-todo-key-alist nil)
2064 (make-variable-buffer-local 'org-todo-key-alist)
2065 (defvar org-todo-key-trigger nil)
2066 (make-variable-buffer-local 'org-todo-key-trigger)
2068 (defcustom org-todo-interpretation 'sequence
2069 "Controls how TODO keywords are interpreted.
2070 This variable is in principle obsolete and is only used for
2071 backward compatibility, if the interpretation of todo keywords is
2072 not given already in `org-todo-keywords'. See that variable for
2073 more information."
2074 :group 'org-todo
2075 :group 'org-keywords
2076 :type '(choice (const sequence)
2077 (const type)))
2079 (defcustom org-use-fast-todo-selection t
2080 "Non-nil means use the fast todo selection scheme with C-c C-t.
2081 This variable describes if and under what circumstances the cycling
2082 mechanism for TODO keywords will be replaced by a single-key, direct
2083 selection scheme.
2085 When nil, fast selection is never used.
2087 When the symbol `prefix', it will be used when `org-todo' is called with
2088 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2089 in an agenda buffer.
2091 When t, fast selection is used by default. In this case, the prefix
2092 argument forces cycling instead.
2094 In all cases, the special interface is only used if access keys have actually
2095 been assigned by the user, i.e. if keywords in the configuration are followed
2096 by a letter in parenthesis, like TODO(t)."
2097 :group 'org-todo
2098 :type '(choice
2099 (const :tag "Never" nil)
2100 (const :tag "By default" t)
2101 (const :tag "Only with C-u C-c C-t" prefix)))
2103 (defcustom org-provide-todo-statistics t
2104 "Non-nil means update todo statistics after insert and toggle.
2105 ALL-HEADLINES means update todo statistics by including headlines
2106 with no TODO keyword as well, counting them as not done.
2107 A list of TODO keywords means the same, but skip keywords that are
2108 not in this list.
2110 When this is set, todo statistics is updated in the parent of the
2111 current entry each time a todo state is changed."
2112 :group 'org-todo
2113 :type '(choice
2114 (const :tag "Yes, only for TODO entries" t)
2115 (const :tag "Yes, including all entries" 'all-headlines)
2116 (repeat :tag "Yes, for TODOs in this list"
2117 (string :tag "TODO keyword"))
2118 (other :tag "No TODO statistics" nil)))
2120 (defcustom org-hierarchical-todo-statistics t
2121 "Non-nil means TODO statistics covers just direct children.
2122 When nil, all entries in the subtree are considered.
2123 This has only an effect if `org-provide-todo-statistics' is set.
2124 To set this to nil for only a single subtree, use a COOKIE_DATA
2125 property and include the word \"recursive\" into the value."
2126 :group 'org-todo
2127 :type 'boolean)
2129 (defcustom org-after-todo-state-change-hook nil
2130 "Hook which is run after the state of a TODO item was changed.
2131 The new state (a string with a TODO keyword, or nil) is available in the
2132 Lisp variable `state'."
2133 :group 'org-todo
2134 :type 'hook)
2136 (defvar org-blocker-hook nil
2137 "Hook for functions that are allowed to block a state change.
2139 Each function gets as its single argument a property list, see
2140 `org-trigger-hook' for more information about this list.
2142 If any of the functions in this hook returns nil, the state change
2143 is blocked.")
2145 (defvar org-trigger-hook nil
2146 "Hook for functions that are triggered by a state change.
2148 Each function gets as its single argument a property list with at least
2149 the following elements:
2151 (:type type-of-change :position pos-at-entry-start
2152 :from old-state :to new-state)
2154 Depending on the type, more properties may be present.
2156 This mechanism is currently implemented for:
2158 TODO state changes
2159 ------------------
2160 :type todo-state-change
2161 :from previous state (keyword as a string), or nil, or a symbol
2162 'todo' or 'done', to indicate the general type of state.
2163 :to new state, like in :from")
2165 (defcustom org-enforce-todo-dependencies nil
2166 "Non-nil means undone TODO entries will block switching the parent to DONE.
2167 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2168 be blocked if any prior sibling is not yet done.
2169 Finally, if the parent is blocked because of ordered siblings of its own,
2170 the child will also be blocked.
2171 This variable needs to be set before org.el is loaded, and you need to
2172 restart Emacs after a change to make the change effective. The only way
2173 to change is while Emacs is running is through the customize interface."
2174 :set (lambda (var val)
2175 (set var val)
2176 (if val
2177 (add-hook 'org-blocker-hook
2178 'org-block-todo-from-children-or-siblings-or-parent)
2179 (remove-hook 'org-blocker-hook
2180 'org-block-todo-from-children-or-siblings-or-parent)))
2181 :group 'org-todo
2182 :type 'boolean)
2184 (defcustom org-enforce-todo-checkbox-dependencies nil
2185 "Non-nil means unchecked boxes will block switching the parent to DONE.
2186 When this is nil, checkboxes have no influence on switching TODO states.
2187 When non-nil, you first need to check off all check boxes before the TODO
2188 entry can be switched to DONE.
2189 This variable needs to be set before org.el is loaded, and you need to
2190 restart Emacs after a change to make the change effective. The only way
2191 to change is while Emacs is running is through the customize interface."
2192 :set (lambda (var val)
2193 (set var val)
2194 (if val
2195 (add-hook 'org-blocker-hook
2196 'org-block-todo-from-checkboxes)
2197 (remove-hook 'org-blocker-hook
2198 'org-block-todo-from-checkboxes)))
2199 :group 'org-todo
2200 :type 'boolean)
2202 (defcustom org-treat-insert-todo-heading-as-state-change nil
2203 "Non-nil means inserting a TODO heading is treated as state change.
2204 So when the command \\[org-insert-todo-heading] is used, state change
2205 logging will apply if appropriate. When nil, the new TODO item will
2206 be inserted directly, and no logging will take place."
2207 :group 'org-todo
2208 :type 'boolean)
2210 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2211 "Non-nil means switching TODO states with S-cursor counts as state change.
2212 This is the default behavior. However, setting this to nil allows a
2213 convenient way to select a TODO state and bypass any logging associated
2214 with that."
2215 :group 'org-todo
2216 :type 'boolean)
2218 (defcustom org-todo-state-tags-triggers nil
2219 "Tag changes that should be triggered by TODO state changes.
2220 This is a list. Each entry is
2222 (state-change (tag . flag) .......)
2224 State-change can be a string with a state, and empty string to indicate the
2225 state that has no TODO keyword, or it can be one of the symbols `todo'
2226 or `done', meaning any not-done or done state, respectively."
2227 :group 'org-todo
2228 :group 'org-tags
2229 :type '(repeat
2230 (cons (choice :tag "When changing to"
2231 (const :tag "Not-done state" todo)
2232 (const :tag "Done state" done)
2233 (string :tag "State"))
2234 (repeat
2235 (cons :tag "Tag action"
2236 (string :tag "Tag")
2237 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2239 (defcustom org-log-done nil
2240 "Information to record when a task moves to the DONE state.
2242 Possible values are:
2244 nil Don't add anything, just change the keyword
2245 time Add a time stamp to the task
2246 note Prompt for a note and add it with template `org-log-note-headings'
2248 This option can also be set with on a per-file-basis with
2250 #+STARTUP: nologdone
2251 #+STARTUP: logdone
2252 #+STARTUP: lognotedone
2254 You can have local logging settings for a subtree by setting the LOGGING
2255 property to one or more of these keywords."
2256 :group 'org-todo
2257 :group 'org-progress
2258 :type '(choice
2259 (const :tag "No logging" nil)
2260 (const :tag "Record CLOSED timestamp" time)
2261 (const :tag "Record CLOSED timestamp with note." note)))
2263 ;; Normalize old uses of org-log-done.
2264 (cond
2265 ((eq org-log-done t) (setq org-log-done 'time))
2266 ((and (listp org-log-done) (memq 'done org-log-done))
2267 (setq org-log-done 'note)))
2269 (defcustom org-log-reschedule nil
2270 "Information to record when the scheduling date of a tasks is modified.
2272 Possible values are:
2274 nil Don't add anything, just change the date
2275 time Add a time stamp to the task
2276 note Prompt for a note and add it with template `org-log-note-headings'
2278 This option can also be set with on a per-file-basis with
2280 #+STARTUP: nologreschedule
2281 #+STARTUP: logreschedule
2282 #+STARTUP: lognotereschedule"
2283 :group 'org-todo
2284 :group 'org-progress
2285 :type '(choice
2286 (const :tag "No logging" nil)
2287 (const :tag "Record timestamp" time)
2288 (const :tag "Record timestamp with note." note)))
2290 (defcustom org-log-redeadline nil
2291 "Information to record when the deadline date of a tasks is modified.
2293 Possible values are:
2295 nil Don't add anything, just change the date
2296 time Add a time stamp to the task
2297 note Prompt for a note and add it with template `org-log-note-headings'
2299 This option can also be set with on a per-file-basis with
2301 #+STARTUP: nologredeadline
2302 #+STARTUP: logredeadline
2303 #+STARTUP: lognoteredeadline
2305 You can have local logging settings for a subtree by setting the LOGGING
2306 property to one or more of these keywords."
2307 :group 'org-todo
2308 :group 'org-progress
2309 :type '(choice
2310 (const :tag "No logging" nil)
2311 (const :tag "Record timestamp" time)
2312 (const :tag "Record timestamp with note." note)))
2314 (defcustom org-log-note-clock-out nil
2315 "Non-nil means record a note when clocking out of an item.
2316 This can also be configured on a per-file basis by adding one of
2317 the following lines anywhere in the buffer:
2319 #+STARTUP: lognoteclock-out
2320 #+STARTUP: nolognoteclock-out"
2321 :group 'org-todo
2322 :group 'org-progress
2323 :type 'boolean)
2325 (defcustom org-log-done-with-time t
2326 "Non-nil means the CLOSED time stamp will contain date and time.
2327 When nil, only the date will be recorded."
2328 :group 'org-progress
2329 :type 'boolean)
2331 (defcustom org-log-note-headings
2332 '((done . "CLOSING NOTE %t")
2333 (state . "State %-12s from %-12S %t")
2334 (note . "Note taken on %t")
2335 (reschedule . "Rescheduled from %S on %t")
2336 (delschedule . "Not scheduled, was %S on %t")
2337 (redeadline . "New deadline from %S on %t")
2338 (deldeadline . "Removed deadline, was %S on %t")
2339 (refile . "Refiled on %t")
2340 (clock-out . ""))
2341 "Headings for notes added to entries.
2342 The value is an alist, with the car being a symbol indicating the note
2343 context, and the cdr is the heading to be used. The heading may also be the
2344 empty string.
2345 %t in the heading will be replaced by a time stamp.
2346 %T will be an active time stamp instead the default inactive one
2347 %s will be replaced by the new TODO state, in double quotes.
2348 %S will be replaced by the old TODO state, in double quotes.
2349 %u will be replaced by the user name.
2350 %U will be replaced by the full user name.
2352 In fact, it is not a good idea to change the `state' entry, because
2353 agenda log mode depends on the format of these entries."
2354 :group 'org-todo
2355 :group 'org-progress
2356 :type '(list :greedy t
2357 (cons (const :tag "Heading when closing an item" done) string)
2358 (cons (const :tag
2359 "Heading when changing todo state (todo sequence only)"
2360 state) string)
2361 (cons (const :tag "Heading when just taking a note" note) string)
2362 (cons (const :tag "Heading when clocking out" clock-out) string)
2363 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2364 (cons (const :tag "Heading when rescheduling" reschedule) string)
2365 (cons (const :tag "Heading when changing deadline" redeadline) string)
2366 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2367 (cons (const :tag "Heading when refiling" refile) string)))
2369 (unless (assq 'note org-log-note-headings)
2370 (push '(note . "%t") org-log-note-headings))
2372 (defcustom org-log-into-drawer nil
2373 "Non-nil means insert state change notes and time stamps into a drawer.
2374 When nil, state changes notes will be inserted after the headline and
2375 any scheduling and clock lines, but not inside a drawer.
2377 The value of this variable should be the name of the drawer to use.
2378 LOGBOOK is proposed at the default drawer for this purpose, you can
2379 also set this to a string to define the drawer of your choice.
2381 A value of t is also allowed, representing \"LOGBOOK\".
2383 If this variable is set, `org-log-state-notes-insert-after-drawers'
2384 will be ignored.
2386 You can set the property LOG_INTO_DRAWER to overrule this setting for
2387 a subtree."
2388 :group 'org-todo
2389 :group 'org-progress
2390 :type '(choice
2391 (const :tag "Not into a drawer" nil)
2392 (const :tag "LOGBOOK" t)
2393 (string :tag "Other")))
2395 (if (fboundp 'defvaralias)
2396 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2398 (defun org-log-into-drawer ()
2399 "Return the value of `org-log-into-drawer', but let properties overrule.
2400 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2401 used instead of the default value."
2402 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2403 (cond
2404 ((or (not p) (equal p "nil")) org-log-into-drawer)
2405 ((equal p "t") "LOGBOOK")
2406 (t p))))
2408 (defcustom org-log-state-notes-insert-after-drawers nil
2409 "Non-nil means insert state change notes after any drawers in entry.
2410 Only the drawers that *immediately* follow the headline and the
2411 deadline/scheduled line are skipped.
2412 When nil, insert notes right after the heading and perhaps the line
2413 with deadline/scheduling if present.
2415 This variable will have no effect if `org-log-into-drawer' is
2416 set."
2417 :group 'org-todo
2418 :group 'org-progress
2419 :type 'boolean)
2421 (defcustom org-log-states-order-reversed t
2422 "Non-nil means the latest state note will be directly after heading.
2423 When nil, the state change notes will be ordered according to time."
2424 :group 'org-todo
2425 :group 'org-progress
2426 :type 'boolean)
2428 (defcustom org-todo-repeat-to-state nil
2429 "The TODO state to which a repeater should return the repeating task.
2430 By default this is the first task in a TODO sequence, or the previous state
2431 in a TODO_TYP set. But you can specify another task here.
2432 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2433 :group 'org-todo
2434 :type '(choice (const :tag "Head of sequence" nil)
2435 (string :tag "Specific state")))
2437 (defcustom org-log-repeat 'time
2438 "Non-nil means record moving through the DONE state when triggering repeat.
2439 An auto-repeating task is immediately switched back to TODO when
2440 marked DONE. If you are not logging state changes (by adding \"@\"
2441 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2442 record a closing note, there will be no record of the task moving
2443 through DONE. This variable forces taking a note anyway.
2445 nil Don't force a record
2446 time Record a time stamp
2447 note Record a note
2449 This option can also be set with on a per-file-basis with
2451 #+STARTUP: logrepeat
2452 #+STARTUP: lognoterepeat
2453 #+STARTUP: nologrepeat
2455 You can have local logging settings for a subtree by setting the LOGGING
2456 property to one or more of these keywords."
2457 :group 'org-todo
2458 :group 'org-progress
2459 :type '(choice
2460 (const :tag "Don't force a record" nil)
2461 (const :tag "Force recording the DONE state" time)
2462 (const :tag "Force recording a note with the DONE state" note)))
2465 (defgroup org-priorities nil
2466 "Priorities in Org-mode."
2467 :tag "Org Priorities"
2468 :group 'org-todo)
2470 (defcustom org-enable-priority-commands t
2471 "Non-nil means priority commands are active.
2472 When nil, these commands will be disabled, so that you never accidentally
2473 set a priority."
2474 :group 'org-priorities
2475 :type 'boolean)
2477 (defcustom org-highest-priority ?A
2478 "The highest priority of TODO items. A character like ?A, ?B etc.
2479 Must have a smaller ASCII number than `org-lowest-priority'."
2480 :group 'org-priorities
2481 :type 'character)
2483 (defcustom org-lowest-priority ?C
2484 "The lowest priority of TODO items. A character like ?A, ?B etc.
2485 Must have a larger ASCII number than `org-highest-priority'."
2486 :group 'org-priorities
2487 :type 'character)
2489 (defcustom org-default-priority ?B
2490 "The default priority of TODO items.
2491 This is the priority an item gets if no explicit priority is given.
2492 When starting to cycle on an empty priority the first step in the cycle
2493 depends on `org-priority-start-cycle-with-default'. The resulting first
2494 step priority must not exceed the range from `org-highest-priority' to
2495 `org-lowest-priority' which means that `org-default-priority' has to be
2496 in this range exclusive or inclusive the range boundaries. Else the
2497 first step refuses to set the default and the second will fall back
2498 to (depending on the command used) the highest or lowest priority."
2499 :group 'org-priorities
2500 :type 'character)
2502 (defcustom org-priority-start-cycle-with-default t
2503 "Non-nil means start with default priority when starting to cycle.
2504 When this is nil, the first step in the cycle will be (depending on the
2505 command used) one higher or lower than the default priority.
2506 See also `org-default-priority'."
2507 :group 'org-priorities
2508 :type 'boolean)
2510 (defcustom org-get-priority-function nil
2511 "Function to extract the priority from a string.
2512 The string is normally the headline. If this is nil Org computes the
2513 priority from the priority cookie like [#A] in the headline. It returns
2514 an integer, increasing by 1000 for each priority level.
2515 The user can set a different function here, which should take a string
2516 as an argument and return the numeric priority."
2517 :group 'org-priorities
2518 :type 'function)
2520 (defgroup org-time nil
2521 "Options concerning time stamps and deadlines in Org-mode."
2522 :tag "Org Time"
2523 :group 'org)
2525 (defcustom org-insert-labeled-timestamps-at-point nil
2526 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2527 When nil, these labeled time stamps are forces into the second line of an
2528 entry, just after the headline. When scheduling from the global TODO list,
2529 the time stamp will always be forced into the second line."
2530 :group 'org-time
2531 :type 'boolean)
2533 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2534 "Formats for `format-time-string' which are used for time stamps.
2535 It is not recommended to change this constant.")
2537 (defcustom org-time-stamp-rounding-minutes '(0 5)
2538 "Number of minutes to round time stamps to.
2539 These are two values, the first applies when first creating a time stamp.
2540 The second applies when changing it with the commands `S-up' and `S-down'.
2541 When changing the time stamp, this means that it will change in steps
2542 of N minutes, as given by the second value.
2544 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2545 numbers should be factors of 60, so for example 5, 10, 15.
2547 When this is larger than 1, you can still force an exact time stamp by using
2548 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2549 and by using a prefix arg to `S-up/down' to specify the exact number
2550 of minutes to shift."
2551 :group 'org-time
2552 :get '(lambda (var) ; Make sure both elements are there
2553 (if (integerp (default-value var))
2554 (list (default-value var) 5)
2555 (default-value var)))
2556 :type '(list
2557 (integer :tag "when inserting times")
2558 (integer :tag "when modifying times")))
2560 ;; Normalize old customizations of this variable.
2561 (when (integerp org-time-stamp-rounding-minutes)
2562 (setq org-time-stamp-rounding-minutes
2563 (list org-time-stamp-rounding-minutes
2564 org-time-stamp-rounding-minutes)))
2566 (defcustom org-display-custom-times nil
2567 "Non-nil means overlay custom formats over all time stamps.
2568 The formats are defined through the variable `org-time-stamp-custom-formats'.
2569 To turn this on on a per-file basis, insert anywhere in the file:
2570 #+STARTUP: customtime"
2571 :group 'org-time
2572 :set 'set-default
2573 :type 'sexp)
2574 (make-variable-buffer-local 'org-display-custom-times)
2576 (defcustom org-time-stamp-custom-formats
2577 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2578 "Custom formats for time stamps. See `format-time-string' for the syntax.
2579 These are overlayed over the default ISO format if the variable
2580 `org-display-custom-times' is set. Time like %H:%M should be at the
2581 end of the second format. The custom formats are also honored by export
2582 commands, if custom time display is turned on at the time of export."
2583 :group 'org-time
2584 :type 'sexp)
2586 (defun org-time-stamp-format (&optional long inactive)
2587 "Get the right format for a time string."
2588 (let ((f (if long (cdr org-time-stamp-formats)
2589 (car org-time-stamp-formats))))
2590 (if inactive
2591 (concat "[" (substring f 1 -1) "]")
2592 f)))
2594 (defcustom org-time-clocksum-format "%d:%02d"
2595 "The format string used when creating CLOCKSUM lines.
2596 This is also used when org-mode generates a time duration."
2597 :group 'org-time
2598 :type 'string)
2600 (defcustom org-time-clocksum-use-fractional nil
2601 "If non-nil, \\[org-clock-display] uses fractional times.
2602 org-mode generates a time duration."
2603 :group 'org-time
2604 :type 'boolean)
2606 (defcustom org-time-clocksum-fractional-format "%.2f"
2607 "The format string used when creating CLOCKSUM lines, or when
2608 org-mode generates a time duration."
2609 :group 'org-time
2610 :type 'string)
2612 (defcustom org-deadline-warning-days 14
2613 "No. of days before expiration during which a deadline becomes active.
2614 This variable governs the display in sparse trees and in the agenda.
2615 When 0 or negative, it means use this number (the absolute value of it)
2616 even if a deadline has a different individual lead time specified.
2618 Custom commands can set this variable in the options section."
2619 :group 'org-time
2620 :group 'org-agenda-daily/weekly
2621 :type 'integer)
2623 (defcustom org-read-date-prefer-future t
2624 "Non-nil means assume future for incomplete date input from user.
2625 This affects the following situations:
2626 1. The user gives a month but not a year.
2627 For example, if it is April and you enter \"feb 2\", this will be read
2628 as Feb 2, *next* year. \"May 5\", however, will be this year.
2629 2. The user gives a day, but no month.
2630 For example, if today is the 15th, and you enter \"3\", Org-mode will
2631 read this as the third of *next* month. However, if you enter \"17\",
2632 it will be considered as *this* month.
2634 If you set this variable to the symbol `time', then also the following
2635 will work:
2637 3. If the user gives a time, but no day. If the time is before now,
2638 to will be interpreted as tomorrow.
2640 Currently none of this works for ISO week specifications.
2642 When this option is nil, the current day, month and year will always be
2643 used as defaults.
2645 See also `org-agenda-jump-prefer-future'."
2646 :group 'org-time
2647 :type '(choice
2648 (const :tag "Never" nil)
2649 (const :tag "Check month and day" t)
2650 (const :tag "Check month, day, and time" time)))
2652 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2653 "Should the agenda jump command prefer the future for incomplete dates?
2654 The default is to do the same as configured in `org-read-date-prefer-future'.
2655 But you can also set a deviating value here.
2656 This may t or nil, or the symbol `org-read-date-prefer-future'."
2657 :group 'org-agenda
2658 :group 'org-time
2659 :type '(choice
2660 (const :tag "Use org-read-date-prefer-future"
2661 org-read-date-prefer-future)
2662 (const :tag "Never" nil)
2663 (const :tag "Always" t)))
2665 (defcustom org-read-date-force-compatible-dates t
2666 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2668 Depending on the system Emacs is running on, certain dates cannot
2669 be represented with the type used internally to represent time.
2670 Dates between 1970-1-1 and 2038-1-1 can always be represented
2671 correctly. Some systems allow for earlier dates, some for later,
2672 some for both. One way to find out it to insert any date into an
2673 Org buffer, putting the cursor on the year and hitting S-up and
2674 S-down to test the range.
2676 When this variable is set to t, the date/time prompt will not let
2677 you specify dates outside the 1970-2037 range, so it is certain that
2678 these dates will work in whatever version of Emacs you are
2679 running, and also that you can move a file from one Emacs implementation
2680 to another. WHenever Org is forcing the year for you, it will display
2681 a message and beep.
2683 When this variable is nil, Org will check if the date is
2684 representable in the specific Emacs implementation you are using.
2685 If not, it will force a year, usually the current year, and beep
2686 to remind you. Currently this setting is not recommended because
2687 the likelihood that you will open your Org files in an Emacs that
2688 has limited date range is not negligible.
2690 A workaround for this problem is to use diary sexp dates for time
2691 stamps outside of this range."
2692 :group 'org-time
2693 :type 'boolean)
2695 (defcustom org-read-date-display-live t
2696 "Non-nil means display current interpretation of date prompt live.
2697 This display will be in an overlay, in the minibuffer."
2698 :group 'org-time
2699 :type 'boolean)
2701 (defcustom org-read-date-popup-calendar t
2702 "Non-nil means pop up a calendar when prompting for a date.
2703 In the calendar, the date can be selected with mouse-1. However, the
2704 minibuffer will also be active, and you can simply enter the date as well.
2705 When nil, only the minibuffer will be available."
2706 :group 'org-time
2707 :type 'boolean)
2708 (if (fboundp 'defvaralias)
2709 (defvaralias 'org-popup-calendar-for-date-prompt
2710 'org-read-date-popup-calendar))
2712 (defcustom org-read-date-minibuffer-setup-hook nil
2713 "Hook to be used to set up keys for the date/time interface.
2714 Add key definitions to `minibuffer-local-map', which will be a temporary
2715 copy."
2716 :group 'org-time
2717 :type 'hook)
2719 (defcustom org-extend-today-until 0
2720 "The hour when your day really ends. Must be an integer.
2721 This has influence for the following applications:
2722 - When switching the agenda to \"today\". It it is still earlier than
2723 the time given here, the day recognized as TODAY is actually yesterday.
2724 - When a date is read from the user and it is still before the time given
2725 here, the current date and time will be assumed to be yesterday, 23:59.
2726 Also, timestamps inserted in remember templates follow this rule.
2728 IMPORTANT: This is a feature whose implementation is and likely will
2729 remain incomplete. Really, it is only here because past midnight seems to
2730 be the favorite working time of John Wiegley :-)"
2731 :group 'org-time
2732 :type 'integer)
2734 (defcustom org-edit-timestamp-down-means-later nil
2735 "Non-nil means S-down will increase the time in a time stamp.
2736 When nil, S-up will increase."
2737 :group 'org-time
2738 :type 'boolean)
2740 (defcustom org-calendar-follow-timestamp-change t
2741 "Non-nil means make the calendar window follow timestamp changes.
2742 When a timestamp is modified and the calendar window is visible, it will be
2743 moved to the new date."
2744 :group 'org-time
2745 :type 'boolean)
2747 (defgroup org-tags nil
2748 "Options concerning tags in Org-mode."
2749 :tag "Org Tags"
2750 :group 'org)
2752 (defcustom org-tag-alist nil
2753 "List of tags allowed in Org-mode files.
2754 When this list is nil, Org-mode will base TAG input on what is already in the
2755 buffer.
2756 The value of this variable is an alist, the car of each entry must be a
2757 keyword as a string, the cdr may be a character that is used to select
2758 that tag through the fast-tag-selection interface.
2759 See the manual for details."
2760 :group 'org-tags
2761 :type '(repeat
2762 (choice
2763 (cons (string :tag "Tag name")
2764 (character :tag "Access char"))
2765 (list :tag "Start radio group"
2766 (const :startgroup)
2767 (option (string :tag "Group description")))
2768 (list :tag "End radio group"
2769 (const :endgroup)
2770 (option (string :tag "Group description")))
2771 (const :tag "New line" (:newline)))))
2773 (defcustom org-tag-persistent-alist nil
2774 "List of tags that will always appear in all Org-mode files.
2775 This is in addition to any in buffer settings or customizations
2776 of `org-tag-alist'.
2777 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2778 The value of this variable is an alist, the car of each entry must be a
2779 keyword as a string, the cdr may be a character that is used to select
2780 that tag through the fast-tag-selection interface.
2781 See the manual for details.
2782 To disable these tags on a per-file basis, insert anywhere in the file:
2783 #+STARTUP: noptag"
2784 :group 'org-tags
2785 :type '(repeat
2786 (choice
2787 (cons (string :tag "Tag name")
2788 (character :tag "Access char"))
2789 (const :tag "Start radio group" (:startgroup))
2790 (const :tag "End radio group" (:endgroup))
2791 (const :tag "New line" (:newline)))))
2793 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2794 "If non-nil, always offer completion for all tags of all agenda files.
2795 Instead of customizing this variable directly, you might want to
2796 set it locally for capture buffers, because there no list of
2797 tags in that file can be created dynamically (there are none).
2799 (add-hook 'org-capture-mode-hook
2800 (lambda ()
2801 (set (make-local-variable
2802 'org-complete-tags-always-offer-all-agenda-tags)
2803 t)))"
2804 :group 'org-tags
2805 :type 'boolean)
2807 (defvar org-file-tags nil
2808 "List of tags that can be inherited by all entries in the file.
2809 The tags will be inherited if the variable `org-use-tag-inheritance'
2810 says they should be.
2811 This variable is populated from #+FILETAGS lines.")
2813 (defcustom org-use-fast-tag-selection 'auto
2814 "Non-nil means use fast tag selection scheme.
2815 This is a special interface to select and deselect tags with single keys.
2816 When nil, fast selection is never used.
2817 When the symbol `auto', fast selection is used if and only if selection
2818 characters for tags have been configured, either through the variable
2819 `org-tag-alist' or through a #+TAGS line in the buffer.
2820 When t, fast selection is always used and selection keys are assigned
2821 automatically if necessary."
2822 :group 'org-tags
2823 :type '(choice
2824 (const :tag "Always" t)
2825 (const :tag "Never" nil)
2826 (const :tag "When selection characters are configured" 'auto)))
2828 (defcustom org-fast-tag-selection-single-key nil
2829 "Non-nil means fast tag selection exits after first change.
2830 When nil, you have to press RET to exit it.
2831 During fast tag selection, you can toggle this flag with `C-c'.
2832 This variable can also have the value `expert'. In this case, the window
2833 displaying the tags menu is not even shown, until you press C-c again."
2834 :group 'org-tags
2835 :type '(choice
2836 (const :tag "No" nil)
2837 (const :tag "Yes" t)
2838 (const :tag "Expert" expert)))
2840 (defvar org-fast-tag-selection-include-todo nil
2841 "Non-nil means fast tags selection interface will also offer TODO states.
2842 This is an undocumented feature, you should not rely on it.")
2844 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2845 "The column to which tags should be indented in a headline.
2846 If this number is positive, it specifies the column. If it is negative,
2847 it means that the tags should be flushright to that column. For example,
2848 -80 works well for a normal 80 character screen."
2849 :group 'org-tags
2850 :type 'integer)
2852 (defcustom org-auto-align-tags t
2853 "Non-nil means realign tags after pro/demotion of TODO state change.
2854 These operations change the length of a headline and therefore shift
2855 the tags around. With this options turned on, after each such operation
2856 the tags are again aligned to `org-tags-column'."
2857 :group 'org-tags
2858 :type 'boolean)
2860 (defcustom org-use-tag-inheritance t
2861 "Non-nil means tags in levels apply also for sublevels.
2862 When nil, only the tags directly given in a specific line apply there.
2863 This may also be a list of tags that should be inherited, or a regexp that
2864 matches tags that should be inherited. Additional control is possible
2865 with the variable `org-tags-exclude-from-inheritance' which gives an
2866 explicit list of tags to be excluded from inheritance., even if the value of
2867 `org-use-tag-inheritance' would select it for inheritance.
2869 If this option is t, a match early-on in a tree can lead to a large
2870 number of matches in the subtree when constructing the agenda or creating
2871 a sparse tree. If you only want to see the first match in a tree during
2872 a search, check out the variable `org-tags-match-list-sublevels'."
2873 :group 'org-tags
2874 :type '(choice
2875 (const :tag "Not" nil)
2876 (const :tag "Always" t)
2877 (repeat :tag "Specific tags" (string :tag "Tag"))
2878 (regexp :tag "Tags matched by regexp")))
2880 (defcustom org-tags-exclude-from-inheritance nil
2881 "List of tags that should never be inherited.
2882 This is a way to exclude a few tags from inheritance. For way to do
2883 the opposite, to actively allow inheritance for selected tags,
2884 see the variable `org-use-tag-inheritance'."
2885 :group 'org-tags
2886 :type '(repeat (string :tag "Tag")))
2888 (defun org-tag-inherit-p (tag)
2889 "Check if TAG is one that should be inherited."
2890 (cond
2891 ((member tag org-tags-exclude-from-inheritance) nil)
2892 ((eq org-use-tag-inheritance t) t)
2893 ((not org-use-tag-inheritance) nil)
2894 ((stringp org-use-tag-inheritance)
2895 (string-match org-use-tag-inheritance tag))
2896 ((listp org-use-tag-inheritance)
2897 (member tag org-use-tag-inheritance))
2898 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2900 (defcustom org-tags-match-list-sublevels t
2901 "Non-nil means list also sublevels of headlines matching a search.
2902 This variable applies to tags/property searches, and also to stuck
2903 projects because this search is based on a tags match as well.
2905 When set to the symbol `indented', sublevels are indented with
2906 leading dots.
2908 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2909 the sublevels of a headline matching a tag search often also match
2910 the same search. Listing all of them can create very long lists.
2911 Setting this variable to nil causes subtrees of a match to be skipped.
2913 This variable is semi-obsolete and probably should always be true. It
2914 is better to limit inheritance to certain tags using the variables
2915 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2916 :group 'org-tags
2917 :type '(choice
2918 (const :tag "No, don't list them" nil)
2919 (const :tag "Yes, do list them" t)
2920 (const :tag "List them, indented with leading dots" indented)))
2922 (defcustom org-tags-sort-function nil
2923 "When set, tags are sorted using this function as a comparator."
2924 :group 'org-tags
2925 :type '(choice
2926 (const :tag "No sorting" nil)
2927 (const :tag "Alphabetical" string<)
2928 (const :tag "Reverse alphabetical" string>)
2929 (function :tag "Custom function" nil)))
2931 (defvar org-tags-history nil
2932 "History of minibuffer reads for tags.")
2933 (defvar org-last-tags-completion-table nil
2934 "The last used completion table for tags.")
2935 (defvar org-after-tags-change-hook nil
2936 "Hook that is run after the tags in a line have changed.")
2938 (defgroup org-properties nil
2939 "Options concerning properties in Org-mode."
2940 :tag "Org Properties"
2941 :group 'org)
2943 (defcustom org-property-format "%-10s %s"
2944 "How property key/value pairs should be formatted by `indent-line'.
2945 When `indent-line' hits a property definition, it will format the line
2946 according to this format, mainly to make sure that the values are
2947 lined-up with respect to each other."
2948 :group 'org-properties
2949 :type 'string)
2951 (defcustom org-use-property-inheritance nil
2952 "Non-nil means properties apply also for sublevels.
2954 This setting is chiefly used during property searches. Turning it on can
2955 cause significant overhead when doing a search, which is why it is not
2956 on by default.
2958 When nil, only the properties directly given in the current entry count.
2959 When t, every property is inherited. The value may also be a list of
2960 properties that should have inheritance, or a regular expression matching
2961 properties that should be inherited.
2963 However, note that some special properties use inheritance under special
2964 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2965 and the properties ending in \"_ALL\" when they are used as descriptor
2966 for valid values of a property.
2968 Note for programmers:
2969 When querying an entry with `org-entry-get', you can control if inheritance
2970 should be used. By default, `org-entry-get' looks only at the local
2971 properties. You can request inheritance by setting the inherit argument
2972 to t (to force inheritance) or to `selective' (to respect the setting
2973 in this variable)."
2974 :group 'org-properties
2975 :type '(choice
2976 (const :tag "Not" nil)
2977 (const :tag "Always" t)
2978 (repeat :tag "Specific properties" (string :tag "Property"))
2979 (regexp :tag "Properties matched by regexp")))
2981 (defun org-property-inherit-p (property)
2982 "Check if PROPERTY is one that should be inherited."
2983 (cond
2984 ((eq org-use-property-inheritance t) t)
2985 ((not org-use-property-inheritance) nil)
2986 ((stringp org-use-property-inheritance)
2987 (string-match org-use-property-inheritance property))
2988 ((listp org-use-property-inheritance)
2989 (member property org-use-property-inheritance))
2990 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2992 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2993 "The default column format, if no other format has been defined.
2994 This variable can be set on the per-file basis by inserting a line
2996 #+COLUMNS: %25ITEM ....."
2997 :group 'org-properties
2998 :type 'string)
3000 (defcustom org-columns-ellipses ".."
3001 "The ellipses to be used when a field in column view is truncated.
3002 When this is the empty string, as many characters as possible are shown,
3003 but then there will be no visual indication that the field has been truncated.
3004 When this is a string of length N, the last N characters of a truncated
3005 field are replaced by this string. If the column is narrower than the
3006 ellipses string, only part of the ellipses string will be shown."
3007 :group 'org-properties
3008 :type 'string)
3010 (defcustom org-columns-modify-value-for-display-function nil
3011 "Function that modifies values for display in column view.
3012 For example, it can be used to cut out a certain part from a time stamp.
3013 The function must take 2 arguments:
3015 column-title The title of the column (*not* the property name)
3016 value The value that should be modified.
3018 The function should return the value that should be displayed,
3019 or nil if the normal value should be used."
3020 :group 'org-properties
3021 :type 'function)
3023 (defcustom org-effort-property "Effort"
3024 "The property that is being used to keep track of effort estimates.
3025 Effort estimates given in this property need to have the format H:MM."
3026 :group 'org-properties
3027 :group 'org-progress
3028 :type '(string :tag "Property"))
3030 (defconst org-global-properties-fixed
3031 '(("VISIBILITY_ALL" . "folded children content all")
3032 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3033 "List of property/value pairs that can be inherited by any entry.
3035 These are fixed values, for the preset properties. The user variable
3036 that can be used to add to this list is `org-global-properties'.
3038 The entries in this list are cons cells where the car is a property
3039 name and cdr is a string with the value. If the value represents
3040 multiple items like an \"_ALL\" property, separate the items by
3041 spaces.")
3043 (defcustom org-global-properties nil
3044 "List of property/value pairs that can be inherited by any entry.
3046 This list will be combined with the constant `org-global-properties-fixed'.
3048 The entries in this list are cons cells where the car is a property
3049 name and cdr is a string with the value.
3051 You can set buffer-local values for the same purpose in the variable
3052 `org-file-properties' this by adding lines like
3054 #+PROPERTY: NAME VALUE"
3055 :group 'org-properties
3056 :type '(repeat
3057 (cons (string :tag "Property")
3058 (string :tag "Value"))))
3060 (defvar org-file-properties nil
3061 "List of property/value pairs that can be inherited by any entry.
3062 Valid for the current buffer.
3063 This variable is populated from #+PROPERTY lines.")
3064 (make-variable-buffer-local 'org-file-properties)
3066 (defgroup org-agenda nil
3067 "Options concerning agenda views in Org-mode."
3068 :tag "Org Agenda"
3069 :group 'org)
3071 (defvar org-category nil
3072 "Variable used by org files to set a category for agenda display.
3073 Such files should use a file variable to set it, for example
3075 # -*- mode: org; org-category: \"ELisp\"
3077 or contain a special line
3079 #+CATEGORY: ELisp
3081 If the file does not specify a category, then file's base name
3082 is used instead.")
3083 (make-variable-buffer-local 'org-category)
3084 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
3086 (defcustom org-agenda-files nil
3087 "The files to be used for agenda display.
3088 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3089 \\[org-remove-file]. You can also use customize to edit the list.
3091 If an entry is a directory, all files in that directory that are matched by
3092 `org-agenda-file-regexp' will be part of the file list.
3094 If the value of the variable is not a list but a single file name, then
3095 the list of agenda files is actually stored and maintained in that file, one
3096 agenda file per line. In this file paths can be given relative to
3097 `org-directory'. Tilde expansion and environment variable substitution
3098 are also made."
3099 :group 'org-agenda
3100 :type '(choice
3101 (repeat :tag "List of files and directories" file)
3102 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3104 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3105 "Regular expression to match files for `org-agenda-files'.
3106 If any element in the list in that variable contains a directory instead
3107 of a normal file, all files in that directory that are matched by this
3108 regular expression will be included."
3109 :group 'org-agenda
3110 :type 'regexp)
3112 (defcustom org-agenda-text-search-extra-files nil
3113 "List of extra files to be searched by text search commands.
3114 These files will be search in addition to the agenda files by the
3115 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3116 Note that these files will only be searched for text search commands,
3117 not for the other agenda views like todo lists, tag searches or the weekly
3118 agenda. This variable is intended to list notes and possibly archive files
3119 that should also be searched by these two commands.
3120 In fact, if the first element in the list is the symbol `agenda-archives',
3121 than all archive files of all agenda files will be added to the search
3122 scope."
3123 :group 'org-agenda
3124 :type '(set :greedy t
3125 (const :tag "Agenda Archives" agenda-archives)
3126 (repeat :inline t (file))))
3128 (if (fboundp 'defvaralias)
3129 (defvaralias 'org-agenda-multi-occur-extra-files
3130 'org-agenda-text-search-extra-files))
3132 (defcustom org-agenda-skip-unavailable-files nil
3133 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3134 A nil value means to remove them, after a query, from the list."
3135 :group 'org-agenda
3136 :type 'boolean)
3138 (defcustom org-calendar-to-agenda-key [?c]
3139 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3140 The command `org-calendar-goto-agenda' will be bound to this key. The
3141 default is the character `c' because then `c' can be used to switch back and
3142 forth between agenda and calendar."
3143 :group 'org-agenda
3144 :type 'sexp)
3146 (defcustom org-calendar-agenda-action-key [?k]
3147 "The key to be installed in `calendar-mode-map' for agenda-action.
3148 The command `org-agenda-action' will be bound to this key. The
3149 default is the character `k' because we use the same key in the agenda."
3150 :group 'org-agenda
3151 :type 'sexp)
3153 (defcustom org-calendar-insert-diary-entry-key [?i]
3154 "The key to be installed in `calendar-mode-map' for adding diary entries.
3155 This option is irrelevant until `org-agenda-diary-file' has been configured
3156 to point to an Org-mode file. When that is the case, the command
3157 `org-agenda-diary-entry' will be bound to the key given here, by default
3158 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3159 if you want to continue doing this, you need to change this to a different
3160 key."
3161 :group 'org-agenda
3162 :type 'sexp)
3164 (defcustom org-agenda-diary-file 'diary-file
3165 "File to which to add new entries with the `i' key in agenda and calendar.
3166 When this is the symbol `diary-file', the functionality in the Emacs
3167 calendar will be used to add entries to the `diary-file'. But when this
3168 points to a file, `org-agenda-diary-entry' will be used instead."
3169 :group 'org-agenda
3170 :type '(choice
3171 (const :tag "The standard Emacs diary file" diary-file)
3172 (file :tag "Special Org file diary entries")))
3174 (eval-after-load "calendar"
3175 '(progn
3176 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3177 'org-calendar-goto-agenda)
3178 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3179 'org-agenda-action)
3180 (add-hook 'calendar-mode-hook
3181 (lambda ()
3182 (unless (eq org-agenda-diary-file 'diary-file)
3183 (define-key calendar-mode-map
3184 org-calendar-insert-diary-entry-key
3185 'org-agenda-diary-entry))))))
3187 (defgroup org-latex nil
3188 "Options for embedding LaTeX code into Org-mode."
3189 :tag "Org LaTeX"
3190 :group 'org)
3192 (defcustom org-format-latex-options
3193 '(:foreground default :background default :scale 1.0
3194 :html-foreground "Black" :html-background "Transparent"
3195 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3196 "Options for creating images from LaTeX fragments.
3197 This is a property list with the following properties:
3198 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3199 `default' means use the foreground of the default face.
3200 :background the background color, or \"Transparent\".
3201 `default' means use the background of the default face.
3202 :scale a scaling factor for the size of the images, to get more pixels
3203 :html-foreground, :html-background, :html-scale
3204 the same numbers for HTML export.
3205 :matchers a list indicating which matchers should be used to
3206 find LaTeX fragments. Valid members of this list are:
3207 \"begin\" find environments
3208 \"$1\" find single characters surrounded by $.$
3209 \"$\" find math expressions surrounded by $...$
3210 \"$$\" find math expressions surrounded by $$....$$
3211 \"\\(\" find math expressions surrounded by \\(...\\)
3212 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3213 :group 'org-latex
3214 :type 'plist)
3216 (defcustom org-format-latex-signal-error t
3217 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3218 When nil, just push out a message."
3219 :group 'org-latex
3220 :type 'boolean)
3222 (defcustom org-format-latex-header "\\documentclass{article}
3223 \\usepackage[usenames]{color}
3224 \\usepackage{amsmath}
3225 \\usepackage[mathscr]{eucal}
3226 \\pagestyle{empty} % do not remove
3227 \[PACKAGES]
3228 \[DEFAULT-PACKAGES]
3229 % The settings below are copied from fullpage.sty
3230 \\setlength{\\textwidth}{\\paperwidth}
3231 \\addtolength{\\textwidth}{-3cm}
3232 \\setlength{\\oddsidemargin}{1.5cm}
3233 \\addtolength{\\oddsidemargin}{-2.54cm}
3234 \\setlength{\\evensidemargin}{\\oddsidemargin}
3235 \\setlength{\\textheight}{\\paperheight}
3236 \\addtolength{\\textheight}{-\\headheight}
3237 \\addtolength{\\textheight}{-\\headsep}
3238 \\addtolength{\\textheight}{-\\footskip}
3239 \\addtolength{\\textheight}{-3cm}
3240 \\setlength{\\topmargin}{1.5cm}
3241 \\addtolength{\\topmargin}{-2.54cm}"
3242 "The document header used for processing LaTeX fragments.
3243 It is imperative that this header make sure that no page number
3244 appears on the page. The package defined in the variables
3245 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3246 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3247 will be appended."
3248 :group 'org-latex
3249 :type 'string)
3251 (defvar org-format-latex-header-extra nil)
3253 (defun org-set-packages-alist (var val)
3254 "Set the packages alist and make sure it has 3 elements per entry."
3255 (set var (mapcar (lambda (x)
3256 (if (and (consp x) (= (length x) 2))
3257 (list (car x) (nth 1 x) t)
3259 val)))
3261 (defun org-get-packages-alist (var)
3263 "Get the packages alist and make sure it has 3 elements per entry."
3264 (mapcar (lambda (x)
3265 (if (and (consp x) (= (length x) 2))
3266 (list (car x) (nth 1 x) t)
3268 (default-value var)))
3270 ;; The following variables are defined here because is it also used
3271 ;; when formatting latex fragments. Originally it was part of the
3272 ;; LaTeX exporter, which is why the name includes "export".
3273 (defcustom org-export-latex-default-packages-alist
3274 '(("AUTO" "inputenc" t)
3275 ("T1" "fontenc" t)
3276 ("" "fixltx2e" nil)
3277 ("" "graphicx" t)
3278 ("" "longtable" nil)
3279 ("" "float" nil)
3280 ("" "wrapfig" nil)
3281 ("" "soul" t)
3282 ("" "textcomp" t)
3283 ("" "marvosym" t)
3284 ("" "wasysym" t)
3285 ("" "latexsym" t)
3286 ("" "amssymb" t)
3287 ("" "hyperref" nil)
3288 "\\tolerance=1000"
3290 "Alist of default packages to be inserted in the header.
3291 Change this only if one of the packages here causes an incompatibility
3292 with another package you are using.
3293 The packages in this list are needed by one part or another of Org-mode
3294 to function properly.
3296 - inputenc, fontenc: for basic font and character selection
3297 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3298 for interpreting the entities in `org-entities'. You can skip some of these
3299 packages if you don't use any of the symbols in it.
3300 - graphicx: for including images
3301 - float, wrapfig: for figure placement
3302 - longtable: for long tables
3303 - hyperref: for cross references
3305 Therefore you should not modify this variable unless you know what you
3306 are doing. The one reason to change it anyway is that you might be loading
3307 some other package that conflicts with one of the default packages.
3308 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3309 If SNIPPET-FLAG is t, the package also needs to be included when
3310 compiling LaTeX snippets into images for inclusion into HTML."
3311 :group 'org-export-latex
3312 :set 'org-set-packages-alist
3313 :get 'org-get-packages-alist
3314 :type '(repeat
3315 (choice
3316 (list :tag "options/package pair"
3317 (string :tag "options")
3318 (string :tag "package")
3319 (boolean :tag "Snippet"))
3320 (string :tag "A line of LaTeX"))))
3322 (defcustom org-export-latex-packages-alist nil
3323 "Alist of packages to be inserted in every LaTeX header.
3324 These will be inserted after `org-export-latex-default-packages-alist'.
3325 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3326 SNIPPET-FLAG, when t, indicates that this package is also needed when
3327 turning LaTeX snippets into images for inclusion into HTML.
3328 Make sure that you only list packages here which:
3329 - you want in every file
3330 - do not conflict with the default packages in
3331 `org-export-latex-default-packages-alist'
3332 - do not conflict with the setup in `org-format-latex-header'."
3333 :group 'org-export-latex
3334 :set 'org-set-packages-alist
3335 :get 'org-get-packages-alist
3336 :type '(repeat
3337 (choice
3338 (list :tag "options/package pair"
3339 (string :tag "options")
3340 (string :tag "package")
3341 (boolean :tag "Snippet"))
3342 (string :tag "A line of LaTeX"))))
3345 (defgroup org-appearance nil
3346 "Settings for Org-mode appearance."
3347 :tag "Org Appearance"
3348 :group 'org)
3350 (defcustom org-level-color-stars-only nil
3351 "Non-nil means fontify only the stars in each headline.
3352 When nil, the entire headline is fontified.
3353 Changing it requires restart of `font-lock-mode' to become effective
3354 also in regions already fontified."
3355 :group 'org-appearance
3356 :type 'boolean)
3358 (defcustom org-hide-leading-stars nil
3359 "Non-nil means hide the first N-1 stars in a headline.
3360 This works by using the face `org-hide' for these stars. This
3361 face is white for a light background, and black for a dark
3362 background. You may have to customize the face `org-hide' to
3363 make this work.
3364 Changing it requires restart of `font-lock-mode' to become effective
3365 also in regions already fontified.
3366 You may also set this on a per-file basis by adding one of the following
3367 lines to the buffer:
3369 #+STARTUP: hidestars
3370 #+STARTUP: showstars"
3371 :group 'org-appearance
3372 :type 'boolean)
3374 (defcustom org-hidden-keywords nil
3375 "List of symbols corresponding to keywords to be hidden the org buffer.
3376 For example, a value '(title) for this list will make the document's title
3377 appear in the buffer without the initial #+TITLE: keyword."
3378 :group 'org-appearance
3379 :type '(set (const :tag "#+AUTHOR" author)
3380 (const :tag "#+DATE" date)
3381 (const :tag "#+EMAIL" email)
3382 (const :tag "#+TITLE" title)))
3384 (defcustom org-fontify-done-headline nil
3385 "Non-nil means change the face of a headline if it is marked DONE.
3386 Normally, only the TODO/DONE keyword indicates the state of a headline.
3387 When this is non-nil, the headline after the keyword is set to the
3388 `org-headline-done' as an additional indication."
3389 :group 'org-appearance
3390 :type 'boolean)
3392 (defcustom org-fontify-emphasized-text t
3393 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3394 Changing this variable requires a restart of Emacs to take effect."
3395 :group 'org-appearance
3396 :type 'boolean)
3398 (defcustom org-fontify-whole-heading-line nil
3399 "Non-nil means fontify the whole line for headings.
3400 This is useful when setting a background color for the
3401 org-level-* faces."
3402 :group 'org-appearance
3403 :type 'boolean)
3405 (defcustom org-highlight-latex-fragments-and-specials nil
3406 "Non-nil means fontify what is treated specially by the exporters."
3407 :group 'org-appearance
3408 :type 'boolean)
3410 (defcustom org-hide-emphasis-markers nil
3411 "Non-nil mean font-lock should hide the emphasis marker characters."
3412 :group 'org-appearance
3413 :type 'boolean)
3415 (defcustom org-pretty-entities nil
3416 "Non-nil means show entities as UTF8 characters.
3417 When nil, the \\name form remains in the buffer."
3418 :group 'org-appearance
3419 :type 'boolean)
3421 (defcustom org-pretty-entities-include-sub-superscripts t
3422 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3423 :group 'org-appearance
3424 :type 'boolean)
3426 (defvar org-emph-re nil
3427 "Regular expression for matching emphasis.
3428 After a match, the match groups contain these elements:
3429 0 The match of the full regular expression, including the characters
3430 before and after the proper match
3431 1 The character before the proper match, or empty at beginning of line
3432 2 The proper match, including the leading and trailing markers
3433 3 The leading marker like * or /, indicating the type of highlighting
3434 4 The text between the emphasis markers, not including the markers
3435 5 The character after the match, empty at the end of a line")
3436 (defvar org-verbatim-re nil
3437 "Regular expression for matching verbatim text.")
3438 (defvar org-emphasis-regexp-components) ; defined just below
3439 (defvar org-emphasis-alist) ; defined just below
3440 (defun org-set-emph-re (var val)
3441 "Set variable and compute the emphasis regular expression."
3442 (set var val)
3443 (when (and (boundp 'org-emphasis-alist)
3444 (boundp 'org-emphasis-regexp-components)
3445 org-emphasis-alist org-emphasis-regexp-components)
3446 (let* ((e org-emphasis-regexp-components)
3447 (pre (car e))
3448 (post (nth 1 e))
3449 (border (nth 2 e))
3450 (body (nth 3 e))
3451 (nl (nth 4 e))
3452 (body1 (concat body "*?"))
3453 (markers (mapconcat 'car org-emphasis-alist ""))
3454 (vmarkers (mapconcat
3455 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3456 org-emphasis-alist "")))
3457 ;; make sure special characters appear at the right position in the class
3458 (if (string-match "\\^" markers)
3459 (setq markers (concat (replace-match "" t t markers) "^")))
3460 (if (string-match "-" markers)
3461 (setq markers (concat (replace-match "" t t markers) "-")))
3462 (if (string-match "\\^" vmarkers)
3463 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3464 (if (string-match "-" vmarkers)
3465 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3466 (if (> nl 0)
3467 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3468 (int-to-string nl) "\\}")))
3469 ;; Make the regexp
3470 (setq org-emph-re
3471 (concat "\\([" pre "]\\|^\\)"
3472 "\\("
3473 "\\([" markers "]\\)"
3474 "\\("
3475 "[^" border "]\\|"
3476 "[^" border "]"
3477 body1
3478 "[^" border "]"
3479 "\\)"
3480 "\\3\\)"
3481 "\\([" post "]\\|$\\)"))
3482 (setq org-verbatim-re
3483 (concat "\\([" pre "]\\|^\\)"
3484 "\\("
3485 "\\([" vmarkers "]\\)"
3486 "\\("
3487 "[^" border "]\\|"
3488 "[^" border "]"
3489 body1
3490 "[^" border "]"
3491 "\\)"
3492 "\\3\\)"
3493 "\\([" post "]\\|$\\)")))))
3495 (defcustom org-emphasis-regexp-components
3496 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3497 "Components used to build the regular expression for emphasis.
3498 This is a list with five entries. Terminology: In an emphasis string
3499 like \" *strong word* \", we call the initial space PREMATCH, the final
3500 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3501 and \"trong wor\" is the body. The different components in this variable
3502 specify what is allowed/forbidden in each part:
3504 pre Chars allowed as prematch. Beginning of line will be allowed too.
3505 post Chars allowed as postmatch. End of line will be allowed too.
3506 border The chars *forbidden* as border characters.
3507 body-regexp A regexp like \".\" to match a body character. Don't use
3508 non-shy groups here, and don't allow newline here.
3509 newline The maximum number of newlines allowed in an emphasis exp.
3511 Use customize to modify this, or restart Emacs after changing it."
3512 :group 'org-appearance
3513 :set 'org-set-emph-re
3514 :type '(list
3515 (sexp :tag "Allowed chars in pre ")
3516 (sexp :tag "Allowed chars in post ")
3517 (sexp :tag "Forbidden chars in border ")
3518 (sexp :tag "Regexp for body ")
3519 (integer :tag "number of newlines allowed")
3520 (option (boolean :tag "Please ignore this button"))))
3522 (defcustom org-emphasis-alist
3523 `(("*" bold "<b>" "</b>")
3524 ("/" italic "<i>" "</i>")
3525 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3526 ("=" org-code "<code>" "</code>" verbatim)
3527 ("~" org-verbatim "<code>" "</code>" verbatim)
3528 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3529 "<del>" "</del>")
3531 "Special syntax for emphasized text.
3532 Text starting and ending with a special character will be emphasized, for
3533 example *bold*, _underlined_ and /italic/. This variable sets the marker
3534 characters, the face to be used by font-lock for highlighting in Org-mode
3535 Emacs buffers, and the HTML tags to be used for this.
3536 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3537 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3538 Use customize to modify this, or restart Emacs after changing it."
3539 :group 'org-appearance
3540 :set 'org-set-emph-re
3541 :type '(repeat
3542 (list
3543 (string :tag "Marker character")
3544 (choice
3545 (face :tag "Font-lock-face")
3546 (plist :tag "Face property list"))
3547 (string :tag "HTML start tag")
3548 (string :tag "HTML end tag")
3549 (option (const verbatim)))))
3551 (defvar org-protecting-blocks
3552 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3553 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3554 This is needed for font-lock setup.")
3556 ;;; Miscellaneous options
3558 (defgroup org-completion nil
3559 "Completion in Org-mode."
3560 :tag "Org Completion"
3561 :group 'org)
3563 (defcustom org-completion-use-ido nil
3564 "Non-nil means use ido completion wherever possible.
3565 Note that `ido-mode' must be active for this variable to be relevant.
3566 If you decide to turn this variable on, you might well want to turn off
3567 `org-outline-path-complete-in-steps'.
3568 See also `org-completion-use-iswitchb'."
3569 :group 'org-completion
3570 :type 'boolean)
3572 (defcustom org-completion-use-iswitchb nil
3573 "Non-nil means use iswitchb completion wherever possible.
3574 Note that `iswitchb-mode' must be active for this variable to be relevant.
3575 If you decide to turn this variable on, you might well want to turn off
3576 `org-outline-path-complete-in-steps'.
3577 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3578 :group 'org-completion
3579 :type 'boolean)
3581 (defcustom org-completion-fallback-command 'hippie-expand
3582 "The expansion command called by \\[pcomplete] in normal context.
3583 Normal means, no org-mode-specific context."
3584 :group 'org-completion
3585 :type 'function)
3587 ;;; Functions and variables from their packages
3588 ;; Declared here to avoid compiler warnings
3590 ;; XEmacs only
3591 (defvar outline-mode-menu-heading)
3592 (defvar outline-mode-menu-show)
3593 (defvar outline-mode-menu-hide)
3594 (defvar zmacs-regions) ; XEmacs regions
3596 ;; Emacs only
3597 (defvar mark-active)
3599 ;; Various packages
3600 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3601 (declare-function calendar-forward-day "cal-move" (arg))
3602 (declare-function calendar-goto-date "cal-move" (date))
3603 (declare-function calendar-goto-today "cal-move" ())
3604 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3605 (defvar calc-embedded-close-formula)
3606 (defvar calc-embedded-open-formula)
3607 (declare-function cdlatex-tab "ext:cdlatex" ())
3608 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3609 (defvar font-lock-unfontify-region-function)
3610 (declare-function iswitchb-read-buffer "iswitchb"
3611 (prompt &optional default require-match start matches-set))
3612 (defvar iswitchb-temp-buflist)
3613 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3614 (defvar org-agenda-tags-todo-honor-ignore-options)
3615 (declare-function org-agenda-skip "org-agenda" ())
3616 (declare-function
3617 org-format-agenda-item "org-agenda"
3618 (extra txt &optional category tags dotime noprefix remove-re habitp))
3619 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3620 (declare-function org-agenda-change-all-lines "org-agenda"
3621 (newhead hdmarker &optional fixface just-this))
3622 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3623 (declare-function org-agenda-maybe-redo "org-agenda" ())
3624 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3625 (beg end))
3626 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3627 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3628 "org-agenda" (&optional end))
3629 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3630 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3631 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3632 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3633 (declare-function org-indent-mode "org-indent" (&optional arg))
3634 (declare-function parse-time-string "parse-time" (string))
3635 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3636 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3637 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3638 (defvar remember-data-file)
3639 (defvar texmathp-why)
3640 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3641 (declare-function table--at-cell-p "table" (position &optional object at-column))
3643 (defvar w3m-current-url)
3644 (defvar w3m-current-title)
3646 (defvar org-latex-regexps)
3648 ;;; Autoload and prepare some org modules
3650 ;; Some table stuff that needs to be defined here, because it is used
3651 ;; by the functions setting up org-mode or checking for table context.
3653 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3654 "Detect an org-type or table-type table.")
3655 (defconst org-table-line-regexp "^[ \t]*|"
3656 "Detect an org-type table line.")
3657 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3658 "Detect an org-type table line.")
3659 (defconst org-table-hline-regexp "^[ \t]*|-"
3660 "Detect an org-type table hline.")
3661 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3662 "Detect a table-type table hline.")
3663 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3664 "Detect the first line outside a table when searching from within it.
3665 This works for both table types.")
3667 ;; Autoload the functions in org-table.el that are needed by functions here.
3669 (eval-and-compile
3670 (org-autoload "org-table"
3671 '(org-table-align org-table-begin org-table-blank-field
3672 org-table-convert org-table-convert-region org-table-copy-down
3673 org-table-copy-region org-table-create
3674 org-table-create-or-convert-from-region
3675 org-table-create-with-table.el org-table-current-dline
3676 org-table-cut-region org-table-delete-column org-table-edit-field
3677 org-table-edit-formulas org-table-end org-table-eval-formula
3678 org-table-export org-table-field-info
3679 org-table-get-stored-formulas org-table-goto-column
3680 org-table-hline-and-move org-table-import org-table-insert-column
3681 org-table-insert-hline org-table-insert-row org-table-iterate
3682 org-table-justify-field-maybe org-table-kill-row
3683 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3684 org-table-move-column org-table-move-column-left
3685 org-table-move-column-right org-table-move-row
3686 org-table-move-row-down org-table-move-row-up
3687 org-table-next-field org-table-next-row org-table-paste-rectangle
3688 org-table-previous-field org-table-recalculate
3689 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3690 org-table-toggle-coordinate-overlays
3691 org-table-toggle-formula-debugger org-table-wrap-region
3692 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3693 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3694 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3696 (defun org-at-table-p (&optional table-type)
3697 "Return t if the cursor is inside an org-type table.
3698 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3699 (if org-enable-table-editor
3700 (save-excursion
3701 (beginning-of-line 1)
3702 (looking-at (if table-type org-table-any-line-regexp
3703 org-table-line-regexp)))
3704 nil))
3705 (defsubst org-table-p () (org-at-table-p))
3707 (defun org-at-table.el-p ()
3708 "Return t if and only if we are at a table.el table."
3709 (and (org-at-table-p 'any)
3710 (save-excursion
3711 (goto-char (org-table-begin 'any))
3712 (looking-at org-table1-hline-regexp))))
3713 (defun org-table-recognize-table.el ()
3714 "If there is a table.el table nearby, recognize it and move into it."
3715 (if org-table-tab-recognizes-table.el
3716 (if (org-at-table.el-p)
3717 (progn
3718 (beginning-of-line 1)
3719 (if (looking-at org-table-dataline-regexp)
3721 (if (looking-at org-table1-hline-regexp)
3722 (progn
3723 (beginning-of-line 2)
3724 (if (looking-at org-table-any-border-regexp)
3725 (beginning-of-line -1)))))
3726 (if (re-search-forward "|" (org-table-end t) t)
3727 (progn
3728 (require 'table)
3729 (if (table--at-cell-p (point))
3731 (message "recognizing table.el table...")
3732 (table-recognize-table)
3733 (message "recognizing table.el table...done")))
3734 (error "This should not happen"))
3736 nil)
3737 nil))
3739 (defun org-at-table-hline-p ()
3740 "Return t if the cursor is inside a hline in a table."
3741 (if org-enable-table-editor
3742 (save-excursion
3743 (beginning-of-line 1)
3744 (looking-at org-table-hline-regexp))
3745 nil))
3747 (defvar org-table-clean-did-remove-column nil)
3749 (defun org-table-map-tables (function &optional quietly)
3750 "Apply FUNCTION to the start of all tables in the buffer."
3751 (save-excursion
3752 (save-restriction
3753 (widen)
3754 (goto-char (point-min))
3755 (while (re-search-forward org-table-any-line-regexp nil t)
3756 (unless quietly
3757 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3758 (beginning-of-line 1)
3759 (when (looking-at org-table-line-regexp)
3760 (save-excursion (funcall function))
3761 (or (looking-at org-table-line-regexp)
3762 (forward-char 1)))
3763 (re-search-forward org-table-any-border-regexp nil 1))))
3764 (unless quietly (message "Mapping tables: done")))
3766 ;; Declare and autoload functions from org-exp.el & Co
3768 (declare-function org-default-export-plist "org-exp")
3769 (declare-function org-infile-export-plist "org-exp")
3770 (declare-function org-get-current-options "org-exp")
3771 (eval-and-compile
3772 (org-autoload "org-exp"
3773 '(org-export org-export-visible
3774 org-insert-export-options-template
3775 org-table-clean-before-export))
3776 (org-autoload "org-ascii"
3777 '(org-export-as-ascii org-export-ascii-preprocess
3778 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3779 org-export-region-as-ascii))
3780 (org-autoload "org-latex"
3781 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3782 org-replace-region-by-latex org-export-region-as-latex
3783 org-export-as-latex org-export-as-pdf
3784 org-export-as-pdf-and-open))
3785 (org-autoload "org-html"
3786 '(org-export-as-html-and-open
3787 org-export-as-html-batch org-export-as-html-to-buffer
3788 org-replace-region-by-html org-export-region-as-html
3789 org-export-as-html))
3790 (org-autoload "org-docbook"
3791 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3792 org-replace-region-by-docbook org-export-region-as-docbook
3793 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3794 org-export-as-docbook))
3795 (org-autoload "org-icalendar"
3796 '(org-export-icalendar-this-file
3797 org-export-icalendar-all-agenda-files
3798 org-export-icalendar-combine-agenda-files))
3799 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3800 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3802 ;; Declare and autoload functions from org-agenda.el
3804 (eval-and-compile
3805 (org-autoload "org-agenda"
3806 '(org-agenda org-agenda-list org-search-view
3807 org-todo-list org-tags-view org-agenda-list-stuck-projects
3808 org-diary org-agenda-to-appt
3809 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3811 ;; Autoload org-remember
3813 (eval-and-compile
3814 (org-autoload "org-remember"
3815 '(org-remember-insinuate org-remember-annotation
3816 org-remember-apply-template org-remember org-remember-handler)))
3818 (eval-and-compile
3819 (org-autoload "org-capture"
3820 '(org-capture org-capture-insert-template-here
3821 org-capture-import-remember-templates)))
3823 ;; Autoload org-clock.el
3825 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3826 (beg end))
3827 (declare-function org-clock-update-mode-line "org-clock" ())
3828 (declare-function org-resolve-clocks "org-clock"
3829 (&optional also-non-dangling-p prompt last-valid))
3830 (defvar org-clock-start-time)
3831 (defvar org-clock-marker (make-marker)
3832 "Marker recording the last clock-in.")
3833 (defvar org-clock-hd-marker (make-marker)
3834 "Marker recording the last clock-in, but the headline position.")
3835 (defvar org-clock-heading ""
3836 "The heading of the current clock entry.")
3837 (defun org-clock-is-active ()
3838 "Return non-nil if clock is currently running.
3839 The return value is actually the clock marker."
3840 (marker-buffer org-clock-marker))
3842 (eval-and-compile
3843 (org-autoload
3844 "org-clock"
3845 '(org-clock-in org-clock-out org-clock-cancel
3846 org-clock-goto org-clock-sum org-clock-display
3847 org-clock-remove-overlays org-clock-report
3848 org-clocktable-shift org-dblock-write:clocktable
3849 org-get-clocktable org-resolve-clocks)))
3851 (defun org-clock-update-time-maybe ()
3852 "If this is a CLOCK line, update it and return t.
3853 Otherwise, return nil."
3854 (interactive)
3855 (save-excursion
3856 (beginning-of-line 1)
3857 (skip-chars-forward " \t")
3858 (when (looking-at org-clock-string)
3859 (let ((re (concat "[ \t]*" org-clock-string
3860 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3861 "\\([ \t]*=>.*\\)?\\)?"))
3862 ts te h m s neg)
3863 (cond
3864 ((not (looking-at re))
3865 nil)
3866 ((not (match-end 2))
3867 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3868 (> org-clock-marker (point))
3869 (<= org-clock-marker (point-at-eol)))
3870 ;; The clock is running here
3871 (setq org-clock-start-time
3872 (apply 'encode-time
3873 (org-parse-time-string (match-string 1))))
3874 (org-clock-update-mode-line)))
3876 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3877 (end-of-line 1)
3878 (setq ts (match-string 1)
3879 te (match-string 3))
3880 (setq s (- (org-float-time
3881 (apply 'encode-time (org-parse-time-string te)))
3882 (org-float-time
3883 (apply 'encode-time (org-parse-time-string ts))))
3884 neg (< s 0)
3885 s (abs s)
3886 h (floor (/ s 3600))
3887 s (- s (* 3600 h))
3888 m (floor (/ s 60))
3889 s (- s (* 60 s)))
3890 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3891 t))))))
3893 (defun org-check-running-clock ()
3894 "Check if the current buffer contains the running clock.
3895 If yes, offer to stop it and to save the buffer with the changes."
3896 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3897 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3898 (buffer-name))))
3899 (org-clock-out)
3900 (when (y-or-n-p "Save changed buffer?")
3901 (save-buffer))))
3903 (defun org-clocktable-try-shift (dir n)
3904 "Check if this line starts a clock table, if yes, shift the time block."
3905 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3906 (org-clocktable-shift dir n)))
3908 ;; Autoload org-timer.el
3910 (eval-and-compile
3911 (org-autoload
3912 "org-timer"
3913 '(org-timer-start org-timer org-timer-item
3914 org-timer-change-times-in-region
3915 org-timer-set-timer
3916 org-timer-reset-timers
3917 org-timer-show-remaining-time)))
3919 ;; Autoload org-feed.el
3921 (eval-and-compile
3922 (org-autoload
3923 "org-feed"
3924 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3927 ;; Autoload org-indent.el
3929 ;; Define the variable already here, to make sure we have it.
3930 (defvar org-indent-mode nil
3931 "Non-nil if Org-Indent mode is enabled.
3932 Use the command `org-indent-mode' to change this variable.")
3934 (eval-and-compile
3935 (org-autoload
3936 "org-indent"
3937 '(org-indent-mode)))
3939 ;; Autoload org-mobile.el
3941 (eval-and-compile
3942 (org-autoload
3943 "org-mobile"
3944 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3946 ;; Autoload archiving code
3947 ;; The stuff that is needed for cycling and tags has to be defined here.
3949 (defgroup org-archive nil
3950 "Options concerning archiving in Org-mode."
3951 :tag "Org Archive"
3952 :group 'org-structure)
3954 (defcustom org-archive-location "%s_archive::"
3955 "The location where subtrees should be archived.
3957 The value of this variable is a string, consisting of two parts,
3958 separated by a double-colon. The first part is a filename and
3959 the second part is a headline.
3961 When the filename is omitted, archiving happens in the same file.
3962 %s in the filename will be replaced by the current file
3963 name (without the directory part). Archiving to a different file
3964 is useful to keep archived entries from contributing to the
3965 Org-mode Agenda.
3967 The archived entries will be filed as subtrees of the specified
3968 headline. When the headline is omitted, the subtrees are simply
3969 filed away at the end of the file, as top-level entries. Also in
3970 the heading you can use %s to represent the file name, this can be
3971 useful when using the same archive for a number of different files.
3973 Here are a few examples:
3974 \"%s_archive::\"
3975 If the current file is Projects.org, archive in file
3976 Projects.org_archive, as top-level trees. This is the default.
3978 \"::* Archived Tasks\"
3979 Archive in the current file, under the top-level headline
3980 \"* Archived Tasks\".
3982 \"~/org/archive.org::\"
3983 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3985 \"~/org/archive.org::From %s\"
3986 Archive in file ~/org/archive.org (absolute path), under headlines
3987 \"From FILENAME\" where file name is the current file name.
3989 \"basement::** Finished Tasks\"
3990 Archive in file ./basement (relative path), as level 3 trees
3991 below the level 2 heading \"** Finished Tasks\".
3993 You may set this option on a per-file basis by adding to the buffer a
3994 line like
3996 #+ARCHIVE: basement::** Finished Tasks
3998 You may also define it locally for a subtree by setting an ARCHIVE property
3999 in the entry. If such a property is found in an entry, or anywhere up
4000 the hierarchy, it will be used."
4001 :group 'org-archive
4002 :type 'string)
4004 (defcustom org-archive-tag "ARCHIVE"
4005 "The tag that marks a subtree as archived.
4006 An archived subtree does not open during visibility cycling, and does
4007 not contribute to the agenda listings.
4008 After changing this, font-lock must be restarted in the relevant buffers to
4009 get the proper fontification."
4010 :group 'org-archive
4011 :group 'org-keywords
4012 :type 'string)
4014 (defcustom org-agenda-skip-archived-trees t
4015 "Non-nil means the agenda will skip any items located in archived trees.
4016 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4017 variable is no longer recommended, you should leave it at the value t.
4018 Instead, use the key `v' to cycle the archives-mode in the agenda."
4019 :group 'org-archive
4020 :group 'org-agenda-skip
4021 :type 'boolean)
4023 (defcustom org-columns-skip-archived-trees t
4024 "Non-nil means ignore archived trees when creating column view."
4025 :group 'org-archive
4026 :group 'org-properties
4027 :type 'boolean)
4029 (defcustom org-cycle-open-archived-trees nil
4030 "Non-nil means `org-cycle' will open archived trees.
4031 An archived tree is a tree marked with the tag ARCHIVE.
4032 When nil, archived trees will stay folded. You can still open them with
4033 normal outline commands like `show-all', but not with the cycling commands."
4034 :group 'org-archive
4035 :group 'org-cycle
4036 :type 'boolean)
4038 (defcustom org-sparse-tree-open-archived-trees nil
4039 "Non-nil means sparse tree construction shows matches in archived trees.
4040 When nil, matches in these trees are highlighted, but the trees are kept in
4041 collapsed state."
4042 :group 'org-archive
4043 :group 'org-sparse-trees
4044 :type 'boolean)
4046 (defun org-cycle-hide-archived-subtrees (state)
4047 "Re-hide all archived subtrees after a visibility state change."
4048 (when (and (not org-cycle-open-archived-trees)
4049 (not (memq state '(overview folded))))
4050 (save-excursion
4051 (let* ((globalp (memq state '(contents all)))
4052 (beg (if globalp (point-min) (point)))
4053 (end (if globalp (point-max) (org-end-of-subtree t))))
4054 (org-hide-archived-subtrees beg end)
4055 (goto-char beg)
4056 (if (looking-at (concat ".*:" org-archive-tag ":"))
4057 (message "%s" (substitute-command-keys
4058 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4060 (defun org-force-cycle-archived ()
4061 "Cycle subtree even if it is archived."
4062 (interactive)
4063 (setq this-command 'org-cycle)
4064 (let ((org-cycle-open-archived-trees t))
4065 (call-interactively 'org-cycle)))
4067 (defun org-hide-archived-subtrees (beg end)
4068 "Re-hide all archived subtrees after a visibility state change."
4069 (save-excursion
4070 (let* ((re (concat ":" org-archive-tag ":")))
4071 (goto-char beg)
4072 (while (re-search-forward re end t)
4073 (when (org-on-heading-p)
4074 (org-flag-subtree t)
4075 (org-end-of-subtree t))))))
4077 (defun org-flag-subtree (flag)
4078 (save-excursion
4079 (org-back-to-heading t)
4080 (outline-end-of-heading)
4081 (outline-flag-region (point)
4082 (progn (org-end-of-subtree t) (point))
4083 flag)))
4085 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4087 (eval-and-compile
4088 (org-autoload "org-archive"
4089 '(org-add-archive-files org-archive-subtree
4090 org-archive-to-archive-sibling org-toggle-archive-tag
4091 org-archive-subtree-default
4092 org-archive-subtree-default-with-confirmation)))
4094 ;; Autoload Column View Code
4096 (declare-function org-columns-number-to-string "org-colview")
4097 (declare-function org-columns-get-format-and-top-level "org-colview")
4098 (declare-function org-columns-compute "org-colview")
4100 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4101 '(org-columns-number-to-string org-columns-get-format-and-top-level
4102 org-columns-compute org-agenda-columns org-columns-remove-overlays
4103 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4105 ;; Autoload ID code
4107 (declare-function org-id-store-link "org-id")
4108 (declare-function org-id-locations-load "org-id")
4109 (declare-function org-id-locations-save "org-id")
4110 (defvar org-id-track-globally)
4111 (org-autoload "org-id"
4112 '(org-id-get-create org-id-new org-id-copy org-id-get
4113 org-id-get-with-outline-path-completion
4114 org-id-get-with-outline-drilling org-id-store-link
4115 org-id-goto org-id-find org-id-store-link))
4117 ;; Autoload Plotting Code
4119 (org-autoload "org-plot"
4120 '(org-plot/gnuplot))
4122 ;;; Variables for pre-computed regular expressions, all buffer local
4124 (defvar org-drawer-regexp nil
4125 "Matches first line of a hidden block.")
4126 (make-variable-buffer-local 'org-drawer-regexp)
4127 (defvar org-todo-regexp nil
4128 "Matches any of the TODO state keywords.")
4129 (make-variable-buffer-local 'org-todo-regexp)
4130 (defvar org-not-done-regexp nil
4131 "Matches any of the TODO state keywords except the last one.")
4132 (make-variable-buffer-local 'org-not-done-regexp)
4133 (defvar org-not-done-heading-regexp nil
4134 "Matches a TODO headline that is not done.")
4135 (make-variable-buffer-local 'org-not-done-regexp)
4136 (defvar org-todo-line-regexp nil
4137 "Matches a headline and puts TODO state into group 2 if present.")
4138 (make-variable-buffer-local 'org-todo-line-regexp)
4139 (defvar org-complex-heading-regexp nil
4140 "Matches a headline and puts everything into groups:
4141 group 1: the stars
4142 group 2: The todo keyword, maybe
4143 group 3: Priority cookie
4144 group 4: True headline
4145 group 5: Tags")
4146 (make-variable-buffer-local 'org-complex-heading-regexp)
4147 (defvar org-complex-heading-regexp-format nil
4148 "Printf format to make regexp to match an exact headline.
4149 This regexp will match the headline of any node which hase the exact
4150 headline text that is put into the format, but may have any TODO state,
4151 priority and tags.")
4152 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4153 (defvar org-todo-line-tags-regexp nil
4154 "Matches a headline and puts TODO state into group 2 if present.
4155 Also put tags into group 4 if tags are present.")
4156 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4157 (defvar org-nl-done-regexp nil
4158 "Matches newline followed by a headline with the DONE keyword.")
4159 (make-variable-buffer-local 'org-nl-done-regexp)
4160 (defvar org-looking-at-done-regexp nil
4161 "Matches the DONE keyword a point.")
4162 (make-variable-buffer-local 'org-looking-at-done-regexp)
4163 (defvar org-ds-keyword-length 12
4164 "Maximum length of the Deadline and SCHEDULED keywords.")
4165 (make-variable-buffer-local 'org-ds-keyword-length)
4166 (defvar org-deadline-regexp nil
4167 "Matches the DEADLINE keyword.")
4168 (make-variable-buffer-local 'org-deadline-regexp)
4169 (defvar org-deadline-time-regexp nil
4170 "Matches the DEADLINE keyword together with a time stamp.")
4171 (make-variable-buffer-local 'org-deadline-time-regexp)
4172 (defvar org-deadline-line-regexp nil
4173 "Matches the DEADLINE keyword and the rest of the line.")
4174 (make-variable-buffer-local 'org-deadline-line-regexp)
4175 (defvar org-scheduled-regexp nil
4176 "Matches the SCHEDULED keyword.")
4177 (make-variable-buffer-local 'org-scheduled-regexp)
4178 (defvar org-scheduled-time-regexp nil
4179 "Matches the SCHEDULED keyword together with a time stamp.")
4180 (make-variable-buffer-local 'org-scheduled-time-regexp)
4181 (defvar org-closed-time-regexp nil
4182 "Matches the CLOSED keyword together with a time stamp.")
4183 (make-variable-buffer-local 'org-closed-time-regexp)
4185 (defvar org-keyword-time-regexp nil
4186 "Matches any of the 4 keywords, together with the time stamp.")
4187 (make-variable-buffer-local 'org-keyword-time-regexp)
4188 (defvar org-keyword-time-not-clock-regexp nil
4189 "Matches any of the 3 keywords, together with the time stamp.")
4190 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4191 (defvar org-maybe-keyword-time-regexp nil
4192 "Matches a timestamp, possibly preceded by a keyword.")
4193 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4194 (defvar org-planning-or-clock-line-re nil
4195 "Matches a line with planning or clock info.")
4196 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4197 (defvar org-all-time-keywords nil
4198 "List of time keywords.")
4199 (make-variable-buffer-local 'org-all-time-keywords)
4201 (defconst org-plain-time-of-day-regexp
4202 (concat
4203 "\\(\\<[012]?[0-9]"
4204 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4205 "\\(--?"
4206 "\\(\\<[012]?[0-9]"
4207 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4208 "\\)?")
4209 "Regular expression to match a plain time or time range.
4210 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4211 groups carry important information:
4212 0 the full match
4213 1 the first time, range or not
4214 8 the second time, if it is a range.")
4216 (defconst org-plain-time-extension-regexp
4217 (concat
4218 "\\(\\<[012]?[0-9]"
4219 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4220 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4221 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4222 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4223 groups carry important information:
4224 0 the full match
4225 7 hours of duration
4226 9 minutes of duration")
4228 (defconst org-stamp-time-of-day-regexp
4229 (concat
4230 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4231 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4232 "\\(--?"
4233 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4234 "Regular expression to match a timestamp time or time range.
4235 After a match, the following groups carry important information:
4236 0 the full match
4237 1 date plus weekday, for back referencing to make sure both times are on the same day
4238 2 the first time, range or not
4239 4 the second time, if it is a range.")
4241 (defconst org-startup-options
4242 '(("fold" org-startup-folded t)
4243 ("overview" org-startup-folded t)
4244 ("nofold" org-startup-folded nil)
4245 ("showall" org-startup-folded nil)
4246 ("showeverything" org-startup-folded showeverything)
4247 ("content" org-startup-folded content)
4248 ("indent" org-startup-indented t)
4249 ("noindent" org-startup-indented nil)
4250 ("hidestars" org-hide-leading-stars t)
4251 ("showstars" org-hide-leading-stars nil)
4252 ("odd" org-odd-levels-only t)
4253 ("oddeven" org-odd-levels-only nil)
4254 ("align" org-startup-align-all-tables t)
4255 ("noalign" org-startup-align-all-tables nil)
4256 ("inlineimages" org-startup-with-inline-images t)
4257 ("noinlineimages" org-startup-with-inline-images nil)
4258 ("customtime" org-display-custom-times t)
4259 ("logdone" org-log-done time)
4260 ("lognotedone" org-log-done note)
4261 ("nologdone" org-log-done nil)
4262 ("lognoteclock-out" org-log-note-clock-out t)
4263 ("nolognoteclock-out" org-log-note-clock-out nil)
4264 ("logrepeat" org-log-repeat state)
4265 ("lognoterepeat" org-log-repeat note)
4266 ("nologrepeat" org-log-repeat nil)
4267 ("logreschedule" org-log-reschedule time)
4268 ("lognotereschedule" org-log-reschedule note)
4269 ("nologreschedule" org-log-reschedule nil)
4270 ("logredeadline" org-log-redeadline time)
4271 ("lognoteredeadline" org-log-redeadline note)
4272 ("nologredeadline" org-log-redeadline nil)
4273 ("logrefile" org-log-refile time)
4274 ("lognoterefile" org-log-refile note)
4275 ("nologrefile" org-log-refile nil)
4276 ("fninline" org-footnote-define-inline t)
4277 ("nofninline" org-footnote-define-inline nil)
4278 ("fnlocal" org-footnote-section nil)
4279 ("fnauto" org-footnote-auto-label t)
4280 ("fnprompt" org-footnote-auto-label nil)
4281 ("fnconfirm" org-footnote-auto-label confirm)
4282 ("fnplain" org-footnote-auto-label plain)
4283 ("fnadjust" org-footnote-auto-adjust t)
4284 ("nofnadjust" org-footnote-auto-adjust nil)
4285 ("constcgs" constants-unit-system cgs)
4286 ("constSI" constants-unit-system SI)
4287 ("noptag" org-tag-persistent-alist nil)
4288 ("hideblocks" org-hide-block-startup t)
4289 ("nohideblocks" org-hide-block-startup nil)
4290 ("beamer" org-startup-with-beamer-mode t)
4291 ("entitiespretty" org-pretty-entities t)
4292 ("entitiesplain" org-pretty-entities nil))
4293 "Variable associated with STARTUP options for org-mode.
4294 Each element is a list of three items: The startup options as written
4295 in the #+STARTUP line, the corresponding variable, and the value to
4296 set this variable to if the option is found. An optional forth element PUSH
4297 means to push this value onto the list in the variable.")
4299 (defun org-set-regexps-and-options ()
4300 "Precompute regular expressions for current buffer."
4301 (when (org-mode-p)
4302 (org-set-local 'org-todo-kwd-alist nil)
4303 (org-set-local 'org-todo-key-alist nil)
4304 (org-set-local 'org-todo-key-trigger nil)
4305 (org-set-local 'org-todo-keywords-1 nil)
4306 (org-set-local 'org-done-keywords nil)
4307 (org-set-local 'org-todo-heads nil)
4308 (org-set-local 'org-todo-sets nil)
4309 (org-set-local 'org-todo-log-states nil)
4310 (org-set-local 'org-file-properties nil)
4311 (org-set-local 'org-file-tags nil)
4312 (let ((re (org-make-options-regexp
4313 '("CATEGORY" "TODO" "COLUMNS"
4314 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4315 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4316 "OPTIONS")
4317 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4318 (splitre "[ \t]+")
4319 (scripts org-use-sub-superscripts)
4320 kwds kws0 kwsa key log value cat arch tags const links hw dws
4321 tail sep kws1 prio props ftags drawers beamer-p
4322 ext-setup-or-nil setup-contents (start 0))
4323 (save-excursion
4324 (save-restriction
4325 (widen)
4326 (goto-char (point-min))
4327 (while (or (and ext-setup-or-nil
4328 (string-match re ext-setup-or-nil start)
4329 (setq start (match-end 0)))
4330 (and (setq ext-setup-or-nil nil start 0)
4331 (re-search-forward re nil t)))
4332 (setq key (upcase (match-string 1 ext-setup-or-nil))
4333 value (org-match-string-no-properties 2 ext-setup-or-nil))
4334 (if (stringp value) (setq value (org-trim value)))
4335 (cond
4336 ((equal key "CATEGORY")
4337 (setq cat value))
4338 ((member key '("SEQ_TODO" "TODO"))
4339 (push (cons 'sequence (org-split-string value splitre)) kwds))
4340 ((equal key "TYP_TODO")
4341 (push (cons 'type (org-split-string value splitre)) kwds))
4342 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4343 ;; general TODO-like setup
4344 (push (cons (intern (downcase (match-string 1 key)))
4345 (org-split-string value splitre)) kwds))
4346 ((equal key "TAGS")
4347 (setq tags (append tags (if tags '("\\n") nil)
4348 (org-split-string value splitre))))
4349 ((equal key "COLUMNS")
4350 (org-set-local 'org-columns-default-format value))
4351 ((equal key "LINK")
4352 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4353 (push (cons (match-string 1 value)
4354 (org-trim (match-string 2 value)))
4355 links)))
4356 ((equal key "PRIORITIES")
4357 (setq prio (org-split-string value " +")))
4358 ((equal key "PROPERTY")
4359 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4360 (push (cons (match-string 1 value) (match-string 2 value))
4361 props)))
4362 ((equal key "FILETAGS")
4363 (when (string-match "\\S-" value)
4364 (setq ftags
4365 (append
4366 ftags
4367 (apply 'append
4368 (mapcar (lambda (x) (org-split-string x ":"))
4369 (org-split-string value)))))))
4370 ((equal key "DRAWERS")
4371 (setq drawers (org-split-string value splitre)))
4372 ((equal key "CONSTANTS")
4373 (setq const (append const (org-split-string value splitre))))
4374 ((equal key "STARTUP")
4375 (let ((opts (org-split-string value splitre))
4376 l var val)
4377 (while (setq l (pop opts))
4378 (when (setq l (assoc l org-startup-options))
4379 (setq var (nth 1 l) val (nth 2 l))
4380 (if (not (nth 3 l))
4381 (set (make-local-variable var) val)
4382 (if (not (listp (symbol-value var)))
4383 (set (make-local-variable var) nil))
4384 (set (make-local-variable var) (symbol-value var))
4385 (add-to-list var val))))))
4386 ((equal key "ARCHIVE")
4387 (setq arch value)
4388 (remove-text-properties 0 (length arch)
4389 '(face t fontified t) arch))
4390 ((equal key "LATEX_CLASS")
4391 (setq beamer-p (equal value "beamer")))
4392 ((equal key "OPTIONS")
4393 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4394 (setq scripts (read (match-string 2 value)))))
4395 ((equal key "SETUPFILE")
4396 (setq setup-contents (org-file-contents
4397 (expand-file-name
4398 (org-remove-double-quotes value))
4399 'noerror))
4400 (if (not ext-setup-or-nil)
4401 (setq ext-setup-or-nil setup-contents start 0)
4402 (setq ext-setup-or-nil
4403 (concat (substring ext-setup-or-nil 0 start)
4404 "\n" setup-contents "\n"
4405 (substring ext-setup-or-nil start)))))
4406 ))))
4407 (org-set-local 'org-use-sub-superscripts scripts)
4408 (when cat
4409 (org-set-local 'org-category (intern cat))
4410 (push (cons "CATEGORY" cat) props))
4411 (when prio
4412 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4413 (setq prio (mapcar 'string-to-char prio))
4414 (org-set-local 'org-highest-priority (nth 0 prio))
4415 (org-set-local 'org-lowest-priority (nth 1 prio))
4416 (org-set-local 'org-default-priority (nth 2 prio)))
4417 (and props (org-set-local 'org-file-properties (nreverse props)))
4418 (and ftags (org-set-local 'org-file-tags
4419 (mapcar 'org-add-prop-inherited ftags)))
4420 (and drawers (org-set-local 'org-drawers drawers))
4421 (and arch (org-set-local 'org-archive-location arch))
4422 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4423 ;; Process the TODO keywords
4424 (unless kwds
4425 ;; Use the global values as if they had been given locally.
4426 (setq kwds (default-value 'org-todo-keywords))
4427 (if (stringp (car kwds))
4428 (setq kwds (list (cons org-todo-interpretation
4429 (default-value 'org-todo-keywords)))))
4430 (setq kwds (reverse kwds)))
4431 (setq kwds (nreverse kwds))
4432 (let (inter kws kw)
4433 (while (setq kws (pop kwds))
4434 (let ((kws (or
4435 (run-hook-with-args-until-success
4436 'org-todo-setup-filter-hook kws)
4437 kws)))
4438 (setq inter (pop kws) sep (member "|" kws)
4439 kws0 (delete "|" (copy-sequence kws))
4440 kwsa nil
4441 kws1 (mapcar
4442 (lambda (x)
4443 ;; 1 2
4444 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4445 (progn
4446 (setq kw (match-string 1 x)
4447 key (and (match-end 2) (match-string 2 x))
4448 log (org-extract-log-state-settings x))
4449 (push (cons kw (and key (string-to-char key))) kwsa)
4450 (and log (push log org-todo-log-states))
4452 (error "Invalid TODO keyword %s" x)))
4453 kws0)
4454 kwsa (if kwsa (append '((:startgroup))
4455 (nreverse kwsa)
4456 '((:endgroup))))
4457 hw (car kws1)
4458 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4459 tail (list inter hw (car dws) (org-last dws))))
4460 (add-to-list 'org-todo-heads hw 'append)
4461 (push kws1 org-todo-sets)
4462 (setq org-done-keywords (append org-done-keywords dws nil))
4463 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4464 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4465 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4466 (setq org-todo-sets (nreverse org-todo-sets)
4467 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4468 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4469 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4470 ;; Process the constants
4471 (when const
4472 (let (e cst)
4473 (while (setq e (pop const))
4474 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4475 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4476 (setq org-table-formula-constants-local cst)))
4478 ;; Process the tags.
4479 (when tags
4480 (let (e tgs)
4481 (while (setq e (pop tags))
4482 (cond
4483 ((equal e "{") (push '(:startgroup) tgs))
4484 ((equal e "}") (push '(:endgroup) tgs))
4485 ((equal e "\\n") (push '(:newline) tgs))
4486 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4487 (push (cons (match-string 1 e)
4488 (string-to-char (match-string 2 e)))
4489 tgs))
4490 (t (push (list e) tgs))))
4491 (org-set-local 'org-tag-alist nil)
4492 (while (setq e (pop tgs))
4493 (or (and (stringp (car e))
4494 (assoc (car e) org-tag-alist))
4495 (push e org-tag-alist)))))
4497 ;; Compute the regular expressions and other local variables
4498 (if (not org-done-keywords)
4499 (setq org-done-keywords (and org-todo-keywords-1
4500 (list (org-last org-todo-keywords-1)))))
4501 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4502 (length org-scheduled-string)
4503 (length org-clock-string)
4504 (length org-closed-string)))
4505 org-drawer-regexp
4506 (concat "^[ \t]*:\\("
4507 (mapconcat 'regexp-quote org-drawers "\\|")
4508 "\\):[ \t]*$")
4509 org-not-done-keywords
4510 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4511 org-todo-regexp
4512 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4513 "\\|") "\\)\\>")
4514 org-not-done-regexp
4515 (concat "\\<\\("
4516 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4517 "\\)\\>")
4518 org-not-done-heading-regexp
4519 (concat "^\\(\\*+\\)[ \t]+\\("
4520 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4521 "\\)\\>")
4522 org-todo-line-regexp
4523 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4524 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4525 "\\)\\>\\)?[ \t]*\\(.*\\)")
4526 org-complex-heading-regexp
4527 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4528 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4529 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4530 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
4531 org-complex-heading-regexp-format
4532 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4533 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4534 "\\)\\>\\)?"
4535 "\\(?:[ \t]*\\(\\[#.\\]\\)\\)?"
4536 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4537 "[ \t]*\\(%s\\)"
4538 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4539 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?[ \t]*$")
4540 org-nl-done-regexp
4541 (concat "\n\\*+[ \t]+"
4542 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4543 "\\)" "\\>")
4544 org-todo-line-tags-regexp
4545 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4546 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4547 (org-re
4548 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@#%]+:[ \t]*\\)?$\\)"))
4549 org-looking-at-done-regexp
4550 (concat "^" "\\(?:"
4551 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4552 "\\>")
4553 org-deadline-regexp (concat "\\<" org-deadline-string)
4554 org-deadline-time-regexp
4555 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4556 org-deadline-line-regexp
4557 (concat "\\<\\(" org-deadline-string "\\).*")
4558 org-scheduled-regexp
4559 (concat "\\<" org-scheduled-string)
4560 org-scheduled-time-regexp
4561 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4562 org-closed-time-regexp
4563 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4564 org-keyword-time-regexp
4565 (concat "\\<\\(" org-scheduled-string
4566 "\\|" org-deadline-string
4567 "\\|" org-closed-string
4568 "\\|" org-clock-string "\\)"
4569 " *[[<]\\([^]>]+\\)[]>]")
4570 org-keyword-time-not-clock-regexp
4571 (concat "\\<\\(" org-scheduled-string
4572 "\\|" org-deadline-string
4573 "\\|" org-closed-string
4574 "\\)"
4575 " *[[<]\\([^]>]+\\)[]>]")
4576 org-maybe-keyword-time-regexp
4577 (concat "\\(\\<\\(" org-scheduled-string
4578 "\\|" org-deadline-string
4579 "\\|" org-closed-string
4580 "\\|" org-clock-string "\\)\\)?"
4581 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4582 org-planning-or-clock-line-re
4583 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4584 "\\|" org-deadline-string
4585 "\\|" org-closed-string "\\|" org-clock-string
4586 "\\)\\>\\)")
4587 org-all-time-keywords
4588 (mapcar (lambda (w) (substring w 0 -1))
4589 (list org-scheduled-string org-deadline-string
4590 org-clock-string org-closed-string))
4592 (org-compute-latex-and-specials-regexp)
4593 (org-set-font-lock-defaults))))
4595 (defun org-file-contents (file &optional noerror)
4596 "Return the contents of FILE, as a string."
4597 (if (or (not file)
4598 (not (file-readable-p file)))
4599 (if noerror
4600 (progn
4601 (message "Cannot read file \"%s\"" file)
4602 (ding) (sit-for 2)
4604 (error "Cannot read file \"%s\"" file))
4605 (with-temp-buffer
4606 (insert-file-contents file)
4607 (buffer-string))))
4609 (defun org-extract-log-state-settings (x)
4610 "Extract the log state setting from a TODO keyword string.
4611 This will extract info from a string like \"WAIT(w@/!)\"."
4612 (let (kw key log1 log2)
4613 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4614 (setq kw (match-string 1 x)
4615 key (and (match-end 2) (match-string 2 x))
4616 log1 (and (match-end 3) (match-string 3 x))
4617 log2 (and (match-end 4) (match-string 4 x)))
4618 (and (or log1 log2)
4619 (list kw
4620 (and log1 (if (equal log1 "!") 'time 'note))
4621 (and log2 (if (equal log2 "!") 'time 'note)))))))
4623 (defun org-remove-keyword-keys (list)
4624 "Remove a pair of parenthesis at the end of each string in LIST."
4625 (mapcar (lambda (x)
4626 (if (string-match "(.*)$" x)
4627 (substring x 0 (match-beginning 0))
4629 list))
4631 (defun org-assign-fast-keys (alist)
4632 "Assign fast keys to a keyword-key alist.
4633 Respect keys that are already there."
4634 (let (new e (alt ?0))
4635 (while (setq e (pop alist))
4636 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4637 (cdr e)) ;; Key already assigned.
4638 (push e new)
4639 (let ((clist (string-to-list (downcase (car e))))
4640 (used (append new alist)))
4641 (when (= (car clist) ?@)
4642 (pop clist))
4643 (while (and clist (rassoc (car clist) used))
4644 (pop clist))
4645 (unless clist
4646 (while (rassoc alt used)
4647 (incf alt)))
4648 (push (cons (car e) (or (car clist) alt)) new))))
4649 (nreverse new)))
4651 ;;; Some variables used in various places
4653 (defvar org-window-configuration nil
4654 "Used in various places to store a window configuration.")
4655 (defvar org-selected-window nil
4656 "Used in various places to store a window configuration.")
4657 (defvar org-finish-function nil
4658 "Function to be called when `C-c C-c' is used.
4659 This is for getting out of special buffers like remember.")
4662 ;; FIXME: Occasionally check by commenting these, to make sure
4663 ;; no other functions uses these, forgetting to let-bind them.
4664 (defvar entry)
4665 (defvar last-state)
4666 (defvar date)
4668 ;; Defined somewhere in this file, but used before definition.
4669 (defvar org-entities) ;; defined in org-entities.el
4670 (defvar org-struct-menu)
4671 (defvar org-org-menu)
4672 (defvar org-tbl-menu)
4674 ;;;; Define the Org-mode
4676 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4677 (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"))
4680 ;; We use a before-change function to check if a table might need
4681 ;; an update.
4682 (defvar org-table-may-need-update t
4683 "Indicates that a table might need an update.
4684 This variable is set by `org-before-change-function'.
4685 `org-table-align' sets it back to nil.")
4686 (defun org-before-change-function (beg end)
4687 "Every change indicates that a table might need an update."
4688 (setq org-table-may-need-update t))
4689 (defvar org-mode-map)
4690 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4691 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4692 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4693 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4694 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4695 (defvar org-table-buffer-is-an nil)
4696 (defconst org-outline-regexp "\\*+ ")
4698 ;;;###autoload
4699 (define-derived-mode org-mode outline-mode "Org"
4700 "Outline-based notes management and organizer, alias
4701 \"Carsten's outline-mode for keeping track of everything.\"
4703 Org-mode develops organizational tasks around a NOTES file which
4704 contains information about projects as plain text. Org-mode is
4705 implemented on top of outline-mode, which is ideal to keep the content
4706 of large files well structured. It supports ToDo items, deadlines and
4707 time stamps, which magically appear in the diary listing of the Emacs
4708 calendar. Tables are easily created with a built-in table editor.
4709 Plain text URL-like links connect to websites, emails (VM), Usenet
4710 messages (Gnus), BBDB entries, and any files related to the project.
4711 For printing and sharing of notes, an Org-mode file (or a part of it)
4712 can be exported as a structured ASCII or HTML file.
4714 The following commands are available:
4716 \\{org-mode-map}"
4718 ;; Get rid of Outline menus, they are not needed
4719 ;; Need to do this here because define-derived-mode sets up
4720 ;; the keymap so late. Still, it is a waste to call this each time
4721 ;; we switch another buffer into org-mode.
4722 (if (featurep 'xemacs)
4723 (when (boundp 'outline-mode-menu-heading)
4724 ;; Assume this is Greg's port, it uses easymenu
4725 (easy-menu-remove outline-mode-menu-heading)
4726 (easy-menu-remove outline-mode-menu-show)
4727 (easy-menu-remove outline-mode-menu-hide))
4728 (define-key org-mode-map [menu-bar headings] 'undefined)
4729 (define-key org-mode-map [menu-bar hide] 'undefined)
4730 (define-key org-mode-map [menu-bar show] 'undefined))
4732 (org-load-modules-maybe)
4733 (easy-menu-add org-org-menu)
4734 (easy-menu-add org-tbl-menu)
4735 (org-install-agenda-files-menu)
4736 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4737 (add-to-invisibility-spec '(org-cwidth))
4738 (add-to-invisibility-spec '(org-hide-block . t))
4739 (when (featurep 'xemacs)
4740 (org-set-local 'line-move-ignore-invisible t))
4741 (org-set-local 'outline-regexp org-outline-regexp)
4742 (org-set-local 'outline-level 'org-outline-level)
4743 (when (and org-ellipsis
4744 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4745 (fboundp 'make-glyph-code))
4746 (unless org-display-table
4747 (setq org-display-table (make-display-table)))
4748 (set-display-table-slot
4749 org-display-table 4
4750 (vconcat (mapcar
4751 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4752 org-ellipsis)))
4753 (if (stringp org-ellipsis) org-ellipsis "..."))))
4754 (setq buffer-display-table org-display-table))
4755 (org-set-regexps-and-options)
4756 (when (and org-tag-faces (not org-tags-special-faces-re))
4757 ;; tag faces set outside customize.... force initialization.
4758 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4759 ;; Calc embedded
4760 (org-set-local 'calc-embedded-open-mode "# ")
4761 (modify-syntax-entry ?@ "w")
4762 (if org-startup-truncated (setq truncate-lines t))
4763 (org-set-local 'font-lock-unfontify-region-function
4764 'org-unfontify-region)
4765 ;; Activate before-change-function
4766 (org-set-local 'org-table-may-need-update t)
4767 (org-add-hook 'before-change-functions 'org-before-change-function nil
4768 'local)
4769 ;; Check for running clock before killing a buffer
4770 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4771 ;; Paragraphs and auto-filling
4772 (org-set-autofill-regexps)
4773 (setq indent-line-function 'org-indent-line-function)
4774 (org-update-radio-target-regexp)
4775 ;; Beginning/end of defun
4776 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4777 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4778 ;; Next error for sparse trees
4779 (org-set-local 'next-error-function 'org-occur-next-match)
4780 ;; Make sure dependence stuff works reliably, even for users who set it
4781 ;; too late :-(
4782 (if org-enforce-todo-dependencies
4783 (add-hook 'org-blocker-hook
4784 'org-block-todo-from-children-or-siblings-or-parent)
4785 (remove-hook 'org-blocker-hook
4786 'org-block-todo-from-children-or-siblings-or-parent))
4787 (if org-enforce-todo-checkbox-dependencies
4788 (add-hook 'org-blocker-hook
4789 'org-block-todo-from-checkboxes)
4790 (remove-hook 'org-blocker-hook
4791 'org-block-todo-from-checkboxes))
4793 ;; Comment characters
4794 (org-set-local 'comment-start "#")
4795 (org-set-local 'comment-padding " ")
4797 ;; Align options lines
4798 (org-set-local
4799 'align-mode-rules-list
4800 '((org-in-buffer-settings
4801 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4802 (modes . '(org-mode)))))
4804 ;; Imenu
4805 (org-set-local 'imenu-create-index-function
4806 'org-imenu-get-tree)
4808 ;; Make isearch reveal context
4809 (if (or (featurep 'xemacs)
4810 (not (boundp 'outline-isearch-open-invisible-function)))
4811 ;; Emacs 21 and XEmacs make use of the hook
4812 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4813 ;; Emacs 22 deals with this through a special variable
4814 (org-set-local 'outline-isearch-open-invisible-function
4815 (lambda (&rest ignore) (org-show-context 'isearch))))
4817 ;; Turn on org-beamer-mode?
4818 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4820 ;; Setup the pcomplete hooks
4821 (set (make-local-variable 'pcomplete-command-completion-function)
4822 'org-pcomplete-initial)
4823 (set (make-local-variable 'pcomplete-command-name-function)
4824 'org-command-at-point)
4825 (set (make-local-variable 'pcomplete-default-completion-function)
4826 'ignore)
4827 (set (make-local-variable 'pcomplete-parse-arguments-function)
4828 'org-parse-arguments)
4829 (set (make-local-variable 'pcomplete-termination-string) "")
4831 ;; If empty file that did not turn on org-mode automatically, make it to.
4832 (if (and org-insert-mode-line-in-empty-file
4833 (interactive-p)
4834 (= (point-min) (point-max)))
4835 (insert "# -*- mode: org -*-\n\n"))
4836 (unless org-inhibit-startup
4837 (when org-startup-align-all-tables
4838 (let ((bmp (buffer-modified-p)))
4839 (org-table-map-tables 'org-table-align 'quietly)
4840 (set-buffer-modified-p bmp)))
4841 (when org-startup-with-inline-images
4842 (org-display-inline-images))
4843 (when org-startup-indented
4844 (require 'org-indent)
4845 (org-indent-mode 1))
4846 (unless org-inhibit-startup-visibility-stuff
4847 (org-set-startup-visibility))))
4849 (when (fboundp 'abbrev-table-put)
4850 (abbrev-table-put org-mode-abbrev-table
4851 :parents (list text-mode-abbrev-table)))
4853 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4855 (defun org-current-time ()
4856 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4857 (if (> (car org-time-stamp-rounding-minutes) 1)
4858 (let ((r (car org-time-stamp-rounding-minutes))
4859 (time (decode-time)))
4860 (apply 'encode-time
4861 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4862 (nthcdr 2 time))))
4863 (current-time)))
4865 (defun org-today ()
4866 "Return today date, considering `org-extend-today-until'."
4867 (time-to-days
4868 (time-subtract (current-time)
4869 (list 0 (* 3600 org-extend-today-until) 0))))
4871 ;;;; Font-Lock stuff, including the activators
4873 (defvar org-mouse-map (make-sparse-keymap))
4874 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
4875 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
4876 (when org-mouse-1-follows-link
4877 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4878 (when org-tab-follows-link
4879 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4880 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4882 (require 'font-lock)
4884 (defconst org-non-link-chars "]\t\n\r<>")
4885 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4886 "shell" "elisp" "doi" "message"))
4887 (defvar org-link-types-re nil
4888 "Matches a link that has a url-like prefix like \"http:\"")
4889 (defvar org-link-re-with-space nil
4890 "Matches a link with spaces, optional angular brackets around it.")
4891 (defvar org-link-re-with-space2 nil
4892 "Matches a link with spaces, optional angular brackets around it.")
4893 (defvar org-link-re-with-space3 nil
4894 "Matches a link with spaces, only for internal part in bracket links.")
4895 (defvar org-angle-link-re nil
4896 "Matches link with angular brackets, spaces are allowed.")
4897 (defvar org-plain-link-re nil
4898 "Matches plain link, without spaces.")
4899 (defvar org-bracket-link-regexp nil
4900 "Matches a link in double brackets.")
4901 (defvar org-bracket-link-analytic-regexp nil
4902 "Regular expression used to analyze links.
4903 Here is what the match groups contain after a match:
4904 1: http:
4905 2: http
4906 3: path
4907 4: [desc]
4908 5: desc")
4909 (defvar org-bracket-link-analytic-regexp++ nil
4910 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
4911 (defvar org-any-link-re nil
4912 "Regular expression matching any link.")
4914 (defcustom org-match-sexp-depth 3
4915 "Number of stacked braces for sub/superscript matching.
4916 This has to be set before loading org.el to be effective."
4917 :group 'org-export-translation ; ??????????????????????????/
4918 :type 'integer)
4920 (defun org-create-multibrace-regexp (left right n)
4921 "Create a regular expression which will match a balanced sexp.
4922 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
4923 as single character strings.
4924 The regexp returned will match the entire expression including the
4925 delimiters. It will also define a single group which contains the
4926 match except for the outermost delimiters. The maximum depth of
4927 stacked delimiters is N. Escaping delimiters is not possible."
4928 (let* ((nothing (concat "[^" left right "]*?"))
4929 (or "\\|")
4930 (re nothing)
4931 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
4932 (while (> n 1)
4933 (setq n (1- n)
4934 re (concat re or next)
4935 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
4936 (concat left "\\(" re "\\)" right)))
4938 (defvar org-match-substring-regexp
4939 (concat
4940 "\\([^\\]\\)\\([_^]\\)\\("
4941 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4942 "\\|"
4943 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
4944 "\\|"
4945 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
4946 "The regular expression matching a sub- or superscript.")
4948 (defvar org-match-substring-with-braces-regexp
4949 (concat
4950 "\\([^\\]\\)\\([_^]\\)\\("
4951 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4952 "\\)")
4953 "The regular expression matching a sub- or superscript, forcing braces.")
4955 (defun org-make-link-regexps ()
4956 "Update the link regular expressions.
4957 This should be called after the variable `org-link-types' has changed."
4958 (setq org-link-types-re
4959 (concat
4960 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4961 org-link-re-with-space
4962 (concat
4963 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4964 "\\([^" org-non-link-chars " ]"
4965 "[^" org-non-link-chars "]*"
4966 "[^" org-non-link-chars " ]\\)>?")
4967 org-link-re-with-space2
4968 (concat
4969 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4970 "\\([^" org-non-link-chars " ]"
4971 "[^\t\n\r]*"
4972 "[^" org-non-link-chars " ]\\)>?")
4973 org-link-re-with-space3
4974 (concat
4975 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4976 "\\([^" org-non-link-chars " ]"
4977 "[^\t\n\r]*\\)")
4978 org-angle-link-re
4979 (concat
4980 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4981 "\\([^" org-non-link-chars " ]"
4982 "[^" org-non-link-chars "]*"
4983 "\\)>")
4984 org-plain-link-re
4985 (concat
4986 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4987 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4988 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4989 org-bracket-link-regexp
4990 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4991 org-bracket-link-analytic-regexp
4992 (concat
4993 "\\[\\["
4994 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4995 "\\([^]]+\\)"
4996 "\\]"
4997 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4998 "\\]")
4999 org-bracket-link-analytic-regexp++
5000 (concat
5001 "\\[\\["
5002 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5003 "\\([^]]+\\)"
5004 "\\]"
5005 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5006 "\\]")
5007 org-any-link-re
5008 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5009 org-angle-link-re "\\)\\|\\("
5010 org-plain-link-re "\\)")))
5012 (org-make-link-regexps)
5014 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5015 "Regular expression for fast time stamp matching.")
5016 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?\\)[]>]"
5017 "Regular expression for fast time stamp matching.")
5018 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5019 "Regular expression matching time strings for analysis.
5020 This one does not require the space after the date, so it can be used
5021 on a string that terminates immediately after the date.")
5022 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5023 "Regular expression matching time strings for analysis.")
5024 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5025 "Regular expression matching time stamps, with groups.")
5026 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5027 "Regular expression matching time stamps (also [..]), with groups.")
5028 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5029 "Regular expression matching a time stamp range.")
5030 (defconst org-tr-regexp-both
5031 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5032 "Regular expression matching a time stamp range.")
5033 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5034 org-ts-regexp "\\)?")
5035 "Regular expression matching a time stamp or time stamp range.")
5036 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5037 org-ts-regexp-both "\\)?")
5038 "Regular expression matching a time stamp or time stamp range.
5039 The time stamps may be either active or inactive.")
5041 (defvar org-emph-face nil)
5043 (defun org-do-emphasis-faces (limit)
5044 "Run through the buffer and add overlays to links."
5045 (let (rtn a)
5046 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5047 (if (not (= (char-after (match-beginning 3))
5048 (char-after (match-beginning 4))))
5049 (progn
5050 (setq rtn t)
5051 (setq a (assoc (match-string 3) org-emphasis-alist))
5052 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5053 'face
5054 (nth 1 a))
5055 (and (nth 4 a)
5056 (org-remove-flyspell-overlays-in
5057 (match-beginning 0) (match-end 0)))
5058 (add-text-properties (match-beginning 2) (match-end 2)
5059 '(font-lock-multiline t org-emphasis t))
5060 (when org-hide-emphasis-markers
5061 (add-text-properties (match-end 4) (match-beginning 5)
5062 '(invisible org-link))
5063 (add-text-properties (match-beginning 3) (match-end 3)
5064 '(invisible org-link)))))
5065 (backward-char 1))
5066 rtn))
5068 (defun org-emphasize (&optional char)
5069 "Insert or change an emphasis, i.e. a font like bold or italic.
5070 If there is an active region, change that region to a new emphasis.
5071 If there is no region, just insert the marker characters and position
5072 the cursor between them.
5073 CHAR should be either the marker character, or the first character of the
5074 HTML tag associated with that emphasis. If CHAR is a space, the means
5075 to remove the emphasis of the selected region.
5076 If char is not given (for example in an interactive call) it
5077 will be prompted for."
5078 (interactive)
5079 (let ((eal org-emphasis-alist) e det
5080 (erc org-emphasis-regexp-components)
5081 (prompt "")
5082 (string "") beg end move tag c s)
5083 (if (org-region-active-p)
5084 (setq beg (region-beginning) end (region-end)
5085 string (buffer-substring beg end))
5086 (setq move t))
5088 (while (setq e (pop eal))
5089 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5090 c (aref tag 0))
5091 (push (cons c (string-to-char (car e))) det)
5092 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5093 (substring tag 1)))))
5094 (setq det (nreverse det))
5095 (unless char
5096 (message "%s" (concat "Emphasis marker or tag:" prompt))
5097 (setq char (read-char-exclusive)))
5098 (setq char (or (cdr (assoc char det)) char))
5099 (if (equal char ?\ )
5100 (setq s "" move nil)
5101 (unless (assoc (char-to-string char) org-emphasis-alist)
5102 (error "No such emphasis marker: \"%c\"" char))
5103 (setq s (char-to-string char)))
5104 (while (and (> (length string) 1)
5105 (equal (substring string 0 1) (substring string -1))
5106 (assoc (substring string 0 1) org-emphasis-alist))
5107 (setq string (substring string 1 -1)))
5108 (setq string (concat s string s))
5109 (if beg (delete-region beg end))
5110 (unless (or (bolp)
5111 (string-match (concat "[" (nth 0 erc) "\n]")
5112 (char-to-string (char-before (point)))))
5113 (insert " "))
5114 (unless (or (eobp)
5115 (string-match (concat "[" (nth 1 erc) "\n]")
5116 (char-to-string (char-after (point)))))
5117 (insert " ") (backward-char 1))
5118 (insert string)
5119 (and move (backward-char 1))))
5121 (defconst org-nonsticky-props
5122 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5124 (defsubst org-rear-nonsticky-at (pos)
5125 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5127 (defun org-activate-plain-links (limit)
5128 "Run through the buffer and add overlays to links."
5129 (catch 'exit
5130 (let (f)
5131 (if (re-search-forward org-plain-link-re limit t)
5132 (progn
5133 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5134 (setq f (get-text-property (match-beginning 0) 'face))
5135 (if (or (eq f 'org-tag)
5136 (and (listp f) (memq 'org-tag f)))
5138 (add-text-properties (match-beginning 0) (match-end 0)
5139 (list 'mouse-face 'highlight
5140 'face 'org-link
5141 'keymap org-mouse-map))
5142 (org-rear-nonsticky-at (match-end 0)))
5143 t)))))
5145 (defun org-activate-code (limit)
5146 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
5147 (progn
5148 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5149 (remove-text-properties (match-beginning 0) (match-end 0)
5150 '(display t invisible t intangible t))
5151 t)))
5153 (defcustom org-src-fontify-natively nil
5154 "When non-nil, fontify code in code blocks."
5155 :type 'boolean
5156 :group 'org-appearance
5157 :group 'org-babel)
5159 (defun org-fontify-meta-lines-and-blocks (limit)
5160 "Fontify #+ lines and blocks, in the correct ways."
5161 (let ((case-fold-search t))
5162 (if (re-search-forward
5163 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5164 limit t)
5165 (let ((beg (match-beginning 0))
5166 (block-start (match-end 0))
5167 (block-end nil)
5168 (lang (match-string 7))
5169 (beg1 (line-beginning-position 2))
5170 (dc1 (downcase (match-string 2)))
5171 (dc3 (downcase (match-string 3)))
5172 end end1 quoting block-type ovl)
5173 (cond
5174 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5175 ;; a single line of backend-specific content
5176 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5177 (remove-text-properties (match-beginning 0) (match-end 0)
5178 '(display t invisible t intangible t))
5179 (add-text-properties (match-beginning 1) (match-end 3)
5180 '(font-lock-fontified t face org-meta-line))
5181 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5182 '(font-lock-fontified t face org-block))
5183 ; for backend-specific code
5185 ((and (match-end 4) (equal dc3 "begin"))
5186 ;; Truly a block
5187 (setq block-type (downcase (match-string 5))
5188 quoting (member block-type org-protecting-blocks))
5189 (when (re-search-forward
5190 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5191 nil t) ;; on purpose, we look further than LIMIT
5192 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5193 (setq block-end (match-beginning 0))
5194 (when quoting
5195 (remove-text-properties beg end
5196 '(display t invisible t intangible t)))
5197 (add-text-properties
5198 beg end
5199 '(font-lock-fontified t font-lock-multiline t))
5200 (add-text-properties beg beg1 '(face org-meta-line))
5201 (add-text-properties end1 (+ end 1) '(face org-meta-line))
5202 ; for end_src
5203 (cond
5204 ((and lang org-src-fontify-natively)
5205 (org-src-font-lock-fontify-block lang block-start block-end)
5206 ;; remove old background overlays
5207 (mapc (lambda (ov)
5208 (if (eq (overlay-get ov 'face) 'org-block-background)
5209 (delete-overlay ov)))
5210 (overlays-at (/ (+ beg1 block-end) 2)))
5211 ;; add a background overlay
5212 (setq ovl (make-overlay beg1 block-end))
5213 (overlay-put ovl 'face 'org-block-background)
5214 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5215 (quoting
5216 (add-text-properties beg1 (+ end1 1) '(face org-block)))
5217 ; end of source block
5218 ((not org-fontify-quote-and-verse-blocks))
5219 ((string= block-type "quote")
5220 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5221 ((string= block-type "verse")
5222 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5223 (add-text-properties beg beg1 '(face org-block-begin-line))
5224 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5226 ((member dc1 '("title:" "author:" "email:" "date:"))
5227 (add-text-properties
5228 beg (match-end 3)
5229 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5230 '(font-lock-fontified t invisible t)
5231 '(font-lock-fontified t face org-document-info-keyword)))
5232 (add-text-properties
5233 (match-beginning 6) (match-end 6)
5234 (if (string-equal dc1 "title:")
5235 '(font-lock-fontified t face org-document-title)
5236 '(font-lock-fontified t face org-document-info))))
5237 ((not (member (char-after beg) '(?\ ?\t)))
5238 ;; just any other in-buffer setting, but not indented
5239 (add-text-properties
5240 beg (1+ (match-end 0))
5241 '(font-lock-fontified t face org-meta-line))
5243 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5244 "orgtbl:" "tblfm:" "tblname:" "result:"
5245 "results:" "source:" "srcname:" "call:"))
5246 (and (match-end 4) (equal dc3 "attr")))
5247 (add-text-properties
5248 beg (match-end 0)
5249 '(font-lock-fontified t face org-meta-line))
5251 ((member dc3 '(" " ""))
5252 (add-text-properties
5253 beg (match-end 0)
5254 '(font-lock-fontified t face font-lock-comment-face)))
5255 (t nil))))))
5257 (defun org-activate-angle-links (limit)
5258 "Run through the buffer and add overlays to links."
5259 (if (re-search-forward org-angle-link-re limit t)
5260 (progn
5261 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5262 (add-text-properties (match-beginning 0) (match-end 0)
5263 (list 'mouse-face 'highlight
5264 'keymap org-mouse-map))
5265 (org-rear-nonsticky-at (match-end 0))
5266 t)))
5268 (defun org-activate-footnote-links (limit)
5269 "Run through the buffer and add overlays to links."
5270 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
5271 limit t)
5272 (progn
5273 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5274 (add-text-properties (match-beginning 2) (match-end 2)
5275 (list 'mouse-face 'highlight
5276 'keymap org-mouse-map
5277 'help-echo
5278 (if (= (point-at-bol) (match-beginning 2))
5279 "Footnote definition"
5280 "Footnote reference")
5282 (org-rear-nonsticky-at (match-end 2))
5283 t)))
5285 (defun org-activate-bracket-links (limit)
5286 "Run through the buffer and add overlays to bracketed links."
5287 (if (re-search-forward org-bracket-link-regexp limit t)
5288 (let* ((help (concat "LINK: "
5289 (org-match-string-no-properties 1)))
5290 ;; FIXME: above we should remove the escapes.
5291 ;; but that requires another match, protecting match data,
5292 ;; a lot of overhead for font-lock.
5293 (ip (org-maybe-intangible
5294 (list 'invisible 'org-link
5295 'keymap org-mouse-map 'mouse-face 'highlight
5296 'font-lock-multiline t 'help-echo help)))
5297 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5298 'font-lock-multiline t 'help-echo help)))
5299 ;; We need to remove the invisible property here. Table narrowing
5300 ;; may have made some of this invisible.
5301 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5302 (remove-text-properties (match-beginning 0) (match-end 0)
5303 '(invisible nil))
5304 (if (match-end 3)
5305 (progn
5306 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5307 (org-rear-nonsticky-at (match-beginning 3))
5308 (add-text-properties (match-beginning 3) (match-end 3) vp)
5309 (org-rear-nonsticky-at (match-end 3))
5310 (add-text-properties (match-end 3) (match-end 0) ip)
5311 (org-rear-nonsticky-at (match-end 0)))
5312 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5313 (org-rear-nonsticky-at (match-beginning 1))
5314 (add-text-properties (match-beginning 1) (match-end 1) vp)
5315 (org-rear-nonsticky-at (match-end 1))
5316 (add-text-properties (match-end 1) (match-end 0) ip)
5317 (org-rear-nonsticky-at (match-end 0)))
5318 t)))
5320 (defun org-activate-dates (limit)
5321 "Run through the buffer and add overlays to dates."
5322 (if (re-search-forward org-tsr-regexp-both limit t)
5323 (progn
5324 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5325 (add-text-properties (match-beginning 0) (match-end 0)
5326 (list 'mouse-face 'highlight
5327 'keymap org-mouse-map))
5328 (org-rear-nonsticky-at (match-end 0))
5329 (when org-display-custom-times
5330 (if (match-end 3)
5331 (org-display-custom-time (match-beginning 3) (match-end 3)))
5332 (org-display-custom-time (match-beginning 1) (match-end 1)))
5333 t)))
5335 (defvar org-target-link-regexp nil
5336 "Regular expression matching radio targets in plain text.")
5337 (make-variable-buffer-local 'org-target-link-regexp)
5338 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5339 "Regular expression matching a link target.")
5340 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5341 "Regular expression matching a radio target.")
5342 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5343 "Regular expression matching any target.")
5345 (defun org-activate-target-links (limit)
5346 "Run through the buffer and add overlays to target matches."
5347 (when org-target-link-regexp
5348 (let ((case-fold-search t))
5349 (if (re-search-forward org-target-link-regexp limit t)
5350 (progn
5351 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5352 (add-text-properties (match-beginning 0) (match-end 0)
5353 (list 'mouse-face 'highlight
5354 'keymap org-mouse-map
5355 'help-echo "Radio target link"
5356 'org-linked-text t))
5357 (org-rear-nonsticky-at (match-end 0))
5358 t)))))
5360 (defun org-update-radio-target-regexp ()
5361 "Find all radio targets in this file and update the regular expression."
5362 (interactive)
5363 (when (memq 'radio org-activate-links)
5364 (setq org-target-link-regexp
5365 (org-make-target-link-regexp (org-all-targets 'radio)))
5366 (org-restart-font-lock)))
5368 (defun org-hide-wide-columns (limit)
5369 (let (s e)
5370 (setq s (text-property-any (point) (or limit (point-max))
5371 'org-cwidth t))
5372 (when s
5373 (setq e (next-single-property-change s 'org-cwidth))
5374 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5375 (goto-char e)
5376 t)))
5378 (defvar org-latex-and-specials-regexp nil
5379 "Regular expression for highlighting export special stuff.")
5380 (defvar org-match-substring-regexp)
5381 (defvar org-match-substring-with-braces-regexp)
5383 ;; This should be with the exporter code, but we also use if for font-locking
5384 (defconst org-export-html-special-string-regexps
5385 '(("\\\\-" . "&shy;")
5386 ("---\\([^-]\\)" . "&mdash;\\1")
5387 ("--\\([^-]\\)" . "&ndash;\\1")
5388 ("\\.\\.\\." . "&hellip;"))
5389 "Regular expressions for special string conversion.")
5392 (defun org-compute-latex-and-specials-regexp ()
5393 "Compute regular expression for stuff treated specially by exporters."
5394 (if (not org-highlight-latex-fragments-and-specials)
5395 (org-set-local 'org-latex-and-specials-regexp nil)
5396 (require 'org-exp)
5397 (let*
5398 ((matchers (plist-get org-format-latex-options :matchers))
5399 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5400 org-latex-regexps)))
5401 (org-export-allow-BIND nil)
5402 (options (org-combine-plists (org-default-export-plist)
5403 (org-infile-export-plist)))
5404 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5405 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5406 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5407 (org-export-html-expand (plist-get options :expand-quoted-html))
5408 (org-export-with-special-strings (plist-get options :special-strings))
5409 (re-sub
5410 (cond
5411 ((equal org-export-with-sub-superscripts '{})
5412 (list org-match-substring-with-braces-regexp))
5413 (org-export-with-sub-superscripts
5414 (list org-match-substring-regexp))
5415 (t nil)))
5416 (re-latex
5417 (if org-export-with-LaTeX-fragments
5418 (mapcar (lambda (x) (nth 1 x)) latexs)))
5419 (re-macros
5420 (if org-export-with-TeX-macros
5421 (list (concat "\\\\"
5422 (regexp-opt
5423 (append
5425 (delq nil
5426 (mapcar 'car-safe
5427 (append org-entities-user
5428 org-entities)))
5429 (if (boundp 'org-latex-entities)
5430 (mapcar (lambda (x)
5431 (or (car-safe x) x))
5432 org-latex-entities)
5433 nil))
5434 'words))) ; FIXME
5436 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5437 (re-special (if org-export-with-special-strings
5438 (mapcar (lambda (x) (car x))
5439 org-export-html-special-string-regexps)))
5440 (re-rest
5441 (delq nil
5442 (list
5443 (if org-export-html-expand "@<[^>\n]+>")
5444 ))))
5445 (org-set-local
5446 'org-latex-and-specials-regexp
5447 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5448 re-rest) "\\|")))))
5450 (defun org-do-latex-and-special-faces (limit)
5451 "Run through the buffer and add overlays to links."
5452 (when org-latex-and-specials-regexp
5453 (let (rtn d)
5454 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5455 limit t))
5456 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5457 'face))
5458 '(org-code org-verbatim underline)))
5459 (progn
5460 (setq rtn t
5461 d (cond ((member (char-after (1+ (match-beginning 0)))
5462 '(?_ ?^)) 1)
5463 (t 0)))
5464 (font-lock-prepend-text-property
5465 (+ d (match-beginning 0)) (match-end 0)
5466 'face 'org-latex-and-export-specials)
5467 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5468 '(font-lock-multiline t)))))
5469 rtn)))
5471 (defun org-restart-font-lock ()
5472 "Restart `font-lock-mode', to force refontification."
5473 (when (and (boundp 'font-lock-mode) font-lock-mode)
5474 (font-lock-mode -1)
5475 (font-lock-mode 1)))
5477 (defun org-all-targets (&optional radio)
5478 "Return a list of all targets in this file.
5479 With optional argument RADIO, only find radio targets."
5480 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5481 rtn)
5482 (save-excursion
5483 (goto-char (point-min))
5484 (while (re-search-forward re nil t)
5485 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5486 rtn)))
5488 (defun org-make-target-link-regexp (targets)
5489 "Make regular expression matching all strings in TARGETS.
5490 The regular expression finds the targets also if there is a line break
5491 between words."
5492 (and targets
5493 (concat
5494 "\\<\\("
5495 (mapconcat
5496 (lambda (x)
5497 (setq x (regexp-quote x))
5498 (while (string-match " +" x)
5499 (setq x (replace-match "\\s-+" t t x)))
5501 targets
5502 "\\|")
5503 "\\)\\>")))
5505 (defun org-activate-tags (limit)
5506 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5507 (progn
5508 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5509 (add-text-properties (match-beginning 1) (match-end 1)
5510 (list 'mouse-face 'highlight
5511 'keymap org-mouse-map))
5512 (org-rear-nonsticky-at (match-end 1))
5513 t)))
5515 (defun org-outline-level ()
5516 "Compute the outline level of the heading at point.
5517 This function assumes that the cursor is at the beginning of a line matched
5518 by `outline-regexp'. Otherwise it returns garbage.
5519 If this is called at a normal headline, the level is the number of stars.
5520 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5521 (save-excursion
5522 (looking-at outline-regexp)
5523 (1- (- (match-end 0) (match-beginning 0)))))
5525 (defvar org-font-lock-keywords nil)
5527 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5528 "Regular expression matching a property line.")
5530 (defvar org-font-lock-hook nil
5531 "Functions to be called for special font lock stuff.")
5533 (defvar org-font-lock-set-keywords-hook nil
5534 "Functions that can manipulate `org-font-lock-extra-keywords'.
5535 This is calles after `org-font-lock-extra-keywords' is defined, but before
5536 it is installed to be used by font lock. This can be useful if something
5537 needs to be inserted at a specific position in the font-lock sequence.")
5539 (defun org-font-lock-hook (limit)
5540 (run-hook-with-args 'org-font-lock-hook limit))
5542 (defun org-set-font-lock-defaults ()
5543 (let* ((em org-fontify-emphasized-text)
5544 (lk org-activate-links)
5545 (org-font-lock-extra-keywords
5546 (list
5547 ;; Call the hook
5548 '(org-font-lock-hook)
5549 ;; Headlines
5550 `(,(if org-fontify-whole-heading-line
5551 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5552 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5553 (1 (org-get-level-face 1))
5554 (2 (org-get-level-face 2))
5555 (3 (org-get-level-face 3)))
5556 ;; Table lines
5557 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5558 (1 'org-table t))
5559 ;; Table internals
5560 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5561 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5562 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5563 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5564 ;; Drawers
5565 (list org-drawer-regexp '(0 'org-special-keyword t))
5566 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5567 ;; Properties
5568 (list org-property-re
5569 '(1 'org-special-keyword t)
5570 '(3 'org-property-value t))
5571 ;; Links
5572 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5573 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5574 (if (memq 'plain lk) '(org-activate-plain-links))
5575 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5576 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5577 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5578 (if (memq 'footnote lk) '(org-activate-footnote-links
5579 (2 'org-footnote t)))
5580 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5581 '(org-hide-wide-columns (0 nil append))
5582 ;; TODO lines
5583 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5584 '(1 (org-get-todo-face 1) t))
5585 ;; DONE
5586 (if org-fontify-done-headline
5587 (list (concat "^[*]+ +\\<\\("
5588 (mapconcat 'regexp-quote org-done-keywords "\\|")
5589 "\\)\\(.*\\)")
5590 '(2 'org-headline-done t))
5591 nil)
5592 ;; Priorities
5593 '(org-font-lock-add-priority-faces)
5594 ;; Tags
5595 '(org-font-lock-add-tag-faces)
5596 ;; Special keywords
5597 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5598 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5599 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5600 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5601 ;; Emphasis
5602 (if em
5603 (if (featurep 'xemacs)
5604 '(org-do-emphasis-faces (0 nil append))
5605 '(org-do-emphasis-faces)))
5606 ;; Checkboxes
5607 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5608 1 'org-checkbox prepend)
5609 (if (cdr (assq 'checkbox org-list-automatic-rules))
5610 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5611 (0 (org-get-checkbox-statistics-face) t)))
5612 ;; Description list items
5613 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5614 1 'bold prepend)
5615 ;; ARCHIVEd headings
5616 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5617 '(1 'org-archived prepend))
5618 ;; Specials
5619 '(org-do-latex-and-special-faces)
5620 '(org-fontify-entities)
5621 '(org-raise-scripts)
5622 ;; Code
5623 '(org-activate-code (1 'org-code t))
5624 ;; COMMENT
5625 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5626 "\\|" org-quote-string "\\)\\>")
5627 '(1 'org-special-keyword t))
5628 '("^#.*" (0 'font-lock-comment-face t))
5629 ;; Blocks and meta lines
5630 '(org-fontify-meta-lines-and-blocks)
5632 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5633 (run-hooks 'org-font-lock-set-keywords-hook)
5634 ;; Now set the full font-lock-keywords
5635 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5636 (org-set-local 'font-lock-defaults
5637 '(org-font-lock-keywords t nil nil backward-paragraph))
5638 (kill-local-variable 'font-lock-keywords) nil))
5640 (defun org-toggle-pretty-entities ()
5641 "Toggle the composition display of entities as UTF8 characters."
5642 (interactive)
5643 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5644 (org-restart-font-lock)
5645 (if org-pretty-entities
5646 (message "Entities are displayed as UTF8 characers")
5647 (save-restriction
5648 (widen)
5649 (org-decompose-region (point-min) (point-max))
5650 (message "Entities are displayed plain"))))
5652 (defun org-fontify-entities (limit)
5653 "Find an entity to fontify."
5654 (let (ee)
5655 (when org-pretty-entities
5656 (catch 'match
5657 (while (re-search-forward
5658 "\\\\\\([a-zA-Z][a-zA-Z0-9]*\\)\\($\\|[^[:alnum:]\n]\\)"
5659 limit t)
5660 (if (and (not (org-in-indented-comment-line))
5661 (setq ee (org-entity-get (match-string 1)))
5662 (= (length (nth 6 ee)) 1))
5663 (progn
5664 (add-text-properties
5665 (match-beginning 0) (match-end 1)
5666 (list 'font-lock-fontified t))
5667 (compose-region (match-beginning 0) (match-end 1)
5668 (nth 6 ee) nil)
5669 (backward-char 1)
5670 (throw 'match t))))
5671 nil))))
5673 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5674 "Fontify string S like in Org-mode."
5675 (with-temp-buffer
5676 (insert s)
5677 (let ((org-odd-levels-only odd-levels))
5678 (org-mode)
5679 (font-lock-fontify-buffer)
5680 (buffer-string))))
5682 (defvar org-m nil)
5683 (defvar org-l nil)
5684 (defvar org-f nil)
5685 (defun org-get-level-face (n)
5686 "Get the right face for match N in font-lock matching of headlines."
5687 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5688 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5689 (if org-cycle-level-faces
5690 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5691 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5692 (cond
5693 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5694 ((eq n 2) org-f)
5695 (t (if org-level-color-stars-only nil org-f))))
5698 (defun org-get-todo-face (kwd)
5699 "Get the right face for a TODO keyword KWD.
5700 If KWD is a number, get the corresponding match group."
5701 (if (numberp kwd) (setq kwd (match-string kwd)))
5702 (or (org-face-from-face-or-color
5703 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5704 (and (member kwd org-done-keywords) 'org-done)
5705 'org-todo))
5707 (defun org-face-from-face-or-color (context inherit face-or-color)
5708 "Create a face list that inherits INHERIT, but sets the foreground color.
5709 When FACE-OR-COLOR is not a string, just return it."
5710 (if (stringp face-or-color)
5711 (list :inherit inherit
5712 (cdr (assoc context org-faces-easy-properties))
5713 face-or-color)
5714 face-or-color))
5716 (defun org-font-lock-add-tag-faces (limit)
5717 "Add the special tag faces."
5718 (when (and org-tag-faces org-tags-special-faces-re)
5719 (while (re-search-forward org-tags-special-faces-re limit t)
5720 (add-text-properties (match-beginning 1) (match-end 1)
5721 (list 'face (org-get-tag-face 1)
5722 'font-lock-fontified t))
5723 (backward-char 1))))
5725 (defun org-font-lock-add-priority-faces (limit)
5726 "Add the special priority faces."
5727 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5728 (add-text-properties
5729 (match-beginning 0) (match-end 0)
5730 (list 'face (or (org-face-from-face-or-color
5731 'priority 'org-special-keyword
5732 (cdr (assoc (char-after (match-beginning 1))
5733 org-priority-faces)))
5734 'org-special-keyword)
5735 'font-lock-fontified t))))
5737 (defun org-get-tag-face (kwd)
5738 "Get the right face for a TODO keyword KWD.
5739 If KWD is a number, get the corresponding match group."
5740 (if (numberp kwd) (setq kwd (match-string kwd)))
5741 (or (org-face-from-face-or-color
5742 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5743 'org-tag))
5745 (defun org-unfontify-region (beg end &optional maybe_loudly)
5746 "Remove fontification and activation overlays from links."
5747 (font-lock-default-unfontify-region beg end)
5748 (let* ((buffer-undo-list t)
5749 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5750 (inhibit-modification-hooks t)
5751 deactivate-mark buffer-file-name buffer-file-truename)
5752 (org-decompose-region beg end)
5753 (remove-text-properties
5754 beg end
5755 (if org-indent-mode
5756 ;; also remove line-prefix and wrap-prefix properties
5757 '(mouse-face t keymap t org-linked-text t
5758 invisible t intangible t
5759 line-prefix t wrap-prefix t
5760 org-no-flyspell t org-emphasis t)
5761 '(mouse-face t keymap t org-linked-text t
5762 invisible t intangible t
5763 org-no-flyspell t org-emphasis t)))
5764 (org-remove-font-lock-display-properties beg end)))
5766 (defconst org-script-display '(((raise -0.3) (height 0.7))
5767 ((raise 0.3) (height 0.7))
5768 ((raise -0.5))
5769 ((raise 0.5)))
5770 "Display properties for showing superscripts and subscripts.")
5772 (defun org-remove-font-lock-display-properties (beg end)
5773 "Remove specific display properties that have been added by font lock.
5774 The will remove the raise properties that are used to show superscripts
5775 and subscripts."
5776 (let (next prop)
5777 (while (< beg end)
5778 (setq next (next-single-property-change beg 'display nil end)
5779 prop (get-text-property beg 'display))
5780 (if (member prop org-script-display)
5781 (put-text-property beg next 'display nil))
5782 (setq beg next))))
5784 (defun org-raise-scripts (limit)
5785 "Add raise properties to sub/superscripts."
5786 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5787 (if (re-search-forward
5788 (if (eq org-use-sub-superscripts t)
5789 org-match-substring-regexp
5790 org-match-substring-with-braces-regexp)
5791 limit t)
5792 (let* ((pos (point)) table-p comment-p
5793 (mpos (match-beginning 3))
5794 (emph-p (get-text-property mpos 'org-emphasis))
5795 (link-p (get-text-property mpos 'mouse-face))
5796 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5797 (goto-char (point-at-bol))
5798 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5799 comment-p (org-looking-at-p "[ \t]*#"))
5800 (goto-char pos)
5801 ;; FIXME: Should we go back one character here, for a_b^c
5802 ;; (goto-char (1- pos)) ;????????????????????
5803 (if (or comment-p emph-p link-p keyw-p)
5805 (put-text-property (match-beginning 3) (match-end 0)
5806 'display
5807 (if (equal (char-after (match-beginning 2)) ?^)
5808 (nth (if table-p 3 1) org-script-display)
5809 (nth (if table-p 2 0) org-script-display)))
5810 (add-text-properties (match-beginning 2) (match-end 2)
5811 (list 'invisible t
5812 'org-dwidth t 'org-dwidth-n 1))
5813 (if (and (eq (char-after (match-beginning 3)) ?{)
5814 (eq (char-before (match-end 3)) ?}))
5815 (progn
5816 (add-text-properties
5817 (match-beginning 3) (1+ (match-beginning 3))
5818 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
5819 (add-text-properties
5820 (1- (match-end 3)) (match-end 3)
5821 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
5822 t)))))
5824 ;;;; Visibility cycling, including org-goto and indirect buffer
5826 ;;; Cycling
5828 (defvar org-cycle-global-status nil)
5829 (make-variable-buffer-local 'org-cycle-global-status)
5830 (defvar org-cycle-subtree-status nil)
5831 (make-variable-buffer-local 'org-cycle-subtree-status)
5833 ;;;###autoload
5835 (defvar org-inlinetask-min-level)
5837 (defun org-cycle (&optional arg)
5838 "TAB-action and visibility cycling for Org-mode.
5840 This is the command invoked in Org-mode by the TAB key. Its main purpose
5841 is outline visibility cycling, but it also invokes other actions
5842 in special contexts.
5844 - When this function is called with a prefix argument, rotate the entire
5845 buffer through 3 states (global cycling)
5846 1. OVERVIEW: Show only top-level headlines.
5847 2. CONTENTS: Show all headlines of all levels, but no body text.
5848 3. SHOW ALL: Show everything.
5849 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5850 determined by the variable `org-startup-folded', and by any VISIBILITY
5851 properties in the buffer.
5852 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5853 including any drawers.
5855 - When inside a table, re-align the table and move to the next field.
5857 - When point is at the beginning of a headline, rotate the subtree started
5858 by this line through 3 different states (local cycling)
5859 1. FOLDED: Only the main headline is shown.
5860 2. CHILDREN: The main headline and the direct children are shown.
5861 From this state, you can move to one of the children
5862 and zoom in further.
5863 3. SUBTREE: Show the entire subtree, including body text.
5864 If there is no subtree, switch directly from CHILDREN to FOLDED.
5866 - When point is at the beginning of an empty headline and the variable
5867 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5868 of the headline by demoting and promoting it to likely levels. This
5869 speeds up creation document structure by pressing TAB once or several
5870 times right after creating a new headline.
5872 - When there is a numeric prefix, go up to a heading with level ARG, do
5873 a `show-subtree' and return to the previous cursor position. If ARG
5874 is negative, go up that many levels.
5876 - When point is not at the beginning of a headline, execute the global
5877 binding for TAB, which is re-indenting the line. See the option
5878 `org-cycle-emulate-tab' for details.
5880 - Special case: if point is at the beginning of the buffer and there is
5881 no headline in line 1, this function will act as if called with prefix arg
5882 (C-u TAB, same as S-TAB) also when called without prefix arg.
5883 But only if also the variable `org-cycle-global-at-bob' is t."
5884 (interactive "P")
5885 (org-load-modules-maybe)
5886 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5887 (and org-cycle-level-after-item/entry-creation
5888 (or (org-cycle-level)
5889 (org-cycle-item-indentation))))
5890 (let* ((limit-level
5891 (or org-cycle-max-level
5892 (and (boundp 'org-inlinetask-min-level)
5893 org-inlinetask-min-level
5894 (1- org-inlinetask-min-level))))
5895 (nstars (and limit-level
5896 (if org-odd-levels-only
5897 (and limit-level (1- (* limit-level 2)))
5898 limit-level)))
5899 (outline-regexp
5900 (if (not (org-mode-p))
5901 outline-regexp
5902 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
5903 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
5904 (not (looking-at outline-regexp))))
5905 (org-cycle-hook
5906 (if bob-special
5907 (delq 'org-optimize-window-after-visibility-change
5908 (copy-sequence org-cycle-hook))
5909 org-cycle-hook))
5910 (pos (point)))
5912 (if (or bob-special (equal arg '(4)))
5913 ;; special case: use global cycling
5914 (setq arg t))
5916 (cond
5918 ((equal arg '(16))
5919 (setq last-command 'dummy)
5920 (org-set-startup-visibility)
5921 (message "Startup visibility, plus VISIBILITY properties"))
5923 ((equal arg '(64))
5924 (show-all)
5925 (message "Entire buffer visible, including drawers"))
5927 ;; Table: enter it or move to the next field.
5928 ((org-at-table-p 'any)
5929 (if (org-at-table.el-p)
5930 (message "Use C-c ' to edit table.el tables")
5931 (if arg (org-table-edit-field t)
5932 (org-table-justify-field-maybe)
5933 (call-interactively 'org-table-next-field))))
5935 ((run-hook-with-args-until-success
5936 'org-tab-after-check-for-table-hook))
5938 ;; Global cycling: delegate to `org-cycle-internal-global'.
5939 ((eq arg t) (org-cycle-internal-global))
5941 ;; Drawers: delegate to `org-flag-drawer'.
5942 ((and org-drawers org-drawer-regexp
5943 (save-excursion
5944 (beginning-of-line 1)
5945 (looking-at org-drawer-regexp)))
5946 (org-flag-drawer ; toggle block visibility
5947 (not (get-char-property (match-end 0) 'invisible))))
5949 ;; Show-subtree, ARG levels up from here.
5950 ((integerp arg)
5951 (save-excursion
5952 (org-back-to-heading)
5953 (outline-up-heading (if (< arg 0) (- arg)
5954 (- (funcall outline-level) arg)))
5955 (org-show-subtree)))
5957 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
5958 ((and (featurep 'org-inlinetask)
5959 (org-inlinetask-at-task-p)
5960 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5961 (org-inlinetask-toggle-visibility))
5963 ;; At an item/headline: delegate to `org-cycle-internal-local'.
5964 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
5965 (save-excursion (beginning-of-line 1)
5966 (looking-at outline-regexp)))
5967 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5968 (org-cycle-internal-local))
5970 ;; From there: TAB emulation and template completion.
5971 (buffer-read-only (org-back-to-heading))
5973 ((run-hook-with-args-until-success
5974 'org-tab-after-check-for-cycling-hook))
5976 ((org-try-structure-completion))
5978 ((org-try-cdlatex-tab))
5980 ((run-hook-with-args-until-success
5981 'org-tab-before-tab-emulation-hook))
5983 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5984 (or (not (bolp))
5985 (not (looking-at outline-regexp))))
5986 (call-interactively (global-key-binding "\t")))
5988 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5989 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5990 (or (and (eq org-cycle-emulate-tab 'white)
5991 (= (match-end 0) (point-at-eol)))
5992 (and (eq org-cycle-emulate-tab 'whitestart)
5993 (>= (match-end 0) pos))))
5995 (eq org-cycle-emulate-tab t))
5996 (call-interactively (global-key-binding "\t")))
5998 (t (save-excursion
5999 (org-back-to-heading)
6000 (org-cycle)))))))
6002 (defun org-cycle-internal-global ()
6003 "Do the global cycling action."
6004 (cond
6005 ((and (eq last-command this-command)
6006 (eq org-cycle-global-status 'overview))
6007 ;; We just created the overview - now do table of contents
6008 ;; This can be slow in very large buffers, so indicate action
6009 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6010 (message "CONTENTS...")
6011 (org-content)
6012 (message "CONTENTS...done")
6013 (setq org-cycle-global-status 'contents)
6014 (run-hook-with-args 'org-cycle-hook 'contents))
6016 ((and (eq last-command this-command)
6017 (eq org-cycle-global-status 'contents))
6018 ;; We just showed the table of contents - now show everything
6019 (run-hook-with-args 'org-pre-cycle-hook 'all)
6020 (show-all)
6021 (message "SHOW ALL")
6022 (setq org-cycle-global-status 'all)
6023 (run-hook-with-args 'org-cycle-hook 'all))
6026 ;; Default action: go to overview
6027 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6028 (org-overview)
6029 (message "OVERVIEW")
6030 (setq org-cycle-global-status 'overview)
6031 (run-hook-with-args 'org-cycle-hook 'overview))))
6033 (defun org-cycle-internal-local ()
6034 "Do the local cycling action."
6035 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6036 ;; First, determine end of headline (EOH), end of subtree or item
6037 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6038 (save-excursion
6039 (if (org-at-item-p)
6040 (progn
6041 (beginning-of-line)
6042 (setq struct (org-list-struct))
6043 (setq eoh (point-at-eol))
6044 (setq eos (org-list-get-item-end-before-blank (point) struct))
6045 (setq has-children (org-list-has-child-p (point) struct)))
6046 (org-back-to-heading)
6047 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6048 (setq eos (save-excursion
6049 (org-end-of-subtree t)
6050 (unless (eobp)
6051 (skip-chars-forward " \t\n"))
6052 (if (eobp) (point) (1- (point)))))
6053 (setq has-children
6054 (or (save-excursion
6055 (let ((level (funcall outline-level)))
6056 (outline-next-heading)
6057 (and (org-at-heading-p t)
6058 (> (funcall outline-level) level))))
6059 (save-excursion
6060 (org-list-search-forward (org-item-beginning-re) eos t)))))
6061 ;; Determine end invisible part of buffer (EOL)
6062 (beginning-of-line 2)
6063 ;; XEmacs doesn't have `next-single-char-property-change'
6064 (if (featurep 'xemacs)
6065 (while (and (not (eobp)) ;; this is like `next-line'
6066 (get-char-property (1- (point)) 'invisible))
6067 (beginning-of-line 2))
6068 (while (and (not (eobp)) ;; this is like `next-line'
6069 (get-char-property (1- (point)) 'invisible))
6070 (goto-char (next-single-char-property-change (point) 'invisible))
6071 (and (eolp) (beginning-of-line 2))))
6072 (setq eol (point)))
6073 ;; Find out what to do next and set `this-command'
6074 (cond
6075 ((= eos eoh)
6076 ;; Nothing is hidden behind this heading
6077 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6078 (message "EMPTY ENTRY")
6079 (setq org-cycle-subtree-status nil)
6080 (save-excursion
6081 (goto-char eos)
6082 (outline-next-heading)
6083 (if (outline-invisible-p) (org-flag-heading nil))))
6084 ((and (or (>= eol eos)
6085 (not (string-match "\\S-" (buffer-substring eol eos))))
6086 (or has-children
6087 (not (setq children-skipped
6088 org-cycle-skip-children-state-if-no-children))))
6089 ;; Entire subtree is hidden in one line: children view
6090 (run-hook-with-args 'org-pre-cycle-hook 'children)
6091 (if (org-at-item-p)
6092 (org-list-set-item-visibility (point-at-bol) struct 'children)
6093 (org-show-entry)
6094 (show-children)
6095 ;; Fold every list in subtree to top-level items.
6096 (when (eq org-cycle-include-plain-lists 'integrate)
6097 (save-excursion
6098 (org-back-to-heading)
6099 (while (org-list-search-forward (org-item-beginning-re) eos t)
6100 (beginning-of-line 1)
6101 (let* ((struct (org-list-struct))
6102 (prevs (org-list-prevs-alist struct))
6103 (end (org-list-get-bottom-point struct)))
6104 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6105 (org-list-get-all-items (point) struct prevs))
6106 (goto-char end))))))
6107 (message "CHILDREN")
6108 (save-excursion
6109 (goto-char eos)
6110 (outline-next-heading)
6111 (if (outline-invisible-p) (org-flag-heading nil)))
6112 (setq org-cycle-subtree-status 'children)
6113 (run-hook-with-args 'org-cycle-hook 'children))
6114 ((or children-skipped
6115 (and (eq last-command this-command)
6116 (eq org-cycle-subtree-status 'children)))
6117 ;; We just showed the children, or no children are there,
6118 ;; now show everything.
6119 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6120 (outline-flag-region eoh eos nil)
6121 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6122 (setq org-cycle-subtree-status 'subtree)
6123 (run-hook-with-args 'org-cycle-hook 'subtree))
6125 ;; Default action: hide the subtree.
6126 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6127 (outline-flag-region eoh eos t)
6128 (message "FOLDED")
6129 (setq org-cycle-subtree-status 'folded)
6130 (run-hook-with-args 'org-cycle-hook 'folded)))))
6132 ;;;###autoload
6133 (defun org-global-cycle (&optional arg)
6134 "Cycle the global visibility. For details see `org-cycle'.
6135 With \\[universal-argument] prefix arg, switch to startup visibility.
6136 With a numeric prefix, show all headlines up to that level."
6137 (interactive "P")
6138 (let ((org-cycle-include-plain-lists
6139 (if (org-mode-p) org-cycle-include-plain-lists nil)))
6140 (cond
6141 ((integerp arg)
6142 (show-all)
6143 (hide-sublevels arg)
6144 (setq org-cycle-global-status 'contents))
6145 ((equal arg '(4))
6146 (org-set-startup-visibility)
6147 (message "Startup visibility, plus VISIBILITY properties."))
6149 (org-cycle '(4))))))
6151 (defun org-set-startup-visibility ()
6152 "Set the visibility required by startup options and properties."
6153 (cond
6154 ((eq org-startup-folded t)
6155 (org-cycle '(4)))
6156 ((eq org-startup-folded 'content)
6157 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6158 (org-cycle '(4)) (org-cycle '(4)))))
6159 (unless (eq org-startup-folded 'showeverything)
6160 (if org-hide-block-startup (org-hide-block-all))
6161 (org-set-visibility-according-to-property 'no-cleanup)
6162 (org-cycle-hide-archived-subtrees 'all)
6163 (org-cycle-hide-drawers 'all)
6164 (org-cycle-show-empty-lines t)))
6166 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6167 "Switch subtree visibilities according to :VISIBILITY: property."
6168 (interactive)
6169 (let (org-show-entry-below state)
6170 (save-excursion
6171 (goto-char (point-min))
6172 (while (re-search-forward
6173 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6174 nil t)
6175 (setq state (match-string 1))
6176 (save-excursion
6177 (org-back-to-heading t)
6178 (hide-subtree)
6179 (org-reveal)
6180 (cond
6181 ((equal state '("fold" "folded"))
6182 (hide-subtree))
6183 ((equal state "children")
6184 (org-show-hidden-entry)
6185 (show-children))
6186 ((equal state "content")
6187 (save-excursion
6188 (save-restriction
6189 (org-narrow-to-subtree)
6190 (org-content))))
6191 ((member state '("all" "showall"))
6192 (show-subtree)))))
6193 (unless no-cleanup
6194 (org-cycle-hide-archived-subtrees 'all)
6195 (org-cycle-hide-drawers 'all)
6196 (org-cycle-show-empty-lines 'all)))))
6198 (defun org-overview ()
6199 "Switch to overview mode, showing only top-level headlines.
6200 Really, this shows all headlines with level equal or greater than the level
6201 of the first headline in the buffer. This is important, because if the
6202 first headline is not level one, then (hide-sublevels 1) gives confusing
6203 results."
6204 (interactive)
6205 (let ((level (save-excursion
6206 (goto-char (point-min))
6207 (if (re-search-forward (concat "^" outline-regexp) nil t)
6208 (progn
6209 (goto-char (match-beginning 0))
6210 (funcall outline-level))))))
6211 (and level (hide-sublevels level))))
6213 (defun org-content (&optional arg)
6214 "Show all headlines in the buffer, like a table of contents.
6215 With numerical argument N, show content up to level N."
6216 (interactive "P")
6217 (save-excursion
6218 ;; Visit all headings and show their offspring
6219 (and (integerp arg) (org-overview))
6220 (goto-char (point-max))
6221 (catch 'exit
6222 (while (and (progn (condition-case nil
6223 (outline-previous-visible-heading 1)
6224 (error (goto-char (point-min))))
6226 (looking-at outline-regexp))
6227 (if (integerp arg)
6228 (show-children (1- arg))
6229 (show-branches))
6230 (if (bobp) (throw 'exit nil))))))
6233 (defun org-optimize-window-after-visibility-change (state)
6234 "Adjust the window after a change in outline visibility.
6235 This function is the default value of the hook `org-cycle-hook'."
6236 (when (get-buffer-window (current-buffer))
6237 (cond
6238 ((eq state 'content) nil)
6239 ((eq state 'all) nil)
6240 ((eq state 'folded) nil)
6241 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6242 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6244 (defun org-remove-empty-overlays-at (pos)
6245 "Remove outline overlays that do not contain non-white stuff."
6246 (mapc
6247 (lambda (o)
6248 (and (eq 'outline (overlay-get o 'invisible))
6249 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6250 (overlay-end o))))
6251 (delete-overlay o)))
6252 (overlays-at pos)))
6254 (defun org-clean-visibility-after-subtree-move ()
6255 "Fix visibility issues after moving a subtree."
6256 ;; First, find a reasonable region to look at:
6257 ;; Start two siblings above, end three below
6258 (let* ((beg (save-excursion
6259 (and (org-get-last-sibling)
6260 (org-get-last-sibling))
6261 (point)))
6262 (end (save-excursion
6263 (and (org-get-next-sibling)
6264 (org-get-next-sibling)
6265 (org-get-next-sibling))
6266 (if (org-at-heading-p)
6267 (point-at-eol)
6268 (point))))
6269 (level (looking-at "\\*+"))
6270 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6271 (save-excursion
6272 (save-restriction
6273 (narrow-to-region beg end)
6274 (when re
6275 ;; Properly fold already folded siblings
6276 (goto-char (point-min))
6277 (while (re-search-forward re nil t)
6278 (if (and (not (outline-invisible-p))
6279 (save-excursion
6280 (goto-char (point-at-eol)) (outline-invisible-p)))
6281 (hide-entry))))
6282 (org-cycle-show-empty-lines 'overview)
6283 (org-cycle-hide-drawers 'overview)))))
6285 (defun org-cycle-show-empty-lines (state)
6286 "Show empty lines above all visible headlines.
6287 The region to be covered depends on STATE when called through
6288 `org-cycle-hook'. Lisp program can use t for STATE to get the
6289 entire buffer covered. Note that an empty line is only shown if there
6290 are at least `org-cycle-separator-lines' empty lines before the headline."
6291 (when (not (= org-cycle-separator-lines 0))
6292 (save-excursion
6293 (let* ((n (abs org-cycle-separator-lines))
6294 (re (cond
6295 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6296 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6297 (t (let ((ns (number-to-string (- n 2))))
6298 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6299 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6300 beg end b e)
6301 (cond
6302 ((memq state '(overview contents t))
6303 (setq beg (point-min) end (point-max)))
6304 ((memq state '(children folded))
6305 (setq beg (point) end (progn (org-end-of-subtree t t)
6306 (beginning-of-line 2)
6307 (point)))))
6308 (when beg
6309 (goto-char beg)
6310 (while (re-search-forward re end t)
6311 (unless (get-char-property (match-end 1) 'invisible)
6312 (setq e (match-end 1))
6313 (if (< org-cycle-separator-lines 0)
6314 (setq b (save-excursion
6315 (goto-char (match-beginning 0))
6316 (org-back-over-empty-lines)
6317 (if (save-excursion
6318 (goto-char (max (point-min) (1- (point))))
6319 (org-on-heading-p))
6320 (1- (point))
6321 (point))))
6322 (setq b (match-beginning 1)))
6323 (outline-flag-region b e nil)))))))
6324 ;; Never hide empty lines at the end of the file.
6325 (save-excursion
6326 (goto-char (point-max))
6327 (outline-previous-heading)
6328 (outline-end-of-heading)
6329 (if (and (looking-at "[ \t\n]+")
6330 (= (match-end 0) (point-max)))
6331 (outline-flag-region (point) (match-end 0) nil))))
6333 (defun org-show-empty-lines-in-parent ()
6334 "Move to the parent and re-show empty lines before visible headlines."
6335 (save-excursion
6336 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6337 (org-cycle-show-empty-lines context))))
6339 (defun org-files-list ()
6340 "Return `org-agenda-files' list, plus all open org-mode files.
6341 This is useful for operations that need to scan all of a user's
6342 open and agenda-wise Org files."
6343 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6344 (dolist (buf (buffer-list))
6345 (with-current-buffer buf
6346 (if (and (org-mode-p) (buffer-file-name))
6347 (let ((file (expand-file-name (buffer-file-name))))
6348 (unless (member file files)
6349 (push file files))))))
6350 files))
6352 (defsubst org-entry-beginning-position ()
6353 "Return the beginning position of the current entry."
6354 (save-excursion (outline-back-to-heading t) (point)))
6356 (defsubst org-entry-end-position ()
6357 "Return the end position of the current entry."
6358 (save-excursion (outline-next-heading) (point)))
6360 (defun org-cycle-hide-drawers (state)
6361 "Re-hide all drawers after a visibility state change."
6362 (when (and (org-mode-p)
6363 (not (memq state '(overview folded contents))))
6364 (save-excursion
6365 (let* ((globalp (memq state '(contents all)))
6366 (beg (if globalp (point-min) (point)))
6367 (end (if globalp (point-max)
6368 (if (eq state 'children)
6369 (save-excursion (outline-next-heading) (point))
6370 (org-end-of-subtree t)))))
6371 (goto-char beg)
6372 (while (re-search-forward org-drawer-regexp end t)
6373 (org-flag-drawer t))))))
6375 (defun org-flag-drawer (flag)
6376 (save-excursion
6377 (beginning-of-line 1)
6378 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6379 (let ((b (match-end 0))
6380 (outline-regexp org-outline-regexp))
6381 (if (re-search-forward
6382 "^[ \t]*:END:"
6383 (save-excursion (outline-next-heading) (point)) t)
6384 (outline-flag-region b (point-at-eol) flag)
6385 (error ":END: line missing at position %s" b))))))
6387 (defun org-subtree-end-visible-p ()
6388 "Is the end of the current subtree visible?"
6389 (pos-visible-in-window-p
6390 (save-excursion (org-end-of-subtree t) (point))))
6392 (defun org-first-headline-recenter (&optional N)
6393 "Move cursor to the first headline and recenter the headline.
6394 Optional argument N means put the headline into the Nth line of the window."
6395 (goto-char (point-min))
6396 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6397 (beginning-of-line)
6398 (recenter (prefix-numeric-value N))))
6400 ;;; Saving and restoring visibility
6402 (defun org-outline-overlay-data (&optional use-markers)
6403 "Return a list of the locations of all outline overlays.
6404 These are overlays with the `invisible' property value `outline'.
6405 The return value is a list of cons cells, with start and stop
6406 positions for each overlay.
6407 If USE-MARKERS is set, return the positions as markers."
6408 (let (beg end)
6409 (save-excursion
6410 (save-restriction
6411 (widen)
6412 (delq nil
6413 (mapcar (lambda (o)
6414 (when (eq (overlay-get o 'invisible) 'outline)
6415 (setq beg (overlay-start o)
6416 end (overlay-end o))
6417 (and beg end (> end beg)
6418 (if use-markers
6419 (cons (move-marker (make-marker) beg)
6420 (move-marker (make-marker) end))
6421 (cons beg end)))))
6422 (overlays-in (point-min) (point-max))))))))
6424 (defun org-set-outline-overlay-data (data)
6425 "Create visibility overlays for all positions in DATA.
6426 DATA should have been made by `org-outline-overlay-data'."
6427 (let (o)
6428 (save-excursion
6429 (save-restriction
6430 (widen)
6431 (show-all)
6432 (mapc (lambda (c)
6433 (setq o (make-overlay (car c) (cdr c)))
6434 (overlay-put o 'invisible 'outline))
6435 data)))))
6437 ;;; Folding of blocks
6439 (defconst org-block-regexp
6440 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
6441 "Regular expression for hiding blocks.")
6443 (defvar org-hide-block-overlays nil
6444 "Overlays hiding blocks.")
6445 (make-variable-buffer-local 'org-hide-block-overlays)
6447 (defun org-block-map (function &optional start end)
6448 "Call FUNCTION at the head of all source blocks in the current buffer.
6449 Optional arguments START and END can be used to limit the range."
6450 (let ((start (or start (point-min)))
6451 (end (or end (point-max))))
6452 (save-excursion
6453 (goto-char start)
6454 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6455 (save-excursion
6456 (save-match-data
6457 (goto-char (match-beginning 0))
6458 (funcall function)))))))
6460 (defun org-hide-block-toggle-all ()
6461 "Toggle the visibility of all blocks in the current buffer."
6462 (org-block-map #'org-hide-block-toggle))
6464 (defun org-hide-block-all ()
6465 "Fold all blocks in the current buffer."
6466 (interactive)
6467 (org-show-block-all)
6468 (org-block-map #'org-hide-block-toggle-maybe))
6470 (defun org-show-block-all ()
6471 "Unfold all blocks in the current buffer."
6472 (interactive)
6473 (mapc 'delete-overlay org-hide-block-overlays)
6474 (setq org-hide-block-overlays nil))
6476 (defun org-hide-block-toggle-maybe ()
6477 "Toggle visibility of block at point."
6478 (interactive)
6479 (let ((case-fold-search t))
6480 (if (save-excursion
6481 (beginning-of-line 1)
6482 (looking-at org-block-regexp))
6483 (progn (org-hide-block-toggle)
6484 t) ;; to signal that we took action
6485 nil))) ;; to signal that we did not
6487 (defun org-hide-block-toggle (&optional force)
6488 "Toggle the visibility of the current block."
6489 (interactive)
6490 (save-excursion
6491 (beginning-of-line)
6492 (if (re-search-forward org-block-regexp nil t)
6493 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6494 (end (match-end 0)) ;; end of entire body
6496 (if (memq t (mapcar (lambda (overlay)
6497 (eq (overlay-get overlay 'invisible)
6498 'org-hide-block))
6499 (overlays-at start)))
6500 (if (or (not force) (eq force 'off))
6501 (mapc (lambda (ov)
6502 (when (member ov org-hide-block-overlays)
6503 (setq org-hide-block-overlays
6504 (delq ov org-hide-block-overlays)))
6505 (when (eq (overlay-get ov 'invisible)
6506 'org-hide-block)
6507 (delete-overlay ov)))
6508 (overlays-at start)))
6509 (setq ov (make-overlay start end))
6510 (overlay-put ov 'invisible 'org-hide-block)
6511 ;; make the block accessible to isearch
6512 (overlay-put
6513 ov 'isearch-open-invisible
6514 (lambda (ov)
6515 (when (member ov org-hide-block-overlays)
6516 (setq org-hide-block-overlays
6517 (delq ov org-hide-block-overlays)))
6518 (when (eq (overlay-get ov 'invisible)
6519 'org-hide-block)
6520 (delete-overlay ov))))
6521 (push ov org-hide-block-overlays)))
6522 (error "Not looking at a source block"))))
6524 ;; org-tab-after-check-for-cycling-hook
6525 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6526 ;; Remove overlays when changing major mode
6527 (add-hook 'org-mode-hook
6528 (lambda () (org-add-hook 'change-major-mode-hook
6529 'org-show-block-all 'append 'local)))
6531 ;;; Org-goto
6533 (defvar org-goto-window-configuration nil)
6534 (defvar org-goto-marker nil)
6535 (defvar org-goto-map
6536 (let ((map (make-sparse-keymap)))
6537 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6538 (while (setq cmd (pop cmds))
6539 (substitute-key-definition cmd cmd map global-map)))
6540 (suppress-keymap map)
6541 (org-defkey map "\C-m" 'org-goto-ret)
6542 (org-defkey map [(return)] 'org-goto-ret)
6543 (org-defkey map [(left)] 'org-goto-left)
6544 (org-defkey map [(right)] 'org-goto-right)
6545 (org-defkey map [(control ?g)] 'org-goto-quit)
6546 (org-defkey map "\C-i" 'org-cycle)
6547 (org-defkey map [(tab)] 'org-cycle)
6548 (org-defkey map [(down)] 'outline-next-visible-heading)
6549 (org-defkey map [(up)] 'outline-previous-visible-heading)
6550 (if org-goto-auto-isearch
6551 (if (fboundp 'define-key-after)
6552 (define-key-after map [t] 'org-goto-local-auto-isearch)
6553 nil)
6554 (org-defkey map "q" 'org-goto-quit)
6555 (org-defkey map "n" 'outline-next-visible-heading)
6556 (org-defkey map "p" 'outline-previous-visible-heading)
6557 (org-defkey map "f" 'outline-forward-same-level)
6558 (org-defkey map "b" 'outline-backward-same-level)
6559 (org-defkey map "u" 'outline-up-heading))
6560 (org-defkey map "/" 'org-occur)
6561 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6562 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6563 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6564 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6565 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6566 map))
6568 (defconst org-goto-help
6569 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6570 RET=jump to location [Q]uit and return to previous location
6571 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6573 (defvar org-goto-start-pos) ; dynamically scoped parameter
6575 ;; FIXME: Docstring does not mention both interfaces
6576 (defun org-goto (&optional alternative-interface)
6577 "Look up a different location in the current file, keeping current visibility.
6579 When you want look-up or go to a different location in a document, the
6580 fastest way is often to fold the entire buffer and then dive into the tree.
6581 This method has the disadvantage, that the previous location will be folded,
6582 which may not be what you want.
6584 This command works around this by showing a copy of the current buffer
6585 in an indirect buffer, in overview mode. You can dive into the tree in
6586 that copy, use org-occur and incremental search to find a location.
6587 When pressing RET or `Q', the command returns to the original buffer in
6588 which the visibility is still unchanged. After RET is will also jump to
6589 the location selected in the indirect buffer and expose the
6590 the headline hierarchy above."
6591 (interactive "P")
6592 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6593 (org-refile-use-outline-path t)
6594 (org-refile-target-verify-function nil)
6595 (interface
6596 (if (not alternative-interface)
6597 org-goto-interface
6598 (if (eq org-goto-interface 'outline)
6599 'outline-path-completion
6600 'outline)))
6601 (org-goto-start-pos (point))
6602 (selected-point
6603 (if (eq interface 'outline)
6604 (car (org-get-location (current-buffer) org-goto-help))
6605 (let ((pa (org-refile-get-location "Goto")))
6606 (org-refile-check-position pa)
6607 (nth 3 pa)))))
6608 (if selected-point
6609 (progn
6610 (org-mark-ring-push org-goto-start-pos)
6611 (goto-char selected-point)
6612 (if (or (outline-invisible-p) (org-invisible-p2))
6613 (org-show-context 'org-goto)))
6614 (message "Quit"))))
6616 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6617 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6618 (defvar org-goto-local-auto-isearch-map) ; defined below
6620 (defun org-get-location (buf help)
6621 "Let the user select a location in the Org-mode buffer BUF.
6622 This function uses a recursive edit. It returns the selected position
6623 or nil."
6624 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6625 (isearch-hide-immediately nil)
6626 (isearch-search-fun-function
6627 (lambda () 'org-goto-local-search-headings))
6628 (org-goto-selected-point org-goto-exit-command)
6629 (pop-up-frames nil)
6630 (special-display-buffer-names nil)
6631 (special-display-regexps nil)
6632 (special-display-function nil))
6633 (save-excursion
6634 (save-window-excursion
6635 (delete-other-windows)
6636 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6637 (switch-to-buffer
6638 (condition-case nil
6639 (make-indirect-buffer (current-buffer) "*org-goto*")
6640 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6641 (with-output-to-temp-buffer "*Help*"
6642 (princ help))
6643 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6644 (setq buffer-read-only nil)
6645 (let ((org-startup-truncated t)
6646 (org-startup-folded nil)
6647 (org-startup-align-all-tables nil))
6648 (org-mode)
6649 (org-overview))
6650 (setq buffer-read-only t)
6651 (if (and (boundp 'org-goto-start-pos)
6652 (integer-or-marker-p org-goto-start-pos))
6653 (let ((org-show-hierarchy-above t)
6654 (org-show-siblings t)
6655 (org-show-following-heading t))
6656 (goto-char org-goto-start-pos)
6657 (and (outline-invisible-p) (org-show-context)))
6658 (goto-char (point-min)))
6659 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6660 (message "Select location and press RET")
6661 (use-local-map org-goto-map)
6662 (recursive-edit)
6664 (kill-buffer "*org-goto*")
6665 (cons org-goto-selected-point org-goto-exit-command)))
6667 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6668 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6669 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6670 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6672 (defun org-goto-local-search-headings (string bound noerror)
6673 "Search and make sure that any matches are in headlines."
6674 (catch 'return
6675 (while (if isearch-forward
6676 (search-forward string bound noerror)
6677 (search-backward string bound noerror))
6678 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6679 (and (member :headline context)
6680 (not (member :tags context))))
6681 (throw 'return (point))))))
6683 (defun org-goto-local-auto-isearch ()
6684 "Start isearch."
6685 (interactive)
6686 (goto-char (point-min))
6687 (let ((keys (this-command-keys)))
6688 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6689 (isearch-mode t)
6690 (isearch-process-search-char (string-to-char keys)))))
6692 (defun org-goto-ret (&optional arg)
6693 "Finish `org-goto' by going to the new location."
6694 (interactive "P")
6695 (setq org-goto-selected-point (point)
6696 org-goto-exit-command 'return)
6697 (throw 'exit nil))
6699 (defun org-goto-left ()
6700 "Finish `org-goto' by going to the new location."
6701 (interactive)
6702 (if (org-on-heading-p)
6703 (progn
6704 (beginning-of-line 1)
6705 (setq org-goto-selected-point (point)
6706 org-goto-exit-command 'left)
6707 (throw 'exit nil))
6708 (error "Not on a heading")))
6710 (defun org-goto-right ()
6711 "Finish `org-goto' by going to the new location."
6712 (interactive)
6713 (if (org-on-heading-p)
6714 (progn
6715 (setq org-goto-selected-point (point)
6716 org-goto-exit-command 'right)
6717 (throw 'exit nil))
6718 (error "Not on a heading")))
6720 (defun org-goto-quit ()
6721 "Finish `org-goto' without cursor motion."
6722 (interactive)
6723 (setq org-goto-selected-point nil)
6724 (setq org-goto-exit-command 'quit)
6725 (throw 'exit nil))
6727 ;;; Indirect buffer display of subtrees
6729 (defvar org-indirect-dedicated-frame nil
6730 "This is the frame being used for indirect tree display.")
6731 (defvar org-last-indirect-buffer nil)
6733 (defun org-tree-to-indirect-buffer (&optional arg)
6734 "Create indirect buffer and narrow it to current subtree.
6735 With numerical prefix ARG, go up to this level and then take that tree.
6736 If ARG is negative, go up that many levels.
6737 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6738 indirect buffer previously made with this command, to avoid proliferation of
6739 indirect buffers. However, when you call the command with a \
6740 \\[universal-argument] prefix, or
6741 when `org-indirect-buffer-display' is `new-frame', the last buffer
6742 is kept so that you can work with several indirect buffers at the same time.
6743 If `org-indirect-buffer-display' is `dedicated-frame', the \
6744 \\[universal-argument] prefix also
6745 requests that a new frame be made for the new buffer, so that the dedicated
6746 frame is not changed."
6747 (interactive "P")
6748 (let ((cbuf (current-buffer))
6749 (cwin (selected-window))
6750 (pos (point))
6751 beg end level heading ibuf)
6752 (save-excursion
6753 (org-back-to-heading t)
6754 (when (numberp arg)
6755 (setq level (org-outline-level))
6756 (if (< arg 0) (setq arg (+ level arg)))
6757 (while (> (setq level (org-outline-level)) arg)
6758 (outline-up-heading 1 t)))
6759 (setq beg (point)
6760 heading (org-get-heading))
6761 (org-end-of-subtree t t)
6762 (if (org-on-heading-p) (backward-char 1))
6763 (setq end (point)))
6764 (if (and (buffer-live-p org-last-indirect-buffer)
6765 (not (eq org-indirect-buffer-display 'new-frame))
6766 (not arg))
6767 (kill-buffer org-last-indirect-buffer))
6768 (setq ibuf (org-get-indirect-buffer cbuf)
6769 org-last-indirect-buffer ibuf)
6770 (cond
6771 ((or (eq org-indirect-buffer-display 'new-frame)
6772 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6773 (select-frame (make-frame))
6774 (delete-other-windows)
6775 (switch-to-buffer ibuf)
6776 (org-set-frame-title heading))
6777 ((eq org-indirect-buffer-display 'dedicated-frame)
6778 (raise-frame
6779 (select-frame (or (and org-indirect-dedicated-frame
6780 (frame-live-p org-indirect-dedicated-frame)
6781 org-indirect-dedicated-frame)
6782 (setq org-indirect-dedicated-frame (make-frame)))))
6783 (delete-other-windows)
6784 (switch-to-buffer ibuf)
6785 (org-set-frame-title (concat "Indirect: " heading)))
6786 ((eq org-indirect-buffer-display 'current-window)
6787 (switch-to-buffer ibuf))
6788 ((eq org-indirect-buffer-display 'other-window)
6789 (pop-to-buffer ibuf))
6790 (t (error "Invalid value")))
6791 (if (featurep 'xemacs)
6792 (save-excursion (org-mode) (turn-on-font-lock)))
6793 (narrow-to-region beg end)
6794 (show-all)
6795 (goto-char pos)
6796 (and (window-live-p cwin) (select-window cwin))))
6798 (defun org-get-indirect-buffer (&optional buffer)
6799 (setq buffer (or buffer (current-buffer)))
6800 (let ((n 1) (base (buffer-name buffer)) bname)
6801 (while (buffer-live-p
6802 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6803 (setq n (1+ n)))
6804 (condition-case nil
6805 (make-indirect-buffer buffer bname 'clone)
6806 (error (make-indirect-buffer buffer bname)))))
6808 (defun org-set-frame-title (title)
6809 "Set the title of the current frame to the string TITLE."
6810 ;; FIXME: how to name a single frame in XEmacs???
6811 (unless (featurep 'xemacs)
6812 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6814 ;;;; Structure editing
6816 ;;; Inserting headlines
6818 (defun org-previous-line-empty-p ()
6819 (save-excursion
6820 (and (not (bobp))
6821 (or (beginning-of-line 0) t)
6822 (save-match-data
6823 (looking-at "[ \t]*$")))))
6825 (defun org-insert-heading (&optional force-heading invisible-ok)
6826 "Insert a new heading or item with same depth at point.
6827 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6828 If point is at the beginning of a headline, insert a sibling before the
6829 current headline. If point is not at the beginning, split the line,
6830 create the new headline with the text in the current line after point
6831 \(but see also the variable `org-M-RET-may-split-line').
6833 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6834 This is important for non-interactive uses of the command."
6835 (interactive "P")
6836 (if (or (= (buffer-size) 0)
6837 (and (not (save-excursion
6838 (and (ignore-errors (org-back-to-heading invisible-ok))
6839 (org-on-heading-p))))
6840 (not (org-in-item-p))))
6841 (progn
6842 (insert "\n* ")
6843 (run-hooks 'org-insert-heading-hook))
6844 (when (or force-heading (not (org-insert-item)))
6845 (let* ((empty-line-p nil)
6846 (level nil)
6847 (on-heading (org-on-heading-p))
6848 (head (save-excursion
6849 (condition-case nil
6850 (progn
6851 (org-back-to-heading invisible-ok)
6852 (when (and (not on-heading)
6853 (featurep 'org-inlinetask)
6854 (integerp org-inlinetask-min-level)
6855 (>= (length (match-string 0))
6856 org-inlinetask-min-level))
6857 ;; Find a heading level before the inline task
6858 (while (and (setq level (org-up-heading-safe))
6859 (>= level org-inlinetask-min-level)))
6860 (if (org-on-heading-p)
6861 (org-back-to-heading invisible-ok)
6862 (error "This should not happen")))
6863 (setq empty-line-p (org-previous-line-empty-p))
6864 (match-string 0))
6865 (error "*"))))
6866 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6867 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6868 pos hide-previous previous-pos)
6869 (cond
6870 ((and (org-on-heading-p) (bolp)
6871 (or (bobp)
6872 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
6873 ;; insert before the current line
6874 (open-line (if blank 2 1)))
6875 ((and (bolp)
6876 (not org-insert-heading-respect-content)
6877 (or (bobp)
6878 (save-excursion
6879 (backward-char 1) (not (outline-invisible-p)))))
6880 ;; insert right here
6881 nil)
6883 ;; somewhere in the line
6884 (save-excursion
6885 (setq previous-pos (point-at-bol))
6886 (end-of-line)
6887 (setq hide-previous (outline-invisible-p)))
6888 (and org-insert-heading-respect-content (org-show-subtree))
6889 (let ((split
6890 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6891 (save-excursion
6892 (let ((p (point)))
6893 (goto-char (point-at-bol))
6894 (and (looking-at org-complex-heading-regexp)
6895 (> p (match-beginning 4)))))))
6896 tags pos)
6897 (cond
6898 (org-insert-heading-respect-content
6899 (org-end-of-subtree nil t)
6900 (when (featurep 'org-inlinetask)
6901 (while (and (not (eobp))
6902 (looking-at "\\(\\*+\\)[ \t]+")
6903 (>= (length (match-string 1))
6904 org-inlinetask-min-level))
6905 (org-end-of-subtree nil t)))
6906 (or (bolp) (newline))
6907 (or (org-previous-line-empty-p)
6908 (and blank (newline)))
6909 (open-line 1))
6910 ((org-on-heading-p)
6911 (when hide-previous
6912 (show-children)
6913 (org-show-entry))
6914 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
6915 (setq tags (and (match-end 2) (match-string 2)))
6916 (and (match-end 1)
6917 (delete-region (match-beginning 1) (match-end 1)))
6918 (setq pos (point-at-bol))
6919 (or split (end-of-line 1))
6920 (delete-horizontal-space)
6921 (if (string-match "\\`\\*+\\'"
6922 (buffer-substring (point-at-bol) (point)))
6923 (insert " "))
6924 (newline (if blank 2 1))
6925 (when tags
6926 (save-excursion
6927 (goto-char pos)
6928 (end-of-line 1)
6929 (insert " " tags)
6930 (org-set-tags nil 'align))))
6932 (or split (end-of-line 1))
6933 (newline (if blank 2 1)))))))
6934 (insert head) (just-one-space)
6935 (setq pos (point))
6936 (end-of-line 1)
6937 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6938 (when (and org-insert-heading-respect-content hide-previous)
6939 (save-excursion
6940 (goto-char previous-pos)
6941 (hide-subtree)))
6942 (run-hooks 'org-insert-heading-hook)))))
6944 (defun org-get-heading (&optional no-tags)
6945 "Return the heading of the current entry, without the stars."
6946 (save-excursion
6947 (org-back-to-heading t)
6948 (if (looking-at
6949 (if no-tags
6950 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@#%]+:[ \t]*\\)?$")
6951 "\\*+[ \t]+\\([^\r\n]*\\)"))
6952 (match-string 1) "")))
6954 (defun org-heading-components ()
6955 "Return the components of the current heading.
6956 This is a list with the following elements:
6957 - the level as an integer
6958 - the reduced level, different if `org-odd-levels-only' is set.
6959 - the TODO keyword, or nil
6960 - the priority character, like ?A, or nil if no priority is given
6961 - the headline text itself, or the tags string if no headline text
6962 - the tags string, or nil."
6963 (save-excursion
6964 (org-back-to-heading t)
6965 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6966 (list (length (match-string 1))
6967 (org-reduced-level (length (match-string 1)))
6968 (org-match-string-no-properties 2)
6969 (and (match-end 3) (aref (match-string 3) 2))
6970 (org-match-string-no-properties 4)
6971 (org-match-string-no-properties 5)))))
6973 (defun org-get-entry ()
6974 "Get the entry text, after heading, entire subtree."
6975 (save-excursion
6976 (org-back-to-heading t)
6977 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6979 (defun org-insert-heading-after-current ()
6980 "Insert a new heading with same level as current, after current subtree."
6981 (interactive)
6982 (org-back-to-heading)
6983 (org-insert-heading)
6984 (org-move-subtree-down)
6985 (end-of-line 1))
6987 (defun org-insert-heading-respect-content ()
6988 (interactive)
6989 (let ((org-insert-heading-respect-content t))
6990 (org-insert-heading t)))
6992 (defun org-insert-todo-heading-respect-content (&optional force-state)
6993 (interactive "P")
6994 (let ((org-insert-heading-respect-content t))
6995 (org-insert-todo-heading force-state t)))
6997 (defun org-insert-todo-heading (arg &optional force-heading)
6998 "Insert a new heading with the same level and TODO state as current heading.
6999 If the heading has no TODO state, or if the state is DONE, use the first
7000 state (TODO by default). Also with prefix arg, force first state."
7001 (interactive "P")
7002 (when (or force-heading (not (org-insert-item 'checkbox)))
7003 (org-insert-heading force-heading)
7004 (save-excursion
7005 (org-back-to-heading)
7006 (outline-previous-heading)
7007 (looking-at org-todo-line-regexp))
7008 (let*
7009 ((new-mark-x
7010 (if (or arg
7011 (not (match-beginning 2))
7012 (member (match-string 2) org-done-keywords))
7013 (car org-todo-keywords-1)
7014 (match-string 2)))
7015 (new-mark
7017 (run-hook-with-args-until-success
7018 'org-todo-get-default-hook new-mark-x nil)
7019 new-mark-x)))
7020 (beginning-of-line 1)
7021 (and (looking-at "\\*+ ") (goto-char (match-end 0))
7022 (if org-treat-insert-todo-heading-as-state-change
7023 (org-todo new-mark)
7024 (insert new-mark " "))))
7025 (when org-provide-todo-statistics
7026 (org-update-parent-todo-statistics))))
7028 (defun org-insert-subheading (arg)
7029 "Insert a new subheading and demote it.
7030 Works for outline headings and for plain lists alike."
7031 (interactive "P")
7032 (org-insert-heading arg)
7033 (cond
7034 ((org-on-heading-p) (org-do-demote))
7035 ((org-at-item-p) (org-indent-item))))
7037 (defun org-insert-todo-subheading (arg)
7038 "Insert a new subheading with TODO keyword or checkbox and demote it.
7039 Works for outline headings and for plain lists alike."
7040 (interactive "P")
7041 (org-insert-todo-heading arg)
7042 (cond
7043 ((org-on-heading-p) (org-do-demote))
7044 ((org-at-item-p) (org-indent-item))))
7046 ;;; Promotion and Demotion
7048 (defvar org-after-demote-entry-hook nil
7049 "Hook run after an entry has been demoted.
7050 The cursor will be at the beginning of the entry.
7051 When a subtree is being demoted, the hook will be called for each node.")
7053 (defvar org-after-promote-entry-hook nil
7054 "Hook run after an entry has been promoted.
7055 The cursor will be at the beginning of the entry.
7056 When a subtree is being promoted, the hook will be called for each node.")
7058 (defun org-promote-subtree ()
7059 "Promote the entire subtree.
7060 See also `org-promote'."
7061 (interactive)
7062 (save-excursion
7063 (org-with-limited-levels (org-map-tree 'org-promote)))
7064 (org-fix-position-after-promote))
7066 (defun org-demote-subtree ()
7067 "Demote the entire subtree. See `org-demote'.
7068 See also `org-promote'."
7069 (interactive)
7070 (save-excursion
7071 (org-with-limited-levels (org-map-tree 'org-demote)))
7072 (org-fix-position-after-promote))
7075 (defun org-do-promote ()
7076 "Promote the current heading higher up the tree.
7077 If the region is active in `transient-mark-mode', promote all headings
7078 in the region."
7079 (interactive)
7080 (save-excursion
7081 (if (org-region-active-p)
7082 (org-map-region 'org-promote (region-beginning) (region-end))
7083 (org-promote)))
7084 (org-fix-position-after-promote))
7086 (defun org-do-demote ()
7087 "Demote the current heading lower down the tree.
7088 If the region is active in `transient-mark-mode', demote all headings
7089 in the region."
7090 (interactive)
7091 (save-excursion
7092 (if (org-region-active-p)
7093 (org-map-region 'org-demote (region-beginning) (region-end))
7094 (org-demote)))
7095 (org-fix-position-after-promote))
7097 (defun org-fix-position-after-promote ()
7098 "Make sure that after pro/demotion cursor position is right."
7099 (let ((pos (point)))
7100 (when (save-excursion
7101 (beginning-of-line 1)
7102 (looking-at org-todo-line-regexp)
7103 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7104 (cond ((eobp) (insert " "))
7105 ((eolp) (insert " "))
7106 ((equal (char-after) ?\ ) (forward-char 1))))))
7108 (defun org-current-level ()
7109 "Return the level of the current entry, or nil if before the first headline.
7110 The level is the number of stars at the beginning of the headline."
7111 (save-excursion
7112 (org-with-limited-levels
7113 (ignore-errors
7114 (org-back-to-heading t)
7115 (funcall outline-level)))))
7117 (defun org-get-previous-line-level ()
7118 "Return the outline depth of the last headline before the current line.
7119 Returns 0 for the first headline in the buffer, and nil if before the
7120 first headline."
7121 (let ((current-level (org-current-level))
7122 (prev-level (when (> (line-number-at-pos) 1)
7123 (save-excursion
7124 (beginning-of-line 0)
7125 (org-current-level)))))
7126 (cond ((null current-level) nil) ; Before first headline
7127 ((null prev-level) 0) ; At first headline
7128 (prev-level))))
7130 (defun org-reduced-level (l)
7131 "Compute the effective level of a heading.
7132 This takes into account the setting of `org-odd-levels-only'."
7133 (cond
7134 ((zerop l) 0)
7135 (org-odd-levels-only (1+ (floor (/ l 2))))
7136 (t l)))
7138 (defun org-level-increment ()
7139 "Return the number of stars that will be added or removed at a
7140 time to headlines when structure editing, based on the value of
7141 `org-odd-levels-only'."
7142 (if org-odd-levels-only 2 1))
7144 (defun org-get-valid-level (level &optional change)
7145 "Rectify a level change under the influence of `org-odd-levels-only'
7146 LEVEL is a current level, CHANGE is by how much the level should be
7147 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7148 even level numbers will become the next higher odd number."
7149 (if org-odd-levels-only
7150 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7151 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7152 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7153 (max 1 (+ level (or change 0)))))
7155 (if (boundp 'define-obsolete-function-alias)
7156 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7157 (define-obsolete-function-alias 'org-get-legal-level
7158 'org-get-valid-level)
7159 (define-obsolete-function-alias 'org-get-legal-level
7160 'org-get-valid-level "23.1")))
7162 (defun org-promote ()
7163 "Promote the current heading higher up the tree.
7164 If the region is active in `transient-mark-mode', promote all headings
7165 in the region."
7166 (org-back-to-heading t)
7167 (let* ((level (save-match-data (funcall outline-level)))
7168 (after-change-functions (remove 'flyspell-after-change-function
7169 after-change-functions))
7170 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7171 (diff (abs (- level (length up-head) -1))))
7172 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7173 (replace-match up-head nil t)
7174 ;; Fixup tag positioning
7175 (and org-auto-align-tags (org-set-tags nil t))
7176 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7177 (run-hooks 'org-after-promote-entry-hook)))
7179 (defun org-demote ()
7180 "Demote the current heading lower down the tree.
7181 If the region is active in `transient-mark-mode', demote all headings
7182 in the region."
7183 (org-back-to-heading t)
7184 (let* ((level (save-match-data (funcall outline-level)))
7185 (after-change-functions (remove 'flyspell-after-change-function
7186 after-change-functions))
7187 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7188 (diff (abs (- level (length down-head) -1))))
7189 (replace-match down-head nil t)
7190 ;; Fixup tag positioning
7191 (and org-auto-align-tags (org-set-tags nil t))
7192 (if org-adapt-indentation (org-fixup-indentation diff))
7193 (run-hooks 'org-after-demote-entry-hook)))
7195 (defun org-cycle-level ()
7196 "Cycle the level of an empty headline through possible states.
7197 This goes first to child, then to parent, level, then up the hierarchy.
7198 After top level, it switches back to sibling level."
7199 (interactive)
7200 (let ((org-adapt-indentation nil))
7201 (when (org-point-at-end-of-empty-headline)
7202 (setq this-command 'org-cycle-level) ; Only needed for caching
7203 (let ((cur-level (org-current-level))
7204 (prev-level (org-get-previous-line-level)))
7205 (cond
7206 ;; If first headline in file, promote to top-level.
7207 ((= prev-level 0)
7208 (loop repeat (/ (- cur-level 1) (org-level-increment))
7209 do (org-do-promote)))
7210 ;; If same level as prev, demote one.
7211 ((= prev-level cur-level)
7212 (org-do-demote))
7213 ;; If parent is top-level, promote to top level if not already.
7214 ((= prev-level 1)
7215 (loop repeat (/ (- cur-level 1) (org-level-increment))
7216 do (org-do-promote)))
7217 ;; If top-level, return to prev-level.
7218 ((= cur-level 1)
7219 (loop repeat (/ (- prev-level 1) (org-level-increment))
7220 do (org-do-demote)))
7221 ;; If less than prev-level, promote one.
7222 ((< cur-level prev-level)
7223 (org-do-promote))
7224 ;; If deeper than prev-level, promote until higher than
7225 ;; prev-level.
7226 ((> cur-level prev-level)
7227 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7228 do (org-do-promote))))
7229 t))))
7231 (defun org-map-tree (fun)
7232 "Call FUN for every heading underneath the current one."
7233 (org-back-to-heading)
7234 (let ((level (funcall outline-level)))
7235 (save-excursion
7236 (funcall fun)
7237 (while (and (progn
7238 (outline-next-heading)
7239 (> (funcall outline-level) level))
7240 (not (eobp)))
7241 (funcall fun)))))
7243 (defun org-map-region (fun beg end)
7244 "Call FUN for every heading between BEG and END."
7245 (let ((org-ignore-region t))
7246 (save-excursion
7247 (setq end (copy-marker end))
7248 (goto-char beg)
7249 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
7250 (< (point) end))
7251 (funcall fun))
7252 (while (and (progn
7253 (outline-next-heading)
7254 (< (point) end))
7255 (not (eobp)))
7256 (funcall fun)))))
7258 (defun org-fixup-indentation (diff)
7259 "Change the indentation in the current entry by DIFF.
7260 However, if any line in the current entry has no indentation, or if it
7261 would end up with no indentation after the change, nothing at all is done."
7262 (save-excursion
7263 (let ((end (save-excursion (outline-next-heading)
7264 (point-marker)))
7265 (prohibit (if (> diff 0)
7266 "^\\S-"
7267 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7268 col)
7269 (unless (save-excursion (end-of-line 1)
7270 (re-search-forward prohibit end t))
7271 (while (and (< (point) end)
7272 (re-search-forward "^[ \t]+" end t))
7273 (goto-char (match-end 0))
7274 (setq col (current-column))
7275 (if (< diff 0) (replace-match ""))
7276 (org-indent-to-column (+ diff col))))
7277 (move-marker end nil))))
7279 (defun org-convert-to-odd-levels ()
7280 "Convert an org-mode file with all levels allowed to one with odd levels.
7281 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7282 level 5 etc."
7283 (interactive)
7284 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7285 (let ((outline-regexp org-outline-regexp)
7286 (outline-level 'org-outline-level)
7287 (org-odd-levels-only nil) n)
7288 (save-excursion
7289 (goto-char (point-min))
7290 (while (re-search-forward "^\\*\\*+ " nil t)
7291 (setq n (- (length (match-string 0)) 2))
7292 (while (>= (setq n (1- n)) 0)
7293 (org-demote))
7294 (end-of-line 1))))))
7296 (defun org-convert-to-oddeven-levels ()
7297 "Convert an org-mode file with only odd levels to one with odd/even levels.
7298 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7299 file contains a section with an even level, conversion would
7300 destroy the structure of the file. An error is signaled in this
7301 case."
7302 (interactive)
7303 (goto-char (point-min))
7304 ;; First check if there are no even levels
7305 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7306 (org-show-context t)
7307 (error "Not all levels are odd in this file. Conversion not possible"))
7308 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7309 (let ((outline-regexp org-outline-regexp)
7310 (outline-level 'org-outline-level)
7311 (org-odd-levels-only nil) n)
7312 (save-excursion
7313 (goto-char (point-min))
7314 (while (re-search-forward "^\\*\\*+ " nil t)
7315 (setq n (/ (1- (length (match-string 0))) 2))
7316 (while (>= (setq n (1- n)) 0)
7317 (org-promote))
7318 (end-of-line 1))))))
7320 (defun org-tr-level (n)
7321 "Make N odd if required."
7322 (if org-odd-levels-only (1+ (/ n 2)) n))
7324 ;;; Vertical tree motion, cutting and pasting of subtrees
7326 (defun org-move-subtree-up (&optional arg)
7327 "Move the current subtree up past ARG headlines of the same level."
7328 (interactive "p")
7329 (org-move-subtree-down (- (prefix-numeric-value arg))))
7331 (defun org-move-subtree-down (&optional arg)
7332 "Move the current subtree down past ARG headlines of the same level."
7333 (interactive "p")
7334 (setq arg (prefix-numeric-value arg))
7335 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7336 'org-get-last-sibling))
7337 (ins-point (make-marker))
7338 (cnt (abs arg))
7339 (col (current-column))
7340 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7341 ;; Select the tree
7342 (org-back-to-heading)
7343 (setq beg0 (point))
7344 (save-excursion
7345 (setq ne-beg (org-back-over-empty-lines))
7346 (setq beg (point)))
7347 (save-match-data
7348 (save-excursion (outline-end-of-heading)
7349 (setq folded (outline-invisible-p)))
7350 (outline-end-of-subtree))
7351 (outline-next-heading)
7352 (setq ne-end (org-back-over-empty-lines))
7353 (setq end (point))
7354 (goto-char beg0)
7355 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7356 ;; include less whitespace
7357 (save-excursion
7358 (goto-char beg)
7359 (forward-line (- ne-beg ne-end))
7360 (setq beg (point))))
7361 ;; Find insertion point, with error handling
7362 (while (> cnt 0)
7363 (or (and (funcall movfunc) (looking-at outline-regexp))
7364 (progn (goto-char beg0)
7365 (error "Cannot move past superior level or buffer limit")))
7366 (setq cnt (1- cnt)))
7367 (if (> arg 0)
7368 ;; Moving forward - still need to move over subtree
7369 (progn (org-end-of-subtree t t)
7370 (save-excursion
7371 (org-back-over-empty-lines)
7372 (or (bolp) (newline)))))
7373 (setq ne-ins (org-back-over-empty-lines))
7374 (move-marker ins-point (point))
7375 (setq txt (buffer-substring beg end))
7376 (org-save-markers-in-region beg end)
7377 (delete-region beg end)
7378 (org-remove-empty-overlays-at beg)
7379 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7380 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7381 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7382 (let ((bbb (point)))
7383 (insert-before-markers txt)
7384 (org-reinstall-markers-in-region bbb)
7385 (move-marker ins-point bbb))
7386 (or (bolp) (insert "\n"))
7387 (setq ins-end (point))
7388 (goto-char ins-point)
7389 (org-skip-whitespace)
7390 (when (and (< arg 0)
7391 (org-first-sibling-p)
7392 (> ne-ins ne-beg))
7393 ;; Move whitespace back to beginning
7394 (save-excursion
7395 (goto-char ins-end)
7396 (let ((kill-whole-line t))
7397 (kill-line (- ne-ins ne-beg)) (point)))
7398 (insert (make-string (- ne-ins ne-beg) ?\n)))
7399 (move-marker ins-point nil)
7400 (if folded
7401 (hide-subtree)
7402 (org-show-entry)
7403 (show-children)
7404 (org-cycle-hide-drawers 'children))
7405 (org-clean-visibility-after-subtree-move)
7406 ;; move back to the initial column we were at
7407 (move-to-column col)))
7409 (defvar org-subtree-clip ""
7410 "Clipboard for cut and paste of subtrees.
7411 This is actually only a copy of the kill, because we use the normal kill
7412 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7414 (defvar org-subtree-clip-folded nil
7415 "Was the last copied subtree folded?
7416 This is used to fold the tree back after pasting.")
7418 (defun org-cut-subtree (&optional n)
7419 "Cut the current subtree into the clipboard.
7420 With prefix arg N, cut this many sequential subtrees.
7421 This is a short-hand for marking the subtree and then cutting it."
7422 (interactive "p")
7423 (org-copy-subtree n 'cut))
7425 (defun org-copy-subtree (&optional n cut force-store-markers)
7426 "Cut the current subtree into the clipboard.
7427 With prefix arg N, cut this many sequential subtrees.
7428 This is a short-hand for marking the subtree and then copying it.
7429 If CUT is non-nil, actually cut the subtree.
7430 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7431 of some markers in the region, even if CUT is non-nil. This is
7432 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7433 (interactive "p")
7434 (let (beg end folded (beg0 (point)))
7435 (if (interactive-p)
7436 (org-back-to-heading nil) ; take what looks like a subtree
7437 (org-back-to-heading t)) ; take what is really there
7438 (org-back-over-empty-lines)
7439 (setq beg (point))
7440 (skip-chars-forward " \t\r\n")
7441 (save-match-data
7442 (save-excursion (outline-end-of-heading)
7443 (setq folded (outline-invisible-p)))
7444 (condition-case nil
7445 (org-forward-same-level (1- n) t)
7446 (error nil))
7447 (org-end-of-subtree t t))
7448 (org-back-over-empty-lines)
7449 (setq end (point))
7450 (goto-char beg0)
7451 (when (> end beg)
7452 (setq org-subtree-clip-folded folded)
7453 (when (or cut force-store-markers)
7454 (org-save-markers-in-region beg end))
7455 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7456 (setq org-subtree-clip (current-kill 0))
7457 (message "%s: Subtree(s) with %d characters"
7458 (if cut "Cut" "Copied")
7459 (length org-subtree-clip)))))
7461 (defun org-paste-subtree (&optional level tree for-yank)
7462 "Paste the clipboard as a subtree, with modification of headline level.
7463 The entire subtree is promoted or demoted in order to match a new headline
7464 level.
7466 If the cursor is at the beginning of a headline, the same level as
7467 that headline is used to paste the tree
7469 If not, the new level is derived from the *visible* headings
7470 before and after the insertion point, and taken to be the inferior headline
7471 level of the two. So if the previous visible heading is level 3 and the
7472 next is level 4 (or vice versa), level 4 will be used for insertion.
7473 This makes sure that the subtree remains an independent subtree and does
7474 not swallow low level entries.
7476 You can also force a different level, either by using a numeric prefix
7477 argument, or by inserting the heading marker by hand. For example, if the
7478 cursor is after \"*****\", then the tree will be shifted to level 5.
7480 If optional TREE is given, use this text instead of the kill ring.
7482 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7483 move back over whitespace before inserting, and move point to the end of
7484 the inserted text when done."
7485 (interactive "P")
7486 (setq tree (or tree (and kill-ring (current-kill 0))))
7487 (unless (org-kill-is-subtree-p tree)
7488 (error "%s"
7489 (substitute-command-keys
7490 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7491 (let* ((visp (not (outline-invisible-p)))
7492 (txt tree)
7493 (^re (concat "^\\(" outline-regexp "\\)"))
7494 (re (concat "\\(" outline-regexp "\\)"))
7495 (^re_ (concat "\\(\\*+\\)[ \t]*"))
7497 (old-level (if (string-match ^re txt)
7498 (- (match-end 0) (match-beginning 0) 1)
7499 -1))
7500 (force-level (cond (level (prefix-numeric-value level))
7501 ((and (looking-at "[ \t]*$")
7502 (string-match
7503 ^re_ (buffer-substring
7504 (point-at-bol) (point))))
7505 (- (match-end 1) (match-beginning 1)))
7506 ((and (bolp)
7507 (looking-at org-outline-regexp))
7508 (- (match-end 0) (point) 1))
7509 (t nil)))
7510 (previous-level (save-excursion
7511 (condition-case nil
7512 (progn
7513 (outline-previous-visible-heading 1)
7514 (if (looking-at re)
7515 (- (match-end 0) (match-beginning 0) 1)
7517 (error 1))))
7518 (next-level (save-excursion
7519 (condition-case nil
7520 (progn
7521 (or (looking-at outline-regexp)
7522 (outline-next-visible-heading 1))
7523 (if (looking-at re)
7524 (- (match-end 0) (match-beginning 0) 1)
7526 (error 1))))
7527 (new-level (or force-level (max previous-level next-level)))
7528 (shift (if (or (= old-level -1)
7529 (= new-level -1)
7530 (= old-level new-level))
7532 (- new-level old-level)))
7533 (delta (if (> shift 0) -1 1))
7534 (func (if (> shift 0) 'org-demote 'org-promote))
7535 (org-odd-levels-only nil)
7536 beg end newend)
7537 ;; Remove the forced level indicator
7538 (if force-level
7539 (delete-region (point-at-bol) (point)))
7540 ;; Paste
7541 (beginning-of-line 1)
7542 (unless for-yank (org-back-over-empty-lines))
7543 (setq beg (point))
7544 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7545 (insert-before-markers txt)
7546 (unless (string-match "\n\\'" txt) (insert "\n"))
7547 (setq newend (point))
7548 (org-reinstall-markers-in-region beg)
7549 (setq end (point))
7550 (goto-char beg)
7551 (skip-chars-forward " \t\n\r")
7552 (setq beg (point))
7553 (if (and (outline-invisible-p) visp)
7554 (save-excursion (outline-show-heading)))
7555 ;; Shift if necessary
7556 (unless (= shift 0)
7557 (save-restriction
7558 (narrow-to-region beg end)
7559 (while (not (= shift 0))
7560 (org-map-region func (point-min) (point-max))
7561 (setq shift (+ delta shift)))
7562 (goto-char (point-min))
7563 (setq newend (point-max))))
7564 (when (or (interactive-p) for-yank)
7565 (message "Clipboard pasted as level %d subtree" new-level))
7566 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7567 kill-ring
7568 (eq org-subtree-clip (current-kill 0))
7569 org-subtree-clip-folded)
7570 ;; The tree was folded before it was killed/copied
7571 (hide-subtree))
7572 (and for-yank (goto-char newend))))
7574 (defun org-kill-is-subtree-p (&optional txt)
7575 "Check if the current kill is an outline subtree, or a set of trees.
7576 Returns nil if kill does not start with a headline, or if the first
7577 headline level is not the largest headline level in the tree.
7578 So this will actually accept several entries of equal levels as well,
7579 which is OK for `org-paste-subtree'.
7580 If optional TXT is given, check this string instead of the current kill."
7581 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7582 (start-level (and kill
7583 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
7584 org-outline-regexp "\\)")
7585 kill)
7586 (- (match-end 2) (match-beginning 2) 1)))
7587 (re (concat "^" org-outline-regexp))
7588 (start (1+ (or (match-beginning 2) -1))))
7589 (if (not start-level)
7590 (progn
7591 nil) ;; does not even start with a heading
7592 (catch 'exit
7593 (while (setq start (string-match re kill (1+ start)))
7594 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7595 (throw 'exit nil)))
7596 t))))
7598 (defvar org-markers-to-move nil
7599 "Markers that should be moved with a cut-and-paste operation.
7600 Those markers are stored together with their positions relative to
7601 the start of the region.")
7603 (defun org-save-markers-in-region (beg end)
7604 "Check markers in region.
7605 If these markers are between BEG and END, record their position relative
7606 to BEG, so that after moving the block of text, we can put the markers back
7607 into place.
7608 This function gets called just before an entry or tree gets cut from the
7609 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7610 called immediately, to move the markers with the entries."
7611 (setq org-markers-to-move nil)
7612 (when (featurep 'org-clock)
7613 (org-clock-save-markers-for-cut-and-paste beg end))
7614 (when (featurep 'org-agenda)
7615 (org-agenda-save-markers-for-cut-and-paste beg end)))
7617 (defun org-check-and-save-marker (marker beg end)
7618 "Check if MARKER is between BEG and END.
7619 If yes, remember the marker and the distance to BEG."
7620 (when (and (marker-buffer marker)
7621 (equal (marker-buffer marker) (current-buffer)))
7622 (if (and (>= marker beg) (< marker end))
7623 (push (cons marker (- marker beg)) org-markers-to-move))))
7625 (defun org-reinstall-markers-in-region (beg)
7626 "Move all remembered markers to their position relative to BEG."
7627 (mapc (lambda (x)
7628 (move-marker (car x) (+ beg (cdr x))))
7629 org-markers-to-move)
7630 (setq org-markers-to-move nil))
7632 (defun org-narrow-to-subtree ()
7633 "Narrow buffer to the current subtree."
7634 (interactive)
7635 (save-excursion
7636 (save-match-data
7637 (org-with-limited-levels
7638 (narrow-to-region
7639 (progn (org-back-to-heading t) (point))
7640 (progn (org-end-of-subtree t t)
7641 (if (and (org-on-heading-p) (not (eobp))) (backward-char 1))
7642 (point)))))))
7644 (defun org-narrow-to-block ()
7645 "Narrow buffer to the current block."
7646 (interactive)
7647 (let ((bstart "^[ \t]*#\\+begin")
7648 (bend "[ \t]*#\\+end")
7649 (case-fold-search t) ;; allow #+BEGIN
7650 b_start b_end)
7651 (if (org-in-regexps-block-p bstart bend)
7652 (progn
7653 (save-excursion (re-search-backward bstart nil t)
7654 (setq b_start (match-beginning 0)))
7655 (save-excursion (re-search-forward bend nil t)
7656 (setq b_end (match-end 0)))
7657 (narrow-to-region b_start b_end))
7658 (error "Not in a block"))))
7660 (eval-when-compile
7661 (defvar org-property-drawer-re))
7663 (defvar org-property-start-re) ;; defined below
7664 (defun org-clone-subtree-with-time-shift (n &optional shift)
7665 "Clone the task (subtree) at point N times.
7666 The clones will be inserted as siblings.
7668 In interactive use, the user will be prompted for the number of
7669 clones to be produced, and for a time SHIFT, which may be a
7670 repeater as used in time stamps, for example `+3d'.
7672 When a valid repeater is given and the entry contains any time
7673 stamps, the clones will become a sequence in time, with time
7674 stamps in the subtree shifted for each clone produced. If SHIFT
7675 is nil or the empty string, time stamps will be left alone. The
7676 ID property of the original subtree is removed.
7678 If the original subtree did contain time stamps with a repeater,
7679 the following will happen:
7680 - the repeater will be removed in each clone
7681 - an additional clone will be produced, with the current, unshifted
7682 date(s) in the entry.
7683 - the original entry will be placed *after* all the clones, with
7684 repeater intact.
7685 - the start days in the repeater in the original entry will be shifted
7686 to past the last clone.
7687 I this way you can spell out a number of instances of a repeating task,
7688 and still retain the repeater to cover future instances of the task."
7689 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7690 (let (beg end template task idprop
7691 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7692 (if (not (and (integerp n) (> n 0)))
7693 (error "Invalid number of replications %s" n))
7694 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7695 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7696 shift)))
7697 (error "Invalid shift specification %s" shift))
7698 (when doshift
7699 (setq shift-n (string-to-number (match-string 1 shift))
7700 shift-what (cdr (assoc (match-string 2 shift)
7701 '(("d" . day) ("w" . week)
7702 ("m" . month) ("y" . year))))))
7703 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7704 (setq nmin 1 nmax n)
7705 (org-back-to-heading t)
7706 (setq beg (point))
7707 (setq idprop (org-entry-get nil "ID"))
7708 (org-end-of-subtree t t)
7709 (or (bolp) (insert "\n"))
7710 (setq end (point))
7711 (setq template (buffer-substring beg end))
7712 (when (and doshift
7713 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7714 (delete-region beg end)
7715 (setq end beg)
7716 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7717 (goto-char end)
7718 (loop for n from nmin to nmax do
7719 ;; prepare clone
7720 (with-temp-buffer
7721 (insert template)
7722 (org-mode)
7723 (goto-char (point-min))
7724 (and idprop (if org-clone-delete-id
7725 (org-entry-delete nil "ID")
7726 (org-id-get-create t)))
7727 (while (re-search-forward org-property-start-re nil t)
7728 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7729 (goto-char (point-min))
7730 (when doshift
7731 (while (re-search-forward org-ts-regexp-both nil t)
7732 (org-timestamp-change (* n shift-n) shift-what))
7733 (unless (= n n-no-remove)
7734 (goto-char (point-min))
7735 (while (re-search-forward org-ts-regexp nil t)
7736 (save-excursion
7737 (goto-char (match-beginning 0))
7738 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7739 (delete-region (match-beginning 1) (match-end 1)))))))
7740 (setq task (buffer-string)))
7741 (insert task))
7742 (goto-char beg)))
7744 ;;; Outline Sorting
7746 (defun org-sort (with-case)
7747 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7748 Optional argument WITH-CASE means sort case-sensitively.
7749 With a double prefix argument, also remove duplicate entries."
7750 (interactive "P")
7751 (cond
7752 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7753 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7755 (org-call-with-arg 'org-sort-entries with-case))))
7757 (defun org-sort-remove-invisible (s)
7758 (remove-text-properties 0 (length s) org-rm-props s)
7759 (while (string-match org-bracket-link-regexp s)
7760 (setq s (replace-match (if (match-end 2)
7761 (match-string 3 s)
7762 (match-string 1 s)) t t s)))
7765 (defvar org-priority-regexp) ; defined later in the file
7767 (defvar org-after-sorting-entries-or-items-hook nil
7768 "Hook that is run after a bunch of entries or items have been sorted.
7769 When children are sorted, the cursor is in the parent line when this
7770 hook gets called. When a region or a plain list is sorted, the cursor
7771 will be in the first entry of the sorted region/list.")
7773 (defun org-sort-entries
7774 (&optional with-case sorting-type getkey-func compare-func property)
7775 "Sort entries on a certain level of an outline tree.
7776 If there is an active region, the entries in the region are sorted.
7777 Else, if the cursor is before the first entry, sort the top-level items.
7778 Else, the children of the entry at point are sorted.
7780 Sorting can be alphabetically, numerically, by date/time as given by
7781 a time stamp, by a property or by priority.
7783 The command prompts for the sorting type unless it has been given to the
7784 function through the SORTING-TYPE argument, which needs to be a character,
7785 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7786 precise meaning of each character:
7788 n Numerically, by converting the beginning of the entry/item to a number.
7789 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7790 t By date/time, either the first active time stamp in the entry, or, if
7791 none exist, by the first inactive one.
7792 s By the scheduled date/time.
7793 d By deadline date/time.
7794 c By creation time, which is assumed to be the first inactive time stamp
7795 at the beginning of a line.
7796 p By priority according to the cookie.
7797 r By the value of a property.
7799 Capital letters will reverse the sort order.
7801 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7802 called with point at the beginning of the record. It must return either
7803 a string or a number that should serve as the sorting key for that record.
7805 Comparing entries ignores case by default. However, with an optional argument
7806 WITH-CASE, the sorting considers case as well."
7807 (interactive "P")
7808 (let ((case-func (if with-case 'identity 'downcase))
7809 start beg end stars re re2
7810 txt what tmp)
7811 ;; Find beginning and end of region to sort
7812 (cond
7813 ((org-region-active-p)
7814 ;; we will sort the region
7815 (setq end (region-end)
7816 what "region")
7817 (goto-char (region-beginning))
7818 (if (not (org-on-heading-p)) (outline-next-heading))
7819 (setq start (point)))
7820 ((or (org-on-heading-p)
7821 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7822 ;; we will sort the children of the current headline
7823 (org-back-to-heading)
7824 (setq start (point)
7825 end (progn (org-end-of-subtree t t)
7826 (or (bolp) (insert "\n"))
7827 (org-back-over-empty-lines)
7828 (point))
7829 what "children")
7830 (goto-char start)
7831 (show-subtree)
7832 (outline-next-heading))
7834 ;; we will sort the top-level entries in this file
7835 (goto-char (point-min))
7836 (or (org-on-heading-p) (outline-next-heading))
7837 (setq start (point))
7838 (goto-char (point-max))
7839 (beginning-of-line 1)
7840 (when (looking-at ".*?\\S-")
7841 ;; File ends in a non-white line
7842 (end-of-line 1)
7843 (insert "\n"))
7844 (setq end (point-max))
7845 (setq what "top-level")
7846 (goto-char start)
7847 (show-all)))
7849 (setq beg (point))
7850 (if (>= beg end) (error "Nothing to sort"))
7852 (looking-at "\\(\\*+\\)")
7853 (setq stars (match-string 1)
7854 re (concat "^" (regexp-quote stars) " +")
7855 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
7856 txt (buffer-substring beg end))
7857 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7858 (if (and (not (equal stars "*")) (string-match re2 txt))
7859 (error "Region to sort contains a level above the first entry"))
7861 (unless sorting-type
7862 (message
7863 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7864 [t]ime [s]cheduled [d]eadline [c]reated
7865 A/N/T/S/D/C/P/O/F means reversed:"
7866 what)
7867 (setq sorting-type (read-char-exclusive))
7869 (and (= (downcase sorting-type) ?f)
7870 (setq getkey-func
7871 (org-icompleting-read "Sort using function: "
7872 obarray 'fboundp t nil nil))
7873 (setq getkey-func (intern getkey-func)))
7875 (and (= (downcase sorting-type) ?r)
7876 (setq property
7877 (org-icompleting-read "Property: "
7878 (mapcar 'list (org-buffer-property-keys t))
7879 nil t))))
7881 (message "Sorting entries...")
7883 (save-restriction
7884 (narrow-to-region start end)
7885 (let ((dcst (downcase sorting-type))
7886 (case-fold-search nil)
7887 (now (current-time)))
7888 (sort-subr
7889 (/= dcst sorting-type)
7890 ;; This function moves to the beginning character of the "record" to
7891 ;; be sorted.
7892 (lambda nil
7893 (if (re-search-forward re nil t)
7894 (goto-char (match-beginning 0))
7895 (goto-char (point-max))))
7896 ;; This function moves to the last character of the "record" being
7897 ;; sorted.
7898 (lambda nil
7899 (save-match-data
7900 (condition-case nil
7901 (outline-forward-same-level 1)
7902 (error
7903 (goto-char (point-max))))))
7904 ;; This function returns the value that gets sorted against.
7905 (lambda nil
7906 (cond
7907 ((= dcst ?n)
7908 (if (looking-at org-complex-heading-regexp)
7909 (string-to-number (match-string 4))
7910 nil))
7911 ((= dcst ?a)
7912 (if (looking-at org-complex-heading-regexp)
7913 (funcall case-func (match-string 4))
7914 nil))
7915 ((= dcst ?t)
7916 (let ((end (save-excursion (outline-next-heading) (point))))
7917 (if (or (re-search-forward org-ts-regexp end t)
7918 (re-search-forward org-ts-regexp-both end t))
7919 (org-time-string-to-seconds (match-string 0))
7920 (org-float-time now))))
7921 ((= dcst ?c)
7922 (let ((end (save-excursion (outline-next-heading) (point))))
7923 (if (re-search-forward
7924 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7925 end t)
7926 (org-time-string-to-seconds (match-string 0))
7927 (org-float-time now))))
7928 ((= dcst ?s)
7929 (let ((end (save-excursion (outline-next-heading) (point))))
7930 (if (re-search-forward org-scheduled-time-regexp end t)
7931 (org-time-string-to-seconds (match-string 1))
7932 (org-float-time now))))
7933 ((= dcst ?d)
7934 (let ((end (save-excursion (outline-next-heading) (point))))
7935 (if (re-search-forward org-deadline-time-regexp end t)
7936 (org-time-string-to-seconds (match-string 1))
7937 (org-float-time now))))
7938 ((= dcst ?p)
7939 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7940 (string-to-char (match-string 2))
7941 org-default-priority))
7942 ((= dcst ?r)
7943 (or (org-entry-get nil property) ""))
7944 ((= dcst ?o)
7945 (if (looking-at org-complex-heading-regexp)
7946 (- 9999 (length (member (match-string 2)
7947 org-todo-keywords-1)))))
7948 ((= dcst ?f)
7949 (if getkey-func
7950 (progn
7951 (setq tmp (funcall getkey-func))
7952 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7953 tmp)
7954 (error "Invalid key function `%s'" getkey-func)))
7955 (t (error "Invalid sorting type `%c'" sorting-type))))
7957 (cond
7958 ((= dcst ?a) 'string<)
7959 ((= dcst ?f) compare-func)
7960 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7961 (t nil)))))
7962 (run-hooks 'org-after-sorting-entries-or-items-hook)
7963 (message "Sorting entries...done")))
7965 (defun org-do-sort (table what &optional with-case sorting-type)
7966 "Sort TABLE of WHAT according to SORTING-TYPE.
7967 The user will be prompted for the SORTING-TYPE if the call to this
7968 function does not specify it. WHAT is only for the prompt, to indicate
7969 what is being sorted. The sorting key will be extracted from
7970 the car of the elements of the table.
7971 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7972 (unless sorting-type
7973 (message
7974 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7975 what)
7976 (setq sorting-type (read-char-exclusive)))
7977 (let ((dcst (downcase sorting-type))
7978 extractfun comparefun)
7979 ;; Define the appropriate functions
7980 (cond
7981 ((= dcst ?n)
7982 (setq extractfun 'string-to-number
7983 comparefun (if (= dcst sorting-type) '< '>)))
7984 ((= dcst ?a)
7985 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7986 (lambda(x) (downcase (org-sort-remove-invisible x))))
7987 comparefun (if (= dcst sorting-type)
7988 'string<
7989 (lambda (a b) (and (not (string< a b))
7990 (not (string= a b)))))))
7991 ((= dcst ?t)
7992 (setq extractfun
7993 (lambda (x)
7994 (if (or (string-match org-ts-regexp x)
7995 (string-match org-ts-regexp-both x))
7996 (org-float-time
7997 (org-time-string-to-time (match-string 0 x)))
7999 comparefun (if (= dcst sorting-type) '< '>)))
8000 (t (error "Invalid sorting type `%c'" sorting-type)))
8002 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8003 table)
8004 (lambda (a b) (funcall comparefun (car a) (car b))))))
8007 ;;; The orgstruct minor mode
8009 ;; Define a minor mode which can be used in other modes in order to
8010 ;; integrate the org-mode structure editing commands.
8012 ;; This is really a hack, because the org-mode structure commands use
8013 ;; keys which normally belong to the major mode. Here is how it
8014 ;; works: The minor mode defines all the keys necessary to operate the
8015 ;; structure commands, but wraps the commands into a function which
8016 ;; tests if the cursor is currently at a headline or a plain list
8017 ;; item. If that is the case, the structure command is used,
8018 ;; temporarily setting many Org-mode variables like regular
8019 ;; expressions for filling etc. However, when any of those keys is
8020 ;; used at a different location, function uses `key-binding' to look
8021 ;; up if the key has an associated command in another currently active
8022 ;; keymap (minor modes, major mode, global), and executes that
8023 ;; command. There might be problems if any of the keys is otherwise
8024 ;; used as a prefix key.
8026 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8027 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8028 ;; addresses this by checking explicitly for both bindings.
8030 (defvar orgstruct-mode-map (make-sparse-keymap)
8031 "Keymap for the minor `orgstruct-mode'.")
8033 (defvar org-local-vars nil
8034 "List of local variables, for use by `orgstruct-mode'.")
8036 ;;;###autoload
8037 (define-minor-mode orgstruct-mode
8038 "Toggle the minor mode `orgstruct-mode'.
8039 This mode is for using Org-mode structure commands in other
8040 modes. The following keys behave as if Org-mode were active, if
8041 the cursor is on a headline, or on a plain list item (both as
8042 defined by Org-mode).
8044 M-up Move entry/item up
8045 M-down Move entry/item down
8046 M-left Promote
8047 M-right Demote
8048 M-S-up Move entry/item up
8049 M-S-down Move entry/item down
8050 M-S-left Promote subtree
8051 M-S-right Demote subtree
8052 M-q Fill paragraph and items like in Org-mode
8053 C-c ^ Sort entries
8054 C-c - Cycle list bullet
8055 TAB Cycle item visibility
8056 M-RET Insert new heading/item
8057 S-M-RET Insert new TODO heading / Checkbox item
8058 C-c C-c Set tags / toggle checkbox"
8059 nil " OrgStruct" nil
8060 (org-load-modules-maybe)
8061 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8063 ;;;###autoload
8064 (defun turn-on-orgstruct ()
8065 "Unconditionally turn on `orgstruct-mode'."
8066 (orgstruct-mode 1))
8068 (defun orgstruct++-mode (&optional arg)
8069 "Toggle `orgstruct-mode', the enhanced version of it.
8070 In addition to setting orgstruct-mode, this also exports all indentation
8071 and autofilling variables from org-mode into the buffer. It will also
8072 recognize item context in multiline items.
8073 Note that turning off orgstruct-mode will *not* remove the
8074 indentation/paragraph settings. This can only be done by refreshing the
8075 major mode, for example with \\[normal-mode]."
8076 (interactive "P")
8077 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8078 (if (< arg 1)
8079 (orgstruct-mode -1)
8080 (orgstruct-mode 1)
8081 (let (var val)
8082 (mapc
8083 (lambda (x)
8084 (when (string-match
8085 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8086 (symbol-name (car x)))
8087 (setq var (car x) val (nth 1 x))
8088 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8089 org-local-vars)
8090 (org-set-local 'orgstruct-is-++ t))))
8092 (defvar orgstruct-is-++ nil
8093 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8094 (make-variable-buffer-local 'orgstruct-is-++)
8096 ;;;###autoload
8097 (defun turn-on-orgstruct++ ()
8098 "Unconditionally turn on `orgstruct++-mode'."
8099 (orgstruct++-mode 1))
8101 (defun orgstruct-error ()
8102 "Error when there is no default binding for a structure key."
8103 (interactive)
8104 (error "This key has no function outside structure elements"))
8106 (defun orgstruct-setup ()
8107 "Setup orgstruct keymaps."
8108 (let ((nfunc 0)
8109 (bindings
8110 (list
8111 '([(meta up)] org-metaup)
8112 '([(meta down)] org-metadown)
8113 '([(meta left)] org-metaleft)
8114 '([(meta right)] org-metaright)
8115 '([(meta shift up)] org-shiftmetaup)
8116 '([(meta shift down)] org-shiftmetadown)
8117 '([(meta shift left)] org-shiftmetaleft)
8118 '([(meta shift right)] org-shiftmetaright)
8119 '([?\e (up)] org-metaup)
8120 '([?\e (down)] org-metadown)
8121 '([?\e (left)] org-metaleft)
8122 '([?\e (right)] org-metaright)
8123 '([?\e (shift up)] org-shiftmetaup)
8124 '([?\e (shift down)] org-shiftmetadown)
8125 '([?\e (shift left)] org-shiftmetaleft)
8126 '([?\e (shift right)] org-shiftmetaright)
8127 '([(shift up)] org-shiftup)
8128 '([(shift down)] org-shiftdown)
8129 '([(shift left)] org-shiftleft)
8130 '([(shift right)] org-shiftright)
8131 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8132 '("\M-q" fill-paragraph)
8133 '("\C-c^" org-sort)
8134 '("\C-c-" org-cycle-list-bullet)))
8135 elt key fun cmd)
8136 (while (setq elt (pop bindings))
8137 (setq nfunc (1+ nfunc))
8138 (setq key (org-key (car elt))
8139 fun (nth 1 elt)
8140 cmd (orgstruct-make-binding fun nfunc key))
8141 (org-defkey orgstruct-mode-map key cmd))
8143 ;; Special treatment needed for TAB and RET
8144 (org-defkey orgstruct-mode-map [(tab)]
8145 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8146 (org-defkey orgstruct-mode-map "\C-i"
8147 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8149 (org-defkey orgstruct-mode-map "\M-\C-m"
8150 (orgstruct-make-binding 'org-insert-heading 105
8151 "\M-\C-m" [(meta return)]))
8152 (org-defkey orgstruct-mode-map [(meta return)]
8153 (orgstruct-make-binding 'org-insert-heading 106
8154 [(meta return)] "\M-\C-m"))
8156 (org-defkey orgstruct-mode-map [(shift meta return)]
8157 (orgstruct-make-binding 'org-insert-todo-heading 107
8158 [(meta return)] "\M-\C-m"))
8160 (org-defkey orgstruct-mode-map "\e\C-m"
8161 (orgstruct-make-binding 'org-insert-heading 108
8162 "\e\C-m" [?\e (return)]))
8163 (org-defkey orgstruct-mode-map [?\e (return)]
8164 (orgstruct-make-binding 'org-insert-heading 109
8165 [?\e (return)] "\e\C-m"))
8166 (org-defkey orgstruct-mode-map [?\e (shift return)]
8167 (orgstruct-make-binding 'org-insert-todo-heading 110
8168 [?\e (return)] "\e\C-m"))
8170 (unless org-local-vars
8171 (setq org-local-vars (org-get-local-variables)))
8175 (defun orgstruct-make-binding (fun n &rest keys)
8176 "Create a function for binding in the structure minor mode.
8177 FUN is the command to call inside a table. N is used to create a unique
8178 command name. KEYS are keys that should be checked in for a command
8179 to execute outside of tables."
8180 (eval
8181 (list 'defun
8182 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8183 '(arg)
8184 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8185 "Outside of structure, run the binding of `"
8186 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8187 "'.")
8188 '(interactive "p")
8189 (list 'if
8190 `(org-context-p 'headline 'item
8191 (and orgstruct-is-++
8192 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8193 'item-body))
8194 (list 'org-run-like-in-org-mode (list 'quote fun))
8195 (list 'let '(orgstruct-mode)
8196 (list 'call-interactively
8197 (append '(or)
8198 (mapcar (lambda (k)
8199 (list 'key-binding k))
8200 keys)
8201 '('orgstruct-error))))))))
8203 (defun org-context-p (&rest contexts)
8204 "Check if local context is any of CONTEXTS.
8205 Possible values in the list of contexts are `table', `headline', and `item'."
8206 (let ((pos (point)))
8207 (goto-char (point-at-bol))
8208 (prog1 (or (and (memq 'table contexts)
8209 (looking-at "[ \t]*|"))
8210 (and (memq 'headline contexts)
8211 ;;????????? (looking-at "\\*+"))
8212 (looking-at outline-regexp))
8213 (and (memq 'item contexts)
8214 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8215 (and (memq 'item-body contexts)
8216 (org-in-item-p)))
8217 (goto-char pos))))
8219 (defun org-get-local-variables ()
8220 "Return a list of all local variables in an org-mode buffer."
8221 (let (varlist)
8222 (with-current-buffer (get-buffer-create "*Org tmp*")
8223 (erase-buffer)
8224 (org-mode)
8225 (setq varlist (buffer-local-variables)))
8226 (kill-buffer "*Org tmp*")
8227 (delq nil
8228 (mapcar
8229 (lambda (x)
8230 (setq x
8231 (if (symbolp x)
8232 (list x)
8233 (list (car x) (list 'quote (cdr x)))))
8234 (if (string-match
8235 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8236 (symbol-name (car x)))
8237 x nil))
8238 varlist))))
8240 (defun org-clone-local-variables (from-buffer &optional regexp)
8241 "Clone local variables from FROM-BUFFER.
8242 Optional argument REGEXP selects variables to clone."
8243 (mapc
8244 (lambda (pair)
8245 (and (symbolp (car pair))
8246 (or (null regexp)
8247 (string-match regexp (symbol-name (car pair))))
8248 (set (make-local-variable (car pair))
8249 (cdr pair))))
8250 (buffer-local-variables from-buffer)))
8252 ;;;###autoload
8253 (defun org-run-like-in-org-mode (cmd)
8254 "Run a command, pretending that the current buffer is in Org-mode.
8255 This will temporarily bind local variables that are typically bound in
8256 Org-mode to the values they have in Org-mode, and then interactively
8257 call CMD."
8258 (org-load-modules-maybe)
8259 (unless org-local-vars
8260 (setq org-local-vars (org-get-local-variables)))
8261 (eval (list 'let org-local-vars
8262 (list 'call-interactively (list 'quote cmd)))))
8264 ;;;; Archiving
8266 (defun org-get-category (&optional pos force-refresh)
8267 "Get the category applying to position POS."
8268 (if force-refresh (org-refresh-category-properties))
8269 (let ((pos (or pos (point))))
8270 (or (get-text-property pos 'org-category)
8271 (progn (org-refresh-category-properties)
8272 (get-text-property pos 'org-category)))))
8274 (defun org-refresh-category-properties ()
8275 "Refresh category text properties in the buffer."
8276 (let ((def-cat (cond
8277 ((null org-category)
8278 (if buffer-file-name
8279 (file-name-sans-extension
8280 (file-name-nondirectory buffer-file-name))
8281 "???"))
8282 ((symbolp org-category) (symbol-name org-category))
8283 (t org-category)))
8284 beg end cat pos optionp)
8285 (org-unmodified
8286 (save-excursion
8287 (save-restriction
8288 (widen)
8289 (goto-char (point-min))
8290 (put-text-property (point) (point-max) 'org-category def-cat)
8291 (while (re-search-forward
8292 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8293 (setq pos (match-end 0)
8294 optionp (equal (char-after (match-beginning 0)) ?#)
8295 cat (org-trim (match-string 2)))
8296 (if optionp
8297 (setq beg (point-at-bol) end (point-max))
8298 (org-back-to-heading t)
8299 (setq beg (point) end (org-end-of-subtree t t)))
8300 (put-text-property beg end 'org-category cat)
8301 (goto-char pos)))))))
8304 ;;;; Link Stuff
8306 ;;; Link abbreviations
8308 (defun org-link-expand-abbrev (link)
8309 "Apply replacements as defined in `org-link-abbrev-alist."
8310 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8311 (let* ((key (match-string 1 link))
8312 (as (or (assoc key org-link-abbrev-alist-local)
8313 (assoc key org-link-abbrev-alist)))
8314 (tag (and (match-end 2) (match-string 3 link)))
8315 rpl)
8316 (if (not as)
8317 link
8318 (setq rpl (cdr as))
8319 (cond
8320 ((symbolp rpl) (funcall rpl tag))
8321 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8322 ((string-match "%h" rpl)
8323 (replace-match (url-hexify-string (or tag "")) t t rpl))
8324 (t (concat rpl tag)))))
8325 link))
8327 ;;; Storing and inserting links
8329 (defvar org-insert-link-history nil
8330 "Minibuffer history for links inserted with `org-insert-link'.")
8332 (defvar org-stored-links nil
8333 "Contains the links stored with `org-store-link'.")
8335 (defvar org-store-link-plist nil
8336 "Plist with info about the most recently link created with `org-store-link'.")
8338 (defvar org-link-protocols nil
8339 "Link protocols added to Org-mode using `org-add-link-type'.")
8341 (defvar org-store-link-functions nil
8342 "List of functions that are called to create and store a link.
8343 Each function will be called in turn until one returns a non-nil
8344 value. Each function should check if it is responsible for creating
8345 this link (for example by looking at the major mode).
8346 If not, it must exit and return nil.
8347 If yes, it should return a non-nil value after a calling
8348 `org-store-link-props' with a list of properties and values.
8349 Special properties are:
8351 :type The link prefix, like \"http\". This must be given.
8352 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8353 This is obligatory as well.
8354 :description Optional default description for the second pair
8355 of brackets in an Org-mode link. The user can still change
8356 this when inserting this link into an Org-mode buffer.
8358 In addition to these, any additional properties can be specified
8359 and then used in remember templates.")
8361 (defun org-add-link-type (type &optional follow export)
8362 "Add TYPE to the list of `org-link-types'.
8363 Re-compute all regular expressions depending on `org-link-types'
8365 FOLLOW and EXPORT are two functions.
8367 FOLLOW should take the link path as the single argument and do whatever
8368 is necessary to follow the link, for example find a file or display
8369 a mail message.
8371 EXPORT should format the link path for export to one of the export formats.
8372 It should be a function accepting three arguments:
8374 path the path of the link, the text after the prefix (like \"http:\")
8375 desc the description of the link, if any, or a description added by
8376 org-export-normalize-links if there is none
8377 format the export format, a symbol like `html' or `latex' or `ascii'..
8379 The function may use the FORMAT information to return different values
8380 depending on the format. The return value will be put literally into
8381 the exported file. If the return value is nil, this means Org should
8382 do what it normally does with links which do not have EXPORT defined.
8384 Org-mode has a built-in default for exporting links. If you are happy with
8385 this default, there is no need to define an export function for the link
8386 type. For a simple example of an export function, see `org-bbdb.el'."
8387 (add-to-list 'org-link-types type t)
8388 (org-make-link-regexps)
8389 (if (assoc type org-link-protocols)
8390 (setcdr (assoc type org-link-protocols) (list follow export))
8391 (push (list type follow export) org-link-protocols)))
8393 (defvar org-agenda-buffer-name)
8395 ;;;###autoload
8396 (defun org-store-link (arg)
8397 "\\<org-mode-map>Store an org-link to the current location.
8398 This link is added to `org-stored-links' and can later be inserted
8399 into an org-buffer with \\[org-insert-link].
8401 For some link types, a prefix arg is interpreted:
8402 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8403 For file links, arg negates `org-context-in-file-links'."
8404 (interactive "P")
8405 (org-load-modules-maybe)
8406 (setq org-store-link-plist nil) ; reset
8407 (org-with-limited-levels
8408 (let (link cpltxt desc description search txt custom-id agenda-link)
8409 (cond
8411 ((run-hook-with-args-until-success 'org-store-link-functions)
8412 (setq link (plist-get org-store-link-plist :link)
8413 desc (or (plist-get org-store-link-plist :description) link)))
8415 ((equal (buffer-name) "*Org Edit Src Example*")
8416 (let (label gc)
8417 (while (or (not label)
8418 (save-excursion
8419 (save-restriction
8420 (widen)
8421 (goto-char (point-min))
8422 (re-search-forward
8423 (regexp-quote (format org-coderef-label-format label))
8424 nil t))))
8425 (when label (message "Label exists already") (sit-for 2))
8426 (setq label (read-string "Code line label: " label)))
8427 (end-of-line 1)
8428 (setq link (format org-coderef-label-format label))
8429 (setq gc (- 79 (length link)))
8430 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8431 (insert link)
8432 (setq link (concat "(" label ")") desc nil)))
8434 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8435 ;; We are in the agenda, link to referenced location
8436 (let ((m (or (get-text-property (point) 'org-hd-marker)
8437 (get-text-property (point) 'org-marker))))
8438 (when m
8439 (org-with-point-at m
8440 (setq agenda-link
8441 (if (interactive-p)
8442 (call-interactively 'org-store-link)
8443 (org-store-link nil)))))))
8445 ((eq major-mode 'calendar-mode)
8446 (let ((cd (calendar-cursor-to-date)))
8447 (setq link
8448 (format-time-string
8449 (car org-time-stamp-formats)
8450 (apply 'encode-time
8451 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8452 nil nil nil))))
8453 (org-store-link-props :type "calendar" :date cd)))
8455 ((eq major-mode 'w3-mode)
8456 (setq cpltxt (if (and (buffer-name)
8457 (not (string-match "Untitled" (buffer-name))))
8458 (buffer-name)
8459 (url-view-url t))
8460 link (org-make-link (url-view-url t)))
8461 (org-store-link-props :type "w3" :url (url-view-url t)))
8463 ((eq major-mode 'w3m-mode)
8464 (setq cpltxt (or w3m-current-title w3m-current-url)
8465 link (org-make-link w3m-current-url))
8466 (org-store-link-props :type "w3m" :url (url-view-url t)))
8468 ((setq search (run-hook-with-args-until-success
8469 'org-create-file-search-functions))
8470 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8471 "::" search))
8472 (setq cpltxt (or description link)))
8474 ((eq major-mode 'image-mode)
8475 (setq cpltxt (concat "file:"
8476 (abbreviate-file-name buffer-file-name))
8477 link (org-make-link cpltxt))
8478 (org-store-link-props :type "image" :file buffer-file-name))
8480 ((eq major-mode 'dired-mode)
8481 ;; link to the file in the current line
8482 (let ((file (dired-get-filename nil t)))
8483 (setq file (if file
8484 (abbreviate-file-name
8485 (expand-file-name (dired-get-filename nil t)))
8486 ;; otherwise, no file so use current directory.
8487 default-directory))
8488 (setq cpltxt (concat "file:" file)
8489 link (org-make-link cpltxt))))
8491 ((and (buffer-file-name (buffer-base-buffer)) (org-mode-p))
8492 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8493 (cond
8494 ((org-in-regexp "<<\\(.*?\\)>>")
8495 (setq cpltxt
8496 (concat "file:"
8497 (abbreviate-file-name
8498 (buffer-file-name (buffer-base-buffer)))
8499 "::" (match-string 1))
8500 link (org-make-link cpltxt)))
8501 ((and (featurep 'org-id)
8502 (or (eq org-link-to-org-use-id t)
8503 (and (eq org-link-to-org-use-id 'create-if-interactive)
8504 (interactive-p))
8505 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
8506 (interactive-p)
8507 (not custom-id))
8508 (and org-link-to-org-use-id
8509 (org-entry-get nil "ID"))))
8510 ;; We can make a link using the ID.
8511 (setq link (condition-case nil
8512 (prog1 (org-id-store-link)
8513 (setq desc (plist-get org-store-link-plist
8514 :description)))
8515 (error
8516 ;; probably before first headline, link to file only
8517 (concat "file:"
8518 (abbreviate-file-name
8519 (buffer-file-name (buffer-base-buffer))))))))
8521 ;; Just link to current headline
8522 (setq cpltxt (concat "file:"
8523 (abbreviate-file-name
8524 (buffer-file-name (buffer-base-buffer)))))
8525 ;; Add a context search string
8526 (when (org-xor org-context-in-file-links arg)
8527 (setq txt (cond
8528 ((org-on-heading-p) nil)
8529 ((org-region-active-p)
8530 (buffer-substring (region-beginning) (region-end)))
8531 (t nil)))
8532 (when (or (null txt) (string-match "\\S-" txt))
8533 (setq cpltxt
8534 (concat cpltxt "::"
8535 (condition-case nil
8536 (org-make-org-heading-search-string txt)
8537 (error "")))
8538 desc (or (nth 4 (ignore-errors
8539 (org-heading-components))) "NONE"))))
8540 (if (string-match "::\\'" cpltxt)
8541 (setq cpltxt (substring cpltxt 0 -2)))
8542 (setq link (org-make-link cpltxt)))))
8544 ((buffer-file-name (buffer-base-buffer))
8545 ;; Just link to this file here.
8546 (setq cpltxt (concat "file:"
8547 (abbreviate-file-name
8548 (buffer-file-name (buffer-base-buffer)))))
8549 ;; Add a context string
8550 (when (org-xor org-context-in-file-links arg)
8551 (setq txt (if (org-region-active-p)
8552 (buffer-substring (region-beginning) (region-end))
8553 (buffer-substring (point-at-bol) (point-at-eol))))
8554 ;; Only use search option if there is some text.
8555 (when (string-match "\\S-" txt)
8556 (setq cpltxt
8557 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8558 desc "NONE")))
8559 (setq link (org-make-link cpltxt)))
8561 ((interactive-p)
8562 (error "Cannot link to a buffer which is not visiting a file"))
8564 (t (setq link nil)))
8566 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8567 (setq link (or link cpltxt)
8568 desc (or desc cpltxt))
8569 (if (equal desc "NONE") (setq desc nil))
8571 (if (and (or (interactive-p) executing-kbd-macro) link)
8572 (progn
8573 (setq org-stored-links
8574 (cons (list link desc) org-stored-links))
8575 (message "Stored: %s" (or desc link))
8576 (when custom-id
8577 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8578 "::#" custom-id))
8579 (setq org-stored-links
8580 (cons (list link desc) org-stored-links))))
8581 (or agenda-link (and link (org-make-link-string link desc)))))))
8583 (defun org-store-link-props (&rest plist)
8584 "Store link properties, extract names and addresses."
8585 (let (x adr)
8586 (when (setq x (plist-get plist :from))
8587 (setq adr (mail-extract-address-components x))
8588 (setq plist (plist-put plist :fromname (car adr)))
8589 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8590 (when (setq x (plist-get plist :to))
8591 (setq adr (mail-extract-address-components x))
8592 (setq plist (plist-put plist :toname (car adr)))
8593 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8594 (let ((from (plist-get plist :from))
8595 (to (plist-get plist :to)))
8596 (when (and from to org-from-is-user-regexp)
8597 (setq plist
8598 (plist-put plist :fromto
8599 (if (string-match org-from-is-user-regexp from)
8600 (concat "to %t")
8601 (concat "from %f"))))))
8602 (setq org-store-link-plist plist))
8604 (defun org-add-link-props (&rest plist)
8605 "Add these properties to the link property list."
8606 (let (key value)
8607 (while plist
8608 (setq key (pop plist) value (pop plist))
8609 (setq org-store-link-plist
8610 (plist-put org-store-link-plist key value)))))
8612 (defun org-email-link-description (&optional fmt)
8613 "Return the description part of an email link.
8614 This takes information from `org-store-link-plist' and formats it
8615 according to FMT (default from `org-email-link-description-format')."
8616 (setq fmt (or fmt org-email-link-description-format))
8617 (let* ((p org-store-link-plist)
8618 (to (plist-get p :toaddress))
8619 (from (plist-get p :fromaddress))
8620 (table
8621 (list
8622 (cons "%c" (plist-get p :fromto))
8623 (cons "%F" (plist-get p :from))
8624 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8625 (cons "%T" (plist-get p :to))
8626 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8627 (cons "%s" (plist-get p :subject))
8628 (cons "%d" (plist-get p :date))
8629 (cons "%m" (plist-get p :message-id)))))
8630 (when (string-match "%c" fmt)
8631 ;; Check if the user wrote this message
8632 (if (and org-from-is-user-regexp from to
8633 (save-match-data (string-match org-from-is-user-regexp from)))
8634 (setq fmt (replace-match "to %t" t t fmt))
8635 (setq fmt (replace-match "from %f" t t fmt))))
8636 (org-replace-escapes fmt table)))
8638 (defun org-make-org-heading-search-string (&optional string heading)
8639 "Make search string for STRING or current headline."
8640 (interactive)
8641 (let ((s (or string (org-get-heading)))
8642 (lines org-context-in-file-links))
8643 (unless (and string (not heading))
8644 ;; We are using a headline, clean up garbage in there.
8645 (if (string-match org-todo-regexp s)
8646 (setq s (replace-match "" t t s)))
8647 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8648 (setq s (replace-match "" t t s)))
8649 (setq s (org-trim s))
8650 (if (string-match (concat "^\\(" org-quote-string "\\|"
8651 org-comment-string "\\)") s)
8652 (setq s (replace-match "" t t s)))
8653 (while (string-match org-ts-regexp s)
8654 (setq s (replace-match "" t t s))))
8655 (or string (setq s (concat "*" s))) ; Add * for headlines
8656 (when (and string (integerp lines) (> lines 0))
8657 (let ((slines (org-split-string s "\n")))
8658 (when (< lines (length slines))
8659 (setq s (mapconcat
8660 'identity
8661 (reverse (nthcdr (- (length slines) lines)
8662 (reverse slines))) "\n")))))
8663 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8665 (defun org-make-link (&rest strings)
8666 "Concatenate STRINGS."
8667 (apply 'concat strings))
8669 (defun org-make-link-string (link &optional description)
8670 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8671 (unless (string-match "\\S-" link)
8672 (error "Empty link"))
8673 (when (and description
8674 (stringp description)
8675 (not (string-match "\\S-" description)))
8676 (setq description nil))
8677 (when (stringp description)
8678 ;; Remove brackets from the description, they are fatal.
8679 (while (string-match "\\[" description)
8680 (setq description (replace-match "{" t t description)))
8681 (while (string-match "\\]" description)
8682 (setq description (replace-match "}" t t description))))
8683 (when (equal (org-link-escape link) description)
8684 ;; No description needed, it is identical
8685 (setq description nil))
8686 (when (and (not description)
8687 (not (equal link (org-link-escape link))))
8688 (setq description (org-extract-attributes link)))
8689 (setq link (if (string-match org-link-types-re link)
8690 (concat (match-string 1 link)
8691 (org-link-escape (substring link (match-end 1))))
8692 (org-link-escape link)))
8693 (concat "[[" link "]"
8694 (if description (concat "[" description "]") "")
8695 "]"))
8697 (defconst org-link-escape-chars
8698 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8699 "List of characters that should be escaped in link.
8700 This is the list that is used for internal purposes.")
8702 (defvar org-url-encoding-use-url-hexify nil)
8704 (defconst org-link-escape-chars-browser
8705 '(?\ )
8706 "List of escapes for characters that are problematic in links.
8707 This is the list that is used before handing over to the browser.")
8709 (defun org-link-escape (text &optional table merge)
8710 "Return percent escaped representation of TEXT.
8711 TEXT is a string with the text to escape.
8712 Optional argument TABLE is a list with characters that should be
8713 escaped. When nil, `org-link-escape-chars' is used.
8714 If optional argument MERGE is set, merge TABLE into
8715 `org-link-escape-chars'."
8716 (if (and org-url-encoding-use-url-hexify (not table))
8717 (url-hexify-string text)
8718 (cond
8719 ((and table merge)
8720 (mapc (lambda (defchr)
8721 (unless (member defchr table)
8722 (setq table (cons defchr table)))) org-link-escape-chars))
8723 ((null table)
8724 (setq table org-link-escape-chars)))
8725 (mapconcat
8726 (lambda (char)
8727 (if (or (member char table)
8728 (< char 32) (= char 37) (> char 126))
8729 (mapconcat (lambda (sequence-element)
8730 (format "%%%.2X" sequence-element))
8731 (or (encode-coding-char char 'utf-8)
8732 (error "Unable to percent escape character: %s"
8733 (char-to-string char))) "")
8734 (char-to-string char))) text "")))
8736 (defun org-link-unescape (str)
8737 "Unhex hexified unicode strings as returned from the JavaScript function
8738 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
8739 (unless (and (null str) (string= "" str))
8740 (let ((pos 0) (case-fold-search t) unhexed)
8741 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
8742 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
8743 (setq str (replace-match unhexed t t str))
8744 (setq pos (+ pos (length unhexed))))))
8745 str)
8747 (defun org-link-unescape-compound (hex)
8748 "Unhexify unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
8749 Note: this function also decodes single byte encodings like
8750 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
8751 (save-match-data
8752 (let* ((bytes (cdr (split-string hex "%")))
8753 (ret "")
8754 (eat 0)
8755 (sum 0))
8756 (while bytes
8757 (let* ((val (string-to-number (pop bytes) 16))
8758 (shift-xor
8759 (if (= 0 eat)
8760 (cond
8761 ((>= val 252) (cons 6 252))
8762 ((>= val 248) (cons 5 248))
8763 ((>= val 240) (cons 4 240))
8764 ((>= val 224) (cons 3 224))
8765 ((>= val 192) (cons 2 192))
8766 (t (cons 0 0)))
8767 (cons 6 128))))
8768 (if (>= val 192) (setq eat (car shift-xor)))
8769 (setq val (logxor val (cdr shift-xor)))
8770 (setq sum (+ (lsh sum (car shift-xor)) val))
8771 (if (> eat 0) (setq eat (- eat 1)))
8772 (cond
8773 ((= 0 eat) ;multi byte
8774 (setq ret (concat ret (org-char-to-string sum)))
8775 (setq sum 0))
8776 ((not bytes) ; single byte(s)
8777 (setq ret (org-link-unescape-single-byte-sequence hex))))
8778 )) ;; end (while bytes
8779 ret )))
8781 (defun org-link-unescape-single-byte-sequence (hex)
8782 "Unhexify hex-encoded single byte character sequences."
8783 (mapconcat (lambda (byte)
8784 (char-to-string (string-to-number byte 16)))
8785 (cdr (split-string hex "%")) ""))
8787 (defun org-xor (a b)
8788 "Exclusive or."
8789 (if a (not b) b))
8791 (defun org-fixup-message-id-for-http (s)
8792 "Replace special characters in a message id, so it can be used in an http query."
8793 (when (string-match "%" s)
8794 (setq s (mapconcat (lambda (c)
8795 (if (eq c ?%)
8796 "%25"
8797 (char-to-string c)))
8798 s "")))
8799 (while (string-match "<" s)
8800 (setq s (replace-match "%3C" t t s)))
8801 (while (string-match ">" s)
8802 (setq s (replace-match "%3E" t t s)))
8803 (while (string-match "@" s)
8804 (setq s (replace-match "%40" t t s)))
8807 ;;;###autoload
8808 (defun org-insert-link-global ()
8809 "Insert a link like Org-mode does.
8810 This command can be called in any mode to insert a link in Org-mode syntax."
8811 (interactive)
8812 (org-load-modules-maybe)
8813 (org-run-like-in-org-mode 'org-insert-link))
8815 (defun org-insert-link (&optional complete-file link-location)
8816 "Insert a link. At the prompt, enter the link.
8818 Completion can be used to insert any of the link protocol prefixes like
8819 http or ftp in use.
8821 The history can be used to select a link previously stored with
8822 `org-store-link'. When the empty string is entered (i.e. if you just
8823 press RET at the prompt), the link defaults to the most recently
8824 stored link. As SPC triggers completion in the minibuffer, you need to
8825 use M-SPC or C-q SPC to force the insertion of a space character.
8827 You will also be prompted for a description, and if one is given, it will
8828 be displayed in the buffer instead of the link.
8830 If there is already a link at point, this command will allow you to edit link
8831 and description parts.
8833 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8834 be selected using completion. The path to the file will be relative to the
8835 current directory if the file is in the current directory or a subdirectory.
8836 Otherwise, the link will be the absolute path as completed in the minibuffer
8837 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8838 option `org-link-file-path-type'.
8840 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8841 the current directory or below.
8843 With three \\[universal-argument] prefixes, negate the meaning of
8844 `org-keep-stored-link-after-insertion'.
8846 If `org-make-link-description-function' is non-nil, this function will be
8847 called with the link target, and the result will be the default
8848 link description.
8850 If the LINK-LOCATION parameter is non-nil, this value will be
8851 used as the link location instead of reading one interactively."
8852 (interactive "P")
8853 (let* ((wcf (current-window-configuration))
8854 (region (if (org-region-active-p)
8855 (buffer-substring (region-beginning) (region-end))))
8856 (remove (and region (list (region-beginning) (region-end))))
8857 (desc region)
8858 tmphist ; byte-compile incorrectly complains about this
8859 (link link-location)
8860 entry file all-prefixes)
8861 (cond
8862 (link-location) ; specified by arg, just use it.
8863 ((org-in-regexp org-bracket-link-regexp 1)
8864 ;; We do have a link at point, and we are going to edit it.
8865 (setq remove (list (match-beginning 0) (match-end 0)))
8866 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8867 (setq link (read-string "Link: "
8868 (org-link-unescape
8869 (org-match-string-no-properties 1)))))
8870 ((or (org-in-regexp org-angle-link-re)
8871 (org-in-regexp org-plain-link-re))
8872 ;; Convert to bracket link
8873 (setq remove (list (match-beginning 0) (match-end 0))
8874 link (read-string "Link: "
8875 (org-remove-angle-brackets (match-string 0)))))
8876 ((member complete-file '((4) (16)))
8877 ;; Completing read for file names.
8878 (setq link (org-file-complete-link complete-file)))
8880 ;; Read link, with completion for stored links.
8881 (with-output-to-temp-buffer "*Org Links*"
8882 (princ "Insert a link.
8883 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8884 (when org-stored-links
8885 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8886 (princ (mapconcat
8887 (lambda (x)
8888 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8889 (reverse org-stored-links) "\n"))))
8890 (let ((cw (selected-window)))
8891 (select-window (get-buffer-window "*Org Links*" 'visible))
8892 (with-current-buffer "*Org Links*" (setq truncate-lines) t)
8893 (unless (pos-visible-in-window-p (point-max))
8894 (org-fit-window-to-buffer))
8895 (and (window-live-p cw) (select-window cw)))
8896 ;; Fake a link history, containing the stored links.
8897 (setq tmphist (append (mapcar 'car org-stored-links)
8898 org-insert-link-history))
8899 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8900 (mapcar 'car org-link-abbrev-alist)
8901 org-link-types))
8902 (unwind-protect
8903 (progn
8904 (setq link
8905 (let ((org-completion-use-ido nil)
8906 (org-completion-use-iswitchb nil))
8907 (org-completing-read
8908 "Link: "
8909 (append
8910 (mapcar (lambda (x) (list (concat x ":")))
8911 all-prefixes)
8912 (mapcar 'car org-stored-links))
8913 nil nil nil
8914 'tmphist
8915 (car (car org-stored-links)))))
8916 (if (not (string-match "\\S-" link))
8917 (error "No link selected"))
8918 (if (or (member link all-prefixes)
8919 (and (equal ":" (substring link -1))
8920 (member (substring link 0 -1) all-prefixes)
8921 (setq link (substring link 0 -1))))
8922 (setq link (org-link-try-special-completion link))))
8923 (set-window-configuration wcf)
8924 (kill-buffer "*Org Links*"))
8925 (setq entry (assoc link org-stored-links))
8926 (or entry (push link org-insert-link-history))
8927 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8928 (not org-keep-stored-link-after-insertion))
8929 (setq org-stored-links (delq (assoc link org-stored-links)
8930 org-stored-links)))
8931 (setq desc (or desc (nth 1 entry)))))
8933 (if (string-match org-plain-link-re link)
8934 ;; URL-like link, normalize the use of angular brackets.
8935 (setq link (org-make-link (org-remove-angle-brackets link))))
8937 ;; Check if we are linking to the current file with a search option
8938 ;; If yes, simplify the link by using only the search option.
8939 (when (and buffer-file-name
8940 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8941 (let* ((path (match-string 1 link))
8942 (case-fold-search nil)
8943 (search (match-string 2 link)))
8944 (save-match-data
8945 (if (equal (file-truename buffer-file-name) (file-truename path))
8946 ;; We are linking to this same file, with a search option
8947 (setq link search)))))
8949 ;; Check if we can/should use a relative path. If yes, simplify the link
8950 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8951 (let* ((type (match-string 1 link))
8952 (path (match-string 2 link))
8953 (origpath path)
8954 (case-fold-search nil))
8955 (cond
8956 ((or (eq org-link-file-path-type 'absolute)
8957 (equal complete-file '(16)))
8958 (setq path (abbreviate-file-name (expand-file-name path))))
8959 ((eq org-link-file-path-type 'noabbrev)
8960 (setq path (expand-file-name path)))
8961 ((eq org-link-file-path-type 'relative)
8962 (setq path (file-relative-name path)))
8964 (save-match-data
8965 (if (string-match (concat "^" (regexp-quote
8966 (expand-file-name
8967 (file-name-as-directory
8968 default-directory))))
8969 (expand-file-name path))
8970 ;; We are linking a file with relative path name.
8971 (setq path (substring (expand-file-name path)
8972 (match-end 0)))
8973 (setq path (abbreviate-file-name (expand-file-name path)))))))
8974 (setq link (concat type path))
8975 (if (equal desc origpath)
8976 (setq desc path))))
8978 (if org-make-link-description-function
8979 (setq desc (funcall org-make-link-description-function link desc)))
8981 (setq desc (read-string "Description: " desc))
8982 (unless (string-match "\\S-" desc) (setq desc nil))
8983 (if remove (apply 'delete-region remove))
8984 (insert (org-make-link-string link desc))))
8986 (defun org-link-try-special-completion (type)
8987 "If there is completion support for link type TYPE, offer it."
8988 (let ((fun (intern (concat "org-" type "-complete-link"))))
8989 (if (functionp fun)
8990 (funcall fun)
8991 (read-string "Link (no completion support): " (concat type ":")))))
8993 (defun org-file-complete-link (&optional arg)
8994 "Create a file link using completion."
8995 (let (file link)
8996 (setq file (read-file-name "File: "))
8997 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8998 (pwd1 (file-name-as-directory (abbreviate-file-name
8999 (expand-file-name ".")))))
9000 (cond
9001 ((equal arg '(16))
9002 (setq link (org-make-link
9003 "file:"
9004 (abbreviate-file-name (expand-file-name file)))))
9005 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9006 (setq link (org-make-link "file:" (match-string 1 file))))
9007 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9008 (expand-file-name file))
9009 (setq link (org-make-link
9010 "file:" (match-string 1 (expand-file-name file)))))
9011 (t (setq link (org-make-link "file:" file)))))
9012 link))
9014 (defun org-completing-read (&rest args)
9015 "Completing-read with SPACE being a normal character."
9016 (let ((minibuffer-local-completion-map
9017 (copy-keymap minibuffer-local-completion-map)))
9018 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9019 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9020 (apply 'org-icompleting-read args)))
9022 (defun org-completing-read-no-i (&rest args)
9023 (let (org-completion-use-ido org-completion-use-iswitchb)
9024 (apply 'org-completing-read args)))
9026 (defun org-iswitchb-completing-read (prompt choices &rest args)
9027 "Use iswitch as a completing-read replacement to choose from choices.
9028 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9029 from."
9030 (let* ((iswitchb-use-virtual-buffers nil)
9031 (iswitchb-make-buflist-hook
9032 (lambda ()
9033 (setq iswitchb-temp-buflist choices))))
9034 (iswitchb-read-buffer prompt)))
9036 (defun org-icompleting-read (&rest args)
9037 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9038 (org-without-partial-completion
9039 (if (and org-completion-use-ido
9040 (fboundp 'ido-completing-read)
9041 (boundp 'ido-mode) ido-mode
9042 (listp (second args)))
9043 (let ((ido-enter-matching-directory nil))
9044 (apply 'ido-completing-read (concat (car args))
9045 (if (consp (car (nth 1 args)))
9046 (mapcar 'car (nth 1 args))
9047 (nth 1 args))
9048 (cddr args)))
9049 (if (and org-completion-use-iswitchb
9050 (boundp 'iswitchb-mode) iswitchb-mode
9051 (listp (second args)))
9052 (apply 'org-iswitchb-completing-read (concat (car args))
9053 (if (consp (car (nth 1 args)))
9054 (mapcar 'car (nth 1 args))
9055 (nth 1 args))
9056 (cddr args))
9057 (apply 'completing-read args)))))
9059 (defun org-extract-attributes (s)
9060 "Extract the attributes cookie from a string and set as text property."
9061 (let (a attr (start 0) key value)
9062 (save-match-data
9063 (when (string-match "{{\\([^}]+\\)}}$" s)
9064 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9065 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9066 (setq key (match-string 1 a) value (match-string 2 a)
9067 start (match-end 0)
9068 attr (plist-put attr (intern key) value))))
9069 (org-add-props s nil 'org-attr attr))
9072 (defun org-extract-attributes-from-string (tag)
9073 (let (key value attr)
9074 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9075 (setq key (match-string 1 tag) value (match-string 2 tag)
9076 tag (replace-match "" t t tag)
9077 attr (plist-put attr (intern key) value)))
9078 (cons tag attr)))
9080 (defun org-attributes-to-string (plist)
9081 "Format a property list into an HTML attribute list."
9082 (let ((s "") key value)
9083 (while plist
9084 (setq key (pop plist) value (pop plist))
9085 (and value
9086 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9089 ;;; Opening/following a link
9091 (defvar org-link-search-failed nil)
9093 (defvar org-open-link-functions nil
9094 "Hook for functions finding a plain text link.
9095 These functions must take a single argument, the link content.
9096 They will be called for links that look like [[link text][description]]
9097 when LINK TEXT does not have a protocol like \"http:\" and does not look
9098 like a filename (e.g. \"./blue.png\").
9100 These functions will be called *before* Org attempts to resolve the
9101 link by doing text searches in the current buffer - so if you want a
9102 link \"[[target]]\" to still find \"<<target>>\", your function should
9103 handle this as a special case.
9105 When the function does handle the link, it must return a non-nil value.
9106 If it decides that it is not responsible for this link, it must return
9107 nil to indicate that that Org-mode can continue with other options
9108 like exact and fuzzy text search.")
9110 (defun org-next-link ()
9111 "Move forward to the next link.
9112 If the link is in hidden text, expose it."
9113 (interactive)
9114 (when (and org-link-search-failed (eq this-command last-command))
9115 (goto-char (point-min))
9116 (message "Link search wrapped back to beginning of buffer"))
9117 (setq org-link-search-failed nil)
9118 (let* ((pos (point))
9119 (ct (org-context))
9120 (a (assoc :link ct)))
9121 (if a (goto-char (nth 2 a)))
9122 (if (re-search-forward org-any-link-re nil t)
9123 (progn
9124 (goto-char (match-beginning 0))
9125 (if (outline-invisible-p) (org-show-context)))
9126 (goto-char pos)
9127 (setq org-link-search-failed t)
9128 (error "No further link found"))))
9130 (defun org-previous-link ()
9131 "Move backward to the previous link.
9132 If the link is in hidden text, expose it."
9133 (interactive)
9134 (when (and org-link-search-failed (eq this-command last-command))
9135 (goto-char (point-max))
9136 (message "Link search wrapped back to end of buffer"))
9137 (setq org-link-search-failed nil)
9138 (let* ((pos (point))
9139 (ct (org-context))
9140 (a (assoc :link ct)))
9141 (if a (goto-char (nth 1 a)))
9142 (if (re-search-backward org-any-link-re nil t)
9143 (progn
9144 (goto-char (match-beginning 0))
9145 (if (outline-invisible-p) (org-show-context)))
9146 (goto-char pos)
9147 (setq org-link-search-failed t)
9148 (error "No further link found"))))
9150 (defun org-translate-link (s)
9151 "Translate a link string if a translation function has been defined."
9152 (if (and org-link-translation-function
9153 (fboundp org-link-translation-function)
9154 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9155 (progn
9156 (setq s (funcall org-link-translation-function
9157 (match-string 1) (match-string 2)))
9158 (concat (car s) ":" (cdr s)))
9161 (defun org-translate-link-from-planner (type path)
9162 "Translate a link from Emacs Planner syntax so that Org can follow it.
9163 This is still an experimental function, your mileage may vary."
9164 (cond
9165 ((member type '("http" "https" "news" "ftp"))
9166 ;; standard Internet links are the same.
9167 nil)
9168 ((and (equal type "irc") (string-match "^//" path))
9169 ;; Planner has two / at the beginning of an irc link, we have 1.
9170 ;; We should have zero, actually....
9171 (setq path (substring path 1)))
9172 ((and (equal type "lisp") (string-match "^/" path))
9173 ;; Planner has a slash, we do not.
9174 (setq type "elisp" path (substring path 1)))
9175 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9176 ;; A typical message link. Planner has the id after the final slash,
9177 ;; we separate it with a hash mark
9178 (setq path (concat (match-string 1 path) "#"
9179 (org-remove-angle-brackets (match-string 2 path)))))
9181 (cons type path))
9183 (defun org-find-file-at-mouse (ev)
9184 "Open file link or URL at mouse."
9185 (interactive "e")
9186 (mouse-set-point ev)
9187 (org-open-at-point 'in-emacs))
9189 (defun org-open-at-mouse (ev)
9190 "Open file link or URL at mouse."
9191 (interactive "e")
9192 (mouse-set-point ev)
9193 (if (eq major-mode 'org-agenda-mode)
9194 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9195 (org-open-at-point))
9197 (defvar org-window-config-before-follow-link nil
9198 "The window configuration before following a link.
9199 This is saved in case the need arises to restore it.")
9201 (defvar org-open-link-marker (make-marker)
9202 "Marker pointing to the location where `org-open-at-point; was called.")
9204 ;;;###autoload
9205 (defun org-open-at-point-global ()
9206 "Follow a link like Org-mode does.
9207 This command can be called in any mode to follow a link that has
9208 Org-mode syntax."
9209 (interactive)
9210 (org-run-like-in-org-mode 'org-open-at-point))
9212 ;;;###autoload
9213 (defun org-open-link-from-string (s &optional arg reference-buffer)
9214 "Open a link in the string S, as if it was in Org-mode."
9215 (interactive "sLink: \nP")
9216 (let ((reference-buffer (or reference-buffer (current-buffer))))
9217 (with-temp-buffer
9218 (let ((org-inhibit-startup t))
9219 (org-mode)
9220 (insert s)
9221 (goto-char (point-min))
9222 (when reference-buffer
9223 (setq org-link-abbrev-alist-local
9224 (with-current-buffer reference-buffer
9225 org-link-abbrev-alist-local)))
9226 (org-open-at-point arg reference-buffer)))))
9228 (defvar org-open-at-point-functions nil
9229 "Hook that is run when following a link at point.
9231 Functions in this hook must return t if they identify and follow
9232 a link at point. If they don't find anything interesting at point,
9233 they must return nil.")
9235 (defun org-open-at-point (&optional arg reference-buffer)
9236 "Open link at or after point.
9237 If there is no link at point, this function will search forward up to
9238 the end of the current line.
9239 Normally, files will be opened by an appropriate application. If the
9240 optional prefix argument ARG is non-nil, Emacs will visit the file.
9241 With a double prefix argument, try to open outside of Emacs, in the
9242 application the system uses for this file type."
9243 (interactive "P")
9244 ;; if in a code block, then open the block's results
9245 (unless (call-interactively #'org-babel-open-src-block-result)
9246 (org-load-modules-maybe)
9247 (move-marker org-open-link-marker (point))
9248 (setq org-window-config-before-follow-link (current-window-configuration))
9249 (org-remove-occur-highlights nil nil t)
9250 (cond
9251 ((and (org-on-heading-p)
9252 (not (org-in-regexp
9253 (concat org-plain-link-re "\\|"
9254 org-bracket-link-regexp "\\|"
9255 org-angle-link-re "\\|"
9256 "[ \t]:[^ \t\n]+:[ \t]*$")))
9257 (not (get-text-property (point) 'org-linked-text)))
9258 (or (org-offer-links-in-entry arg)
9259 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9260 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9261 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9262 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9263 (not (org-in-regexp org-bracket-link-regexp)))
9264 (org-footnote-action))
9266 (let (type path link line search (pos (point)))
9267 (catch 'match
9268 (save-excursion
9269 (skip-chars-forward "^]\n\r")
9270 (when (org-in-regexp org-bracket-link-regexp 1)
9271 (setq link (org-extract-attributes
9272 (org-link-unescape (org-match-string-no-properties 1))))
9273 (while (string-match " *\n *" link)
9274 (setq link (replace-match " " t t link)))
9275 (setq link (org-link-expand-abbrev link))
9276 (cond
9277 ((or (file-name-absolute-p link)
9278 (string-match "^\\.\\.?/" link))
9279 (setq type "file" path link))
9280 ((string-match org-link-re-with-space3 link)
9281 (setq type (match-string 1 link) path (match-string 2 link)))
9282 (t (setq type "thisfile" path link)))
9283 (throw 'match t)))
9285 (when (get-text-property (point) 'org-linked-text)
9286 (setq type "thisfile"
9287 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9288 (1+ (point)) (point))
9289 path (buffer-substring
9290 (or (previous-single-property-change pos 'org-linked-text)
9291 (point-min))
9292 (or (next-single-property-change pos 'org-linked-text)
9293 (point-max))))
9294 (throw 'match t))
9296 (save-excursion
9297 (when (or (org-in-regexp org-angle-link-re)
9298 (org-in-regexp org-plain-link-re))
9299 (setq type (match-string 1) path (match-string 2))
9300 (throw 'match t)))
9301 (save-excursion
9302 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9303 (setq type "tags"
9304 path (match-string 1))
9305 (while (string-match ":" path)
9306 (setq path (replace-match "+" t t path)))
9307 (throw 'match t)))
9308 (when (org-in-regexp "<\\([^><\n]+\\)>")
9309 (setq type "tree-match"
9310 path (match-string 1))
9311 (throw 'match t)))
9312 (unless path
9313 (error "No link found"))
9315 ;; switch back to reference buffer
9316 ;; needed when if called in a temporary buffer through
9317 ;; org-open-link-from-string
9318 (with-current-buffer (or reference-buffer (current-buffer))
9320 ;; Remove any trailing spaces in path
9321 (if (string-match " +\\'" path)
9322 (setq path (replace-match "" t t path)))
9323 (if (and org-link-translation-function
9324 (fboundp org-link-translation-function))
9325 ;; Check if we need to translate the link
9326 (let ((tmp (funcall org-link-translation-function type path)))
9327 (setq type (car tmp) path (cdr tmp))))
9329 (cond
9331 ((assoc type org-link-protocols)
9332 (funcall (nth 1 (assoc type org-link-protocols)) path))
9334 ((equal type "mailto")
9335 (let ((cmd (car org-link-mailto-program))
9336 (args (cdr org-link-mailto-program)) args1
9337 (address path) (subject "") a)
9338 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9339 (setq address (match-string 1 path)
9340 subject (org-link-escape (match-string 2 path))))
9341 (while args
9342 (cond
9343 ((not (stringp (car args))) (push (pop args) args1))
9344 (t (setq a (pop args))
9345 (if (string-match "%a" a)
9346 (setq a (replace-match address t t a)))
9347 (if (string-match "%s" a)
9348 (setq a (replace-match subject t t a)))
9349 (push a args1))))
9350 (apply cmd (nreverse args1))))
9352 ((member type '("http" "https" "ftp" "news"))
9353 (browse-url (concat type ":" (org-link-escape
9354 path org-link-escape-chars-browser))))
9356 ((string= type "doi")
9357 (browse-url (concat "http://dx.doi.org/"
9358 (org-link-escape
9359 path org-link-escape-chars-browser))))
9361 ((member type '("message"))
9362 (browse-url (concat type ":" path)))
9364 ((string= type "tags")
9365 (org-tags-view arg path))
9367 ((string= type "tree-match")
9368 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9370 ((string= type "file")
9371 (if (string-match "::\\([0-9]+\\)\\'" path)
9372 (setq line (string-to-number (match-string 1 path))
9373 path (substring path 0 (match-beginning 0)))
9374 (if (string-match "::\\(.+\\)\\'" path)
9375 (setq search (match-string 1 path)
9376 path (substring path 0 (match-beginning 0)))))
9377 (if (string-match "[*?{]" (file-name-nondirectory path))
9378 (dired path)
9379 (org-open-file path arg line search)))
9381 ((string= type "shell")
9382 (let ((cmd path))
9383 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9384 (string-match org-confirm-shell-link-not-regexp cmd))
9385 (not org-confirm-shell-link-function)
9386 (funcall org-confirm-shell-link-function
9387 (format "Execute \"%s\" in shell? "
9388 (org-add-props cmd nil
9389 'face 'org-warning))))
9390 (progn
9391 (message "Executing %s" cmd)
9392 (shell-command cmd))
9393 (error "Abort"))))
9395 ((string= type "elisp")
9396 (let ((cmd path))
9397 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9398 (string-match org-confirm-elisp-link-not-regexp cmd))
9399 (not org-confirm-elisp-link-function)
9400 (funcall org-confirm-elisp-link-function
9401 (format "Execute \"%s\" as elisp? "
9402 (org-add-props cmd nil
9403 'face 'org-warning))))
9404 (message "%s => %s" cmd
9405 (if (equal (string-to-char cmd) ?\()
9406 (eval (read cmd))
9407 (call-interactively (read cmd))))
9408 (error "Abort"))))
9410 ((and (string= type "thisfile")
9411 (run-hook-with-args-until-success
9412 'org-open-link-functions path)))
9414 ((string= type "thisfile")
9415 (if arg
9416 (switch-to-buffer-other-window
9417 (org-get-buffer-for-internal-link (current-buffer)))
9418 (org-mark-ring-push))
9419 (let ((cmd `(org-link-search
9420 ,path
9421 ,(cond ((equal arg '(4)) ''occur)
9422 ((equal arg '(16)) ''org-occur)
9423 (t nil))
9424 ,pos)))
9425 (condition-case nil (eval cmd)
9426 (error (progn (widen) (eval cmd))))))
9429 (browse-url-at-point)))))))
9430 (move-marker org-open-link-marker nil)
9431 (run-hook-with-args 'org-follow-link-hook)))
9433 (defun org-offer-links-in-entry (&optional nth zero)
9434 "Offer links in the current entry and follow the selected link.
9435 If there is only one link, follow it immediately as well.
9436 If NTH is an integer, immediately pick the NTH link found.
9437 If ZERO is a string, check also this string for a link, and if
9438 there is one, offer it as link number zero."
9439 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9440 "\\(" org-angle-link-re "\\)\\|"
9441 "\\(" org-plain-link-re "\\)"))
9442 (cnt ?0)
9443 (in-emacs (if (integerp nth) nil nth))
9444 have-zero end links link c)
9445 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9446 (push (match-string 0 zero) links)
9447 (setq cnt (1- cnt) have-zero t))
9448 (save-excursion
9449 (org-back-to-heading t)
9450 (setq end (save-excursion (outline-next-heading) (point)))
9451 (while (re-search-forward re end t)
9452 (push (match-string 0) links))
9453 (setq links (org-uniquify (reverse links))))
9455 (cond
9456 ((null links)
9457 (message "No links"))
9458 ((equal (length links) 1)
9459 (setq link (list (car links))))
9460 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9461 (setq link (nth (if have-zero nth (1- nth)) links)))
9462 (t ; we have to select a link
9463 (save-excursion
9464 (save-window-excursion
9465 (delete-other-windows)
9466 (with-output-to-temp-buffer "*Select Link*"
9467 (mapc (lambda (l)
9468 (if (not (string-match org-bracket-link-regexp l))
9469 (princ (format "[%c] %s\n" (incf cnt)
9470 (org-remove-angle-brackets l)))
9471 (if (match-end 3)
9472 (princ (format "[%c] %s (%s)\n" (incf cnt)
9473 (match-string 3 l) (match-string 1 l)))
9474 (princ (format "[%c] %s\n" (incf cnt)
9475 (match-string 1 l))))))
9476 links))
9477 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9478 (message "Select link to open, RET to open all:")
9479 (setq c (read-char-exclusive))
9480 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9481 (when (equal c ?q) (error "Abort"))
9482 (if (equal c ?\C-m)
9483 (setq link links)
9484 (setq nth (- c ?0))
9485 (if have-zero (setq nth (1+ nth)))
9486 (unless (and (integerp nth) (>= (length links) nth))
9487 (error "Invalid link selection"))
9488 (setq link (list (nth (1- nth) links))))))
9489 (if link
9490 (let ((buf (current-buffer)))
9491 (dolist (l link)
9492 (org-open-link-from-string l in-emacs buf))
9494 nil)))
9496 ;; Add special file links that specify the way of opening
9498 (org-add-link-type "file+sys" 'org-open-file-with-system)
9499 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9500 (defun org-open-file-with-system (path)
9501 "Open file at PATH using the system way of opening it."
9502 (org-open-file path 'system))
9503 (defun org-open-file-with-emacs (path)
9504 "Open file at PATH in Emacs."
9505 (org-open-file path 'emacs))
9506 (defun org-remove-file-link-modifiers ()
9507 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9508 (goto-char (point-min))
9509 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9510 (org-if-unprotected
9511 (replace-match "file:" t t))))
9512 (eval-after-load "org-exp"
9513 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9514 'org-remove-file-link-modifiers))
9516 ;;;; Time estimates
9518 (defun org-get-effort (&optional pom)
9519 "Get the effort estimate for the current entry."
9520 (org-entry-get pom org-effort-property))
9522 ;;; File search
9524 (defvar org-create-file-search-functions nil
9525 "List of functions to construct the right search string for a file link.
9526 These functions are called in turn with point at the location to
9527 which the link should point.
9529 A function in the hook should first test if it would like to
9530 handle this file type, for example by checking the `major-mode'
9531 or the file extension. If it decides not to handle this file, it
9532 should just return nil to give other functions a chance. If it
9533 does handle the file, it must return the search string to be used
9534 when following the link. The search string will be part of the
9535 file link, given after a double colon, and `org-open-at-point'
9536 will automatically search for it. If special measures must be
9537 taken to make the search successful, another function should be
9538 added to the companion hook `org-execute-file-search-functions',
9539 which see.
9541 A function in this hook may also use `setq' to set the variable
9542 `description' to provide a suggestion for the descriptive text to
9543 be used for this link when it gets inserted into an Org-mode
9544 buffer with \\[org-insert-link].")
9546 (defvar org-execute-file-search-functions nil
9547 "List of functions to execute a file search triggered by a link.
9549 Functions added to this hook must accept a single argument, the
9550 search string that was part of the file link, the part after the
9551 double colon. The function must first check if it would like to
9552 handle this search, for example by checking the `major-mode' or
9553 the file extension. If it decides not to handle this search, it
9554 should just return nil to give other functions a chance. If it
9555 does handle the search, it must return a non-nil value to keep
9556 other functions from trying.
9558 Each function can access the current prefix argument through the
9559 variable `current-prefix-argument'. Note that a single prefix is
9560 used to force opening a link in Emacs, so it may be good to only
9561 use a numeric or double prefix to guide the search function.
9563 In case this is needed, a function in this hook can also restore
9564 the window configuration before `org-open-at-point' was called using:
9566 (set-window-configuration org-window-config-before-follow-link)")
9568 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9569 (defun org-link-search (s &optional type avoid-pos)
9570 "Search for a link search option.
9571 If S is surrounded by forward slashes, it is interpreted as a
9572 regular expression. In org-mode files, this will create an `org-occur'
9573 sparse tree. In ordinary files, `occur' will be used to list matches.
9574 If the current buffer is in `dired-mode', grep will be used to search
9575 in all files. If AVOID-POS is given, ignore matches near that position."
9576 (let ((case-fold-search t)
9577 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9578 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9579 (append '(("") (" ") ("\t") ("\n"))
9580 org-emphasis-alist)
9581 "\\|") "\\)"))
9582 (pos (point))
9583 (pre nil) (post nil)
9584 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9585 (cond
9586 ;; First check if there are any special search functions
9587 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9588 ;; Now try the builtin stuff
9589 ((and (equal (string-to-char s0) ?#)
9590 (> (length s0) 1)
9591 (save-excursion
9592 (goto-char (point-min))
9593 (and
9594 (re-search-forward
9595 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9596 (setq type 'dedicated
9597 pos (match-beginning 0))))
9598 ;; There is an exact target for this
9599 (goto-char pos)
9600 (org-back-to-heading t)))
9601 ((save-excursion
9602 (goto-char (point-min))
9603 (and
9604 (re-search-forward
9605 (concat "<<" (regexp-quote s0) ">>") nil t)
9606 (setq type 'dedicated
9607 pos (match-beginning 0))))
9608 ;; There is an exact target for this
9609 (goto-char pos))
9610 ((and (string-match "^(\\(.*\\))$" s0)
9611 (save-excursion
9612 (goto-char (point-min))
9613 (and
9614 (re-search-forward
9615 (concat "[^[]" (regexp-quote
9616 (format org-coderef-label-format
9617 (match-string 1 s0))))
9618 nil t)
9619 (setq type 'dedicated
9620 pos (1+ (match-beginning 0))))))
9621 ;; There is a coderef target for this
9622 (goto-char pos))
9623 ((string-match "^/\\(.*\\)/$" s)
9624 ;; A regular expression
9625 (cond
9626 ((org-mode-p)
9627 (org-occur (match-string 1 s)))
9628 ;;((eq major-mode 'dired-mode)
9629 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9630 (t (org-do-occur (match-string 1 s)))))
9631 ((and (org-mode-p) org-link-search-must-match-exact-headline)
9632 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9633 (goto-char (point-min))
9634 (cond
9635 ((let (case-fold-search)
9636 (re-search-forward (format org-complex-heading-regexp-format
9637 (regexp-quote s))
9638 nil t))
9639 ;; OK, found a match
9640 (setq type 'dedicated)
9641 (goto-char (match-beginning 0)))
9642 ((and (not org-link-search-inhibit-query)
9643 (eq org-link-search-must-match-exact-headline 'query-to-create)
9644 (y-or-n-p "No match - create this as a new heading? "))
9645 (goto-char (point-max))
9646 (or (bolp) (newline))
9647 (insert "* " s "\n")
9648 (beginning-of-line 0))
9650 (goto-char pos)
9651 (error "No match"))))
9653 ;; A normal search string
9654 (when (equal (string-to-char s) ?*)
9655 ;; Anchor on headlines, post may include tags.
9656 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9657 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9658 s (substring s 1)))
9659 (remove-text-properties
9660 0 (length s)
9661 '(face nil mouse-face nil keymap nil fontified nil) s)
9662 ;; Make a series of regular expressions to find a match
9663 (setq words (org-split-string s "[ \n\r\t]+")
9665 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9666 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9667 "\\)" markers)
9668 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9669 re2a (concat "[ \t\r\n]" re2a_)
9670 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9671 re4 (concat "[^a-zA-Z_]" re4_)
9673 re1 (concat pre re2 post)
9674 re3 (concat pre (if pre re4_ re4) post)
9675 re5 (concat pre ".*" re4)
9676 re2 (concat pre re2)
9677 re2a (concat pre (if pre re2a_ re2a))
9678 re4 (concat pre (if pre re4_ re4))
9679 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9680 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9681 re5 "\\)"
9683 (cond
9684 ((eq type 'org-occur) (org-occur reall))
9685 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9686 (t (goto-char (point-min))
9687 (setq type 'fuzzy)
9688 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9689 (org-search-not-self 1 re1 nil t)
9690 (org-search-not-self 1 re2 nil t)
9691 (org-search-not-self 1 re2a nil t)
9692 (org-search-not-self 1 re3 nil t)
9693 (org-search-not-self 1 re4 nil t)
9694 (org-search-not-self 1 re5 nil t)
9696 (goto-char (match-beginning 1))
9697 (goto-char pos)
9698 (error "No match"))))))
9699 (and (org-mode-p) (org-show-context 'link-search))
9700 type))
9702 (defun org-search-not-self (group &rest args)
9703 "Execute `re-search-forward', but only accept matches that do not
9704 enclose the position of `org-open-link-marker'."
9705 (let ((m org-open-link-marker))
9706 (catch 'exit
9707 (while (apply 're-search-forward args)
9708 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9709 (goto-char (match-end group))
9710 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9711 (> (match-beginning 0) (marker-position m))
9712 (< (match-end 0) (marker-position m)))
9713 (save-match-data
9714 (or (not (org-in-regexp
9715 org-bracket-link-analytic-regexp 1))
9716 (not (match-end 4)) ; no description
9717 (and (<= (match-beginning 4) (point))
9718 (>= (match-end 4) (point))))))
9719 (throw 'exit (point))))))))
9721 (defun org-get-buffer-for-internal-link (buffer)
9722 "Return a buffer to be used for displaying the link target of internal links."
9723 (cond
9724 ((not org-display-internal-link-with-indirect-buffer)
9725 buffer)
9726 ((string-match "(Clone)$" (buffer-name buffer))
9727 (message "Buffer is already a clone, not making another one")
9728 ;; we also do not modify visibility in this case
9729 buffer)
9730 (t ; make a new indirect buffer for displaying the link
9731 (let* ((bn (buffer-name buffer))
9732 (ibn (concat bn "(Clone)"))
9733 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9734 (with-current-buffer ib (org-overview))
9735 ib))))
9737 (defun org-do-occur (regexp &optional cleanup)
9738 "Call the Emacs command `occur'.
9739 If CLEANUP is non-nil, remove the printout of the regular expression
9740 in the *Occur* buffer. This is useful if the regex is long and not useful
9741 to read."
9742 (occur regexp)
9743 (when cleanup
9744 (let ((cwin (selected-window)) win beg end)
9745 (when (setq win (get-buffer-window "*Occur*"))
9746 (select-window win))
9747 (goto-char (point-min))
9748 (when (re-search-forward "match[a-z]+" nil t)
9749 (setq beg (match-end 0))
9750 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9751 (setq end (1- (match-beginning 0)))))
9752 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9753 (goto-char (point-min))
9754 (select-window cwin))))
9756 ;;; The mark ring for links jumps
9758 (defvar org-mark-ring nil
9759 "Mark ring for positions before jumps in Org-mode.")
9760 (defvar org-mark-ring-last-goto nil
9761 "Last position in the mark ring used to go back.")
9762 ;; Fill and close the ring
9763 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9764 (loop for i from 1 to org-mark-ring-length do
9765 (push (make-marker) org-mark-ring))
9766 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9767 org-mark-ring)
9769 (defun org-mark-ring-push (&optional pos buffer)
9770 "Put the current position or POS into the mark ring and rotate it."
9771 (interactive)
9772 (setq pos (or pos (point)))
9773 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9774 (move-marker (car org-mark-ring)
9775 (or pos (point))
9776 (or buffer (current-buffer)))
9777 (message "%s"
9778 (substitute-command-keys
9779 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9781 (defun org-mark-ring-goto (&optional n)
9782 "Jump to the previous position in the mark ring.
9783 With prefix arg N, jump back that many stored positions. When
9784 called several times in succession, walk through the entire ring.
9785 Org-mode commands jumping to a different position in the current file,
9786 or to another Org-mode file, automatically push the old position
9787 onto the ring."
9788 (interactive "p")
9789 (let (p m)
9790 (if (eq last-command this-command)
9791 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9792 (setq p org-mark-ring))
9793 (setq org-mark-ring-last-goto p)
9794 (setq m (car p))
9795 (switch-to-buffer (marker-buffer m))
9796 (goto-char m)
9797 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9799 (defun org-remove-angle-brackets (s)
9800 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9801 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9803 (defun org-add-angle-brackets (s)
9804 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9805 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9807 (defun org-remove-double-quotes (s)
9808 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9809 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9812 ;;; Following specific links
9814 (defun org-follow-timestamp-link ()
9815 (cond
9816 ((org-at-date-range-p t)
9817 (let ((org-agenda-start-on-weekday)
9818 (t1 (match-string 1))
9819 (t2 (match-string 2)))
9820 (setq t1 (time-to-days (org-time-string-to-time t1))
9821 t2 (time-to-days (org-time-string-to-time t2)))
9822 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9823 ((org-at-timestamp-p t)
9824 (org-agenda-list nil (time-to-days (org-time-string-to-time
9825 (substring (match-string 1) 0 10)))
9827 (t (error "This should not happen"))))
9830 ;;; Following file links
9831 (defvar org-wait nil)
9832 (defun org-open-file (path &optional in-emacs line search)
9833 "Open the file at PATH.
9834 First, this expands any special file name abbreviations. Then the
9835 configuration variable `org-file-apps' is checked if it contains an
9836 entry for this file type, and if yes, the corresponding command is launched.
9838 If no application is found, Emacs simply visits the file.
9840 With optional prefix argument IN-EMACS, Emacs will visit the file.
9841 With a double \\[universal-argument] \\[universal-argument] \
9842 prefix arg, Org tries to avoid opening in Emacs
9843 and to use an external application to visit the file.
9845 Optional LINE specifies a line to go to, optional SEARCH a string
9846 to search for. If LINE or SEARCH is given, the file will be
9847 opened in Emacs, unless an entry from org-file-apps that makes
9848 use of groups in a regexp matches.
9849 If the file does not exist, an error is thrown."
9850 (let* ((file (if (equal path "")
9851 buffer-file-name
9852 (substitute-in-file-name (expand-file-name path))))
9853 (file-apps (append org-file-apps (org-default-apps)))
9854 (apps (org-remove-if
9855 'org-file-apps-entry-match-against-dlink-p file-apps))
9856 (apps-dlink (org-remove-if-not
9857 'org-file-apps-entry-match-against-dlink-p file-apps))
9858 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9859 (dirp (if remp nil (file-directory-p file)))
9860 (file (if (and dirp org-open-directory-means-index-dot-org)
9861 (concat (file-name-as-directory file) "index.org")
9862 file))
9863 (a-m-a-p (assq 'auto-mode apps))
9864 (dfile (downcase file))
9865 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9866 (link (cond ((and (eq line nil)
9867 (eq search nil))
9868 file)
9869 (line
9870 (concat file "::" (number-to-string line)))
9871 (search
9872 (concat file "::" search))))
9873 (dlink (downcase link))
9874 (old-buffer (current-buffer))
9875 (old-pos (point))
9876 (old-mode major-mode)
9877 ext cmd link-match-data)
9878 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9879 (setq ext (match-string 1 dfile))
9880 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9881 (setq ext (match-string 1 dfile))))
9882 (cond
9883 ((member in-emacs '((16) system))
9884 (setq cmd (cdr (assoc 'system apps))))
9885 (in-emacs (setq cmd 'emacs))
9887 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9888 (and dirp (cdr (assoc 'directory apps)))
9889 ; first, try matching against apps-dlink
9890 ; if we get a match here, store the match data for later
9891 (let ((match (assoc-default dlink apps-dlink
9892 'string-match)))
9893 (if match
9894 (progn (setq link-match-data (match-data))
9895 match)
9896 (progn (setq in-emacs (or in-emacs line search))
9897 nil))) ; if we have no match in apps-dlink,
9898 ; always open the file in emacs if line or search
9899 ; is given (for backwards compatibility)
9900 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9901 'string-match)
9902 (cdr (assoc ext apps))
9903 (cdr (assoc t apps))))))
9904 (when (eq cmd 'system)
9905 (setq cmd (cdr (assoc 'system apps))))
9906 (when (eq cmd 'default)
9907 (setq cmd (cdr (assoc t apps))))
9908 (when (eq cmd 'mailcap)
9909 (require 'mailcap)
9910 (mailcap-parse-mailcaps)
9911 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9912 (command (mailcap-mime-info mime-type)))
9913 (if (stringp command)
9914 (setq cmd command)
9915 (setq cmd 'emacs))))
9916 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9917 (not (file-exists-p file))
9918 (not org-open-non-existing-files))
9919 (error "No such file: %s" file))
9920 (cond
9921 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9922 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9923 (while (string-match "['\"]%s['\"]" cmd)
9924 (setq cmd (replace-match "%s" t t cmd)))
9925 (while (string-match "%s" cmd)
9926 (setq cmd (replace-match
9927 (save-match-data
9928 (shell-quote-argument
9929 (convert-standard-filename file)))
9930 t t cmd)))
9932 ;; Replace "%1", "%2" etc. in command with group matches from regex
9933 (save-match-data
9934 (let ((match-index 1)
9935 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9936 (set-match-data link-match-data)
9937 (while (<= match-index number-of-groups)
9938 (let ((regex (concat "%" (number-to-string match-index)))
9939 (replace-with (match-string match-index dlink)))
9940 (while (string-match regex cmd)
9941 (setq cmd (replace-match replace-with t t cmd))))
9942 (setq match-index (+ match-index 1)))))
9944 (save-window-excursion
9945 (start-process-shell-command cmd nil cmd)
9946 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9948 ((or (stringp cmd)
9949 (eq cmd 'emacs))
9950 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9951 (widen)
9952 (if line (org-goto-line line)
9953 (if search (org-link-search search))))
9954 ((consp cmd)
9955 (let ((file (convert-standard-filename file)))
9956 (save-match-data
9957 (set-match-data link-match-data)
9958 (eval cmd))))
9959 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9960 (and (org-mode-p) (eq old-mode 'org-mode)
9961 (or (not (equal old-buffer (current-buffer)))
9962 (not (equal old-pos (point))))
9963 (org-mark-ring-push old-pos old-buffer))))
9965 (defun org-file-apps-entry-match-against-dlink-p (entry)
9966 "This function returns non-nil if `entry' uses a regular
9967 expression which should be matched against the whole link by
9968 org-open-file.
9970 It assumes that is the case when the entry uses a regular
9971 expression which has at least one grouping construct and the
9972 action is either a lisp form or a command string containing
9973 '%1', i.e. using at least one subexpression match as a
9974 parameter."
9975 (let ((selector (car entry))
9976 (action (cdr entry)))
9977 (if (stringp selector)
9978 (and (> (regexp-opt-depth selector) 0)
9979 (or (and (stringp action)
9980 (string-match "%[0-9]" action))
9981 (consp action)))
9982 nil)))
9984 (defun org-default-apps ()
9985 "Return the default applications for this operating system."
9986 (cond
9987 ((eq system-type 'darwin)
9988 org-file-apps-defaults-macosx)
9989 ((eq system-type 'windows-nt)
9990 org-file-apps-defaults-windowsnt)
9991 (t org-file-apps-defaults-gnu)))
9993 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9994 "Convert extensions to regular expressions in the cars of LIST.
9995 Also, weed out any non-string entries, because the return value is used
9996 only for regexp matching.
9997 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9998 point to the symbol `emacs', indicating that the file should
9999 be opened in Emacs."
10000 (append
10001 (delq nil
10002 (mapcar (lambda (x)
10003 (if (not (stringp (car x)))
10005 (if (string-match "\\W" (car x))
10007 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10008 list))
10009 (if add-auto-mode
10010 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10012 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10013 (defun org-file-remote-p (file)
10014 "Test whether FILE specifies a location on a remote system.
10015 Return non-nil if the location is indeed remote.
10017 For example, the filename \"/user@host:/foo\" specifies a location
10018 on the system \"/user@host:\"."
10019 (cond ((fboundp 'file-remote-p)
10020 (file-remote-p file))
10021 ((fboundp 'tramp-handle-file-remote-p)
10022 (tramp-handle-file-remote-p file))
10023 ((and (boundp 'ange-ftp-name-format)
10024 (string-match (car ange-ftp-name-format) file))
10026 (t nil)))
10029 ;;;; Refiling
10031 (defun org-get-org-file ()
10032 "Read a filename, with default directory `org-directory'."
10033 (let ((default (or org-default-notes-file remember-data-file)))
10034 (read-file-name (format "File name [%s]: " default)
10035 (file-name-as-directory org-directory)
10036 default)))
10038 (defun org-notes-order-reversed-p ()
10039 "Check if the current file should receive notes in reversed order."
10040 (cond
10041 ((not org-reverse-note-order) nil)
10042 ((eq t org-reverse-note-order) t)
10043 ((not (listp org-reverse-note-order)) nil)
10044 (t (catch 'exit
10045 (let ((all org-reverse-note-order)
10046 entry)
10047 (while (setq entry (pop all))
10048 (if (string-match (car entry) buffer-file-name)
10049 (throw 'exit (cdr entry))))
10050 nil)))))
10052 (defvar org-refile-target-table nil
10053 "The list of refile targets, created by `org-refile'.")
10055 (defvar org-agenda-new-buffers nil
10056 "Buffers created to visit agenda files.")
10058 (defvar org-refile-cache nil
10059 "Cache for refile targets.")
10061 (defvar org-refile-markers nil
10062 "All the markers used for caching refile locations.")
10064 (defun org-refile-marker (pos)
10065 "Get a new refile marker, but only if caching is in use."
10066 (if (not org-refile-use-cache)
10068 (let ((m (make-marker)))
10069 (move-marker m pos)
10070 (push m org-refile-markers)
10071 m)))
10073 (defun org-refile-cache-clear ()
10074 "Clear the refile cache and disable all the markers."
10075 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10076 (setq org-refile-markers nil)
10077 (setq org-refile-cache nil)
10078 (message "Refile cache has been cleared"))
10080 (defun org-refile-cache-check-set (set)
10081 "Check if all the markers in the cache still have live buffers."
10082 (let (marker)
10083 (catch 'exit
10084 (while (and set (setq marker (nth 3 (pop set))))
10085 ;; if org-refile-use-outline-path is 'file, marker may be nil
10086 (when (and marker (null (marker-buffer marker)))
10087 (message "not found") (sit-for 3)
10088 (throw 'exit nil)))
10089 t)))
10091 (defun org-refile-cache-put (set &rest identifiers)
10092 "Push the refile targets SET into the cache, under IDENTIFIERS."
10093 (let* ((key (sha1 (prin1-to-string identifiers)))
10094 (entry (assoc key org-refile-cache)))
10095 (if entry
10096 (setcdr entry set)
10097 (push (cons key set) org-refile-cache))))
10099 (defun org-refile-cache-get (&rest identifiers)
10100 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10101 (cond
10102 ((not org-refile-cache) nil)
10103 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10105 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10106 org-refile-cache))))
10107 (and set (org-refile-cache-check-set set) set)))))
10109 (defun org-refile-get-targets (&optional default-buffer)
10110 "Produce a table with refile targets."
10111 (let ((case-fold-search nil)
10112 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10113 (entries (or org-refile-targets '((nil . (:level . 1)))))
10114 targets tgs txt re files f desc descre fast-path-p level pos0)
10115 (message "Getting targets...")
10116 (with-current-buffer (or default-buffer (current-buffer))
10117 (while (setq entry (pop entries))
10118 (setq files (car entry) desc (cdr entry))
10119 (setq fast-path-p nil)
10120 (cond
10121 ((null files) (setq files (list (current-buffer))))
10122 ((eq files 'org-agenda-files)
10123 (setq files (org-agenda-files 'unrestricted)))
10124 ((and (symbolp files) (fboundp files))
10125 (setq files (funcall files)))
10126 ((and (symbolp files) (boundp files))
10127 (setq files (symbol-value files))))
10128 (if (stringp files) (setq files (list files)))
10129 (cond
10130 ((eq (car desc) :tag)
10131 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10132 ((eq (car desc) :todo)
10133 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10134 ((eq (car desc) :regexp)
10135 (setq descre (cdr desc)))
10136 ((eq (car desc) :level)
10137 (setq descre (concat "^\\*\\{" (number-to-string
10138 (if org-odd-levels-only
10139 (1- (* 2 (cdr desc)))
10140 (cdr desc)))
10141 "\\}[ \t]")))
10142 ((eq (car desc) :maxlevel)
10143 (setq fast-path-p t)
10144 (setq descre (concat "^\\*\\{1," (number-to-string
10145 (if org-odd-levels-only
10146 (1- (* 2 (cdr desc)))
10147 (cdr desc)))
10148 "\\}[ \t]")))
10149 (t (error "Bad refiling target description %s" desc)))
10150 (while (setq f (pop files))
10151 (with-current-buffer
10152 (if (bufferp f) f (org-get-agenda-file-buffer f))
10154 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10155 (progn
10156 (if (bufferp f) (setq f (buffer-file-name
10157 (buffer-base-buffer f))))
10158 (setq f (and f (expand-file-name f)))
10159 (if (eq org-refile-use-outline-path 'file)
10160 (push (list (file-name-nondirectory f) f nil nil) tgs))
10161 (save-excursion
10162 (save-restriction
10163 (widen)
10164 (goto-char (point-min))
10165 (while (re-search-forward descre nil t)
10166 (goto-char (setq pos0 (point-at-bol)))
10167 (catch 'next
10168 (when org-refile-target-verify-function
10169 (save-match-data
10170 (or (funcall org-refile-target-verify-function)
10171 (throw 'next t))))
10172 (when (looking-at org-complex-heading-regexp)
10173 (setq level (org-reduced-level
10174 (- (match-end 1) (match-beginning 1)))
10175 txt (org-link-display-format (match-string 4))
10176 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10177 re (format org-complex-heading-regexp-format
10178 (regexp-quote (match-string 4))))
10179 (when org-refile-use-outline-path
10180 (setq txt (mapconcat
10181 'org-protect-slash
10182 (append
10183 (if (eq org-refile-use-outline-path
10184 'file)
10185 (list (file-name-nondirectory
10186 (buffer-file-name
10187 (buffer-base-buffer))))
10188 (if (eq org-refile-use-outline-path
10189 'full-file-path)
10190 (list (buffer-file-name
10191 (buffer-base-buffer)))))
10192 (org-get-outline-path fast-path-p
10193 level txt)
10194 (list txt))
10195 "/")))
10196 (push (list txt f re (org-refile-marker (point)))
10197 tgs)))
10198 (when (= (point) pos0)
10199 ;; verification function has not moved point
10200 (goto-char (point-at-eol))))))))
10201 (when org-refile-use-cache
10202 (org-refile-cache-put tgs (buffer-file-name) descre))
10203 (setq targets (append tgs targets))
10204 ))))
10205 (message "Getting targets...done")
10206 (nreverse targets)))
10208 (defun org-protect-slash (s)
10209 (while (string-match "/" s)
10210 (setq s (replace-match "\\" t t s)))
10213 (defvar org-olpa (make-vector 20 nil))
10215 (defun org-get-outline-path (&optional fastp level heading)
10216 "Return the outline path to the current entry, as a list.
10218 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10219 routine which makes outline path derivations for an entire file,
10220 avoiding backtracing. Refile target collection makes use of that."
10221 (if fastp
10222 (progn
10223 (if (> level 19)
10224 (error "Outline path failure, more than 19 levels"))
10225 (loop for i from level upto 19 do
10226 (aset org-olpa i nil))
10227 (prog1
10228 (delq nil (append org-olpa nil))
10229 (aset org-olpa level heading)))
10230 (let (rtn case-fold-search)
10231 (save-excursion
10232 (save-restriction
10233 (widen)
10234 (while (org-up-heading-safe)
10235 (when (looking-at org-complex-heading-regexp)
10236 (push (org-match-string-no-properties 4) rtn)))
10237 rtn)))))
10239 (defun org-format-outline-path (path &optional width prefix)
10240 "Format the outline path PATH for display.
10241 Width is the maximum number of characters that is available.
10242 Prefix is a prefix to be included in the returned string,
10243 such as the file name."
10244 (setq width (or width 79))
10245 (if prefix (setq width (- width (length prefix))))
10246 (if (not path)
10247 (or prefix "")
10248 (let* ((nsteps (length path))
10249 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10250 (maxwidth (if (<= total-width width)
10251 10000 ;; everything fits
10252 ;; we need to shorten the level headings
10253 (/ (- width nsteps) nsteps)))
10254 (org-odd-levels-only nil)
10255 (n 0)
10256 (total (1+ (length prefix))))
10257 (setq maxwidth (max maxwidth 10))
10258 (concat prefix
10259 (mapconcat
10260 (lambda (h)
10261 (setq n (1+ n))
10262 (if (and (= n nsteps) (< maxwidth 10000))
10263 (setq maxwidth (- total-width total)))
10264 (if (< (length h) maxwidth)
10265 (progn (setq total (+ total (length h) 1)) h)
10266 (setq h (substring h 0 (- maxwidth 2))
10267 total (+ total maxwidth 1))
10268 (if (string-match "[ \t]+\\'" h)
10269 (setq h (substring h 0 (match-beginning 0))))
10270 (setq h (concat h "..")))
10271 (org-add-props h nil 'face
10272 (nth (% (1- n) org-n-level-faces)
10273 org-level-faces))
10275 path "/")))))
10277 (defun org-display-outline-path (&optional file current)
10278 "Display the current outline path in the echo area."
10279 (interactive "P")
10280 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10281 (case-fold-search nil)
10282 (path (and (org-mode-p) (org-get-outline-path))))
10283 (if current (setq path (append path
10284 (save-excursion
10285 (org-back-to-heading t)
10286 (if (looking-at org-complex-heading-regexp)
10287 (list (match-string 4)))))))
10288 (message "%s"
10289 (org-format-outline-path
10290 path
10291 (1- (frame-width))
10292 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10294 (defvar org-refile-history nil
10295 "History for refiling operations.")
10297 (defvar org-after-refile-insert-hook nil
10298 "Hook run after `org-refile' has inserted its stuff at the new location.
10299 Note that this is still *before* the stuff will be removed from
10300 the *old* location.")
10302 (defvar org-capture-last-stored-marker)
10303 (defun org-refile (&optional goto default-buffer rfloc)
10304 "Move the entry at point to another heading.
10305 The list of target headings is compiled using the information in
10306 `org-refile-targets', which see. This list is created before each use
10307 and will therefore always be up-to-date.
10309 At the target location, the entry is filed as a subitem of the target heading.
10310 Depending on `org-reverse-note-order', the new subitem will either be the
10311 first or the last subitem.
10313 If there is an active region, all entries in that region will be moved.
10314 However, the region must fulfill the requirement that the first heading
10315 is the first one sets the top-level of the moved text - at most siblings
10316 below it are allowed.
10318 With prefix arg GOTO, the command will only visit the target location,
10319 not actually move anything.
10320 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10321 go to the location where the last refiling
10322 operation has put the subtree.
10323 With a prefix argument of `2', refile to the running clock.
10325 RFLOC can be a refile location obtained in a different way.
10327 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10329 If you are using target caching (see `org-refile-use-cache'),
10330 You have to clear the target cache in order to find new targets.
10331 This can be done with a 0 prefix: `C-0 C-c C-w'"
10332 (interactive "P")
10333 (if (member goto '(0 (64)))
10334 (org-refile-cache-clear)
10335 (let* ((cbuf (current-buffer))
10336 (regionp (org-region-active-p))
10337 (region-start (and regionp (region-beginning)))
10338 (region-end (and regionp (region-end)))
10339 (region-length (and regionp (- region-end region-start)))
10340 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10341 pos it nbuf file re level reversed)
10342 (setq last-command nil)
10343 (when regionp
10344 (goto-char region-start)
10345 (or (bolp) (goto-char (point-at-bol)))
10346 (setq region-start (point))
10347 (unless (org-kill-is-subtree-p
10348 (buffer-substring region-start region-end))
10349 (error "The region is not a (sequence of) subtree(s)")))
10350 (if (equal goto '(16))
10351 (org-refile-goto-last-stored)
10352 (when (or
10353 (and (equal goto 2)
10354 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10355 (prog1
10356 (setq it (list (or org-clock-heading "running clock")
10357 (buffer-file-name
10358 (marker-buffer org-clock-hd-marker))
10360 (marker-position org-clock-hd-marker)))
10361 (setq goto nil)))
10362 (setq it (or rfloc
10363 (save-excursion
10364 (org-refile-get-location
10365 (if goto "Goto" "Refile to") default-buffer
10366 org-refile-allow-creating-parent-nodes)))))
10367 (setq file (nth 1 it)
10368 re (nth 2 it)
10369 pos (nth 3 it))
10370 (if (and (not goto)
10372 (equal (buffer-file-name) file)
10373 (if regionp
10374 (and (>= pos region-start)
10375 (<= pos region-end))
10376 (and (>= pos (point))
10377 (< pos (save-excursion
10378 (org-end-of-subtree t t))))))
10379 (error "Cannot refile to position inside the tree or region"))
10381 (setq nbuf (or (find-buffer-visiting file)
10382 (find-file-noselect file)))
10383 (if goto
10384 (progn
10385 (switch-to-buffer nbuf)
10386 (goto-char pos)
10387 (org-show-context 'org-goto))
10388 (if regionp
10389 (progn
10390 (org-kill-new (buffer-substring region-start region-end))
10391 (org-save-markers-in-region region-start region-end))
10392 (org-copy-subtree 1 nil t))
10393 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10394 (find-file-noselect file)))
10395 (setq reversed (org-notes-order-reversed-p))
10396 (save-excursion
10397 (save-restriction
10398 (widen)
10399 (if pos
10400 (progn
10401 (goto-char pos)
10402 (looking-at outline-regexp)
10403 (setq level (org-get-valid-level (funcall outline-level) 1))
10404 (goto-char
10405 (if reversed
10406 (or (outline-next-heading) (point-max))
10407 (or (save-excursion (org-get-next-sibling))
10408 (org-end-of-subtree t t)
10409 (point-max)))))
10410 (setq level 1)
10411 (if (not reversed)
10412 (goto-char (point-max))
10413 (goto-char (point-min))
10414 (or (outline-next-heading) (goto-char (point-max)))))
10415 (if (not (bolp)) (newline))
10416 (org-paste-subtree level)
10417 (when org-log-refile
10418 (org-add-log-setup 'refile nil nil 'findpos
10419 org-log-refile)
10420 (unless (eq org-log-refile 'note)
10421 (save-excursion (org-add-log-note))))
10422 (and org-auto-align-tags (org-set-tags nil t))
10423 (bookmark-set "org-refile-last-stored")
10424 ;; If we are refiling for capture, make sure that the
10425 ;; last-capture pointers point here
10426 (when (org-bound-and-true-p org-refile-for-capture)
10427 (bookmark-set "org-capture-last-stored-marker")
10428 (move-marker org-capture-last-stored-marker (point)))
10429 (if (fboundp 'deactivate-mark) (deactivate-mark))
10430 (run-hooks 'org-after-refile-insert-hook))))
10431 (if regionp
10432 (delete-region (point) (+ (point) region-length))
10433 (org-cut-subtree))
10434 (when (featurep 'org-inlinetask)
10435 (org-inlinetask-remove-END-maybe))
10436 (setq org-markers-to-move nil)
10437 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10439 (defun org-refile-goto-last-stored ()
10440 "Go to the location where the last refile was stored."
10441 (interactive)
10442 (bookmark-jump "org-refile-last-stored")
10443 (message "This is the location of the last refile"))
10445 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
10446 "Prompt the user for a refile location, using PROMPT.
10447 PROMPT should not be suffixed with a colon and a space, because
10448 this function appends the default value from
10449 `org-refile-history' automatically, if that is not empty."
10450 (let ((org-refile-targets org-refile-targets)
10451 (org-refile-use-outline-path org-refile-use-outline-path))
10452 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
10453 (unless org-refile-target-table
10454 (error "No refile targets"))
10455 (let* ((prompt (concat prompt
10456 (and (car org-refile-history)
10457 (concat " (default " (car org-refile-history) ")"))
10458 ": "))
10459 (cbuf (current-buffer))
10460 (partial-completion-mode nil)
10461 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10462 (cfunc (if (and org-refile-use-outline-path
10463 org-outline-path-complete-in-steps)
10464 'org-olpath-completing-read
10465 'org-icompleting-read))
10466 (extra (if org-refile-use-outline-path "/" ""))
10467 (filename (and cfn (expand-file-name cfn)))
10468 (tbl (mapcar
10469 (lambda (x)
10470 (if (and (not (member org-refile-use-outline-path
10471 '(file full-file-path)))
10472 (not (equal filename (nth 1 x))))
10473 (cons (concat (car x) extra " ("
10474 (file-name-nondirectory (nth 1 x)) ")")
10475 (cdr x))
10476 (cons (concat (car x) extra) (cdr x))))
10477 org-refile-target-table))
10478 (completion-ignore-case t)
10479 pa answ parent-target child parent old-hist)
10480 (setq old-hist org-refile-history)
10481 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10482 nil 'org-refile-history (car org-refile-history)))
10483 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10484 (org-refile-check-position pa)
10485 (if pa
10486 (progn
10487 (when (or (not org-refile-history)
10488 (not (eq old-hist org-refile-history))
10489 (not (equal (car pa) (car org-refile-history))))
10490 (setq org-refile-history
10491 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10492 org-refile-history
10493 (cdr org-refile-history))))
10494 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10495 (pop org-refile-history)))
10497 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10498 (progn
10499 (setq parent (match-string 1 answ)
10500 child (match-string 2 answ))
10501 (setq parent-target (or (assoc parent tbl)
10502 (assoc (concat parent "/") tbl)))
10503 (when (and parent-target
10504 (or (eq new-nodes t)
10505 (and (eq new-nodes 'confirm)
10506 (y-or-n-p (format "Create new node \"%s\"? "
10507 child)))))
10508 (org-refile-new-child parent-target child)))
10509 (error "Invalid target location")))))
10511 (defun org-refile-check-position (refile-pointer)
10512 "Check if the refile pointer matches the readline to which it points."
10513 (let* ((file (nth 1 refile-pointer))
10514 (re (nth 2 refile-pointer))
10515 (pos (nth 3 refile-pointer))
10516 buffer)
10517 (when (org-string-nw-p re)
10518 (setq buffer (if (markerp pos)
10519 (marker-buffer pos)
10520 (or (find-buffer-visiting file)
10521 (find-file-noselect file))))
10522 (with-current-buffer buffer
10523 (save-excursion
10524 (save-restriction
10525 (widen)
10526 (goto-char pos)
10527 (beginning-of-line 1)
10528 (unless (org-looking-at-p re)
10529 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10531 (defun org-refile-new-child (parent-target child)
10532 "Use refile target PARENT-TARGET to add new CHILD below it."
10533 (unless parent-target
10534 (error "Cannot find parent for new node"))
10535 (let ((file (nth 1 parent-target))
10536 (pos (nth 3 parent-target))
10537 level)
10538 (with-current-buffer (or (find-buffer-visiting file)
10539 (find-file-noselect file))
10540 (save-excursion
10541 (save-restriction
10542 (widen)
10543 (if pos
10544 (goto-char pos)
10545 (goto-char (point-max))
10546 (if (not (bolp)) (newline)))
10547 (when (looking-at outline-regexp)
10548 (setq level (funcall outline-level))
10549 (org-end-of-subtree t t))
10550 (org-back-over-empty-lines)
10551 (insert "\n" (make-string
10552 (if pos (org-get-valid-level level 1) 1) ?*)
10553 " " child "\n")
10554 (beginning-of-line 0)
10555 (list (concat (car parent-target) "/" child) file "" (point)))))))
10557 (defun org-olpath-completing-read (prompt collection &rest args)
10558 "Read an outline path like a file name."
10559 (let ((thetable collection)
10560 (org-completion-use-ido nil) ; does not work with ido.
10561 (org-completion-use-iswitchb nil)) ; or iswitchb
10562 (apply
10563 'org-icompleting-read prompt
10564 (lambda (string predicate &optional flag)
10565 (let (rtn r f (l (length string)))
10566 (cond
10567 ((eq flag nil)
10568 ;; try completion
10569 (try-completion string thetable))
10570 ((eq flag t)
10571 ;; all-completions
10572 (setq rtn (all-completions string thetable predicate))
10573 (mapcar
10574 (lambda (x)
10575 (setq r (substring x l))
10576 (if (string-match " ([^)]*)$" x)
10577 (setq f (match-string 0 x))
10578 (setq f ""))
10579 (if (string-match "/" r)
10580 (concat string (substring r 0 (match-end 0)) f)
10582 rtn))
10583 ((eq flag 'lambda)
10584 ;; exact match?
10585 (assoc string thetable)))
10587 args)))
10589 ;;;; Dynamic blocks
10591 (defun org-find-dblock (name)
10592 "Find the first dynamic block with name NAME in the buffer.
10593 If not found, stay at current position and return nil."
10594 (let (pos)
10595 (save-excursion
10596 (goto-char (point-min))
10597 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
10598 nil t)
10599 (match-beginning 0))))
10600 (if pos (goto-char pos))
10601 pos))
10603 (defconst org-dblock-start-re
10604 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10605 "Matches the start line of a dynamic block, with parameters.")
10607 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10608 "Matches the end of a dynamic block.")
10610 (defun org-create-dblock (plist)
10611 "Create a dynamic block section, with parameters taken from PLIST.
10612 PLIST must contain a :name entry which is used as name of the block."
10613 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10614 (end-of-line 1)
10615 (newline))
10616 (let ((col (current-column))
10617 (name (plist-get plist :name)))
10618 (insert "#+BEGIN: " name)
10619 (while plist
10620 (if (eq (car plist) :name)
10621 (setq plist (cddr plist))
10622 (insert " " (prin1-to-string (pop plist)))))
10623 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10624 (beginning-of-line -2)))
10626 (defun org-prepare-dblock ()
10627 "Prepare dynamic block for refresh.
10628 This empties the block, puts the cursor at the insert position and returns
10629 the property list including an extra property :name with the block name."
10630 (unless (looking-at org-dblock-start-re)
10631 (error "Not at a dynamic block"))
10632 (let* ((begdel (1+ (match-end 0)))
10633 (name (org-no-properties (match-string 1)))
10634 (params (append (list :name name)
10635 (read (concat "(" (match-string 3) ")")))))
10636 (save-excursion
10637 (beginning-of-line 1)
10638 (skip-chars-forward " \t")
10639 (setq params (plist-put params :indentation-column (current-column))))
10640 (unless (re-search-forward org-dblock-end-re nil t)
10641 (error "Dynamic block not terminated"))
10642 (setq params
10643 (append params
10644 (list :content (buffer-substring
10645 begdel (match-beginning 0)))))
10646 (delete-region begdel (match-beginning 0))
10647 (goto-char begdel)
10648 (open-line 1)
10649 params))
10651 (defun org-map-dblocks (&optional command)
10652 "Apply COMMAND to all dynamic blocks in the current buffer.
10653 If COMMAND is not given, use `org-update-dblock'."
10654 (let ((cmd (or command 'org-update-dblock)))
10655 (save-excursion
10656 (goto-char (point-min))
10657 (while (re-search-forward org-dblock-start-re nil t)
10658 (goto-char (match-beginning 0))
10659 (save-excursion
10660 (condition-case nil
10661 (funcall cmd)
10662 (error (message "Error during update of dynamic block"))))
10663 (unless (re-search-forward org-dblock-end-re nil t)
10664 (error "Dynamic block not terminated"))))))
10666 (defun org-dblock-update (&optional arg)
10667 "User command for updating dynamic blocks.
10668 Update the dynamic block at point. With prefix ARG, update all dynamic
10669 blocks in the buffer."
10670 (interactive "P")
10671 (if arg
10672 (org-update-all-dblocks)
10673 (or (looking-at org-dblock-start-re)
10674 (org-beginning-of-dblock))
10675 (org-update-dblock)))
10677 (defun org-update-dblock ()
10678 "Update the dynamic block at point.
10679 This means to empty the block, parse for parameters and then call
10680 the correct writing function."
10681 (interactive)
10682 (save-window-excursion
10683 (let* ((pos (point))
10684 (line (org-current-line))
10685 (params (org-prepare-dblock))
10686 (name (plist-get params :name))
10687 (indent (plist-get params :indentation-column))
10688 (cmd (intern (concat "org-dblock-write:" name))))
10689 (message "Updating dynamic block `%s' at line %d..." name line)
10690 (funcall cmd params)
10691 (message "Updating dynamic block `%s' at line %d...done" name line)
10692 (goto-char pos)
10693 (when (and indent (> indent 0))
10694 (setq indent (make-string indent ?\ ))
10695 (save-excursion
10696 (org-beginning-of-dblock)
10697 (forward-line 1)
10698 (while (not (looking-at org-dblock-end-re))
10699 (insert indent)
10700 (beginning-of-line 2))
10701 (when (looking-at org-dblock-end-re)
10702 (and (looking-at "[ \t]+")
10703 (replace-match ""))
10704 (insert indent)))))))
10706 (defun org-beginning-of-dblock ()
10707 "Find the beginning of the dynamic block at point.
10708 Error if there is no such block at point."
10709 (let ((pos (point))
10710 beg)
10711 (end-of-line 1)
10712 (if (and (re-search-backward org-dblock-start-re nil t)
10713 (setq beg (match-beginning 0))
10714 (re-search-forward org-dblock-end-re nil t)
10715 (> (match-end 0) pos))
10716 (goto-char beg)
10717 (goto-char pos)
10718 (error "Not in a dynamic block"))))
10720 (defun org-update-all-dblocks ()
10721 "Update all dynamic blocks in the buffer.
10722 This function can be used in a hook."
10723 (interactive)
10724 (when (org-mode-p)
10725 (org-map-dblocks 'org-update-dblock)))
10728 ;;;; Completion
10730 (defconst org-additional-option-like-keywords
10731 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10732 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
10733 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10734 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
10735 "BEGIN:" "END:"
10736 "ORGTBL" "TBLFM:" "TBLNAME:"
10737 "BEGIN_EXAMPLE" "END_EXAMPLE"
10738 "BEGIN_QUOTE" "END_QUOTE"
10739 "BEGIN_VERSE" "END_VERSE"
10740 "BEGIN_CENTER" "END_CENTER"
10741 "BEGIN_SRC" "END_SRC"
10742 "BEGIN_RESULT" "END_RESULT"
10743 "SOURCE:" "SRCNAME:" "FUNCTION:"
10744 "RESULTS:"
10745 "HEADER:" "HEADERS:"
10746 "BABEL:"
10747 "CATEGORY:" "COLUMNS:" "PROPERTY:"
10748 "CAPTION:" "LABEL:"
10749 "SETUPFILE:"
10750 "INCLUDE:"
10751 "BIND:"
10752 "MACRO:"))
10754 (defcustom org-structure-template-alist
10756 ("s" "#+begin_src ?\n\n#+end_src"
10757 "<src lang=\"?\">\n\n</src>")
10758 ("e" "#+begin_example\n?\n#+end_example"
10759 "<example>\n?\n</example>")
10760 ("q" "#+begin_quote\n?\n#+end_quote"
10761 "<quote>\n?\n</quote>")
10762 ("v" "#+begin_verse\n?\n#+end_verse"
10763 "<verse>\n?\n/verse>")
10764 ("c" "#+begin_center\n?\n#+end_center"
10765 "<center>\n?\n/center>")
10766 ("l" "#+begin_latex\n?\n#+end_latex"
10767 "<literal style=\"latex\">\n?\n</literal>")
10768 ("L" "#+latex: "
10769 "<literal style=\"latex\">?</literal>")
10770 ("h" "#+begin_html\n?\n#+end_html"
10771 "<literal style=\"html\">\n?\n</literal>")
10772 ("H" "#+html: "
10773 "<literal style=\"html\">?</literal>")
10774 ("a" "#+begin_ascii\n?\n#+end_ascii")
10775 ("A" "#+ascii: ")
10776 ("i" "#+index: ?"
10777 "#+index: ?")
10778 ("I" "#+include %file ?"
10779 "<include file=%file markup=\"?\">")
10781 "Structure completion elements.
10782 This is a list of abbreviation keys and values. The value gets inserted
10783 if you type `<' followed by the key and then press the completion key,
10784 usually `M-TAB'. %file will be replaced by a file name after prompting
10785 for the file using completion. The cursor will be placed at the position
10786 of the `?` in the template.
10787 There are two templates for each key, the first uses the original Org syntax,
10788 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10789 the default when the /org-mtags.el/ module has been loaded. See also the
10790 variable `org-mtags-prefer-muse-templates'.
10791 This is an experimental feature, it is undecided if it is going to stay in."
10792 :group 'org-completion
10793 :type '(repeat
10794 (string :tag "Key")
10795 (string :tag "Template")
10796 (string :tag "Muse Template")))
10798 (defun org-try-structure-completion ()
10799 "Try to complete a structure template before point.
10800 This looks for strings like \"<e\" on an otherwise empty line and
10801 expands them."
10802 (let ((l (buffer-substring (point-at-bol) (point)))
10804 (when (and (looking-at "[ \t]*$")
10805 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
10806 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10807 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10808 (match-beginning 1)) a)
10809 t)))
10811 (defun org-complete-expand-structure-template (start cell)
10812 "Expand a structure template."
10813 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10814 (rpl (nth (if musep 2 1) cell))
10815 (ind ""))
10816 (delete-region start (point))
10817 (when (string-match "\\`#\\+" rpl)
10818 (cond
10819 ((bolp))
10820 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10821 (setq ind (buffer-substring (point-at-bol) (point))))
10822 (t (newline))))
10823 (setq start (point))
10824 (if (string-match "%file" rpl)
10825 (setq rpl (replace-match
10826 (concat
10827 "\""
10828 (save-match-data
10829 (abbreviate-file-name (read-file-name "Include file: ")))
10830 "\"")
10831 t t rpl)))
10832 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10833 (concat "\n" ind)))
10834 (insert rpl)
10835 (if (re-search-backward "\\?" start t) (delete-char 1))))
10837 ;;;; TODO, DEADLINE, Comments
10839 (defun org-toggle-comment ()
10840 "Change the COMMENT state of an entry."
10841 (interactive)
10842 (save-excursion
10843 (org-back-to-heading)
10844 (let (case-fold-search)
10845 (if (looking-at (concat outline-regexp
10846 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10847 (replace-match "" t t nil 1)
10848 (if (looking-at outline-regexp)
10849 (progn
10850 (goto-char (match-end 0))
10851 (insert org-comment-string " ")))))))
10853 (defvar org-last-todo-state-is-todo nil
10854 "This is non-nil when the last TODO state change led to a TODO state.
10855 If the last change removed the TODO tag or switched to DONE, then
10856 this is nil.")
10858 (defvar org-setting-tags nil) ; dynamically skipped
10860 (defvar org-todo-setup-filter-hook nil
10861 "Hook for functions that pre-filter todo specs.
10862 Each function takes a todo spec and returns either nil or the spec
10863 transformed into canonical form." )
10865 (defvar org-todo-get-default-hook nil
10866 "Hook for functions that get a default item for todo.
10867 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10868 nil or a string to be used for the todo mark." )
10870 (defvar org-agenda-headline-snapshot-before-repeat)
10872 (defun org-todo (&optional arg)
10873 "Change the TODO state of an item.
10874 The state of an item is given by a keyword at the start of the heading,
10875 like
10876 *** TODO Write paper
10877 *** DONE Call mom
10879 The different keywords are specified in the variable `org-todo-keywords'.
10880 By default the available states are \"TODO\" and \"DONE\".
10881 So for this example: when the item starts with TODO, it is changed to DONE.
10882 When it starts with DONE, the DONE is removed. And when neither TODO nor
10883 DONE are present, add TODO at the beginning of the heading.
10885 With \\[universal-argument] prefix arg, use completion to determine the new \
10886 state.
10887 With numeric prefix arg, switch to that state.
10888 With a double \\[universal-argument] prefix, switch to the next set of TODO \
10889 keywords (nextset).
10890 With a triple \\[universal-argument] prefix, circumvent any state blocking.
10892 For calling through lisp, arg is also interpreted in the following way:
10893 'none -> empty state
10894 \"\"(empty string) -> switch to empty state
10895 'done -> switch to DONE
10896 'nextset -> switch to the next set of keywords
10897 'previousset -> switch to the previous set of keywords
10898 \"WAITING\" -> switch to the specified keyword, but only if it
10899 really is a member of `org-todo-keywords'."
10900 (interactive "P")
10901 (if (equal arg '(16)) (setq arg 'nextset))
10902 (let ((org-blocker-hook org-blocker-hook)
10903 (case-fold-search nil))
10904 (when (equal arg '(64))
10905 (setq arg nil org-blocker-hook nil))
10906 (when (and org-blocker-hook
10907 (or org-inhibit-blocking
10908 (org-entry-get nil "NOBLOCKING")))
10909 (setq org-blocker-hook nil))
10910 (save-excursion
10911 (catch 'exit
10912 (org-back-to-heading t)
10913 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10914 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10915 (looking-at " *"))
10916 (let* ((match-data (match-data))
10917 (startpos (point-at-bol))
10918 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
10919 (org-log-done org-log-done)
10920 (org-log-repeat org-log-repeat)
10921 (org-todo-log-states org-todo-log-states)
10922 (this (match-string 1))
10923 (hl-pos (match-beginning 0))
10924 (head (org-get-todo-sequence-head this))
10925 (ass (assoc head org-todo-kwd-alist))
10926 (interpret (nth 1 ass))
10927 (done-word (nth 3 ass))
10928 (final-done-word (nth 4 ass))
10929 (last-state (or this ""))
10930 (completion-ignore-case t)
10931 (member (member this org-todo-keywords-1))
10932 (tail (cdr member))
10933 (state (cond
10934 ((and org-todo-key-trigger
10935 (or (and (equal arg '(4))
10936 (eq org-use-fast-todo-selection 'prefix))
10937 (and (not arg) org-use-fast-todo-selection
10938 (not (eq org-use-fast-todo-selection
10939 'prefix)))))
10940 ;; Use fast selection
10941 (org-fast-todo-selection))
10942 ((and (equal arg '(4))
10943 (or (not org-use-fast-todo-selection)
10944 (not org-todo-key-trigger)))
10945 ;; Read a state with completion
10946 (org-icompleting-read
10947 "State: " (mapcar (lambda(x) (list x))
10948 org-todo-keywords-1)
10949 nil t))
10950 ((eq arg 'right)
10951 (if this
10952 (if tail (car tail) nil)
10953 (car org-todo-keywords-1)))
10954 ((eq arg 'left)
10955 (if (equal member org-todo-keywords-1)
10957 (if this
10958 (nth (- (length org-todo-keywords-1)
10959 (length tail) 2)
10960 org-todo-keywords-1)
10961 (org-last org-todo-keywords-1))))
10962 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10963 (setq arg nil))) ; hack to fall back to cycling
10964 (arg
10965 ;; user or caller requests a specific state
10966 (cond
10967 ((equal arg "") nil)
10968 ((eq arg 'none) nil)
10969 ((eq arg 'done) (or done-word (car org-done-keywords)))
10970 ((eq arg 'nextset)
10971 (or (car (cdr (member head org-todo-heads)))
10972 (car org-todo-heads)))
10973 ((eq arg 'previousset)
10974 (let ((org-todo-heads (reverse org-todo-heads)))
10975 (or (car (cdr (member head org-todo-heads)))
10976 (car org-todo-heads))))
10977 ((car (member arg org-todo-keywords-1)))
10978 ((stringp arg)
10979 (error "State `%s' not valid in this file" arg))
10980 ((nth (1- (prefix-numeric-value arg))
10981 org-todo-keywords-1))))
10982 ((null member) (or head (car org-todo-keywords-1)))
10983 ((equal this final-done-word) nil) ;; -> make empty
10984 ((null tail) nil) ;; -> first entry
10985 ((memq interpret '(type priority))
10986 (if (eq this-command last-command)
10987 (car tail)
10988 (if (> (length tail) 0)
10989 (or done-word (car org-done-keywords))
10990 nil)))
10992 (car tail))))
10993 (state (or
10994 (run-hook-with-args-until-success
10995 'org-todo-get-default-hook state last-state)
10996 state))
10997 (next (if state (concat " " state " ") " "))
10998 (change-plist (list :type 'todo-state-change :from this :to state
10999 :position startpos))
11000 dolog now-done-p)
11001 (when org-blocker-hook
11002 (setq org-last-todo-state-is-todo
11003 (not (member this org-done-keywords)))
11004 (unless (save-excursion
11005 (save-match-data
11006 (org-with-wide-buffer
11007 (run-hook-with-args-until-failure
11008 'org-blocker-hook change-plist))))
11009 (if (interactive-p)
11010 (error "TODO state change from %s to %s blocked" this state)
11011 ;; fail silently
11012 (message "TODO state change from %s to %s blocked" this state)
11013 (throw 'exit nil))))
11014 (store-match-data match-data)
11015 (replace-match next t t)
11016 (unless (pos-visible-in-window-p hl-pos)
11017 (message "TODO state changed to %s" (org-trim next)))
11018 (unless head
11019 (setq head (org-get-todo-sequence-head state)
11020 ass (assoc head org-todo-kwd-alist)
11021 interpret (nth 1 ass)
11022 done-word (nth 3 ass)
11023 final-done-word (nth 4 ass)))
11024 (when (memq arg '(nextset previousset))
11025 (message "Keyword-Set %d/%d: %s"
11026 (- (length org-todo-sets) -1
11027 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11028 (length org-todo-sets)
11029 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11030 (setq org-last-todo-state-is-todo
11031 (not (member state org-done-keywords)))
11032 (setq now-done-p (and (member state org-done-keywords)
11033 (not (member this org-done-keywords))))
11034 (and logging (org-local-logging logging))
11035 (when (and (or org-todo-log-states org-log-done)
11036 (not (eq org-inhibit-logging t))
11037 (not (memq arg '(nextset previousset))))
11038 ;; we need to look at recording a time and note
11039 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11040 (nth 2 (assoc this org-todo-log-states))))
11041 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11042 (setq dolog 'time))
11043 (when (and state
11044 (member state org-not-done-keywords)
11045 (not (member this org-not-done-keywords)))
11046 ;; This is now a todo state and was not one before
11047 ;; If there was a CLOSED time stamp, get rid of it.
11048 (org-add-planning-info nil nil 'closed))
11049 (when (and now-done-p org-log-done)
11050 ;; It is now done, and it was not done before
11051 (org-add-planning-info 'closed (org-current-time))
11052 (if (and (not dolog) (eq 'note org-log-done))
11053 (org-add-log-setup 'done state this 'findpos 'note)))
11054 (when (and state dolog)
11055 ;; This is a non-nil state, and we need to log it
11056 (org-add-log-setup 'state state this 'findpos dolog)))
11057 ;; Fixup tag positioning
11058 (org-todo-trigger-tag-changes state)
11059 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11060 (when org-provide-todo-statistics
11061 (org-update-parent-todo-statistics))
11062 (run-hooks 'org-after-todo-state-change-hook)
11063 (if (and arg (not (member state org-done-keywords)))
11064 (setq head (org-get-todo-sequence-head state)))
11065 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11066 ;; Do we need to trigger a repeat?
11067 (when now-done-p
11068 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11069 ;; This is for the agenda, take a snapshot of the headline.
11070 (save-match-data
11071 (setq org-agenda-headline-snapshot-before-repeat
11072 (org-get-heading))))
11073 (org-auto-repeat-maybe state))
11074 ;; Fixup cursor location if close to the keyword
11075 (if (and (outline-on-heading-p)
11076 (not (bolp))
11077 (save-excursion (beginning-of-line 1)
11078 (looking-at org-todo-line-regexp))
11079 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11080 (progn
11081 (goto-char (or (match-end 2) (match-end 1)))
11082 (and (looking-at " ") (just-one-space))))
11083 (when org-trigger-hook
11084 (save-excursion
11085 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11087 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11088 "Block turning an entry into a TODO, using the hierarchy.
11089 This checks whether the current task should be blocked from state
11090 changes. Such blocking occurs when:
11092 1. The task has children which are not all in a completed state.
11094 2. A task has a parent with the property :ORDERED:, and there
11095 are siblings prior to the current task with incomplete
11096 status.
11098 3. The parent of the task is blocked because it has siblings that should
11099 be done first, or is child of a block grandparent TODO entry."
11101 (if (not org-enforce-todo-dependencies)
11102 t ; if locally turned off don't block
11103 (catch 'dont-block
11104 ;; If this is not a todo state change, or if this entry is already DONE,
11105 ;; do not block
11106 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11107 (member (plist-get change-plist :from)
11108 (cons 'done org-done-keywords))
11109 (member (plist-get change-plist :to)
11110 (cons 'todo org-not-done-keywords))
11111 (not (plist-get change-plist :to)))
11112 (throw 'dont-block t))
11113 ;; If this task has children, and any are undone, it's blocked
11114 (save-excursion
11115 (org-back-to-heading t)
11116 (let ((this-level (funcall outline-level)))
11117 (outline-next-heading)
11118 (let ((child-level (funcall outline-level)))
11119 (while (and (not (eobp))
11120 (> child-level this-level))
11121 ;; this todo has children, check whether they are all
11122 ;; completed
11123 (if (and (not (org-entry-is-done-p))
11124 (org-entry-is-todo-p))
11125 (throw 'dont-block nil))
11126 (outline-next-heading)
11127 (setq child-level (funcall outline-level))))))
11128 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11129 ;; any previous siblings are undone, it's blocked
11130 (save-excursion
11131 (org-back-to-heading t)
11132 (let* ((pos (point))
11133 (parent-pos (and (org-up-heading-safe) (point))))
11134 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11135 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11136 (forward-line 1)
11137 (re-search-forward org-not-done-heading-regexp pos t))
11138 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11139 ;; Search further up the hierarchy, to see if an anchestor is blocked
11140 (while t
11141 (goto-char parent-pos)
11142 (if (not (looking-at org-not-done-heading-regexp))
11143 (throw 'dont-block t)) ; do not block, parent is not a TODO
11144 (setq pos (point))
11145 (setq parent-pos (and (org-up-heading-safe) (point)))
11146 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11147 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11148 (forward-line 1)
11149 (re-search-forward org-not-done-heading-regexp pos t))
11150 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11152 (defcustom org-track-ordered-property-with-tag nil
11153 "Should the ORDERED property also be shown as a tag?
11154 The ORDERED property decides if an entry should require subtasks to be
11155 completed in sequence. Since a property is not very visible, setting
11156 this option means that toggling the ORDERED property with the command
11157 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11158 not relevant for the behavior, but it makes things more visible.
11160 Note that toggling the tag with tags commands will not change the property
11161 and therefore not influence behavior!
11163 This can be t, meaning the tag ORDERED should be used, It can also be a
11164 string to select a different tag for this task."
11165 :group 'org-todo
11166 :type '(choice
11167 (const :tag "No tracking" nil)
11168 (const :tag "Track with ORDERED tag" t)
11169 (string :tag "Use other tag")))
11171 (defun org-toggle-ordered-property ()
11172 "Toggle the ORDERED property of the current entry.
11173 For better visibility, you can track the value of this property with a tag.
11174 See variable `org-track-ordered-property-with-tag'."
11175 (interactive)
11176 (let* ((t1 org-track-ordered-property-with-tag)
11177 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11178 (save-excursion
11179 (org-back-to-heading)
11180 (if (org-entry-get nil "ORDERED")
11181 (progn
11182 (org-delete-property "ORDERED")
11183 (and tag (org-toggle-tag tag 'off))
11184 (message "Subtasks can be completed in arbitrary order"))
11185 (org-entry-put nil "ORDERED" "t")
11186 (and tag (org-toggle-tag tag 'on))
11187 (message "Subtasks must be completed in sequence")))))
11189 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11190 (defun org-block-todo-from-checkboxes (change-plist)
11191 "Block turning an entry into a TODO, using checkboxes.
11192 This checks whether the current task should be blocked from state
11193 changes because there are unchecked boxes in this entry."
11194 (if (not org-enforce-todo-checkbox-dependencies)
11195 t ; if locally turned off don't block
11196 (catch 'dont-block
11197 ;; If this is not a todo state change, or if this entry is already DONE,
11198 ;; do not block
11199 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11200 (member (plist-get change-plist :from)
11201 (cons 'done org-done-keywords))
11202 (member (plist-get change-plist :to)
11203 (cons 'todo org-not-done-keywords))
11204 (not (plist-get change-plist :to)))
11205 (throw 'dont-block t))
11206 ;; If this task has checkboxes that are not checked, it's blocked
11207 (save-excursion
11208 (org-back-to-heading t)
11209 (let ((beg (point)) end)
11210 (outline-next-heading)
11211 (setq end (point))
11212 (goto-char beg)
11213 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
11214 end t)
11215 (progn
11216 (if (boundp 'org-blocked-by-checkboxes)
11217 (setq org-blocked-by-checkboxes t))
11218 (throw 'dont-block nil)))))
11219 t))) ; do not block
11221 (defun org-entry-blocked-p ()
11222 "Is the current entry blocked?"
11223 (if (org-entry-get nil "NOBLOCKING")
11224 nil ;; Never block this entry
11225 (not
11226 (run-hook-with-args-until-failure
11227 'org-blocker-hook
11228 (list :type 'todo-state-change
11229 :position (point)
11230 :from 'todo
11231 :to 'done)))))
11233 (defun org-update-statistics-cookies (all)
11234 "Update the statistics cookie, either from TODO or from checkboxes.
11235 This should be called with the cursor in a line with a statistics cookie."
11236 (interactive "P")
11237 (if all
11238 (progn
11239 (org-update-checkbox-count 'all)
11240 (org-map-entries 'org-update-parent-todo-statistics))
11241 (if (not (org-on-heading-p))
11242 (org-update-checkbox-count)
11243 (let ((pos (move-marker (make-marker) (point)))
11244 end l1 l2)
11245 (ignore-errors (org-back-to-heading t))
11246 (if (not (org-on-heading-p))
11247 (org-update-checkbox-count)
11248 (setq l1 (org-outline-level))
11249 (setq end (save-excursion
11250 (outline-next-heading)
11251 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11252 (point)))
11253 (if (and (save-excursion
11254 (re-search-forward
11255 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11256 (not (save-excursion (re-search-forward
11257 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11258 (org-update-checkbox-count)
11259 (if (and l2 (> l2 l1))
11260 (progn
11261 (goto-char end)
11262 (org-update-parent-todo-statistics))
11263 (goto-char pos)
11264 (beginning-of-line 1)
11265 (while (re-search-forward
11266 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11267 (point-at-eol) t)
11268 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11269 (goto-char pos)
11270 (move-marker pos nil)))))
11272 (defvar org-entry-property-inherited-from) ;; defined below
11273 (defun org-update-parent-todo-statistics ()
11274 "Update any statistics cookie in the parent of the current headline.
11275 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11276 the entire subtree and this will travel up the hierarchy and update
11277 statistics everywhere."
11278 (interactive)
11279 (let* ((lim 0) prop
11280 (recursive (or (not org-hierarchical-todo-statistics)
11281 (string-match
11282 "\\<recursive\\>"
11283 (or (setq prop (org-entry-get
11284 nil "COOKIE_DATA" 'inherit)) ""))))
11285 (lim (or (and prop (marker-position
11286 org-entry-property-inherited-from))
11287 lim))
11288 (first t)
11289 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11290 level ltoggle l1 new ndel
11291 (cnt-all 0) (cnt-done 0) is-percent kwd
11292 checkbox-beg ov ovs ove cookie-present)
11293 (catch 'exit
11294 (save-excursion
11295 (beginning-of-line 1)
11296 (if (org-at-heading-p)
11297 (setq ltoggle (funcall outline-level))
11298 (error "This should not happen"))
11299 (while (and (setq level (org-up-heading-safe))
11300 (or recursive first)
11301 (>= (point) lim))
11302 (setq first nil cookie-present nil)
11303 (unless (and level
11304 (not (string-match
11305 "\\<checkbox\\>"
11306 (downcase
11307 (or (org-entry-get
11308 nil "COOKIE_DATA")
11309 "")))))
11310 (throw 'exit nil))
11311 (while (re-search-forward box-re (point-at-eol) t)
11312 (setq cnt-all 0 cnt-done 0 cookie-present t)
11313 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11314 (save-match-data
11315 (unless (outline-next-heading) (throw 'exit nil))
11316 (while (and (looking-at org-complex-heading-regexp)
11317 (> (setq l1 (length (match-string 1))) level))
11318 (setq kwd (and (or recursive (= l1 ltoggle))
11319 (match-string 2)))
11320 (if (or (eq org-provide-todo-statistics 'all-headlines)
11321 (and (listp org-provide-todo-statistics)
11322 (or (member kwd org-provide-todo-statistics)
11323 (member kwd org-done-keywords))))
11324 (setq cnt-all (1+ cnt-all))
11325 (if (eq org-provide-todo-statistics t)
11326 (and kwd (setq cnt-all (1+ cnt-all)))))
11327 (and (member kwd org-done-keywords)
11328 (setq cnt-done (1+ cnt-done)))
11329 (outline-next-heading)))
11330 (setq new
11331 (if is-percent
11332 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11333 (format "[%d/%d]" cnt-done cnt-all))
11334 ndel (- (match-end 0) checkbox-beg))
11335 ;; handle overlays when updating cookie from column view
11336 (when (setq ov (car (overlays-at checkbox-beg)))
11337 (setq ovs (overlay-start ov) ove (overlay-end ov))
11338 (delete-overlay ov))
11339 (goto-char checkbox-beg)
11340 (insert new)
11341 (delete-region (point) (+ (point) ndel))
11342 (when ov (move-overlay ov ovs ove)))
11343 (when cookie-present
11344 (run-hook-with-args 'org-after-todo-statistics-hook
11345 cnt-done (- cnt-all cnt-done))))))
11346 (run-hooks 'org-todo-statistics-hook)))
11348 (defvar org-after-todo-statistics-hook nil
11349 "Hook that is called after a TODO statistics cookie has been updated.
11350 Each function is called with two arguments: the number of not-done entries
11351 and the number of done entries.
11353 For example, the following function, when added to this hook, will switch
11354 an entry to DONE when all children are done, and back to TODO when new
11355 entries are set to a TODO status. Note that this hook is only called
11356 when there is a statistics cookie in the headline!
11358 (defun org-summary-todo (n-done n-not-done)
11359 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11360 (let (org-log-done org-log-states) ; turn off logging
11361 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11364 (defvar org-todo-statistics-hook nil
11365 "Hook that is run whenever Org thinks TODO statistics should be updated.
11366 This hook runs even if there is no statistics cookie present, in which case
11367 `org-after-todo-statistics-hook' would not run.")
11369 (defun org-todo-trigger-tag-changes (state)
11370 "Apply the changes defined in `org-todo-state-tags-triggers'."
11371 (let ((l org-todo-state-tags-triggers)
11372 changes)
11373 (when (or (not state) (equal state ""))
11374 (setq changes (append changes (cdr (assoc "" l)))))
11375 (when (and (stringp state) (> (length state) 0))
11376 (setq changes (append changes (cdr (assoc state l)))))
11377 (when (member state org-not-done-keywords)
11378 (setq changes (append changes (cdr (assoc 'todo l)))))
11379 (when (member state org-done-keywords)
11380 (setq changes (append changes (cdr (assoc 'done l)))))
11381 (dolist (c changes)
11382 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11384 (defun org-local-logging (value)
11385 "Get logging settings from a property VALUE."
11386 (let* (words w a)
11387 ;; directly set the variables, they are already local.
11388 (setq org-log-done nil
11389 org-log-repeat nil
11390 org-todo-log-states nil)
11391 (setq words (org-split-string value))
11392 (while (setq w (pop words))
11393 (cond
11394 ((setq a (assoc w org-startup-options))
11395 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11396 (set (nth 1 a) (nth 2 a))))
11397 ((setq a (org-extract-log-state-settings w))
11398 (and (member (car a) org-todo-keywords-1)
11399 (push a org-todo-log-states)))))))
11401 (defun org-get-todo-sequence-head (kwd)
11402 "Return the head of the TODO sequence to which KWD belongs.
11403 If KWD is not set, check if there is a text property remembering the
11404 right sequence."
11405 (let (p)
11406 (cond
11407 ((not kwd)
11408 (or (get-text-property (point-at-bol) 'org-todo-head)
11409 (progn
11410 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11411 nil (point-at-eol)))
11412 (get-text-property p 'org-todo-head))))
11413 ((not (member kwd org-todo-keywords-1))
11414 (car org-todo-keywords-1))
11415 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11417 (defun org-fast-todo-selection ()
11418 "Fast TODO keyword selection with single keys.
11419 Returns the new TODO keyword, or nil if no state change should occur."
11420 (let* ((fulltable org-todo-key-alist)
11421 (done-keywords org-done-keywords) ;; needed for the faces.
11422 (maxlen (apply 'max (mapcar
11423 (lambda (x)
11424 (if (stringp (car x)) (string-width (car x)) 0))
11425 fulltable)))
11426 (expert nil)
11427 (fwidth (+ maxlen 3 1 3))
11428 (ncol (/ (- (window-width) 4) fwidth))
11429 tg cnt e c tbl
11430 groups ingroup)
11431 (save-excursion
11432 (save-window-excursion
11433 (if expert
11434 (set-buffer (get-buffer-create " *Org todo*"))
11435 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11436 (erase-buffer)
11437 (org-set-local 'org-done-keywords done-keywords)
11438 (setq tbl fulltable cnt 0)
11439 (while (setq e (pop tbl))
11440 (cond
11441 ((equal e '(:startgroup))
11442 (push '() groups) (setq ingroup t)
11443 (when (not (= cnt 0))
11444 (setq cnt 0)
11445 (insert "\n"))
11446 (insert "{ "))
11447 ((equal e '(:endgroup))
11448 (setq ingroup nil cnt 0)
11449 (insert "}\n"))
11450 ((equal e '(:newline))
11451 (when (not (= cnt 0))
11452 (setq cnt 0)
11453 (insert "\n")
11454 (setq e (car tbl))
11455 (while (equal (car tbl) '(:newline))
11456 (insert "\n")
11457 (setq tbl (cdr tbl)))))
11459 (setq tg (car e) c (cdr e))
11460 (if ingroup (push tg (car groups)))
11461 (setq tg (org-add-props tg nil 'face
11462 (org-get-todo-face tg)))
11463 (if (and (= cnt 0) (not ingroup)) (insert " "))
11464 (insert "[" c "] " tg (make-string
11465 (- fwidth 4 (length tg)) ?\ ))
11466 (when (= (setq cnt (1+ cnt)) ncol)
11467 (insert "\n")
11468 (if ingroup (insert " "))
11469 (setq cnt 0)))))
11470 (insert "\n")
11471 (goto-char (point-min))
11472 (if (not expert) (org-fit-window-to-buffer))
11473 (message "[a-z..]:Set [SPC]:clear")
11474 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11475 (cond
11476 ((or (= c ?\C-g)
11477 (and (= c ?q) (not (rassoc c fulltable))))
11478 (setq quit-flag t))
11479 ((= c ?\ ) nil)
11480 ((setq e (rassoc c fulltable) tg (car e))
11482 (t (setq quit-flag t)))))))
11484 (defun org-entry-is-todo-p ()
11485 (member (org-get-todo-state) org-not-done-keywords))
11487 (defun org-entry-is-done-p ()
11488 (member (org-get-todo-state) org-done-keywords))
11490 (defun org-get-todo-state ()
11491 (save-excursion
11492 (org-back-to-heading t)
11493 (and (looking-at org-todo-line-regexp)
11494 (match-end 2)
11495 (match-string 2))))
11497 (defun org-at-date-range-p (&optional inactive-ok)
11498 "Is the cursor inside a date range?"
11499 (interactive)
11500 (save-excursion
11501 (catch 'exit
11502 (let ((pos (point)))
11503 (skip-chars-backward "^[<\r\n")
11504 (skip-chars-backward "<[")
11505 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11506 (>= (match-end 0) pos)
11507 (throw 'exit t))
11508 (skip-chars-backward "^<[\r\n")
11509 (skip-chars-backward "<[")
11510 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11511 (>= (match-end 0) pos)
11512 (throw 'exit t)))
11513 nil)))
11515 (defun org-get-repeat (&optional tagline)
11516 "Check if there is a deadline/schedule with repeater in this entry."
11517 (save-match-data
11518 (save-excursion
11519 (org-back-to-heading t)
11520 (and (re-search-forward (if tagline
11521 (concat tagline "\\s-*" org-repeat-re)
11522 org-repeat-re)
11523 (org-entry-end-position) t)
11524 (match-string-no-properties 1)))))
11526 (defvar org-last-changed-timestamp)
11527 (defvar org-last-inserted-timestamp)
11528 (defvar org-log-post-message)
11529 (defvar org-log-note-purpose)
11530 (defvar org-log-note-how)
11531 (defvar org-log-note-extra)
11532 (defun org-auto-repeat-maybe (done-word)
11533 "Check if the current headline contains a repeated deadline/schedule.
11534 If yes, set TODO state back to what it was and change the base date
11535 of repeating deadline/scheduled time stamps to new date.
11536 This function is run automatically after each state change to a DONE state."
11537 ;; last-state is dynamically scoped into this function
11538 (let* ((repeat (org-get-repeat))
11539 (aa (assoc last-state org-todo-kwd-alist))
11540 (interpret (nth 1 aa))
11541 (head (nth 2 aa))
11542 (whata '(("d" . day) ("m" . month) ("y" . year)))
11543 (msg "Entry repeats: ")
11544 (org-log-done nil)
11545 (org-todo-log-states nil)
11546 re type n what ts time to-state)
11547 (when repeat
11548 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11549 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11550 org-todo-repeat-to-state))
11551 (unless (and to-state (member to-state org-todo-keywords-1))
11552 (setq to-state (if (eq interpret 'type) last-state head)))
11553 (org-todo to-state)
11554 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11555 (org-entry-put nil "LAST_REPEAT" (format-time-string
11556 (org-time-stamp-format t t))))
11557 (when org-log-repeat
11558 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11559 (memq 'org-add-log-note post-command-hook))
11560 ;; OK, we are already setup for some record
11561 (if (eq org-log-repeat 'note)
11562 ;; make sure we take a note, not only a time stamp
11563 (setq org-log-note-how 'note))
11564 ;; Set up for taking a record
11565 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11566 last-state
11567 'findpos org-log-repeat)))
11568 (org-back-to-heading t)
11569 (org-add-planning-info nil nil 'closed)
11570 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11571 org-deadline-time-regexp "\\)\\|\\("
11572 org-ts-regexp "\\)"))
11573 (while (re-search-forward
11574 re (save-excursion (outline-next-heading) (point)) t)
11575 (setq type (if (match-end 1) org-scheduled-string
11576 (if (match-end 3) org-deadline-string "Plain:"))
11577 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11578 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11579 (setq n (string-to-number (match-string 2 ts))
11580 what (match-string 3 ts))
11581 (if (equal what "w") (setq n (* n 7) what "d"))
11582 ;; Preparation, see if we need to modify the start date for the change
11583 (when (match-end 1)
11584 (setq time (save-match-data (org-time-string-to-time ts)))
11585 (cond
11586 ((equal (match-string 1 ts) ".")
11587 ;; Shift starting date to today
11588 (org-timestamp-change
11589 (- (time-to-days (current-time)) (time-to-days time))
11590 'day))
11591 ((equal (match-string 1 ts) "+")
11592 (let ((nshiftmax 10) (nshift 0))
11593 (while (or (= nshift 0)
11594 (<= (time-to-days time)
11595 (time-to-days (current-time))))
11596 (when (= (incf nshift) nshiftmax)
11597 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11598 (error "Abort")))
11599 (org-timestamp-change n (cdr (assoc what whata)))
11600 (org-at-timestamp-p t)
11601 (setq ts (match-string 1))
11602 (setq time (save-match-data (org-time-string-to-time ts)))))
11603 (org-timestamp-change (- n) (cdr (assoc what whata)))
11604 ;; rematch, so that we have everything in place for the real shift
11605 (org-at-timestamp-p t)
11606 (setq ts (match-string 1))
11607 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11608 (org-timestamp-change n (cdr (assoc what whata)))
11609 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11610 (setq org-log-post-message msg)
11611 (message "%s" msg))))
11613 (defun org-show-todo-tree (arg)
11614 "Make a compact tree which shows all headlines marked with TODO.
11615 The tree will show the lines where the regexp matches, and all higher
11616 headlines above the match.
11617 With a \\[universal-argument] prefix, prompt for a regexp to match.
11618 With a numeric prefix N, construct a sparse tree for the Nth element
11619 of `org-todo-keywords-1'."
11620 (interactive "P")
11621 (let ((case-fold-search nil)
11622 (kwd-re
11623 (cond ((null arg) org-not-done-regexp)
11624 ((equal arg '(4))
11625 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11626 (mapcar 'list org-todo-keywords-1))))
11627 (concat "\\("
11628 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11629 "\\)\\>")))
11630 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11631 (regexp-quote (nth (1- (prefix-numeric-value arg))
11632 org-todo-keywords-1)))
11633 (t (error "Invalid prefix argument: %s" arg)))))
11634 (message "%d TODO entries found"
11635 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
11637 (defun org-deadline (&optional remove time)
11638 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11639 With argument REMOVE, remove any deadline from the item.
11640 When TIME is set, it should be an internal time specification, and the
11641 scheduling will use the corresponding date."
11642 (interactive "P")
11643 (let* ((old-date (org-entry-get nil "DEADLINE"))
11644 (repeater (and old-date
11645 (string-match
11646 "\\([.+]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11647 old-date)
11648 (match-string 1 old-date))))
11649 (if remove
11650 (progn
11651 (when (and old-date org-log-redeadline)
11652 (org-add-log-setup 'deldeadline nil old-date 'findpos
11653 org-log-redeadline))
11654 (org-remove-timestamp-with-keyword org-deadline-string)
11655 (message "Item no longer has a deadline."))
11656 (org-add-planning-info 'deadline time 'closed)
11657 (when (and old-date org-log-redeadline
11658 (not (equal old-date
11659 (substring org-last-inserted-timestamp 1 -1))))
11660 (org-add-log-setup 'redeadline nil old-date 'findpos
11661 org-log-redeadline))
11662 (when repeater
11663 (save-excursion
11664 (org-back-to-heading t)
11665 (when (re-search-forward (concat org-deadline-string " "
11666 org-last-inserted-timestamp)
11667 (save-excursion
11668 (outline-next-heading) (point)) t)
11669 (goto-char (1- (match-end 0)))
11670 (insert " " repeater)
11671 (setq org-last-inserted-timestamp
11672 (concat (substring org-last-inserted-timestamp 0 -1)
11673 " " repeater
11674 (substring org-last-inserted-timestamp -1))))))
11675 (message "Deadline on %s" org-last-inserted-timestamp))))
11677 (defun org-schedule (&optional remove time)
11678 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11679 With argument REMOVE, remove any scheduling date from the item.
11680 When TIME is set, it should be an internal time specification, and the
11681 scheduling will use the corresponding date."
11682 (interactive "P")
11683 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11684 (repeater (and old-date
11685 (string-match
11686 "\\([.+]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11687 old-date)
11688 (match-string 1 old-date))))
11689 (if remove
11690 (progn
11691 (when (and old-date org-log-reschedule)
11692 (org-add-log-setup 'delschedule nil old-date 'findpos
11693 org-log-reschedule))
11694 (org-remove-timestamp-with-keyword org-scheduled-string)
11695 (message "Item is no longer scheduled."))
11696 (org-add-planning-info 'scheduled time 'closed)
11697 (when (and old-date org-log-reschedule
11698 (not (equal old-date
11699 (substring org-last-inserted-timestamp 1 -1))))
11700 (org-add-log-setup 'reschedule nil old-date 'findpos
11701 org-log-reschedule))
11702 (when repeater
11703 (save-excursion
11704 (org-back-to-heading t)
11705 (when (re-search-forward (concat org-scheduled-string " "
11706 org-last-inserted-timestamp)
11707 (save-excursion
11708 (outline-next-heading) (point)) t)
11709 (goto-char (1- (match-end 0)))
11710 (insert " " repeater)
11711 (setq org-last-inserted-timestamp
11712 (concat (substring org-last-inserted-timestamp 0 -1)
11713 " " repeater
11714 (substring org-last-inserted-timestamp -1))))))
11715 (message "Scheduled to %s" org-last-inserted-timestamp))))
11717 (defun org-get-scheduled-time (pom &optional inherit)
11718 "Get the scheduled time as a time tuple, of a format suitable
11719 for calling org-schedule with, or if there is no scheduling,
11720 returns nil."
11721 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11722 (when time
11723 (apply 'encode-time (org-parse-time-string time)))))
11725 (defun org-get-deadline-time (pom &optional inherit)
11726 "Get the deadline as a time tuple, of a format suitable for
11727 calling org-deadline with, or if there is no scheduling, returns
11728 nil."
11729 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11730 (when time
11731 (apply 'encode-time (org-parse-time-string time)))))
11733 (defun org-remove-timestamp-with-keyword (keyword)
11734 "Remove all time stamps with KEYWORD in the current entry."
11735 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11736 beg)
11737 (save-excursion
11738 (org-back-to-heading t)
11739 (setq beg (point))
11740 (outline-next-heading)
11741 (while (re-search-backward re beg t)
11742 (replace-match "")
11743 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11744 (equal (char-before) ?\ ))
11745 (backward-delete-char 1)
11746 (if (string-match "^[ \t]*$" (buffer-substring
11747 (point-at-bol) (point-at-eol)))
11748 (delete-region (point-at-bol)
11749 (min (point-max) (1+ (point-at-eol))))))))))
11751 (defun org-add-planning-info (what &optional time &rest remove)
11752 "Insert new timestamp with keyword in the line directly after the headline.
11753 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11754 If non is given, the user is prompted for a date.
11755 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11756 be removed."
11757 (interactive)
11758 (let (org-time-was-given org-end-time-was-given ts
11759 end default-time default-input)
11761 (catch 'exit
11762 (when (and (not time) (memq what '(scheduled deadline)))
11763 ;; Try to get a default date/time from existing timestamp
11764 (save-excursion
11765 (org-back-to-heading t)
11766 (setq end (save-excursion (outline-next-heading) (point)))
11767 (when (re-search-forward (if (eq what 'scheduled)
11768 org-scheduled-time-regexp
11769 org-deadline-time-regexp)
11770 end t)
11771 (setq ts (match-string 1)
11772 default-time
11773 (apply 'encode-time (org-parse-time-string ts))
11774 default-input (and ts (org-get-compact-tod ts))))))
11775 (when what
11776 ;; If necessary, get the time from the user
11777 (setq time (or time (org-read-date nil 'to-time nil nil
11778 default-time default-input))))
11780 (when (and org-insert-labeled-timestamps-at-point
11781 (member what '(scheduled deadline)))
11782 (insert
11783 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11784 (org-insert-time-stamp time org-time-was-given
11785 nil nil nil (list org-end-time-was-given))
11786 (setq what nil))
11787 (save-excursion
11788 (save-restriction
11789 (let (col list elt ts buffer-invisibility-spec)
11790 (org-back-to-heading t)
11791 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11792 (goto-char (match-end 1))
11793 (setq col (current-column))
11794 (goto-char (match-end 0))
11795 (if (eobp) (insert "\n") (forward-char 1))
11796 (when (and (not what)
11797 (not (looking-at
11798 (concat "[ \t]*"
11799 org-keyword-time-not-clock-regexp))))
11800 ;; Nothing to add, nothing to remove...... :-)
11801 (throw 'exit nil))
11802 (if (and (not (looking-at outline-regexp))
11803 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11804 "[^\r\n]*"))
11805 (not (equal (match-string 1) org-clock-string)))
11806 (narrow-to-region (match-beginning 0) (match-end 0))
11807 (insert-before-markers "\n")
11808 (backward-char 1)
11809 (narrow-to-region (point) (point))
11810 (and org-adapt-indentation (org-indent-to-column col)))
11811 ;; Check if we have to remove something.
11812 (setq list (cons what remove))
11813 (while list
11814 (setq elt (pop list))
11815 (goto-char (point-min))
11816 (when (or (and (eq elt 'scheduled)
11817 (re-search-forward org-scheduled-time-regexp nil t))
11818 (and (eq elt 'deadline)
11819 (re-search-forward org-deadline-time-regexp nil t))
11820 (and (eq elt 'closed)
11821 (re-search-forward org-closed-time-regexp nil t)))
11822 (replace-match "")
11823 (if (looking-at "--+<[^>]+>") (replace-match ""))
11824 (skip-chars-backward " ")
11825 (if (looking-at " +") (replace-match ""))))
11826 (goto-char (point-max))
11827 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11828 (when what
11829 (insert
11830 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11831 (cond ((eq what 'scheduled) org-scheduled-string)
11832 ((eq what 'deadline) org-deadline-string)
11833 ((eq what 'closed) org-closed-string))
11834 " ")
11835 (setq ts (org-insert-time-stamp
11836 time
11837 (or org-time-was-given
11838 (and (eq what 'closed) org-log-done-with-time))
11839 (eq what 'closed)
11840 nil nil (list org-end-time-was-given)))
11841 (end-of-line 1))
11842 (goto-char (point-min))
11843 (widen)
11844 (if (and (looking-at "[ \t]*\n")
11845 (equal (char-before) ?\n))
11846 (delete-region (1- (point)) (point-at-eol)))
11847 ts))))))
11849 (defvar org-log-note-marker (make-marker))
11850 (defvar org-log-note-purpose nil)
11851 (defvar org-log-note-state nil)
11852 (defvar org-log-note-previous-state nil)
11853 (defvar org-log-note-how nil)
11854 (defvar org-log-note-extra nil)
11855 (defvar org-log-note-window-configuration nil)
11856 (defvar org-log-note-return-to (make-marker))
11857 (defvar org-log-post-message nil
11858 "Message to be displayed after a log note has been stored.
11859 The auto-repeater uses this.")
11861 (defun org-add-note ()
11862 "Add a note to the current entry.
11863 This is done in the same way as adding a state change note."
11864 (interactive)
11865 (org-add-log-setup 'note nil nil 'findpos nil))
11867 (defvar org-property-end-re)
11868 (defun org-add-log-setup (&optional purpose state prev-state
11869 findpos how extra)
11870 "Set up the post command hook to take a note.
11871 If this is about to TODO state change, the new state is expected in STATE.
11872 When FINDPOS is non-nil, find the correct position for the note in
11873 the current entry. If not, assume that it can be inserted at point.
11874 HOW is an indicator what kind of note should be created.
11875 EXTRA is additional text that will be inserted into the notes buffer."
11876 (let* ((org-log-into-drawer (org-log-into-drawer))
11877 (drawer (cond ((stringp org-log-into-drawer)
11878 org-log-into-drawer)
11879 (org-log-into-drawer "LOGBOOK")
11880 (t nil))))
11881 (save-restriction
11882 (save-excursion
11883 (when findpos
11884 (org-back-to-heading t)
11885 (narrow-to-region (point) (save-excursion
11886 (outline-next-heading) (point)))
11887 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11888 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11889 "[^\r\n]*\\)?"))
11890 (goto-char (match-end 0))
11891 (cond
11892 (drawer
11893 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11894 nil t)
11895 (progn
11896 (goto-char (match-end 0))
11897 (or org-log-states-order-reversed
11898 (and (re-search-forward org-property-end-re nil t)
11899 (goto-char (1- (match-beginning 0))))))
11900 (insert "\n:" drawer ":\n:END:")
11901 (beginning-of-line 0)
11902 (org-indent-line-function)
11903 (beginning-of-line 2)
11904 (org-indent-line-function)
11905 (end-of-line 0)))
11906 ((and org-log-state-notes-insert-after-drawers
11907 (save-excursion
11908 (forward-line) (looking-at org-drawer-regexp)))
11909 (forward-line)
11910 (while (looking-at org-drawer-regexp)
11911 (goto-char (match-end 0))
11912 (re-search-forward org-property-end-re (point-max) t)
11913 (forward-line))
11914 (forward-line -1)))
11915 (unless org-log-states-order-reversed
11916 (and (= (char-after) ?\n) (forward-char 1))
11917 (org-skip-over-state-notes)
11918 (skip-chars-backward " \t\n\r")))
11919 (move-marker org-log-note-marker (point))
11920 (setq org-log-note-purpose purpose
11921 org-log-note-state state
11922 org-log-note-previous-state prev-state
11923 org-log-note-how how
11924 org-log-note-extra extra)
11925 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11927 (defun org-skip-over-state-notes ()
11928 "Skip past the list of State notes in an entry."
11929 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11930 (when (ignore-errors (goto-char (org-in-item-p)))
11931 (let* ((struct (org-list-struct))
11932 (prevs (org-list-prevs-alist struct)))
11933 (while (looking-at "[ \t]*- State")
11934 (goto-char (or (org-list-get-next-item (point) struct prevs)
11935 (org-list-get-item-end (point) struct)))))))
11937 (defun org-add-log-note (&optional purpose)
11938 "Pop up a window for taking a note, and add this note later at point."
11939 (remove-hook 'post-command-hook 'org-add-log-note)
11940 (setq org-log-note-window-configuration (current-window-configuration))
11941 (delete-other-windows)
11942 (move-marker org-log-note-return-to (point))
11943 (switch-to-buffer (marker-buffer org-log-note-marker))
11944 (goto-char org-log-note-marker)
11945 (org-switch-to-buffer-other-window "*Org Note*")
11946 (erase-buffer)
11947 (if (memq org-log-note-how '(time state))
11948 (let (current-prefix-arg) (org-store-log-note))
11949 (let ((org-inhibit-startup t)) (org-mode))
11950 (insert (format "# Insert note for %s.
11951 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11952 (cond
11953 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11954 ((eq org-log-note-purpose 'done) "closed todo item")
11955 ((eq org-log-note-purpose 'state)
11956 (format "state change from \"%s\" to \"%s\""
11957 (or org-log-note-previous-state "")
11958 (or org-log-note-state "")))
11959 ((eq org-log-note-purpose 'reschedule)
11960 "rescheduling")
11961 ((eq org-log-note-purpose 'delschedule)
11962 "no longer scheduled")
11963 ((eq org-log-note-purpose 'redeadline)
11964 "changing deadline")
11965 ((eq org-log-note-purpose 'deldeadline)
11966 "removing deadline")
11967 ((eq org-log-note-purpose 'refile)
11968 "refiling")
11969 ((eq org-log-note-purpose 'note)
11970 "this entry")
11971 (t (error "This should not happen")))))
11972 (if org-log-note-extra (insert org-log-note-extra))
11973 (org-set-local 'org-finish-function 'org-store-log-note)))
11975 (defvar org-note-abort nil) ; dynamically scoped
11976 (defun org-store-log-note ()
11977 "Finish taking a log note, and insert it to where it belongs."
11978 (let ((txt (buffer-string))
11979 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11980 lines ind bul)
11981 (kill-buffer (current-buffer))
11982 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11983 (setq txt (replace-match "" t t txt)))
11984 (if (string-match "\\s-+\\'" txt)
11985 (setq txt (replace-match "" t t txt)))
11986 (setq lines (org-split-string txt "\n"))
11987 (when (and note (string-match "\\S-" note))
11988 (setq note
11989 (org-replace-escapes
11990 note
11991 (list (cons "%u" (user-login-name))
11992 (cons "%U" user-full-name)
11993 (cons "%t" (format-time-string
11994 (org-time-stamp-format 'long 'inactive)
11995 (current-time)))
11996 (cons "%T" (format-time-string
11997 (org-time-stamp-format 'long nil)
11998 (current-time)))
11999 (cons "%s" (if org-log-note-state
12000 (concat "\"" org-log-note-state "\"")
12001 ""))
12002 (cons "%S" (if org-log-note-previous-state
12003 (concat "\"" org-log-note-previous-state "\"")
12004 "\"\"")))))
12005 (if lines (setq note (concat note " \\\\")))
12006 (push note lines))
12007 (when (or current-prefix-arg org-note-abort)
12008 (when org-log-into-drawer
12009 (org-remove-empty-drawer-at
12010 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12011 org-log-note-marker))
12012 (setq lines nil))
12013 (when lines
12014 (with-current-buffer (marker-buffer org-log-note-marker)
12015 (save-excursion
12016 (goto-char org-log-note-marker)
12017 (move-marker org-log-note-marker nil)
12018 (end-of-line 1)
12019 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12020 (setq ind (save-excursion
12021 (if (ignore-errors (goto-char (org-in-item-p)))
12022 (let ((struct (org-list-struct)))
12023 (org-list-get-ind
12024 (org-list-get-top-point struct) struct))
12025 (skip-chars-backward " \r\t\n")
12026 (cond
12027 ((and (org-at-heading-p)
12028 org-adapt-indentation)
12029 (1+ (org-current-level)))
12030 ((org-at-heading-p) 0)
12031 (t (org-get-indentation))))))
12032 (setq bul (org-list-bullet-string "-"))
12033 (org-indent-line-to ind)
12034 (insert bul (pop lines))
12035 (let ((ind-body (+ (length bul) ind)))
12036 (while lines
12037 (insert "\n")
12038 (org-indent-line-to ind-body)
12039 (insert (pop lines))))
12040 (message "Note stored")
12041 (org-back-to-heading t)
12042 (org-cycle-hide-drawers 'children)))))
12043 (set-window-configuration org-log-note-window-configuration)
12044 (with-current-buffer (marker-buffer org-log-note-return-to)
12045 (goto-char org-log-note-return-to))
12046 (move-marker org-log-note-return-to nil)
12047 (and org-log-post-message (message "%s" org-log-post-message)))
12049 (defun org-remove-empty-drawer-at (drawer pos)
12050 "Remove an empty drawer DRAWER at position POS.
12051 POS may also be a marker."
12052 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12053 (save-excursion
12054 (save-restriction
12055 (widen)
12056 (goto-char pos)
12057 (if (org-in-regexp
12058 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12059 (replace-match ""))))))
12061 (defun org-sparse-tree (&optional arg)
12062 "Create a sparse tree, prompt for the details.
12063 This command can create sparse trees. You first need to select the type
12064 of match used to create the tree:
12066 t Show all TODO entries.
12067 T Show entries with a specific TODO keyword.
12068 m Show entries selected by a tags/property match.
12069 p Enter a property name and its value (both with completion on existing
12070 names/values) and show entries with that property.
12071 r Show entries matching a regular expression (`/' can be used as well)
12072 d Show deadlines due within `org-deadline-warning-days'.
12073 b Show deadlines and scheduled items before a date.
12074 a Show deadlines and scheduled items after a date."
12075 (interactive "P")
12076 (let (ans kwd value)
12077 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12078 (setq ans (read-char-exclusive))
12079 (cond
12080 ((equal ans ?d)
12081 (call-interactively 'org-check-deadlines))
12082 ((equal ans ?b)
12083 (call-interactively 'org-check-before-date))
12084 ((equal ans ?a)
12085 (call-interactively 'org-check-after-date))
12086 ((equal ans ?t)
12087 (org-show-todo-tree nil))
12088 ((equal ans ?T)
12089 (org-show-todo-tree '(4)))
12090 ((member ans '(?T ?m))
12091 (call-interactively 'org-match-sparse-tree))
12092 ((member ans '(?p ?P))
12093 (setq kwd (org-icompleting-read "Property: "
12094 (mapcar 'list (org-buffer-property-keys))))
12095 (setq value (org-icompleting-read "Value: "
12096 (mapcar 'list (org-property-values kwd))))
12097 (unless (string-match "\\`{.*}\\'" value)
12098 (setq value (concat "\"" value "\"")))
12099 (org-match-sparse-tree arg (concat kwd "=" value)))
12100 ((member ans '(?r ?R ?/))
12101 (call-interactively 'org-occur))
12102 (t (error "No such sparse tree command \"%c\"" ans)))))
12104 (defvar org-occur-highlights nil
12105 "List of overlays used for occur matches.")
12106 (make-variable-buffer-local 'org-occur-highlights)
12107 (defvar org-occur-parameters nil
12108 "Parameters of the active org-occur calls.
12109 This is a list, each call to org-occur pushes as cons cell,
12110 containing the regular expression and the callback, onto the list.
12111 The list can contain several entries if `org-occur' has been called
12112 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12113 will only contain one set of parameters. When the highlights are
12114 removed (for example with `C-c C-c', or with the next edit (depending
12115 on `org-remove-highlights-with-change'), this variable is emptied
12116 as well.")
12117 (make-variable-buffer-local 'org-occur-parameters)
12119 (defun org-occur (regexp &optional keep-previous callback)
12120 "Make a compact tree which shows all matches of REGEXP.
12121 The tree will show the lines where the regexp matches, and all higher
12122 headlines above the match. It will also show the heading after the match,
12123 to make sure editing the matching entry is easy.
12124 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12125 call to `org-occur' will be kept, to allow stacking of calls to this
12126 command.
12127 If CALLBACK is non-nil, it is a function which is called to confirm
12128 that the match should indeed be shown."
12129 (interactive "sRegexp: \nP")
12130 (when (equal regexp "")
12131 (error "Regexp cannot be empty"))
12132 (unless keep-previous
12133 (org-remove-occur-highlights nil nil t))
12134 (push (cons regexp callback) org-occur-parameters)
12135 (let ((cnt 0))
12136 (save-excursion
12137 (goto-char (point-min))
12138 (if (or (not keep-previous) ; do not want to keep
12139 (not org-occur-highlights)) ; no previous matches
12140 ;; hide everything
12141 (org-overview))
12142 (while (re-search-forward regexp nil t)
12143 (when (or (not callback)
12144 (save-match-data (funcall callback)))
12145 (setq cnt (1+ cnt))
12146 (when org-highlight-sparse-tree-matches
12147 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12148 (org-show-context 'occur-tree))))
12149 (when org-remove-highlights-with-change
12150 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12151 nil 'local))
12152 (unless org-sparse-tree-open-archived-trees
12153 (org-hide-archived-subtrees (point-min) (point-max)))
12154 (run-hooks 'org-occur-hook)
12155 (if (interactive-p)
12156 (message "%d match(es) for regexp %s" cnt regexp))
12157 cnt))
12159 (defun org-occur-next-match (&optional n reset)
12160 "Function for `next-error-function' to find sparse tree matches.
12161 N is the number of matches to move, when negative move backwards.
12162 RESET is entirely ignored - this function always goes back to the
12163 starting point when no match is found."
12164 (let* ((limit (if (< n 0) (point-min) (point-max)))
12165 (search-func (if (< n 0)
12166 'previous-single-char-property-change
12167 'next-single-char-property-change))
12168 (n (abs n))
12169 (pos (point))
12171 (catch 'exit
12172 (while (setq p1 (funcall search-func (point) 'org-type))
12173 (when (equal p1 limit)
12174 (goto-char pos)
12175 (error "No more matches"))
12176 (when (equal (get-char-property p1 'org-type) 'org-occur)
12177 (setq n (1- n))
12178 (when (= n 0)
12179 (goto-char p1)
12180 (throw 'exit (point))))
12181 (goto-char p1))
12182 (goto-char p1)
12183 (error "No more matches"))))
12185 (defun org-show-context (&optional key)
12186 "Make sure point and context are visible.
12187 How much context is shown depends upon the variables
12188 `org-show-hierarchy-above', `org-show-following-heading'. and
12189 `org-show-siblings'."
12190 (let ((heading-p (org-on-heading-p t))
12191 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12192 (following-p (org-get-alist-option org-show-following-heading key))
12193 (entry-p (org-get-alist-option org-show-entry-below key))
12194 (siblings-p (org-get-alist-option org-show-siblings key)))
12195 (catch 'exit
12196 ;; Show heading or entry text
12197 (if (and heading-p (not entry-p))
12198 (org-flag-heading nil) ; only show the heading
12199 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12200 (org-show-hidden-entry))) ; show entire entry
12201 (when following-p
12202 ;; Show next sibling, or heading below text
12203 (save-excursion
12204 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12205 (org-flag-heading nil))))
12206 (when siblings-p (org-show-siblings))
12207 (when hierarchy-p
12208 ;; show all higher headings, possibly with siblings
12209 (save-excursion
12210 (while (and (condition-case nil
12211 (progn (org-up-heading-all 1) t)
12212 (error nil))
12213 (not (bobp)))
12214 (org-flag-heading nil)
12215 (when siblings-p (org-show-siblings))))))))
12217 (defvar org-reveal-start-hook nil
12218 "Hook run before revealing a location.")
12220 (defun org-reveal (&optional siblings)
12221 "Show current entry, hierarchy above it, and the following headline.
12222 This can be used to show a consistent set of context around locations
12223 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12224 not t for the search context.
12226 With optional argument SIBLINGS, on each level of the hierarchy all
12227 siblings are shown. This repairs the tree structure to what it would
12228 look like when opened with hierarchical calls to `org-cycle'.
12229 With double optional argument \\[universal-argument] \\[universal-argument], \
12230 go to the parent and show the
12231 entire tree."
12232 (interactive "P")
12233 (run-hooks 'org-reveal-start-hook)
12234 (let ((org-show-hierarchy-above t)
12235 (org-show-following-heading t)
12236 (org-show-siblings (if siblings t org-show-siblings)))
12237 (org-show-context nil))
12238 (when (equal siblings '(16))
12239 (save-excursion
12240 (when (org-up-heading-safe)
12241 (org-show-subtree)
12242 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12244 (defun org-highlight-new-match (beg end)
12245 "Highlight from BEG to END and mark the highlight is an occur headline."
12246 (let ((ov (make-overlay beg end)))
12247 (overlay-put ov 'face 'secondary-selection)
12248 (overlay-put ov 'org-type 'org-occur)
12249 (push ov org-occur-highlights)))
12251 (defun org-remove-occur-highlights (&optional beg end noremove)
12252 "Remove the occur highlights from the buffer.
12253 BEG and END are ignored. If NOREMOVE is nil, remove this function
12254 from the `before-change-functions' in the current buffer."
12255 (interactive)
12256 (unless org-inhibit-highlight-removal
12257 (mapc 'delete-overlay org-occur-highlights)
12258 (setq org-occur-highlights nil)
12259 (setq org-occur-parameters nil)
12260 (unless noremove
12261 (remove-hook 'before-change-functions
12262 'org-remove-occur-highlights 'local))))
12264 ;;;; Priorities
12266 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12267 "Regular expression matching the priority indicator.")
12269 (defvar org-remove-priority-next-time nil)
12271 (defun org-priority-up ()
12272 "Increase the priority of the current item."
12273 (interactive)
12274 (org-priority 'up))
12276 (defun org-priority-down ()
12277 "Decrease the priority of the current item."
12278 (interactive)
12279 (org-priority 'down))
12281 (defun org-priority (&optional action)
12282 "Change the priority of an item by ARG.
12283 ACTION can be `set', `up', `down', or a character."
12284 (interactive)
12285 (unless org-enable-priority-commands
12286 (error "Priority commands are disabled"))
12287 (setq action (or action 'set))
12288 (let (current new news have remove)
12289 (save-excursion
12290 (org-back-to-heading t)
12291 (if (looking-at org-priority-regexp)
12292 (setq current (string-to-char (match-string 2))
12293 have t))
12294 (cond
12295 ((eq action 'remove)
12296 (setq remove t new ?\ ))
12297 ((or (eq action 'set)
12298 (if (featurep 'xemacs) (characterp action) (integerp action)))
12299 (if (not (eq action 'set))
12300 (setq new action)
12301 (message "Priority %c-%c, SPC to remove: "
12302 org-highest-priority org-lowest-priority)
12303 (save-match-data
12304 (setq new (read-char-exclusive))))
12305 (if (and (= (upcase org-highest-priority) org-highest-priority)
12306 (= (upcase org-lowest-priority) org-lowest-priority))
12307 (setq new (upcase new)))
12308 (cond ((equal new ?\ ) (setq remove t))
12309 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12310 (error "Priority must be between `%c' and `%c'"
12311 org-highest-priority org-lowest-priority))))
12312 ((eq action 'up)
12313 (setq new (if have
12314 (1- current) ; normal cycling
12315 ;; last priority was empty
12316 (if (eq last-command this-command)
12317 org-lowest-priority ; wrap around empty to lowest
12318 ;; default
12319 (if org-priority-start-cycle-with-default
12320 org-default-priority
12321 (1- org-default-priority))))))
12322 ((eq action 'down)
12323 (setq new (if have
12324 (1+ current) ; normal cycling
12325 ;; last priority was empty
12326 (if (eq last-command this-command)
12327 org-highest-priority ; wrap around empty to highest
12328 ;; default
12329 (if org-priority-start-cycle-with-default
12330 org-default-priority
12331 (1+ org-default-priority))))))
12332 (t (error "Invalid action")))
12333 (if (or (< (upcase new) org-highest-priority)
12334 (> (upcase new) org-lowest-priority))
12335 (if (and (memq action '(up down))
12336 (not have) (not (eq last-command this-command)))
12337 ;; `new' is from default priority
12338 (error
12339 "The default can not be set, see `org-default-priority' why")
12340 ;; normal cycling: `new' is beyond highest/lowest priority
12341 ;; and is wrapped around to the empty priority
12342 (setq remove t)))
12343 (setq news (format "%c" new))
12344 (if have
12345 (if remove
12346 (replace-match "" t t nil 1)
12347 (replace-match news t t nil 2))
12348 (if remove
12349 (error "No priority cookie found in line")
12350 (let ((case-fold-search nil))
12351 (looking-at org-todo-line-regexp))
12352 (if (match-end 2)
12353 (progn
12354 (goto-char (match-end 2))
12355 (insert " [#" news "]"))
12356 (goto-char (match-beginning 3))
12357 (insert "[#" news "] "))))
12358 (org-preserve-lc (org-set-tags nil 'align)))
12359 (if remove
12360 (message "Priority removed")
12361 (message "Priority of current item set to %s" news))))
12363 (defun org-get-priority (s)
12364 "Find priority cookie and return priority."
12365 (if (functionp org-get-priority-function)
12366 (funcall org-get-priority-function)
12367 (save-match-data
12368 (if (not (string-match org-priority-regexp s))
12369 (* 1000 (- org-lowest-priority org-default-priority))
12370 (* 1000 (- org-lowest-priority
12371 (string-to-char (match-string 2 s))))))))
12373 ;;;; Tags
12375 (defvar org-agenda-archives-mode)
12376 (defvar org-map-continue-from nil
12377 "Position from where mapping should continue.
12378 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12380 (defvar org-scanner-tags nil
12381 "The current tag list while the tags scanner is running.")
12382 (defvar org-trust-scanner-tags nil
12383 "Should `org-get-tags-at' use the tags for the scanner.
12384 This is for internal dynamical scoping only.
12385 When this is non-nil, the function `org-get-tags-at' will return the value
12386 of `org-scanner-tags' instead of building the list by itself. This
12387 can lead to large speed-ups when the tags scanner is used in a file with
12388 many entries, and when the list of tags is retrieved, for example to
12389 obtain a list of properties. Building the tags list for each entry in such
12390 a file becomes an N^2 operation - but with this variable set, it scales
12391 as N.")
12393 (defun org-scan-tags (action matcher &optional todo-only)
12394 "Scan headline tags with inheritance and produce output ACTION.
12396 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12397 or `agenda' to produce an entry list for an agenda view. It can also be
12398 a Lisp form or a function that should be called at each matched headline, in
12399 this case the return value is a list of all return values from these calls.
12401 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12402 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12403 only lines with a TODO keyword are included in the output."
12404 (require 'org-agenda)
12405 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
12406 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12407 (org-re
12408 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12409 (props (list 'face 'default
12410 'done-face 'org-agenda-done
12411 'undone-face 'default
12412 'mouse-face 'highlight
12413 'org-not-done-regexp org-not-done-regexp
12414 'org-todo-regexp org-todo-regexp
12415 'help-echo
12416 (format "mouse-2 or RET jump to org file %s"
12417 (abbreviate-file-name
12418 (or (buffer-file-name (buffer-base-buffer))
12419 (buffer-name (buffer-base-buffer)))))))
12420 (case-fold-search nil)
12421 (org-map-continue-from nil)
12422 lspos tags tags-list
12423 (tags-alist (list (cons 0 org-file-tags)))
12424 (llast 0) rtn rtn1 level category i txt
12425 todo marker entry priority)
12426 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12427 (setq action (list 'lambda nil action)))
12428 (save-excursion
12429 (goto-char (point-min))
12430 (when (eq action 'sparse-tree)
12431 (org-overview)
12432 (org-remove-occur-highlights))
12433 (while (re-search-forward re nil t)
12434 (catch :skip
12435 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12436 tags (if (match-end 4) (org-match-string-no-properties 4)))
12437 (goto-char (setq lspos (match-beginning 0)))
12438 (setq level (org-reduced-level (funcall outline-level))
12439 category (org-get-category))
12440 (setq i llast llast level)
12441 ;; remove tag lists from same and sublevels
12442 (while (>= i level)
12443 (when (setq entry (assoc i tags-alist))
12444 (setq tags-alist (delete entry tags-alist)))
12445 (setq i (1- i)))
12446 ;; add the next tags
12447 (when tags
12448 (setq tags (org-split-string tags ":")
12449 tags-alist
12450 (cons (cons level tags) tags-alist)))
12451 ;; compile tags for current headline
12452 (setq tags-list
12453 (if org-use-tag-inheritance
12454 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12455 tags)
12456 org-scanner-tags tags-list)
12457 (when org-use-tag-inheritance
12458 (setcdr (car tags-alist)
12459 (mapcar (lambda (x)
12460 (setq x (copy-sequence x))
12461 (org-add-prop-inherited x))
12462 (cdar tags-alist))))
12463 (when (and tags org-use-tag-inheritance
12464 (or (not (eq t org-use-tag-inheritance))
12465 org-tags-exclude-from-inheritance))
12466 ;; selective inheritance, remove uninherited ones
12467 (setcdr (car tags-alist)
12468 (org-remove-uninherited-tags (cdar tags-alist))))
12469 (when (and
12471 ;; eval matcher only when the todo condition is OK
12472 (and (or (not todo-only) (member todo org-not-done-keywords))
12473 (let ((case-fold-search t)) (eval matcher)))
12475 ;; Call the skipper, but return t if it does not skip,
12476 ;; so that the `and' form continues evaluating
12477 (progn
12478 (unless (eq action 'sparse-tree) (org-agenda-skip))
12481 ;; Check if timestamps are deselecting this entry
12482 (or (not todo-only)
12483 (and (member todo org-not-done-keywords)
12484 (or (not org-agenda-tags-todo-honor-ignore-options)
12485 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12487 ;; Extra check for the archive tag
12488 ;; FIXME: Does the skipper already do this????
12490 (not (member org-archive-tag tags-list))
12491 ;; we have an archive tag, should we use this anyway?
12492 (or (not org-agenda-skip-archived-trees)
12493 (and (eq action 'agenda) org-agenda-archives-mode))))
12495 ;; select this headline
12497 (cond
12498 ((eq action 'sparse-tree)
12499 (and org-highlight-sparse-tree-matches
12500 (org-get-heading) (match-end 0)
12501 (org-highlight-new-match
12502 (match-beginning 0) (match-beginning 1)))
12503 (org-show-context 'tags-tree))
12504 ((eq action 'agenda)
12505 (setq txt (org-format-agenda-item
12507 (concat
12508 (if (eq org-tags-match-list-sublevels 'indented)
12509 (make-string (1- level) ?.) "")
12510 (org-get-heading))
12511 category
12512 tags-list
12514 priority (org-get-priority txt))
12515 (goto-char lspos)
12516 (setq marker (org-agenda-new-marker))
12517 (org-add-props txt props
12518 'org-marker marker 'org-hd-marker marker 'org-category category
12519 'todo-state todo
12520 'priority priority 'type "tagsmatch")
12521 (push txt rtn))
12522 ((functionp action)
12523 (setq org-map-continue-from nil)
12524 (save-excursion
12525 (setq rtn1 (funcall action))
12526 (push rtn1 rtn)))
12527 (t (error "Invalid action")))
12529 ;; if we are to skip sublevels, jump to end of subtree
12530 (unless org-tags-match-list-sublevels
12531 (org-end-of-subtree t)
12532 (backward-char 1))))
12533 ;; Get the correct position from where to continue
12534 (if org-map-continue-from
12535 (goto-char org-map-continue-from)
12536 (and (= (point) lspos) (end-of-line 1)))))
12537 (when (and (eq action 'sparse-tree)
12538 (not org-sparse-tree-open-archived-trees))
12539 (org-hide-archived-subtrees (point-min) (point-max)))
12540 (nreverse rtn)))
12542 (defun org-remove-uninherited-tags (tags)
12543 "Remove all tags that are not inherited from the list TAGS."
12544 (cond
12545 ((eq org-use-tag-inheritance t)
12546 (if org-tags-exclude-from-inheritance
12547 (org-delete-all org-tags-exclude-from-inheritance tags)
12548 tags))
12549 ((not org-use-tag-inheritance) nil)
12550 ((stringp org-use-tag-inheritance)
12551 (delq nil (mapcar
12552 (lambda (x)
12553 (if (and (string-match org-use-tag-inheritance x)
12554 (not (member x org-tags-exclude-from-inheritance)))
12555 x nil))
12556 tags)))
12557 ((listp org-use-tag-inheritance)
12558 (delq nil (mapcar
12559 (lambda (x)
12560 (if (member x org-use-tag-inheritance) x nil))
12561 tags)))))
12563 (defvar todo-only) ;; dynamically scoped
12565 (defun org-match-sparse-tree (&optional todo-only match)
12566 "Create a sparse tree according to tags string MATCH.
12567 MATCH can contain positive and negative selection of tags, like
12568 \"+WORK+URGENT-WITHBOSS\".
12569 If optional argument TODO-ONLY is non-nil, only select lines that are
12570 also TODO lines."
12571 (interactive "P")
12572 (org-prepare-agenda-buffers (list (current-buffer)))
12573 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12575 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12577 (defvar org-cached-props nil)
12578 (defun org-cached-entry-get (pom property)
12579 (if (or (eq t org-use-property-inheritance)
12580 (and (stringp org-use-property-inheritance)
12581 (string-match org-use-property-inheritance property))
12582 (and (listp org-use-property-inheritance)
12583 (member property org-use-property-inheritance)))
12584 ;; Caching is not possible, check it directly
12585 (org-entry-get pom property 'inherit)
12586 ;; Get all properties, so that we can do complicated checks easily
12587 (cdr (assoc property (or org-cached-props
12588 (setq org-cached-props
12589 (org-entry-properties pom)))))))
12591 (defun org-global-tags-completion-table (&optional files)
12592 "Return the list of all tags in all agenda buffer/files.
12593 Optional FILES argument is a list of files to which can be used
12594 instead of the agenda files."
12595 (save-excursion
12596 (org-uniquify
12597 (delq nil
12598 (apply 'append
12599 (mapcar
12600 (lambda (file)
12601 (set-buffer (find-file-noselect file))
12602 (append (org-get-buffer-tags)
12603 (mapcar (lambda (x) (if (stringp (car-safe x))
12604 (list (car-safe x)) nil))
12605 org-tag-alist)))
12606 (if (and files (car files))
12607 files
12608 (org-agenda-files))))))))
12610 (defun org-make-tags-matcher (match)
12611 "Create the TAGS/TODO matcher form for the selection string MATCH."
12612 ;; todo-only is scoped dynamically into this function, and the function
12613 ;; may change it if the matcher asks for it.
12614 (unless match
12615 ;; Get a new match request, with completion
12616 (let ((org-last-tags-completion-table
12617 (org-global-tags-completion-table)))
12618 (setq match (org-completing-read-no-i
12619 "Match: " 'org-tags-completion-function nil nil nil
12620 'org-tags-history))))
12622 ;; Parse the string and create a lisp form
12623 (let ((match0 match)
12624 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12625 minus tag mm
12626 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12627 orterms term orlist re-p str-p level-p level-op time-p
12628 prop-p pn pv po gv rest)
12629 (if (string-match "/+" match)
12630 ;; match contains also a todo-matching request
12631 (progn
12632 (setq tagsmatch (substring match 0 (match-beginning 0))
12633 todomatch (substring match (match-end 0)))
12634 (if (string-match "^!" todomatch)
12635 (setq todo-only t todomatch (substring todomatch 1)))
12636 (if (string-match "^\\s-*$" todomatch)
12637 (setq todomatch nil)))
12638 ;; only matching tags
12639 (setq tagsmatch match todomatch nil))
12641 ;; Make the tags matcher
12642 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12643 (setq tagsmatcher t)
12644 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12645 (while (setq term (pop orterms))
12646 (while (and (equal (substring term -1) "\\") orterms)
12647 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12648 (while (string-match re term)
12649 (setq rest (substring term (match-end 0))
12650 minus (and (match-end 1)
12651 (equal (match-string 1 term) "-"))
12652 tag (save-match-data (replace-regexp-in-string
12653 "\\\\-" "-"
12654 (match-string 2 term)))
12655 re-p (equal (string-to-char tag) ?{)
12656 level-p (match-end 4)
12657 prop-p (match-end 5)
12658 mm (cond
12659 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12660 (level-p
12661 (setq level-op (org-op-to-function (match-string 3 term)))
12662 `(,level-op level ,(string-to-number
12663 (match-string 4 term))))
12664 (prop-p
12665 (setq pn (match-string 5 term)
12666 po (match-string 6 term)
12667 pv (match-string 7 term)
12668 re-p (equal (string-to-char pv) ?{)
12669 str-p (equal (string-to-char pv) ?\")
12670 time-p (save-match-data
12671 (string-match "^\"[[<].*[]>]\"$" pv))
12672 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12673 (if time-p (setq pv (org-matcher-time pv)))
12674 (setq po (org-op-to-function po (if time-p 'time str-p)))
12675 (cond
12676 ((equal pn "CATEGORY")
12677 (setq gv '(get-text-property (point) 'org-category)))
12678 ((equal pn "TODO")
12679 (setq gv 'todo))
12681 (setq gv `(org-cached-entry-get nil ,pn))))
12682 (if re-p
12683 (if (eq po 'org<>)
12684 `(not (string-match ,pv (or ,gv "")))
12685 `(string-match ,pv (or ,gv "")))
12686 (if str-p
12687 `(,po (or ,gv "") ,pv)
12688 `(,po (string-to-number (or ,gv ""))
12689 ,(string-to-number pv) ))))
12690 (t `(member ,tag tags-list)))
12691 mm (if minus (list 'not mm) mm)
12692 term rest)
12693 (push mm tagsmatcher))
12694 (push (if (> (length tagsmatcher) 1)
12695 (cons 'and tagsmatcher)
12696 (car tagsmatcher))
12697 orlist)
12698 (setq tagsmatcher nil))
12699 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12700 (setq tagsmatcher
12701 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12702 ;; Make the todo matcher
12703 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12704 (setq todomatcher t)
12705 (setq orterms (org-split-string todomatch "|") orlist nil)
12706 (while (setq term (pop orterms))
12707 (while (string-match re term)
12708 (setq minus (and (match-end 1)
12709 (equal (match-string 1 term) "-"))
12710 kwd (match-string 2 term)
12711 re-p (equal (string-to-char kwd) ?{)
12712 term (substring term (match-end 0))
12713 mm (if re-p
12714 `(string-match ,(substring kwd 1 -1) todo)
12715 (list 'equal 'todo kwd))
12716 mm (if minus (list 'not mm) mm))
12717 (push mm todomatcher))
12718 (push (if (> (length todomatcher) 1)
12719 (cons 'and todomatcher)
12720 (car todomatcher))
12721 orlist)
12722 (setq todomatcher nil))
12723 (setq todomatcher (if (> (length orlist) 1)
12724 (cons 'or orlist) (car orlist))))
12726 ;; Return the string and lisp forms of the matcher
12727 (setq matcher (if todomatcher
12728 (list 'and tagsmatcher todomatcher)
12729 tagsmatcher))
12730 (cons match0 matcher)))
12732 (defun org-op-to-function (op &optional stringp)
12733 "Turn an operator into the appropriate function."
12734 (setq op
12735 (cond
12736 ((equal op "<" ) '(< string< org-time<))
12737 ((equal op ">" ) '(> org-string> org-time>))
12738 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12739 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12740 ((member op '("=" "==")) '(= string= org-time=))
12741 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12742 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12744 (defun org<> (a b) (not (= a b)))
12745 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12746 (defun org-string>= (a b) (not (string< a b)))
12747 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12748 (defun org-string<> (a b) (not (string= a b)))
12749 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
12750 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
12751 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
12752 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
12753 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
12754 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12755 (defun org-2ft (s)
12756 "Convert S to a floating point time.
12757 If S is already a number, just return it. If it is a string, parse
12758 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12759 (cond
12760 ((numberp s) s)
12761 ((stringp s)
12762 (condition-case nil
12763 (float-time (apply 'encode-time (org-parse-time-string s)))
12764 (error 0.)))
12765 (t 0.)))
12767 (defun org-time-today ()
12768 "Time in seconds today at 0:00.
12769 Returns the float number of seconds since the beginning of the
12770 epoch to the beginning of today (00:00)."
12771 (float-time (apply 'encode-time
12772 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12774 (defun org-matcher-time (s)
12775 "Interpret a time comparison value."
12776 (save-match-data
12777 (cond
12778 ((string= s "<now>") (float-time))
12779 ((string= s "<today>") (org-time-today))
12780 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12781 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12782 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12783 (+ (org-time-today)
12784 (* (string-to-number (match-string 1 s))
12785 (cdr (assoc (match-string 2 s)
12786 '(("d" . 86400.0) ("w" . 604800.0)
12787 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12788 (t (org-2ft s)))))
12790 (defun org-match-any-p (re list)
12791 "Does re match any element of list?"
12792 (setq list (mapcar (lambda (x) (string-match re x)) list))
12793 (delq nil list))
12795 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12796 (defvar org-tags-overlay (make-overlay 1 1))
12797 (org-detach-overlay org-tags-overlay)
12799 (defun org-get-local-tags-at (&optional pos)
12800 "Get a list of tags defined in the current headline."
12801 (org-get-tags-at pos 'local))
12803 (defun org-get-local-tags ()
12804 "Get a list of tags defined in the current headline."
12805 (org-get-tags-at nil 'local))
12807 (defun org-get-tags-at (&optional pos local)
12808 "Get a list of all headline tags applicable at POS.
12809 POS defaults to point. If tags are inherited, the list contains
12810 the targets in the same sequence as the headlines appear, i.e.
12811 the tags of the current headline come last.
12812 When LOCAL is non-nil, only return tags from the current headline,
12813 ignore inherited ones."
12814 (interactive)
12815 (if (and org-trust-scanner-tags
12816 (or (not pos) (equal pos (point)))
12817 (not local))
12818 org-scanner-tags
12819 (let (tags ltags lastpos parent)
12820 (save-excursion
12821 (save-restriction
12822 (widen)
12823 (goto-char (or pos (point)))
12824 (save-match-data
12825 (catch 'done
12826 (condition-case nil
12827 (progn
12828 (org-back-to-heading t)
12829 (while (not (equal lastpos (point)))
12830 (setq lastpos (point))
12831 (when (looking-at
12832 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
12833 (setq ltags (org-split-string
12834 (org-match-string-no-properties 1) ":"))
12835 (when parent
12836 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12837 (setq tags (append
12838 (if parent
12839 (org-remove-uninherited-tags ltags)
12840 ltags)
12841 tags)))
12842 (or org-use-tag-inheritance (throw 'done t))
12843 (if local (throw 'done t))
12844 (or (org-up-heading-safe) (error nil))
12845 (setq parent t)))
12846 (error nil)))))
12847 (if local
12848 tags
12849 (append (org-remove-uninherited-tags org-file-tags) tags))))))
12851 (defun org-add-prop-inherited (s)
12852 (add-text-properties 0 (length s) '(inherited t) s)
12855 (defun org-toggle-tag (tag &optional onoff)
12856 "Toggle the tag TAG for the current line.
12857 If ONOFF is `on' or `off', don't toggle but set to this state."
12858 (let (res current)
12859 (save-excursion
12860 (org-back-to-heading t)
12861 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
12862 (point-at-eol) t)
12863 (progn
12864 (setq current (match-string 1))
12865 (replace-match ""))
12866 (setq current ""))
12867 (setq current (nreverse (org-split-string current ":")))
12868 (cond
12869 ((eq onoff 'on)
12870 (setq res t)
12871 (or (member tag current) (push tag current)))
12872 ((eq onoff 'off)
12873 (or (not (member tag current)) (setq current (delete tag current))))
12874 (t (if (member tag current)
12875 (setq current (delete tag current))
12876 (setq res t)
12877 (push tag current))))
12878 (end-of-line 1)
12879 (if current
12880 (progn
12881 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12882 (org-set-tags nil t))
12883 (delete-horizontal-space))
12884 (run-hooks 'org-after-tags-change-hook))
12885 res))
12887 (defun org-align-tags-here (to-col)
12888 ;; Assumes that this is a headline
12889 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12890 (beginning-of-line 1)
12891 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
12892 (< pos (match-beginning 2)))
12893 (progn
12894 (setq tags-l (- (match-end 2) (match-beginning 2)))
12895 (goto-char (match-beginning 1))
12896 (insert " ")
12897 (delete-region (point) (1+ (match-beginning 2)))
12898 (setq ncol (max (1+ (current-column))
12899 (1+ col)
12900 (if (> to-col 0)
12901 to-col
12902 (- (abs to-col) tags-l))))
12903 (setq p (point))
12904 (insert (make-string (- ncol (current-column)) ?\ ))
12905 (setq ncol (current-column))
12906 (when indent-tabs-mode (tabify p (point-at-eol)))
12907 (org-move-to-column (min ncol col) t))
12908 (goto-char pos))))
12910 (defun org-set-tags-command (&optional arg just-align)
12911 "Call the set-tags command for the current entry."
12912 (interactive "P")
12913 (if (org-on-heading-p)
12914 (org-set-tags arg just-align)
12915 (save-excursion
12916 (org-back-to-heading t)
12917 (org-set-tags arg just-align))))
12919 (defun org-set-tags-to (data)
12920 "Set the tags of the current entry to DATA, replacing the current tags.
12921 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12922 If DATA is nil or the empty string, any tags will be removed."
12923 (interactive "sTags: ")
12924 (setq data
12925 (cond
12926 ((eq data nil) "")
12927 ((equal data "") "")
12928 ((stringp data)
12929 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12930 ":"))
12931 ((listp data)
12932 (concat ":" (mapconcat 'identity data ":") ":"))
12933 (t nil)))
12934 (when data
12935 (save-excursion
12936 (org-back-to-heading t)
12937 (when (looking-at org-complex-heading-regexp)
12938 (if (match-end 5)
12939 (progn
12940 (goto-char (match-beginning 5))
12941 (insert data)
12942 (delete-region (point) (point-at-eol))
12943 (org-set-tags nil 'align))
12944 (goto-char (point-at-eol))
12945 (insert " " data)
12946 (org-set-tags nil 'align)))
12947 (beginning-of-line 1)
12948 (if (looking-at ".*?\\([ \t]+\\)$")
12949 (delete-region (match-beginning 1) (match-end 1))))))
12951 (defun org-align-all-tags ()
12952 "Align the tags i all headings."
12953 (interactive)
12954 (save-excursion
12955 (or (ignore-errors (org-back-to-heading t))
12956 (outline-next-heading))
12957 (if (org-on-heading-p)
12958 (org-set-tags t)
12959 (message "No headings"))))
12961 (defvar org-indent-indentation-per-level)
12962 (defun org-set-tags (&optional arg just-align)
12963 "Set the tags for the current headline.
12964 With prefix ARG, realign all tags in headings in the current buffer."
12965 (interactive "P")
12966 (let* ((re (concat "^" outline-regexp))
12967 (current (org-get-tags-string))
12968 (col (current-column))
12969 (org-setting-tags t)
12970 table current-tags inherited-tags ; computed below when needed
12971 tags p0 c0 c1 rpl di tc level)
12972 (if arg
12973 (save-excursion
12974 (goto-char (point-min))
12975 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12976 (while (re-search-forward re nil t)
12977 (org-set-tags nil t)
12978 (end-of-line 1)))
12979 (message "All tags realigned to column %d" org-tags-column))
12980 (if just-align
12981 (setq tags current)
12982 ;; Get a new set of tags from the user
12983 (save-excursion
12984 (setq table (append org-tag-persistent-alist
12985 (or org-tag-alist (org-get-buffer-tags))
12986 (and
12987 org-complete-tags-always-offer-all-agenda-tags
12988 (org-global-tags-completion-table
12989 (org-agenda-files))))
12990 org-last-tags-completion-table table
12991 current-tags (org-split-string current ":")
12992 inherited-tags (nreverse
12993 (nthcdr (length current-tags)
12994 (nreverse (org-get-tags-at))))
12995 tags
12996 (if (or (eq t org-use-fast-tag-selection)
12997 (and org-use-fast-tag-selection
12998 (delq nil (mapcar 'cdr table))))
12999 (org-fast-tag-selection
13000 current-tags inherited-tags table
13001 (if org-fast-tag-selection-include-todo
13002 org-todo-key-alist))
13003 (let ((org-add-colon-after-tag-completion t))
13004 (org-trim
13005 (org-without-partial-completion
13006 (org-icompleting-read "Tags: "
13007 'org-tags-completion-function
13008 nil nil current 'org-tags-history)))))))
13009 (while (string-match "[-+&]+" tags)
13010 ;; No boolean logic, just a list
13011 (setq tags (replace-match ":" t t tags))))
13013 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13015 (if org-tags-sort-function
13016 (setq tags (mapconcat 'identity
13017 (sort (org-split-string
13018 tags (org-re "[^[:alnum:]_@#%]+"))
13019 org-tags-sort-function) ":")))
13021 (if (string-match "\\`[\t ]*\\'" tags)
13022 (setq tags "")
13023 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13024 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13026 ;; Insert new tags at the correct column
13027 (beginning-of-line 1)
13028 (setq level (or (and (looking-at org-outline-regexp)
13029 (- (match-end 0) (point) 1))
13031 (cond
13032 ((and (equal current "") (equal tags "")))
13033 ((re-search-forward
13034 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13035 (point-at-eol) t)
13036 (if (equal tags "")
13037 (setq rpl "")
13038 (goto-char (match-beginning 0))
13039 (setq c0 (current-column)
13040 ;; compute offset for the case of org-indent-mode active
13041 di (if org-indent-mode
13042 (* (1- org-indent-indentation-per-level) (1- level))
13044 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13045 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13046 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13047 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13048 (replace-match rpl t t)
13049 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13050 tags)
13051 (t (error "Tags alignment failed")))
13052 (org-move-to-column col)
13053 (unless just-align
13054 (run-hooks 'org-after-tags-change-hook)))))
13056 (defun org-change-tag-in-region (beg end tag off)
13057 "Add or remove TAG for each entry in the region.
13058 This works in the agenda, and also in an org-mode buffer."
13059 (interactive
13060 (list (region-beginning) (region-end)
13061 (let ((org-last-tags-completion-table
13062 (if (org-mode-p)
13063 (org-get-buffer-tags)
13064 (org-global-tags-completion-table))))
13065 (org-icompleting-read
13066 "Tag: " 'org-tags-completion-function nil nil nil
13067 'org-tags-history))
13068 (progn
13069 (message "[s]et or [r]emove? ")
13070 (equal (read-char-exclusive) ?r))))
13071 (if (fboundp 'deactivate-mark) (deactivate-mark))
13072 (let ((agendap (equal major-mode 'org-agenda-mode))
13073 l1 l2 m buf pos newhead (cnt 0))
13074 (goto-char end)
13075 (setq l2 (1- (org-current-line)))
13076 (goto-char beg)
13077 (setq l1 (org-current-line))
13078 (loop for l from l1 to l2 do
13079 (org-goto-line l)
13080 (setq m (get-text-property (point) 'org-hd-marker))
13081 (when (or (and (org-mode-p) (org-on-heading-p))
13082 (and agendap m))
13083 (setq buf (if agendap (marker-buffer m) (current-buffer))
13084 pos (if agendap m (point)))
13085 (with-current-buffer buf
13086 (save-excursion
13087 (save-restriction
13088 (goto-char pos)
13089 (setq cnt (1+ cnt))
13090 (org-toggle-tag tag (if off 'off 'on))
13091 (setq newhead (org-get-heading)))))
13092 (and agendap (org-agenda-change-all-lines newhead m))))
13093 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13095 (defun org-tags-completion-function (string predicate &optional flag)
13096 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13097 (confirm (lambda (x) (stringp (car x)))))
13098 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13099 (setq s1 (match-string 1 string)
13100 s2 (match-string 2 string))
13101 (setq s1 "" s2 string))
13102 (cond
13103 ((eq flag nil)
13104 ;; try completion
13105 (setq rtn (try-completion s2 ctable confirm))
13106 (if (stringp rtn)
13107 (setq rtn
13108 (concat s1 s2 (substring rtn (length s2))
13109 (if (and org-add-colon-after-tag-completion
13110 (assoc rtn ctable))
13111 ":" ""))))
13112 rtn)
13113 ((eq flag t)
13114 ;; all-completions
13115 (all-completions s2 ctable confirm)
13117 ((eq flag 'lambda)
13118 ;; exact match?
13119 (assoc s2 ctable)))
13122 (defun org-fast-tag-insert (kwd tags face &optional end)
13123 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13124 (insert (format "%-12s" (concat kwd ":"))
13125 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13126 (or end "")))
13128 (defun org-fast-tag-show-exit (flag)
13129 (save-excursion
13130 (org-goto-line 3)
13131 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13132 (replace-match ""))
13133 (when flag
13134 (end-of-line 1)
13135 (org-move-to-column (- (window-width) 19) t)
13136 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13138 (defun org-set-current-tags-overlay (current prefix)
13139 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13140 (if (featurep 'xemacs)
13141 (org-overlay-display org-tags-overlay (concat prefix s)
13142 'secondary-selection)
13143 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13144 (org-overlay-display org-tags-overlay (concat prefix s)))))
13146 (defvar org-last-tag-selection-key nil)
13147 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13148 "Fast tag selection with single keys.
13149 CURRENT is the current list of tags in the headline, INHERITED is the
13150 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13151 possibly with grouping information. TODO-TABLE is a similar table with
13152 TODO keywords, should these have keys assigned to them.
13153 If the keys are nil, a-z are automatically assigned.
13154 Returns the new tags string, or nil to not change the current settings."
13155 (let* ((fulltable (append table todo-table))
13156 (maxlen (apply 'max (mapcar
13157 (lambda (x)
13158 (if (stringp (car x)) (string-width (car x)) 0))
13159 fulltable)))
13160 (buf (current-buffer))
13161 (expert (eq org-fast-tag-selection-single-key 'expert))
13162 (buffer-tags nil)
13163 (fwidth (+ maxlen 3 1 3))
13164 (ncol (/ (- (window-width) 4) fwidth))
13165 (i-face 'org-done)
13166 (c-face 'org-todo)
13167 tg cnt e c char c1 c2 ntable tbl rtn
13168 ov-start ov-end ov-prefix
13169 (exit-after-next org-fast-tag-selection-single-key)
13170 (done-keywords org-done-keywords)
13171 groups ingroup)
13172 (save-excursion
13173 (beginning-of-line 1)
13174 (if (looking-at
13175 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13176 (setq ov-start (match-beginning 1)
13177 ov-end (match-end 1)
13178 ov-prefix "")
13179 (setq ov-start (1- (point-at-eol))
13180 ov-end (1+ ov-start))
13181 (skip-chars-forward "^\n\r")
13182 (setq ov-prefix
13183 (concat
13184 (buffer-substring (1- (point)) (point))
13185 (if (> (current-column) org-tags-column)
13187 (make-string (- org-tags-column (current-column)) ?\ ))))))
13188 (move-overlay org-tags-overlay ov-start ov-end)
13189 (save-window-excursion
13190 (if expert
13191 (set-buffer (get-buffer-create " *Org tags*"))
13192 (delete-other-windows)
13193 (split-window-vertically)
13194 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13195 (erase-buffer)
13196 (org-set-local 'org-done-keywords done-keywords)
13197 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13198 (org-fast-tag-insert "Current" current c-face "\n\n")
13199 (org-fast-tag-show-exit exit-after-next)
13200 (org-set-current-tags-overlay current ov-prefix)
13201 (setq tbl fulltable char ?a cnt 0)
13202 (while (setq e (pop tbl))
13203 (cond
13204 ((equal (car e) :startgroup)
13205 (push '() groups) (setq ingroup t)
13206 (when (not (= cnt 0))
13207 (setq cnt 0)
13208 (insert "\n"))
13209 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13210 ((equal (car e) :endgroup)
13211 (setq ingroup nil cnt 0)
13212 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13213 ((equal e '(:newline))
13214 (when (not (= cnt 0))
13215 (setq cnt 0)
13216 (insert "\n")
13217 (setq e (car tbl))
13218 (while (equal (car tbl) '(:newline))
13219 (insert "\n")
13220 (setq tbl (cdr tbl)))))
13222 (setq tg (copy-sequence (car e)) c2 nil)
13223 (if (cdr e)
13224 (setq c (cdr e))
13225 ;; automatically assign a character.
13226 (setq c1 (string-to-char
13227 (downcase (substring
13228 tg (if (= (string-to-char tg) ?@) 1 0)))))
13229 (if (or (rassoc c1 ntable) (rassoc c1 table))
13230 (while (or (rassoc char ntable) (rassoc char table))
13231 (setq char (1+ char)))
13232 (setq c2 c1))
13233 (setq c (or c2 char)))
13234 (if ingroup (push tg (car groups)))
13235 (setq tg (org-add-props tg nil 'face
13236 (cond
13237 ((not (assoc tg table))
13238 (org-get-todo-face tg))
13239 ((member tg current) c-face)
13240 ((member tg inherited) i-face)
13241 (t nil))))
13242 (if (and (= cnt 0) (not ingroup)) (insert " "))
13243 (insert "[" c "] " tg (make-string
13244 (- fwidth 4 (length tg)) ?\ ))
13245 (push (cons tg c) ntable)
13246 (when (= (setq cnt (1+ cnt)) ncol)
13247 (insert "\n")
13248 (if ingroup (insert " "))
13249 (setq cnt 0)))))
13250 (setq ntable (nreverse ntable))
13251 (insert "\n")
13252 (goto-char (point-min))
13253 (if (not expert) (org-fit-window-to-buffer))
13254 (setq rtn
13255 (catch 'exit
13256 (while t
13257 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13258 (if (not groups) "no " "")
13259 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13260 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13261 (setq org-last-tag-selection-key c)
13262 (cond
13263 ((= c ?\r) (throw 'exit t))
13264 ((= c ?!)
13265 (setq groups (not groups))
13266 (goto-char (point-min))
13267 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13268 ((= c ?\C-c)
13269 (if (not expert)
13270 (org-fast-tag-show-exit
13271 (setq exit-after-next (not exit-after-next)))
13272 (setq expert nil)
13273 (delete-other-windows)
13274 (set-window-buffer (split-window-vertically) " *Org tags*")
13275 (org-switch-to-buffer-other-window " *Org tags*")
13276 (org-fit-window-to-buffer)))
13277 ((or (= c ?\C-g)
13278 (and (= c ?q) (not (rassoc c ntable))))
13279 (org-detach-overlay org-tags-overlay)
13280 (setq quit-flag t))
13281 ((= c ?\ )
13282 (setq current nil)
13283 (if exit-after-next (setq exit-after-next 'now)))
13284 ((= c ?\t)
13285 (condition-case nil
13286 (setq tg (org-icompleting-read
13287 "Tag: "
13288 (or buffer-tags
13289 (with-current-buffer buf
13290 (org-get-buffer-tags)))))
13291 (quit (setq tg "")))
13292 (when (string-match "\\S-" tg)
13293 (add-to-list 'buffer-tags (list tg))
13294 (if (member tg current)
13295 (setq current (delete tg current))
13296 (push tg current)))
13297 (if exit-after-next (setq exit-after-next 'now)))
13298 ((setq e (rassoc c todo-table) tg (car e))
13299 (with-current-buffer buf
13300 (save-excursion (org-todo tg)))
13301 (if exit-after-next (setq exit-after-next 'now)))
13302 ((setq e (rassoc c ntable) tg (car e))
13303 (if (member tg current)
13304 (setq current (delete tg current))
13305 (loop for g in groups do
13306 (if (member tg g)
13307 (mapc (lambda (x)
13308 (setq current (delete x current)))
13309 g)))
13310 (push tg current))
13311 (if exit-after-next (setq exit-after-next 'now))))
13313 ;; Create a sorted list
13314 (setq current
13315 (sort current
13316 (lambda (a b)
13317 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13318 (if (eq exit-after-next 'now) (throw 'exit t))
13319 (goto-char (point-min))
13320 (beginning-of-line 2)
13321 (delete-region (point) (point-at-eol))
13322 (org-fast-tag-insert "Current" current c-face)
13323 (org-set-current-tags-overlay current ov-prefix)
13324 (while (re-search-forward
13325 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13326 (setq tg (match-string 1))
13327 (add-text-properties
13328 (match-beginning 1) (match-end 1)
13329 (list 'face
13330 (cond
13331 ((member tg current) c-face)
13332 ((member tg inherited) i-face)
13333 (t (get-text-property (match-beginning 1) 'face))))))
13334 (goto-char (point-min)))))
13335 (org-detach-overlay org-tags-overlay)
13336 (if rtn
13337 (mapconcat 'identity current ":")
13338 nil))))
13340 (defun org-get-tags-string ()
13341 "Get the TAGS string in the current headline."
13342 (unless (org-on-heading-p t)
13343 (error "Not on a heading"))
13344 (save-excursion
13345 (beginning-of-line 1)
13346 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13347 (org-match-string-no-properties 1)
13348 "")))
13350 (defun org-get-tags ()
13351 "Get the list of tags specified in the current headline."
13352 (org-split-string (org-get-tags-string) ":"))
13354 (defun org-get-buffer-tags ()
13355 "Get a table of all tags used in the buffer, for completion."
13356 (let (tags)
13357 (save-excursion
13358 (goto-char (point-min))
13359 (while (re-search-forward
13360 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13361 (when (equal (char-after (point-at-bol 0)) ?*)
13362 (mapc (lambda (x) (add-to-list 'tags x))
13363 (org-split-string (org-match-string-no-properties 1) ":")))))
13364 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13365 (mapcar 'list tags)))
13367 ;;;; The mapping API
13369 ;;;###autoload
13370 (defun org-map-entries (func &optional match scope &rest skip)
13371 "Call FUNC at each headline selected by MATCH in SCOPE.
13373 FUNC is a function or a lisp form. The function will be called without
13374 arguments, with the cursor positioned at the beginning of the headline.
13375 The return values of all calls to the function will be collected and
13376 returned as a list.
13378 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13379 does not need to preserve point. After evaluation, the cursor will be
13380 moved to the end of the line (presumably of the headline of the
13381 processed entry) and search continues from there. Under some
13382 circumstances, this may not produce the wanted results. For example,
13383 if you have removed (e.g. archived) the current (sub)tree it could
13384 mean that the next entry will be skipped entirely. In such cases, you
13385 can specify the position from where search should continue by making
13386 FUNC set the variable `org-map-continue-from' to the desired buffer
13387 position.
13389 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13390 Only headlines that are matched by this query will be considered during
13391 the iteration. When MATCH is nil or t, all headlines will be
13392 visited by the iteration.
13394 SCOPE determines the scope of this command. It can be any of:
13396 nil The current buffer, respecting the restriction if any
13397 tree The subtree started with the entry at point
13398 file The current buffer, without restriction
13399 file-with-archives
13400 The current buffer, and any archives associated with it
13401 agenda All agenda files
13402 agenda-with-archives
13403 All agenda files with any archive files associated with them
13404 \(file1 file2 ...)
13405 If this is a list, all files in the list will be scanned
13407 The remaining args are treated as settings for the skipping facilities of
13408 the scanner. The following items can be given here:
13410 archive skip trees with the archive tag.
13411 comment skip trees with the COMMENT keyword
13412 function or Emacs Lisp form:
13413 will be used as value for `org-agenda-skip-function', so whenever
13414 the function returns t, FUNC will not be called for that
13415 entry and search will continue from the point where the
13416 function leaves it.
13418 If your function needs to retrieve the tags including inherited tags
13419 at the *current* entry, you can use the value of the variable
13420 `org-scanner-tags' which will be much faster than getting the value
13421 with `org-get-tags-at'. If your function gets properties with
13422 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13423 to t around the call to `org-entry-properties' to get the same speedup.
13424 Note that if your function moves around to retrieve tags and properties at
13425 a *different* entry, you cannot use these techniques."
13426 (let* ((org-agenda-archives-mode nil) ; just to make sure
13427 (org-agenda-skip-archived-trees (memq 'archive skip))
13428 (org-agenda-skip-comment-trees (memq 'comment skip))
13429 (org-agenda-skip-function
13430 (car (org-delete-all '(comment archive) skip)))
13431 (org-tags-match-list-sublevels t)
13432 matcher file res
13433 org-todo-keywords-for-agenda
13434 org-done-keywords-for-agenda
13435 org-todo-keyword-alist-for-agenda
13436 org-drawers-for-agenda
13437 org-tag-alist-for-agenda)
13439 (cond
13440 ((eq match t) (setq matcher t))
13441 ((eq match nil) (setq matcher t))
13442 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13444 (save-excursion
13445 (save-restriction
13446 (when (eq scope 'tree)
13447 (org-back-to-heading t)
13448 (org-narrow-to-subtree)
13449 (setq scope nil))
13451 (if (not scope)
13452 (progn
13453 (org-prepare-agenda-buffers
13454 (list (buffer-file-name (current-buffer))))
13455 (setq res (org-scan-tags func matcher)))
13456 ;; Get the right scope
13457 (cond
13458 ((and scope (listp scope) (symbolp (car scope)))
13459 (setq scope (eval scope)))
13460 ((eq scope 'agenda)
13461 (setq scope (org-agenda-files t)))
13462 ((eq scope 'agenda-with-archives)
13463 (setq scope (org-agenda-files t))
13464 (setq scope (org-add-archive-files scope)))
13465 ((eq scope 'file)
13466 (setq scope (list (buffer-file-name))))
13467 ((eq scope 'file-with-archives)
13468 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13469 (org-prepare-agenda-buffers scope)
13470 (while (setq file (pop scope))
13471 (with-current-buffer (org-find-base-buffer-visiting file)
13472 (save-excursion
13473 (save-restriction
13474 (widen)
13475 (goto-char (point-min))
13476 (setq res (append res (org-scan-tags func matcher))))))))))
13477 res))
13479 ;;;; Properties
13481 ;;; Setting and retrieving properties
13483 (defconst org-special-properties
13484 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13485 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13486 "The special properties valid in Org-mode.
13488 These are properties that are not defined in the property drawer,
13489 but in some other way.")
13491 (defconst org-default-properties
13492 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13493 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13494 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13495 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13496 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13497 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13498 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13499 "Some properties that are used by Org-mode for various purposes.
13500 Being in this list makes sure that they are offered for completion.")
13502 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13503 "Regular expression matching the first line of a property drawer.")
13505 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13506 "Regular expression matching the last line of a property drawer.")
13508 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13509 "Regular expression matching the first line of a property drawer.")
13511 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13512 "Regular expression matching the first line of a property drawer.")
13514 (defconst org-property-drawer-re
13515 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13516 org-property-end-re "\\)\n?")
13517 "Matches an entire property drawer.")
13519 (defconst org-clock-drawer-re
13520 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13521 org-property-end-re "\\)\n?")
13522 "Matches an entire clock drawer.")
13524 (defsubst org-re-property (property)
13525 "Return a regexp matching PROPERTY.
13526 Match group 1 will be set to the value "
13527 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13529 (defun org-property-action ()
13530 "Do an action on properties."
13531 (interactive)
13532 (let (c)
13533 (org-at-property-p)
13534 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13535 (setq c (read-char-exclusive))
13536 (cond
13537 ((equal c ?s)
13538 (call-interactively 'org-set-property))
13539 ((equal c ?d)
13540 (call-interactively 'org-delete-property))
13541 ((equal c ?D)
13542 (call-interactively 'org-delete-property-globally))
13543 ((equal c ?c)
13544 (call-interactively 'org-compute-property-at-point))
13545 (t (error "No such property action %c" c)))))
13547 (defun org-set-effort (&optional value)
13548 "Set the effort property of the current entry.
13549 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13550 allowed value."
13551 (interactive "P")
13552 (if (equal value 0) (setq value 10))
13553 (let* ((completion-ignore-case t)
13554 (prop org-effort-property)
13555 (cur (org-entry-get nil prop))
13556 (allowed (org-property-get-allowed-values nil prop 'table))
13557 (existing (mapcar 'list (org-property-values prop)))
13559 (val (cond
13560 ((stringp value) value)
13561 ((and allowed (integerp value))
13562 (or (car (nth (1- value) allowed))
13563 (car (org-last allowed))))
13564 (allowed
13565 (message "Select 1-9,0, [RET%s]: %s"
13566 (if cur (concat "=" cur) "")
13567 (mapconcat 'car allowed " "))
13568 (setq rpl (read-char-exclusive))
13569 (if (equal rpl ?\r)
13571 (setq rpl (- rpl ?0))
13572 (if (equal rpl 0) (setq rpl 10))
13573 (if (and (> rpl 0) (<= rpl (length allowed)))
13574 (car (nth (1- rpl) allowed))
13575 (org-completing-read "Effort: " allowed nil))))
13577 (let (org-completion-use-ido org-completion-use-iswitchb)
13578 (org-completing-read
13579 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13580 (concat "[" cur "]") "")
13581 ": ")
13582 existing nil nil "" nil cur))))))
13583 (unless (equal (org-entry-get nil prop) val)
13584 (org-entry-put nil prop val))
13585 (message "%s is now %s" prop val)))
13587 (defun org-at-property-p ()
13588 "Is cursor inside a property drawer?"
13589 (save-excursion
13590 (beginning-of-line 1)
13591 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13592 (save-match-data ;; Used by calling procedures
13593 (let ((p (point))
13594 (range (unless (org-before-first-heading-p)
13595 (org-get-property-block))))
13596 (and range (<= (car range) p) (< p (cdr range))))))))
13598 (defun org-get-property-block (&optional beg end force)
13599 "Return the (beg . end) range of the body of the property drawer.
13600 BEG and END can be beginning and end of subtree, if not given
13601 they will be found.
13602 If the drawer does not exist and FORCE is non-nil, create the drawer."
13603 (catch 'exit
13604 (save-excursion
13605 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13606 (end (or end (progn (outline-next-heading) (point)))))
13607 (goto-char beg)
13608 (if (re-search-forward org-property-start-re end t)
13609 (setq beg (1+ (match-end 0)))
13610 (if force
13611 (save-excursion
13612 (org-insert-property-drawer)
13613 (setq end (progn (outline-next-heading) (point))))
13614 (throw 'exit nil))
13615 (goto-char beg)
13616 (if (re-search-forward org-property-start-re end t)
13617 (setq beg (1+ (match-end 0)))))
13618 (if (re-search-forward org-property-end-re end t)
13619 (setq end (match-beginning 0))
13620 (or force (throw 'exit nil))
13621 (goto-char beg)
13622 (setq end beg)
13623 (org-indent-line-function)
13624 (insert ":END:\n"))
13625 (cons beg end)))))
13627 (defun org-entry-properties (&optional pom which specific)
13628 "Get all properties of the entry at point-or-marker POM.
13629 This includes the TODO keyword, the tags, time strings for deadline,
13630 scheduled, and clocking, and any additional properties defined in the
13631 entry. The return value is an alist, keys may occur multiple times
13632 if the property key was used several times.
13633 POM may also be nil, in which case the current entry is used.
13634 If WHICH is nil or `all', get all properties. If WHICH is
13635 `special' or `standard', only get that subclass. If WHICH
13636 is a string only get exactly this property. SPECIFIC can be a string, the
13637 specific property we are interested in. Specifying it can speed
13638 things up because then unnecessary parsing is avoided."
13639 (setq which (or which 'all))
13640 (org-with-point-at pom
13641 (let ((clockstr (substring org-clock-string 0 -1))
13642 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13643 (case-fold-search nil)
13644 beg end range props sum-props key key1 value string clocksum)
13645 (save-excursion
13646 (when (condition-case nil
13647 (and (org-mode-p) (org-back-to-heading t))
13648 (error nil))
13649 (setq beg (point))
13650 (setq sum-props (get-text-property (point) 'org-summaries))
13651 (setq clocksum (get-text-property (point) :org-clock-minutes))
13652 (outline-next-heading)
13653 (setq end (point))
13654 (when (memq which '(all special))
13655 ;; Get the special properties, like TODO and tags
13656 (goto-char beg)
13657 (when (and (or (not specific) (string= specific "TODO"))
13658 (looking-at org-todo-line-regexp) (match-end 2))
13659 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13660 (when (and (or (not specific) (string= specific "PRIORITY"))
13661 (looking-at org-priority-regexp))
13662 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13663 (when (or (not specific) (string= specific "FILE"))
13664 (push (cons "FILE" buffer-file-name) props))
13665 (when (and (or (not specific) (string= specific "TAGS"))
13666 (setq value (org-get-tags-string))
13667 (string-match "\\S-" value))
13668 (push (cons "TAGS" value) props))
13669 (when (and (or (not specific) (string= specific "ALLTAGS"))
13670 (setq value (org-get-tags-at)))
13671 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13672 ":"))
13673 props))
13674 (when (or (not specific) (string= specific "BLOCKED"))
13675 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13676 (when (or (not specific)
13677 (member specific
13678 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13679 "TIMESTAMP" "TIMESTAMP_IA")))
13680 (catch 'match
13681 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13682 (setq key (if (match-end 1)
13683 (substring (org-match-string-no-properties 1)
13684 0 -1))
13685 string (if (equal key clockstr)
13686 (org-no-properties
13687 (org-trim
13688 (buffer-substring
13689 (match-beginning 3) (goto-char
13690 (point-at-eol)))))
13691 (substring (org-match-string-no-properties 3)
13692 1 -1)))
13693 ;; Get the correct property name from the key. This is
13694 ;; necessary if the user has configured time keywords.
13695 (setq key1 (concat key ":"))
13696 (cond
13697 ((not key)
13698 (setq key
13699 (if (= (char-after (match-beginning 3)) ?\[)
13700 "TIMESTAMP_IA" "TIMESTAMP")))
13701 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
13702 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
13703 ((equal key1 org-closed-string) (setq key "CLOSED"))
13704 ((equal key1 org-clock-string) (setq key "CLOCK")))
13705 (if (and specific (equal key specific) (not (equal key "CLOCK")))
13706 (progn
13707 (push (cons key string) props)
13708 ;; no need to search further if match is found
13709 (throw 'match t))
13710 (when (or (equal key "CLOCK") (not (assoc key props)))
13711 (push (cons key string) props))))))
13714 (when (memq which '(all standard))
13715 ;; Get the standard properties, like :PROP: ...
13716 (setq range (org-get-property-block beg end))
13717 (when range
13718 (goto-char (car range))
13719 (while (re-search-forward
13720 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13721 (cdr range) t)
13722 (setq key (org-match-string-no-properties 1)
13723 value (org-trim (or (org-match-string-no-properties 2) "")))
13724 (unless (member key excluded)
13725 (push (cons key (or value "")) props)))))
13726 (if clocksum
13727 (push (cons "CLOCKSUM"
13728 (org-columns-number-to-string (/ (float clocksum) 60.)
13729 'add_times))
13730 props))
13731 (unless (assoc "CATEGORY" props)
13732 (push (cons "CATEGORY" (org-get-category)) props))
13733 (append sum-props (nreverse props)))))))
13735 (defun org-entry-get (pom property &optional inherit literal-nil)
13736 "Get value of PROPERTY for entry at point-or-marker POM.
13737 If INHERIT is non-nil and the entry does not have the property,
13738 then also check higher levels of the hierarchy.
13739 If INHERIT is the symbol `selective', use inheritance only if the setting
13740 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13741 If the property is present but empty, the return value is the empty string.
13742 If the property is not present at all, nil is returned.
13744 If LITERAL-NIL is set, return the string value \"nil\" as a string,
13745 do not interpret it as the list atom nil. This is used for inheritance
13746 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
13747 (org-with-point-at pom
13748 (if (and inherit (if (eq inherit 'selective)
13749 (org-property-inherit-p property)
13751 (org-entry-get-with-inheritance property literal-nil)
13752 (if (member property org-special-properties)
13753 ;; We need a special property. Use `org-entry-properties' to
13754 ;; retrieve it, but specify the wanted property
13755 (cdr (assoc property (org-entry-properties nil 'special property)))
13756 (let ((range (unless (org-before-first-heading-p)
13757 (org-get-property-block))))
13758 (if (and range
13759 (goto-char (car range))
13760 (re-search-forward
13761 (org-re-property property)
13762 (cdr range) t))
13763 ;; Found the property, return it.
13764 (if (match-end 1)
13765 (if literal-nil
13766 (org-match-string-no-properties 1)
13767 (org-not-nil (org-match-string-no-properties 1)))
13768 "")))))))
13770 (defun org-property-or-variable-value (var &optional inherit)
13771 "Check if there is a property fixing the value of VAR.
13772 If yes, return this value. If not, return the current value of the variable."
13773 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13774 (if (and prop (stringp prop) (string-match "\\S-" prop))
13775 (read prop)
13776 (symbol-value var))))
13778 (defun org-entry-delete (pom property)
13779 "Delete the property PROPERTY from entry at point-or-marker POM."
13780 (org-with-point-at pom
13781 (if (member property org-special-properties)
13782 nil ; cannot delete these properties.
13783 (let ((range (org-get-property-block)))
13784 (if (and range
13785 (goto-char (car range))
13786 (re-search-forward
13787 (org-re-property property)
13788 (cdr range) t))
13789 (progn
13790 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13792 nil)))))
13794 ;; Multi-values properties are properties that contain multiple values
13795 ;; These values are assumed to be single words, separated by whitespace.
13796 (defun org-entry-add-to-multivalued-property (pom property value)
13797 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13798 (let* ((old (org-entry-get pom property))
13799 (values (and old (org-split-string old "[ \t]"))))
13800 (setq value (org-entry-protect-space value))
13801 (unless (member value values)
13802 (setq values (cons value values))
13803 (org-entry-put pom property
13804 (mapconcat 'identity values " ")))))
13806 (defun org-entry-remove-from-multivalued-property (pom property value)
13807 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13808 (let* ((old (org-entry-get pom property))
13809 (values (and old (org-split-string old "[ \t]"))))
13810 (setq value (org-entry-protect-space value))
13811 (when (member value values)
13812 (setq values (delete value values))
13813 (org-entry-put pom property
13814 (mapconcat 'identity values " ")))))
13816 (defun org-entry-member-in-multivalued-property (pom property value)
13817 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13818 (let* ((old (org-entry-get pom property))
13819 (values (and old (org-split-string old "[ \t]"))))
13820 (setq value (org-entry-protect-space value))
13821 (member value values)))
13823 (defun org-entry-get-multivalued-property (pom property)
13824 "Return a list of values in a multivalued property."
13825 (let* ((value (org-entry-get pom property))
13826 (values (and value (org-split-string value "[ \t]"))))
13827 (mapcar 'org-entry-restore-space values)))
13829 (defun org-entry-put-multivalued-property (pom property &rest values)
13830 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13831 VALUES should be a list of strings. Spaces will be protected."
13832 (org-entry-put pom property
13833 (mapconcat 'org-entry-protect-space values " "))
13834 (let* ((value (org-entry-get pom property))
13835 (values (and value (org-split-string value "[ \t]"))))
13836 (mapcar 'org-entry-restore-space values)))
13838 (defun org-entry-protect-space (s)
13839 "Protect spaces and newline in string S."
13840 (while (string-match " " s)
13841 (setq s (replace-match "%20" t t s)))
13842 (while (string-match "\n" s)
13843 (setq s (replace-match "%0A" t t s)))
13846 (defun org-entry-restore-space (s)
13847 "Restore spaces and newline in string S."
13848 (while (string-match "%20" s)
13849 (setq s (replace-match " " t t s)))
13850 (while (string-match "%0A" s)
13851 (setq s (replace-match "\n" t t s)))
13854 (defvar org-entry-property-inherited-from (make-marker)
13855 "Marker pointing to the entry from where a property was inherited.
13856 Each call to `org-entry-get-with-inheritance' will set this marker to the
13857 location of the entry where the inheritance search matched. If there was
13858 no match, the marker will point nowhere.
13859 Note that also `org-entry-get' calls this function, if the INHERIT flag
13860 is set.")
13862 (defun org-entry-get-with-inheritance (property &optional literal-nil)
13863 "Get entry property, and search higher levels if not present.
13864 The search will stop at the first ancestor which has the property defined.
13865 If the value found is \"nil\", return nil to show that the property
13866 should be considered as undefined (this is the meaning of nil here).
13867 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
13868 (move-marker org-entry-property-inherited-from nil)
13869 (let (tmp)
13870 (unless (org-before-first-heading-p)
13871 (save-excursion
13872 (save-restriction
13873 (widen)
13874 (catch 'ex
13875 (while t
13876 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
13877 (org-back-to-heading t)
13878 (move-marker org-entry-property-inherited-from (point))
13879 (throw 'ex tmp))
13880 (or (org-up-heading-safe) (throw 'ex nil)))))))
13881 (setq tmp (or tmp
13882 (cdr (assoc property org-file-properties))
13883 (cdr (assoc property org-global-properties))
13884 (cdr (assoc property org-global-properties-fixed))))
13885 (if literal-nil tmp (org-not-nil tmp))))
13887 (defvar org-property-changed-functions nil
13888 "Hook called when the value of a property has changed.
13889 Each hook function should accept two arguments, the name of the property
13890 and the new value.")
13892 (defun org-entry-put (pom property value)
13893 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13894 (org-with-point-at pom
13895 (org-back-to-heading t)
13896 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13897 range)
13898 (cond
13899 ((equal property "TODO")
13900 (when (and (stringp value) (string-match "\\S-" value)
13901 (not (member value org-todo-keywords-1)))
13902 (error "\"%s\" is not a valid TODO state" value))
13903 (if (or (not value)
13904 (not (string-match "\\S-" value)))
13905 (setq value 'none))
13906 (org-todo value)
13907 (org-set-tags nil 'align))
13908 ((equal property "PRIORITY")
13909 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13910 (string-to-char value) ?\ ))
13911 (org-set-tags nil 'align))
13912 ((equal property "SCHEDULED")
13913 (if (re-search-forward org-scheduled-time-regexp end t)
13914 (cond
13915 ((eq value 'earlier) (org-timestamp-change -1 'day))
13916 ((eq value 'later) (org-timestamp-change 1 'day))
13917 (t (call-interactively 'org-schedule)))
13918 (call-interactively 'org-schedule)))
13919 ((equal property "DEADLINE")
13920 (if (re-search-forward org-deadline-time-regexp end t)
13921 (cond
13922 ((eq value 'earlier) (org-timestamp-change -1 'day))
13923 ((eq value 'later) (org-timestamp-change 1 'day))
13924 (t (call-interactively 'org-deadline)))
13925 (call-interactively 'org-deadline)))
13926 ((member property org-special-properties)
13927 (error "The %s property can not yet be set with `org-entry-put'"
13928 property))
13929 (t ; a non-special property
13930 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13931 (setq range (org-get-property-block beg end 'force))
13932 (goto-char (car range))
13933 (if (re-search-forward
13934 (org-re-property property) (cdr range) t)
13935 (progn
13936 (delete-region (match-beginning 0) (match-end 0))
13937 (goto-char (match-beginning 0)))
13938 (goto-char (cdr range))
13939 (insert "\n")
13940 (backward-char 1)
13941 (org-indent-line-function))
13942 (insert ":" property ":")
13943 (and value (insert " " value))
13944 (org-indent-line-function)))))
13945 (run-hook-with-args 'org-property-changed-functions property value)))
13947 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13948 "Get all property keys in the current buffer.
13949 With INCLUDE-SPECIALS, also list the special properties that reflect things
13950 like tags and TODO state.
13951 With INCLUDE-DEFAULTS, also include properties that has special meaning
13952 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
13953 and others.
13954 With INCLUDE-COLUMNS, also include property names given in COLUMN
13955 formats in the current buffer."
13956 (let (rtn range cfmt s p)
13957 (save-excursion
13958 (save-restriction
13959 (widen)
13960 (goto-char (point-min))
13961 (while (re-search-forward org-property-start-re nil t)
13962 (setq range (org-get-property-block))
13963 (goto-char (car range))
13964 (while (re-search-forward
13965 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13966 (cdr range) t)
13967 (add-to-list 'rtn (org-match-string-no-properties 1)))
13968 (outline-next-heading))))
13970 (when include-specials
13971 (setq rtn (append org-special-properties rtn)))
13973 (when include-defaults
13974 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13975 (add-to-list 'rtn org-effort-property))
13977 (when include-columns
13978 (save-excursion
13979 (save-restriction
13980 (widen)
13981 (goto-char (point-min))
13982 (while (re-search-forward
13983 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13984 nil t)
13985 (setq cfmt (match-string 2) s 0)
13986 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13987 cfmt s)
13988 (setq s (match-end 0)
13989 p (match-string 1 cfmt))
13990 (unless (or (equal p "ITEM")
13991 (member p org-special-properties))
13992 (add-to-list 'rtn (match-string 1 cfmt))))))))
13994 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13996 (defun org-property-values (key)
13997 "Return a list of all values of property KEY in the current buffer."
13998 (save-excursion
13999 (save-restriction
14000 (widen)
14001 (goto-char (point-min))
14002 (let ((re (org-re-property key))
14003 values)
14004 (while (re-search-forward re nil t)
14005 (add-to-list 'values (org-trim (match-string 1))))
14006 (delete "" values)))))
14008 (defun org-insert-property-drawer ()
14009 "Insert a property drawer into the current entry."
14010 (interactive)
14011 (org-back-to-heading t)
14012 (looking-at outline-regexp)
14013 (let ((indent (if org-adapt-indentation
14014 (- (match-end 0)(match-beginning 0))
14016 (beg (point))
14017 (re (concat "^[ \t]*" org-keyword-time-regexp))
14018 end hiddenp)
14019 (outline-next-heading)
14020 (setq end (point))
14021 (goto-char beg)
14022 (while (re-search-forward re end t))
14023 (setq hiddenp (outline-invisible-p))
14024 (end-of-line 1)
14025 (and (equal (char-after) ?\n) (forward-char 1))
14026 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14027 (if (member (match-string 1) '("CLOCK:" ":END:"))
14028 ;; just skip this line
14029 (beginning-of-line 2)
14030 ;; Drawer start, find the end
14031 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14032 (beginning-of-line 1)))
14033 (org-skip-over-state-notes)
14034 (skip-chars-backward " \t\n\r")
14035 (if (eq (char-before) ?*) (forward-char 1))
14036 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14037 (beginning-of-line 0)
14038 (org-indent-to-column indent)
14039 (beginning-of-line 2)
14040 (org-indent-to-column indent)
14041 (beginning-of-line 0)
14042 (if hiddenp
14043 (save-excursion
14044 (org-back-to-heading t)
14045 (hide-entry))
14046 (org-flag-drawer t))))
14048 (defvar org-property-set-functions-alist nil
14049 "Property set function alist.
14050 Each entry should have the following format:
14052 (PROPERTY . READ-FUNCTION)
14054 The read function will be called with the same argument as
14055 `org-completing-read'.")
14057 (defun org-set-property-function (property)
14058 "Get the function that should be used to set PROPERTY.
14059 This is computed according to `org-property-set-functions-alist'."
14060 (or (cdr (assoc property org-property-set-functions-alist))
14061 'org-completing-read))
14063 (defun org-read-property-value (property)
14064 "Read PROPERTY value from user."
14065 (let* ((completion-ignore-case t)
14066 (allowed (org-property-get-allowed-values nil property 'table))
14067 (cur (org-entry-get nil property))
14068 (prompt (concat property " value"
14069 (if (and cur (string-match "\\S-" cur))
14070 (concat " [" cur "]") "") ": "))
14071 (set-function (org-set-property-function property))
14072 (val (if allowed
14073 (funcall set-function prompt allowed nil
14074 (not (get-text-property 0 'org-unrestricted
14075 (caar allowed))))
14076 (let (org-completion-use-ido org-completion-use-iswitchb)
14077 (funcall set-function prompt
14078 (mapcar 'list (org-property-values property))
14079 nil nil "" nil cur)))))
14080 (if (equal val "")
14082 val)))
14084 (defun org-read-property-name ()
14085 "Read a property name."
14086 (let* ((completion-ignore-case t)
14087 (keys (org-buffer-property-keys nil t t))
14088 (property (org-icompleting-read "Property: " (mapcar 'list keys))))
14089 (if (member property keys)
14090 property
14091 (or (cdr (assoc (downcase property)
14092 (mapcar (lambda (x) (cons (downcase x) x))
14093 keys)))
14094 property))))
14096 (defun org-set-property (property value)
14097 "In the current entry, set PROPERTY to VALUE.
14098 When called interactively, this will prompt for a property name, offering
14099 completion on existing and default properties. And then it will prompt
14100 for a value, offering completion either on allowed values (via an inherited
14101 xxx_ALL property) or on existing values in other instances of this property
14102 in the current file."
14103 (interactive (list nil nil))
14104 (let* ((property (or property (org-read-property-name)))
14105 (value (or value (org-read-property-value property))))
14106 (unless (equal (org-entry-get nil property) value)
14107 (org-entry-put nil property value))))
14109 (defun org-delete-property (property)
14110 "In the current entry, delete PROPERTY."
14111 (interactive
14112 (let* ((completion-ignore-case t)
14113 (prop (org-icompleting-read "Property: "
14114 (org-entry-properties nil 'standard))))
14115 (list prop)))
14116 (message "Property %s %s" property
14117 (if (org-entry-delete nil property)
14118 "deleted"
14119 "was not present in the entry")))
14121 (defun org-delete-property-globally (property)
14122 "Remove PROPERTY globally, from all entries."
14123 (interactive
14124 (let* ((completion-ignore-case t)
14125 (prop (org-icompleting-read
14126 "Globally remove property: "
14127 (mapcar 'list (org-buffer-property-keys)))))
14128 (list prop)))
14129 (save-excursion
14130 (save-restriction
14131 (widen)
14132 (goto-char (point-min))
14133 (let ((cnt 0))
14134 (while (re-search-forward
14135 (org-re-property property)
14136 nil t)
14137 (setq cnt (1+ cnt))
14138 (replace-match ""))
14139 (message "Property \"%s\" removed from %d entries" property cnt)))))
14141 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14143 (defun org-compute-property-at-point ()
14144 "Compute the property at point.
14145 This looks for an enclosing column format, extracts the operator and
14146 then applies it to the property in the column format's scope."
14147 (interactive)
14148 (unless (org-at-property-p)
14149 (error "Not at a property"))
14150 (let ((prop (org-match-string-no-properties 2)))
14151 (org-columns-get-format-and-top-level)
14152 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14153 (error "No operator defined for property %s" prop))
14154 (org-columns-compute prop)))
14156 (defvar org-property-allowed-value-functions nil
14157 "Hook for functions supplying allowed values for a specific property.
14158 The functions must take a single argument, the name of the property, and
14159 return a flat list of allowed values. If \":ETC\" is one of
14160 the values, this means that these values are intended as defaults for
14161 completion, but that other values should be allowed too.
14162 The functions must return nil if they are not responsible for this
14163 property.")
14165 (defun org-property-get-allowed-values (pom property &optional table)
14166 "Get allowed values for the property PROPERTY.
14167 When TABLE is non-nil, return an alist that can directly be used for
14168 completion."
14169 (let (vals)
14170 (cond
14171 ((equal property "TODO")
14172 (setq vals (org-with-point-at pom
14173 (append org-todo-keywords-1 '("")))))
14174 ((equal property "PRIORITY")
14175 (let ((n org-lowest-priority))
14176 (while (>= n org-highest-priority)
14177 (push (char-to-string n) vals)
14178 (setq n (1- n)))))
14179 ((member property org-special-properties))
14180 ((setq vals (run-hook-with-args-until-success
14181 'org-property-allowed-value-functions property)))
14183 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14184 (when (and vals (string-match "\\S-" vals))
14185 (setq vals (car (read-from-string (concat "(" vals ")"))))
14186 (setq vals (mapcar (lambda (x)
14187 (cond ((stringp x) x)
14188 ((numberp x) (number-to-string x))
14189 ((symbolp x) (symbol-name x))
14190 (t "???")))
14191 vals)))))
14192 (when (member ":ETC" vals)
14193 (setq vals (remove ":ETC" vals))
14194 (org-add-props (car vals) '(org-unrestricted t)))
14195 (if table (mapcar 'list vals) vals)))
14197 (defun org-property-previous-allowed-value (&optional previous)
14198 "Switch to the next allowed value for this property."
14199 (interactive)
14200 (org-property-next-allowed-value t))
14202 (defun org-property-next-allowed-value (&optional previous)
14203 "Switch to the next allowed value for this property."
14204 (interactive)
14205 (unless (org-at-property-p)
14206 (error "Not at a property"))
14207 (let* ((key (match-string 2))
14208 (value (match-string 3))
14209 (allowed (or (org-property-get-allowed-values (point) key)
14210 (and (member value '("[ ]" "[-]" "[X]"))
14211 '("[ ]" "[X]"))))
14212 nval)
14213 (unless allowed
14214 (error "Allowed values for this property have not been defined"))
14215 (if previous (setq allowed (reverse allowed)))
14216 (if (member value allowed)
14217 (setq nval (car (cdr (member value allowed)))))
14218 (setq nval (or nval (car allowed)))
14219 (if (equal nval value)
14220 (error "Only one allowed value for this property"))
14221 (org-at-property-p)
14222 (replace-match (concat " :" key ": " nval) t t)
14223 (org-indent-line-function)
14224 (beginning-of-line 1)
14225 (skip-chars-forward " \t")
14226 (run-hook-with-args 'org-property-changed-functions key nval)))
14228 (defun org-find-olp (path &optional this-buffer)
14229 "Return a marker pointing to the entry at outline path OLP.
14230 If anything goes wrong, throw an error.
14231 You can wrap this call to catch the error like this:
14233 (condition-case msg
14234 (org-mobile-locate-entry (match-string 4))
14235 (error (nth 1 msg)))
14237 The return value will then be either a string with the error message,
14238 or a marker if everything is OK.
14240 If THIS-BUFFER is set, the outline path does not contain a file,
14241 only headings."
14242 (let* ((file (if this-buffer buffer-file-name (pop path)))
14243 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14244 (level 1)
14245 (lmin 1)
14246 (lmax 1)
14247 limit re end found pos heading cnt flevel)
14248 (unless buffer (error "File not found :%s" file))
14249 (with-current-buffer buffer
14250 (save-excursion
14251 (save-restriction
14252 (widen)
14253 (setq limit (point-max))
14254 (goto-char (point-min))
14255 (while (setq heading (pop path))
14256 (setq re (format org-complex-heading-regexp-format
14257 (regexp-quote heading)))
14258 (setq cnt 0 pos (point))
14259 (while (re-search-forward re end t)
14260 (setq level (- (match-end 1) (match-beginning 1)))
14261 (if (and (>= level lmin) (<= level lmax))
14262 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14263 (when (= cnt 0) (error "Heading not found on level %d: %s"
14264 lmax heading))
14265 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14266 lmax heading))
14267 (goto-char found)
14268 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14269 (setq end (save-excursion (org-end-of-subtree t t))))
14270 (when (org-on-heading-p)
14271 (move-marker (make-marker) (point))))))))
14273 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14274 "Find node HEADING in BUFFER.
14275 Return a marker to the heading if it was found, or nil if not.
14276 If POS-ONLY is set, return just the position instead of a marker.
14278 The heading text must match exact, but it may have a TODO keyword,
14279 a priority cookie and tags in the standard locations."
14280 (with-current-buffer (or buffer (current-buffer))
14281 (save-excursion
14282 (save-restriction
14283 (widen)
14284 (goto-char (point-min))
14285 (let (case-fold-search)
14286 (if (re-search-forward
14287 (format org-complex-heading-regexp-format
14288 (regexp-quote heading)) nil t)
14289 (if pos-only
14290 (match-beginning 0)
14291 (move-marker (make-marker) (match-beginning 0)))))))))
14293 (defun org-find-exact-heading-in-directory (heading &optional dir)
14294 "Find Org node headline HEADING in all .org files in directory DIR.
14295 When the target headline is found, return a marker to this location."
14296 (let ((files (directory-files (or dir default-directory)
14297 nil "\\`[^.#].*\\.org\\'"))
14298 file visiting m buffer)
14299 (catch 'found
14300 (while (setq file (pop files))
14301 (message "trying %s" file)
14302 (setq visiting (org-find-base-buffer-visiting file))
14303 (setq buffer (or visiting (find-file-noselect file)))
14304 (setq m (org-find-exact-headline-in-buffer
14305 heading buffer))
14306 (when (and (not m) (not visiting)) (kill-buffer buffer))
14307 (and m (throw 'found m))))))
14309 (defun org-find-entry-with-id (ident)
14310 "Locate the entry that contains the ID property with exact value IDENT.
14311 IDENT can be a string, a symbol or a number, this function will search for
14312 the string representation of it.
14313 Return the position where this entry starts, or nil if there is no such entry."
14314 (interactive "sID: ")
14315 (let ((id (cond
14316 ((stringp ident) ident)
14317 ((symbol-name ident) (symbol-name ident))
14318 ((numberp ident) (number-to-string ident))
14319 (t (error "IDENT %s must be a string, symbol or number" ident))))
14320 (case-fold-search nil))
14321 (save-excursion
14322 (save-restriction
14323 (widen)
14324 (goto-char (point-min))
14325 (when (re-search-forward
14326 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14327 nil t)
14328 (org-back-to-heading t)
14329 (point))))))
14331 ;;;; Timestamps
14333 (defvar org-last-changed-timestamp nil)
14334 (defvar org-last-inserted-timestamp nil
14335 "The last time stamp inserted with `org-insert-time-stamp'.")
14336 (defvar org-time-was-given) ; dynamically scoped parameter
14337 (defvar org-end-time-was-given) ; dynamically scoped parameter
14338 (defvar org-ts-what) ; dynamically scoped parameter
14340 (defun org-time-stamp (arg &optional inactive)
14341 "Prompt for a date/time and insert a time stamp.
14342 If the user specifies a time like HH:MM, or if this command is called
14343 with a prefix argument, the time stamp will contain date and time.
14344 Otherwise, only the date will be included. All parts of a date not
14345 specified by the user will be filled in from the current date/time.
14346 So if you press just return without typing anything, the time stamp
14347 will represent the current date/time. If there is already a timestamp
14348 at the cursor, it will be modified."
14349 (interactive "P")
14350 (let* ((ts nil)
14351 (default-time
14352 ;; Default time is either today, or, when entering a range,
14353 ;; the range start.
14354 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14355 (save-excursion
14356 (re-search-backward
14357 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14358 (- (point) 20) t)))
14359 (apply 'encode-time (org-parse-time-string (match-string 1)))
14360 (current-time)))
14361 (default-input (and ts (org-get-compact-tod ts)))
14362 org-time-was-given org-end-time-was-given time)
14363 (cond
14364 ((and (org-at-timestamp-p t)
14365 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14366 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14367 (insert "--")
14368 (setq time (let ((this-command this-command))
14369 (org-read-date arg 'totime nil nil
14370 default-time default-input)))
14371 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14372 ((org-at-timestamp-p t)
14373 (setq time (let ((this-command this-command))
14374 (org-read-date arg 'totime nil nil default-time default-input)))
14375 (when (org-at-timestamp-p t) ; just to get the match data
14376 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14377 (replace-match "")
14378 (setq org-last-changed-timestamp
14379 (org-insert-time-stamp
14380 time (or org-time-was-given arg)
14381 inactive nil nil (list org-end-time-was-given))))
14382 (message "Timestamp updated"))
14384 (setq time (let ((this-command this-command))
14385 (org-read-date arg 'totime nil nil default-time default-input)))
14386 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14387 nil nil (list org-end-time-was-given))))))
14389 ;; FIXME: can we use this for something else, like computing time differences?
14390 (defun org-get-compact-tod (s)
14391 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14392 (let* ((t1 (match-string 1 s))
14393 (h1 (string-to-number (match-string 2 s)))
14394 (m1 (string-to-number (match-string 3 s)))
14395 (t2 (and (match-end 4) (match-string 5 s)))
14396 (h2 (and t2 (string-to-number (match-string 6 s))))
14397 (m2 (and t2 (string-to-number (match-string 7 s))))
14398 dh dm)
14399 (if (not t2)
14401 (setq dh (- h2 h1) dm (- m2 m1))
14402 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14403 (concat t1 "+" (number-to-string dh)
14404 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14406 (defun org-time-stamp-inactive (&optional arg)
14407 "Insert an inactive time stamp.
14408 An inactive time stamp is enclosed in square brackets instead of angle
14409 brackets. It is inactive in the sense that it does not trigger agenda entries,
14410 does not link to the calendar and cannot be changed with the S-cursor keys.
14411 So these are more for recording a certain time/date."
14412 (interactive "P")
14413 (org-time-stamp arg 'inactive))
14415 (defvar org-date-ovl (make-overlay 1 1))
14416 (overlay-put org-date-ovl 'face 'org-warning)
14417 (org-detach-overlay org-date-ovl)
14419 (defvar org-ans1) ; dynamically scoped parameter
14420 (defvar org-ans2) ; dynamically scoped parameter
14422 (defvar org-plain-time-of-day-regexp) ; defined below
14424 (defvar org-overriding-default-time nil) ; dynamically scoped
14425 (defvar org-read-date-overlay nil)
14426 (defvar org-dcst nil) ; dynamically scoped
14427 (defvar org-read-date-history nil)
14428 (defvar org-read-date-final-answer nil)
14429 (defvar org-read-date-analyze-futurep nil)
14430 (defvar org-read-date-analyze-forced-year nil)
14432 (defun org-read-date (&optional with-time to-time from-string prompt
14433 default-time default-input)
14434 "Read a date, possibly a time, and make things smooth for the user.
14435 The prompt will suggest to enter an ISO date, but you can also enter anything
14436 which will at least partially be understood by `parse-time-string'.
14437 Unrecognized parts of the date will default to the current day, month, year,
14438 hour and minute. If this command is called to replace a timestamp at point,
14439 of to enter the second timestamp of a range, the default time is taken
14440 from the existing stamp. Furthermore, the command prefers the future,
14441 so if you are giving a date where the year is not given, and the day-month
14442 combination is already past in the current year, it will assume you
14443 mean next year. For details, see the manual. A few examples:
14445 3-2-5 --> 2003-02-05
14446 feb 15 --> currentyear-02-15
14447 2/15 --> currentyear-02-15
14448 sep 12 9 --> 2009-09-12
14449 12:45 --> today 12:45
14450 22 sept 0:34 --> currentyear-09-22 0:34
14451 12 --> currentyear-currentmonth-12
14452 Fri --> nearest Friday (today or later)
14453 etc.
14455 Furthermore you can specify a relative date by giving, as the *first* thing
14456 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14457 change in days weeks, months, years.
14458 With a single plus or minus, the date is relative to today. With a double
14459 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14460 +4d --> four days from today
14461 +4 --> same as above
14462 +2w --> two weeks from today
14463 ++5 --> five days from default date
14465 The function understands only English month and weekday abbreviations,
14466 but this can be configured with the variables `parse-time-months' and
14467 `parse-time-weekdays'.
14469 While prompting, a calendar is popped up - you can also select the
14470 date with the mouse (button 1). The calendar shows a period of three
14471 months. To scroll it to other months, use the keys `>' and `<'.
14472 If you don't like the calendar, turn it off with
14473 \(setq org-read-date-popup-calendar nil)
14475 With optional argument TO-TIME, the date will immediately be converted
14476 to an internal time.
14477 With an optional argument WITH-TIME, the prompt will suggest to also
14478 insert a time. Note that when WITH-TIME is not set, you can still
14479 enter a time, and this function will inform the calling routine about
14480 this change. The calling routine may then choose to change the format
14481 used to insert the time stamp into the buffer to include the time.
14482 With optional argument FROM-STRING, read from this string instead from
14483 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14484 the time/date that is used for everything that is not specified by the
14485 user."
14486 (require 'parse-time)
14487 (let* ((org-time-stamp-rounding-minutes
14488 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14489 (org-dcst org-display-custom-times)
14490 (ct (org-current-time))
14491 (def (or org-overriding-default-time default-time ct))
14492 (defdecode (decode-time def))
14493 (dummy (progn
14494 (when (< (nth 2 defdecode) org-extend-today-until)
14495 (setcar (nthcdr 2 defdecode) -1)
14496 (setcar (nthcdr 1 defdecode) 59)
14497 (setq def (apply 'encode-time defdecode)
14498 defdecode (decode-time def)))))
14499 (calendar-frame-setup nil)
14500 (calendar-setup nil)
14501 (calendar-move-hook nil)
14502 (calendar-view-diary-initially-flag nil)
14503 (calendar-view-holidays-initially-flag nil)
14504 (timestr (format-time-string
14505 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14506 (prompt (concat (if prompt (concat prompt " ") "")
14507 (format "Date+time [%s]: " timestr)))
14508 ans (org-ans0 "") org-ans1 org-ans2 final)
14510 (cond
14511 (from-string (setq ans from-string))
14512 (org-read-date-popup-calendar
14513 (save-excursion
14514 (save-window-excursion
14515 (calendar)
14516 (unwind-protect
14517 (progn
14518 (calendar-forward-day (- (time-to-days def)
14519 (calendar-absolute-from-gregorian
14520 (calendar-current-date))))
14521 (org-eval-in-calendar nil t)
14522 (let* ((old-map (current-local-map))
14523 (map (copy-keymap calendar-mode-map))
14524 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14525 (org-defkey map (kbd "RET") 'org-calendar-select)
14526 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14527 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14528 (org-defkey minibuffer-local-map [(meta shift left)]
14529 (lambda () (interactive)
14530 (org-eval-in-calendar '(calendar-backward-month 1))))
14531 (org-defkey minibuffer-local-map [(meta shift right)]
14532 (lambda () (interactive)
14533 (org-eval-in-calendar '(calendar-forward-month 1))))
14534 (org-defkey minibuffer-local-map [(meta shift up)]
14535 (lambda () (interactive)
14536 (org-eval-in-calendar '(calendar-backward-year 1))))
14537 (org-defkey minibuffer-local-map [(meta shift down)]
14538 (lambda () (interactive)
14539 (org-eval-in-calendar '(calendar-forward-year 1))))
14540 (org-defkey minibuffer-local-map [?\e (shift left)]
14541 (lambda () (interactive)
14542 (org-eval-in-calendar '(calendar-backward-month 1))))
14543 (org-defkey minibuffer-local-map [?\e (shift right)]
14544 (lambda () (interactive)
14545 (org-eval-in-calendar '(calendar-forward-month 1))))
14546 (org-defkey minibuffer-local-map [?\e (shift up)]
14547 (lambda () (interactive)
14548 (org-eval-in-calendar '(calendar-backward-year 1))))
14549 (org-defkey minibuffer-local-map [?\e (shift down)]
14550 (lambda () (interactive)
14551 (org-eval-in-calendar '(calendar-forward-year 1))))
14552 (org-defkey minibuffer-local-map [(shift up)]
14553 (lambda () (interactive)
14554 (org-eval-in-calendar '(calendar-backward-week 1))))
14555 (org-defkey minibuffer-local-map [(shift down)]
14556 (lambda () (interactive)
14557 (org-eval-in-calendar '(calendar-forward-week 1))))
14558 (org-defkey minibuffer-local-map [(shift left)]
14559 (lambda () (interactive)
14560 (org-eval-in-calendar '(calendar-backward-day 1))))
14561 (org-defkey minibuffer-local-map [(shift right)]
14562 (lambda () (interactive)
14563 (org-eval-in-calendar '(calendar-forward-day 1))))
14564 (org-defkey minibuffer-local-map ">"
14565 (lambda () (interactive)
14566 (org-eval-in-calendar '(scroll-calendar-left 1))))
14567 (org-defkey minibuffer-local-map "<"
14568 (lambda () (interactive)
14569 (org-eval-in-calendar '(scroll-calendar-right 1))))
14570 (org-defkey minibuffer-local-map "\C-v"
14571 (lambda () (interactive)
14572 (org-eval-in-calendar
14573 '(calendar-scroll-left-three-months 1))))
14574 (org-defkey minibuffer-local-map "\M-v"
14575 (lambda () (interactive)
14576 (org-eval-in-calendar
14577 '(calendar-scroll-right-three-months 1))))
14578 (run-hooks 'org-read-date-minibuffer-setup-hook)
14579 (unwind-protect
14580 (progn
14581 (use-local-map map)
14582 (add-hook 'post-command-hook 'org-read-date-display)
14583 (setq org-ans0 (read-string prompt default-input
14584 'org-read-date-history nil))
14585 ;; org-ans0: from prompt
14586 ;; org-ans1: from mouse click
14587 ;; org-ans2: from calendar motion
14588 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14589 (remove-hook 'post-command-hook 'org-read-date-display)
14590 (use-local-map old-map)
14591 (when org-read-date-overlay
14592 (delete-overlay org-read-date-overlay)
14593 (setq org-read-date-overlay nil)))))
14594 (bury-buffer "*Calendar*")))))
14596 (t ; Naked prompt only
14597 (unwind-protect
14598 (setq ans (read-string prompt default-input
14599 'org-read-date-history timestr))
14600 (when org-read-date-overlay
14601 (delete-overlay org-read-date-overlay)
14602 (setq org-read-date-overlay nil)))))
14604 (setq final (org-read-date-analyze ans def defdecode))
14606 (when org-read-date-analyze-forced-year
14607 (message "Year was forced into %s"
14608 (if org-read-date-force-compatible-dates
14609 "compatible range (1970-2037)"
14610 "range representable on this machine"))
14611 (ding))
14613 ;; One round trip to get rid of 34th of August and stuff like that....
14614 (setq final (decode-time (apply 'encode-time final)))
14616 (setq org-read-date-final-answer ans)
14618 (if to-time
14619 (apply 'encode-time final)
14620 (if (and (boundp 'org-time-was-given) org-time-was-given)
14621 (format "%04d-%02d-%02d %02d:%02d"
14622 (nth 5 final) (nth 4 final) (nth 3 final)
14623 (nth 2 final) (nth 1 final))
14624 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14626 (defvar def)
14627 (defvar defdecode)
14628 (defvar with-time)
14629 (defun org-read-date-display ()
14630 "Display the current date prompt interpretation in the minibuffer."
14631 (when org-read-date-display-live
14632 (when org-read-date-overlay
14633 (delete-overlay org-read-date-overlay))
14634 (let ((p (point)))
14635 (end-of-line 1)
14636 (while (not (equal (buffer-substring
14637 (max (point-min) (- (point) 4)) (point))
14638 " "))
14639 (insert " "))
14640 (goto-char p))
14641 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14642 " " (or org-ans1 org-ans2)))
14643 (org-end-time-was-given nil)
14644 (f (org-read-date-analyze ans def defdecode))
14645 (fmts (if org-dcst
14646 org-time-stamp-custom-formats
14647 org-time-stamp-formats))
14648 (fmt (if (or with-time
14649 (and (boundp 'org-time-was-given) org-time-was-given))
14650 (cdr fmts)
14651 (car fmts)))
14652 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14653 (when (and org-end-time-was-given
14654 (string-match org-plain-time-of-day-regexp txt))
14655 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14656 org-end-time-was-given
14657 (substring txt (match-end 0)))))
14658 (when org-read-date-analyze-futurep
14659 (setq txt (concat txt " (=>F)")))
14660 (setq org-read-date-overlay
14661 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14662 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14664 (defun org-read-date-analyze (ans def defdecode)
14665 "Analyze the combined answer of the date prompt."
14666 ;; FIXME: cleanup and comment
14667 (let ((nowdecode (decode-time (current-time)))
14668 delta deltan deltaw deltadef year month day
14669 hour minute second wday pm h2 m2 tl wday1
14670 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14671 (setq org-read-date-analyze-futurep nil
14672 org-read-date-analyze-forced-year nil)
14673 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14674 (setq ans "+0"))
14676 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14677 (setq ans (replace-match "" t t ans)
14678 deltan (car delta)
14679 deltaw (nth 1 delta)
14680 deltadef (nth 2 delta)))
14682 ;; Check if there is an iso week date in there
14683 ;; If yes, store the info and postpone interpreting it until the rest
14684 ;; of the parsing is done
14685 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14686 (setq iso-year (if (match-end 1)
14687 (org-small-year-to-year
14688 (string-to-number (match-string 1 ans))))
14689 iso-weekday (if (match-end 3)
14690 (string-to-number (match-string 3 ans)))
14691 iso-week (string-to-number (match-string 2 ans)))
14692 (setq ans (replace-match "" t t ans)))
14694 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14695 (when (string-match
14696 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14697 (setq year (if (match-end 2)
14698 (string-to-number (match-string 2 ans))
14699 (progn (setq kill-year t)
14700 (string-to-number (format-time-string "%Y"))))
14701 month (string-to-number (match-string 3 ans))
14702 day (string-to-number (match-string 4 ans)))
14703 (if (< year 100) (setq year (+ 2000 year)))
14704 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14705 t nil ans)))
14707 ;; Help matching dottet european dates
14708 (when (string-match
14709 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
14710 (setq year (if (match-end 3)
14711 (string-to-number (match-string 3 ans))
14712 (progn (setq kill-year t)
14713 (string-to-number (format-time-string "%Y"))))
14714 day (string-to-number (match-string 1 ans))
14715 month (string-to-number (match-string 2 ans))
14716 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14717 t nil ans)))
14719 ;; Help matching american dates, like 5/30 or 5/30/7
14720 (when (string-match
14721 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14722 (setq year (if (match-end 4)
14723 (string-to-number (match-string 4 ans))
14724 (progn (setq kill-year t)
14725 (string-to-number (format-time-string "%Y"))))
14726 month (string-to-number (match-string 1 ans))
14727 day (string-to-number (match-string 2 ans)))
14728 (if (< year 100) (setq year (+ 2000 year)))
14729 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14730 t nil ans)))
14731 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14732 ;; If there is a time with am/pm, and *no* time without it, we convert
14733 ;; so that matching will be successful.
14734 (loop for i from 1 to 2 do ; twice, for end time as well
14735 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14736 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14737 (setq hour (string-to-number (match-string 1 ans))
14738 minute (if (match-end 3)
14739 (string-to-number (match-string 3 ans))
14741 pm (equal ?p
14742 (string-to-char (downcase (match-string 4 ans)))))
14743 (if (and (= hour 12) (not pm))
14744 (setq hour 0)
14745 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14746 (setq ans (replace-match (format "%02d:%02d" hour minute)
14747 t t ans))))
14749 ;; Check if a time range is given as a duration
14750 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14751 (setq hour (string-to-number (match-string 1 ans))
14752 h2 (+ hour (string-to-number (match-string 3 ans)))
14753 minute (string-to-number (match-string 2 ans))
14754 m2 (+ minute (if (match-end 5) (string-to-number
14755 (match-string 5 ans))0)))
14756 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14757 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14758 t t ans)))
14760 ;; Check if there is a time range
14761 (when (boundp 'org-end-time-was-given)
14762 (setq org-time-was-given nil)
14763 (when (and (string-match org-plain-time-of-day-regexp ans)
14764 (match-end 8))
14765 (setq org-end-time-was-given (match-string 8 ans))
14766 (setq ans (concat (substring ans 0 (match-beginning 7))
14767 (substring ans (match-end 7))))))
14769 (setq tl (parse-time-string ans)
14770 day (or (nth 3 tl) (nth 3 defdecode))
14771 month (or (nth 4 tl)
14772 (if (and org-read-date-prefer-future
14773 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14774 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14775 (nth 4 defdecode)))
14776 year (or (and (not kill-year) (nth 5 tl))
14777 (if (and org-read-date-prefer-future
14778 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14779 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14780 (nth 5 defdecode)))
14781 hour (or (nth 2 tl) (nth 2 defdecode))
14782 minute (or (nth 1 tl) (nth 1 defdecode))
14783 second (or (nth 0 tl) 0)
14784 wday (nth 6 tl))
14786 (when (and (eq org-read-date-prefer-future 'time)
14787 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
14788 (equal day (nth 3 nowdecode))
14789 (equal month (nth 4 nowdecode))
14790 (equal year (nth 5 nowdecode))
14791 (nth 2 tl)
14792 (or (< (nth 2 tl) (nth 2 nowdecode))
14793 (and (= (nth 2 tl) (nth 2 nowdecode))
14794 (nth 1 tl)
14795 (< (nth 1 tl) (nth 1 nowdecode)))))
14796 (setq day (1+ day)
14797 futurep t))
14799 ;; Special date definitions below
14800 (cond
14801 (iso-week
14802 ;; There was an iso week
14803 (require 'cal-iso)
14804 (setq futurep nil)
14805 (setq year (or iso-year year)
14806 day (or iso-weekday wday 1)
14807 wday nil ; to make sure that the trigger below does not match
14808 iso-date (calendar-gregorian-from-absolute
14809 (calendar-absolute-from-iso
14810 (list iso-week day year))))
14811 ; FIXME: Should we also push ISO weeks into the future?
14812 ; (when (and org-read-date-prefer-future
14813 ; (not iso-year)
14814 ; (< (calendar-absolute-from-gregorian iso-date)
14815 ; (time-to-days (current-time))))
14816 ; (setq year (1+ year)
14817 ; iso-date (calendar-gregorian-from-absolute
14818 ; (calendar-absolute-from-iso
14819 ; (list iso-week day year)))))
14820 (setq month (car iso-date)
14821 year (nth 2 iso-date)
14822 day (nth 1 iso-date)))
14823 (deltan
14824 (setq futurep nil)
14825 (unless deltadef
14826 (let ((now (decode-time (current-time))))
14827 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14828 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14829 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14830 ((equal deltaw "m") (setq month (+ month deltan)))
14831 ((equal deltaw "y") (setq year (+ year deltan)))))
14832 ((and wday (not (nth 3 tl)))
14833 (setq futurep nil)
14834 ;; Weekday was given, but no day, so pick that day in the week
14835 ;; on or after the derived date.
14836 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14837 (unless (equal wday wday1)
14838 (setq day (+ day (% (- wday wday1 -7) 7))))))
14839 (if (and (boundp 'org-time-was-given)
14840 (nth 2 tl))
14841 (setq org-time-was-given t))
14842 (if (< year 100) (setq year (+ 2000 year)))
14843 ;; Check of the date is representable
14844 (if org-read-date-force-compatible-dates
14845 (progn
14846 (if (< year 1970)
14847 (setq year 1970 org-read-date-analyze-forced-year t))
14848 (if (> year 2037)
14849 (setq year 2037 org-read-date-analyze-forced-year t)))
14850 (condition-case nil
14851 (encode-time second minute hour day month year)
14852 (error
14853 (setq year (nth 5 defdecode))
14854 (setq org-read-date-analyze-forced-year t))))
14855 (setq org-read-date-analyze-futurep futurep)
14856 (list second minute hour day month year)))
14858 (defvar parse-time-weekdays)
14860 (defun org-read-date-get-relative (s today default)
14861 "Check string S for special relative date string.
14862 TODAY and DEFAULT are internal times, for today and for a default.
14863 Return shift list (N what def-flag)
14864 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
14865 N is the number of WHATs to shift.
14866 DEF-FLAG is t when a double ++ or -- indicates shift relative to
14867 the DEFAULT date rather than TODAY."
14868 (when (and
14869 (string-match
14870 (concat
14871 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14872 "\\([0-9]+\\)?"
14873 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14874 "\\([ \t]\\|$\\)") s)
14875 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
14876 (let* ((dir (if (> (match-end 1) (match-beginning 1))
14877 (string-to-char (substring (match-string 1 s) -1))
14878 ?+))
14879 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
14880 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
14881 (what (if (match-end 3) (match-string 3 s) "d"))
14882 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
14883 (date (if rel default today))
14884 (wday (nth 6 (decode-time date)))
14885 delta)
14886 (if wday1
14887 (progn
14888 (setq delta (mod (+ 7 (- wday1 wday)) 7))
14889 (if (= dir ?-) (setq delta (- delta 7)))
14890 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
14891 (list delta "d" rel))
14892 (list (* n (if (= dir ?-) -1 1)) what rel)))))
14894 (defun org-order-calendar-date-args (arg1 arg2 arg3)
14895 "Turn a user-specified date into the internal representation.
14896 The internal representation needed by the calendar is (month day year).
14897 This is a wrapper to handle the brain-dead convention in calendar that
14898 user function argument order change dependent on argument order."
14899 (if (boundp 'calendar-date-style)
14900 (cond
14901 ((eq calendar-date-style 'american)
14902 (list arg1 arg2 arg3))
14903 ((eq calendar-date-style 'european)
14904 (list arg2 arg1 arg3))
14905 ((eq calendar-date-style 'iso)
14906 (list arg2 arg3 arg1)))
14907 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
14908 (if (org-bound-and-true-p european-calendar-style)
14909 (list arg2 arg1 arg3)
14910 (list arg1 arg2 arg3)))))
14912 (defun org-eval-in-calendar (form &optional keepdate)
14913 "Eval FORM in the calendar window and return to current window.
14914 Also, store the cursor date in variable org-ans2."
14915 (let ((sf (selected-frame))
14916 (sw (selected-window)))
14917 (select-window (get-buffer-window "*Calendar*" t))
14918 (eval form)
14919 (when (and (not keepdate) (calendar-cursor-to-date))
14920 (let* ((date (calendar-cursor-to-date))
14921 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14922 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14923 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14924 (select-window sw)
14925 (org-select-frame-set-input-focus sf)))
14927 (defun org-calendar-select ()
14928 "Return to `org-read-date' with the date currently selected.
14929 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14930 (interactive)
14931 (when (calendar-cursor-to-date)
14932 (let* ((date (calendar-cursor-to-date))
14933 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14934 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14935 (if (active-minibuffer-window) (exit-minibuffer))))
14937 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14938 "Insert a date stamp for the date given by the internal TIME.
14939 WITH-HM means use the stamp format that includes the time of the day.
14940 INACTIVE means use square brackets instead of angular ones, so that the
14941 stamp will not contribute to the agenda.
14942 PRE and POST are optional strings to be inserted before and after the
14943 stamp.
14944 The command returns the inserted time stamp."
14945 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14946 stamp)
14947 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14948 (insert-before-markers (or pre ""))
14949 (when (listp extra)
14950 (setq extra (car extra))
14951 (if (and (stringp extra)
14952 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14953 (setq extra (format "-%02d:%02d"
14954 (string-to-number (match-string 1 extra))
14955 (string-to-number (match-string 2 extra))))
14956 (setq extra nil)))
14957 (when extra
14958 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
14959 (insert-before-markers (setq stamp (format-time-string fmt time)))
14960 (insert-before-markers (or post ""))
14961 (setq org-last-inserted-timestamp stamp)))
14963 (defun org-toggle-time-stamp-overlays ()
14964 "Toggle the use of custom time stamp formats."
14965 (interactive)
14966 (setq org-display-custom-times (not org-display-custom-times))
14967 (unless org-display-custom-times
14968 (let ((p (point-min)) (bmp (buffer-modified-p)))
14969 (while (setq p (next-single-property-change p 'display))
14970 (if (and (get-text-property p 'display)
14971 (eq (get-text-property p 'face) 'org-date))
14972 (remove-text-properties
14973 p (setq p (next-single-property-change p 'display))
14974 '(display t))))
14975 (set-buffer-modified-p bmp)))
14976 (if (featurep 'xemacs)
14977 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
14978 (org-restart-font-lock)
14979 (setq org-table-may-need-update t)
14980 (if org-display-custom-times
14981 (message "Time stamps are overlayed with custom format")
14982 (message "Time stamp overlays removed")))
14984 (defun org-display-custom-time (beg end)
14985 "Overlay modified time stamp format over timestamp between BEG and END."
14986 (let* ((ts (buffer-substring beg end))
14987 t1 w1 with-hm tf time str w2 (off 0))
14988 (save-match-data
14989 (setq t1 (org-parse-time-string ts t))
14990 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
14991 (setq off (- (match-end 0) (match-beginning 0)))))
14992 (setq end (- end off))
14993 (setq w1 (- end beg)
14994 with-hm (and (nth 1 t1) (nth 2 t1))
14995 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
14996 time (org-fix-decoded-time t1)
14997 str (org-add-props
14998 (format-time-string
14999 (substring tf 1 -1) (apply 'encode-time time))
15000 nil 'mouse-face 'highlight)
15001 w2 (length str))
15002 (if (not (= w2 w1))
15003 (add-text-properties (1+ beg) (+ 2 beg)
15004 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15005 (if (featurep 'xemacs)
15006 (progn
15007 (put-text-property beg end 'invisible t)
15008 (put-text-property beg end 'end-glyph (make-glyph str)))
15009 (put-text-property beg end 'display str))))
15011 (defun org-translate-time (string)
15012 "Translate all timestamps in STRING to custom format.
15013 But do this only if the variable `org-display-custom-times' is set."
15014 (when org-display-custom-times
15015 (save-match-data
15016 (let* ((start 0)
15017 (re org-ts-regexp-both)
15018 t1 with-hm inactive tf time str beg end)
15019 (while (setq start (string-match re string start))
15020 (setq beg (match-beginning 0)
15021 end (match-end 0)
15022 t1 (save-match-data
15023 (org-parse-time-string (substring string beg end) t))
15024 with-hm (and (nth 1 t1) (nth 2 t1))
15025 inactive (equal (substring string beg (1+ beg)) "[")
15026 tf (funcall (if with-hm 'cdr 'car)
15027 org-time-stamp-custom-formats)
15028 time (org-fix-decoded-time t1)
15029 str (format-time-string
15030 (concat
15031 (if inactive "[" "<") (substring tf 1 -1)
15032 (if inactive "]" ">"))
15033 (apply 'encode-time time))
15034 string (replace-match str t t string)
15035 start (+ start (length str)))))))
15036 string)
15038 (defun org-fix-decoded-time (time)
15039 "Set 0 instead of nil for the first 6 elements of time.
15040 Don't touch the rest."
15041 (let ((n 0))
15042 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15044 (defun org-days-to-time (timestamp-string)
15045 "Difference between TIMESTAMP-STRING and now in days."
15046 (- (time-to-days (org-time-string-to-time timestamp-string))
15047 (time-to-days (current-time))))
15049 (defun org-deadline-close (timestamp-string &optional ndays)
15050 "Is the time in TIMESTAMP-STRING close to the current date?"
15051 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15052 (and (< (org-days-to-time timestamp-string) ndays)
15053 (not (org-entry-is-done-p))))
15055 (defun org-get-wdays (ts)
15056 "Get the deadline lead time appropriate for timestring TS."
15057 (cond
15058 ((<= org-deadline-warning-days 0)
15059 ;; 0 or negative, enforce this value no matter what
15060 (- org-deadline-warning-days))
15061 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15062 ;; lead time is specified.
15063 (floor (* (string-to-number (match-string 1 ts))
15064 (cdr (assoc (match-string 2 ts)
15065 '(("d" . 1) ("w" . 7)
15066 ("m" . 30.4) ("y" . 365.25)))))))
15067 ;; go for the default.
15068 (t org-deadline-warning-days)))
15070 (defun org-calendar-select-mouse (ev)
15071 "Return to `org-read-date' with the date currently selected.
15072 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15073 (interactive "e")
15074 (mouse-set-point ev)
15075 (when (calendar-cursor-to-date)
15076 (let* ((date (calendar-cursor-to-date))
15077 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15078 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15079 (if (active-minibuffer-window) (exit-minibuffer))))
15081 (defun org-check-deadlines (ndays)
15082 "Check if there are any deadlines due or past due.
15083 A deadline is considered due if it happens within `org-deadline-warning-days'
15084 days from today's date. If the deadline appears in an entry marked DONE,
15085 it is not shown. The prefix arg NDAYS can be used to test that many
15086 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15087 (interactive "P")
15088 (let* ((org-warn-days
15089 (cond
15090 ((equal ndays '(4)) 100000)
15091 (ndays (prefix-numeric-value ndays))
15092 (t (abs org-deadline-warning-days))))
15093 (case-fold-search nil)
15094 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15095 (callback
15096 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15098 (message "%d deadlines past-due or due within %d days"
15099 (org-occur regexp nil callback)
15100 org-warn-days)))
15102 (defun org-check-before-date (date)
15103 "Check if there are deadlines or scheduled entries before DATE."
15104 (interactive (list (org-read-date)))
15105 (let ((case-fold-search nil)
15106 (regexp (concat "\\<\\(" org-deadline-string
15107 "\\|" org-scheduled-string
15108 "\\) *<\\([^>]+\\)>"))
15109 (callback
15110 (lambda () (time-less-p
15111 (org-time-string-to-time (match-string 2))
15112 (org-time-string-to-time date)))))
15113 (message "%d entries before %s"
15114 (org-occur regexp nil callback) date)))
15116 (defun org-check-after-date (date)
15117 "Check if there are deadlines or scheduled entries after DATE."
15118 (interactive (list (org-read-date)))
15119 (let ((case-fold-search nil)
15120 (regexp (concat "\\<\\(" org-deadline-string
15121 "\\|" org-scheduled-string
15122 "\\) *<\\([^>]+\\)>"))
15123 (callback
15124 (lambda () (not
15125 (time-less-p
15126 (org-time-string-to-time (match-string 2))
15127 (org-time-string-to-time date))))))
15128 (message "%d entries after %s"
15129 (org-occur regexp nil callback) date)))
15131 (defun org-evaluate-time-range (&optional to-buffer)
15132 "Evaluate a time range by computing the difference between start and end.
15133 Normally the result is just printed in the echo area, but with prefix arg
15134 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15135 If the time range is actually in a table, the result is inserted into the
15136 next column.
15137 For time difference computation, a year is assumed to be exactly 365
15138 days in order to avoid rounding problems."
15139 (interactive "P")
15141 (org-clock-update-time-maybe)
15142 (save-excursion
15143 (unless (org-at-date-range-p t)
15144 (goto-char (point-at-bol))
15145 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15146 (if (not (org-at-date-range-p t))
15147 (error "Not at a time-stamp range, and none found in current line")))
15148 (let* ((ts1 (match-string 1))
15149 (ts2 (match-string 2))
15150 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15151 (match-end (match-end 0))
15152 (time1 (org-time-string-to-time ts1))
15153 (time2 (org-time-string-to-time ts2))
15154 (t1 (org-float-time time1))
15155 (t2 (org-float-time time2))
15156 (diff (abs (- t2 t1)))
15157 (negative (< (- t2 t1) 0))
15158 ;; (ys (floor (* 365 24 60 60)))
15159 (ds (* 24 60 60))
15160 (hs (* 60 60))
15161 (fy "%dy %dd %02d:%02d")
15162 (fy1 "%dy %dd")
15163 (fd "%dd %02d:%02d")
15164 (fd1 "%dd")
15165 (fh "%02d:%02d")
15166 y d h m align)
15167 (if havetime
15168 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15170 d (floor (/ diff ds)) diff (mod diff ds)
15171 h (floor (/ diff hs)) diff (mod diff hs)
15172 m (floor (/ diff 60)))
15173 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15175 d (floor (+ (/ diff ds) 0.5))
15176 h 0 m 0))
15177 (if (not to-buffer)
15178 (message "%s" (org-make-tdiff-string y d h m))
15179 (if (org-at-table-p)
15180 (progn
15181 (goto-char match-end)
15182 (setq align t)
15183 (and (looking-at " *|") (goto-char (match-end 0))))
15184 (goto-char match-end))
15185 (if (looking-at
15186 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15187 (replace-match ""))
15188 (if negative (insert " -"))
15189 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15190 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15191 (insert " " (format fh h m))))
15192 (if align (org-table-align))
15193 (message "Time difference inserted")))))
15195 (defun org-make-tdiff-string (y d h m)
15196 (let ((fmt "")
15197 (l nil))
15198 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15199 l (push y l)))
15200 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15201 l (push d l)))
15202 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15203 l (push h l)))
15204 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15205 l (push m l)))
15206 (apply 'format fmt (nreverse l))))
15208 (defun org-time-string-to-time (s)
15209 (apply 'encode-time (org-parse-time-string s)))
15210 (defun org-time-string-to-seconds (s)
15211 (org-float-time (org-time-string-to-time s)))
15213 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
15214 "Convert a time stamp to an absolute day number.
15215 If there is a specifier for a cyclic time stamp, get the closest date to
15216 DAYNR.
15217 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15218 The variable date is bound by the calendar when this is called."
15219 (cond
15220 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15221 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15222 daynr
15223 (+ daynr 1000)))
15224 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15225 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15226 (time-to-days (current-time))) (match-string 0 s)
15227 prefer show-all))
15228 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
15230 (defun org-days-to-iso-week (days)
15231 "Return the iso week number."
15232 (require 'cal-iso)
15233 (car (calendar-iso-from-absolute days)))
15235 (defun org-small-year-to-year (year)
15236 "Convert 2-digit years into 4-digit years.
15237 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15238 The year 2000 cannot be abbreviated. Any year larger than 99
15239 is returned unchanged."
15240 (if (< year 38)
15241 (setq year (+ 2000 year))
15242 (if (< year 100)
15243 (setq year (+ 1900 year))))
15244 year)
15246 (defun org-time-from-absolute (d)
15247 "Return the time corresponding to date D.
15248 D may be an absolute day number, or a calendar-type list (month day year)."
15249 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15250 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15252 (defun org-calendar-holiday ()
15253 "List of holidays, for Diary display in Org-mode."
15254 (require 'holidays)
15255 (let ((hl (funcall
15256 (if (fboundp 'calendar-check-holidays)
15257 'calendar-check-holidays 'check-calendar-holidays) date)))
15258 (if hl (mapconcat 'identity hl "; "))))
15260 (defun org-diary-sexp-entry (sexp entry date)
15261 "Process a SEXP diary ENTRY for DATE."
15262 (require 'diary-lib)
15263 (let ((result (if calendar-debug-sexp
15264 (let ((stack-trace-on-error t))
15265 (eval (car (read-from-string sexp))))
15266 (condition-case nil
15267 (eval (car (read-from-string sexp)))
15268 (error
15269 (beep)
15270 (message "Bad sexp at line %d in %s: %s"
15271 (org-current-line)
15272 (buffer-file-name) sexp)
15273 (sleep-for 2))))))
15274 (cond ((stringp result) (split-string result "; "))
15275 ((and (consp result)
15276 (not (consp (cdr result)))
15277 (stringp (cdr result))) (cdr result))
15278 ((and (consp result)
15279 (stringp (car result))) result)
15280 (result entry)
15281 (t nil))))
15283 (defun org-diary-to-ical-string (frombuf)
15284 "Get iCalendar entries from diary entries in buffer FROMBUF.
15285 This uses the icalendar.el library."
15286 (let* ((tmpdir (if (featurep 'xemacs)
15287 (temp-directory)
15288 temporary-file-directory))
15289 (tmpfile (make-temp-name
15290 (expand-file-name "orgics" tmpdir)))
15291 buf rtn b e)
15292 (with-current-buffer frombuf
15293 (icalendar-export-region (point-min) (point-max) tmpfile)
15294 (setq buf (find-buffer-visiting tmpfile))
15295 (set-buffer buf)
15296 (goto-char (point-min))
15297 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15298 (setq b (match-beginning 0)))
15299 (goto-char (point-max))
15300 (if (re-search-backward "^END:VEVENT" nil t)
15301 (setq e (match-end 0)))
15302 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15303 (kill-buffer buf)
15304 (delete-file tmpfile)
15305 rtn))
15307 (defun org-closest-date (start current change prefer show-all)
15308 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15309 When PREFER is `past', return a date that is either CURRENT or past.
15310 When PREFER is `future', return a date that is either CURRENT or future.
15311 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15312 ;; Make the proper lists from the dates
15313 (catch 'exit
15314 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15315 dn dw sday cday n1 n2 n0
15316 d m y y1 y2 date1 date2 nmonths nm ny m2)
15318 (setq start (org-date-to-gregorian start)
15319 current (org-date-to-gregorian
15320 (if show-all
15321 current
15322 (time-to-days (current-time))))
15323 sday (calendar-absolute-from-gregorian start)
15324 cday (calendar-absolute-from-gregorian current))
15326 (if (<= cday sday) (throw 'exit sday))
15328 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15329 (setq dn (string-to-number (match-string 1 change))
15330 dw (cdr (assoc (match-string 2 change) a1)))
15331 (error "Invalid change specifier: %s" change))
15332 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15333 (cond
15334 ((eq dw 'day)
15335 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15336 n2 (+ n1 dn)))
15337 ((eq dw 'year)
15338 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15339 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15340 (setq date1 (list m d y1)
15341 n1 (calendar-absolute-from-gregorian date1)
15342 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15343 n2 (calendar-absolute-from-gregorian date2)))
15344 ((eq dw 'month)
15345 ;; approx number of month between the two dates
15346 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15347 ;; How often does dn fit in there?
15348 (setq d (nth 1 start) m (car start) y (nth 2 start)
15349 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15350 m (+ m nm)
15351 ny (floor (/ m 12))
15352 y (+ y ny)
15353 m (- m (* ny 12)))
15354 (while (> m 12) (setq m (- m 12) y (1+ y)))
15355 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15356 (setq m2 (+ m dn) y2 y)
15357 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15358 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15359 (while (<= n2 cday)
15360 (setq n1 n2 m m2 y y2)
15361 (setq m2 (+ m dn) y2 y)
15362 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15363 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15364 ;; Make sure n1 is the earlier date
15365 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15366 (if show-all
15367 (cond
15368 ((eq prefer 'past) (if (= cday n2) n2 n1))
15369 ((eq prefer 'future) (if (= cday n1) n1 n2))
15370 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15371 (cond
15372 ((eq prefer 'past) (if (= cday n2) n2 n1))
15373 ((eq prefer 'future) (if (= cday n1) n1 n2))
15374 (t (if (= cday n1) n1 n2)))))))
15376 (defun org-date-to-gregorian (date)
15377 "Turn any specification of DATE into a Gregorian date for the calendar."
15378 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15379 ((and (listp date) (= (length date) 3)) date)
15380 ((stringp date)
15381 (setq date (org-parse-time-string date))
15382 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15383 ((listp date)
15384 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15386 (defun org-parse-time-string (s &optional nodefault)
15387 "Parse the standard Org-mode time string.
15388 This should be a lot faster than the normal `parse-time-string'.
15389 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15390 hour and minute fields will be nil if not given."
15391 (if (string-match org-ts-regexp0 s)
15392 (list 0
15393 (if (or (match-beginning 8) (not nodefault))
15394 (string-to-number (or (match-string 8 s) "0")))
15395 (if (or (match-beginning 7) (not nodefault))
15396 (string-to-number (or (match-string 7 s) "0")))
15397 (string-to-number (match-string 4 s))
15398 (string-to-number (match-string 3 s))
15399 (string-to-number (match-string 2 s))
15400 nil nil nil)
15401 (error "Not a standard Org-mode time string: %s" s)))
15403 (defun org-timestamp-up (&optional arg)
15404 "Increase the date item at the cursor by one.
15405 If the cursor is on the year, change the year. If it is on the month or
15406 the day, change that.
15407 With prefix ARG, change by that many units."
15408 (interactive "p")
15409 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15411 (defun org-timestamp-down (&optional arg)
15412 "Decrease the date item at the cursor by one.
15413 If the cursor is on the year, change the year. If it is on the month or
15414 the day, change that.
15415 With prefix ARG, change by that many units."
15416 (interactive "p")
15417 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15419 (defun org-timestamp-up-day (&optional arg)
15420 "Increase the date in the time stamp by one day.
15421 With prefix ARG, change that many days."
15422 (interactive "p")
15423 (if (and (not (org-at-timestamp-p t))
15424 (org-on-heading-p))
15425 (org-todo 'up)
15426 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15428 (defun org-timestamp-down-day (&optional arg)
15429 "Decrease the date in the time stamp by one day.
15430 With prefix ARG, change that many days."
15431 (interactive "p")
15432 (if (and (not (org-at-timestamp-p t))
15433 (org-on-heading-p))
15434 (org-todo 'down)
15435 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15437 (defun org-at-timestamp-p (&optional inactive-ok)
15438 "Determine if the cursor is in or at a timestamp."
15439 (interactive)
15440 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15441 (pos (point))
15442 (ans (or (looking-at tsr)
15443 (save-excursion
15444 (skip-chars-backward "^[<\n\r\t")
15445 (if (> (point) (point-min)) (backward-char 1))
15446 (and (looking-at tsr)
15447 (> (- (match-end 0) pos) -1))))))
15448 (and ans
15449 (boundp 'org-ts-what)
15450 (setq org-ts-what
15451 (cond
15452 ((= pos (match-beginning 0)) 'bracket)
15453 ((= pos (1- (match-end 0))) 'bracket)
15454 ((org-pos-in-match-range pos 2) 'year)
15455 ((org-pos-in-match-range pos 3) 'month)
15456 ((org-pos-in-match-range pos 7) 'hour)
15457 ((org-pos-in-match-range pos 8) 'minute)
15458 ((or (org-pos-in-match-range pos 4)
15459 (org-pos-in-match-range pos 5)) 'day)
15460 ((and (> pos (or (match-end 8) (match-end 5)))
15461 (< pos (match-end 0)))
15462 (- pos (or (match-end 8) (match-end 5))))
15463 (t 'day))))
15464 ans))
15466 (defun org-toggle-timestamp-type ()
15467 "Toggle the type (<active> or [inactive]) of a time stamp."
15468 (interactive)
15469 (when (org-at-timestamp-p t)
15470 (let ((beg (match-beginning 0)) (end (match-end 0))
15471 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15472 (save-excursion
15473 (goto-char beg)
15474 (while (re-search-forward "[][<>]" end t)
15475 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15476 t t)))
15477 (message "Timestamp is now %sactive"
15478 (if (equal (char-after beg) ?<) "" "in")))))
15480 (defun org-timestamp-change (n &optional what updown)
15481 "Change the date in the time stamp at point.
15482 The date will be changed by N times WHAT. WHAT can be `day', `month',
15483 `year', `minute', `second'. If WHAT is not given, the cursor position
15484 in the timestamp determines what will be changed."
15485 (let ((pos (point))
15486 with-hm inactive
15487 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15488 org-ts-what
15489 extra rem
15490 ts time time0)
15491 (if (not (org-at-timestamp-p t))
15492 (error "Not at a timestamp"))
15493 (if (and (not what) (eq org-ts-what 'bracket))
15494 (org-toggle-timestamp-type)
15495 (if (and (not what) (not (eq org-ts-what 'day))
15496 org-display-custom-times
15497 (get-text-property (point) 'display)
15498 (not (get-text-property (1- (point)) 'display)))
15499 (setq org-ts-what 'day))
15500 (setq org-ts-what (or what org-ts-what)
15501 inactive (= (char-after (match-beginning 0)) ?\[)
15502 ts (match-string 0))
15503 (replace-match "")
15504 (if (string-match
15505 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15507 (setq extra (match-string 1 ts)))
15508 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15509 (setq with-hm t))
15510 (setq time0 (org-parse-time-string ts))
15511 (when (and updown
15512 (eq org-ts-what 'minute)
15513 (not current-prefix-arg))
15514 ;; This looks like s-up and s-down. Change by one rounding step.
15515 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15516 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15517 (setcar (cdr time0) (+ (nth 1 time0)
15518 (if (> n 0) (- rem) (- dm rem))))))
15519 (setq time
15520 (encode-time (or (car time0) 0)
15521 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15522 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15523 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15524 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15525 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15526 (nthcdr 6 time0)))
15527 (when (and (member org-ts-what '(hour minute))
15528 extra
15529 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15530 (setq extra (org-modify-ts-extra
15531 extra
15532 (if (eq org-ts-what 'hour) 2 5)
15533 n dm)))
15534 (when (integerp org-ts-what)
15535 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15536 (if (eq what 'calendar)
15537 (let ((cal-date (org-get-date-from-calendar)))
15538 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15539 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15540 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15541 (setcar time0 (or (car time0) 0))
15542 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15543 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15544 (setq time (apply 'encode-time time0))))
15545 (setq org-last-changed-timestamp
15546 (org-insert-time-stamp time with-hm inactive nil nil extra))
15547 (org-clock-update-time-maybe)
15548 (goto-char pos)
15549 ;; Try to recenter the calendar window, if any
15550 (if (and org-calendar-follow-timestamp-change
15551 (get-buffer-window "*Calendar*" t)
15552 (memq org-ts-what '(day month year)))
15553 (org-recenter-calendar (time-to-days time))))))
15555 (defun org-modify-ts-extra (s pos n dm)
15556 "Change the different parts of the lead-time and repeat fields in timestamp."
15557 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15558 ng h m new rem)
15559 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15560 (cond
15561 ((or (org-pos-in-match-range pos 2)
15562 (org-pos-in-match-range pos 3))
15563 (setq m (string-to-number (match-string 3 s))
15564 h (string-to-number (match-string 2 s)))
15565 (if (org-pos-in-match-range pos 2)
15566 (setq h (+ h n))
15567 (setq n (* dm (org-no-warnings (signum n))))
15568 (when (not (= 0 (setq rem (% m dm))))
15569 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15570 (setq m (+ m n)))
15571 (if (< m 0) (setq m (+ m 60) h (1- h)))
15572 (if (> m 59) (setq m (- m 60) h (1+ h)))
15573 (setq h (min 24 (max 0 h)))
15574 (setq ng 1 new (format "-%02d:%02d" h m)))
15575 ((org-pos-in-match-range pos 6)
15576 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15577 ((org-pos-in-match-range pos 5)
15578 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15580 ((org-pos-in-match-range pos 9)
15581 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15582 ((org-pos-in-match-range pos 8)
15583 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15585 (when ng
15586 (setq s (concat
15587 (substring s 0 (match-beginning ng))
15589 (substring s (match-end ng))))))
15592 (defun org-recenter-calendar (date)
15593 "If the calendar is visible, recenter it to DATE."
15594 (let* ((win (selected-window))
15595 (cwin (get-buffer-window "*Calendar*" t))
15596 (calendar-move-hook nil))
15597 (when cwin
15598 (select-window cwin)
15599 (calendar-goto-date (if (listp date) date
15600 (calendar-gregorian-from-absolute date)))
15601 (select-window win))))
15603 (defun org-goto-calendar (&optional arg)
15604 "Go to the Emacs calendar at the current date.
15605 If there is a time stamp in the current line, go to that date.
15606 A prefix ARG can be used to force the current date."
15607 (interactive "P")
15608 (let ((tsr org-ts-regexp) diff
15609 (calendar-move-hook nil)
15610 (calendar-view-holidays-initially-flag nil)
15611 (calendar-view-diary-initially-flag nil))
15612 (if (or (org-at-timestamp-p)
15613 (save-excursion
15614 (beginning-of-line 1)
15615 (looking-at (concat ".*" tsr))))
15616 (let ((d1 (time-to-days (current-time)))
15617 (d2 (time-to-days
15618 (org-time-string-to-time (match-string 1)))))
15619 (setq diff (- d2 d1))))
15620 (calendar)
15621 (calendar-goto-today)
15622 (if (and diff (not arg)) (calendar-forward-day diff))))
15624 (defun org-get-date-from-calendar ()
15625 "Return a list (month day year) of date at point in calendar."
15626 (with-current-buffer "*Calendar*"
15627 (save-match-data
15628 (calendar-cursor-to-date))))
15630 (defun org-date-from-calendar ()
15631 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15632 If there is already a time stamp at the cursor position, update it."
15633 (interactive)
15634 (if (org-at-timestamp-p t)
15635 (org-timestamp-change 0 'calendar)
15636 (let ((cal-date (org-get-date-from-calendar)))
15637 (org-insert-time-stamp
15638 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15640 (defun org-minutes-to-hh:mm-string (m)
15641 "Compute H:MM from a number of minutes."
15642 (let ((h (/ m 60)))
15643 (setq m (- m (* 60 h)))
15644 (format org-time-clocksum-format h m)))
15646 (defun org-hh:mm-string-to-minutes (s)
15647 "Convert a string H:MM to a number of minutes.
15648 If the string is just a number, interpret it as minutes.
15649 In fact, the first hh:mm or number in the string will be taken,
15650 there can be extra stuff in the string.
15651 If no number is found, the return value is 0."
15652 (cond
15653 ((integerp s) s)
15654 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
15655 (+ (* (string-to-number (match-string 1 s)) 60)
15656 (string-to-number (match-string 2 s))))
15657 ((string-match "\\([0-9]+\\)" s)
15658 (string-to-number (match-string 1 s)))
15659 (t 0)))
15661 (defcustom org-effort-durations
15662 `(("h" . 60)
15663 ("d" . ,(* 60 8))
15664 ("w" . ,(* 60 8 5))
15665 ("m" . ,(* 60 8 5 4))
15666 ("y" . ,(* 60 8 5 40)))
15667 "Conversion factor to minutes for an effort modifier.
15669 Each entry has the form (MODIFIER . MINUTES).
15671 In an effort string, a number followed by MODIFIER is multiplied
15672 by the specified number of MINUTES to obtain an effort in
15673 minutes.
15675 For example, if the value of this variable is ((\"hours\" . 60)), then an
15676 effort string \"2hours\" is equivalent to 120 minutes."
15677 :group 'org-agenda
15678 :type '(alist :key-type (string :tag "Modifier")
15679 :value-type (number :tag "Minutes")))
15681 (defun org-duration-string-to-minutes (s)
15682 "Convert a duration string S to minutes.
15684 A bare number is interpreted as minutes, modifiers can be set by
15685 customizing `org-effort-durations' (which see).
15687 Entries containing a colon are interpreted as H:MM by
15688 `org-hh:mm-string-to-minutes'."
15689 (let ((result 0)
15690 (re (concat "\\([0-9]+\\) *\\("
15691 (regexp-opt (mapcar 'car org-effort-durations))
15692 "\\)")))
15693 (while (string-match re s)
15694 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
15695 (string-to-number (match-string 1 s))))
15696 (setq s (replace-match "" nil t s)))
15697 (incf result (org-hh:mm-string-to-minutes s))
15698 result))
15700 ;;;; Files
15702 (defun org-save-all-org-buffers ()
15703 "Save all Org-mode buffers without user confirmation."
15704 (interactive)
15705 (message "Saving all Org-mode buffers...")
15706 (save-some-buffers t 'org-mode-p)
15707 (when (featurep 'org-id) (org-id-locations-save))
15708 (message "Saving all Org-mode buffers... done"))
15710 (defun org-revert-all-org-buffers ()
15711 "Revert all Org-mode buffers.
15712 Prompt for confirmation when there are unsaved changes.
15713 Be sure you know what you are doing before letting this function
15714 overwrite your changes.
15716 This function is useful in a setup where one tracks org files
15717 with a version control system, to revert on one machine after pulling
15718 changes from another. I believe the procedure must be like this:
15720 1. M-x org-save-all-org-buffers
15721 2. Pull changes from the other machine, resolve conflicts
15722 3. M-x org-revert-all-org-buffers"
15723 (interactive)
15724 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
15725 (error "Abort"))
15726 (save-excursion
15727 (save-window-excursion
15728 (mapc
15729 (lambda (b)
15730 (when (and (with-current-buffer b (org-mode-p))
15731 (with-current-buffer b buffer-file-name))
15732 (switch-to-buffer b)
15733 (revert-buffer t 'no-confirm)))
15734 (buffer-list))
15735 (when (and (featurep 'org-id) org-id-track-globally)
15736 (org-id-locations-load)))))
15738 ;;;; Agenda files
15740 ;;;###autoload
15741 (defun org-switchb (&optional arg)
15742 "Switch between Org buffers.
15743 With a prefix argument, restrict available to files.
15744 With two prefix arguments, restrict available buffers to agenda files.
15746 Defaults to `iswitchb' for buffer name completion.
15747 Set `org-completion-use-ido' to make it use ido instead."
15748 (interactive "P")
15749 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
15750 ((equal arg '(16)) (org-buffer-list 'agenda))
15751 (t (org-buffer-list))))
15752 (org-completion-use-iswitchb org-completion-use-iswitchb)
15753 (org-completion-use-ido org-completion-use-ido))
15754 (unless (or org-completion-use-ido org-completion-use-iswitchb)
15755 (setq org-completion-use-iswitchb t))
15756 (switch-to-buffer
15757 (org-icompleting-read "Org buffer: "
15758 (mapcar 'list (mapcar 'buffer-name blist))
15759 nil t))))
15761 ;;; Define some older names previously used for this functionality
15762 ;;;###autoload
15763 (defalias 'org-ido-switchb 'org-switchb)
15764 ;;;###autoload
15765 (defalias 'org-iswitchb 'org-switchb)
15767 (defun org-buffer-list (&optional predicate exclude-tmp)
15768 "Return a list of Org buffers.
15769 PREDICATE can be `export', `files' or `agenda'.
15771 export restrict the list to Export buffers.
15772 files restrict the list to buffers visiting Org files.
15773 agenda restrict the list to buffers visiting agenda files.
15775 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
15776 (let* ((bfn nil)
15777 (agenda-files (and (eq predicate 'agenda)
15778 (mapcar 'file-truename (org-agenda-files t))))
15779 (filter
15780 (cond
15781 ((eq predicate 'files)
15782 (lambda (b) (with-current-buffer b (org-mode-p))))
15783 ((eq predicate 'export)
15784 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
15785 ((eq predicate 'agenda)
15786 (lambda (b)
15787 (with-current-buffer b
15788 (and (org-mode-p)
15789 (setq bfn (buffer-file-name b))
15790 (member (file-truename bfn) agenda-files)))))
15791 (t (lambda (b) (with-current-buffer b
15792 (or (org-mode-p)
15793 (string-match "\*Org .*Export"
15794 (buffer-name b)))))))))
15795 (delq nil
15796 (mapcar
15797 (lambda(b)
15798 (if (and (funcall filter b)
15799 (or (not exclude-tmp)
15800 (not (string-match "tmp" (buffer-name b)))))
15802 nil))
15803 (buffer-list)))))
15805 (defun org-agenda-files (&optional unrestricted archives)
15806 "Get the list of agenda files.
15807 Optional UNRESTRICTED means return the full list even if a restriction
15808 is currently in place.
15809 When ARCHIVES is t, include all archive files that are really being
15810 used by the agenda files. If ARCHIVE is `ifmode', do this only if
15811 `org-agenda-archives-mode' is t."
15812 (let ((files
15813 (cond
15814 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
15815 ((stringp org-agenda-files) (org-read-agenda-file-list))
15816 ((listp org-agenda-files) org-agenda-files)
15817 (t (error "Invalid value of `org-agenda-files'")))))
15818 (setq files (apply 'append
15819 (mapcar (lambda (f)
15820 (if (file-directory-p f)
15821 (directory-files
15822 f t org-agenda-file-regexp)
15823 (list f)))
15824 files)))
15825 (when org-agenda-skip-unavailable-files
15826 (setq files (delq nil
15827 (mapcar (function
15828 (lambda (file)
15829 (and (file-readable-p file) file)))
15830 files))))
15831 (when (or (eq archives t)
15832 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
15833 (setq files (org-add-archive-files files)))
15834 files))
15836 (defun org-agenda-file-p (&optional file)
15837 "Return non-nil, if FILE is an agenda file.
15838 If FILE is omitted, use the file associated with the current
15839 buffer."
15840 (member (or file (buffer-file-name))
15841 (org-agenda-files t)))
15843 (defun org-edit-agenda-file-list ()
15844 "Edit the list of agenda files.
15845 Depending on setup, this either uses customize to edit the variable
15846 `org-agenda-files', or it visits the file that is holding the list. In the
15847 latter case, the buffer is set up in a way that saving it automatically kills
15848 the buffer and restores the previous window configuration."
15849 (interactive)
15850 (if (stringp org-agenda-files)
15851 (let ((cw (current-window-configuration)))
15852 (find-file org-agenda-files)
15853 (org-set-local 'org-window-configuration cw)
15854 (org-add-hook 'after-save-hook
15855 (lambda ()
15856 (set-window-configuration
15857 (prog1 org-window-configuration
15858 (kill-buffer (current-buffer))))
15859 (org-install-agenda-files-menu)
15860 (message "New agenda file list installed"))
15861 nil 'local)
15862 (message "%s" (substitute-command-keys
15863 "Edit list and finish with \\[save-buffer]")))
15864 (customize-variable 'org-agenda-files)))
15866 (defun org-store-new-agenda-file-list (list)
15867 "Set new value for the agenda file list and save it correctly."
15868 (if (stringp org-agenda-files)
15869 (let ((fe (org-read-agenda-file-list t)) b u)
15870 (while (setq b (find-buffer-visiting org-agenda-files))
15871 (kill-buffer b))
15872 (with-temp-file org-agenda-files
15873 (insert
15874 (mapconcat
15875 (lambda (f) ;; Keep un-expanded entries.
15876 (if (setq u (assoc f fe))
15877 (cdr u)
15879 list "\n")
15880 "\n")))
15881 (let ((org-mode-hook nil) (org-inhibit-startup t)
15882 (org-insert-mode-line-in-empty-file nil))
15883 (setq org-agenda-files list)
15884 (customize-save-variable 'org-agenda-files org-agenda-files))))
15886 (defun org-read-agenda-file-list (&optional pair-with-expansion)
15887 "Read the list of agenda files from a file.
15888 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
15889 filenames, used by `org-store-new-agenda-file-list' to write back
15890 un-expanded file names."
15891 (when (file-directory-p org-agenda-files)
15892 (error "`org-agenda-files' cannot be a single directory"))
15893 (when (stringp org-agenda-files)
15894 (with-temp-buffer
15895 (insert-file-contents org-agenda-files)
15896 (mapcar
15897 (lambda (f)
15898 (let ((e (expand-file-name (substitute-in-file-name f)
15899 org-directory)))
15900 (if pair-with-expansion
15901 (cons e f)
15902 e)))
15903 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
15905 ;;;###autoload
15906 (defun org-cycle-agenda-files ()
15907 "Cycle through the files in `org-agenda-files'.
15908 If the current buffer visits an agenda file, find the next one in the list.
15909 If the current buffer does not, find the first agenda file."
15910 (interactive)
15911 (let* ((fs (org-agenda-files t))
15912 (files (append fs (list (car fs))))
15913 (tcf (if buffer-file-name (file-truename buffer-file-name)))
15914 file)
15915 (unless files (error "No agenda files"))
15916 (catch 'exit
15917 (while (setq file (pop files))
15918 (if (equal (file-truename file) tcf)
15919 (when (car files)
15920 (find-file (car files))
15921 (throw 'exit t))))
15922 (find-file (car fs)))
15923 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
15925 (defun org-agenda-file-to-front (&optional to-end)
15926 "Move/add the current file to the top of the agenda file list.
15927 If the file is not present in the list, it is added to the front. If it is
15928 present, it is moved there. With optional argument TO-END, add/move to the
15929 end of the list."
15930 (interactive "P")
15931 (let ((org-agenda-skip-unavailable-files nil)
15932 (file-alist (mapcar (lambda (x)
15933 (cons (file-truename x) x))
15934 (org-agenda-files t)))
15935 (ctf (file-truename buffer-file-name))
15936 x had)
15937 (setq x (assoc ctf file-alist) had x)
15939 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
15940 (if to-end
15941 (setq file-alist (append (delq x file-alist) (list x)))
15942 (setq file-alist (cons x (delq x file-alist))))
15943 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
15944 (org-install-agenda-files-menu)
15945 (message "File %s to %s of agenda file list"
15946 (if had "moved" "added") (if to-end "end" "front"))))
15948 (defun org-remove-file (&optional file)
15949 "Remove current file from the list of files in variable `org-agenda-files'.
15950 These are the files which are being checked for agenda entries.
15951 Optional argument FILE means use this file instead of the current."
15952 (interactive)
15953 (let* ((org-agenda-skip-unavailable-files nil)
15954 (file (or file buffer-file-name))
15955 (true-file (file-truename file))
15956 (afile (abbreviate-file-name file))
15957 (files (delq nil (mapcar
15958 (lambda (x)
15959 (if (equal true-file
15960 (file-truename x))
15961 nil x))
15962 (org-agenda-files t)))))
15963 (if (not (= (length files) (length (org-agenda-files t))))
15964 (progn
15965 (org-store-new-agenda-file-list files)
15966 (org-install-agenda-files-menu)
15967 (message "Removed file: %s" afile))
15968 (message "File was not in list: %s (not removed)" afile))))
15970 (defun org-file-menu-entry (file)
15971 (vector file (list 'find-file file) t))
15973 (defun org-check-agenda-file (file)
15974 "Make sure FILE exists. If not, ask user what to do."
15975 (when (not (file-exists-p file))
15976 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
15977 (abbreviate-file-name file))
15978 (let ((r (downcase (read-char-exclusive))))
15979 (cond
15980 ((equal r ?r)
15981 (org-remove-file file)
15982 (throw 'nextfile t))
15983 (t (error "Abort"))))))
15985 (defun org-get-agenda-file-buffer (file)
15986 "Get a buffer visiting FILE. If the buffer needs to be created, add
15987 it to the list of buffers which might be released later."
15988 (let ((buf (org-find-base-buffer-visiting file)))
15989 (if buf
15990 buf ; just return it
15991 ;; Make a new buffer and remember it
15992 (setq buf (find-file-noselect file))
15993 (if buf (push buf org-agenda-new-buffers))
15994 buf)))
15996 (defun org-release-buffers (blist)
15997 "Release all buffers in list, asking the user for confirmation when needed.
15998 When a buffer is unmodified, it is just killed. When modified, it is saved
15999 \(if the user agrees) and then killed."
16000 (let (buf file)
16001 (while (setq buf (pop blist))
16002 (setq file (buffer-file-name buf))
16003 (when (and (buffer-modified-p buf)
16004 file
16005 (y-or-n-p (format "Save file %s? " file)))
16006 (with-current-buffer buf (save-buffer)))
16007 (kill-buffer buf))))
16009 (defun org-prepare-agenda-buffers (files)
16010 "Create buffers for all agenda files, protect archived trees and comments."
16011 (interactive)
16012 (let ((pa '(:org-archived t))
16013 (pc '(:org-comment t))
16014 (pall '(:org-archived t :org-comment t))
16015 (inhibit-read-only t)
16016 (rea (concat ":" org-archive-tag ":"))
16017 bmp file re)
16018 (save-excursion
16019 (save-restriction
16020 (while (setq file (pop files))
16021 (catch 'nextfile
16022 (if (bufferp file)
16023 (set-buffer file)
16024 (org-check-agenda-file file)
16025 (set-buffer (org-get-agenda-file-buffer file)))
16026 (widen)
16027 (setq bmp (buffer-modified-p))
16028 (org-refresh-category-properties)
16029 (setq org-todo-keywords-for-agenda
16030 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16031 (setq org-done-keywords-for-agenda
16032 (append org-done-keywords-for-agenda org-done-keywords))
16033 (setq org-todo-keyword-alist-for-agenda
16034 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16035 (setq org-drawers-for-agenda
16036 (append org-drawers-for-agenda org-drawers))
16037 (setq org-tag-alist-for-agenda
16038 (append org-tag-alist-for-agenda org-tag-alist))
16040 (save-excursion
16041 (remove-text-properties (point-min) (point-max) pall)
16042 (when org-agenda-skip-archived-trees
16043 (goto-char (point-min))
16044 (while (re-search-forward rea nil t)
16045 (if (org-on-heading-p t)
16046 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16047 (goto-char (point-min))
16048 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
16049 (while (re-search-forward re nil t)
16050 (add-text-properties
16051 (match-beginning 0) (org-end-of-subtree t) pc)))
16052 (set-buffer-modified-p bmp)))))
16053 (setq org-todo-keywords-for-agenda
16054 (org-uniquify org-todo-keywords-for-agenda))
16055 (setq org-todo-keyword-alist-for-agenda
16056 (org-uniquify org-todo-keyword-alist-for-agenda)
16057 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16059 ;;;; Embedded LaTeX
16061 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16062 "Keymap for the minor `org-cdlatex-mode'.")
16064 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16065 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16066 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16067 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16068 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16070 (defvar org-cdlatex-texmathp-advice-is-done nil
16071 "Flag remembering if we have applied the advice to texmathp already.")
16073 (define-minor-mode org-cdlatex-mode
16074 "Toggle the minor `org-cdlatex-mode'.
16075 This mode supports entering LaTeX environment and math in LaTeX fragments
16076 in Org-mode.
16077 \\{org-cdlatex-mode-map}"
16078 nil " OCDL" nil
16079 (when org-cdlatex-mode (require 'cdlatex))
16080 (unless org-cdlatex-texmathp-advice-is-done
16081 (setq org-cdlatex-texmathp-advice-is-done t)
16082 (defadvice texmathp (around org-math-always-on activate)
16083 "Always return t in org-mode buffers.
16084 This is because we want to insert math symbols without dollars even outside
16085 the LaTeX math segments. If Orgmode thinks that point is actually inside
16086 an embedded LaTeX fragment, let texmathp do its job.
16087 \\[org-cdlatex-mode-map]"
16088 (interactive)
16089 (let (p)
16090 (cond
16091 ((not (org-mode-p)) ad-do-it)
16092 ((eq this-command 'cdlatex-math-symbol)
16093 (setq ad-return-value t
16094 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16096 (let ((p (org-inside-LaTeX-fragment-p)))
16097 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16098 (setq ad-return-value t
16099 texmathp-why '("Org-mode embedded math" . 0))
16100 (if p ad-do-it)))))))))
16102 (defun turn-on-org-cdlatex ()
16103 "Unconditionally turn on `org-cdlatex-mode'."
16104 (org-cdlatex-mode 1))
16106 (defun org-inside-LaTeX-fragment-p ()
16107 "Test if point is inside a LaTeX fragment.
16108 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16109 sequence appearing also before point.
16110 Even though the matchers for math are configurable, this function assumes
16111 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16112 delimiters are skipped when they have been removed by customization.
16113 The return value is nil, or a cons cell with the delimiter and
16114 and the position of this delimiter.
16116 This function does a reasonably good job, but can locally be fooled by
16117 for example currency specifications. For example it will assume being in
16118 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16119 fragments that are properly closed, but during editing, we have to live
16120 with the uncertainty caused by missing closing delimiters. This function
16121 looks only before point, not after."
16122 (catch 'exit
16123 (let ((pos (point))
16124 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16125 (lim (progn
16126 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16127 (point)))
16128 dd-on str (start 0) m re)
16129 (goto-char pos)
16130 (when dodollar
16131 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16132 re (nth 1 (assoc "$" org-latex-regexps)))
16133 (while (string-match re str start)
16134 (cond
16135 ((= (match-end 0) (length str))
16136 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16137 ((= (match-end 0) (- (length str) 5))
16138 (throw 'exit nil))
16139 (t (setq start (match-end 0))))))
16140 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16141 (goto-char pos)
16142 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16143 (and (match-beginning 2) (throw 'exit nil))
16144 ;; count $$
16145 (while (re-search-backward "\\$\\$" lim t)
16146 (setq dd-on (not dd-on)))
16147 (goto-char pos)
16148 (if dd-on (cons "$$" m))))))
16150 (defun org-inside-latex-macro-p ()
16151 "Is point inside a LaTeX macro or its arguments?"
16152 (save-match-data
16153 (org-in-regexp
16154 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16156 (defun org-try-cdlatex-tab ()
16157 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16158 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16159 - inside a LaTeX fragment, or
16160 - after the first word in a line, where an abbreviation expansion could
16161 insert a LaTeX environment."
16162 (when org-cdlatex-mode
16163 (cond
16164 ((save-excursion
16165 (skip-chars-backward "a-zA-Z0-9*")
16166 (skip-chars-backward " \t")
16167 (bolp))
16168 (cdlatex-tab) t)
16169 ((org-inside-LaTeX-fragment-p)
16170 (cdlatex-tab) t)
16171 (t nil))))
16173 (defun org-cdlatex-underscore-caret (&optional arg)
16174 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16175 Revert to the normal definition outside of these fragments."
16176 (interactive "P")
16177 (if (org-inside-LaTeX-fragment-p)
16178 (call-interactively 'cdlatex-sub-superscript)
16179 (let (org-cdlatex-mode)
16180 (call-interactively (key-binding (vector last-input-event))))))
16182 (defun org-cdlatex-math-modify (&optional arg)
16183 "Execute `cdlatex-math-modify' in LaTeX fragments.
16184 Revert to the normal definition outside of these fragments."
16185 (interactive "P")
16186 (if (org-inside-LaTeX-fragment-p)
16187 (call-interactively 'cdlatex-math-modify)
16188 (let (org-cdlatex-mode)
16189 (call-interactively (key-binding (vector last-input-event))))))
16191 (defvar org-latex-fragment-image-overlays nil
16192 "List of overlays carrying the images of latex fragments.")
16193 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16195 (defun org-remove-latex-fragment-image-overlays ()
16196 "Remove all overlays with LaTeX fragment images in current buffer."
16197 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16198 (setq org-latex-fragment-image-overlays nil))
16200 (defun org-preview-latex-fragment (&optional subtree)
16201 "Preview the LaTeX fragment at point, or all locally or globally.
16202 If the cursor is in a LaTeX fragment, create the image and overlay
16203 it over the source code. If there is no fragment at point, display
16204 all fragments in the current text, from one headline to the next. With
16205 prefix SUBTREE, display all fragments in the current subtree. With a
16206 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16207 the cursor is before the first headline,
16208 display all fragments in the buffer.
16209 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16210 (interactive "P")
16211 (org-remove-latex-fragment-image-overlays)
16212 (save-excursion
16213 (save-restriction
16214 (let (beg end at msg)
16215 (cond
16216 ((or (equal subtree '(16))
16217 (not (save-excursion
16218 (re-search-backward (concat "^" outline-regexp) nil t))))
16219 (setq beg (point-min) end (point-max)
16220 msg "Creating images for buffer...%s"))
16221 ((equal subtree '(4))
16222 (org-back-to-heading)
16223 (setq beg (point) end (org-end-of-subtree t)
16224 msg "Creating images for subtree...%s"))
16226 (if (setq at (org-inside-LaTeX-fragment-p))
16227 (goto-char (max (point-min) (- (cdr at) 2)))
16228 (org-back-to-heading))
16229 (setq beg (point) end (progn (outline-next-heading) (point))
16230 msg (if at "Creating image...%s"
16231 "Creating images for entry...%s"))))
16232 (message msg "")
16233 (narrow-to-region beg end)
16234 (goto-char beg)
16235 (org-format-latex
16236 (concat "ltxpng/" (file-name-sans-extension
16237 (file-name-nondirectory
16238 buffer-file-name)))
16239 default-directory 'overlays msg at 'forbuffer 'dvipng)
16240 (message msg "done. Use `C-c C-c' to remove images.")))))
16242 (defvar org-latex-regexps
16243 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16244 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16245 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16246 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16247 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16248 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16249 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16250 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16251 "Regular expressions for matching embedded LaTeX.")
16253 (defvar org-export-have-math nil) ;; dynamic scoping
16254 (defun org-format-latex (prefix &optional dir overlays msg at
16255 forbuffer processing-type)
16256 "Replace LaTeX fragments with links to an image, and produce images.
16257 Some of the options can be changed using the variable
16258 `org-format-latex-options'."
16259 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16260 (let* ((prefixnodir (file-name-nondirectory prefix))
16261 (absprefix (expand-file-name prefix dir))
16262 (todir (file-name-directory absprefix))
16263 (opt org-format-latex-options)
16264 (matchers (plist-get opt :matchers))
16265 (re-list org-latex-regexps)
16266 (org-format-latex-header-extra
16267 (plist-get (org-infile-export-plist) :latex-header-extra))
16268 (cnt 0) txt hash link beg end re e checkdir
16269 executables-checked string
16270 m n block linkfile movefile ov)
16271 ;; Check the different regular expressions
16272 (while (setq e (pop re-list))
16273 (setq m (car e) re (nth 1 e) n (nth 2 e)
16274 block (if (nth 3 e) "\n\n" ""))
16275 (when (member m matchers)
16276 (goto-char (point-min))
16277 (while (re-search-forward re nil t)
16278 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16279 (not (get-text-property (match-beginning n)
16280 'org-protected))
16281 (or (not overlays)
16282 (not (eq (get-char-property (match-beginning n)
16283 'org-overlay-type)
16284 'org-latex-overlay))))
16285 (setq org-export-have-math t)
16286 (cond
16287 ((eq processing-type 'verbatim)
16288 ;; Leave the text verbatim, just protect it
16289 (add-text-properties (match-beginning n) (match-end n)
16290 '(org-protected t)))
16291 ((eq processing-type 'mathjax)
16292 ;; Prepare for MathJax processing
16293 (setq string (match-string n))
16294 (if (member m '("$" "$1"))
16295 (save-excursion
16296 (delete-region (match-beginning n) (match-end n))
16297 (goto-char (match-beginning n))
16298 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16299 "\\)")
16300 '(org-protected t))))
16301 (add-text-properties (match-beginning n) (match-end n)
16302 '(org-protected t))))
16303 ((or (eq processing-type 'dvipng) t)
16304 ;; Process to an image
16305 (setq txt (match-string n)
16306 beg (match-beginning n) end (match-end n)
16307 cnt (1+ cnt))
16308 (let (print-length print-level) ; make sure full list is printed
16309 (setq hash (sha1 (prin1-to-string
16310 (list org-format-latex-header
16311 org-format-latex-header-extra
16312 org-export-latex-default-packages-alist
16313 org-export-latex-packages-alist
16314 org-format-latex-options
16315 forbuffer txt)))
16316 linkfile (format "%s_%s.png" prefix hash)
16317 movefile (format "%s_%s.png" absprefix hash)))
16318 (setq link (concat block "[[file:" linkfile "]]" block))
16319 (if msg (message msg cnt))
16320 (goto-char beg)
16321 (unless checkdir ; make sure the directory exists
16322 (setq checkdir t)
16323 (or (file-directory-p todir) (make-directory todir t)))
16325 (unless executables-checked
16326 (org-check-external-command
16327 "latex" "needed to convert LaTeX fragments to images")
16328 (org-check-external-command
16329 "dvipng" "needed to convert LaTeX fragments to images")
16330 (setq executables-checked t))
16332 (unless (file-exists-p movefile)
16333 (org-create-formula-image
16334 txt movefile opt forbuffer))
16335 (if overlays
16336 (progn
16337 (mapc (lambda (o)
16338 (if (eq (overlay-get o 'org-overlay-type)
16339 'org-latex-overlay)
16340 (delete-overlay o)))
16341 (overlays-in beg end))
16342 (setq ov (make-overlay beg end))
16343 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16344 (if (featurep 'xemacs)
16345 (progn
16346 (overlay-put ov 'invisible t)
16347 (overlay-put
16348 ov 'end-glyph
16349 (make-glyph (vector 'png :file movefile))))
16350 (overlay-put
16351 ov 'display
16352 (list 'image :type 'png :file movefile :ascent 'center)))
16353 (push ov org-latex-fragment-image-overlays)
16354 (goto-char end))
16355 (delete-region beg end)
16356 (insert (org-add-props link
16357 (list 'org-latex-src
16358 (replace-regexp-in-string
16359 "\"" "" txt)))))))))))))
16361 ;; This function borrows from Ganesh Swami's latex2png.el
16362 (defun org-create-formula-image (string tofile options buffer)
16363 "This calls dvipng."
16364 (require 'org-latex)
16365 (let* ((tmpdir (if (featurep 'xemacs)
16366 (temp-directory)
16367 temporary-file-directory))
16368 (texfilebase (make-temp-name
16369 (expand-file-name "orgtex" tmpdir)))
16370 (texfile (concat texfilebase ".tex"))
16371 (dvifile (concat texfilebase ".dvi"))
16372 (pngfile (concat texfilebase ".png"))
16373 (fnh (if (featurep 'xemacs)
16374 (font-height (get-face-font 'default))
16375 (face-attribute 'default :height nil)))
16376 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16377 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16378 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16379 "Black"))
16380 (bg (or (plist-get options (if buffer :background :html-background))
16381 "Transparent")))
16382 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16383 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16384 (with-temp-file texfile
16385 (insert (org-splice-latex-header
16386 org-format-latex-header
16387 org-export-latex-default-packages-alist
16388 org-export-latex-packages-alist t
16389 org-format-latex-header-extra))
16390 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16391 (require 'org-latex)
16392 (org-export-latex-fix-inputenc))
16393 (let ((dir default-directory))
16394 (condition-case nil
16395 (progn
16396 (cd tmpdir)
16397 (call-process "latex" nil nil nil texfile))
16398 (error nil))
16399 (cd dir))
16400 (if (not (file-exists-p dvifile))
16401 (progn (message "Failed to create dvi file from %s" texfile) nil)
16402 (condition-case nil
16403 (call-process "dvipng" nil nil nil
16404 "-fg" fg "-bg" bg
16405 "-D" dpi
16406 ;;"-x" scale "-y" scale
16407 "-T" "tight"
16408 "-o" pngfile
16409 dvifile)
16410 (error nil))
16411 (if (not (file-exists-p pngfile))
16412 (if org-format-latex-signal-error
16413 (error "Failed to create png file from %s" texfile)
16414 (message "Failed to create png file from %s" texfile)
16415 nil)
16416 ;; Use the requested file name and clean up
16417 (copy-file pngfile tofile 'replace)
16418 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16419 (delete-file (concat texfilebase e)))
16420 pngfile))))
16422 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16423 "Fill a LaTeX header template TPL.
16424 In the template, the following place holders will be recognized:
16426 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16427 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16428 [PACKAGES] \\usepackage statements for PKG
16429 [NO-PACKAGES] do not include PKG
16430 [EXTRA] the string EXTRA
16431 [NO-EXTRA] do not include EXTRA
16433 For backward compatibility, if both the positive and the negative place
16434 holder is missing, the positive one (without the \"NO-\") will be
16435 assumed to be present at the end of the template.
16436 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16437 EXTRA is a string.
16438 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16439 (let (rpl (end ""))
16440 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16441 (setq rpl (if (or (match-end 1) (not def-pkg))
16442 "" (org-latex-packages-to-string def-pkg snippets-p t))
16443 tpl (replace-match rpl t t tpl))
16444 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16446 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16447 (setq rpl (if (or (match-end 1) (not pkg))
16448 "" (org-latex-packages-to-string pkg snippets-p t))
16449 tpl (replace-match rpl t t tpl))
16450 (if pkg (setq end
16451 (concat end "\n"
16452 (org-latex-packages-to-string pkg snippets-p)))))
16454 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16455 (setq rpl (if (or (match-end 1) (not extra))
16456 "" (concat extra "\n"))
16457 tpl (replace-match rpl t t tpl))
16458 (if (and extra (string-match "\\S-" extra))
16459 (setq end (concat end "\n" extra))))
16461 (if (string-match "\\S-" end)
16462 (concat tpl "\n" end)
16463 tpl)))
16465 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16466 "Turn an alist of packages into a string with the \\usepackage macros."
16467 (setq pkg (mapconcat (lambda(p)
16468 (cond
16469 ((stringp p) p)
16470 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16471 (format "%% Package %s omitted" (cadr p)))
16472 ((equal "" (car p))
16473 (format "\\usepackage{%s}" (cadr p)))
16475 (format "\\usepackage[%s]{%s}"
16476 (car p) (cadr p)))))
16478 "\n"))
16479 (if newline (concat pkg "\n") pkg))
16481 (defun org-dvipng-color (attr)
16482 "Return an rgb color specification for dvipng."
16483 (apply 'format "rgb %s %s %s"
16484 (mapcar 'org-normalize-color
16485 (color-values (face-attribute 'default attr nil)))))
16487 (defun org-normalize-color (value)
16488 "Return string to be used as color value for an RGB component."
16489 (format "%g" (/ value 65535.0)))
16491 ;; Image display
16494 (defvar org-inline-image-overlays nil)
16495 (make-variable-buffer-local 'org-inline-image-overlays)
16497 (defun org-toggle-inline-images (&optional include-linked)
16498 "Toggle the display of inline images.
16499 INCLUDE-LINKED is passed to `org-display-inline-images'."
16500 (interactive "P")
16501 (if org-inline-image-overlays
16502 (progn
16503 (org-remove-inline-images)
16504 (message "Inline image display turned off"))
16505 (org-display-inline-images include-linked)
16506 (if org-inline-image-overlays
16507 (message "%d images displayed inline"
16508 (length org-inline-image-overlays))
16509 (message "No images to display inline"))))
16511 (defun org-display-inline-images (&optional include-linked refresh beg end)
16512 "Display inline images.
16513 Normally only links without a description part are inlined, because this
16514 is how it will work for export. When INCLUDE-LINKED is set, also links
16515 with a description part will be inlined. This can be nice for a quick
16516 look at those images, but it does not reflect what exported files will look
16517 like.
16518 When REFRESH is set, refresh existing images between BEG and END.
16519 This will create new image displays only if necessary.
16520 BEG and END default to the buffer boundaries."
16521 (interactive "P")
16522 (unless refresh
16523 (org-remove-inline-images)
16524 (if (fboundp 'clear-image-cache) (clear-image-cache)))
16525 (save-excursion
16526 (save-restriction
16527 (widen)
16528 (setq beg (or beg (point-min)) end (or end (point-max)))
16529 (goto-char (point-min))
16530 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
16531 (substring (org-image-file-name-regexp) 0 -2)
16532 "\\)\\]" (if include-linked "" "\\]")))
16533 old file ov img)
16534 (while (re-search-forward re end t)
16535 (setq old (get-char-property-and-overlay (match-beginning 1)
16536 'org-image-overlay))
16537 (setq file (expand-file-name
16538 (concat (or (match-string 3) "") (match-string 4))))
16539 (when (file-exists-p file)
16540 (if (and (car-safe old) refresh)
16541 (image-refresh (overlay-get (cdr old) 'display))
16542 (setq img (save-match-data (create-image file)))
16543 (when img
16544 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
16545 (overlay-put ov 'display img)
16546 (overlay-put ov 'face 'default)
16547 (overlay-put ov 'org-image-overlay t)
16548 (overlay-put ov 'modification-hooks
16549 (list 'org-display-inline-modification-hook))
16550 (push ov org-inline-image-overlays)))))))))
16552 (defun org-display-inline-modification-hook (ov after beg end &optional len)
16553 "Remove inline-display overlay if a corresponding region is modified."
16554 (let ((inhibit-modification-hooks t))
16555 (when (and ov after)
16556 (delete ov org-inline-image-overlays)
16557 (delete-overlay ov))))
16559 (defun org-remove-inline-images ()
16560 "Remove inline display of images."
16561 (interactive)
16562 (mapc 'delete-overlay org-inline-image-overlays)
16563 (setq org-inline-image-overlays nil))
16565 ;;;; Key bindings
16567 ;; Make `C-c C-x' a prefix key
16568 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
16570 ;; TAB key with modifiers
16571 (org-defkey org-mode-map "\C-i" 'org-cycle)
16572 (org-defkey org-mode-map [(tab)] 'org-cycle)
16573 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
16574 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
16575 (org-defkey org-mode-map "\M-\t" 'pcomplete)
16576 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
16577 ;; The following line is necessary under Suse GNU/Linux
16578 (unless (featurep 'xemacs)
16579 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
16580 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
16581 (define-key org-mode-map [backtab] 'org-shifttab)
16583 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
16584 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
16585 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
16587 ;; Cursor keys with modifiers
16588 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
16589 (org-defkey org-mode-map [(meta right)] 'org-metaright)
16590 (org-defkey org-mode-map [(meta up)] 'org-metaup)
16591 (org-defkey org-mode-map [(meta down)] 'org-metadown)
16593 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
16594 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
16595 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
16596 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
16598 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
16599 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
16600 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
16601 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
16603 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
16604 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
16606 ;; Babel keys
16607 (define-key org-mode-map org-babel-key-prefix org-babel-map)
16608 (mapc (lambda (pair)
16609 (define-key org-babel-map (car pair) (cdr pair)))
16610 org-babel-key-bindings)
16612 ;;; Extra keys for tty access.
16613 ;; We only set them when really needed because otherwise the
16614 ;; menus don't show the simple keys
16616 (when (or org-use-extra-keys
16617 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
16618 (not window-system))
16619 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
16620 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
16621 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
16622 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
16623 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
16624 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
16625 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
16626 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
16627 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
16628 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
16629 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
16630 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
16631 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
16632 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16633 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16634 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16635 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
16636 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
16637 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
16638 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
16639 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
16640 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
16641 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
16642 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
16643 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
16644 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
16645 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
16646 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
16648 ;; All the other keys
16650 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16651 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
16652 (if (boundp 'narrow-map)
16653 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
16654 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
16655 (if (boundp 'narrow-map)
16656 (org-defkey narrow-map "b" 'org-narrow-to-block)
16657 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
16658 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
16659 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
16660 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
16661 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
16662 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
16663 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
16664 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
16665 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
16666 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
16667 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
16668 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
16669 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
16670 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
16671 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
16672 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
16673 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
16674 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
16675 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
16676 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
16677 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
16678 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
16679 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
16680 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
16681 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
16682 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
16683 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
16684 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
16685 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
16686 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
16687 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16688 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16689 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16690 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16691 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
16692 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
16693 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16694 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
16695 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
16696 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
16697 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
16698 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16699 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
16700 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
16701 (org-defkey org-mode-map "\C-c^" 'org-sort)
16702 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16703 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
16704 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
16705 (org-defkey org-mode-map "\C-m" 'org-return)
16706 (org-defkey org-mode-map "\C-j" 'org-return-indent)
16707 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
16708 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
16709 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
16710 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
16711 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
16712 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
16713 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16714 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16715 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
16716 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
16717 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
16718 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
16719 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
16720 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16721 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
16722 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
16723 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
16724 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
16725 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
16726 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
16727 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
16729 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
16730 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16731 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16732 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16734 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16735 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16736 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16737 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
16738 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16739 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16740 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16741 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16742 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16743 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
16744 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
16745 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16746 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
16747 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
16748 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
16749 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
16750 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
16751 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
16753 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
16754 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
16755 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
16756 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
16757 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
16759 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
16761 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
16763 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
16764 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
16766 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
16769 (when (featurep 'xemacs)
16770 (org-defkey org-mode-map 'button3 'popup-mode-menu))
16773 (defconst org-speed-commands-default
16775 ("Outline Navigation")
16776 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
16777 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
16778 ("f" . (org-speed-move-safe 'org-forward-same-level))
16779 ("b" . (org-speed-move-safe 'org-backward-same-level))
16780 ("u" . (org-speed-move-safe 'outline-up-heading))
16781 ("j" . org-goto)
16782 ("g" . (org-refile t))
16783 ("Outline Visibility")
16784 ("c" . org-cycle)
16785 ("C" . org-shifttab)
16786 (" " . org-display-outline-path)
16787 ("Outline Structure Editing")
16788 ("U" . org-shiftmetaup)
16789 ("D" . org-shiftmetadown)
16790 ("r" . org-metaright)
16791 ("l" . org-metaleft)
16792 ("R" . org-shiftmetaright)
16793 ("L" . org-shiftmetaleft)
16794 ("i" . (progn (forward-char 1) (call-interactively
16795 'org-insert-heading-respect-content)))
16796 ("^" . org-sort)
16797 ("w" . org-refile)
16798 ("a" . org-archive-subtree-default-with-confirmation)
16799 ("." . org-mark-subtree)
16800 ("Clock Commands")
16801 ("I" . org-clock-in)
16802 ("O" . org-clock-out)
16803 ("Meta Data Editing")
16804 ("t" . org-todo)
16805 ("0" . (org-priority ?\ ))
16806 ("1" . (org-priority ?A))
16807 ("2" . (org-priority ?B))
16808 ("3" . (org-priority ?C))
16809 (";" . org-set-tags-command)
16810 ("e" . org-set-effort)
16811 ("Agenda Views etc")
16812 ("v" . org-agenda)
16813 ("/" . org-sparse-tree)
16814 ("Misc")
16815 ("o" . org-open-at-point)
16816 ("?" . org-speed-command-help)
16817 ("<" . (org-agenda-set-restriction-lock 'subtree))
16818 (">" . (org-agenda-remove-restriction-lock))
16820 "The default speed commands.")
16822 (defun org-print-speed-command (e)
16823 (if (> (length (car e)) 1)
16824 (progn
16825 (princ "\n")
16826 (princ (car e))
16827 (princ "\n")
16828 (princ (make-string (length (car e)) ?-))
16829 (princ "\n"))
16830 (princ (car e))
16831 (princ " ")
16832 (if (symbolp (cdr e))
16833 (princ (symbol-name (cdr e)))
16834 (prin1 (cdr e)))
16835 (princ "\n")))
16837 (defun org-speed-command-help ()
16838 "Show the available speed commands."
16839 (interactive)
16840 (if (not org-use-speed-commands)
16841 (error "Speed commands are not activated, customize `org-use-speed-commands'")
16842 (with-output-to-temp-buffer "*Help*"
16843 (princ "User-defined Speed commands\n===========================\n")
16844 (mapc 'org-print-speed-command org-speed-commands-user)
16845 (princ "\n")
16846 (princ "Built-in Speed commands\n=======================\n")
16847 (mapc 'org-print-speed-command org-speed-commands-default))
16848 (with-current-buffer "*Help*"
16849 (setq truncate-lines t))))
16851 (defun org-speed-move-safe (cmd)
16852 "Execute CMD, but make sure that the cursor always ends up in a headline.
16853 If not, return to the original position and throw an error."
16854 (interactive)
16855 (let ((pos (point)))
16856 (call-interactively cmd)
16857 (unless (and (bolp) (org-on-heading-p))
16858 (goto-char pos)
16859 (error "Boundary reached while executing %s" cmd))))
16861 (defvar org-self-insert-command-undo-counter 0)
16863 (defvar org-table-auto-blank-field) ; defined in org-table.el
16864 (defvar org-speed-command nil)
16866 (defun org-speed-command-default-hook (keys)
16867 "Hook for activating single-letter speed commands.
16868 `org-speed-commands-default' specifies a minimal command set. Use
16869 `org-speed-commands-user' for further customization."
16870 (when (or (and (bolp) (looking-at outline-regexp))
16871 (and (functionp org-use-speed-commands)
16872 (funcall org-use-speed-commands)))
16873 (cdr (assoc keys (append org-speed-commands-user
16874 org-speed-commands-default)))))
16876 (defun org-babel-speed-command-hook (keys)
16877 "Hook for activating single-letter code block commands."
16878 (when (and (bolp) (looking-at org-babel-src-block-regexp))
16879 (cdr (assoc keys org-babel-key-bindings))))
16881 (defcustom org-speed-command-hook
16882 '(org-speed-command-default-hook org-babel-speed-command-hook)
16883 "Hook for activating speed commands at strategic locations.
16884 Hook functions are called in sequence until a valid handler is
16885 found.
16887 Each hook takes a single argument, a user-pressed command key
16888 which is also a `self-insert-command' from the global map.
16890 Within the hook, examine the cursor position and the command key
16891 and return nil or a valid handler as appropriate. Handler could
16892 be one of an interactive command, a function, or a form.
16894 Set `org-use-speed-commands' to non-nil value to enable this
16895 hook. The default setting is `org-speed-command-default-hook'."
16896 :group 'org-structure
16897 :type 'hook)
16899 (defun org-self-insert-command (N)
16900 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16901 If the cursor is in a table looking at whitespace, the whitespace is
16902 overwritten, and the table is not marked as requiring realignment."
16903 (interactive "p")
16904 (cond
16905 ((and org-use-speed-commands
16906 (setq org-speed-command
16907 (run-hook-with-args-until-success
16908 'org-speed-command-hook (this-command-keys))))
16909 (cond
16910 ((commandp org-speed-command)
16911 (setq this-command org-speed-command)
16912 (call-interactively org-speed-command))
16913 ((functionp org-speed-command)
16914 (funcall org-speed-command))
16915 ((and org-speed-command (listp org-speed-command))
16916 (eval org-speed-command))
16917 (t (let (org-use-speed-commands)
16918 (call-interactively 'org-self-insert-command)))))
16919 ((and
16920 (org-table-p)
16921 (progn
16922 ;; check if we blank the field, and if that triggers align
16923 (and (featurep 'org-table) org-table-auto-blank-field
16924 (member last-command
16925 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
16926 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16927 ;; got extra space, this field does not determine column width
16928 (let (org-table-may-need-update) (org-table-blank-field))
16929 ;; no extra space, this field may determine column width
16930 (org-table-blank-field)))
16932 (eq N 1)
16933 (looking-at "[^|\n]* |"))
16934 (let (org-table-may-need-update)
16935 (goto-char (1- (match-end 0)))
16936 (delete-char -1)
16937 (goto-char (match-beginning 0))
16938 (self-insert-command N)))
16940 (setq org-table-may-need-update t)
16941 (self-insert-command N)
16942 (org-fix-tags-on-the-fly)
16943 (if org-self-insert-cluster-for-undo
16944 (if (not (eq last-command 'org-self-insert-command))
16945 (setq org-self-insert-command-undo-counter 1)
16946 (if (>= org-self-insert-command-undo-counter 20)
16947 (setq org-self-insert-command-undo-counter 1)
16948 (and (> org-self-insert-command-undo-counter 0)
16949 buffer-undo-list (listp buffer-undo-list)
16950 (not (cadr buffer-undo-list)) ; remove nil entry
16951 (setcdr buffer-undo-list (cddr buffer-undo-list)))
16952 (setq org-self-insert-command-undo-counter
16953 (1+ org-self-insert-command-undo-counter))))))))
16955 (defun org-fix-tags-on-the-fly ()
16956 (when (and (equal (char-after (point-at-bol)) ?*)
16957 (org-on-heading-p))
16958 (org-align-tags-here org-tags-column)))
16960 (defun org-delete-backward-char (N)
16961 "Like `delete-backward-char', insert whitespace at field end in tables.
16962 When deleting backwards, in tables this function will insert whitespace in
16963 front of the next \"|\" separator, to keep the table aligned. The table will
16964 still be marked for re-alignment if the field did fill the entire column,
16965 because, in this case the deletion might narrow the column."
16966 (interactive "p")
16967 (if (and (org-table-p)
16968 (eq N 1)
16969 (string-match "|" (buffer-substring (point-at-bol) (point)))
16970 (looking-at ".*?|"))
16971 (let ((pos (point))
16972 (noalign (looking-at "[^|\n\r]* |"))
16973 (c org-table-may-need-update))
16974 (backward-delete-char N)
16975 (if (not overwrite-mode)
16976 (progn
16977 (skip-chars-forward "^|")
16978 (insert " ")
16979 (goto-char (1- pos))))
16980 ;; noalign: if there were two spaces at the end, this field
16981 ;; does not determine the width of the column.
16982 (if noalign (setq org-table-may-need-update c)))
16983 (backward-delete-char N)
16984 (org-fix-tags-on-the-fly)))
16986 (defun org-delete-char (N)
16987 "Like `delete-char', but insert whitespace at field end in tables.
16988 When deleting characters, in tables this function will insert whitespace in
16989 front of the next \"|\" separator, to keep the table aligned. The table will
16990 still be marked for re-alignment if the field did fill the entire column,
16991 because, in this case the deletion might narrow the column."
16992 (interactive "p")
16993 (if (and (org-table-p)
16994 (not (bolp))
16995 (not (= (char-after) ?|))
16996 (eq N 1))
16997 (if (looking-at ".*?|")
16998 (let ((pos (point))
16999 (noalign (looking-at "[^|\n\r]* |"))
17000 (c org-table-may-need-update))
17001 (replace-match (concat
17002 (substring (match-string 0) 1 -1)
17003 " |"))
17004 (goto-char pos)
17005 ;; noalign: if there were two spaces at the end, this field
17006 ;; does not determine the width of the column.
17007 (if noalign (setq org-table-may-need-update c)))
17008 (delete-char N))
17009 (delete-char N)
17010 (org-fix-tags-on-the-fly)))
17012 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17013 (put 'org-self-insert-command 'delete-selection t)
17014 (put 'orgtbl-self-insert-command 'delete-selection t)
17015 (put 'org-delete-char 'delete-selection 'supersede)
17016 (put 'org-delete-backward-char 'delete-selection 'supersede)
17017 (put 'org-yank 'delete-selection 'yank)
17019 ;; Make `flyspell-mode' delay after some commands
17020 (put 'org-self-insert-command 'flyspell-delayed t)
17021 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17022 (put 'org-delete-char 'flyspell-delayed t)
17023 (put 'org-delete-backward-char 'flyspell-delayed t)
17025 ;; Make pabbrev-mode expand after org-mode commands
17026 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17027 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17029 ;; How to do this: Measure non-white length of current string
17030 ;; If equal to column width, we should realign.
17032 (defun org-remap (map &rest commands)
17033 "In MAP, remap the functions given in COMMANDS.
17034 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17035 (let (new old)
17036 (while commands
17037 (setq old (pop commands) new (pop commands))
17038 (if (fboundp 'command-remapping)
17039 (org-defkey map (vector 'remap old) new)
17040 (substitute-key-definition old new map global-map)))))
17042 (when (eq org-enable-table-editor 'optimized)
17043 ;; If the user wants maximum table support, we need to hijack
17044 ;; some standard editing functions
17045 (org-remap org-mode-map
17046 'self-insert-command 'org-self-insert-command
17047 'delete-char 'org-delete-char
17048 'delete-backward-char 'org-delete-backward-char)
17049 (org-defkey org-mode-map "|" 'org-force-self-insert))
17051 (defvar org-ctrl-c-ctrl-c-hook nil
17052 "Hook for functions attaching themselves to `C-c C-c'.
17053 This can be used to add additional functionality to the C-c C-c key which
17054 executes context-dependent commands.
17055 Each function will be called with no arguments. The function must check
17056 if the context is appropriate for it to act. If yes, it should do its
17057 thing and then return a non-nil value. If the context is wrong,
17058 just do nothing and return nil.")
17060 (defvar org-tab-first-hook nil
17061 "Hook for functions to attach themselves to TAB.
17062 See `org-ctrl-c-ctrl-c-hook' for more information.
17063 This hook runs as the first action when TAB is pressed, even before
17064 `org-cycle' messes around with the `outline-regexp' to cater for
17065 inline tasks and plain list item folding.
17066 If any function in this hook returns t, any other actions that
17067 would have been caused by TAB (such as table field motion or visibility
17068 cycling) will not occur.")
17070 (defvar org-tab-after-check-for-table-hook nil
17071 "Hook for functions to attach themselves to TAB.
17072 See `org-ctrl-c-ctrl-c-hook' for more information.
17073 This hook runs after it has been established that the cursor is not in a
17074 table, but before checking if the cursor is in a headline or if global cycling
17075 should be done.
17076 If any function in this hook returns t, not other actions like visibility
17077 cycling will be done.")
17079 (defvar org-tab-after-check-for-cycling-hook nil
17080 "Hook for functions to attach themselves to TAB.
17081 See `org-ctrl-c-ctrl-c-hook' for more information.
17082 This hook runs after it has been established that not table field motion and
17083 not visibility should be done because of current context. This is probably
17084 the place where a package like yasnippets can hook in.")
17086 (defvar org-tab-before-tab-emulation-hook nil
17087 "Hook for functions to attach themselves to TAB.
17088 See `org-ctrl-c-ctrl-c-hook' for more information.
17089 This hook runs after every other options for TAB have been exhausted, but
17090 before indentation and \t insertion takes place.")
17092 (defvar org-metaleft-hook nil
17093 "Hook for functions attaching themselves to `M-left'.
17094 See `org-ctrl-c-ctrl-c-hook' for more information.")
17095 (defvar org-metaright-hook nil
17096 "Hook for functions attaching themselves to `M-right'.
17097 See `org-ctrl-c-ctrl-c-hook' for more information.")
17098 (defvar org-metaup-hook nil
17099 "Hook for functions attaching themselves to `M-up'.
17100 See `org-ctrl-c-ctrl-c-hook' for more information.")
17101 (defvar org-metadown-hook nil
17102 "Hook for functions attaching themselves to `M-down'.
17103 See `org-ctrl-c-ctrl-c-hook' for more information.")
17104 (defvar org-shiftmetaleft-hook nil
17105 "Hook for functions attaching themselves to `M-S-left'.
17106 See `org-ctrl-c-ctrl-c-hook' for more information.")
17107 (defvar org-shiftmetaright-hook nil
17108 "Hook for functions attaching themselves to `M-S-right'.
17109 See `org-ctrl-c-ctrl-c-hook' for more information.")
17110 (defvar org-shiftmetaup-hook nil
17111 "Hook for functions attaching themselves to `M-S-up'.
17112 See `org-ctrl-c-ctrl-c-hook' for more information.")
17113 (defvar org-shiftmetadown-hook nil
17114 "Hook for functions attaching themselves to `M-S-down'.
17115 See `org-ctrl-c-ctrl-c-hook' for more information.")
17116 (defvar org-metareturn-hook nil
17117 "Hook for functions attaching themselves to `M-RET'.
17118 See `org-ctrl-c-ctrl-c-hook' for more information.")
17119 (defvar org-shiftup-hook nil
17120 "Hook for functions attaching themselves to `S-up'.
17121 See `org-ctrl-c-ctrl-c-hook' for more information.")
17122 (defvar org-shiftup-final-hook nil
17123 "Hook for functions attaching themselves to `S-up'.
17124 This one runs after all other options except shift-select have been excluded.
17125 See `org-ctrl-c-ctrl-c-hook' for more information.")
17126 (defvar org-shiftdown-hook nil
17127 "Hook for functions attaching themselves to `S-down'.
17128 See `org-ctrl-c-ctrl-c-hook' for more information.")
17129 (defvar org-shiftdown-final-hook nil
17130 "Hook for functions attaching themselves to `S-down'.
17131 This one runs after all other options except shift-select have been excluded.
17132 See `org-ctrl-c-ctrl-c-hook' for more information.")
17133 (defvar org-shiftleft-hook nil
17134 "Hook for functions attaching themselves to `S-left'.
17135 See `org-ctrl-c-ctrl-c-hook' for more information.")
17136 (defvar org-shiftleft-final-hook nil
17137 "Hook for functions attaching themselves to `S-left'.
17138 This one runs after all other options except shift-select have been excluded.
17139 See `org-ctrl-c-ctrl-c-hook' for more information.")
17140 (defvar org-shiftright-hook nil
17141 "Hook for functions attaching themselves to `S-right'.
17142 See `org-ctrl-c-ctrl-c-hook' for more information.")
17143 (defvar org-shiftright-final-hook nil
17144 "Hook for functions attaching themselves to `S-right'.
17145 This one runs after all other options except shift-select have been excluded.
17146 See `org-ctrl-c-ctrl-c-hook' for more information.")
17148 (defun org-modifier-cursor-error ()
17149 "Throw an error, a modified cursor command was applied in wrong context."
17150 (error "This command is active in special context like tables, headlines or items"))
17152 (defun org-shiftselect-error ()
17153 "Throw an error because Shift-Cursor command was applied in wrong context."
17154 (if (and (boundp 'shift-select-mode) shift-select-mode)
17155 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17156 (error "This command works only in special context like headlines or timestamps")))
17158 (defun org-call-for-shift-select (cmd)
17159 (let ((this-command-keys-shift-translated t))
17160 (call-interactively cmd)))
17162 (defun org-shifttab (&optional arg)
17163 "Global visibility cycling or move to previous table field.
17164 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17165 on context.
17166 See the individual commands for more information."
17167 (interactive "P")
17168 (cond
17169 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17170 ((integerp arg)
17171 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17172 (message "Content view to level: %d" arg)
17173 (org-content (prefix-numeric-value arg2))
17174 (setq org-cycle-global-status 'overview)))
17175 (t (call-interactively 'org-global-cycle))))
17177 (defun org-shiftmetaleft ()
17178 "Promote subtree or delete table column.
17179 Calls `org-promote-subtree', `org-outdent-item',
17180 or `org-table-delete-column', depending on context.
17181 See the individual commands for more information."
17182 (interactive)
17183 (cond
17184 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17185 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17186 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17187 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17188 (t (org-modifier-cursor-error))))
17190 (defun org-shiftmetaright ()
17191 "Demote subtree or insert table column.
17192 Calls `org-demote-subtree', `org-indent-item',
17193 or `org-table-insert-column', depending on context.
17194 See the individual commands for more information."
17195 (interactive)
17196 (cond
17197 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17198 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17199 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17200 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17201 (t (org-modifier-cursor-error))))
17203 (defun org-shiftmetaup (&optional arg)
17204 "Move subtree up or kill table row.
17205 Calls `org-move-subtree-up' or `org-table-kill-row' or
17206 `org-move-item-up' depending on context. See the individual commands
17207 for more information."
17208 (interactive "P")
17209 (cond
17210 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17211 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17212 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17213 ((org-at-item-p) (call-interactively 'org-move-item-up))
17214 (t (org-modifier-cursor-error))))
17216 (defun org-shiftmetadown (&optional arg)
17217 "Move subtree down or insert table row.
17218 Calls `org-move-subtree-down' or `org-table-insert-row' or
17219 `org-move-item-down', depending on context. See the individual
17220 commands for more information."
17221 (interactive "P")
17222 (cond
17223 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17224 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17225 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17226 ((org-at-item-p) (call-interactively 'org-move-item-down))
17227 (t (org-modifier-cursor-error))))
17229 (defsubst org-hidden-tree-error ()
17230 (error
17231 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17233 (defun org-metaleft (&optional arg)
17234 "Promote heading or move table column to left.
17235 Calls `org-do-promote' or `org-table-move-column', depending on context.
17236 With no specific context, calls the Emacs default `backward-word'.
17237 See the individual commands for more information."
17238 (interactive "P")
17239 (cond
17240 ((run-hook-with-args-until-success 'org-metaleft-hook))
17241 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17242 ((org-with-limited-levels
17243 (or (org-on-heading-p)
17244 (and (org-region-active-p)
17245 (save-excursion
17246 (goto-char (region-beginning))
17247 (org-on-heading-p)))))
17248 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17249 (call-interactively 'org-do-promote))
17250 ;; At an inline task.
17251 ((org-on-heading-p)
17252 (call-interactively 'org-inlinetask-promote))
17253 ((or (org-at-item-p)
17254 (and (org-region-active-p)
17255 (save-excursion
17256 (goto-char (region-beginning))
17257 (org-at-item-p))))
17258 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17259 (call-interactively 'org-outdent-item))
17260 (t (call-interactively 'backward-word))))
17262 (defun org-metaright (&optional arg)
17263 "Demote subtree or move table column to right.
17264 Calls `org-do-demote' or `org-table-move-column', depending on context.
17265 With no specific context, calls the Emacs default `forward-word'.
17266 See the individual commands for more information."
17267 (interactive "P")
17268 (cond
17269 ((run-hook-with-args-until-success 'org-metaright-hook))
17270 ((org-at-table-p) (call-interactively 'org-table-move-column))
17271 ((org-with-limited-levels
17272 (or (org-on-heading-p)
17273 (and (org-region-active-p)
17274 (save-excursion
17275 (goto-char (region-beginning))
17276 (org-on-heading-p)))))
17277 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17278 (call-interactively 'org-do-demote))
17279 ;; At an inline task.
17280 ((org-on-heading-p)
17281 (call-interactively 'org-inlinetask-demote))
17282 ((or (org-at-item-p)
17283 (and (org-region-active-p)
17284 (save-excursion
17285 (goto-char (region-beginning))
17286 (org-at-item-p))))
17287 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17288 (call-interactively 'org-indent-item))
17289 (t (call-interactively 'forward-word))))
17291 (defun org-check-for-hidden (what)
17292 "Check if there are hidden headlines/items in the current visual line.
17293 WHAT can be either `headlines' or `items'. If the current line is
17294 an outline or item heading and it has a folded subtree below it,
17295 this function returns t, nil otherwise."
17296 (let ((re (cond
17297 ((eq what 'headlines) (concat "^" org-outline-regexp))
17298 ((eq what 'items) (org-item-beginning-re))
17299 (t (error "This should not happen"))))
17300 beg end)
17301 (save-excursion
17302 (catch 'exit
17303 (unless (org-region-active-p)
17304 (setq beg (point-at-bol))
17305 (beginning-of-line 2)
17306 (while (and (not (eobp)) ;; this is like `next-line'
17307 (get-char-property (1- (point)) 'invisible))
17308 (beginning-of-line 2))
17309 (setq end (point))
17310 (goto-char beg)
17311 (goto-char (point-at-eol))
17312 (setq end (max end (point)))
17313 (while (re-search-forward re end t)
17314 (if (get-char-property (match-beginning 0) 'invisible)
17315 (throw 'exit t))))
17316 nil))))
17318 (defun org-metaup (&optional arg)
17319 "Move subtree up or move table row up.
17320 Calls `org-move-subtree-up' or `org-table-move-row' or
17321 `org-move-item-up', depending on context. See the individual commands
17322 for more information."
17323 (interactive "P")
17324 (cond
17325 ((run-hook-with-args-until-success 'org-metaup-hook))
17326 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17327 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17328 ((org-at-item-p) (call-interactively 'org-move-item-up))
17329 (t (transpose-lines 1) (beginning-of-line -1))))
17331 (defun org-metadown (&optional arg)
17332 "Move subtree down or move table row down.
17333 Calls `org-move-subtree-down' or `org-table-move-row' or
17334 `org-move-item-down', depending on context. See the individual
17335 commands for more information."
17336 (interactive "P")
17337 (cond
17338 ((run-hook-with-args-until-success 'org-metadown-hook))
17339 ((org-at-table-p) (call-interactively 'org-table-move-row))
17340 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17341 ((org-at-item-p) (call-interactively 'org-move-item-down))
17342 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17344 (defun org-shiftup (&optional arg)
17345 "Increase item in timestamp or increase priority of current headline.
17346 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17347 depending on context. See the individual commands for more information."
17348 (interactive "P")
17349 (cond
17350 ((run-hook-with-args-until-success 'org-shiftup-hook))
17351 ((and org-support-shift-select (org-region-active-p))
17352 (org-call-for-shift-select 'previous-line))
17353 ((org-at-timestamp-p t)
17354 (call-interactively (if org-edit-timestamp-down-means-later
17355 'org-timestamp-down 'org-timestamp-up)))
17356 ((and (not (eq org-support-shift-select 'always))
17357 org-enable-priority-commands
17358 (org-on-heading-p))
17359 (call-interactively 'org-priority-up))
17360 ((and (not org-support-shift-select) (org-at-item-p))
17361 (call-interactively 'org-previous-item))
17362 ((org-clocktable-try-shift 'up arg))
17363 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17364 (org-support-shift-select
17365 (org-call-for-shift-select 'previous-line))
17366 (t (org-shiftselect-error))))
17368 (defun org-shiftdown (&optional arg)
17369 "Decrease item in timestamp or decrease priority of current headline.
17370 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
17371 depending on context. See the individual commands for more information."
17372 (interactive "P")
17373 (cond
17374 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17375 ((and org-support-shift-select (org-region-active-p))
17376 (org-call-for-shift-select 'next-line))
17377 ((org-at-timestamp-p t)
17378 (call-interactively (if org-edit-timestamp-down-means-later
17379 'org-timestamp-up 'org-timestamp-down)))
17380 ((and (not (eq org-support-shift-select 'always))
17381 org-enable-priority-commands
17382 (org-on-heading-p))
17383 (call-interactively 'org-priority-down))
17384 ((and (not org-support-shift-select) (org-at-item-p))
17385 (call-interactively 'org-next-item))
17386 ((org-clocktable-try-shift 'down arg))
17387 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17388 (org-support-shift-select
17389 (org-call-for-shift-select 'next-line))
17390 (t (org-shiftselect-error))))
17392 (defun org-shiftright (&optional arg)
17393 "Cycle the thing at point or in the current line, depending on context.
17394 Depending on context, this does one of the following:
17396 - switch a timestamp at point one day into the future
17397 - on a headline, switch to the next TODO keyword.
17398 - on an item, switch entire list to the next bullet type
17399 - on a property line, switch to the next allowed value
17400 - on a clocktable definition line, move time block into the future"
17401 (interactive "P")
17402 (cond
17403 ((run-hook-with-args-until-success 'org-shiftright-hook))
17404 ((and org-support-shift-select (org-region-active-p))
17405 (org-call-for-shift-select 'forward-char))
17406 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17407 ((and (not (eq org-support-shift-select 'always))
17408 (org-on-heading-p))
17409 (let ((org-inhibit-logging
17410 (not org-treat-S-cursor-todo-selection-as-state-change))
17411 (org-inhibit-blocking
17412 (not org-treat-S-cursor-todo-selection-as-state-change)))
17413 (org-call-with-arg 'org-todo 'right)))
17414 ((or (and org-support-shift-select
17415 (not (eq org-support-shift-select 'always))
17416 (org-at-item-bullet-p))
17417 (and (not org-support-shift-select) (org-at-item-p)))
17418 (org-call-with-arg 'org-cycle-list-bullet nil))
17419 ((and (not (eq org-support-shift-select 'always))
17420 (org-at-property-p))
17421 (call-interactively 'org-property-next-allowed-value))
17422 ((org-clocktable-try-shift 'right arg))
17423 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
17424 (org-support-shift-select
17425 (org-call-for-shift-select 'forward-char))
17426 (t (org-shiftselect-error))))
17428 (defun org-shiftleft (&optional arg)
17429 "Cycle the thing at point or in the current line, depending on context.
17430 Depending on context, this does one of the following:
17432 - switch a timestamp at point one day into the past
17433 - on a headline, switch to the previous TODO keyword.
17434 - on an item, switch entire list to the previous bullet type
17435 - on a property line, switch to the previous allowed value
17436 - on a clocktable definition line, move time block into the past"
17437 (interactive "P")
17438 (cond
17439 ((run-hook-with-args-until-success 'org-shiftleft-hook))
17440 ((and org-support-shift-select (org-region-active-p))
17441 (org-call-for-shift-select 'backward-char))
17442 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17443 ((and (not (eq org-support-shift-select 'always))
17444 (org-on-heading-p))
17445 (let ((org-inhibit-logging
17446 (not org-treat-S-cursor-todo-selection-as-state-change))
17447 (org-inhibit-blocking
17448 (not org-treat-S-cursor-todo-selection-as-state-change)))
17449 (org-call-with-arg 'org-todo 'left)))
17450 ((or (and org-support-shift-select
17451 (not (eq org-support-shift-select 'always))
17452 (org-at-item-bullet-p))
17453 (and (not org-support-shift-select) (org-at-item-p)))
17454 (org-call-with-arg 'org-cycle-list-bullet 'previous))
17455 ((and (not (eq org-support-shift-select 'always))
17456 (org-at-property-p))
17457 (call-interactively 'org-property-previous-allowed-value))
17458 ((org-clocktable-try-shift 'left arg))
17459 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
17460 (org-support-shift-select
17461 (org-call-for-shift-select 'backward-char))
17462 (t (org-shiftselect-error))))
17464 (defun org-shiftcontrolright ()
17465 "Switch to next TODO set."
17466 (interactive)
17467 (cond
17468 ((and org-support-shift-select (org-region-active-p))
17469 (org-call-for-shift-select 'forward-word))
17470 ((and (not (eq org-support-shift-select 'always))
17471 (org-on-heading-p))
17472 (org-call-with-arg 'org-todo 'nextset))
17473 (org-support-shift-select
17474 (org-call-for-shift-select 'forward-word))
17475 (t (org-shiftselect-error))))
17477 (defun org-shiftcontrolleft ()
17478 "Switch to previous TODO set."
17479 (interactive)
17480 (cond
17481 ((and org-support-shift-select (org-region-active-p))
17482 (org-call-for-shift-select 'backward-word))
17483 ((and (not (eq org-support-shift-select 'always))
17484 (org-on-heading-p))
17485 (org-call-with-arg 'org-todo 'previousset))
17486 (org-support-shift-select
17487 (org-call-for-shift-select 'backward-word))
17488 (t (org-shiftselect-error))))
17490 (defun org-ctrl-c-ret ()
17491 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
17492 (interactive)
17493 (cond
17494 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
17495 (t (call-interactively 'org-insert-heading))))
17497 (defun org-copy-special ()
17498 "Copy region in table or copy current subtree.
17499 Calls `org-table-copy' or `org-copy-subtree', depending on context.
17500 See the individual commands for more information."
17501 (interactive)
17502 (call-interactively
17503 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
17505 (defun org-cut-special ()
17506 "Cut region in table or cut current subtree.
17507 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17508 See the individual commands for more information."
17509 (interactive)
17510 (call-interactively
17511 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17513 (defun org-paste-special (arg)
17514 "Paste rectangular region into table, or past subtree relative to level.
17515 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17516 See the individual commands for more information."
17517 (interactive "P")
17518 (if (org-at-table-p)
17519 (org-table-paste-rectangle)
17520 (org-paste-subtree arg)))
17522 (defun org-edit-special (&optional arg)
17523 "Call a special editor for the stuff at point.
17524 When at a table, call the formula editor with `org-table-edit-formulas'.
17525 When at the first line of an src example, call `org-edit-src-code'.
17526 When in an #+include line, visit the include file. Otherwise call
17527 `ffap' to visit the file at point."
17528 (interactive)
17529 ;; possibly prep session before editing source
17530 (when arg
17531 (let* ((info (org-babel-get-src-block-info))
17532 (lang (nth 0 info))
17533 (params (nth 2 info))
17534 (session (cdr (assoc :session params))))
17535 (when (and info session) ;; we are in a source-code block with a session
17536 (funcall
17537 (intern (concat "org-babel-prep-session:" lang)) session params))))
17538 (cond ;; proceed with `org-edit-special'
17539 ((save-excursion
17540 (beginning-of-line 1)
17541 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
17542 (find-file (org-trim (match-string 1))))
17543 ((org-edit-src-code))
17544 ((org-edit-fixed-width-region))
17545 ((org-at-table.el-p)
17546 (org-edit-src-code))
17547 ((or (org-at-table-p)
17548 (save-excursion
17549 (beginning-of-line 1)
17550 (looking-at "[ \t]*#\\+TBLFM:")))
17551 (call-interactively 'org-table-edit-formulas))
17552 (t (call-interactively 'ffap))))
17554 (defun org-ctrl-c-ctrl-c (&optional arg)
17555 "Set tags in headline, or update according to changed information at point.
17557 This command does many different things, depending on context:
17559 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
17560 this is what we do.
17562 - If the cursor is on a statistics cookie, update it.
17564 - If the cursor is in a headline, prompt for tags and insert them
17565 into the current line, aligned to `org-tags-column'. When called
17566 with prefix arg, realign all tags in the current buffer.
17568 - If the cursor is in one of the special #+KEYWORD lines, this
17569 triggers scanning the buffer for these lines and updating the
17570 information.
17572 - If the cursor is inside a table, realign the table. This command
17573 works even if the automatic table editor has been turned off.
17575 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17576 the entire table.
17578 - If the cursor is at a footnote reference or definition, jump to
17579 the corresponding definition or references, respectively.
17581 - If the cursor is a the beginning of a dynamic block, update it.
17583 - If the current buffer is a capture buffer, close note and file it.
17585 - If the cursor is on a <<<target>>>, update radio targets and
17586 corresponding links in this buffer.
17588 - If the cursor is on a numbered item in a plain list, renumber the
17589 ordered list.
17591 - If the cursor is on a checkbox, toggle it.
17593 - If the cursor is on a code block, evaluate it. The variable
17594 `org-confirm-babel-evaluate' can be used to control prompting
17595 before code block evaluation, by default every code block
17596 evaluation requires confirmation. Code block evaluation can be
17597 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
17598 (interactive "P")
17599 (let ((org-enable-table-editor t))
17600 (cond
17601 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
17602 org-occur-highlights
17603 org-latex-fragment-image-overlays)
17604 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
17605 (org-remove-occur-highlights)
17606 (org-remove-latex-fragment-image-overlays)
17607 (message "Temporary highlights/overlays removed from current buffer"))
17608 ((and (local-variable-p 'org-finish-function (current-buffer))
17609 (fboundp org-finish-function))
17610 (funcall org-finish-function))
17611 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
17612 ((or (looking-at org-property-start-re)
17613 (org-at-property-p))
17614 (call-interactively 'org-property-action))
17615 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17616 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
17617 (or (org-on-heading-p) (org-at-item-p)))
17618 (call-interactively 'org-update-statistics-cookies))
17619 ((org-on-heading-p) (call-interactively 'org-set-tags))
17620 ((org-at-table.el-p)
17621 (message "Use C-c ' to edit table.el tables"))
17622 ((org-at-table-p)
17623 (org-table-maybe-eval-formula)
17624 (if arg
17625 (call-interactively 'org-table-recalculate)
17626 (org-table-maybe-recalculate-line))
17627 (call-interactively 'org-table-align)
17628 (orgtbl-send-table 'maybe))
17629 ((or (org-footnote-at-reference-p)
17630 (org-footnote-at-definition-p))
17631 (call-interactively 'org-footnote-action))
17632 ((org-at-item-checkbox-p)
17633 ;; Cursor at a checkbox: repair list and update checkboxes. Send
17634 ;; list only if at top item.
17635 (let* ((cbox (match-string 1))
17636 (struct (org-list-struct))
17637 (old-struct (copy-tree struct))
17638 (parents (org-list-parents-alist struct))
17639 (prevs (org-list-prevs-alist struct))
17640 (orderedp (org-entry-get nil "ORDERED"))
17641 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
17642 block-item)
17643 ;; Use a light version of `org-toggle-checkbox' to avoid
17644 ;; computing list structure twice.
17645 (org-list-set-checkbox (point-at-bol) struct
17646 (cond
17647 ((equal arg '(16)) "[-]")
17648 ((equal arg '(4)) nil)
17649 ((equal "[X]" cbox) "[ ]")
17650 (t "[X]")))
17651 (org-list-struct-fix-ind struct parents)
17652 (org-list-struct-fix-bul struct prevs)
17653 (setq block-item
17654 (org-list-struct-fix-box struct parents prevs orderedp))
17655 (when block-item
17656 (message
17657 "Checkboxes were removed due to unchecked box at line %d"
17658 (org-current-line block-item)))
17659 (org-list-struct-apply-struct struct old-struct)
17660 (org-update-checkbox-count-maybe)
17661 (when firstp (org-list-send-list 'maybe))))
17662 ((org-at-item-p)
17663 ;; Cursor at an item: repair list. Do checkbox related actions
17664 ;; only if function was called with an argument. Send list only
17665 ;; if at top item.
17666 (let* ((struct (org-list-struct))
17667 (old-struct (copy-tree struct))
17668 (parents (org-list-parents-alist struct))
17669 (prevs (org-list-prevs-alist struct))
17670 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
17671 (org-list-struct-fix-ind struct parents)
17672 (org-list-struct-fix-bul struct prevs)
17673 (when arg
17674 (org-list-set-checkbox (point-at-bol) struct "[ ]")
17675 (org-list-struct-fix-box struct parents prevs))
17676 (org-list-struct-apply-struct struct old-struct)
17677 (when arg (org-update-checkbox-count-maybe))
17678 (when firstp (org-list-send-list 'maybe))))
17679 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
17680 ;; Dynamic block
17681 (beginning-of-line 1)
17682 (save-excursion (org-update-dblock)))
17683 ((save-excursion
17684 (beginning-of-line 1)
17685 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
17686 (cond
17687 ((equal (match-string 1) "TBLFM")
17688 ;; Recalculate the table before this line
17689 (save-excursion
17690 (beginning-of-line 1)
17691 (skip-chars-backward " \r\n\t")
17692 (if (org-at-table-p)
17693 (org-call-with-arg 'org-table-recalculate (or arg t)))))
17695 (let ((org-inhibit-startup-visibility-stuff t)
17696 (org-startup-align-all-tables nil))
17697 (org-save-outline-visibility 'use-markers (org-mode-restart)))
17698 (message "Local setup has been refreshed"))))
17699 ((org-clock-update-time-maybe))
17700 (t (error "C-c C-c can do nothing useful at this location")))))
17702 (defun org-mode-restart ()
17703 "Restart Org-mode, to scan again for special lines.
17704 Also updates the keyword regular expressions."
17705 (interactive)
17706 (org-mode)
17707 (message "Org-mode restarted"))
17709 (defun org-kill-note-or-show-branches ()
17710 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
17711 (interactive)
17712 (if (not org-finish-function)
17713 (progn
17714 (hide-subtree)
17715 (call-interactively 'show-branches))
17716 (let ((org-note-abort t))
17717 (funcall org-finish-function))))
17719 (defun org-return (&optional indent)
17720 "Goto next table row or insert a newline.
17721 Calls `org-table-next-row' or `newline', depending on context.
17722 See the individual commands for more information."
17723 (interactive)
17724 (cond
17725 ((bobp) (if indent (newline-and-indent) (newline)))
17726 ((org-at-table-p)
17727 (org-table-justify-field-maybe)
17728 (call-interactively 'org-table-next-row))
17729 ;; when `newline-and-indent' is called within a list, make sure
17730 ;; text moved stays inside the item.
17731 ((and (org-in-item-p) indent)
17732 (if (and (org-at-item-p) (>= (point) (match-end 0)))
17733 (progn
17734 (newline)
17735 (org-indent-line-to (length (match-string 0))))
17736 (let ((ind (org-get-indentation)))
17737 (newline)
17738 (if (org-looking-back org-list-end-re)
17739 (org-indent-line-function)
17740 (org-indent-line-to ind)))))
17741 ((and org-return-follows-link
17742 (eq (get-text-property (point) 'face) 'org-link))
17743 (call-interactively 'org-open-at-point))
17744 ((and (org-at-heading-p)
17745 (looking-at
17746 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
17747 (org-show-entry)
17748 (end-of-line 1)
17749 (newline))
17750 (t (if indent (newline-and-indent) (newline)))))
17752 (defun org-return-indent ()
17753 "Goto next table row or insert a newline and indent.
17754 Calls `org-table-next-row' or `newline-and-indent', depending on
17755 context. See the individual commands for more information."
17756 (interactive)
17757 (org-return t))
17759 (defun org-ctrl-c-star ()
17760 "Compute table, or change heading status of lines.
17761 Calls `org-table-recalculate' or `org-toggle-heading',
17762 depending on context."
17763 (interactive)
17764 (cond
17765 ((org-at-table-p)
17766 (call-interactively 'org-table-recalculate))
17768 ;; Convert all lines in region to list items
17769 (call-interactively 'org-toggle-heading))))
17771 (defun org-ctrl-c-minus ()
17772 "Insert separator line in table or modify bullet status of line.
17773 Also turns a plain line or a region of lines into list items.
17774 Calls `org-table-insert-hline', `org-toggle-item', or
17775 `org-cycle-list-bullet', depending on context."
17776 (interactive)
17777 (cond
17778 ((org-at-table-p)
17779 (call-interactively 'org-table-insert-hline))
17780 ((org-region-active-p)
17781 (call-interactively 'org-toggle-item))
17782 ((org-in-item-p)
17783 (call-interactively 'org-cycle-list-bullet))
17785 (call-interactively 'org-toggle-item))))
17787 (defun org-toggle-item (arg)
17788 "Convert headings or normal lines to items, items to normal lines.
17789 If there is no active region, only the current line is considered.
17791 If the first non blank line in the region is an headline, convert
17792 all headlines to items, shifting text accordingly.
17794 If it is an item, convert all items to normal lines.
17796 If it is normal text, change region into an item. With a prefix
17797 argument ARG, change each line in region into an item."
17798 (interactive "P")
17799 (let ((shift-text
17800 (function
17801 ;; Shift text in current section to IND, from point to END.
17802 ;; The function leaves point to END line.
17803 (lambda (ind end)
17804 (let ((min-i 1000) (end (copy-marker end)))
17805 ;; First determine the minimum indentation (MIN-I) of
17806 ;; the text.
17807 (save-excursion
17808 (catch 'exit
17809 (while (< (point) end)
17810 (let ((i (org-get-indentation)))
17811 (cond
17812 ;; Skip blank lines and inline tasks.
17813 ((looking-at "^[ \t]*$"))
17814 ((looking-at "^\\*+ "))
17815 ;; We can't find less than 0 indentation.
17816 ((zerop i) (throw 'exit (setq min-i 0)))
17817 ((< i min-i) (setq min-i i))))
17818 (forward-line))))
17819 ;; Then indent each line so that a line indented to
17820 ;; MIN-I becomes indented to IND. Ignore blank lines
17821 ;; and inline tasks in the process.
17822 (let ((delta (- ind min-i)))
17823 (while (< (point) end)
17824 (unless (or (looking-at "^[ \t]*$")
17825 (looking-at "^\\*+ "))
17826 (org-indent-line-to (+ (org-get-indentation) delta)))
17827 (forward-line)))))))
17828 (skip-blanks
17829 (function
17830 ;; Return beginning of first non-blank line, starting from
17831 ;; line at POS.
17832 (lambda (pos)
17833 (save-excursion
17834 (goto-char pos)
17835 (skip-chars-forward " \r\t\n")
17836 (point-at-bol)))))
17837 beg end)
17838 ;; Determine boundaries of changes.
17839 (if (org-region-active-p)
17840 (setq beg (funcall skip-blanks (region-beginning))
17841 end (copy-marker (region-end)))
17842 (setq beg (funcall skip-blanks (point-at-bol))
17843 end (copy-marker (point-at-eol))))
17844 ;; Depending on the starting line, choose an action on the text
17845 ;; between BEG and END.
17846 (org-with-limited-levels
17847 (save-excursion
17848 (goto-char beg)
17849 (cond
17850 ;; Case 1. Start at an item: de-itemize. Note that it only
17851 ;; happens when a region is active: `org-ctrl-c-minus'
17852 ;; would call `org-cycle-list-bullet' otherwise.
17853 ((org-at-item-p)
17854 (while (< (point) end)
17855 (when (org-at-item-p)
17856 (skip-chars-forward " \t")
17857 (delete-region (point) (match-end 0)))
17858 (forward-line)))
17859 ;; Case 2. Start at an heading: convert to items.
17860 ((org-on-heading-p)
17861 (let* ((bul (org-list-bullet-string "-"))
17862 (bul-len (length bul))
17863 ;; Indentation of the first heading. It should be
17864 ;; relative to the indentation of its parent, if any.
17865 (start-ind (save-excursion
17866 (cond
17867 ((not org-adapt-indentation) 0)
17868 ((not (outline-previous-heading)) 0)
17869 (t (length (match-string 0))))))
17870 ;; Level of first heading. Further headings will be
17871 ;; compared to it to determine hierarchy in the list.
17872 (ref-level (org-reduced-level (org-outline-level))))
17873 (while (< (point) end)
17874 (let* ((level (org-reduced-level (org-outline-level)))
17875 (delta (max 0 (- level ref-level))))
17876 ;; If current headline is less indented than the first
17877 ;; one, set it as reference, in order to preserve
17878 ;; subtrees.
17879 (when (< level ref-level) (setq ref-level level))
17880 (replace-match bul t t)
17881 (org-indent-line-to (+ start-ind (* delta bul-len)))
17882 ;; Ensure all text down to END (or SECTION-END) belongs
17883 ;; to the newly created item.
17884 (let ((section-end (save-excursion
17885 (or (outline-next-heading) (point)))))
17886 (forward-line)
17887 (funcall shift-text
17888 (+ start-ind (* (1+ delta) bul-len))
17889 (min end section-end)))))))
17890 ;; Case 3. Normal line with ARG: turn each non-item line into
17891 ;; an item.
17892 (arg
17893 (while (< (point) end)
17894 (unless (or (org-on-heading-p) (org-at-item-p))
17895 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17896 (replace-match
17897 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
17898 (forward-line)))
17899 ;; Case 4. Normal line without ARG: make the first line of
17900 ;; region an item, and shift indentation of others
17901 ;; lines to set them as item's body.
17902 (t (let* ((bul (org-list-bullet-string "-"))
17903 (bul-len (length bul))
17904 (ref-ind (org-get-indentation)))
17905 (skip-chars-forward " \t")
17906 (insert bul)
17907 (forward-line)
17908 (while (< (point) end)
17909 ;; Ensure that lines less indented than first one
17910 ;; still get included in item body.
17911 (funcall shift-text
17912 (+ ref-ind bul-len)
17913 (min end (save-excursion (or (outline-next-heading)
17914 (point)))))
17915 (forward-line)))))))))
17917 (defun org-toggle-heading (&optional nstars)
17918 "Convert headings to normal text, or items or text to headings.
17919 If there is no active region, only the current line is considered.
17921 If the first non blank line is an headline, remove the stars from
17922 all headlines in the region.
17924 If it is a plain list item, turn all plain list items into headings.
17926 If it is a normal line, turn each and every normal line (i.e. not
17927 an heading or an item) in the region into a heading.
17929 When converting a line into a heading, the number of stars is chosen
17930 such that the lines become children of the current entry. However,
17931 when a prefix argument is given, its value determines the number of
17932 stars to add."
17933 (interactive "P")
17934 (let ((skip-blanks
17935 (function
17936 ;; Return beginning of first non-blank line, starting from
17937 ;; line at POS.
17938 (lambda (pos)
17939 (save-excursion
17940 (goto-char pos)
17941 (skip-chars-forward " \r\t\n")
17942 (point-at-bol)))))
17943 beg end)
17944 ;; Determine boundaries of changes. If region ends at a bol, do
17945 ;; not consider the last line to be in the region.
17946 (if (org-region-active-p)
17947 (setq beg (funcall skip-blanks (region-beginning))
17948 end (copy-marker (save-excursion
17949 (goto-char (region-end))
17950 (if (bolp) (point) (point-at-eol)))))
17951 (setq beg (funcall skip-blanks (point-at-bol))
17952 end (copy-marker (point-at-eol))))
17953 ;; Ensure inline tasks don't count as headings.
17954 (org-with-limited-levels
17955 (save-excursion
17956 (goto-char beg)
17957 (cond
17958 ;; Case 1. Started at an heading: de-star headings.
17959 ((org-on-heading-p)
17960 (while (< (point) end)
17961 (when (org-on-heading-p t)
17962 (looking-at outline-regexp) (replace-match ""))
17963 (forward-line)))
17964 ;; Case 2. Started at an item: change items into headlines.
17965 ((org-at-item-p)
17966 (let ((stars (make-string
17967 (if nstars
17968 (prefix-numeric-value current-prefix-arg)
17969 (or (org-current-level) 0))
17970 ?*)))
17971 (while (< (point) end)
17972 (when (org-at-item-p)
17973 ;; Pay attention to cases when region ends before list.
17974 (let* ((struct (org-list-struct))
17975 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
17976 (save-restriction
17977 (narrow-to-region (point) list-end)
17978 (insert
17979 (org-list-to-subtree
17980 (org-list-parse-list t)
17981 '(:istart (concat stars (funcall get-stars depth))
17982 :icount (concat stars
17983 (funcall get-stars depth))))))))
17984 (forward-line))))
17985 ;; Case 3. Started at normal text: make every line an heading,
17986 ;; skipping headlines and items.
17987 (t (let* ((stars (make-string
17988 (if nstars
17989 (prefix-numeric-value current-prefix-arg)
17990 (or (org-current-level) 0))
17991 ?*))
17992 (add-stars (cond (nstars "")
17993 ((equal stars "") "*")
17994 (org-odd-levels-only "**")
17995 (t "*")))
17996 (rpl (concat stars add-stars " ")))
17997 (while (< (point) end)
17998 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
17999 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18000 (replace-match (concat rpl (match-string 2))))
18001 (forward-line)))))))))
18003 (defun org-meta-return (&optional arg)
18004 "Insert a new heading or wrap a region in a table.
18005 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18006 See the individual commands for more information."
18007 (interactive "P")
18008 (cond
18009 ((run-hook-with-args-until-success 'org-metareturn-hook))
18010 ((org-at-table-p)
18011 (call-interactively 'org-table-wrap-region))
18012 (t (call-interactively 'org-insert-heading))))
18014 ;;; Menu entries
18016 ;; Define the Org-mode menus
18017 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18018 '("Tbl"
18019 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18020 ["Next Field" org-cycle (org-at-table-p)]
18021 ["Previous Field" org-shifttab (org-at-table-p)]
18022 ["Next Row" org-return (org-at-table-p)]
18023 "--"
18024 ["Blank Field" org-table-blank-field (org-at-table-p)]
18025 ["Edit Field" org-table-edit-field (org-at-table-p)]
18026 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18027 "--"
18028 ("Column"
18029 ["Move Column Left" org-metaleft (org-at-table-p)]
18030 ["Move Column Right" org-metaright (org-at-table-p)]
18031 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18032 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18033 ("Row"
18034 ["Move Row Up" org-metaup (org-at-table-p)]
18035 ["Move Row Down" org-metadown (org-at-table-p)]
18036 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18037 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18038 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18039 "--"
18040 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18041 ("Rectangle"
18042 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18043 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18044 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18045 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18046 "--"
18047 ("Calculate"
18048 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18049 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18050 ["Edit Formulas" org-edit-special (org-at-table-p)]
18051 "--"
18052 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18053 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18054 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18055 "--"
18056 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18057 "--"
18058 ["Sum Column/Rectangle" org-table-sum
18059 (or (org-at-table-p) (org-region-active-p))]
18060 ["Which Column?" org-table-current-column (org-at-table-p)])
18061 ["Debug Formulas"
18062 org-table-toggle-formula-debugger
18063 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18064 ["Show Col/Row Numbers"
18065 org-table-toggle-coordinate-overlays
18066 :style toggle
18067 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18068 "--"
18069 ["Create" org-table-create (and (not (org-at-table-p))
18070 org-enable-table-editor)]
18071 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18072 ["Import from File" org-table-import (not (org-at-table-p))]
18073 ["Export to File" org-table-export (org-at-table-p)]
18074 "--"
18075 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18077 (easy-menu-define org-org-menu org-mode-map "Org menu"
18078 '("Org"
18079 ("Show/Hide"
18080 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18081 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18082 ["Sparse Tree..." org-sparse-tree t]
18083 ["Reveal Context" org-reveal t]
18084 ["Show All" show-all t]
18085 "--"
18086 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18087 "--"
18088 ["New Heading" org-insert-heading t]
18089 ("Navigate Headings"
18090 ["Up" outline-up-heading t]
18091 ["Next" outline-next-visible-heading t]
18092 ["Previous" outline-previous-visible-heading t]
18093 ["Next Same Level" outline-forward-same-level t]
18094 ["Previous Same Level" outline-backward-same-level t]
18095 "--"
18096 ["Jump" org-goto t])
18097 ("Edit Structure"
18098 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18099 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18100 "--"
18101 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18102 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18103 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18104 "--"
18105 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18106 "--"
18107 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18108 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18109 ["Demote Heading" org-metaright (not (org-at-table-p))]
18110 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18111 "--"
18112 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18113 "--"
18114 ["Convert to odd levels" org-convert-to-odd-levels t]
18115 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18116 ("Editing"
18117 ["Emphasis..." org-emphasize t]
18118 ["Edit Source Example" org-edit-special t]
18119 "--"
18120 ["Footnote new/jump" org-footnote-action t]
18121 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18122 ("Archive"
18123 ["Archive (default method)" org-archive-subtree-default t]
18124 "--"
18125 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18126 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18127 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18129 "--"
18130 ("Hyperlinks"
18131 ["Store Link (Global)" org-store-link t]
18132 ["Find existing link to here" org-occur-link-in-agenda-files t]
18133 ["Insert Link" org-insert-link t]
18134 ["Follow Link" org-open-at-point t]
18135 "--"
18136 ["Next link" org-next-link t]
18137 ["Previous link" org-previous-link t]
18138 "--"
18139 ["Descriptive Links"
18140 (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
18141 :style radio
18142 :selected (member '(org-link) buffer-invisibility-spec)]
18143 ["Literal Links"
18144 (progn
18145 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
18146 :style radio
18147 :selected (not (member '(org-link) buffer-invisibility-spec))])
18148 "--"
18149 ("TODO Lists"
18150 ["TODO/DONE/-" org-todo t]
18151 ("Select keyword"
18152 ["Next keyword" org-shiftright (org-on-heading-p)]
18153 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18154 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18155 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18156 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18157 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18158 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18159 "--"
18160 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18161 :selected org-enforce-todo-dependencies :style toggle :active t]
18162 "Settings for tree at point"
18163 ["Do Children sequentially" org-toggle-ordered-property :style radio
18164 :selected (org-entry-get nil "ORDERED")
18165 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18166 ["Do Children parallel" org-toggle-ordered-property :style radio
18167 :selected (not (org-entry-get nil "ORDERED"))
18168 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18169 "--"
18170 ["Set Priority" org-priority t]
18171 ["Priority Up" org-shiftup t]
18172 ["Priority Down" org-shiftdown t]
18173 "--"
18174 ["Get news from all feeds" org-feed-update-all t]
18175 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18176 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18177 ("TAGS and Properties"
18178 ["Set Tags" org-set-tags-command t]
18179 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18180 "--"
18181 ["Set property" org-set-property t]
18182 ["Column view of properties" org-columns t]
18183 ["Insert Column View DBlock" org-insert-columns-dblock t])
18184 ("Dates and Scheduling"
18185 ["Timestamp" org-time-stamp t]
18186 ["Timestamp (inactive)" org-time-stamp-inactive t]
18187 ("Change Date"
18188 ["1 Day Later" org-shiftright t]
18189 ["1 Day Earlier" org-shiftleft t]
18190 ["1 ... Later" org-shiftup t]
18191 ["1 ... Earlier" org-shiftdown t])
18192 ["Compute Time Range" org-evaluate-time-range t]
18193 ["Schedule Item" org-schedule t]
18194 ["Deadline" org-deadline t]
18195 "--"
18196 ["Custom time format" org-toggle-time-stamp-overlays
18197 :style radio :selected org-display-custom-times]
18198 "--"
18199 ["Goto Calendar" org-goto-calendar t]
18200 ["Date from Calendar" org-date-from-calendar t]
18201 "--"
18202 ["Start/Restart Timer" org-timer-start t]
18203 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18204 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18205 ["Insert Timer String" org-timer t]
18206 ["Insert Timer Item" org-timer-item t])
18207 ("Logging work"
18208 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18209 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18210 ["Clock out" org-clock-out t]
18211 ["Clock cancel" org-clock-cancel t]
18212 "--"
18213 ["Mark as default task" org-clock-mark-default-task t]
18214 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18215 ["Goto running clock" org-clock-goto t]
18216 "--"
18217 ["Display times" org-clock-display t]
18218 ["Create clock table" org-clock-report t]
18219 "--"
18220 ["Record DONE time"
18221 (progn (setq org-log-done (not org-log-done))
18222 (message "Switching to %s will %s record a timestamp"
18223 (car org-done-keywords)
18224 (if org-log-done "automatically" "not")))
18225 :style toggle :selected org-log-done])
18226 "--"
18227 ["Agenda Command..." org-agenda t]
18228 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18229 ("File List for Agenda")
18230 ("Special views current file"
18231 ["TODO Tree" org-show-todo-tree t]
18232 ["Check Deadlines" org-check-deadlines t]
18233 ["Timeline" org-timeline t]
18234 ["Tags/Property tree" org-match-sparse-tree t])
18235 "--"
18236 ["Export/Publish..." org-export t]
18237 ("LaTeX"
18238 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18239 :selected org-cdlatex-mode]
18240 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18241 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18242 ["Modify math symbol" org-cdlatex-math-modify
18243 (org-inside-LaTeX-fragment-p)]
18244 ["Insert citation" org-reftex-citation t]
18245 "--"
18246 ["Template for BEAMER" org-insert-beamer-options-template t])
18247 "--"
18248 ("MobileOrg"
18249 ["Push Files and Views" org-mobile-push t]
18250 ["Get Captured and Flagged" org-mobile-pull t]
18251 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18252 "--"
18253 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18254 "--"
18255 ("Documentation"
18256 ["Show Version" org-version t]
18257 ["Info Documentation" org-info t])
18258 ("Customize"
18259 ["Browse Org Group" org-customize t]
18260 "--"
18261 ["Expand This Menu" org-create-customize-menu
18262 (fboundp 'customize-menu-create)])
18263 ["Send bug report" org-submit-bug-report t]
18264 "--"
18265 ("Refresh/Reload"
18266 ["Refresh setup current buffer" org-mode-restart t]
18267 ["Reload Org (after update)" org-reload t]
18268 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18271 (defun org-info (&optional node)
18272 "Read documentation for Org-mode in the info system.
18273 With optional NODE, go directly to that node."
18274 (interactive)
18275 (info (format "(org)%s" (or node ""))))
18277 ;;;###autoload
18278 (defun org-submit-bug-report ()
18279 "Submit a bug report on Org-mode via mail.
18281 Don't hesitate to report any problems or inaccurate documentation.
18283 If you don't have setup sending mail from (X)Emacs, please copy the
18284 output buffer into your mail program, as it gives us important
18285 information about your Org-mode version and configuration."
18286 (interactive)
18287 (require 'reporter)
18288 (org-load-modules-maybe)
18289 (org-require-autoloaded-modules)
18290 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18291 (reporter-submit-bug-report
18292 "emacs-orgmode@gnu.org"
18293 (org-version)
18294 (let (list)
18295 (save-window-excursion
18296 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
18297 (delete-other-windows)
18298 (erase-buffer)
18299 (insert "You are about to submit a bug report to the Org-mode mailing list.
18301 We would like to add your full Org-mode and Outline configuration to the
18302 bug report. This greatly simplifies the work of the maintainer and
18303 other experts on the mailing list.
18305 HOWEVER, some variables you have customized may contain private
18306 information. The names of customers, colleagues, or friends, might
18307 appear in the form of file names, tags, todo states, or search strings.
18308 If you answer yes to the prompt, you might want to check and remove
18309 such private information before sending the email.")
18310 (add-text-properties (point-min) (point-max) '(face org-warning))
18311 (when (yes-or-no-p "Include your Org-mode configuration ")
18312 (mapatoms
18313 (lambda (v)
18314 (and (boundp v)
18315 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
18316 (or (and (symbol-value v)
18317 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
18318 (and
18319 (get v 'custom-type) (get v 'standard-value)
18320 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18321 (push v list)))))
18322 (kill-buffer (get-buffer "*Warn about privacy*"))
18323 list))
18324 nil nil
18325 "Remember to cover the basics, that is, what you expected to happen and
18326 what in fact did happen. You don't know how to make a good report? See
18328 http://orgmode.org/manual/Feedback.html#Feedback
18330 Your bug report will be posted to the Org-mode mailing list.
18331 ------------------------------------------------------------------------")
18332 (save-excursion
18333 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
18334 (replace-match "\\1Bug: \\3 [\\2]")))))
18337 (defun org-install-agenda-files-menu ()
18338 (let ((bl (buffer-list)))
18339 (save-excursion
18340 (while bl
18341 (set-buffer (pop bl))
18342 (if (org-mode-p) (setq bl nil)))
18343 (when (org-mode-p)
18344 (easy-menu-change
18345 '("Org") "File List for Agenda"
18346 (append
18347 (list
18348 ["Edit File List" (org-edit-agenda-file-list) t]
18349 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
18350 ["Remove Current File from List" org-remove-file t]
18351 ["Cycle through agenda files" org-cycle-agenda-files t]
18352 ["Occur in all agenda files" org-occur-in-agenda-files t]
18353 "--")
18354 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
18356 ;;;; Documentation
18358 ;;;###autoload
18359 (defun org-require-autoloaded-modules ()
18360 (interactive)
18361 (mapc 'require
18362 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
18363 org-docbook org-exp org-html org-icalendar
18364 org-id org-latex
18365 org-publish org-remember org-table
18366 org-timer org-xoxo)))
18368 ;;;###autoload
18369 (defun org-reload (&optional uncompiled)
18370 "Reload all org lisp files.
18371 With prefix arg UNCOMPILED, load the uncompiled versions."
18372 (interactive "P")
18373 (require 'find-func)
18374 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
18375 (dir-org (file-name-directory (org-find-library-name "org")))
18376 (dir-org-contrib (ignore-errors
18377 (file-name-directory
18378 (org-find-library-name "org-contribdir"))))
18379 (babel-files
18380 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
18381 (append (list nil "comint" "eval" "exp" "keys"
18382 "lob" "ref" "table" "tangle")
18383 (delq nil
18384 (mapcar
18385 (lambda (lang)
18386 (when (cdr lang) (symbol-name (car lang))))
18387 org-babel-load-languages)))))
18388 (files
18389 (append (directory-files dir-org t file-re)
18390 babel-files
18391 (and dir-org-contrib
18392 (directory-files dir-org-contrib t file-re))))
18393 (remove-re (concat (if (featurep 'xemacs)
18394 "org-colview" "org-colview-xemacs")
18395 "\\'")))
18396 (setq files (mapcar 'file-name-sans-extension files))
18397 (setq files (mapcar
18398 (lambda (x) (if (string-match remove-re x) nil x))
18399 files))
18400 (setq files (delq nil files))
18401 (mapc
18402 (lambda (f)
18403 (when (featurep (intern (file-name-nondirectory f)))
18404 (if (and (not uncompiled)
18405 (file-exists-p (concat f ".elc")))
18406 (load (concat f ".elc") nil nil t)
18407 (load (concat f ".el") nil nil t))))
18408 files))
18409 (org-version))
18411 ;;;###autoload
18412 (defun org-customize ()
18413 "Call the customize function with org as argument."
18414 (interactive)
18415 (org-load-modules-maybe)
18416 (org-require-autoloaded-modules)
18417 (customize-browse 'org))
18419 (defun org-create-customize-menu ()
18420 "Create a full customization menu for Org-mode, insert it into the menu."
18421 (interactive)
18422 (org-load-modules-maybe)
18423 (org-require-autoloaded-modules)
18424 (if (fboundp 'customize-menu-create)
18425 (progn
18426 (easy-menu-change
18427 '("Org") "Customize"
18428 `(["Browse Org group" org-customize t]
18429 "--"
18430 ,(customize-menu-create 'org)
18431 ["Set" Custom-set t]
18432 ["Save" Custom-save t]
18433 ["Reset to Current" Custom-reset-current t]
18434 ["Reset to Saved" Custom-reset-saved t]
18435 ["Reset to Standard Settings" Custom-reset-standard t]))
18436 (message "\"Org\"-menu now contains full customization menu"))
18437 (error "Cannot expand menu (outdated version of cus-edit.el)")))
18439 ;;;; Miscellaneous stuff
18441 ;;; Generally useful functions
18443 (defun org-get-at-bol (property)
18444 "Get text property PROPERTY at beginning of line."
18445 (get-text-property (point-at-bol) property))
18447 (defun org-find-text-property-in-string (prop s)
18448 "Return the first non-nil value of property PROP in string S."
18449 (or (get-text-property 0 prop s)
18450 (get-text-property (or (next-single-property-change 0 prop s) 0)
18451 prop s)))
18453 (defun org-display-warning (message) ;; Copied from Emacs-Muse
18454 "Display the given MESSAGE as a warning."
18455 (if (fboundp 'display-warning)
18456 (display-warning 'org message
18457 (if (featurep 'xemacs) 'warning :warning))
18458 (let ((buf (get-buffer-create "*Org warnings*")))
18459 (with-current-buffer buf
18460 (goto-char (point-max))
18461 (insert "Warning (Org): " message)
18462 (unless (bolp)
18463 (newline)))
18464 (display-buffer buf)
18465 (sit-for 0))))
18467 (defun org-eval (form)
18468 "Eval FORM and return result."
18469 (condition-case error
18470 (eval form)
18471 (error (format "%%![Error: %s]" error))))
18473 (defun org-in-commented-line ()
18474 "Is point in a line starting with `#'?"
18475 (equal (char-after (point-at-bol)) ?#))
18477 (defun org-in-indented-comment-line ()
18478 "Is point in a line starting with `#' after some white space?"
18479 (save-excursion
18480 (save-match-data
18481 (goto-char (point-at-bol))
18482 (looking-at "[ \t]*#"))))
18484 (defun org-in-verbatim-emphasis ()
18485 (save-match-data
18486 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
18488 (defun org-goto-marker-or-bmk (marker &optional bookmark)
18489 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
18490 (if (and marker (marker-buffer marker)
18491 (buffer-live-p (marker-buffer marker)))
18492 (progn
18493 (switch-to-buffer (marker-buffer marker))
18494 (if (or (> marker (point-max)) (< marker (point-min)))
18495 (widen))
18496 (goto-char marker)
18497 (org-show-context 'org-goto))
18498 (if bookmark
18499 (bookmark-jump bookmark)
18500 (error "Cannot find location"))))
18502 (defun org-quote-csv-field (s)
18503 "Quote field for inclusion in CSV material."
18504 (if (string-match "[\",]" s)
18505 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
18508 (defun org-force-self-insert (N)
18509 "Needed to enforce self-insert under remapping."
18510 (interactive "p")
18511 (self-insert-command N))
18513 (defun org-string-width (s)
18514 "Compute width of string, ignoring invisible characters.
18515 This ignores character with invisibility property `org-link', and also
18516 characters with property `org-cwidth', because these will become invisible
18517 upon the next fontification round."
18518 (let (b l)
18519 (when (or (eq t buffer-invisibility-spec)
18520 (assq 'org-link buffer-invisibility-spec))
18521 (while (setq b (text-property-any 0 (length s)
18522 'invisible 'org-link s))
18523 (setq s (concat (substring s 0 b)
18524 (substring s (or (next-single-property-change
18525 b 'invisible s) (length s)))))))
18526 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
18527 (setq s (concat (substring s 0 b)
18528 (substring s (or (next-single-property-change
18529 b 'org-cwidth s) (length s))))))
18530 (setq l (string-width s) b -1)
18531 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
18532 (setq l (- l (get-text-property b 'org-dwidth-n s))))
18535 (defun org-shorten-string (s maxlength)
18536 "Shorten string S so tht it is no longer than MAXLENGTH characters.
18537 If the string is shorter or has length MAXLENGTH, just return the
18538 original string. If it is longer, the functions finds a space in the
18539 string, breaks this string off at that locations and adds three dots
18540 as ellipsis. Including the ellipsis, the string will not be longer
18541 than MAXLENGTH. If finding a good breaking point in the string does
18542 not work, the string is just chopped off in the middle of a word
18543 if necessary."
18544 (if (<= (length s) maxlength)
18546 (let* ((n (max (- maxlength 4) 1))
18547 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
18548 (if (string-match re s)
18549 (concat (match-string 1 s) "...")
18550 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
18552 (defun org-get-indentation (&optional line)
18553 "Get the indentation of the current line, interpreting tabs.
18554 When LINE is given, assume it represents a line and compute its indentation."
18555 (if line
18556 (if (string-match "^ *" (org-remove-tabs line))
18557 (match-end 0))
18558 (save-excursion
18559 (beginning-of-line 1)
18560 (skip-chars-forward " \t")
18561 (current-column))))
18563 (defun org-get-string-indentation (s)
18564 "What indentation has S due to SPACE and TAB at the beginning of the string?"
18565 (let ((n -1) (i 0) (w tab-width) c)
18566 (catch 'exit
18567 (while (< (setq n (1+ n)) (length s))
18568 (setq c (aref s n))
18569 (cond ((= c ?\ ) (setq i (1+ i)))
18570 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
18571 (t (throw 'exit t)))))
18574 (defun org-remove-tabs (s &optional width)
18575 "Replace tabulators in S with spaces.
18576 Assumes that s is a single line, starting in column 0."
18577 (setq width (or width tab-width))
18578 (while (string-match "\t" s)
18579 (setq s (replace-match
18580 (make-string
18581 (- (* width (/ (+ (match-beginning 0) width) width))
18582 (match-beginning 0)) ?\ )
18583 t t s)))
18586 (defun org-fix-indentation (line ind)
18587 "Fix indentation in LINE.
18588 IND is a cons cell with target and minimum indentation.
18589 If the current indentation in LINE is smaller than the minimum,
18590 leave it alone. If it is larger than ind, set it to the target."
18591 (let* ((l (org-remove-tabs line))
18592 (i (org-get-indentation l))
18593 (i1 (car ind)) (i2 (cdr ind)))
18594 (if (>= i i2) (setq l (substring line i2)))
18595 (if (> i1 0)
18596 (concat (make-string i1 ?\ ) l)
18597 l)))
18599 (defun org-remove-indentation (code &optional n)
18600 "Remove the maximum common indentation from the lines in CODE.
18601 N may optionally be the number of spaces to remove."
18602 (with-temp-buffer
18603 (insert code)
18604 (org-do-remove-indentation n)
18605 (buffer-string)))
18607 (defun org-do-remove-indentation (&optional n)
18608 "Remove the maximum common indentation from the buffer."
18609 (untabify (point-min) (point-max))
18610 (let ((min 10000) re)
18611 (if n
18612 (setq min n)
18613 (goto-char (point-min))
18614 (while (re-search-forward "^ *[^ \n]" nil t)
18615 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
18616 (unless (or (= min 0) (= min 10000))
18617 (setq re (format "^ \\{%d\\}" min))
18618 (goto-char (point-min))
18619 (while (re-search-forward re nil t)
18620 (replace-match "")
18621 (end-of-line 1))
18622 min)))
18624 (defun org-fill-template (template alist)
18625 "Find each %key of ALIST in TEMPLATE and replace it."
18626 (let ((case-fold-search nil)
18627 entry key value)
18628 (setq alist (sort (copy-sequence alist)
18629 (lambda (a b) (< (length (car a)) (length (car b))))))
18630 (while (setq entry (pop alist))
18631 (setq template
18632 (replace-regexp-in-string
18633 (concat "%" (regexp-quote (car entry)))
18634 (cdr entry) template t t)))
18635 template))
18637 (defun org-base-buffer (buffer)
18638 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
18639 (if (not buffer)
18640 buffer
18641 (or (buffer-base-buffer buffer)
18642 buffer)))
18644 (defun org-trim (s)
18645 "Remove whitespace at beginning and end of string."
18646 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
18647 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
18650 (defun org-wrap (string &optional width lines)
18651 "Wrap string to either a number of lines, or a width in characters.
18652 If WIDTH is non-nil, the string is wrapped to that width, however many lines
18653 that costs. If there is a word longer than WIDTH, the text is actually
18654 wrapped to the length of that word.
18655 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
18656 many lines, whatever width that takes.
18657 The return value is a list of lines, without newlines at the end."
18658 (let* ((words (org-split-string string "[ \t\n]+"))
18659 (maxword (apply 'max (mapcar 'org-string-width words)))
18660 w ll)
18661 (cond (width
18662 (org-do-wrap words (max maxword width)))
18663 (lines
18664 (setq w maxword)
18665 (setq ll (org-do-wrap words maxword))
18666 (if (<= (length ll) lines)
18668 (setq ll words)
18669 (while (> (length ll) lines)
18670 (setq w (1+ w))
18671 (setq ll (org-do-wrap words w)))
18672 ll))
18673 (t (error "Cannot wrap this")))))
18675 (defun org-do-wrap (words width)
18676 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
18677 (let (lines line)
18678 (while words
18679 (setq line (pop words))
18680 (while (and words (< (+ (length line) (length (car words))) width))
18681 (setq line (concat line " " (pop words))))
18682 (setq lines (push line lines)))
18683 (nreverse lines)))
18685 (defun org-split-string (string &optional separators)
18686 "Splits STRING into substrings at SEPARATORS.
18687 No empty strings are returned if there are matches at the beginning
18688 and end of string."
18689 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
18690 (start 0)
18691 notfirst
18692 (list nil))
18693 (while (and (string-match rexp string
18694 (if (and notfirst
18695 (= start (match-beginning 0))
18696 (< start (length string)))
18697 (1+ start) start))
18698 (< (match-beginning 0) (length string)))
18699 (setq notfirst t)
18700 (or (eq (match-beginning 0) 0)
18701 (and (eq (match-beginning 0) (match-end 0))
18702 (eq (match-beginning 0) start))
18703 (setq list
18704 (cons (substring string start (match-beginning 0))
18705 list)))
18706 (setq start (match-end 0)))
18707 (or (eq start (length string))
18708 (setq list
18709 (cons (substring string start)
18710 list)))
18711 (nreverse list)))
18713 (defun org-quote-vert (s)
18714 "Replace \"|\" with \"\\vert\"."
18715 (while (string-match "|" s)
18716 (setq s (replace-match "\\vert" t t s)))
18719 (defun org-uuidgen-p (s)
18720 "Is S an ID created by UUIDGEN?"
18721 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
18723 (defun org-context ()
18724 "Return a list of contexts of the current cursor position.
18725 If several contexts apply, all are returned.
18726 Each context entry is a list with a symbol naming the context, and
18727 two positions indicating start and end of the context. Possible
18728 contexts are:
18730 :headline anywhere in a headline
18731 :headline-stars on the leading stars in a headline
18732 :todo-keyword on a TODO keyword (including DONE) in a headline
18733 :tags on the TAGS in a headline
18734 :priority on the priority cookie in a headline
18735 :item on the first line of a plain list item
18736 :item-bullet on the bullet/number of a plain list item
18737 :checkbox on the checkbox in a plain list item
18738 :table in an org-mode table
18739 :table-special on a special filed in a table
18740 :table-table in a table.el table
18741 :link on a hyperlink
18742 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
18743 :target on a <<target>>
18744 :radio-target on a <<<radio-target>>>
18745 :latex-fragment on a LaTeX fragment
18746 :latex-preview on a LaTeX fragment with overlayed preview image
18748 This function expects the position to be visible because it uses font-lock
18749 faces as a help to recognize the following contexts: :table-special, :link,
18750 and :keyword."
18751 (let* ((f (get-text-property (point) 'face))
18752 (faces (if (listp f) f (list f)))
18753 (p (point)) clist o)
18754 ;; First the large context
18755 (cond
18756 ((org-on-heading-p t)
18757 (push (list :headline (point-at-bol) (point-at-eol)) clist)
18758 (when (progn
18759 (beginning-of-line 1)
18760 (looking-at org-todo-line-tags-regexp))
18761 (push (org-point-in-group p 1 :headline-stars) clist)
18762 (push (org-point-in-group p 2 :todo-keyword) clist)
18763 (push (org-point-in-group p 4 :tags) clist))
18764 (goto-char p)
18765 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
18766 (if (looking-at "\\[#[A-Z0-9]\\]")
18767 (push (org-point-in-group p 0 :priority) clist)))
18769 ((org-at-item-p)
18770 (push (org-point-in-group p 2 :item-bullet) clist)
18771 (push (list :item (point-at-bol)
18772 (save-excursion (org-end-of-item) (point)))
18773 clist)
18774 (and (org-at-item-checkbox-p)
18775 (push (org-point-in-group p 0 :checkbox) clist)))
18777 ((org-at-table-p)
18778 (push (list :table (org-table-begin) (org-table-end)) clist)
18779 (if (memq 'org-formula faces)
18780 (push (list :table-special
18781 (previous-single-property-change p 'face)
18782 (next-single-property-change p 'face)) clist)))
18783 ((org-at-table-p 'any)
18784 (push (list :table-table) clist)))
18785 (goto-char p)
18787 ;; Now the small context
18788 (cond
18789 ((org-at-timestamp-p)
18790 (push (org-point-in-group p 0 :timestamp) clist))
18791 ((memq 'org-link faces)
18792 (push (list :link
18793 (previous-single-property-change p 'face)
18794 (next-single-property-change p 'face)) clist))
18795 ((memq 'org-special-keyword faces)
18796 (push (list :keyword
18797 (previous-single-property-change p 'face)
18798 (next-single-property-change p 'face)) clist))
18799 ((org-on-target-p)
18800 (push (org-point-in-group p 0 :target) clist)
18801 (goto-char (1- (match-beginning 0)))
18802 (if (looking-at org-radio-target-regexp)
18803 (push (org-point-in-group p 0 :radio-target) clist))
18804 (goto-char p))
18805 ((setq o (car (delq nil
18806 (mapcar
18807 (lambda (x)
18808 (if (memq x org-latex-fragment-image-overlays) x))
18809 (overlays-at (point))))))
18810 (push (list :latex-fragment
18811 (overlay-start o) (overlay-end o)) clist)
18812 (push (list :latex-preview
18813 (overlay-start o) (overlay-end o)) clist))
18814 ((org-inside-LaTeX-fragment-p)
18815 ;; FIXME: positions wrong.
18816 (push (list :latex-fragment (point) (point)) clist)))
18818 (setq clist (nreverse (delq nil clist)))
18819 clist))
18821 ;; FIXME: Compare with at-regexp-p Do we need both?
18822 (defun org-in-regexp (re &optional nlines visually)
18823 "Check if point is inside a match of regexp.
18824 Normally only the current line is checked, but you can include NLINES extra
18825 lines both before and after point into the search.
18826 If VISUALLY is set, require that the cursor is not after the match but
18827 really on, so that the block visually is on the match."
18828 (catch 'exit
18829 (let ((pos (point))
18830 (eol (point-at-eol (+ 1 (or nlines 0))))
18831 (inc (if visually 1 0)))
18832 (save-excursion
18833 (beginning-of-line (- 1 (or nlines 0)))
18834 (while (re-search-forward re eol t)
18835 (if (and (<= (match-beginning 0) pos)
18836 (>= (+ inc (match-end 0)) pos))
18837 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
18839 (defun org-at-regexp-p (regexp)
18840 "Is point inside a match of REGEXP in the current line?"
18841 (catch 'exit
18842 (save-excursion
18843 (let ((pos (point)) (end (point-at-eol)))
18844 (beginning-of-line 1)
18845 (while (re-search-forward regexp end t)
18846 (if (and (<= (match-beginning 0) pos)
18847 (>= (match-end 0) pos))
18848 (throw 'exit t)))
18849 nil))))
18851 (defun org-in-regexps-block-p (start-re end-re &optional bound)
18852 "Return t if the current point is between matches of START-RE and END-RE.
18853 This will also return t if point is on one of the two matches or
18854 in an unfinished block. END-RE can be a string or a form
18855 returning a string.
18857 An optional third argument bounds the search for START-RE. It
18858 defaults to previous heading or `point-min'."
18859 (let ((pos (point))
18860 (limit (or bound (save-excursion (outline-previous-heading)))))
18861 (save-excursion
18862 ;; we're on a block when point is on start-re...
18863 (or (org-at-regexp-p start-re)
18864 ;; ... or start-re can be found above...
18865 (and (re-search-backward start-re limit t)
18866 ;; ... but no end-re between start-re and point.
18867 (not (re-search-forward (eval end-re) pos t)))))))
18869 (defun org-occur-in-agenda-files (regexp &optional nlines)
18870 "Call `multi-occur' with buffers for all agenda files."
18871 (interactive "sOrg-files matching: \np")
18872 (let* ((files (org-agenda-files))
18873 (tnames (mapcar 'file-truename files))
18874 (extra org-agenda-text-search-extra-files)
18876 (when (eq (car extra) 'agenda-archives)
18877 (setq extra (cdr extra))
18878 (setq files (org-add-archive-files files)))
18879 (while (setq f (pop extra))
18880 (unless (member (file-truename f) tnames)
18881 (add-to-list 'files f 'append)
18882 (add-to-list 'tnames (file-truename f) 'append)))
18883 (multi-occur
18884 (mapcar (lambda (x)
18885 (with-current-buffer
18886 (or (get-file-buffer x) (find-file-noselect x))
18887 (widen)
18888 (current-buffer)))
18889 files)
18890 regexp)))
18892 (if (boundp 'occur-mode-find-occurrence-hook)
18893 ;; Emacs 23
18894 (add-hook 'occur-mode-find-occurrence-hook
18895 (lambda ()
18896 (when (org-mode-p)
18897 (org-reveal))))
18898 ;; Emacs 22
18899 (defadvice occur-mode-goto-occurrence
18900 (after org-occur-reveal activate)
18901 (and (org-mode-p) (org-reveal)))
18902 (defadvice occur-mode-goto-occurrence-other-window
18903 (after org-occur-reveal activate)
18904 (and (org-mode-p) (org-reveal)))
18905 (defadvice occur-mode-display-occurrence
18906 (after org-occur-reveal activate)
18907 (when (org-mode-p)
18908 (let ((pos (occur-mode-find-occurrence)))
18909 (with-current-buffer (marker-buffer pos)
18910 (save-excursion
18911 (goto-char pos)
18912 (org-reveal)))))))
18914 (defun org-occur-link-in-agenda-files ()
18915 "Create a link and search for it in the agendas.
18916 The link is not stored in `org-stored-links', it is just created
18917 for the search purpose."
18918 (interactive)
18919 (let ((link (condition-case nil
18920 (org-store-link nil)
18921 (error "Unable to create a link to here"))))
18922 (org-occur-in-agenda-files (regexp-quote link))))
18924 (defun org-uniquify (list)
18925 "Remove duplicate elements from LIST."
18926 (let (res)
18927 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
18928 res))
18930 (defun org-delete-all (elts list)
18931 "Remove all elements in ELTS from LIST."
18932 (while elts
18933 (setq list (delete (pop elts) list)))
18934 list)
18936 (defun org-count (cl-item cl-seq)
18937 "Count the number of occurrences of ITEM in SEQ.
18938 Taken from `count' in cl-seq.el with all keyword arguments removed."
18939 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
18940 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
18941 (while (< cl-start cl-end)
18942 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
18943 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
18944 (setq cl-start (1+ cl-start)))
18945 cl-count))
18947 (defun org-remove-if (predicate seq)
18948 "Remove everything from SEQ that fulfills PREDICATE."
18949 (let (res e)
18950 (while seq
18951 (setq e (pop seq))
18952 (if (not (funcall predicate e)) (push e res)))
18953 (nreverse res)))
18955 (defun org-remove-if-not (predicate seq)
18956 "Remove everything from SEQ that does not fulfill PREDICATE."
18957 (let (res e)
18958 (while seq
18959 (setq e (pop seq))
18960 (if (funcall predicate e) (push e res)))
18961 (nreverse res)))
18963 (defun org-back-over-empty-lines ()
18964 "Move backwards over whitespace, to the beginning of the first empty line.
18965 Returns the number of empty lines passed."
18966 (let ((pos (point)))
18967 (if (cdr (assoc 'heading org-blank-before-new-entry))
18968 (skip-chars-backward " \t\n\r")
18969 (forward-line -1))
18970 (beginning-of-line 2)
18971 (goto-char (min (point) pos))
18972 (count-lines (point) pos)))
18974 (defun org-skip-whitespace ()
18975 (skip-chars-forward " \t\n\r"))
18977 (defun org-point-in-group (point group &optional context)
18978 "Check if POINT is in match-group GROUP.
18979 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
18980 match. If the match group does not exist or point is not inside it,
18981 return nil."
18982 (and (match-beginning group)
18983 (>= point (match-beginning group))
18984 (<= point (match-end group))
18985 (if context
18986 (list context (match-beginning group) (match-end group))
18987 t)))
18989 (defun org-switch-to-buffer-other-window (&rest args)
18990 "Switch to buffer in a second window on the current frame.
18991 In particular, do not allow pop-up frames.
18992 Returns the newly created buffer."
18993 (let (pop-up-frames special-display-buffer-names special-display-regexps
18994 special-display-function)
18995 (apply 'switch-to-buffer-other-window args)))
18997 (defun org-combine-plists (&rest plists)
18998 "Create a single property list from all plists in PLISTS.
18999 The process starts by copying the first list, and then setting properties
19000 from the other lists. Settings in the last list are the most significant
19001 ones and overrule settings in the other lists."
19002 (let ((rtn (copy-sequence (pop plists)))
19003 p v ls)
19004 (while plists
19005 (setq ls (pop plists))
19006 (while ls
19007 (setq p (pop ls) v (pop ls))
19008 (setq rtn (plist-put rtn p v))))
19009 rtn))
19011 (defun org-move-line-down (arg)
19012 "Move the current line down. With prefix argument, move it past ARG lines."
19013 (interactive "p")
19014 (let ((col (current-column))
19015 beg end pos)
19016 (beginning-of-line 1) (setq beg (point))
19017 (beginning-of-line 2) (setq end (point))
19018 (beginning-of-line (+ 1 arg))
19019 (setq pos (move-marker (make-marker) (point)))
19020 (insert (delete-and-extract-region beg end))
19021 (goto-char pos)
19022 (org-move-to-column col)))
19024 (defun org-move-line-up (arg)
19025 "Move the current line up. With prefix argument, move it past ARG lines."
19026 (interactive "p")
19027 (let ((col (current-column))
19028 beg end pos)
19029 (beginning-of-line 1) (setq beg (point))
19030 (beginning-of-line 2) (setq end (point))
19031 (beginning-of-line (- arg))
19032 (setq pos (move-marker (make-marker) (point)))
19033 (insert (delete-and-extract-region beg end))
19034 (goto-char pos)
19035 (org-move-to-column col)))
19037 (defun org-replace-escapes (string table)
19038 "Replace %-escapes in STRING with values in TABLE.
19039 TABLE is an association list with keys like \"%a\" and string values.
19040 The sequences in STRING may contain normal field width and padding information,
19041 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19042 so values can contain further %-escapes if they are define later in TABLE."
19043 (let ((tbl (copy-alist table))
19044 (case-fold-search nil)
19045 (pchg 0)
19046 e re rpl)
19047 (while (setq e (pop tbl))
19048 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19049 (when (and (cdr e) (string-match re (cdr e)))
19050 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19051 (safe "SREF"))
19052 (add-text-properties 0 3 (list 'sref sref) safe)
19053 (setcdr e (replace-match safe t t (cdr e)))))
19054 (while (string-match re string)
19055 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19056 (cdr e)))
19057 (setq string (replace-match rpl t t string))))
19058 (while (setq pchg (next-property-change pchg string))
19059 (let ((sref (get-text-property pchg 'sref string)))
19060 (when (and sref (string-match "SREF" string pchg))
19061 (setq string (replace-match sref t t string)))))
19062 string))
19064 (defun org-sublist (list start end)
19065 "Return a section of LIST, from START to END.
19066 Counting starts at 1."
19067 (let (rtn (c start))
19068 (setq list (nthcdr (1- start) list))
19069 (while (and list (<= c end))
19070 (push (pop list) rtn)
19071 (setq c (1+ c)))
19072 (nreverse rtn)))
19074 (defun org-find-base-buffer-visiting (file)
19075 "Like `find-buffer-visiting' but always return the base buffer and
19076 not an indirect buffer."
19077 (let ((buf (or (get-file-buffer file)
19078 (find-buffer-visiting file))))
19079 (if buf
19080 (or (buffer-base-buffer buf) buf)
19081 nil)))
19083 (defun org-image-file-name-regexp (&optional extensions)
19084 "Return regexp matching the file names of images.
19085 If EXTENSIONS is given, only match these."
19086 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19087 (image-file-name-regexp)
19088 (let ((image-file-name-extensions
19089 (or extensions
19090 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19091 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19092 (concat "\\."
19093 (regexp-opt (nconc (mapcar 'upcase
19094 image-file-name-extensions)
19095 image-file-name-extensions)
19097 "\\'"))))
19099 (defun org-file-image-p (file &optional extensions)
19100 "Return non-nil if FILE is an image."
19101 (save-match-data
19102 (string-match (org-image-file-name-regexp extensions) file)))
19104 (defun org-get-cursor-date ()
19105 "Return the date at cursor in as a time.
19106 This works in the calendar and in the agenda, anywhere else it just
19107 returns the current time."
19108 (let (date day defd)
19109 (cond
19110 ((eq major-mode 'calendar-mode)
19111 (setq date (calendar-cursor-to-date)
19112 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19113 ((eq major-mode 'org-agenda-mode)
19114 (setq day (get-text-property (point) 'day))
19115 (if day
19116 (setq date (calendar-gregorian-from-absolute day)
19117 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19118 (nth 2 date))))))
19119 (or defd (current-time))))
19121 (defvar org-agenda-action-marker (make-marker)
19122 "Marker pointing to the entry for the next agenda action.")
19124 (defun org-mark-entry-for-agenda-action ()
19125 "Mark the current entry as target of an agenda action.
19126 Agenda actions are actions executed from the agenda with the key `k',
19127 which make use of the date at the cursor."
19128 (interactive)
19129 (move-marker org-agenda-action-marker
19130 (save-excursion (org-back-to-heading t) (point))
19131 (current-buffer))
19132 (message
19133 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19135 (defun org-mark-subtree ()
19136 "Mark the current subtree.
19137 This puts point at the start of the current subtree, and mark at the end.
19139 If point is in an inline task, mark that task instead."
19140 (interactive)
19141 (let ((inline-task-p
19142 (and (featurep 'org-inlinetask)
19143 (org-inlinetask-in-task-p)))
19144 (beg))
19145 ;; Get beginning of subtree
19146 (cond
19147 (inline-task-p (org-inlinetask-goto-beginning))
19148 ((org-at-heading-p) (beginning-of-line))
19149 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19150 (setq beg (point))
19151 ;; Get end of it
19152 (if inline-task-p
19153 (org-inlinetask-goto-end)
19154 (org-end-of-subtree))
19155 ;; Mark zone
19156 (push-mark (point) nil t)
19157 (goto-char beg)))
19159 ;;; Paragraph filling stuff.
19160 ;; We want this to be just right, so use the full arsenal.
19162 (defun org-indent-line-function ()
19163 "Indent line depending on context."
19164 (interactive)
19165 (let* ((pos (point))
19166 (itemp (org-at-item-p))
19167 (case-fold-search t)
19168 (org-drawer-regexp (or org-drawer-regexp "\000"))
19169 (inline-task-p (and (featurep 'org-inlinetask)
19170 (org-inlinetask-in-task-p)))
19171 (inline-re (and inline-task-p
19172 (org-inlinetask-outline-regexp)))
19173 column)
19174 (beginning-of-line 1)
19175 (cond
19176 ;; Comments
19177 ((looking-at "# ") (setq column 0))
19178 ;; Headings
19179 ((looking-at "\\*+ ") (setq column 0))
19180 ;; Included files
19181 ((looking-at "#\\+include:") (setq column 0))
19182 ;; Footnote definition
19183 ((looking-at org-footnote-definition-re) (setq column 0))
19184 ;; Literal examples
19185 ((looking-at "[ \t]*:[ \t]")
19186 (setq column (org-get-indentation))) ; do nothing
19187 ;; Lists
19188 ((ignore-errors (goto-char (org-in-item-p)))
19189 (setq column (if itemp
19190 (org-get-indentation)
19191 (org-list-item-body-column (point))))
19192 (goto-char pos))
19193 ;; Drawers
19194 ((and (looking-at "[ \t]*:END:")
19195 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19196 (save-excursion
19197 (goto-char (1- (match-beginning 1)))
19198 (setq column (current-column))))
19199 ;; Special blocks
19200 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19201 (save-excursion
19202 (re-search-backward
19203 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19204 (setq column (org-get-indentation (match-string 0))))
19205 ((and (not (looking-at "[ \t]*#\\+begin_"))
19206 (org-in-regexps-block-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19207 (save-excursion
19208 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19209 (setq column
19210 (if (equal (downcase (match-string 1)) "src")
19211 ;; src blocks: let `org-edit-src-exit' handle them
19212 (org-get-indentation)
19213 (org-get-indentation (match-string 0)))))
19214 ;; This line has nothing special, look at the previous relevant
19215 ;; line to compute indentation
19217 (beginning-of-line 0)
19218 (while (and (not (bobp))
19219 (not (looking-at org-drawer-regexp))
19220 ;; When point started in an inline task, do not move
19221 ;; above task starting line.
19222 (not (and inline-task-p (looking-at inline-re)))
19223 ;; Skip drawers, blocks, empty lines, verbatim,
19224 ;; comments, tables, footnotes definitions, lists,
19225 ;; inline tasks.
19226 (or (and (looking-at "[ \t]*:END:")
19227 (re-search-backward org-drawer-regexp nil t))
19228 (and (looking-at "[ \t]*#\\+end_")
19229 (re-search-backward "[ \t]*#\\+begin_"nil t))
19230 (looking-at "[ \t]*[\n:#|]")
19231 (looking-at org-footnote-definition-re)
19232 (and (ignore-errors (goto-char (org-in-item-p)))
19233 (goto-char
19234 (org-list-get-top-point (org-list-struct))))
19235 (and (not inline-task-p)
19236 (featurep 'org-inlinetask)
19237 (org-inlinetask-in-task-p)
19238 (or (org-inlinetask-goto-beginning) t))))
19239 (beginning-of-line 0))
19240 (cond
19241 ;; There was an heading above.
19242 ((looking-at "\\*+[ \t]+")
19243 (if (not org-adapt-indentation)
19244 (setq column 0)
19245 (goto-char (match-end 0))
19246 (setq column (current-column))))
19247 ;; A drawer had started and is unfinished
19248 ((looking-at org-drawer-regexp)
19249 (goto-char (1- (match-beginning 1)))
19250 (setq column (current-column)))
19251 ;; Else, nothing noticeable found: get indentation and go on.
19252 (t (setq column (org-get-indentation))))))
19253 ;; Now apply indentation and move cursor accordingly
19254 (goto-char pos)
19255 (if (<= (current-column) (current-indentation))
19256 (org-indent-line-to column)
19257 (save-excursion (org-indent-line-to column)))
19258 ;; Special polishing for properties, see `org-property-format'
19259 (setq column (current-column))
19260 (beginning-of-line 1)
19261 (if (looking-at
19262 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
19263 (replace-match (concat (match-string 1)
19264 (format org-property-format
19265 (match-string 2) (match-string 3)))
19266 t t))
19267 (org-move-to-column column)))
19269 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
19270 "Variable to store copy of `adaptive-fill-regexp'.
19271 Since `adaptive-fill-regexp' is set to never match, we need to
19272 store a backup of its value before entering `org-mode' so that
19273 the functionality can be provided as a fall-back.")
19275 (defun org-set-autofill-regexps ()
19276 (interactive)
19277 ;; In the paragraph separator we include headlines, because filling
19278 ;; text in a line directly attached to a headline would otherwise
19279 ;; fill the headline as well.
19280 (org-set-local 'comment-start-skip "^#+[ \t]*")
19281 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
19282 ;; The paragraph starter includes hand-formatted lists.
19283 (org-set-local
19284 'paragraph-start
19285 (concat
19286 "\f" "\\|"
19287 "[ ]*$" "\\|"
19288 "\\*+ " "\\|"
19289 "[ \t]*#" "\\|"
19290 (org-item-re) "\\|"
19291 "[ \t]*[:|]" "\\|"
19292 "\\$\\$" "\\|"
19293 "\\\\\\(begin\\|end\\|[][]\\)"))
19294 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
19295 ;; But only if the user has not turned off tables or fixed-width regions
19296 (org-set-local
19297 'auto-fill-inhibit-regexp
19298 (concat "\\*+ \\|#\\+"
19299 "\\|[ \t]*" org-keyword-time-regexp
19300 (if (or org-enable-table-editor org-enable-fixed-width-editor)
19301 (concat
19302 "\\|[ \t]*["
19303 (if org-enable-table-editor "|" "")
19304 (if org-enable-fixed-width-editor ":" "")
19305 "]"))))
19306 ;; We use our own fill-paragraph function, to make sure that tables
19307 ;; and fixed-width regions are not wrapped. That function will pass
19308 ;; through to `fill-paragraph' when appropriate.
19309 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
19310 ;; Prevent auto-fill from inserting unwanted new items.
19311 (org-set-local 'fill-nobreak-predicate
19312 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
19313 fill-nobreak-predicate
19314 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate)))
19315 ;; Adaptive filling: To get full control, first make sure that
19316 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
19317 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
19318 (org-set-local 'org-adaptive-fill-regexp-backup
19319 adaptive-fill-regexp))
19320 (org-set-local 'adaptive-fill-regexp "\000")
19321 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
19322 (org-set-local 'adaptive-fill-function
19323 'org-adaptive-fill-function)
19324 (org-set-local
19325 'align-mode-rules-list
19326 '((org-in-buffer-settings
19327 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
19328 (modes . '(org-mode))))))
19330 (defun org-fill-item-nobreak-p ()
19331 "Non-nil when a line break at point would insert a new item."
19332 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
19334 (defun org-fill-paragraph (&optional justify)
19335 "Re-align a table, pass through to fill-paragraph if no table."
19336 (let ((table-p (org-at-table-p))
19337 (table.el-p (org-at-table.el-p))
19338 (itemp (org-in-item-p)))
19339 (cond ((and (equal (char-after (point-at-bol)) ?*)
19340 (save-excursion (goto-char (point-at-bol))
19341 (looking-at outline-regexp)))
19342 t) ; skip headlines
19343 (table.el-p t) ; skip table.el tables
19344 (table-p (org-table-align) t) ; align Org tables
19345 (itemp ; align text in items
19346 (let* ((struct (save-excursion (goto-char itemp)
19347 (org-list-struct)))
19348 (parents (org-list-parents-alist struct))
19349 (children (org-list-get-children itemp struct parents))
19350 beg end prev next prefix)
19351 ;; Determine in which part of item point is: before
19352 ;; first child, after last child, between two
19353 ;; sub-lists, or simply in item if there's no child.
19354 (cond
19355 ((not children)
19356 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19357 beg itemp
19358 end (org-list-get-item-end itemp struct)))
19359 ((< (point) (setq next (car children)))
19360 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19361 beg itemp
19362 end next))
19363 ((> (point) (setq prev (car (last children))))
19364 (setq beg (org-list-get-item-end prev struct)
19365 end (org-list-get-item-end itemp struct)
19366 prefix (save-excursion
19367 (goto-char beg)
19368 (skip-chars-forward " \t")
19369 (make-string (current-column) ?\ ))))
19370 (t (catch 'exit
19371 (while (setq next (pop children))
19372 (if (> (point) next)
19373 (setq prev next)
19374 (setq beg (org-list-get-item-end prev struct)
19375 end next
19376 prefix (save-excursion
19377 (goto-char beg)
19378 (skip-chars-forward " \t")
19379 (make-string (current-column) ?\ )))
19380 (throw 'exit nil))))))
19381 ;; Use `fill-paragraph' with buffer narrowed to item
19382 ;; without any child, and with our computed PREFIX.
19383 (flet ((fill-context-prefix (from to &optional flr) prefix))
19384 (save-restriction
19385 (narrow-to-region beg end)
19386 (save-excursion (fill-paragraph justify)))) t))
19387 ;; Special case where point is not in a list but is on
19388 ;; a paragraph adjacent to a list: make sure this paragraph
19389 ;; doesn't get merged with the end of the list by narrowing
19390 ;; buffer first.
19391 ((save-excursion (forward-paragraph -1)
19392 (setq itemp (org-in-item-p)))
19393 (let ((struct (save-excursion (goto-char itemp)
19394 (org-list-struct))))
19395 (save-restriction
19396 (narrow-to-region (org-list-get-bottom-point struct)
19397 (save-excursion (forward-paragraph 1)
19398 (point)))
19399 (fill-paragraph justify) t)))
19400 ;; Else simply call `fill-paragraph'.
19401 (t nil))))
19403 ;; For reference, this is the default value of adaptive-fill-regexp
19404 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
19406 (defun org-adaptive-fill-function ()
19407 "Return a fill prefix for org-mode files."
19408 (let (itemp)
19409 (save-excursion
19410 (cond
19411 ;; Comment line
19412 ((looking-at "#[ \t]+")
19413 (match-string-no-properties 0))
19414 ;; Plain list item
19415 ((org-at-item-p)
19416 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
19417 ;; Point is in a list after `backward-paragraph': original
19418 ;; point wasn't in the list, or filling would have been taken
19419 ;; care of by `org-auto-fill-function', but the list and the
19420 ;; real paragraph are not separated by a blank line. Thus, move
19421 ;; point after the list to go back to real paragraph and
19422 ;; determine fill-prefix.
19423 ((setq itemp (org-in-item-p))
19424 (goto-char itemp)
19425 (let* ((struct (org-list-struct))
19426 (bottom (org-list-get-bottom-point struct)))
19427 (goto-char bottom)
19428 (make-string (org-get-indentation) ?\ )))
19429 ;; Other text
19430 ((looking-at org-adaptive-fill-regexp-backup)
19431 (match-string-no-properties 0))))))
19433 (defun org-auto-fill-function ()
19434 "Auto-fill function."
19435 (let (itemp prefix)
19436 ;; When in a list, compute an appropriate fill-prefix and make
19437 ;; sure it will be used by `do-auto-fill'.
19438 (if (setq itemp (org-in-item-p))
19439 (progn
19440 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
19441 (flet ((fill-context-prefix (from to &optional flr) prefix))
19442 (do-auto-fill)))
19443 ;; Else just use `do-auto-fill'.
19444 (do-auto-fill))))
19446 ;;; Other stuff.
19448 (defun org-toggle-fixed-width-section (arg)
19449 "Toggle the fixed-width export.
19450 If there is no active region, the QUOTE keyword at the current headline is
19451 inserted or removed. When present, it causes the text between this headline
19452 and the next to be exported as fixed-width text, and unmodified.
19453 If there is an active region, this command adds or removes a colon as the
19454 first character of this line. If the first character of a line is a colon,
19455 this line is also exported in fixed-width font."
19456 (interactive "P")
19457 (let* ((cc 0)
19458 (regionp (org-region-active-p))
19459 (beg (if regionp (region-beginning) (point)))
19460 (end (if regionp (region-end)))
19461 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
19462 (case-fold-search nil)
19463 (re "[ \t]*\\(: \\)")
19464 off)
19465 (if regionp
19466 (save-excursion
19467 (goto-char beg)
19468 (setq cc (current-column))
19469 (beginning-of-line 1)
19470 (setq off (looking-at re))
19471 (while (> nlines 0)
19472 (setq nlines (1- nlines))
19473 (beginning-of-line 1)
19474 (cond
19475 (arg
19476 (org-move-to-column cc t)
19477 (insert ": \n")
19478 (forward-line -1))
19479 ((and off (looking-at re))
19480 (replace-match "" t t nil 1))
19481 ((not off) (org-move-to-column cc t) (insert ": ")))
19482 (forward-line 1)))
19483 (save-excursion
19484 (org-back-to-heading)
19485 (if (looking-at (concat outline-regexp
19486 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
19487 (replace-match "" t t nil 1)
19488 (if (looking-at outline-regexp)
19489 (progn
19490 (goto-char (match-end 0))
19491 (insert org-quote-string " "))))))))
19493 (defun org-reftex-citation ()
19494 "Use reftex-citation to insert a citation into the buffer.
19495 This looks for a line like
19497 #+BIBLIOGRAPHY: foo plain option:-d
19499 and derives from it that foo.bib is the bibliography file relevant
19500 for this document. It then installs the necessary environment for RefTeX
19501 to work in this buffer and calls `reftex-citation' to insert a citation
19502 into the buffer.
19504 Export of such citations to both LaTeX and HTML is handled by the contributed
19505 package org-exp-bibtex by Taru Karttunen."
19506 (interactive)
19507 (let ((reftex-docstruct-symbol 'rds)
19508 (reftex-cite-format "\\cite{%l}")
19509 rds bib)
19510 (save-excursion
19511 (save-restriction
19512 (widen)
19513 (let ((case-fold-search t)
19514 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
19515 (if (not (save-excursion
19516 (or (re-search-forward re nil t)
19517 (re-search-backward re nil t))))
19518 (error "No bibliography defined in file")
19519 (setq bib (concat (match-string 1) ".bib")
19520 rds (list (list 'bib bib)))))))
19521 (call-interactively 'reftex-citation)))
19523 ;;;; Functions extending outline functionality
19525 (defun org-beginning-of-line (&optional arg)
19526 "Go to the beginning of the current line. If that is invisible, continue
19527 to a visible line beginning. This makes the function of C-a more intuitive.
19528 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19529 first attempt, and only move to after the tags when the cursor is already
19530 beyond the end of the headline."
19531 (interactive "P")
19532 (let ((pos (point))
19533 (special (if (consp org-special-ctrl-a/e)
19534 (car org-special-ctrl-a/e)
19535 org-special-ctrl-a/e))
19536 refpos)
19537 (if (org-bound-and-true-p line-move-visual)
19538 (beginning-of-visual-line 1)
19539 (beginning-of-line 1))
19540 (if (and arg (fboundp 'move-beginning-of-line))
19541 (call-interactively 'move-beginning-of-line)
19542 (if (bobp)
19544 (backward-char 1)
19545 (if (org-truely-invisible-p)
19546 (while (and (not (bobp)) (org-truely-invisible-p))
19547 (backward-char 1)
19548 (beginning-of-line 1))
19549 (forward-char 1))))
19550 (when special
19551 (cond
19552 ((and (looking-at org-complex-heading-regexp)
19553 (= (char-after (match-end 1)) ?\ ))
19554 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
19555 (point-at-eol)))
19556 (goto-char
19557 (if (eq special t)
19558 (cond ((> pos refpos) refpos)
19559 ((= pos (point)) refpos)
19560 (t (point)))
19561 (cond ((> pos (point)) (point))
19562 ((not (eq last-command this-command)) (point))
19563 (t refpos)))))
19564 ((org-at-item-p)
19565 (goto-char
19566 (if (eq special t)
19567 (cond ((> pos (match-end 0)) (match-end 0))
19568 ((= pos (point)) (match-end 0))
19569 (t (point)))
19570 (cond ((> pos (point)) (point))
19571 ((not (eq last-command this-command)) (point))
19572 (t (match-end 0))))))))
19573 (org-no-warnings
19574 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19576 (defun org-end-of-line (&optional arg)
19577 "Go to the end of the line.
19578 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19579 first attempt, and only move to after the tags when the cursor is already
19580 beyond the end of the headline."
19581 (interactive "P")
19582 (let ((special (if (consp org-special-ctrl-a/e)
19583 (cdr org-special-ctrl-a/e)
19584 org-special-ctrl-a/e)))
19585 (if (or (not special)
19586 (not (org-on-heading-p))
19587 arg)
19588 (call-interactively
19589 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
19590 ((fboundp 'move-end-of-line) 'move-end-of-line)
19591 (t 'end-of-line)))
19592 (let ((pos (point)))
19593 (beginning-of-line 1)
19594 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
19595 (if (eq special t)
19596 (if (or (< pos (match-beginning 1))
19597 (= pos (match-end 0)))
19598 (goto-char (match-beginning 1))
19599 (goto-char (match-end 0)))
19600 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
19601 (goto-char (match-end 0))
19602 (goto-char (match-beginning 1))))
19603 (call-interactively (if (fboundp 'move-end-of-line)
19604 'move-end-of-line
19605 'end-of-line)))))
19606 (org-no-warnings
19607 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19609 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
19610 (define-key org-mode-map "\C-e" 'org-end-of-line)
19612 (defun org-backward-sentence (&optional arg)
19613 "Go to beginning of sentence, or beginning of table field.
19614 This will call `backward-sentence' or `org-table-beginning-of-field',
19615 depending on context."
19616 (interactive "P")
19617 (cond
19618 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
19619 (t (call-interactively 'backward-sentence))))
19621 (defun org-forward-sentence (&optional arg)
19622 "Go to end of sentence, or end of table field.
19623 This will call `forward-sentence' or `org-table-end-of-field',
19624 depending on context."
19625 (interactive "P")
19626 (cond
19627 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
19628 (t (call-interactively 'forward-sentence))))
19630 (define-key org-mode-map "\M-a" 'org-backward-sentence)
19631 (define-key org-mode-map "\M-e" 'org-forward-sentence)
19633 (defun org-kill-line (&optional arg)
19634 "Kill line, to tags or end of line."
19635 (interactive "P")
19636 (cond
19637 ((or (not org-special-ctrl-k)
19638 (bolp)
19639 (not (org-on-heading-p)))
19640 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
19641 org-ctrl-k-protect-subtree)
19642 (if (or (eq org-ctrl-k-protect-subtree 'error)
19643 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
19644 (error "C-k aborted - would kill hidden subtree")))
19645 (call-interactively 'kill-line))
19646 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
19647 (kill-region (point) (match-beginning 1))
19648 (org-set-tags nil t))
19649 (t (kill-region (point) (point-at-eol)))))
19651 (define-key org-mode-map "\C-k" 'org-kill-line)
19653 (defun org-yank (&optional arg)
19654 "Yank. If the kill is a subtree, treat it specially.
19655 This command will look at the current kill and check if is a single
19656 subtree, or a series of subtrees[1]. If it passes the test, and if the
19657 cursor is at the beginning of a line or after the stars of a currently
19658 empty headline, then the yank is handled specially. How exactly depends
19659 on the value of the following variables, both set by default.
19661 org-yank-folded-subtrees
19662 When set, the subtree(s) will be folded after insertion, but only
19663 if doing so would now swallow text after the yanked text.
19665 org-yank-adjusted-subtrees
19666 When set, the subtree will be promoted or demoted in order to
19667 fit into the local outline tree structure, which means that the level
19668 will be adjusted so that it becomes the smaller one of the two
19669 *visible* surrounding headings.
19671 Any prefix to this command will cause `yank' to be called directly with
19672 no special treatment. In particular, a simple \\[universal-argument] prefix \
19673 will just
19674 plainly yank the text as it is.
19676 \[1] The test checks if the first non-white line is a heading
19677 and if there are no other headings with fewer stars."
19678 (interactive "P")
19679 (org-yank-generic 'yank arg))
19681 (defun org-yank-generic (command arg)
19682 "Perform some yank-like command.
19684 This function implements the behavior described in the `org-yank'
19685 documentation. However, it has been generalized to work for any
19686 interactive command with similar behavior."
19688 ;; pretend to be command COMMAND
19689 (setq this-command command)
19691 (if arg
19692 (call-interactively command)
19694 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
19695 (and (org-kill-is-subtree-p)
19696 (or (bolp)
19697 (and (looking-at "[ \t]*$")
19698 (string-match
19699 "\\`\\*+\\'"
19700 (buffer-substring (point-at-bol) (point)))))))
19701 swallowp)
19702 (cond
19703 ((and subtreep org-yank-folded-subtrees)
19704 (let ((beg (point))
19705 end)
19706 (if (and subtreep org-yank-adjusted-subtrees)
19707 (org-paste-subtree nil nil 'for-yank)
19708 (call-interactively command))
19710 (setq end (point))
19711 (goto-char beg)
19712 (when (and (bolp) subtreep
19713 (not (setq swallowp
19714 (org-yank-folding-would-swallow-text beg end))))
19715 (or (looking-at outline-regexp)
19716 (re-search-forward (concat "^" outline-regexp) end t))
19717 (while (and (< (point) end) (looking-at outline-regexp))
19718 (hide-subtree)
19719 (org-cycle-show-empty-lines 'folded)
19720 (condition-case nil
19721 (outline-forward-same-level 1)
19722 (error (goto-char end)))))
19723 (when swallowp
19724 (message
19725 "Inserted text not folded because that would swallow text"))
19727 (goto-char end)
19728 (skip-chars-forward " \t\n\r")
19729 (beginning-of-line 1)
19730 (push-mark beg 'nomsg)))
19731 ((and subtreep org-yank-adjusted-subtrees)
19732 (let ((beg (point-at-bol)))
19733 (org-paste-subtree nil nil 'for-yank)
19734 (push-mark beg 'nomsg)))
19736 (call-interactively command))))))
19738 (defun org-yank-folding-would-swallow-text (beg end)
19739 "Would hide-subtree at BEG swallow any text after END?"
19740 (let (level)
19741 (save-excursion
19742 (goto-char beg)
19743 (when (or (looking-at outline-regexp)
19744 (re-search-forward (concat "^" outline-regexp) end t))
19745 (setq level (org-outline-level)))
19746 (goto-char end)
19747 (skip-chars-forward " \t\r\n\v\f")
19748 (if (or (eobp)
19749 (and (bolp) (looking-at org-outline-regexp)
19750 (<= (org-outline-level) level)))
19751 nil ; Nothing would be swallowed
19752 t)))) ; something would swallow
19754 (define-key org-mode-map "\C-y" 'org-yank)
19756 (defun org-truely-invisible-p ()
19757 "Check if point is at a character currently not visible.
19758 This version does not only check the character property, but also
19759 `visible-mode'."
19760 ;; Early versions of noutline don't have `outline-invisible-p'.
19761 (if (org-bound-and-true-p visible-mode)
19763 (outline-invisible-p)))
19765 (defun org-invisible-p2 ()
19766 "Check if point is at a character currently not visible."
19767 (save-excursion
19768 (if (and (eolp) (not (bobp))) (backward-char 1))
19769 ;; Early versions of noutline don't have `outline-invisible-p'.
19770 (outline-invisible-p)))
19772 (defun org-back-to-heading (&optional invisible-ok)
19773 "Call `outline-back-to-heading', but provide a better error message."
19774 (condition-case nil
19775 (outline-back-to-heading invisible-ok)
19776 (error (error "Before first headline at position %d in buffer %s"
19777 (point) (current-buffer)))))
19779 (defun org-beginning-of-defun ()
19780 "Go to the beginning of the subtree, i.e. back to the heading."
19781 (org-back-to-heading))
19782 (defun org-end-of-defun ()
19783 "Go to the end of the subtree."
19784 (org-end-of-subtree nil t))
19786 (defun org-before-first-heading-p ()
19787 "Before first heading?"
19788 (save-excursion
19789 (end-of-line)
19790 (null (re-search-backward "^\\*+ " nil t))))
19792 (defun org-on-heading-p (&optional ignored)
19793 (outline-on-heading-p t))
19794 (defun org-at-heading-p (&optional ignored)
19795 (outline-on-heading-p t))
19797 (defun org-point-at-end-of-empty-headline ()
19798 "If point is at the end of an empty headline, return t, else nil.
19799 If the heading only contains a TODO keyword, it is still still considered
19800 empty."
19801 (and (looking-at "[ \t]*$")
19802 (save-excursion
19803 (beginning-of-line 1)
19804 (let ((case-fold-search nil))
19805 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
19806 "\\)?[ \t]*$"))))))
19807 (defun org-at-heading-or-item-p ()
19808 (or (org-on-heading-p) (org-at-item-p)))
19810 (defun org-on-target-p ()
19811 (or (org-in-regexp org-radio-target-regexp)
19812 (org-in-regexp org-target-regexp)))
19814 (defun org-up-heading-all (arg)
19815 "Move to the heading line of which the present line is a subheading.
19816 This function considers both visible and invisible heading lines.
19817 With argument, move up ARG levels."
19818 (if (fboundp 'outline-up-heading-all)
19819 (outline-up-heading-all arg) ; emacs 21 version of outline.el
19820 (outline-up-heading arg t))) ; emacs 22 version of outline.el
19822 (defun org-up-heading-safe ()
19823 "Move to the heading line of which the present line is a subheading.
19824 This version will not throw an error. It will return the level of the
19825 headline found, or nil if no higher level is found.
19827 Also, this function will be a lot faster than `outline-up-heading',
19828 because it relies on stars being the outline starters. This can really
19829 make a significant difference in outlines with very many siblings."
19830 (let (start-level re)
19831 (org-back-to-heading t)
19832 (setq start-level (funcall outline-level))
19833 (if (equal start-level 1)
19835 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
19836 (if (re-search-backward re nil t)
19837 (funcall outline-level)))))
19839 (defun org-first-sibling-p ()
19840 "Is this heading the first child of its parents?"
19841 (interactive)
19842 (let ((re (concat "^" outline-regexp))
19843 level l)
19844 (unless (org-at-heading-p t)
19845 (error "Not at a heading"))
19846 (setq level (funcall outline-level))
19847 (save-excursion
19848 (if (not (re-search-backward re nil t))
19850 (setq l (funcall outline-level))
19851 (< l level)))))
19853 (defun org-goto-sibling (&optional previous)
19854 "Goto the next sibling, even if it is invisible.
19855 When PREVIOUS is set, go to the previous sibling instead. Returns t
19856 when a sibling was found. When none is found, return nil and don't
19857 move point."
19858 (let ((fun (if previous 're-search-backward 're-search-forward))
19859 (pos (point))
19860 (re (concat "^" outline-regexp))
19861 level l)
19862 (when (condition-case nil (org-back-to-heading t) (error nil))
19863 (setq level (funcall outline-level))
19864 (catch 'exit
19865 (or previous (forward-char 1))
19866 (while (funcall fun re nil t)
19867 (setq l (funcall outline-level))
19868 (when (< l level) (goto-char pos) (throw 'exit nil))
19869 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
19870 (goto-char pos)
19871 nil))))
19873 (defun org-show-siblings ()
19874 "Show all siblings of the current headline."
19875 (save-excursion
19876 (while (org-goto-sibling) (org-flag-heading nil)))
19877 (save-excursion
19878 (while (org-goto-sibling 'previous)
19879 (org-flag-heading nil))))
19881 (defun org-goto-first-child ()
19882 "Goto the first child, even if it is invisible.
19883 Return t when a child was found. Otherwise don't move point and
19884 return nil."
19885 (let (level (pos (point)) (re (concat "^" outline-regexp)))
19886 (when (condition-case nil (org-back-to-heading t) (error nil))
19887 (setq level (outline-level))
19888 (forward-char 1)
19889 (if (and (re-search-forward re nil t) (> (outline-level) level))
19890 (progn (goto-char (match-beginning 0)) t)
19891 (goto-char pos) nil))))
19893 (defun org-show-hidden-entry ()
19894 "Show an entry where even the heading is hidden."
19895 (save-excursion
19896 (org-show-entry)))
19898 (defun org-flag-heading (flag &optional entry)
19899 "Flag the current heading. FLAG non-nil means make invisible.
19900 When ENTRY is non-nil, show the entire entry."
19901 (save-excursion
19902 (org-back-to-heading t)
19903 ;; Check if we should show the entire entry
19904 (if entry
19905 (progn
19906 (org-show-entry)
19907 (save-excursion
19908 (and (outline-next-heading)
19909 (org-flag-heading nil))))
19910 (outline-flag-region (max (point-min) (1- (point)))
19911 (save-excursion (outline-end-of-heading) (point))
19912 flag))))
19914 (defun org-get-next-sibling ()
19915 "Move to next heading of the same level, and return point.
19916 If there is no such heading, return nil.
19917 This is like outline-next-sibling, but invisible headings are ok."
19918 (let ((level (funcall outline-level)))
19919 (outline-next-heading)
19920 (while (and (not (eobp)) (> (funcall outline-level) level))
19921 (outline-next-heading))
19922 (if (or (eobp) (< (funcall outline-level) level))
19924 (point))))
19926 (defun org-get-last-sibling ()
19927 "Move to previous heading of the same level, and return point.
19928 If there is no such heading, return nil."
19929 (let ((opoint (point))
19930 (level (funcall outline-level)))
19931 (outline-previous-heading)
19932 (when (and (/= (point) opoint) (outline-on-heading-p t))
19933 (while (and (> (funcall outline-level) level)
19934 (not (bobp)))
19935 (outline-previous-heading))
19936 (if (< (funcall outline-level) level)
19938 (point)))))
19940 (defun org-end-of-subtree (&optional invisible-OK to-heading)
19941 ;; This contains an exact copy of the original function, but it uses
19942 ;; `org-back-to-heading', to make it work also in invisible
19943 ;; trees. And is uses an invisible-OK argument.
19944 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
19945 ;; Furthermore, when used inside Org, finding the end of a large subtree
19946 ;; with many children and grandchildren etc, this can be much faster
19947 ;; than the outline version.
19948 (org-back-to-heading invisible-OK)
19949 (let ((first t)
19950 (level (funcall outline-level)))
19951 (if (and (org-mode-p) (< level 1000))
19952 ;; A true heading (not a plain list item), in Org-mode
19953 ;; This means we can easily find the end by looking
19954 ;; only for the right number of stars. Using a regexp to do
19955 ;; this is so much faster than using a Lisp loop.
19956 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
19957 (forward-char 1)
19958 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
19959 ;; something else, do it the slow way
19960 (while (and (not (eobp))
19961 (or first (> (funcall outline-level) level)))
19962 (setq first nil)
19963 (outline-next-heading)))
19964 (unless to-heading
19965 (if (memq (preceding-char) '(?\n ?\^M))
19966 (progn
19967 ;; Go to end of line before heading
19968 (forward-char -1)
19969 (if (memq (preceding-char) '(?\n ?\^M))
19970 ;; leave blank line before heading
19971 (forward-char -1))))))
19972 (point))
19974 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
19975 "Use Org version in org-mode, for dramatic speed-up."
19976 (if (org-mode-p)
19977 (progn
19978 (org-end-of-subtree nil t)
19979 (unless (eobp) (backward-char 1)))
19980 ad-do-it))
19982 (defun org-end-of-meta-data-and-drawers ()
19983 "Jump to the first text after meta data and drawers in the current entry.
19984 This will move over empty lines, lines with planning time stamps,
19985 clocking lines, and drawers."
19986 (org-back-to-heading t)
19987 (let ((end (save-excursion (outline-next-heading) (point)))
19988 (re (concat "[ \t]*$"
19989 "\\|"
19990 "\\(" org-drawer-regexp "\\)" ; group 1 are drawers
19991 "\\|"
19992 "\\([ \t]*\\(" org-keyword-time-regexp "\\)\\)")))
19993 (forward-line 1)
19994 (while (looking-at (concat "[ \t]*\\(" org-keyword-time-regexp "\\)"))
19995 (if (not (match-end 1))
19996 ;; empty or planning line
19997 (forward-line 1)
19998 ;; a drawer, find the end
19999 (re-search-forward "^[ \t]*:END:" end 'move)
20000 (forward-line 1)))
20001 (point)))
20003 (defun org-forward-same-level (arg &optional invisible-ok)
20004 "Move forward to the arg'th subheading at same level as this one.
20005 Stop at the first and last subheadings of a superior heading.
20006 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20007 it wil also look at invisible ones."
20008 (interactive "p")
20009 (org-back-to-heading invisible-ok)
20010 (org-on-heading-p)
20011 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20012 (re (format "^\\*\\{1,%d\\} " level))
20014 (forward-char 1)
20015 (while (> arg 0)
20016 (while (and (re-search-forward re nil 'move)
20017 (setq l (- (match-end 0) (match-beginning 0) 1))
20018 (= l level)
20019 (not invisible-ok)
20020 (progn (backward-char 1) (outline-invisible-p)))
20021 (if (< l level) (setq arg 1)))
20022 (setq arg (1- arg)))
20023 (beginning-of-line 1)))
20025 (defun org-backward-same-level (arg &optional invisible-ok)
20026 "Move backward to the arg'th subheading at same level as this one.
20027 Stop at the first and last subheadings of a superior heading."
20028 (interactive "p")
20029 (org-back-to-heading)
20030 (org-on-heading-p)
20031 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20032 (re (format "^\\*\\{1,%d\\} " level))
20034 (while (> arg 0)
20035 (while (and (re-search-backward re nil 'move)
20036 (setq l (- (match-end 0) (match-beginning 0) 1))
20037 (= l level)
20038 (not invisible-ok)
20039 (outline-invisible-p))
20040 (if (< l level) (setq arg 1)))
20041 (setq arg (1- arg)))))
20043 (defun org-show-subtree ()
20044 "Show everything after this heading at deeper levels."
20045 (outline-flag-region
20046 (point)
20047 (save-excursion
20048 (org-end-of-subtree t t))
20049 nil))
20051 (defun org-show-entry ()
20052 "Show the body directly following this heading.
20053 Show the heading too, if it is currently invisible."
20054 (interactive)
20055 (save-excursion
20056 (condition-case nil
20057 (progn
20058 (org-back-to-heading t)
20059 (outline-flag-region
20060 (max (point-min) (1- (point)))
20061 (save-excursion
20062 (if (re-search-forward
20063 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
20064 (match-beginning 1)
20065 (point-max)))
20066 nil)
20067 (org-cycle-hide-drawers 'children))
20068 (error nil))))
20070 (defun org-make-options-regexp (kwds &optional extra)
20071 "Make a regular expression for keyword lines."
20072 (concat
20074 "#?[ \t]*\\+\\("
20075 (mapconcat 'regexp-quote kwds "\\|")
20076 (if extra (concat "\\|" extra))
20077 "\\):[ \t]*"
20078 "\\(.*\\)"))
20080 ;; Make isearch reveal the necessary context
20081 (defun org-isearch-end ()
20082 "Reveal context after isearch exits."
20083 (when isearch-success ; only if search was successful
20084 (if (featurep 'xemacs)
20085 ;; Under XEmacs, the hook is run in the correct place,
20086 ;; we directly show the context.
20087 (org-show-context 'isearch)
20088 ;; In Emacs the hook runs *before* restoring the overlays.
20089 ;; So we have to use a one-time post-command-hook to do this.
20090 ;; (Emacs 22 has a special variable, see function `org-mode')
20091 (unless (and (boundp 'isearch-mode-end-hook-quit)
20092 isearch-mode-end-hook-quit)
20093 ;; Only when the isearch was not quitted.
20094 (org-add-hook 'post-command-hook 'org-isearch-post-command
20095 'append 'local)))))
20097 (defun org-isearch-post-command ()
20098 "Remove self from hook, and show context."
20099 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20100 (org-show-context 'isearch))
20103 ;;;; Integration with and fixes for other packages
20105 ;;; Imenu support
20107 (defvar org-imenu-markers nil
20108 "All markers currently used by Imenu.")
20109 (make-variable-buffer-local 'org-imenu-markers)
20111 (defun org-imenu-new-marker (&optional pos)
20112 "Return a new marker for use by Imenu, and remember the marker."
20113 (let ((m (make-marker)))
20114 (move-marker m (or pos (point)))
20115 (push m org-imenu-markers)
20118 (defun org-imenu-get-tree ()
20119 "Produce the index for Imenu."
20120 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20121 (setq org-imenu-markers nil)
20122 (let* ((n org-imenu-depth)
20123 (re (concat "^" outline-regexp))
20124 (subs (make-vector (1+ n) nil))
20125 (last-level 0)
20126 m level head)
20127 (save-excursion
20128 (save-restriction
20129 (widen)
20130 (goto-char (point-max))
20131 (while (re-search-backward re nil t)
20132 (setq level (org-reduced-level (funcall outline-level)))
20133 (when (<= level n)
20134 (looking-at org-complex-heading-regexp)
20135 (setq head (org-link-display-format
20136 (org-match-string-no-properties 4))
20137 m (org-imenu-new-marker))
20138 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20139 (if (>= level last-level)
20140 (push (cons head m) (aref subs level))
20141 (push (cons head (aref subs (1+ level))) (aref subs level))
20142 (loop for i from (1+ level) to n do (aset subs i nil)))
20143 (setq last-level level)))))
20144 (aref subs 1)))
20146 (eval-after-load "imenu"
20147 '(progn
20148 (add-hook 'imenu-after-jump-hook
20149 (lambda ()
20150 (if (org-mode-p)
20151 (org-show-context 'org-goto))))))
20153 (defun org-link-display-format (link)
20154 "Replace a link with either the description, or the link target
20155 if no description is present"
20156 (save-match-data
20157 (if (string-match org-bracket-link-analytic-regexp link)
20158 (replace-match (if (match-end 5)
20159 (match-string 5 link)
20160 (concat (match-string 1 link)
20161 (match-string 3 link)))
20162 nil t link)
20163 link)))
20165 ;; Speedbar support
20167 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20168 "Overlay marking the agenda restriction line in speedbar.")
20169 (overlay-put org-speedbar-restriction-lock-overlay
20170 'face 'org-agenda-restriction-lock)
20171 (overlay-put org-speedbar-restriction-lock-overlay
20172 'help-echo "Agendas are currently limited to this item.")
20173 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20175 (defun org-speedbar-set-agenda-restriction ()
20176 "Restrict future agenda commands to the location at point in speedbar.
20177 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20178 (interactive)
20179 (require 'org-agenda)
20180 (let (p m tp np dir txt)
20181 (cond
20182 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20183 'org-imenu t))
20184 (setq m (get-text-property p 'org-imenu-marker))
20185 (with-current-buffer (marker-buffer m)
20186 (goto-char m)
20187 (org-agenda-set-restriction-lock 'subtree)))
20188 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20189 'speedbar-function 'speedbar-find-file))
20190 (setq tp (previous-single-property-change
20191 (1+ p) 'speedbar-function)
20192 np (next-single-property-change
20193 tp 'speedbar-function)
20194 dir (speedbar-line-directory)
20195 txt (buffer-substring-no-properties (or tp (point-min))
20196 (or np (point-max))))
20197 (with-current-buffer (find-file-noselect
20198 (let ((default-directory dir))
20199 (expand-file-name txt)))
20200 (unless (org-mode-p)
20201 (error "Cannot restrict to non-Org-mode file"))
20202 (org-agenda-set-restriction-lock 'file)))
20203 (t (error "Don't know how to restrict Org-mode's agenda")))
20204 (move-overlay org-speedbar-restriction-lock-overlay
20205 (point-at-bol) (point-at-eol))
20206 (setq current-prefix-arg nil)
20207 (org-agenda-maybe-redo)))
20209 (eval-after-load "speedbar"
20210 '(progn
20211 (speedbar-add-supported-extension ".org")
20212 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
20213 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
20214 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
20215 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20216 (add-hook 'speedbar-visiting-tag-hook
20217 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
20219 ;;; Fixes and Hacks for problems with other packages
20221 ;; Make flyspell not check words in links, to not mess up our keymap
20222 (defun org-mode-flyspell-verify ()
20223 "Don't let flyspell put overlays at active buttons, or on
20224 {todo,all-time,additional-option-like}-keywords."
20225 (let ((pos (max (1- (point)) (point-min)))
20226 (word (thing-at-point 'word)))
20227 (and (not (get-text-property pos 'keymap))
20228 (not (get-text-property pos 'org-no-flyspell))
20229 (not (member word org-todo-keywords-1))
20230 (not (member word org-all-time-keywords))
20231 (not (member word org-additional-option-like-keywords)))))
20233 (defun org-remove-flyspell-overlays-in (beg end)
20234 "Remove flyspell overlays in region."
20235 (and (org-bound-and-true-p flyspell-mode)
20236 (fboundp 'flyspell-delete-region-overlays)
20237 (flyspell-delete-region-overlays beg end))
20238 (add-text-properties beg end '(org-no-flyspell t)))
20240 ;; Make `bookmark-jump' shows the jump location if it was hidden.
20241 (eval-after-load "bookmark"
20242 '(if (boundp 'bookmark-after-jump-hook)
20243 ;; We can use the hook
20244 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20245 ;; Hook not available, use advice
20246 (defadvice bookmark-jump (after org-make-visible activate)
20247 "Make the position visible."
20248 (org-bookmark-jump-unhide))))
20250 ;; Make sure saveplace shows the location if it was hidden
20251 (eval-after-load "saveplace"
20252 '(defadvice save-place-find-file-hook (after org-make-visible activate)
20253 "Make the position visible."
20254 (org-bookmark-jump-unhide)))
20256 ;; Make sure ecb shows the location if it was hidden
20257 (eval-after-load "ecb"
20258 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
20259 "Make hierarchy visible when jumping into location from ECB tree buffer."
20260 (if (org-mode-p)
20261 (org-show-context))))
20263 (defun org-bookmark-jump-unhide ()
20264 "Unhide the current position, to show the bookmark location."
20265 (and (org-mode-p)
20266 (or (outline-invisible-p)
20267 (save-excursion (goto-char (max (point-min) (1- (point))))
20268 (outline-invisible-p)))
20269 (org-show-context 'bookmark-jump)))
20271 ;; Make session.el ignore our circular variable
20272 (eval-after-load "session"
20273 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20275 ;;;; Experimental code
20277 (defun org-closed-in-range ()
20278 "Sparse tree of items closed in a certain time range.
20279 Still experimental, may disappear in the future."
20280 (interactive)
20281 ;; Get the time interval from the user.
20282 (let* ((time1 (org-float-time
20283 (org-read-date nil 'to-time nil "Starting date: ")))
20284 (time2 (org-float-time
20285 (org-read-date nil 'to-time nil "End date:")))
20286 ;; callback function
20287 (callback (lambda ()
20288 (let ((time
20289 (org-float-time
20290 (apply 'encode-time
20291 (org-parse-time-string
20292 (match-string 1))))))
20293 ;; check if time in interval
20294 (and (>= time time1) (<= time time2))))))
20295 ;; make tree, check each match with the callback
20296 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
20298 ;;;; Finish up
20300 (provide 'org)
20302 (run-hooks 'org-load-hook)
20304 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
20306 ;;; org.el ends here