org-indent.el: tiny docstring fix.
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org.el
blob7a4a771a4f51933b3926189440f1209333850858
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 "Lilypond" lilypond)
169 (const :tag "Maxima" maxima)
170 (const :tag "Matlab" matlab)
171 (const :tag "Mscgen" mscgen)
172 (const :tag "Ocaml" ocaml)
173 (const :tag "Octave" octave)
174 (const :tag "Org" org)
175 (const :tag "Perl" perl)
176 (const :tag "PlantUML" plantuml)
177 (const :tag "Python" python)
178 (const :tag "Ruby" ruby)
179 (const :tag "Sass" sass)
180 (const :tag "Scheme" scheme)
181 (const :tag "Screen" screen)
182 (const :tag "Shell Script" sh)
183 (const :tag "Sql" sql)
184 (const :tag "Sqlite" sqlite))
185 :value-type (boolean :tag "Activate" :value t)))
187 ;;;; Customization variables
188 (defcustom org-clone-delete-id nil
189 "Remove ID property of clones of a subtree.
190 When non-nil, clones of a subtree don't inherit the ID property.
191 Otherwise they inherit the ID property with a new unique
192 identifier."
193 :type 'boolean
194 :group 'org-id)
196 ;;; Version
198 (defconst org-version "7.5"
199 "The version number of the file org.el.")
201 (defun org-version (&optional here)
202 "Show the org-mode version in the echo area.
203 With prefix arg HERE, insert it at point."
204 (interactive "P")
205 (let* ((origin default-directory)
206 (version org-version)
207 (git-version)
208 (dir (concat (file-name-directory (locate-library "org")) "../" )))
209 (when (and (file-exists-p (expand-file-name ".git" dir))
210 (executable-find "git"))
211 (unwind-protect
212 (progn
213 (cd dir)
214 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
215 (with-current-buffer "*Shell Command Output*"
216 (goto-char (point-min))
217 (setq git-version (buffer-substring (point) (point-at-eol))))
218 (subst-char-in-string ?- ?. git-version t)
219 (when (string-match "\\S-"
220 (shell-command-to-string
221 "git diff-index --name-only HEAD --"))
222 (setq git-version (concat git-version ".dirty")))
223 (setq version (concat version " (" git-version ")"))))
224 (cd origin)))
225 (setq version (format "Org-mode version %s" version))
226 (if here (insert version))
227 (message version)))
229 ;;; Compatibility constants
231 ;;; The custom variables
233 (defgroup org nil
234 "Outline-based notes management and organizer."
235 :tag "Org"
236 :group 'outlines
237 :group 'calendar)
239 (defcustom org-mode-hook nil
240 "Mode hook for Org-mode, run after the mode was turned on."
241 :group 'org
242 :type 'hook)
244 (defcustom org-load-hook nil
245 "Hook that is run after org.el has been loaded."
246 :group 'org
247 :type 'hook)
249 (defvar org-modules) ; defined below
250 (defvar org-modules-loaded nil
251 "Have the modules been loaded already?")
253 (defun org-load-modules-maybe (&optional force)
254 "Load all extensions listed in `org-modules'."
255 (when (or force (not org-modules-loaded))
256 (mapc (lambda (ext)
257 (condition-case nil (require ext)
258 (error (message "Problems while trying to load feature `%s'" ext))))
259 org-modules)
260 (setq org-modules-loaded t)))
262 (defun org-set-modules (var value)
263 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
264 (set var value)
265 (when (featurep 'org)
266 (org-load-modules-maybe 'force)))
268 (when (org-bound-and-true-p org-modules)
269 (let ((a (member 'org-infojs org-modules)))
270 (and a (setcar a 'org-jsinfo))))
272 (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)
273 "Modules that should always be loaded together with org.el.
274 If a description starts with <C>, the file is not part of Emacs
275 and loading it will require that you have downloaded and properly installed
276 the org-mode distribution.
278 You can also use this system to load external packages (i.e. neither Org
279 core modules, nor modules from the CONTRIB directory). Just add symbols
280 to the end of the list. If the package is called org-xyz.el, then you need
281 to add the symbol `xyz', and the package must have a call to
283 (provide 'org-xyz)"
284 :group 'org
285 :set 'org-set-modules
286 :type
287 '(set :greedy t
288 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
289 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
290 (const :tag " crypt: Encryption of subtrees" org-crypt)
291 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
292 (const :tag " docview: Links to doc-view buffers" org-docview)
293 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
294 (const :tag " id: Global IDs for identifying entries" org-id)
295 (const :tag " info: Links to Info nodes" org-info)
296 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
297 (const :tag " habit: Track your consistency with habits" org-habit)
298 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
299 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
300 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
301 (const :tag " mew Links to Mew folders/messages" org-mew)
302 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
303 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
304 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
305 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
306 (const :tag " vm: Links to VM folders/messages" org-vm)
307 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
308 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
309 (const :tag " mouse: Additional mouse support" org-mouse)
310 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
312 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
313 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
314 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
315 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
316 (const :tag "C collector: Collect properties into tables" org-collector)
317 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
318 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
319 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
320 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
321 (const :tag "C eval: Include command output as text" org-eval)
322 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
323 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
324 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
325 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
326 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
328 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
330 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
331 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
332 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
333 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
334 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
335 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
336 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
337 (const :tag "C mtags: Support for muse-like tags" org-mtags)
338 (const :tag "C odt: OpenDocumentText exporter for Org-mode" org-odt)
339 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
340 (const :tag "C registry: A registry for Org-mode links" org-registry)
341 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
342 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
343 (const :tag "C secretary: Team management with org-mode" org-secretary)
344 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
345 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
346 (const :tag "C track: Keep up with Org-mode development" org-track)
347 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
348 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
349 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
351 (defcustom org-support-shift-select nil
352 "Non-nil means make shift-cursor commands select text when possible.
354 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
355 selecting a region, or enlarge regions started in this way.
356 In Org-mode, in special contexts, these same keys are used for other
357 purposes, important enough to compete with shift selection. Org tries
358 to balance these needs by supporting `shift-select-mode' outside these
359 special contexts, under control of this variable.
361 The default of this variable is nil, to avoid confusing behavior. Shifted
362 cursor keys will then execute Org commands in the following contexts:
363 - on a headline, changing TODO state (left/right) and priority (up/down)
364 - on a time stamp, changing the time
365 - in a plain list item, changing the bullet type
366 - in a property definition line, switching between allowed values
367 - in the BEGIN line of a clock table (changing the time block).
368 Outside these contexts, the commands will throw an error.
370 When this variable is t and the cursor is not in a special context,
371 Org-mode will support shift-selection for making and enlarging regions.
372 To make this more effective, the bullet cycling will no longer happen
373 anywhere in an item line, but only if the cursor is exactly on the bullet.
375 If you set this variable to the symbol `always', then the keys
376 will not be special in headlines, property lines, and item lines, to make
377 shift selection work there as well. If this is what you want, you can
378 use the following alternative commands: `C-c C-t' and `C-c ,' to
379 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
380 TODO sets, `C-c -' to cycle item bullet types, and properties can be
381 edited by hand or in column view.
383 However, when the cursor is on a timestamp, shift-cursor commands
384 will still edit the time stamp - this is just too good to give up.
386 XEmacs user should have this variable set to nil, because shift-select-mode
387 is Emacs 23 only."
388 :group 'org
389 :type '(choice
390 (const :tag "Never" nil)
391 (const :tag "When outside special context" t)
392 (const :tag "Everywhere except timestamps" always)))
394 (defgroup org-startup nil
395 "Options concerning startup of Org-mode."
396 :tag "Org Startup"
397 :group 'org)
399 (defcustom org-startup-folded t
400 "Non-nil means entering Org-mode will switch to OVERVIEW.
401 This can also be configured on a per-file basis by adding one of
402 the following lines anywhere in the buffer:
404 #+STARTUP: fold (or `overview', this is equivalent)
405 #+STARTUP: nofold (or `showall', this is equivalent)
406 #+STARTUP: content
407 #+STARTUP: showeverything"
408 :group 'org-startup
409 :type '(choice
410 (const :tag "nofold: show all" nil)
411 (const :tag "fold: overview" t)
412 (const :tag "content: all headlines" content)
413 (const :tag "show everything, even drawers" showeverything)))
415 (defcustom org-startup-truncated t
416 "Non-nil means entering Org-mode will set `truncate-lines'.
417 This is useful since some lines containing links can be very long and
418 uninteresting. Also tables look terrible when wrapped."
419 :group 'org-startup
420 :type 'boolean)
422 (defcustom org-startup-indented nil
423 "Non-nil means turn on `org-indent-mode' on startup.
424 This can also be configured on a per-file basis by adding one of
425 the following lines anywhere in the buffer:
427 #+STARTUP: indent
428 #+STARTUP: noindent"
429 :group 'org-structure
430 :type '(choice
431 (const :tag "Not" nil)
432 (const :tag "Globally (slow on startup in large files)" t)))
434 (defcustom org-use-sub-superscripts t
435 "Non-nil means interpret \"_\" and \"^\" for export.
436 When this option is turned on, you can use TeX-like syntax for sub- and
437 superscripts. Several characters after \"_\" or \"^\" will be
438 considered as a single item - so grouping with {} is normally not
439 needed. For example, the following things will be parsed as single
440 sub- or superscripts.
442 10^24 or 10^tau several digits will be considered 1 item.
443 10^-12 or 10^-tau a leading sign with digits or a word
444 x^2-y^3 will be read as x^2 - y^3, because items are
445 terminated by almost any nonword/nondigit char.
446 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
448 Still, ambiguity is possible - so when in doubt use {} to enclose the
449 sub/superscript. If you set this variable to the symbol `{}',
450 the braces are *required* in order to trigger interpretations as
451 sub/superscript. This can be helpful in documents that need \"_\"
452 frequently in plain text.
454 Not all export backends support this, but HTML does.
456 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
457 :group 'org-startup
458 :group 'org-export-translation
459 :type '(choice
460 (const :tag "Always interpret" t)
461 (const :tag "Only with braces" {})
462 (const :tag "Never interpret" nil)))
464 (if (fboundp 'defvaralias)
465 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
468 (defcustom org-startup-with-beamer-mode nil
469 "Non-nil means turn on `org-beamer-mode' on startup.
470 This can also be configured on a per-file basis by adding one of
471 the following lines anywhere in the buffer:
473 #+STARTUP: beamer"
474 :group 'org-startup
475 :type 'boolean)
477 (defcustom org-startup-align-all-tables nil
478 "Non-nil means align all tables when visiting a file.
479 This is useful when the column width in tables is forced with <N> cookies
480 in table fields. Such tables will look correct only after the first re-align.
481 This can also be configured on a per-file basis by adding one of
482 the following lines anywhere in the buffer:
483 #+STARTUP: align
484 #+STARTUP: noalign"
485 :group 'org-startup
486 :type 'boolean)
488 (defcustom org-startup-with-inline-images nil
489 "Non-nil means show inline images when loading a new Org file.
490 This can also be configured on a per-file basis by adding one of
491 the following lines anywhere in the buffer:
492 #+STARTUP: inlineimages
493 #+STARTUP: noinlineimages"
494 :group 'org-startup
495 :type 'boolean)
497 (defcustom org-insert-mode-line-in-empty-file nil
498 "Non-nil means insert the first line setting Org-mode in empty files.
499 When the function `org-mode' is called interactively in an empty file, this
500 normally means that the file name does not automatically trigger Org-mode.
501 To ensure that the file will always be in Org-mode in the future, a
502 line enforcing Org-mode will be inserted into the buffer, if this option
503 has been set."
504 :group 'org-startup
505 :type 'boolean)
507 (defcustom org-replace-disputed-keys nil
508 "Non-nil means use alternative key bindings for some keys.
509 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
510 These keys are also used by other packages like shift-selection-mode'
511 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
512 If you want to use Org-mode together with one of these other modes,
513 or more generally if you would like to move some Org-mode commands to
514 other keys, set this variable and configure the keys with the variable
515 `org-disputed-keys'.
517 This option is only relevant at load-time of Org-mode, and must be set
518 *before* org.el is loaded. Changing it requires a restart of Emacs to
519 become effective."
520 :group 'org-startup
521 :type 'boolean)
523 (defcustom org-use-extra-keys nil
524 "Non-nil means use extra key sequence definitions for certain commands.
525 This happens automatically if you run XEmacs or if `window-system'
526 is nil. This variable lets you do the same manually. You must
527 set it before loading org.
529 Example: on Carbon Emacs 22 running graphically, with an external
530 keyboard on a Powerbook, the default way of setting M-left might
531 not work for either Alt or ESC. Setting this variable will make
532 it work for ESC."
533 :group 'org-startup
534 :type 'boolean)
536 (if (fboundp 'defvaralias)
537 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
539 (defcustom org-disputed-keys
540 '(([(shift up)] . [(meta p)])
541 ([(shift down)] . [(meta n)])
542 ([(shift left)] . [(meta -)])
543 ([(shift right)] . [(meta +)])
544 ([(control shift right)] . [(meta shift +)])
545 ([(control shift left)] . [(meta shift -)]))
546 "Keys for which Org-mode and other modes compete.
547 This is an alist, cars are the default keys, second element specifies
548 the alternative to use when `org-replace-disputed-keys' is t.
550 Keys can be specified in any syntax supported by `define-key'.
551 The value of this option takes effect only at Org-mode's startup,
552 therefore you'll have to restart Emacs to apply it after changing."
553 :group 'org-startup
554 :type 'alist)
556 (defun org-key (key)
557 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
558 Or return the original if not disputed.
559 Also apply the translations defined in `org-xemacs-key-equivalents'."
560 (when org-replace-disputed-keys
561 (let* ((nkey (key-description key))
562 (x (org-find-if (lambda (x)
563 (equal (key-description (car x)) nkey))
564 org-disputed-keys)))
565 (setq key (if x (cdr x) key))))
566 (when (featurep 'xemacs)
567 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
568 key)
570 (defun org-find-if (predicate seq)
571 (catch 'exit
572 (while seq
573 (if (funcall predicate (car seq))
574 (throw 'exit (car seq))
575 (pop seq)))))
577 (defun org-defkey (keymap key def)
578 "Define a key, possibly translated, as returned by `org-key'."
579 (define-key keymap (org-key key) def))
581 (defcustom org-ellipsis nil
582 "The ellipsis to use in the Org-mode outline.
583 When nil, just use the standard three dots. When a string, use that instead,
584 When a face, use the standard 3 dots, but with the specified face.
585 The change affects only Org-mode (which will then use its own display table).
586 Changing this requires executing `M-x org-mode' in a buffer to become
587 effective."
588 :group 'org-startup
589 :type '(choice (const :tag "Default" nil)
590 (face :tag "Face" :value org-warning)
591 (string :tag "String" :value "...#")))
593 (defvar org-display-table nil
594 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
596 (defgroup org-keywords nil
597 "Keywords in Org-mode."
598 :tag "Org Keywords"
599 :group 'org)
601 (defcustom org-deadline-string "DEADLINE:"
602 "String to mark deadline entries.
603 A deadline is this string, followed by a time stamp. Should be a word,
604 terminated by a colon. You can insert a schedule keyword and
605 a timestamp with \\[org-deadline].
606 Changes become only effective after restarting Emacs."
607 :group 'org-keywords
608 :type 'string)
610 (defcustom org-scheduled-string "SCHEDULED:"
611 "String to mark scheduled TODO entries.
612 A schedule is this string, followed by a time stamp. Should be a word,
613 terminated by a colon. You can insert a schedule keyword and
614 a timestamp with \\[org-schedule].
615 Changes become only effective after restarting Emacs."
616 :group 'org-keywords
617 :type 'string)
619 (defcustom org-closed-string "CLOSED:"
620 "String used as the prefix for timestamps logging closing a TODO entry."
621 :group 'org-keywords
622 :type 'string)
624 (defcustom org-clock-string "CLOCK:"
625 "String used as prefix for timestamps clocking work hours on an item."
626 :group 'org-keywords
627 :type 'string)
629 (defcustom org-comment-string "COMMENT"
630 "Entries starting with this keyword will never be exported.
631 An entry can be toggled between COMMENT and normal with
632 \\[org-toggle-comment].
633 Changes become only effective after restarting Emacs."
634 :group 'org-keywords
635 :type 'string)
637 (defcustom org-quote-string "QUOTE"
638 "Entries starting with this keyword will be exported in fixed-width font.
639 Quoting applies only to the text in the entry following the headline, and does
640 not extend beyond the next headline, even if that is lower level.
641 An entry can be toggled between QUOTE and normal with
642 \\[org-toggle-fixed-width-section]."
643 :group 'org-keywords
644 :type 'string)
646 (defconst org-repeat-re
647 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
648 "Regular expression for specifying repeated events.
649 After a match, group 1 contains the repeat expression.")
651 (defgroup org-structure nil
652 "Options concerning the general structure of Org-mode files."
653 :tag "Org Structure"
654 :group 'org)
656 (defgroup org-reveal-location nil
657 "Options about how to make context of a location visible."
658 :tag "Org Reveal Location"
659 :group 'org-structure)
661 (defconst org-context-choice
662 '(choice
663 (const :tag "Always" t)
664 (const :tag "Never" nil)
665 (repeat :greedy t :tag "Individual contexts"
666 (cons
667 (choice :tag "Context"
668 (const agenda)
669 (const org-goto)
670 (const occur-tree)
671 (const tags-tree)
672 (const link-search)
673 (const mark-goto)
674 (const bookmark-jump)
675 (const isearch)
676 (const default))
677 (boolean))))
678 "Contexts for the reveal options.")
680 (defcustom org-show-hierarchy-above '((default . t))
681 "Non-nil means show full hierarchy when revealing a location.
682 Org-mode often shows locations in an org-mode file which might have
683 been invisible before. When this is set, the hierarchy of headings
684 above the exposed location is shown.
685 Turning this off for example for sparse trees makes them very compact.
686 Instead of t, this can also be an alist specifying this option for different
687 contexts. Valid contexts are
688 agenda when exposing an entry from the agenda
689 org-goto when using the command `org-goto' on key C-c C-j
690 occur-tree when using the command `org-occur' on key C-c /
691 tags-tree when constructing a sparse tree based on tags matches
692 link-search when exposing search matches associated with a link
693 mark-goto when exposing the jump goal of a mark
694 bookmark-jump when exposing a bookmark location
695 isearch when exiting from an incremental search
696 default default for all contexts not set explicitly"
697 :group 'org-reveal-location
698 :type org-context-choice)
700 (defcustom org-show-following-heading '((default . nil))
701 "Non-nil means show following heading when revealing a location.
702 Org-mode often shows locations in an org-mode file which might have
703 been invisible before. When this is set, the heading following the
704 match is shown.
705 Turning this off for example for sparse trees makes them very compact,
706 but makes it harder to edit the location of the match. In such a case,
707 use the command \\[org-reveal] to show more context.
708 Instead of t, this can also be an alist specifying this option for different
709 contexts. See `org-show-hierarchy-above' for valid contexts."
710 :group 'org-reveal-location
711 :type org-context-choice)
713 (defcustom org-show-siblings '((default . nil) (isearch t))
714 "Non-nil means show all sibling heading when revealing a location.
715 Org-mode often shows locations in an org-mode file which might have
716 been invisible before. When this is set, the sibling of the current entry
717 heading are all made visible. If `org-show-hierarchy-above' is t,
718 the same happens on each level of the hierarchy above the current entry.
720 By default this is on for the isearch context, off for all other contexts.
721 Turning this off for example for sparse trees makes them very compact,
722 but makes it harder to edit the location of the match. In such a case,
723 use the command \\[org-reveal] to show more context.
724 Instead of t, this can also be an alist specifying this option for different
725 contexts. See `org-show-hierarchy-above' for valid contexts."
726 :group 'org-reveal-location
727 :type org-context-choice)
729 (defcustom org-show-entry-below '((default . nil))
730 "Non-nil means show the entry below a headline when revealing a location.
731 Org-mode often shows locations in an org-mode file which might have
732 been invisible before. When this is set, the text below the headline that is
733 exposed is also shown.
735 By default this is off for all contexts.
736 Instead of t, this can also be an alist specifying this option for different
737 contexts. See `org-show-hierarchy-above' for valid contexts."
738 :group 'org-reveal-location
739 :type org-context-choice)
741 (defcustom org-indirect-buffer-display 'other-window
742 "How should indirect tree buffers be displayed?
743 This applies to indirect buffers created with the commands
744 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
745 Valid values are:
746 current-window Display in the current window
747 other-window Just display in another window.
748 dedicated-frame Create one new frame, and re-use it each time.
749 new-frame Make a new frame each time. Note that in this case
750 previously-made indirect buffers are kept, and you need to
751 kill these buffers yourself."
752 :group 'org-structure
753 :group 'org-agenda-windows
754 :type '(choice
755 (const :tag "In current window" current-window)
756 (const :tag "In current frame, other window" other-window)
757 (const :tag "Each time a new frame" new-frame)
758 (const :tag "One dedicated frame" dedicated-frame)))
760 (defcustom org-use-speed-commands nil
761 "Non-nil means activate single letter commands at beginning of a headline.
762 This may also be a function to test for appropriate locations where speed
763 commands should be active."
764 :group 'org-structure
765 :type '(choice
766 (const :tag "Never" nil)
767 (const :tag "At beginning of headline stars" t)
768 (function)))
770 (defcustom org-speed-commands-user nil
771 "Alist of additional speed commands.
772 This list will be checked before `org-speed-commands-default'
773 when the variable `org-use-speed-commands' is non-nil
774 and when the cursor is at the beginning of a headline.
775 The car if each entry is a string with a single letter, which must
776 be assigned to `self-insert-command' in the global map.
777 The cdr is either a command to be called interactively, a function
778 to be called, or a form to be evaluated.
779 An entry that is just a list with a single string will be interpreted
780 as a descriptive headline that will be added when listing the speed
781 commands in the Help buffer using the `?' speed command."
782 :group 'org-structure
783 :type '(repeat :value ("k" . ignore)
784 (choice :value ("k" . ignore)
785 (list :tag "Descriptive Headline" (string :tag "Headline"))
786 (cons :tag "Letter and Command"
787 (string :tag "Command letter")
788 (choice
789 (function)
790 (sexp))))))
792 (defgroup org-cycle nil
793 "Options concerning visibility cycling in Org-mode."
794 :tag "Org Cycle"
795 :group 'org-structure)
797 (defcustom org-cycle-skip-children-state-if-no-children t
798 "Non-nil means skip CHILDREN state in entries that don't have any."
799 :group 'org-cycle
800 :type 'boolean)
802 (defcustom org-cycle-max-level nil
803 "Maximum level which should still be subject to visibility cycling.
804 Levels higher than this will, for cycling, be treated as text, not a headline.
805 When `org-odd-levels-only' is set, a value of N in this variable actually
806 means 2N-1 stars as the limiting headline.
807 When nil, cycle all levels.
808 Note that the limiting level of cycling is also influenced by
809 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
810 `org-inlinetask-min-level' is, cycling will be limited to levels one less
811 than its value."
812 :group 'org-cycle
813 :type '(choice
814 (const :tag "No limit" nil)
815 (integer :tag "Maximum level")))
817 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
818 "Names of drawers. Drawers are not opened by cycling on the headline above.
819 Drawers only open with a TAB on the drawer line itself. A drawer looks like
820 this:
821 :DRAWERNAME:
822 .....
823 :END:
824 The drawer \"PROPERTIES\" is special for capturing properties through
825 the property API.
827 Drawers can be defined on the per-file basis with a line like:
829 #+DRAWERS: HIDDEN STATE PROPERTIES"
830 :group 'org-structure
831 :group 'org-cycle
832 :type '(repeat (string :tag "Drawer Name")))
834 (defcustom org-hide-block-startup nil
835 "Non-nil means entering Org-mode will fold all blocks.
836 This can also be set in on a per-file basis with
838 #+STARTUP: hideblocks
839 #+STARTUP: showblocks"
840 :group 'org-startup
841 :group 'org-cycle
842 :type 'boolean)
844 (defcustom org-cycle-global-at-bob nil
845 "Cycle globally if cursor is at beginning of buffer and not at a headline.
846 This makes it possible to do global cycling without having to use S-TAB or
847 \\[universal-argument] TAB. For this special case to work, the first line \
848 of the buffer
849 must not be a headline - it may be empty or some other text. When used in
850 this way, `org-cycle-hook' is disables temporarily, to make sure the
851 cursor stays at the beginning of the buffer.
852 When this option is nil, don't do anything special at the beginning
853 of the buffer."
854 :group 'org-cycle
855 :type 'boolean)
857 (defcustom org-cycle-level-after-item/entry-creation t
858 "Non-nil means cycle entry level or item indentation in new empty entries.
860 When the cursor is at the end of an empty headline, i.e with only stars
861 and maybe a TODO keyword, TAB will then switch the entry to become a child,
862 and then all possible ancestor states, before returning to the original state.
863 This makes data entry extremely fast: M-RET to create a new headline,
864 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
866 When the cursor is at the end of an empty plain list item, one TAB will
867 make it a subitem, two or more tabs will back up to make this an item
868 higher up in the item hierarchy."
869 :group 'org-cycle
870 :type 'boolean)
872 (defcustom org-cycle-emulate-tab t
873 "Where should `org-cycle' emulate TAB.
874 nil Never
875 white Only in completely white lines
876 whitestart Only at the beginning of lines, before the first non-white char
877 t Everywhere except in headlines
878 exc-hl-bol Everywhere except at the start of a headline
879 If TAB is used in a place where it does not emulate TAB, the current subtree
880 visibility is cycled."
881 :group 'org-cycle
882 :type '(choice (const :tag "Never" nil)
883 (const :tag "Only in completely white lines" white)
884 (const :tag "Before first char in a line" whitestart)
885 (const :tag "Everywhere except in headlines" t)
886 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
889 (defcustom org-cycle-separator-lines 2
890 "Number of empty lines needed to keep an empty line between collapsed trees.
891 If you leave an empty line between the end of a subtree and the following
892 headline, this empty line is hidden when the subtree is folded.
893 Org-mode will leave (exactly) one empty line visible if the number of
894 empty lines is equal or larger to the number given in this variable.
895 So the default 2 means at least 2 empty lines after the end of a subtree
896 are needed to produce free space between a collapsed subtree and the
897 following headline.
899 If the number is negative, and the number of empty lines is at least -N,
900 all empty lines are shown.
902 Special case: when 0, never leave empty lines in collapsed view."
903 :group 'org-cycle
904 :type 'integer)
905 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
907 (defcustom org-pre-cycle-hook nil
908 "Hook that is run before visibility cycling is happening.
909 The function(s) in this hook must accept a single argument which indicates
910 the new state that will be set right after running this hook. The
911 argument is a symbol. Before a global state change, it can have the values
912 `overview', `content', or `all'. Before a local state change, it can have
913 the values `folded', `children', or `subtree'."
914 :group 'org-cycle
915 :type 'hook)
917 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
918 org-cycle-hide-drawers
919 org-cycle-show-empty-lines
920 org-optimize-window-after-visibility-change)
921 "Hook that is run after `org-cycle' has changed the buffer visibility.
922 The function(s) in this hook must accept a single argument which indicates
923 the new state that was set by the most recent `org-cycle' command. The
924 argument is a symbol. After a global state change, it can have the values
925 `overview', `content', or `all'. After a local state change, it can have
926 the values `folded', `children', or `subtree'."
927 :group 'org-cycle
928 :type 'hook)
930 (defgroup org-edit-structure nil
931 "Options concerning structure editing in Org-mode."
932 :tag "Org Edit Structure"
933 :group 'org-structure)
935 (defcustom org-odd-levels-only nil
936 "Non-nil means skip even levels and only use odd levels for the outline.
937 This has the effect that two stars are being added/taken away in
938 promotion/demotion commands. It also influences how levels are
939 handled by the exporters.
940 Changing it requires restart of `font-lock-mode' to become effective
941 for fontification also in regions already fontified.
942 You may also set this on a per-file basis by adding one of the following
943 lines to the buffer:
945 #+STARTUP: odd
946 #+STARTUP: oddeven"
947 :group 'org-edit-structure
948 :group 'org-appearance
949 :type 'boolean)
951 (defcustom org-adapt-indentation t
952 "Non-nil means adapt indentation to outline node level.
954 When this variable is set, Org assumes that you write outlines by
955 indenting text in each node to align with the headline (after the stars).
956 The following issues are influenced by this variable:
958 - When this is set and the *entire* text in an entry is indented, the
959 indentation is increased by one space in a demotion command, and
960 decreased by one in a promotion command. If any line in the entry
961 body starts with text at column 0, indentation is not changed at all.
963 - Property drawers and planning information is inserted indented when
964 this variable s set. When nil, they will not be indented.
966 - TAB indents a line relative to context. The lines below a headline
967 will be indented when this variable is set.
969 Note that this is all about true indentation, by adding and removing
970 space characters. See also `org-indent.el' which does level-dependent
971 indentation in a virtual way, i.e. at display time in Emacs."
972 :group 'org-edit-structure
973 :type 'boolean)
975 (defcustom org-special-ctrl-a/e nil
976 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
978 When t, `C-a' will bring back the cursor to the beginning of the
979 headline text, i.e. after the stars and after a possible TODO keyword.
980 In an item, this will be the position after the bullet.
981 When the cursor is already at that position, another `C-a' will bring
982 it to the beginning of the line.
984 `C-e' will jump to the end of the headline, ignoring the presence of tags
985 in the headline. A second `C-e' will then jump to the true end of the
986 line, after any tags. This also means that, when this variable is
987 non-nil, `C-e' also will never jump beyond the end of the heading of a
988 folded section, i.e. not after the ellipses.
990 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
991 going to the true line boundary first. Only a directly following, identical
992 keypress will bring the cursor to the special positions.
994 This may also be a cons cell where the behavior for `C-a' and `C-e' is
995 set separately."
996 :group 'org-edit-structure
997 :type '(choice
998 (const :tag "off" nil)
999 (const :tag "on: after stars/bullet and before tags first" t)
1000 (const :tag "reversed: true line boundary first" reversed)
1001 (cons :tag "Set C-a and C-e separately"
1002 (choice :tag "Special C-a"
1003 (const :tag "off" nil)
1004 (const :tag "on: after stars/bullet first" t)
1005 (const :tag "reversed: before stars/bullet first" reversed))
1006 (choice :tag "Special C-e"
1007 (const :tag "off" nil)
1008 (const :tag "on: before tags first" t)
1009 (const :tag "reversed: after tags first" reversed)))))
1010 (if (fboundp 'defvaralias)
1011 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1013 (defcustom org-special-ctrl-k nil
1014 "Non-nil means `C-k' will behave specially in headlines.
1015 When nil, `C-k' will call the default `kill-line' command.
1016 When t, the following will happen while the cursor is in the headline:
1018 - When the cursor is at the beginning of a headline, kill the entire
1019 line and possible the folded subtree below the line.
1020 - When in the middle of the headline text, kill the headline up to the tags.
1021 - When after the headline text, kill the tags."
1022 :group 'org-edit-structure
1023 :type 'boolean)
1025 (defcustom org-ctrl-k-protect-subtree nil
1026 "Non-nil means, do not delete a hidden subtree with C-k.
1027 When set to the symbol `error', simply throw an error when C-k is
1028 used to kill (part-of) a headline that has hidden text behind it.
1029 Any other non-nil value will result in a query to the user, if it is
1030 OK to kill that hidden subtree. When nil, kill without remorse."
1031 :group 'org-edit-structure
1032 :type '(choice
1033 (const :tag "Do not protect hidden subtrees" nil)
1034 (const :tag "Protect hidden subtrees with a security query" t)
1035 (const :tag "Never kill a hidden subtree with C-k" error)))
1037 (defcustom org-yank-folded-subtrees t
1038 "Non-nil means when yanking subtrees, fold them.
1039 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1040 it starts with a heading and all other headings in it are either children
1041 or siblings, then fold all the subtrees. However, do this only if no
1042 text after the yank would be swallowed into a folded tree by this action."
1043 :group 'org-edit-structure
1044 :type 'boolean)
1046 (defcustom org-yank-adjusted-subtrees nil
1047 "Non-nil means when yanking subtrees, adjust the level.
1048 With this setting, `org-paste-subtree' is used to insert the subtree, see
1049 this function for details."
1050 :group 'org-edit-structure
1051 :type 'boolean)
1053 (defcustom org-M-RET-may-split-line '((default . t))
1054 "Non-nil means M-RET will split the line at the cursor position.
1055 When nil, it will go to the end of the line before making a
1056 new line.
1057 You may also set this option in a different way for different
1058 contexts. Valid contexts are:
1060 headline when creating a new headline
1061 item when creating a new item
1062 table in a table field
1063 default the value to be used for all contexts not explicitly
1064 customized"
1065 :group 'org-structure
1066 :group 'org-table
1067 :type '(choice
1068 (const :tag "Always" t)
1069 (const :tag "Never" nil)
1070 (repeat :greedy t :tag "Individual contexts"
1071 (cons
1072 (choice :tag "Context"
1073 (const headline)
1074 (const item)
1075 (const table)
1076 (const default))
1077 (boolean)))))
1080 (defcustom org-insert-heading-respect-content nil
1081 "Non-nil means insert new headings after the current subtree.
1082 When nil, the new heading is created directly after the current line.
1083 The commands \\[org-insert-heading-respect-content] and
1084 \\[org-insert-todo-heading-respect-content] turn this variable on
1085 for the duration of the command."
1086 :group 'org-structure
1087 :type 'boolean)
1089 (defcustom org-blank-before-new-entry '((heading . auto)
1090 (plain-list-item . auto))
1091 "Should `org-insert-heading' leave a blank line before new heading/item?
1092 The value is an alist, with `heading' and `plain-list-item' as car,
1093 and a boolean flag as cdr. The cdr may also be the symbol `auto', and then
1094 Org will look at the surrounding headings/items and try to make an
1095 intelligent decision whether to insert a blank line or not.
1097 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1098 set, the setting here is ignored and no empty line is inserted, to avoid
1099 breaking the list structure."
1100 :group 'org-edit-structure
1101 :type '(list
1102 (cons (const heading)
1103 (choice (const :tag "Never" nil)
1104 (const :tag "Always" t)
1105 (const :tag "Auto" auto)))
1106 (cons (const plain-list-item)
1107 (choice (const :tag "Never" nil)
1108 (const :tag "Always" t)
1109 (const :tag "Auto" auto)))))
1111 (defcustom org-insert-heading-hook nil
1112 "Hook being run after inserting a new heading."
1113 :group 'org-edit-structure
1114 :type 'hook)
1116 (defcustom org-enable-fixed-width-editor t
1117 "Non-nil means lines starting with \":\" are treated as fixed-width.
1118 This currently only means they are never auto-wrapped.
1119 When nil, such lines will be treated like ordinary lines.
1120 See also the QUOTE keyword."
1121 :group 'org-edit-structure
1122 :type 'boolean)
1124 (defcustom org-goto-auto-isearch t
1125 "Non-nil means typing characters in `org-goto' starts incremental search."
1126 :group 'org-edit-structure
1127 :type 'boolean)
1129 (defgroup org-sparse-trees nil
1130 "Options concerning sparse trees in Org-mode."
1131 :tag "Org Sparse Trees"
1132 :group 'org-structure)
1134 (defcustom org-highlight-sparse-tree-matches t
1135 "Non-nil means highlight all matches that define a sparse tree.
1136 The highlights will automatically disappear the next time the buffer is
1137 changed by an edit command."
1138 :group 'org-sparse-trees
1139 :type 'boolean)
1141 (defcustom org-remove-highlights-with-change t
1142 "Non-nil means any change to the buffer will remove temporary highlights.
1143 Such highlights are created by `org-occur' and `org-clock-display'.
1144 When nil, `C-c C-c needs to be used to get rid of the highlights.
1145 The highlights created by `org-preview-latex-fragment' always need
1146 `C-c C-c' to be removed."
1147 :group 'org-sparse-trees
1148 :group 'org-time
1149 :type 'boolean)
1152 (defcustom org-occur-hook '(org-first-headline-recenter)
1153 "Hook that is run after `org-occur' has constructed a sparse tree.
1154 This can be used to recenter the window to show as much of the structure
1155 as possible."
1156 :group 'org-sparse-trees
1157 :type 'hook)
1159 (defgroup org-imenu-and-speedbar nil
1160 "Options concerning imenu and speedbar in Org-mode."
1161 :tag "Org Imenu and Speedbar"
1162 :group 'org-structure)
1164 (defcustom org-imenu-depth 2
1165 "The maximum level for Imenu access to Org-mode headlines.
1166 This also applied for speedbar access."
1167 :group 'org-imenu-and-speedbar
1168 :type 'integer)
1170 (defgroup org-table nil
1171 "Options concerning tables in Org-mode."
1172 :tag "Org Table"
1173 :group 'org)
1175 (defcustom org-enable-table-editor 'optimized
1176 "Non-nil means lines starting with \"|\" are handled by the table editor.
1177 When nil, such lines will be treated like ordinary lines.
1179 When equal to the symbol `optimized', the table editor will be optimized to
1180 do the following:
1181 - Automatic overwrite mode in front of whitespace in table fields.
1182 This makes the structure of the table stay in tact as long as the edited
1183 field does not exceed the column width.
1184 - Minimize the number of realigns. Normally, the table is aligned each time
1185 TAB or RET are pressed to move to another field. With optimization this
1186 happens only if changes to a field might have changed the column width.
1187 Optimization requires replacing the functions `self-insert-command',
1188 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1189 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1190 very good at guessing when a re-align will be necessary, but you can always
1191 force one with \\[org-ctrl-c-ctrl-c].
1193 If you would like to use the optimized version in Org-mode, but the
1194 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1196 This variable can be used to turn on and off the table editor during a session,
1197 but in order to toggle optimization, a restart is required.
1199 See also the variable `org-table-auto-blank-field'."
1200 :group 'org-table
1201 :type '(choice
1202 (const :tag "off" nil)
1203 (const :tag "on" t)
1204 (const :tag "on, optimized" optimized)))
1206 (defcustom org-self-insert-cluster-for-undo t
1207 "Non-nil means cluster self-insert commands for undo when possible.
1208 If this is set, then, like in the Emacs command loop, 20 consecutive
1209 characters will be undone together.
1210 This is configurable, because there is some impact on typing performance."
1211 :group 'org-table
1212 :type 'boolean)
1214 (defcustom org-table-tab-recognizes-table.el t
1215 "Non-nil means TAB will automatically notice a table.el table.
1216 When it sees such a table, it moves point into it and - if necessary -
1217 calls `table-recognize-table'."
1218 :group 'org-table-editing
1219 :type 'boolean)
1221 (defgroup org-link nil
1222 "Options concerning links in Org-mode."
1223 :tag "Org Link"
1224 :group 'org)
1226 (defvar org-link-abbrev-alist-local nil
1227 "Buffer-local version of `org-link-abbrev-alist', which see.
1228 The value of this is taken from the #+LINK lines.")
1229 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1231 (defcustom org-link-abbrev-alist nil
1232 "Alist of link abbreviations.
1233 The car of each element is a string, to be replaced at the start of a link.
1234 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1235 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1237 [[linkkey:tag][description]]
1239 The 'linkkey' must be a word word, starting with a letter, followed
1240 by letters, numbers, '-' or '_'.
1242 If REPLACE is a string, the tag will simply be appended to create the link.
1243 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1244 the placeholder \"%h\" will cause a url-encoded version of the tag to
1245 be inserted at that point (see the function `url-hexify-string').
1247 REPLACE may also be a function that will be called with the tag as the
1248 only argument to create the link, which should be returned as a string.
1250 See the manual for examples."
1251 :group 'org-link
1252 :type '(repeat
1253 (cons
1254 (string :tag "Protocol")
1255 (choice
1256 (string :tag "Format")
1257 (function)))))
1259 (defcustom org-descriptive-links t
1260 "Non-nil means hide link part and only show description of bracket links.
1261 Bracket links are like [[link][description]]. This variable sets the initial
1262 state in new org-mode buffers. The setting can then be toggled on a
1263 per-buffer basis from the Org->Hyperlinks menu."
1264 :group 'org-link
1265 :type 'boolean)
1267 (defcustom org-link-file-path-type 'adaptive
1268 "How the path name in file links should be stored.
1269 Valid values are:
1271 relative Relative to the current directory, i.e. the directory of the file
1272 into which the link is being inserted.
1273 absolute Absolute path, if possible with ~ for home directory.
1274 noabbrev Absolute path, no abbreviation of home directory.
1275 adaptive Use relative path for files in the current directory and sub-
1276 directories of it. For other files, use an absolute path."
1277 :group 'org-link
1278 :type '(choice
1279 (const relative)
1280 (const absolute)
1281 (const noabbrev)
1282 (const adaptive)))
1284 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1285 "Types of links that should be activated in Org-mode files.
1286 This is a list of symbols, each leading to the activation of a certain link
1287 type. In principle, it does not hurt to turn on most link types - there may
1288 be a small gain when turning off unused link types. The types are:
1290 bracket The recommended [[link][description]] or [[link]] links with hiding.
1291 angle Links in angular brackets that may contain whitespace like
1292 <bbdb:Carsten Dominik>.
1293 plain Plain links in normal text, no whitespace, like http://google.com.
1294 radio Text that is matched by a radio target, see manual for details.
1295 tag Tag settings in a headline (link to tag search).
1296 date Time stamps (link to calendar).
1297 footnote Footnote labels.
1299 Changing this variable requires a restart of Emacs to become effective."
1300 :group 'org-link
1301 :type '(set :greedy t
1302 (const :tag "Double bracket links" bracket)
1303 (const :tag "Angular bracket links" angle)
1304 (const :tag "Plain text links" plain)
1305 (const :tag "Radio target matches" radio)
1306 (const :tag "Tags" tag)
1307 (const :tag "Timestamps" date)
1308 (const :tag "Footnotes" footnote)))
1310 (defcustom org-make-link-description-function nil
1311 "Function to use to generate link descriptions from links.
1312 If nil the link location will be used. This function must take
1313 two parameters; the first is the link and the second the
1314 description `org-insert-link' has generated, and should return the
1315 description to use."
1316 :group 'org-link
1317 :type 'function)
1319 (defgroup org-link-store nil
1320 "Options concerning storing links in Org-mode."
1321 :tag "Org Store Link"
1322 :group 'org-link)
1324 (defcustom org-email-link-description-format "Email %c: %.30s"
1325 "Format of the description part of a link to an email or usenet message.
1326 The following %-escapes will be replaced by corresponding information:
1328 %F full \"From\" field
1329 %f name, taken from \"From\" field, address if no name
1330 %T full \"To\" field
1331 %t first name in \"To\" field, address if no name
1332 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1333 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1334 %s subject
1335 %d date
1336 %m message-id.
1338 You may use normal field width specification between the % and the letter.
1339 This is for example useful to limit the length of the subject.
1341 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1342 :group 'org-link-store
1343 :type 'string)
1345 (defcustom org-from-is-user-regexp
1346 (let (r1 r2)
1347 (when (and user-mail-address (not (string= user-mail-address "")))
1348 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1349 (when (and user-full-name (not (string= user-full-name "")))
1350 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1351 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1352 "Regexp matched against the \"From:\" header of an email or usenet message.
1353 It should match if the message is from the user him/herself."
1354 :group 'org-link-store
1355 :type 'regexp)
1357 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1358 "Non-nil means storing a link to an Org file will use entry IDs.
1360 Note that before this variable is even considered, org-id must be loaded,
1361 so please customize `org-modules' and turn it on.
1363 The variable can have the following values:
1365 t Create an ID if needed to make a link to the current entry.
1367 create-if-interactive
1368 If `org-store-link' is called directly (interactively, as a user
1369 command), do create an ID to support the link. But when doing the
1370 job for remember, only use the ID if it already exists. The
1371 purpose of this setting is to avoid proliferation of unwanted
1372 IDs, just because you happen to be in an Org file when you
1373 call `org-remember' that automatically and preemptively
1374 creates a link. If you do want to get an ID link in a remember
1375 template to an entry not having an ID, create it first by
1376 explicitly creating a link to it, using `C-c C-l' first.
1378 create-if-interactive-and-no-custom-id
1379 Like create-if-interactive, but do not create an ID if there is
1380 a CUSTOM_ID property defined in the entry. This is the default.
1382 use-existing
1383 Use existing ID, do not create one.
1385 nil Never use an ID to make a link, instead link using a text search for
1386 the headline text."
1387 :group 'org-link-store
1388 :type '(choice
1389 (const :tag "Create ID to make link" t)
1390 (const :tag "Create if storing link interactively"
1391 create-if-interactive)
1392 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1393 create-if-interactive-and-no-custom-id)
1394 (const :tag "Only use existing" use-existing)
1395 (const :tag "Do not use ID to create link" nil)))
1397 (defcustom org-context-in-file-links t
1398 "Non-nil means file links from `org-store-link' contain context.
1399 A search string will be added to the file name with :: as separator and
1400 used to find the context when the link is activated by the command
1401 `org-open-at-point'. When this option is t, the entire active region
1402 will be placed in the search string of the file link. If set to a
1403 positive integer, only the first n lines of context will be stored.
1405 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1406 negates this setting for the duration of the command."
1407 :group 'org-link-store
1408 :type '(choice boolean integer))
1410 (defcustom org-keep-stored-link-after-insertion nil
1411 "Non-nil means keep link in list for entire session.
1413 The command `org-store-link' adds a link pointing to the current
1414 location to an internal list. These links accumulate during a session.
1415 The command `org-insert-link' can be used to insert links into any
1416 Org-mode file (offering completion for all stored links). When this
1417 option is nil, every link which has been inserted once using \\[org-insert-link]
1418 will be removed from the list, to make completing the unused links
1419 more efficient."
1420 :group 'org-link-store
1421 :type 'boolean)
1423 (defgroup org-link-follow nil
1424 "Options concerning following links in Org-mode."
1425 :tag "Org Follow Link"
1426 :group 'org-link)
1428 (defcustom org-link-translation-function nil
1429 "Function to translate links with different syntax to Org syntax.
1430 This can be used to translate links created for example by the Planner
1431 or emacs-wiki packages to Org syntax.
1432 The function must accept two parameters, a TYPE containing the link
1433 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1434 which is everything after the link protocol. It should return a cons
1435 with possibly modified values of type and path.
1436 Org contains a function for this, so if you set this variable to
1437 `org-translate-link-from-planner', you should be able follow many
1438 links created by planner."
1439 :group 'org-link-follow
1440 :type 'function)
1442 (defcustom org-follow-link-hook nil
1443 "Hook that is run after a link has been followed."
1444 :group 'org-link-follow
1445 :type 'hook)
1447 (defcustom org-tab-follows-link nil
1448 "Non-nil means on links TAB will follow the link.
1449 Needs to be set before org.el is loaded.
1450 This really should not be used, it does not make sense, and the
1451 implementation is bad."
1452 :group 'org-link-follow
1453 :type 'boolean)
1455 (defcustom org-return-follows-link nil
1456 "Non-nil means on links RET will follow the link."
1457 :group 'org-link-follow
1458 :type 'boolean)
1460 (defcustom org-mouse-1-follows-link
1461 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1462 "Non-nil means mouse-1 on a link will follow the link.
1463 A longer mouse click will still set point. Does not work on XEmacs.
1464 Needs to be set before org.el is loaded."
1465 :group 'org-link-follow
1466 :type 'boolean)
1468 (defcustom org-mark-ring-length 4
1469 "Number of different positions to be recorded in the ring.
1470 Changing this requires a restart of Emacs to work correctly."
1471 :group 'org-link-follow
1472 :type 'integer)
1474 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1475 "Non-nil means internal links in Org files must exactly match a headline.
1476 When nil, the link search tries to match a phrase with all words
1477 in the search text."
1478 :group 'org-link-follow
1479 :type '(choice
1480 (const :tag "Use fuzy text search" nil)
1481 (const :tag "Match only exact headline" t)
1482 (const :tag "Match extact headline or query to create it"
1483 query-to-create)))
1485 (defcustom org-link-frame-setup
1486 '((vm . vm-visit-folder-other-frame)
1487 (gnus . org-gnus-no-new-news)
1488 (file . find-file-other-window)
1489 (wl . wl-other-frame))
1490 "Setup the frame configuration for following links.
1491 When following a link with Emacs, it may often be useful to display
1492 this link in another window or frame. This variable can be used to
1493 set this up for the different types of links.
1494 For VM, use any of
1495 `vm-visit-folder'
1496 `vm-visit-folder-other-window'
1497 `vm-visit-folder-other-frame'
1498 For Gnus, use any of
1499 `gnus'
1500 `gnus-other-frame'
1501 `org-gnus-no-new-news'
1502 For FILE, use any of
1503 `find-file'
1504 `find-file-other-window'
1505 `find-file-other-frame'
1506 For Wanderlust use any of
1507 `wl'
1508 `wl-other-frame'
1509 For the calendar, use the variable `calendar-setup'.
1510 For BBDB, it is currently only possible to display the matches in
1511 another window."
1512 :group 'org-link-follow
1513 :type '(list
1514 (cons (const vm)
1515 (choice
1516 (const vm-visit-folder)
1517 (const vm-visit-folder-other-window)
1518 (const vm-visit-folder-other-frame)))
1519 (cons (const gnus)
1520 (choice
1521 (const gnus)
1522 (const gnus-other-frame)
1523 (const org-gnus-no-new-news)))
1524 (cons (const file)
1525 (choice
1526 (const find-file)
1527 (const find-file-other-window)
1528 (const find-file-other-frame)))
1529 (cons (const wl)
1530 (choice
1531 (const wl)
1532 (const wl-other-frame)))))
1534 (defcustom org-display-internal-link-with-indirect-buffer nil
1535 "Non-nil means use indirect buffer to display infile links.
1536 Activating internal links (from one location in a file to another location
1537 in the same file) normally just jumps to the location. When the link is
1538 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1539 is displayed in
1540 another window. When this option is set, the other window actually displays
1541 an indirect buffer clone of the current buffer, to avoid any visibility
1542 changes to the current buffer."
1543 :group 'org-link-follow
1544 :type 'boolean)
1546 (defcustom org-open-non-existing-files nil
1547 "Non-nil means `org-open-file' will open non-existing files.
1548 When nil, an error will be generated.
1549 This variable applies only to external applications because they
1550 might choke on non-existing files. If the link is to a file that
1551 will be opened in Emacs, the variable is ignored."
1552 :group 'org-link-follow
1553 :type 'boolean)
1555 (defcustom org-open-directory-means-index-dot-org nil
1556 "Non-nil means a link to a directory really means to index.org.
1557 When nil, following a directory link will run dired or open a finder/explorer
1558 window on that directory."
1559 :group 'org-link-follow
1560 :type 'boolean)
1562 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1563 "Function and arguments to call for following mailto links.
1564 This is a list with the first element being a Lisp function, and the
1565 remaining elements being arguments to the function. In string arguments,
1566 %a will be replaced by the address, and %s will be replaced by the subject
1567 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1568 :group 'org-link-follow
1569 :type '(choice
1570 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1571 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1572 (const :tag "message-mail" (message-mail "%a" "%s"))
1573 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1575 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1576 "Non-nil means ask for confirmation before executing shell links.
1577 Shell links can be dangerous: just think about a link
1579 [[shell:rm -rf ~/*][Google Search]]
1581 This link would show up in your Org-mode document as \"Google Search\",
1582 but really it would remove your entire home directory.
1583 Therefore we advise against setting this variable to nil.
1584 Just change it to `y-or-n-p' if you want to confirm with a
1585 single keystroke rather than having to type \"yes\"."
1586 :group 'org-link-follow
1587 :type '(choice
1588 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1589 (const :tag "with y-or-n (faster)" y-or-n-p)
1590 (const :tag "no confirmation (dangerous)" nil)))
1591 (put 'org-confirm-shell-link-function
1592 'safe-local-variable
1593 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1595 (defcustom org-confirm-shell-link-not-regexp ""
1596 "A regexp to skip confirmation for shell links."
1597 :group 'org-link-follow
1598 :type 'regexp)
1600 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1601 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1602 Elisp links can be dangerous: just think about a link
1604 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1606 This link would show up in your Org-mode document as \"Google Search\",
1607 but really it would remove your entire home directory.
1608 Therefore we advise against setting this variable to nil.
1609 Just change it to `y-or-n-p' if you want to confirm with a
1610 single keystroke rather than having to type \"yes\"."
1611 :group 'org-link-follow
1612 :type '(choice
1613 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1614 (const :tag "with y-or-n (faster)" y-or-n-p)
1615 (const :tag "no confirmation (dangerous)" nil)))
1616 (put 'org-confirm-shell-link-function
1617 'safe-local-variable
1618 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1620 (defcustom org-confirm-elisp-link-not-regexp ""
1621 "A regexp to skip confirmation for Elisp links."
1622 :group 'org-link-follow
1623 :type 'regexp)
1625 (defconst org-file-apps-defaults-gnu
1626 '((remote . emacs)
1627 (system . mailcap)
1628 (t . mailcap))
1629 "Default file applications on a UNIX or GNU/Linux system.
1630 See `org-file-apps'.")
1632 (defconst org-file-apps-defaults-macosx
1633 '((remote . emacs)
1634 (t . "open %s")
1635 (system . "open %s")
1636 ("ps.gz" . "gv %s")
1637 ("eps.gz" . "gv %s")
1638 ("dvi" . "xdvi %s")
1639 ("fig" . "xfig %s"))
1640 "Default file applications on a MacOS X system.
1641 The system \"open\" is known as a default, but we use X11 applications
1642 for some files for which the OS does not have a good default.
1643 See `org-file-apps'.")
1645 (defconst org-file-apps-defaults-windowsnt
1646 (list
1647 '(remote . emacs)
1648 (cons t
1649 (list (if (featurep 'xemacs)
1650 'mswindows-shell-execute
1651 'w32-shell-execute)
1652 "open" 'file))
1653 (cons 'system
1654 (list (if (featurep 'xemacs)
1655 'mswindows-shell-execute
1656 'w32-shell-execute)
1657 "open" 'file)))
1658 "Default file applications on a Windows NT system.
1659 The system \"open\" is used for most files.
1660 See `org-file-apps'.")
1662 (defcustom org-file-apps
1664 (auto-mode . emacs)
1665 ("\\.mm\\'" . default)
1666 ("\\.x?html?\\'" . default)
1667 ("\\.pdf\\'" . default)
1669 "External applications for opening `file:path' items in a document.
1670 Org-mode uses system defaults for different file types, but
1671 you can use this variable to set the application for a given file
1672 extension. The entries in this list are cons cells where the car identifies
1673 files and the cdr the corresponding command. Possible values for the
1674 file identifier are
1675 \"string\" A string as a file identifier can be interpreted in different
1676 ways, depending on its contents:
1678 - Alphanumeric characters only:
1679 Match links with this file extension.
1680 Example: (\"pdf\" . \"evince %s\")
1681 to open PDFs with evince.
1683 - Regular expression: Match links where the
1684 filename matches the regexp. If you want to
1685 use groups here, use shy groups.
1687 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1688 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1689 to open *.html and *.xhtml with firefox.
1691 - Regular expression which contains (non-shy) groups:
1692 Match links where the whole link, including \"::\", and
1693 anything after that, matches the regexp.
1694 In a custom command string, %1, %2, etc. are replaced with
1695 the parts of the link that were matched by the groups.
1696 For backwards compatibility, if a command string is given
1697 that does not use any of the group matches, this case is
1698 handled identically to the second one (i.e. match against
1699 file name only).
1700 In a custom lisp form, you can access the group matches with
1701 (match-string n link).
1703 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1704 to open [[file:document.pdf::5]] with evince at page 5.
1706 `directory' Matches a directory
1707 `remote' Matches a remote file, accessible through tramp or efs.
1708 Remote files most likely should be visited through Emacs
1709 because external applications cannot handle such paths.
1710 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1711 so all files Emacs knows how to handle. Using this with
1712 command `emacs' will open most files in Emacs. Beware that this
1713 will also open html files inside Emacs, unless you add
1714 (\"html\" . default) to the list as well.
1715 t Default for files not matched by any of the other options.
1716 `system' The system command to open files, like `open' on Windows
1717 and Mac OS X, and mailcap under GNU/Linux. This is the command
1718 that will be selected if you call `C-c C-o' with a double
1719 \\[universal-argument] \\[universal-argument] prefix.
1721 Possible values for the command are:
1722 `emacs' The file will be visited by the current Emacs process.
1723 `default' Use the default application for this file type, which is the
1724 association for t in the list, most likely in the system-specific
1725 part.
1726 This can be used to overrule an unwanted setting in the
1727 system-specific variable.
1728 `system' Use the system command for opening files, like \"open\".
1729 This command is specified by the entry whose car is `system'.
1730 Most likely, the system-specific version of this variable
1731 does define this command, but you can overrule/replace it
1732 here.
1733 string A command to be executed by a shell; %s will be replaced
1734 by the path to the file.
1735 sexp A Lisp form which will be evaluated. The file path will
1736 be available in the Lisp variable `file'.
1737 For more examples, see the system specific constants
1738 `org-file-apps-defaults-macosx'
1739 `org-file-apps-defaults-windowsnt'
1740 `org-file-apps-defaults-gnu'."
1741 :group 'org-link-follow
1742 :type '(repeat
1743 (cons (choice :value ""
1744 (string :tag "Extension")
1745 (const :tag "System command to open files" system)
1746 (const :tag "Default for unrecognized files" t)
1747 (const :tag "Remote file" remote)
1748 (const :tag "Links to a directory" directory)
1749 (const :tag "Any files that have Emacs modes"
1750 auto-mode))
1751 (choice :value ""
1752 (const :tag "Visit with Emacs" emacs)
1753 (const :tag "Use default" default)
1754 (const :tag "Use the system command" system)
1755 (string :tag "Command")
1756 (sexp :tag "Lisp form")))))
1760 (defgroup org-refile nil
1761 "Options concerning refiling entries in Org-mode."
1762 :tag "Org Refile"
1763 :group 'org)
1765 (defcustom org-directory "~/org"
1766 "Directory with org files.
1767 This is just a default location to look for Org files. There is no need
1768 at all to put your files into this directory. It is only used in the
1769 following situations:
1771 1. When a remember template specifies a target file that is not an
1772 absolute path. The path will then be interpreted relative to
1773 `org-directory'
1774 2. When a remember note is filed away in an interactive way (when exiting the
1775 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1776 with `org-directory' as the default path."
1777 :group 'org-refile
1778 :group 'org-remember
1779 :type 'directory)
1781 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1782 "Default target for storing notes.
1783 Used as a fall back file for org-remember.el and org-capture.el, for
1784 templates that do not specify a target file."
1785 :group 'org-refile
1786 :group 'org-remember
1787 :type '(choice
1788 (const :tag "Default from remember-data-file" nil)
1789 file))
1791 (defcustom org-goto-interface 'outline
1792 "The default interface to be used for `org-goto'.
1793 Allowed values are:
1794 outline The interface shows an outline of the relevant file
1795 and the correct heading is found by moving through
1796 the outline or by searching with incremental search.
1797 outline-path-completion Headlines in the current buffer are offered via
1798 completion. This is the interface also used by
1799 the refile command."
1800 :group 'org-refile
1801 :type '(choice
1802 (const :tag "Outline" outline)
1803 (const :tag "Outline-path-completion" outline-path-completion)))
1805 (defcustom org-goto-max-level 5
1806 "Maximum target level when running `org-goto' with refile interface."
1807 :group 'org-refile
1808 :type 'integer)
1810 (defcustom org-reverse-note-order nil
1811 "Non-nil means store new notes at the beginning of a file or entry.
1812 When nil, new notes will be filed to the end of a file or entry.
1813 This can also be a list with cons cells of regular expressions that
1814 are matched against file names, and values."
1815 :group 'org-remember
1816 :group 'org-refile
1817 :type '(choice
1818 (const :tag "Reverse always" t)
1819 (const :tag "Reverse never" nil)
1820 (repeat :tag "By file name regexp"
1821 (cons regexp boolean))))
1823 (defcustom org-log-refile nil
1824 "Information to record when a task is refiled.
1826 Possible values are:
1828 nil Don't add anything
1829 time Add a time stamp to the task
1830 note Prompt for a note and add it with template `org-log-note-headings'
1832 This option can also be set with on a per-file-basis with
1834 #+STARTUP: nologrefile
1835 #+STARTUP: logrefile
1836 #+STARTUP: lognoterefile
1838 You can have local logging settings for a subtree by setting the LOGGING
1839 property to one or more of these keywords.
1841 When bulk-refiling from the agenda, the value `note' is forbidden and
1842 will temporarily be changed to `time'."
1843 :group 'org-refile
1844 :group 'org-progress
1845 :type '(choice
1846 (const :tag "No logging" nil)
1847 (const :tag "Record timestamp" time)
1848 (const :tag "Record timestamp with note." note)))
1850 (defcustom org-refile-targets nil
1851 "Targets for refiling entries with \\[org-refile].
1852 This is list of cons cells. Each cell contains:
1853 - a specification of the files to be considered, either a list of files,
1854 or a symbol whose function or variable value will be used to retrieve
1855 a file name or a list of file names. If you use `org-agenda-files' for
1856 that, all agenda files will be scanned for targets. Nil means consider
1857 headings in the current buffer.
1858 - A specification of how to find candidate refile targets. This may be
1859 any of:
1860 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1861 This tag has to be present in all target headlines, inheritance will
1862 not be considered.
1863 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1864 todo keyword.
1865 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1866 headlines that are refiling targets.
1867 - a cons cell (:level . N). Any headline of level N is considered a target.
1868 Note that, when `org-odd-levels-only' is set, level corresponds to
1869 order in hierarchy, not to the number of stars.
1870 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1871 Note that, when `org-odd-levels-only' is set, level corresponds to
1872 order in hierarchy, not to the number of stars.
1874 You can set the variable `org-refile-target-verify-function' to a function
1875 to verify each headline found by the simple criteria above.
1877 When this variable is nil, all top-level headlines in the current buffer
1878 are used, equivalent to the value `((nil . (:level . 1))'."
1879 :group 'org-refile
1880 :type '(repeat
1881 (cons
1882 (choice :value org-agenda-files
1883 (const :tag "All agenda files" org-agenda-files)
1884 (const :tag "Current buffer" nil)
1885 (function) (variable) (file))
1886 (choice :tag "Identify target headline by"
1887 (cons :tag "Specific tag" (const :value :tag) (string))
1888 (cons :tag "TODO keyword" (const :value :todo) (string))
1889 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1890 (cons :tag "Level number" (const :value :level) (integer))
1891 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1893 (defcustom org-refile-target-verify-function nil
1894 "Function to verify if the headline at point should be a refile target.
1895 The function will be called without arguments, with point at the
1896 beginning of the headline. It should return t and leave point
1897 where it is if the headline is a valid target for refiling.
1899 If the target should not be selected, the function must return nil.
1900 In addition to this, it may move point to a place from where the search
1901 should be continued. For example, the function may decide that the entire
1902 subtree of the current entry should be excluded and move point to the end
1903 of the subtree."
1904 :group 'org-refile
1905 :type 'function)
1907 (defcustom org-refile-use-cache nil
1908 "Non-nil means cache refile targets to speed up the process.
1909 The cache for a particular file will be updated automatically when
1910 the buffer has been killed, or when any of the marker used for flagging
1911 refile targets no longer points at a live buffer.
1912 If you have added new entries to a buffer that might themselves be targets,
1913 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1914 find that easier, `C-u C-u C-u C-c C-w'."
1915 :group 'org-refile
1916 :type 'boolean)
1918 (defcustom org-refile-use-outline-path nil
1919 "Non-nil means provide refile targets as paths.
1920 So a level 3 headline will be available as level1/level2/level3.
1922 When the value is `file', also include the file name (without directory)
1923 into the path. In this case, you can also stop the completion after
1924 the file name, to get entries inserted as top level in the file.
1926 When `full-file-path', include the full file path."
1927 :group 'org-refile
1928 :type '(choice
1929 (const :tag "Not" nil)
1930 (const :tag "Yes" t)
1931 (const :tag "Start with file name" file)
1932 (const :tag "Start with full file path" full-file-path)))
1934 (defcustom org-outline-path-complete-in-steps t
1935 "Non-nil means complete the outline path in hierarchical steps.
1936 When Org-mode uses the refile interface to select an outline path
1937 \(see variable `org-refile-use-outline-path'), the completion of
1938 the path can be done is a single go, or if can be done in steps down
1939 the headline hierarchy. Going in steps is probably the best if you
1940 do not use a special completion package like `ido' or `icicles'.
1941 However, when using these packages, going in one step can be very
1942 fast, while still showing the whole path to the entry."
1943 :group 'org-refile
1944 :type 'boolean)
1946 (defcustom org-refile-allow-creating-parent-nodes nil
1947 "Non-nil means allow to create new nodes as refile targets.
1948 New nodes are then created by adding \"/new node name\" to the completion
1949 of an existing node. When the value of this variable is `confirm',
1950 new node creation must be confirmed by the user (recommended)
1951 When nil, the completion must match an existing entry.
1953 Note that, if the new heading is not seen by the criteria
1954 listed in `org-refile-targets', multiple instances of the same
1955 heading would be created by trying again to file under the new
1956 heading."
1957 :group 'org-refile
1958 :type '(choice
1959 (const :tag "Never" nil)
1960 (const :tag "Always" t)
1961 (const :tag "Prompt for confirmation" confirm)))
1963 (defgroup org-todo nil
1964 "Options concerning TODO items in Org-mode."
1965 :tag "Org TODO"
1966 :group 'org)
1968 (defgroup org-progress nil
1969 "Options concerning Progress logging in Org-mode."
1970 :tag "Org Progress"
1971 :group 'org-time)
1973 (defvar org-todo-interpretation-widgets
1975 (:tag "Sequence (cycling hits every state)" sequence)
1976 (:tag "Type (cycling directly to DONE)" type))
1977 "The available interpretation symbols for customizing `org-todo-keywords'.
1978 Interested libraries should add to this list.")
1980 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1981 "List of TODO entry keyword sequences and their interpretation.
1982 \\<org-mode-map>This is a list of sequences.
1984 Each sequence starts with a symbol, either `sequence' or `type',
1985 indicating if the keywords should be interpreted as a sequence of
1986 action steps, or as different types of TODO items. The first
1987 keywords are states requiring action - these states will select a headline
1988 for inclusion into the global TODO list Org-mode produces. If one of
1989 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
1990 signify that no further action is necessary. If \"|\" is not found,
1991 the last keyword is treated as the only DONE state of the sequence.
1993 The command \\[org-todo] cycles an entry through these states, and one
1994 additional state where no keyword is present. For details about this
1995 cycling, see the manual.
1997 TODO keywords and interpretation can also be set on a per-file basis with
1998 the special #+SEQ_TODO and #+TYP_TODO lines.
2000 Each keyword can optionally specify a character for fast state selection
2001 \(in combination with the variable `org-use-fast-todo-selection')
2002 and specifiers for state change logging, using the same syntax
2003 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2004 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2005 indicates to record a time stamp each time this state is selected.
2007 Each keyword may also specify if a timestamp or a note should be
2008 recorded when entering or leaving the state, by adding additional
2009 characters in the parenthesis after the keyword. This looks like this:
2010 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2011 record only the time of the state change. With X and Y being either
2012 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2013 Y when leaving the state if and only if the *target* state does not
2014 define X. You may omit any of the fast-selection key or X or /Y,
2015 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2017 For backward compatibility, this variable may also be just a list
2018 of keywords - in this case the interpretation (sequence or type) will be
2019 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2020 :group 'org-todo
2021 :group 'org-keywords
2022 :type '(choice
2023 (repeat :tag "Old syntax, just keywords"
2024 (string :tag "Keyword"))
2025 (repeat :tag "New syntax"
2026 (cons
2027 (choice
2028 :tag "Interpretation"
2029 ;;Quick and dirty way to see
2030 ;;`org-todo-interpretations'. This takes the
2031 ;;place of item arguments
2032 :convert-widget
2033 (lambda (widget)
2034 (widget-put widget
2035 :args (mapcar
2036 #'(lambda (x)
2037 (widget-convert
2038 (cons 'const x)))
2039 org-todo-interpretation-widgets))
2040 widget))
2041 (repeat
2042 (string :tag "Keyword"))))))
2044 (defvar org-todo-keywords-1 nil
2045 "All TODO and DONE keywords active in a buffer.")
2046 (make-variable-buffer-local 'org-todo-keywords-1)
2047 (defvar org-todo-keywords-for-agenda nil)
2048 (defvar org-done-keywords-for-agenda nil)
2049 (defvar org-drawers-for-agenda nil)
2050 (defvar org-todo-keyword-alist-for-agenda nil)
2051 (defvar org-tag-alist-for-agenda nil)
2052 (defvar org-agenda-contributing-files nil)
2053 (defvar org-not-done-keywords nil)
2054 (make-variable-buffer-local 'org-not-done-keywords)
2055 (defvar org-done-keywords nil)
2056 (make-variable-buffer-local 'org-done-keywords)
2057 (defvar org-todo-heads nil)
2058 (make-variable-buffer-local 'org-todo-heads)
2059 (defvar org-todo-sets nil)
2060 (make-variable-buffer-local 'org-todo-sets)
2061 (defvar org-todo-log-states nil)
2062 (make-variable-buffer-local 'org-todo-log-states)
2063 (defvar org-todo-kwd-alist nil)
2064 (make-variable-buffer-local 'org-todo-kwd-alist)
2065 (defvar org-todo-key-alist nil)
2066 (make-variable-buffer-local 'org-todo-key-alist)
2067 (defvar org-todo-key-trigger nil)
2068 (make-variable-buffer-local 'org-todo-key-trigger)
2070 (defcustom org-todo-interpretation 'sequence
2071 "Controls how TODO keywords are interpreted.
2072 This variable is in principle obsolete and is only used for
2073 backward compatibility, if the interpretation of todo keywords is
2074 not given already in `org-todo-keywords'. See that variable for
2075 more information."
2076 :group 'org-todo
2077 :group 'org-keywords
2078 :type '(choice (const sequence)
2079 (const type)))
2081 (defcustom org-use-fast-todo-selection t
2082 "Non-nil means use the fast todo selection scheme with C-c C-t.
2083 This variable describes if and under what circumstances the cycling
2084 mechanism for TODO keywords will be replaced by a single-key, direct
2085 selection scheme.
2087 When nil, fast selection is never used.
2089 When the symbol `prefix', it will be used when `org-todo' is called with
2090 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2091 in an agenda buffer.
2093 When t, fast selection is used by default. In this case, the prefix
2094 argument forces cycling instead.
2096 In all cases, the special interface is only used if access keys have actually
2097 been assigned by the user, i.e. if keywords in the configuration are followed
2098 by a letter in parenthesis, like TODO(t)."
2099 :group 'org-todo
2100 :type '(choice
2101 (const :tag "Never" nil)
2102 (const :tag "By default" t)
2103 (const :tag "Only with C-u C-c C-t" prefix)))
2105 (defcustom org-provide-todo-statistics t
2106 "Non-nil means update todo statistics after insert and toggle.
2107 ALL-HEADLINES means update todo statistics by including headlines
2108 with no TODO keyword as well, counting them as not done.
2109 A list of TODO keywords means the same, but skip keywords that are
2110 not in this list.
2112 When this is set, todo statistics is updated in the parent of the
2113 current entry each time a todo state is changed."
2114 :group 'org-todo
2115 :type '(choice
2116 (const :tag "Yes, only for TODO entries" t)
2117 (const :tag "Yes, including all entries" 'all-headlines)
2118 (repeat :tag "Yes, for TODOs in this list"
2119 (string :tag "TODO keyword"))
2120 (other :tag "No TODO statistics" nil)))
2122 (defcustom org-hierarchical-todo-statistics t
2123 "Non-nil means TODO statistics covers just direct children.
2124 When nil, all entries in the subtree are considered.
2125 This has only an effect if `org-provide-todo-statistics' is set.
2126 To set this to nil for only a single subtree, use a COOKIE_DATA
2127 property and include the word \"recursive\" into the value."
2128 :group 'org-todo
2129 :type 'boolean)
2131 (defcustom org-after-todo-state-change-hook nil
2132 "Hook which is run after the state of a TODO item was changed.
2133 The new state (a string with a TODO keyword, or nil) is available in the
2134 Lisp variable `state'."
2135 :group 'org-todo
2136 :type 'hook)
2138 (defvar org-blocker-hook nil
2139 "Hook for functions that are allowed to block a state change.
2141 Each function gets as its single argument a property list, see
2142 `org-trigger-hook' for more information about this list.
2144 If any of the functions in this hook returns nil, the state change
2145 is blocked.")
2147 (defvar org-trigger-hook nil
2148 "Hook for functions that are triggered by a state change.
2150 Each function gets as its single argument a property list with at least
2151 the following elements:
2153 (:type type-of-change :position pos-at-entry-start
2154 :from old-state :to new-state)
2156 Depending on the type, more properties may be present.
2158 This mechanism is currently implemented for:
2160 TODO state changes
2161 ------------------
2162 :type todo-state-change
2163 :from previous state (keyword as a string), or nil, or a symbol
2164 'todo' or 'done', to indicate the general type of state.
2165 :to new state, like in :from")
2167 (defcustom org-enforce-todo-dependencies nil
2168 "Non-nil means undone TODO entries will block switching the parent to DONE.
2169 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2170 be blocked if any prior sibling is not yet done.
2171 Finally, if the parent is blocked because of ordered siblings of its own,
2172 the child will also be blocked.
2173 This variable needs to be set before org.el is loaded, and you need to
2174 restart Emacs after a change to make the change effective. The only way
2175 to change is while Emacs is running is through the customize interface."
2176 :set (lambda (var val)
2177 (set var val)
2178 (if val
2179 (add-hook 'org-blocker-hook
2180 'org-block-todo-from-children-or-siblings-or-parent)
2181 (remove-hook 'org-blocker-hook
2182 'org-block-todo-from-children-or-siblings-or-parent)))
2183 :group 'org-todo
2184 :type 'boolean)
2186 (defcustom org-enforce-todo-checkbox-dependencies nil
2187 "Non-nil means unchecked boxes will block switching the parent to DONE.
2188 When this is nil, checkboxes have no influence on switching TODO states.
2189 When non-nil, you first need to check off all check boxes before the TODO
2190 entry can be switched to DONE.
2191 This variable needs to be set before org.el is loaded, and you need to
2192 restart Emacs after a change to make the change effective. The only way
2193 to change is while Emacs is running is through the customize interface."
2194 :set (lambda (var val)
2195 (set var val)
2196 (if val
2197 (add-hook 'org-blocker-hook
2198 'org-block-todo-from-checkboxes)
2199 (remove-hook 'org-blocker-hook
2200 'org-block-todo-from-checkboxes)))
2201 :group 'org-todo
2202 :type 'boolean)
2204 (defcustom org-treat-insert-todo-heading-as-state-change nil
2205 "Non-nil means inserting a TODO heading is treated as state change.
2206 So when the command \\[org-insert-todo-heading] is used, state change
2207 logging will apply if appropriate. When nil, the new TODO item will
2208 be inserted directly, and no logging will take place."
2209 :group 'org-todo
2210 :type 'boolean)
2212 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2213 "Non-nil means switching TODO states with S-cursor counts as state change.
2214 This is the default behavior. However, setting this to nil allows a
2215 convenient way to select a TODO state and bypass any logging associated
2216 with that."
2217 :group 'org-todo
2218 :type 'boolean)
2220 (defcustom org-todo-state-tags-triggers nil
2221 "Tag changes that should be triggered by TODO state changes.
2222 This is a list. Each entry is
2224 (state-change (tag . flag) .......)
2226 State-change can be a string with a state, and empty string to indicate the
2227 state that has no TODO keyword, or it can be one of the symbols `todo'
2228 or `done', meaning any not-done or done state, respectively."
2229 :group 'org-todo
2230 :group 'org-tags
2231 :type '(repeat
2232 (cons (choice :tag "When changing to"
2233 (const :tag "Not-done state" todo)
2234 (const :tag "Done state" done)
2235 (string :tag "State"))
2236 (repeat
2237 (cons :tag "Tag action"
2238 (string :tag "Tag")
2239 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2241 (defcustom org-log-done nil
2242 "Information to record when a task moves to the DONE state.
2244 Possible values are:
2246 nil Don't add anything, just change the keyword
2247 time Add a time stamp to the task
2248 note Prompt for a note and add it with template `org-log-note-headings'
2250 This option can also be set with on a per-file-basis with
2252 #+STARTUP: nologdone
2253 #+STARTUP: logdone
2254 #+STARTUP: lognotedone
2256 You can have local logging settings for a subtree by setting the LOGGING
2257 property to one or more of these keywords."
2258 :group 'org-todo
2259 :group 'org-progress
2260 :type '(choice
2261 (const :tag "No logging" nil)
2262 (const :tag "Record CLOSED timestamp" time)
2263 (const :tag "Record CLOSED timestamp with note." note)))
2265 ;; Normalize old uses of org-log-done.
2266 (cond
2267 ((eq org-log-done t) (setq org-log-done 'time))
2268 ((and (listp org-log-done) (memq 'done org-log-done))
2269 (setq org-log-done 'note)))
2271 (defcustom org-log-reschedule nil
2272 "Information to record when the scheduling date of a tasks is modified.
2274 Possible values are:
2276 nil Don't add anything, just change the date
2277 time Add a time stamp to the task
2278 note Prompt for a note and add it with template `org-log-note-headings'
2280 This option can also be set with on a per-file-basis with
2282 #+STARTUP: nologreschedule
2283 #+STARTUP: logreschedule
2284 #+STARTUP: lognotereschedule"
2285 :group 'org-todo
2286 :group 'org-progress
2287 :type '(choice
2288 (const :tag "No logging" nil)
2289 (const :tag "Record timestamp" time)
2290 (const :tag "Record timestamp with note." note)))
2292 (defcustom org-log-redeadline nil
2293 "Information to record when the deadline date of a tasks is modified.
2295 Possible values are:
2297 nil Don't add anything, just change the date
2298 time Add a time stamp to the task
2299 note Prompt for a note and add it with template `org-log-note-headings'
2301 This option can also be set with on a per-file-basis with
2303 #+STARTUP: nologredeadline
2304 #+STARTUP: logredeadline
2305 #+STARTUP: lognoteredeadline
2307 You can have local logging settings for a subtree by setting the LOGGING
2308 property to one or more of these keywords."
2309 :group 'org-todo
2310 :group 'org-progress
2311 :type '(choice
2312 (const :tag "No logging" nil)
2313 (const :tag "Record timestamp" time)
2314 (const :tag "Record timestamp with note." note)))
2316 (defcustom org-log-note-clock-out nil
2317 "Non-nil means record a note when clocking out of an item.
2318 This can also be configured on a per-file basis by adding one of
2319 the following lines anywhere in the buffer:
2321 #+STARTUP: lognoteclock-out
2322 #+STARTUP: nolognoteclock-out"
2323 :group 'org-todo
2324 :group 'org-progress
2325 :type 'boolean)
2327 (defcustom org-log-done-with-time t
2328 "Non-nil means the CLOSED time stamp will contain date and time.
2329 When nil, only the date will be recorded."
2330 :group 'org-progress
2331 :type 'boolean)
2333 (defcustom org-log-note-headings
2334 '((done . "CLOSING NOTE %t")
2335 (state . "State %-12s from %-12S %t")
2336 (note . "Note taken on %t")
2337 (reschedule . "Rescheduled from %S on %t")
2338 (delschedule . "Not scheduled, was %S on %t")
2339 (redeadline . "New deadline from %S on %t")
2340 (deldeadline . "Removed deadline, was %S on %t")
2341 (refile . "Refiled on %t")
2342 (clock-out . ""))
2343 "Headings for notes added to entries.
2344 The value is an alist, with the car being a symbol indicating the note
2345 context, and the cdr is the heading to be used. The heading may also be the
2346 empty string.
2347 %t in the heading will be replaced by a time stamp.
2348 %T will be an active time stamp instead the default inactive one
2349 %s will be replaced by the new TODO state, in double quotes.
2350 %S will be replaced by the old TODO state, in double quotes.
2351 %u will be replaced by the user name.
2352 %U will be replaced by the full user name.
2354 In fact, it is not a good idea to change the `state' entry, because
2355 agenda log mode depends on the format of these entries."
2356 :group 'org-todo
2357 :group 'org-progress
2358 :type '(list :greedy t
2359 (cons (const :tag "Heading when closing an item" done) string)
2360 (cons (const :tag
2361 "Heading when changing todo state (todo sequence only)"
2362 state) string)
2363 (cons (const :tag "Heading when just taking a note" note) string)
2364 (cons (const :tag "Heading when clocking out" clock-out) string)
2365 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2366 (cons (const :tag "Heading when rescheduling" reschedule) string)
2367 (cons (const :tag "Heading when changing deadline" redeadline) string)
2368 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2369 (cons (const :tag "Heading when refiling" refile) string)))
2371 (unless (assq 'note org-log-note-headings)
2372 (push '(note . "%t") org-log-note-headings))
2374 (defcustom org-log-into-drawer nil
2375 "Non-nil means insert state change notes and time stamps into a drawer.
2376 When nil, state changes notes will be inserted after the headline and
2377 any scheduling and clock lines, but not inside a drawer.
2379 The value of this variable should be the name of the drawer to use.
2380 LOGBOOK is proposed as the default drawer for this purpose, you can
2381 also set this to a string to define the drawer of your choice.
2383 A value of t is also allowed, representing \"LOGBOOK\".
2385 If this variable is set, `org-log-state-notes-insert-after-drawers'
2386 will be ignored.
2388 You can set the property LOG_INTO_DRAWER to overrule this setting for
2389 a subtree."
2390 :group 'org-todo
2391 :group 'org-progress
2392 :type '(choice
2393 (const :tag "Not into a drawer" nil)
2394 (const :tag "LOGBOOK" t)
2395 (string :tag "Other")))
2397 (if (fboundp 'defvaralias)
2398 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2400 (defun org-log-into-drawer ()
2401 "Return the value of `org-log-into-drawer', but let properties overrule.
2402 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2403 used instead of the default value."
2404 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2405 (cond
2406 ((or (not p) (equal p "nil")) org-log-into-drawer)
2407 ((equal p "t") "LOGBOOK")
2408 (t p))))
2410 (defcustom org-log-state-notes-insert-after-drawers nil
2411 "Non-nil means insert state change notes after any drawers in entry.
2412 Only the drawers that *immediately* follow the headline and the
2413 deadline/scheduled line are skipped.
2414 When nil, insert notes right after the heading and perhaps the line
2415 with deadline/scheduling if present.
2417 This variable will have no effect if `org-log-into-drawer' is
2418 set."
2419 :group 'org-todo
2420 :group 'org-progress
2421 :type 'boolean)
2423 (defcustom org-log-states-order-reversed t
2424 "Non-nil means the latest state note will be directly after heading.
2425 When nil, the state change notes will be ordered according to time."
2426 :group 'org-todo
2427 :group 'org-progress
2428 :type 'boolean)
2430 (defcustom org-todo-repeat-to-state nil
2431 "The TODO state to which a repeater should return the repeating task.
2432 By default this is the first task in a TODO sequence, or the previous state
2433 in a TODO_TYP set. But you can specify another task here.
2434 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2435 :group 'org-todo
2436 :type '(choice (const :tag "Head of sequence" nil)
2437 (string :tag "Specific state")))
2439 (defcustom org-log-repeat 'time
2440 "Non-nil means record moving through the DONE state when triggering repeat.
2441 An auto-repeating task is immediately switched back to TODO when
2442 marked DONE. If you are not logging state changes (by adding \"@\"
2443 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2444 record a closing note, there will be no record of the task moving
2445 through DONE. This variable forces taking a note anyway.
2447 nil Don't force a record
2448 time Record a time stamp
2449 note Record a note
2451 This option can also be set with on a per-file-basis with
2453 #+STARTUP: logrepeat
2454 #+STARTUP: lognoterepeat
2455 #+STARTUP: nologrepeat
2457 You can have local logging settings for a subtree by setting the LOGGING
2458 property to one or more of these keywords."
2459 :group 'org-todo
2460 :group 'org-progress
2461 :type '(choice
2462 (const :tag "Don't force a record" nil)
2463 (const :tag "Force recording the DONE state" time)
2464 (const :tag "Force recording a note with the DONE state" note)))
2467 (defgroup org-priorities nil
2468 "Priorities in Org-mode."
2469 :tag "Org Priorities"
2470 :group 'org-todo)
2472 (defcustom org-enable-priority-commands t
2473 "Non-nil means priority commands are active.
2474 When nil, these commands will be disabled, so that you never accidentally
2475 set a priority."
2476 :group 'org-priorities
2477 :type 'boolean)
2479 (defcustom org-highest-priority ?A
2480 "The highest priority of TODO items. A character like ?A, ?B etc.
2481 Must have a smaller ASCII number than `org-lowest-priority'."
2482 :group 'org-priorities
2483 :type 'character)
2485 (defcustom org-lowest-priority ?C
2486 "The lowest priority of TODO items. A character like ?A, ?B etc.
2487 Must have a larger ASCII number than `org-highest-priority'."
2488 :group 'org-priorities
2489 :type 'character)
2491 (defcustom org-default-priority ?B
2492 "The default priority of TODO items.
2493 This is the priority an item gets if no explicit priority is given.
2494 When starting to cycle on an empty priority the first step in the cycle
2495 depends on `org-priority-start-cycle-with-default'. The resulting first
2496 step priority must not exceed the range from `org-highest-priority' to
2497 `org-lowest-priority' which means that `org-default-priority' has to be
2498 in this range exclusive or inclusive the range boundaries. Else the
2499 first step refuses to set the default and the second will fall back
2500 to (depending on the command used) the highest or lowest priority."
2501 :group 'org-priorities
2502 :type 'character)
2504 (defcustom org-priority-start-cycle-with-default t
2505 "Non-nil means start with default priority when starting to cycle.
2506 When this is nil, the first step in the cycle will be (depending on the
2507 command used) one higher or lower than the default priority.
2508 See also `org-default-priority'."
2509 :group 'org-priorities
2510 :type 'boolean)
2512 (defcustom org-get-priority-function nil
2513 "Function to extract the priority from a string.
2514 The string is normally the headline. If this is nil Org computes the
2515 priority from the priority cookie like [#A] in the headline. It returns
2516 an integer, increasing by 1000 for each priority level.
2517 The user can set a different function here, which should take a string
2518 as an argument and return the numeric priority."
2519 :group 'org-priorities
2520 :type 'function)
2522 (defgroup org-time nil
2523 "Options concerning time stamps and deadlines in Org-mode."
2524 :tag "Org Time"
2525 :group 'org)
2527 (defcustom org-insert-labeled-timestamps-at-point nil
2528 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2529 When nil, these labeled time stamps are forces into the second line of an
2530 entry, just after the headline. When scheduling from the global TODO list,
2531 the time stamp will always be forced into the second line."
2532 :group 'org-time
2533 :type 'boolean)
2535 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2536 "Formats for `format-time-string' which are used for time stamps.
2537 It is not recommended to change this constant.")
2539 (defcustom org-time-stamp-rounding-minutes '(0 5)
2540 "Number of minutes to round time stamps to.
2541 These are two values, the first applies when first creating a time stamp.
2542 The second applies when changing it with the commands `S-up' and `S-down'.
2543 When changing the time stamp, this means that it will change in steps
2544 of N minutes, as given by the second value.
2546 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2547 numbers should be factors of 60, so for example 5, 10, 15.
2549 When this is larger than 1, you can still force an exact time stamp by using
2550 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2551 and by using a prefix arg to `S-up/down' to specify the exact number
2552 of minutes to shift."
2553 :group 'org-time
2554 :get #'(lambda (var) ; Make sure both elements are there
2555 (if (integerp (default-value var))
2556 (list (default-value var) 5)
2557 (default-value var)))
2558 :type '(list
2559 (integer :tag "when inserting times")
2560 (integer :tag "when modifying times")))
2562 ;; Normalize old customizations of this variable.
2563 (when (integerp org-time-stamp-rounding-minutes)
2564 (setq org-time-stamp-rounding-minutes
2565 (list org-time-stamp-rounding-minutes
2566 org-time-stamp-rounding-minutes)))
2568 (defcustom org-display-custom-times nil
2569 "Non-nil means overlay custom formats over all time stamps.
2570 The formats are defined through the variable `org-time-stamp-custom-formats'.
2571 To turn this on on a per-file basis, insert anywhere in the file:
2572 #+STARTUP: customtime"
2573 :group 'org-time
2574 :set 'set-default
2575 :type 'sexp)
2576 (make-variable-buffer-local 'org-display-custom-times)
2578 (defcustom org-time-stamp-custom-formats
2579 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2580 "Custom formats for time stamps. See `format-time-string' for the syntax.
2581 These are overlayed over the default ISO format if the variable
2582 `org-display-custom-times' is set. Time like %H:%M should be at the
2583 end of the second format. The custom formats are also honored by export
2584 commands, if custom time display is turned on at the time of export."
2585 :group 'org-time
2586 :type 'sexp)
2588 (defun org-time-stamp-format (&optional long inactive)
2589 "Get the right format for a time string."
2590 (let ((f (if long (cdr org-time-stamp-formats)
2591 (car org-time-stamp-formats))))
2592 (if inactive
2593 (concat "[" (substring f 1 -1) "]")
2594 f)))
2596 (defcustom org-time-clocksum-format "%d:%02d"
2597 "The format string used when creating CLOCKSUM lines.
2598 This is also used when org-mode generates a time duration."
2599 :group 'org-time
2600 :type 'string)
2602 (defcustom org-time-clocksum-use-fractional nil
2603 "If non-nil, \\[org-clock-display] uses fractional times.
2604 org-mode generates a time duration."
2605 :group 'org-time
2606 :type 'boolean)
2608 (defcustom org-time-clocksum-fractional-format "%.2f"
2609 "The format string used when creating CLOCKSUM lines, or when
2610 org-mode generates a time duration."
2611 :group 'org-time
2612 :type 'string)
2614 (defcustom org-deadline-warning-days 14
2615 "No. of days before expiration during which a deadline becomes active.
2616 This variable governs the display in sparse trees and in the agenda.
2617 When 0 or negative, it means use this number (the absolute value of it)
2618 even if a deadline has a different individual lead time specified.
2620 Custom commands can set this variable in the options section."
2621 :group 'org-time
2622 :group 'org-agenda-daily/weekly
2623 :type 'integer)
2625 (defcustom org-read-date-prefer-future t
2626 "Non-nil means assume future for incomplete date input from user.
2627 This affects the following situations:
2628 1. The user gives a month but not a year.
2629 For example, if it is April and you enter \"feb 2\", this will be read
2630 as Feb 2, *next* year. \"May 5\", however, will be this year.
2631 2. The user gives a day, but no month.
2632 For example, if today is the 15th, and you enter \"3\", Org-mode will
2633 read this as the third of *next* month. However, if you enter \"17\",
2634 it will be considered as *this* month.
2636 If you set this variable to the symbol `time', then also the following
2637 will work:
2639 3. If the user gives a time, but no day. If the time is before now,
2640 to will be interpreted as tomorrow.
2642 Currently none of this works for ISO week specifications.
2644 When this option is nil, the current day, month and year will always be
2645 used as defaults.
2647 See also `org-agenda-jump-prefer-future'."
2648 :group 'org-time
2649 :type '(choice
2650 (const :tag "Never" nil)
2651 (const :tag "Check month and day" t)
2652 (const :tag "Check month, day, and time" time)))
2654 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2655 "Should the agenda jump command prefer the future for incomplete dates?
2656 The default is to do the same as configured in `org-read-date-prefer-future'.
2657 But you can also set a deviating value here.
2658 This may t or nil, or the symbol `org-read-date-prefer-future'."
2659 :group 'org-agenda
2660 :group 'org-time
2661 :type '(choice
2662 (const :tag "Use org-read-date-prefer-future"
2663 org-read-date-prefer-future)
2664 (const :tag "Never" nil)
2665 (const :tag "Always" t)))
2667 (defcustom org-read-date-force-compatible-dates t
2668 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2670 Depending on the system Emacs is running on, certain dates cannot
2671 be represented with the type used internally to represent time.
2672 Dates between 1970-1-1 and 2038-1-1 can always be represented
2673 correctly. Some systems allow for earlier dates, some for later,
2674 some for both. One way to find out it to insert any date into an
2675 Org buffer, putting the cursor on the year and hitting S-up and
2676 S-down to test the range.
2678 When this variable is set to t, the date/time prompt will not let
2679 you specify dates outside the 1970-2037 range, so it is certain that
2680 these dates will work in whatever version of Emacs you are
2681 running, and also that you can move a file from one Emacs implementation
2682 to another. WHenever Org is forcing the year for you, it will display
2683 a message and beep.
2685 When this variable is nil, Org will check if the date is
2686 representable in the specific Emacs implementation you are using.
2687 If not, it will force a year, usually the current year, and beep
2688 to remind you. Currently this setting is not recommended because
2689 the likelihood that you will open your Org files in an Emacs that
2690 has limited date range is not negligible.
2692 A workaround for this problem is to use diary sexp dates for time
2693 stamps outside of this range."
2694 :group 'org-time
2695 :type 'boolean)
2697 (defcustom org-read-date-display-live t
2698 "Non-nil means display current interpretation of date prompt live.
2699 This display will be in an overlay, in the minibuffer."
2700 :group 'org-time
2701 :type 'boolean)
2703 (defcustom org-read-date-popup-calendar t
2704 "Non-nil means pop up a calendar when prompting for a date.
2705 In the calendar, the date can be selected with mouse-1. However, the
2706 minibuffer will also be active, and you can simply enter the date as well.
2707 When nil, only the minibuffer will be available."
2708 :group 'org-time
2709 :type 'boolean)
2710 (if (fboundp 'defvaralias)
2711 (defvaralias 'org-popup-calendar-for-date-prompt
2712 'org-read-date-popup-calendar))
2714 (defcustom org-read-date-minibuffer-setup-hook nil
2715 "Hook to be used to set up keys for the date/time interface.
2716 Add key definitions to `minibuffer-local-map', which will be a temporary
2717 copy."
2718 :group 'org-time
2719 :type 'hook)
2721 (defcustom org-extend-today-until 0
2722 "The hour when your day really ends. Must be an integer.
2723 This has influence for the following applications:
2724 - When switching the agenda to \"today\". It it is still earlier than
2725 the time given here, the day recognized as TODAY is actually yesterday.
2726 - When a date is read from the user and it is still before the time given
2727 here, the current date and time will be assumed to be yesterday, 23:59.
2728 Also, timestamps inserted in remember templates follow this rule.
2730 IMPORTANT: This is a feature whose implementation is and likely will
2731 remain incomplete. Really, it is only here because past midnight seems to
2732 be the favorite working time of John Wiegley :-)"
2733 :group 'org-time
2734 :type 'integer)
2736 (defcustom org-edit-timestamp-down-means-later nil
2737 "Non-nil means S-down will increase the time in a time stamp.
2738 When nil, S-up will increase."
2739 :group 'org-time
2740 :type 'boolean)
2742 (defcustom org-calendar-follow-timestamp-change t
2743 "Non-nil means make the calendar window follow timestamp changes.
2744 When a timestamp is modified and the calendar window is visible, it will be
2745 moved to the new date."
2746 :group 'org-time
2747 :type 'boolean)
2749 (defgroup org-tags nil
2750 "Options concerning tags in Org-mode."
2751 :tag "Org Tags"
2752 :group 'org)
2754 (defcustom org-tag-alist nil
2755 "List of tags allowed in Org-mode files.
2756 When this list is nil, Org-mode will base TAG input on what is already in the
2757 buffer.
2758 The value of this variable is an alist, the car of each entry must be a
2759 keyword as a string, the cdr may be a character that is used to select
2760 that tag through the fast-tag-selection interface.
2761 See the manual for details."
2762 :group 'org-tags
2763 :type '(repeat
2764 (choice
2765 (cons (string :tag "Tag name")
2766 (character :tag "Access char"))
2767 (list :tag "Start radio group"
2768 (const :startgroup)
2769 (option (string :tag "Group description")))
2770 (list :tag "End radio group"
2771 (const :endgroup)
2772 (option (string :tag "Group description")))
2773 (const :tag "New line" (:newline)))))
2775 (defcustom org-tag-persistent-alist nil
2776 "List of tags that will always appear in all Org-mode files.
2777 This is in addition to any in buffer settings or customizations
2778 of `org-tag-alist'.
2779 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2780 The value of this variable is an alist, the car of each entry must be a
2781 keyword as a string, the cdr may be a character that is used to select
2782 that tag through the fast-tag-selection interface.
2783 See the manual for details.
2784 To disable these tags on a per-file basis, insert anywhere in the file:
2785 #+STARTUP: noptag"
2786 :group 'org-tags
2787 :type '(repeat
2788 (choice
2789 (cons (string :tag "Tag name")
2790 (character :tag "Access char"))
2791 (const :tag "Start radio group" (:startgroup))
2792 (const :tag "End radio group" (:endgroup))
2793 (const :tag "New line" (:newline)))))
2795 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2796 "If non-nil, always offer completion for all tags of all agenda files.
2797 Instead of customizing this variable directly, you might want to
2798 set it locally for capture buffers, because there no list of
2799 tags in that file can be created dynamically (there are none).
2801 (add-hook 'org-capture-mode-hook
2802 (lambda ()
2803 (set (make-local-variable
2804 'org-complete-tags-always-offer-all-agenda-tags)
2805 t)))"
2806 :group 'org-tags
2807 :type 'boolean)
2809 (defvar org-file-tags nil
2810 "List of tags that can be inherited by all entries in the file.
2811 The tags will be inherited if the variable `org-use-tag-inheritance'
2812 says they should be.
2813 This variable is populated from #+FILETAGS lines.")
2815 (defcustom org-use-fast-tag-selection 'auto
2816 "Non-nil means use fast tag selection scheme.
2817 This is a special interface to select and deselect tags with single keys.
2818 When nil, fast selection is never used.
2819 When the symbol `auto', fast selection is used if and only if selection
2820 characters for tags have been configured, either through the variable
2821 `org-tag-alist' or through a #+TAGS line in the buffer.
2822 When t, fast selection is always used and selection keys are assigned
2823 automatically if necessary."
2824 :group 'org-tags
2825 :type '(choice
2826 (const :tag "Always" t)
2827 (const :tag "Never" nil)
2828 (const :tag "When selection characters are configured" 'auto)))
2830 (defcustom org-fast-tag-selection-single-key nil
2831 "Non-nil means fast tag selection exits after first change.
2832 When nil, you have to press RET to exit it.
2833 During fast tag selection, you can toggle this flag with `C-c'.
2834 This variable can also have the value `expert'. In this case, the window
2835 displaying the tags menu is not even shown, until you press C-c again."
2836 :group 'org-tags
2837 :type '(choice
2838 (const :tag "No" nil)
2839 (const :tag "Yes" t)
2840 (const :tag "Expert" expert)))
2842 (defvar org-fast-tag-selection-include-todo nil
2843 "Non-nil means fast tags selection interface will also offer TODO states.
2844 This is an undocumented feature, you should not rely on it.")
2846 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2847 "The column to which tags should be indented in a headline.
2848 If this number is positive, it specifies the column. If it is negative,
2849 it means that the tags should be flushright to that column. For example,
2850 -80 works well for a normal 80 character screen."
2851 :group 'org-tags
2852 :type 'integer)
2854 (defcustom org-auto-align-tags t
2855 "Non-nil keeps tags aligned when modifying headlines.
2856 Some operations (i.e. demoting) change the length of a headline and
2857 therefore shift the tags around. With this option turned on, after
2858 each such operation the tags are again aligned to `org-tags-column'."
2859 :group 'org-tags
2860 :type 'boolean)
2862 (defcustom org-use-tag-inheritance t
2863 "Non-nil means tags in levels apply also for sublevels.
2864 When nil, only the tags directly given in a specific line apply there.
2865 This may also be a list of tags that should be inherited, or a regexp that
2866 matches tags that should be inherited. Additional control is possible
2867 with the variable `org-tags-exclude-from-inheritance' which gives an
2868 explicit list of tags to be excluded from inheritance., even if the value of
2869 `org-use-tag-inheritance' would select it for inheritance.
2871 If this option is t, a match early-on in a tree can lead to a large
2872 number of matches in the subtree when constructing the agenda or creating
2873 a sparse tree. If you only want to see the first match in a tree during
2874 a search, check out the variable `org-tags-match-list-sublevels'."
2875 :group 'org-tags
2876 :type '(choice
2877 (const :tag "Not" nil)
2878 (const :tag "Always" t)
2879 (repeat :tag "Specific tags" (string :tag "Tag"))
2880 (regexp :tag "Tags matched by regexp")))
2882 (defcustom org-tags-exclude-from-inheritance nil
2883 "List of tags that should never be inherited.
2884 This is a way to exclude a few tags from inheritance. For way to do
2885 the opposite, to actively allow inheritance for selected tags,
2886 see the variable `org-use-tag-inheritance'."
2887 :group 'org-tags
2888 :type '(repeat (string :tag "Tag")))
2890 (defun org-tag-inherit-p (tag)
2891 "Check if TAG is one that should be inherited."
2892 (cond
2893 ((member tag org-tags-exclude-from-inheritance) nil)
2894 ((eq org-use-tag-inheritance t) t)
2895 ((not org-use-tag-inheritance) nil)
2896 ((stringp org-use-tag-inheritance)
2897 (string-match org-use-tag-inheritance tag))
2898 ((listp org-use-tag-inheritance)
2899 (member tag org-use-tag-inheritance))
2900 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2902 (defcustom org-tags-match-list-sublevels t
2903 "Non-nil means list also sublevels of headlines matching a search.
2904 This variable applies to tags/property searches, and also to stuck
2905 projects because this search is based on a tags match as well.
2907 When set to the symbol `indented', sublevels are indented with
2908 leading dots.
2910 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2911 the sublevels of a headline matching a tag search often also match
2912 the same search. Listing all of them can create very long lists.
2913 Setting this variable to nil causes subtrees of a match to be skipped.
2915 This variable is semi-obsolete and probably should always be true. It
2916 is better to limit inheritance to certain tags using the variables
2917 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2918 :group 'org-tags
2919 :type '(choice
2920 (const :tag "No, don't list them" nil)
2921 (const :tag "Yes, do list them" t)
2922 (const :tag "List them, indented with leading dots" indented)))
2924 (defcustom org-tags-sort-function nil
2925 "When set, tags are sorted using this function as a comparator."
2926 :group 'org-tags
2927 :type '(choice
2928 (const :tag "No sorting" nil)
2929 (const :tag "Alphabetical" string<)
2930 (const :tag "Reverse alphabetical" string>)
2931 (function :tag "Custom function" nil)))
2933 (defvar org-tags-history nil
2934 "History of minibuffer reads for tags.")
2935 (defvar org-last-tags-completion-table nil
2936 "The last used completion table for tags.")
2937 (defvar org-after-tags-change-hook nil
2938 "Hook that is run after the tags in a line have changed.")
2940 (defgroup org-properties nil
2941 "Options concerning properties in Org-mode."
2942 :tag "Org Properties"
2943 :group 'org)
2945 (defcustom org-property-format "%-10s %s"
2946 "How property key/value pairs should be formatted by `indent-line'.
2947 When `indent-line' hits a property definition, it will format the line
2948 according to this format, mainly to make sure that the values are
2949 lined-up with respect to each other."
2950 :group 'org-properties
2951 :type 'string)
2953 (defcustom org-use-property-inheritance nil
2954 "Non-nil means properties apply also for sublevels.
2956 This setting is chiefly used during property searches. Turning it on can
2957 cause significant overhead when doing a search, which is why it is not
2958 on by default.
2960 When nil, only the properties directly given in the current entry count.
2961 When t, every property is inherited. The value may also be a list of
2962 properties that should have inheritance, or a regular expression matching
2963 properties that should be inherited.
2965 However, note that some special properties use inheritance under special
2966 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2967 and the properties ending in \"_ALL\" when they are used as descriptor
2968 for valid values of a property.
2970 Note for programmers:
2971 When querying an entry with `org-entry-get', you can control if inheritance
2972 should be used. By default, `org-entry-get' looks only at the local
2973 properties. You can request inheritance by setting the inherit argument
2974 to t (to force inheritance) or to `selective' (to respect the setting
2975 in this variable)."
2976 :group 'org-properties
2977 :type '(choice
2978 (const :tag "Not" nil)
2979 (const :tag "Always" t)
2980 (repeat :tag "Specific properties" (string :tag "Property"))
2981 (regexp :tag "Properties matched by regexp")))
2983 (defun org-property-inherit-p (property)
2984 "Check if PROPERTY is one that should be inherited."
2985 (cond
2986 ((eq org-use-property-inheritance t) t)
2987 ((not org-use-property-inheritance) nil)
2988 ((stringp org-use-property-inheritance)
2989 (string-match org-use-property-inheritance property))
2990 ((listp org-use-property-inheritance)
2991 (member property org-use-property-inheritance))
2992 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2994 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2995 "The default column format, if no other format has been defined.
2996 This variable can be set on the per-file basis by inserting a line
2998 #+COLUMNS: %25ITEM ....."
2999 :group 'org-properties
3000 :type 'string)
3002 (defcustom org-columns-ellipses ".."
3003 "The ellipses to be used when a field in column view is truncated.
3004 When this is the empty string, as many characters as possible are shown,
3005 but then there will be no visual indication that the field has been truncated.
3006 When this is a string of length N, the last N characters of a truncated
3007 field are replaced by this string. If the column is narrower than the
3008 ellipses string, only part of the ellipses string will be shown."
3009 :group 'org-properties
3010 :type 'string)
3012 (defcustom org-columns-modify-value-for-display-function nil
3013 "Function that modifies values for display in column view.
3014 For example, it can be used to cut out a certain part from a time stamp.
3015 The function must take 2 arguments:
3017 column-title The title of the column (*not* the property name)
3018 value The value that should be modified.
3020 The function should return the value that should be displayed,
3021 or nil if the normal value should be used."
3022 :group 'org-properties
3023 :type 'function)
3025 (defcustom org-effort-property "Effort"
3026 "The property that is being used to keep track of effort estimates.
3027 Effort estimates given in this property need to have the format H:MM."
3028 :group 'org-properties
3029 :group 'org-progress
3030 :type '(string :tag "Property"))
3032 (defconst org-global-properties-fixed
3033 '(("VISIBILITY_ALL" . "folded children content all")
3034 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3035 "List of property/value pairs that can be inherited by any entry.
3037 These are fixed values, for the preset properties. The user variable
3038 that can be used to add to this list is `org-global-properties'.
3040 The entries in this list are cons cells where the car is a property
3041 name and cdr is a string with the value. If the value represents
3042 multiple items like an \"_ALL\" property, separate the items by
3043 spaces.")
3045 (defcustom org-global-properties nil
3046 "List of property/value pairs that can be inherited by any entry.
3048 This list will be combined with the constant `org-global-properties-fixed'.
3050 The entries in this list are cons cells where the car is a property
3051 name and cdr is a string with the value.
3053 You can set buffer-local values for the same purpose in the variable
3054 `org-file-properties' this by adding lines like
3056 #+PROPERTY: NAME VALUE"
3057 :group 'org-properties
3058 :type '(repeat
3059 (cons (string :tag "Property")
3060 (string :tag "Value"))))
3062 (defvar org-file-properties nil
3063 "List of property/value pairs that can be inherited by any entry.
3064 Valid for the current buffer.
3065 This variable is populated from #+PROPERTY lines.")
3066 (make-variable-buffer-local 'org-file-properties)
3068 (defgroup org-agenda nil
3069 "Options concerning agenda views in Org-mode."
3070 :tag "Org Agenda"
3071 :group 'org)
3073 (defvar org-category nil
3074 "Variable used by org files to set a category for agenda display.
3075 Such files should use a file variable to set it, for example
3077 # -*- mode: org; org-category: \"ELisp\"
3079 or contain a special line
3081 #+CATEGORY: ELisp
3083 If the file does not specify a category, then file's base name
3084 is used instead.")
3085 (make-variable-buffer-local 'org-category)
3086 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3088 (defcustom org-agenda-files nil
3089 "The files to be used for agenda display.
3090 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3091 \\[org-remove-file]. You can also use customize to edit the list.
3093 If an entry is a directory, all files in that directory that are matched by
3094 `org-agenda-file-regexp' will be part of the file list.
3096 If the value of the variable is not a list but a single file name, then
3097 the list of agenda files is actually stored and maintained in that file, one
3098 agenda file per line. In this file paths can be given relative to
3099 `org-directory'. Tilde expansion and environment variable substitution
3100 are also made."
3101 :group 'org-agenda
3102 :type '(choice
3103 (repeat :tag "List of files and directories" file)
3104 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3106 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3107 "Regular expression to match files for `org-agenda-files'.
3108 If any element in the list in that variable contains a directory instead
3109 of a normal file, all files in that directory that are matched by this
3110 regular expression will be included."
3111 :group 'org-agenda
3112 :type 'regexp)
3114 (defcustom org-agenda-text-search-extra-files nil
3115 "List of extra files to be searched by text search commands.
3116 These files will be search in addition to the agenda files by the
3117 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3118 Note that these files will only be searched for text search commands,
3119 not for the other agenda views like todo lists, tag searches or the weekly
3120 agenda. This variable is intended to list notes and possibly archive files
3121 that should also be searched by these two commands.
3122 In fact, if the first element in the list is the symbol `agenda-archives',
3123 than all archive files of all agenda files will be added to the search
3124 scope."
3125 :group 'org-agenda
3126 :type '(set :greedy t
3127 (const :tag "Agenda Archives" agenda-archives)
3128 (repeat :inline t (file))))
3130 (if (fboundp 'defvaralias)
3131 (defvaralias 'org-agenda-multi-occur-extra-files
3132 'org-agenda-text-search-extra-files))
3134 (defcustom org-agenda-skip-unavailable-files nil
3135 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3136 A nil value means to remove them, after a query, from the list."
3137 :group 'org-agenda
3138 :type 'boolean)
3140 (defcustom org-calendar-to-agenda-key [?c]
3141 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3142 The command `org-calendar-goto-agenda' will be bound to this key. The
3143 default is the character `c' because then `c' can be used to switch back and
3144 forth between agenda and calendar."
3145 :group 'org-agenda
3146 :type 'sexp)
3148 (defcustom org-calendar-agenda-action-key [?k]
3149 "The key to be installed in `calendar-mode-map' for agenda-action.
3150 The command `org-agenda-action' will be bound to this key. The
3151 default is the character `k' because we use the same key in the agenda."
3152 :group 'org-agenda
3153 :type 'sexp)
3155 (defcustom org-calendar-insert-diary-entry-key [?i]
3156 "The key to be installed in `calendar-mode-map' for adding diary entries.
3157 This option is irrelevant until `org-agenda-diary-file' has been configured
3158 to point to an Org-mode file. When that is the case, the command
3159 `org-agenda-diary-entry' will be bound to the key given here, by default
3160 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3161 if you want to continue doing this, you need to change this to a different
3162 key."
3163 :group 'org-agenda
3164 :type 'sexp)
3166 (defcustom org-agenda-diary-file 'diary-file
3167 "File to which to add new entries with the `i' key in agenda and calendar.
3168 When this is the symbol `diary-file', the functionality in the Emacs
3169 calendar will be used to add entries to the `diary-file'. But when this
3170 points to a file, `org-agenda-diary-entry' will be used instead."
3171 :group 'org-agenda
3172 :type '(choice
3173 (const :tag "The standard Emacs diary file" diary-file)
3174 (file :tag "Special Org file diary entries")))
3176 (eval-after-load "calendar"
3177 '(progn
3178 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3179 'org-calendar-goto-agenda)
3180 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3181 'org-agenda-action)
3182 (add-hook 'calendar-mode-hook
3183 (lambda ()
3184 (unless (eq org-agenda-diary-file 'diary-file)
3185 (define-key calendar-mode-map
3186 org-calendar-insert-diary-entry-key
3187 'org-agenda-diary-entry))))))
3189 (defgroup org-latex nil
3190 "Options for embedding LaTeX code into Org-mode."
3191 :tag "Org LaTeX"
3192 :group 'org)
3194 (defcustom org-format-latex-options
3195 '(:foreground default :background default :scale 1.0
3196 :html-foreground "Black" :html-background "Transparent"
3197 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3198 "Options for creating images from LaTeX fragments.
3199 This is a property list with the following properties:
3200 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3201 `default' means use the foreground of the default face.
3202 :background the background color, or \"Transparent\".
3203 `default' means use the background of the default face.
3204 :scale a scaling factor for the size of the images, to get more pixels
3205 :html-foreground, :html-background, :html-scale
3206 the same numbers for HTML export.
3207 :matchers a list indicating which matchers should be used to
3208 find LaTeX fragments. Valid members of this list are:
3209 \"begin\" find environments
3210 \"$1\" find single characters surrounded by $.$
3211 \"$\" find math expressions surrounded by $...$
3212 \"$$\" find math expressions surrounded by $$....$$
3213 \"\\(\" find math expressions surrounded by \\(...\\)
3214 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3215 :group 'org-latex
3216 :type 'plist)
3218 (defcustom org-format-latex-signal-error t
3219 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3220 When nil, just push out a message."
3221 :group 'org-latex
3222 :type 'boolean)
3224 (defcustom org-format-latex-header "\\documentclass{article}
3225 \\usepackage[usenames]{color}
3226 \\usepackage{amsmath}
3227 \\usepackage[mathscr]{eucal}
3228 \\pagestyle{empty} % do not remove
3229 \[PACKAGES]
3230 \[DEFAULT-PACKAGES]
3231 % The settings below are copied from fullpage.sty
3232 \\setlength{\\textwidth}{\\paperwidth}
3233 \\addtolength{\\textwidth}{-3cm}
3234 \\setlength{\\oddsidemargin}{1.5cm}
3235 \\addtolength{\\oddsidemargin}{-2.54cm}
3236 \\setlength{\\evensidemargin}{\\oddsidemargin}
3237 \\setlength{\\textheight}{\\paperheight}
3238 \\addtolength{\\textheight}{-\\headheight}
3239 \\addtolength{\\textheight}{-\\headsep}
3240 \\addtolength{\\textheight}{-\\footskip}
3241 \\addtolength{\\textheight}{-3cm}
3242 \\setlength{\\topmargin}{1.5cm}
3243 \\addtolength{\\topmargin}{-2.54cm}"
3244 "The document header used for processing LaTeX fragments.
3245 It is imperative that this header make sure that no page number
3246 appears on the page. The package defined in the variables
3247 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3248 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3249 will be appended."
3250 :group 'org-latex
3251 :type 'string)
3253 (defvar org-format-latex-header-extra nil)
3255 (defun org-set-packages-alist (var val)
3256 "Set the packages alist and make sure it has 3 elements per entry."
3257 (set var (mapcar (lambda (x)
3258 (if (and (consp x) (= (length x) 2))
3259 (list (car x) (nth 1 x) t)
3261 val)))
3263 (defun org-get-packages-alist (var)
3265 "Get the packages alist and make sure it has 3 elements per entry."
3266 (mapcar (lambda (x)
3267 (if (and (consp x) (= (length x) 2))
3268 (list (car x) (nth 1 x) t)
3270 (default-value var)))
3272 ;; The following variables are defined here because is it also used
3273 ;; when formatting latex fragments. Originally it was part of the
3274 ;; LaTeX exporter, which is why the name includes "export".
3275 (defcustom org-export-latex-default-packages-alist
3276 '(("AUTO" "inputenc" t)
3277 ("T1" "fontenc" t)
3278 ("" "fixltx2e" nil)
3279 ("" "graphicx" t)
3280 ("" "longtable" nil)
3281 ("" "float" nil)
3282 ("" "wrapfig" nil)
3283 ("" "soul" t)
3284 ("" "textcomp" t)
3285 ("" "marvosym" t)
3286 ("" "wasysym" t)
3287 ("" "latexsym" t)
3288 ("" "amssymb" t)
3289 ("" "hyperref" nil)
3290 "\\tolerance=1000"
3292 "Alist of default packages to be inserted in the header.
3293 Change this only if one of the packages here causes an incompatibility
3294 with another package you are using.
3295 The packages in this list are needed by one part or another of Org-mode
3296 to function properly.
3298 - inputenc, fontenc: for basic font and character selection
3299 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3300 for interpreting the entities in `org-entities'. You can skip some of these
3301 packages if you don't use any of the symbols in it.
3302 - graphicx: for including images
3303 - float, wrapfig: for figure placement
3304 - longtable: for long tables
3305 - hyperref: for cross references
3307 Therefore you should not modify this variable unless you know what you
3308 are doing. The one reason to change it anyway is that you might be loading
3309 some other package that conflicts with one of the default packages.
3310 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3311 If SNIPPET-FLAG is t, the package also needs to be included when
3312 compiling LaTeX snippets into images for inclusion into HTML."
3313 :group 'org-export-latex
3314 :set 'org-set-packages-alist
3315 :get 'org-get-packages-alist
3316 :type '(repeat
3317 (choice
3318 (list :tag "options/package pair"
3319 (string :tag "options")
3320 (string :tag "package")
3321 (boolean :tag "Snippet"))
3322 (string :tag "A line of LaTeX"))))
3324 (defcustom org-export-latex-packages-alist nil
3325 "Alist of packages to be inserted in every LaTeX header.
3326 These will be inserted after `org-export-latex-default-packages-alist'.
3327 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3328 SNIPPET-FLAG, when t, indicates that this package is also needed when
3329 turning LaTeX snippets into images for inclusion into HTML.
3330 Make sure that you only list packages here which:
3331 - you want in every file
3332 - do not conflict with the default packages in
3333 `org-export-latex-default-packages-alist'
3334 - do not conflict with the setup in `org-format-latex-header'."
3335 :group 'org-export-latex
3336 :set 'org-set-packages-alist
3337 :get 'org-get-packages-alist
3338 :type '(repeat
3339 (choice
3340 (list :tag "options/package pair"
3341 (string :tag "options")
3342 (string :tag "package")
3343 (boolean :tag "Snippet"))
3344 (string :tag "A line of LaTeX"))))
3347 (defgroup org-appearance nil
3348 "Settings for Org-mode appearance."
3349 :tag "Org Appearance"
3350 :group 'org)
3352 (defcustom org-level-color-stars-only nil
3353 "Non-nil means fontify only the stars in each headline.
3354 When nil, the entire headline is fontified.
3355 Changing it requires restart of `font-lock-mode' to become effective
3356 also in regions already fontified."
3357 :group 'org-appearance
3358 :type 'boolean)
3360 (defcustom org-hide-leading-stars nil
3361 "Non-nil means hide the first N-1 stars in a headline.
3362 This works by using the face `org-hide' for these stars. This
3363 face is white for a light background, and black for a dark
3364 background. You may have to customize the face `org-hide' to
3365 make this work.
3366 Changing it requires restart of `font-lock-mode' to become effective
3367 also in regions already fontified.
3368 You may also set this on a per-file basis by adding one of the following
3369 lines to the buffer:
3371 #+STARTUP: hidestars
3372 #+STARTUP: showstars"
3373 :group 'org-appearance
3374 :type 'boolean)
3376 (defcustom org-hidden-keywords nil
3377 "List of symbols corresponding to keywords to be hidden the org buffer.
3378 For example, a value '(title) for this list will make the document's title
3379 appear in the buffer without the initial #+TITLE: keyword."
3380 :group 'org-appearance
3381 :type '(set (const :tag "#+AUTHOR" author)
3382 (const :tag "#+DATE" date)
3383 (const :tag "#+EMAIL" email)
3384 (const :tag "#+TITLE" title)))
3386 (defcustom org-fontify-done-headline nil
3387 "Non-nil means change the face of a headline if it is marked DONE.
3388 Normally, only the TODO/DONE keyword indicates the state of a headline.
3389 When this is non-nil, the headline after the keyword is set to the
3390 `org-headline-done' as an additional indication."
3391 :group 'org-appearance
3392 :type 'boolean)
3394 (defcustom org-fontify-emphasized-text t
3395 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3396 Changing this variable requires a restart of Emacs to take effect."
3397 :group 'org-appearance
3398 :type 'boolean)
3400 (defcustom org-fontify-whole-heading-line nil
3401 "Non-nil means fontify the whole line for headings.
3402 This is useful when setting a background color for the
3403 org-level-* faces."
3404 :group 'org-appearance
3405 :type 'boolean)
3407 (defcustom org-highlight-latex-fragments-and-specials nil
3408 "Non-nil means fontify what is treated specially by the exporters."
3409 :group 'org-appearance
3410 :type 'boolean)
3412 (defcustom org-hide-emphasis-markers nil
3413 "Non-nil mean font-lock should hide the emphasis marker characters."
3414 :group 'org-appearance
3415 :type 'boolean)
3417 (defcustom org-pretty-entities nil
3418 "Non-nil means show entities as UTF8 characters.
3419 When nil, the \\name form remains in the buffer."
3420 :group 'org-appearance
3421 :type 'boolean)
3423 (defcustom org-pretty-entities-include-sub-superscripts t
3424 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3425 :group 'org-appearance
3426 :type 'boolean)
3428 (defvar org-emph-re nil
3429 "Regular expression for matching emphasis.
3430 After a match, the match groups contain these elements:
3431 0 The match of the full regular expression, including the characters
3432 before and after the proper match
3433 1 The character before the proper match, or empty at beginning of line
3434 2 The proper match, including the leading and trailing markers
3435 3 The leading marker like * or /, indicating the type of highlighting
3436 4 The text between the emphasis markers, not including the markers
3437 5 The character after the match, empty at the end of a line")
3438 (defvar org-verbatim-re nil
3439 "Regular expression for matching verbatim text.")
3440 (defvar org-emphasis-regexp-components) ; defined just below
3441 (defvar org-emphasis-alist) ; defined just below
3442 (defun org-set-emph-re (var val)
3443 "Set variable and compute the emphasis regular expression."
3444 (set var val)
3445 (when (and (boundp 'org-emphasis-alist)
3446 (boundp 'org-emphasis-regexp-components)
3447 org-emphasis-alist org-emphasis-regexp-components)
3448 (let* ((e org-emphasis-regexp-components)
3449 (pre (car e))
3450 (post (nth 1 e))
3451 (border (nth 2 e))
3452 (body (nth 3 e))
3453 (nl (nth 4 e))
3454 (body1 (concat body "*?"))
3455 (markers (mapconcat 'car org-emphasis-alist ""))
3456 (vmarkers (mapconcat
3457 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3458 org-emphasis-alist "")))
3459 ;; make sure special characters appear at the right position in the class
3460 (if (string-match "\\^" markers)
3461 (setq markers (concat (replace-match "" t t markers) "^")))
3462 (if (string-match "-" markers)
3463 (setq markers (concat (replace-match "" t t markers) "-")))
3464 (if (string-match "\\^" vmarkers)
3465 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3466 (if (string-match "-" vmarkers)
3467 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3468 (if (> nl 0)
3469 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3470 (int-to-string nl) "\\}")))
3471 ;; Make the regexp
3472 (setq org-emph-re
3473 (concat "\\([" pre "]\\|^\\)"
3474 "\\("
3475 "\\([" markers "]\\)"
3476 "\\("
3477 "[^" border "]\\|"
3478 "[^" border "]"
3479 body1
3480 "[^" border "]"
3481 "\\)"
3482 "\\3\\)"
3483 "\\([" post "]\\|$\\)"))
3484 (setq org-verbatim-re
3485 (concat "\\([" pre "]\\|^\\)"
3486 "\\("
3487 "\\([" vmarkers "]\\)"
3488 "\\("
3489 "[^" border "]\\|"
3490 "[^" border "]"
3491 body1
3492 "[^" border "]"
3493 "\\)"
3494 "\\3\\)"
3495 "\\([" post "]\\|$\\)")))))
3497 (defcustom org-emphasis-regexp-components
3498 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3499 "Components used to build the regular expression for emphasis.
3500 This is a list with five entries. Terminology: In an emphasis string
3501 like \" *strong word* \", we call the initial space PREMATCH, the final
3502 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3503 and \"trong wor\" is the body. The different components in this variable
3504 specify what is allowed/forbidden in each part:
3506 pre Chars allowed as prematch. Beginning of line will be allowed too.
3507 post Chars allowed as postmatch. End of line will be allowed too.
3508 border The chars *forbidden* as border characters.
3509 body-regexp A regexp like \".\" to match a body character. Don't use
3510 non-shy groups here, and don't allow newline here.
3511 newline The maximum number of newlines allowed in an emphasis exp.
3513 Use customize to modify this, or restart Emacs after changing it."
3514 :group 'org-appearance
3515 :set 'org-set-emph-re
3516 :type '(list
3517 (sexp :tag "Allowed chars in pre ")
3518 (sexp :tag "Allowed chars in post ")
3519 (sexp :tag "Forbidden chars in border ")
3520 (sexp :tag "Regexp for body ")
3521 (integer :tag "number of newlines allowed")
3522 (option (boolean :tag "Please ignore this button"))))
3524 (defcustom org-emphasis-alist
3525 `(("*" bold "<b>" "</b>")
3526 ("/" italic "<i>" "</i>")
3527 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3528 ("=" org-code "<code>" "</code>" verbatim)
3529 ("~" org-verbatim "<code>" "</code>" verbatim)
3530 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3531 "<del>" "</del>")
3533 "Special syntax for emphasized text.
3534 Text starting and ending with a special character will be emphasized, for
3535 example *bold*, _underlined_ and /italic/. This variable sets the marker
3536 characters, the face to be used by font-lock for highlighting in Org-mode
3537 Emacs buffers, and the HTML tags to be used for this.
3538 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3539 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3540 Use customize to modify this, or restart Emacs after changing it."
3541 :group 'org-appearance
3542 :set 'org-set-emph-re
3543 :type '(repeat
3544 (list
3545 (string :tag "Marker character")
3546 (choice
3547 (face :tag "Font-lock-face")
3548 (plist :tag "Face property list"))
3549 (string :tag "HTML start tag")
3550 (string :tag "HTML end tag")
3551 (option (const verbatim)))))
3553 (defvar org-protecting-blocks
3554 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3555 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3556 This is needed for font-lock setup.")
3558 ;;; Miscellaneous options
3560 (defgroup org-completion nil
3561 "Completion in Org-mode."
3562 :tag "Org Completion"
3563 :group 'org)
3565 (defcustom org-completion-use-ido nil
3566 "Non-nil means use ido completion wherever possible.
3567 Note that `ido-mode' must be active for this variable to be relevant.
3568 If you decide to turn this variable on, you might well want to turn off
3569 `org-outline-path-complete-in-steps'.
3570 See also `org-completion-use-iswitchb'."
3571 :group 'org-completion
3572 :type 'boolean)
3574 (defcustom org-completion-use-iswitchb nil
3575 "Non-nil means use iswitchb completion wherever possible.
3576 Note that `iswitchb-mode' must be active for this variable to be relevant.
3577 If you decide to turn this variable on, you might well want to turn off
3578 `org-outline-path-complete-in-steps'.
3579 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3580 :group 'org-completion
3581 :type 'boolean)
3583 (defcustom org-completion-fallback-command 'hippie-expand
3584 "The expansion command called by \\[pcomplete] in normal context.
3585 Normal means, no org-mode-specific context."
3586 :group 'org-completion
3587 :type 'function)
3589 ;;; Functions and variables from their packages
3590 ;; Declared here to avoid compiler warnings
3592 ;; XEmacs only
3593 (defvar outline-mode-menu-heading)
3594 (defvar outline-mode-menu-show)
3595 (defvar outline-mode-menu-hide)
3596 (defvar zmacs-regions) ; XEmacs regions
3598 ;; Emacs only
3599 (defvar mark-active)
3601 ;; Various packages
3602 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3603 (declare-function calendar-forward-day "cal-move" (arg))
3604 (declare-function calendar-goto-date "cal-move" (date))
3605 (declare-function calendar-goto-today "cal-move" ())
3606 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3607 (defvar calc-embedded-close-formula)
3608 (defvar calc-embedded-open-formula)
3609 (declare-function cdlatex-tab "ext:cdlatex" ())
3610 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3611 (defvar font-lock-unfontify-region-function)
3612 (declare-function iswitchb-read-buffer "iswitchb"
3613 (prompt &optional default require-match start matches-set))
3614 (defvar iswitchb-temp-buflist)
3615 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3616 (defvar org-agenda-tags-todo-honor-ignore-options)
3617 (declare-function org-agenda-skip "org-agenda" ())
3618 (declare-function
3619 org-format-agenda-item "org-agenda"
3620 (extra txt &optional category tags dotime noprefix remove-re habitp))
3621 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3622 (declare-function org-agenda-change-all-lines "org-agenda"
3623 (newhead hdmarker &optional fixface just-this))
3624 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3625 (declare-function org-agenda-maybe-redo "org-agenda" ())
3626 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3627 (beg end))
3628 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3629 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3630 "org-agenda" (&optional end))
3631 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3632 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3633 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3634 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3635 (declare-function org-indent-mode "org-indent" (&optional arg))
3636 (declare-function parse-time-string "parse-time" (string))
3637 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3638 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3639 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3640 (defvar remember-data-file)
3641 (defvar texmathp-why)
3642 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3643 (declare-function table--at-cell-p "table" (position &optional object at-column))
3645 (defvar w3m-current-url)
3646 (defvar w3m-current-title)
3648 (defvar org-latex-regexps)
3650 ;;; Autoload and prepare some org modules
3652 ;; Some table stuff that needs to be defined here, because it is used
3653 ;; by the functions setting up org-mode or checking for table context.
3655 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3656 "Detect an org-type or table-type table.")
3657 (defconst org-table-line-regexp "^[ \t]*|"
3658 "Detect an org-type table line.")
3659 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3660 "Detect an org-type table line.")
3661 (defconst org-table-hline-regexp "^[ \t]*|-"
3662 "Detect an org-type table hline.")
3663 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3664 "Detect a table-type table hline.")
3665 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3666 "Detect the first line outside a table when searching from within it.
3667 This works for both table types.")
3669 ;; Autoload the functions in org-table.el that are needed by functions here.
3671 (eval-and-compile
3672 (org-autoload "org-table"
3673 '(org-table-align org-table-begin org-table-blank-field
3674 org-table-convert org-table-convert-region org-table-copy-down
3675 org-table-copy-region org-table-create
3676 org-table-create-or-convert-from-region
3677 org-table-create-with-table.el org-table-current-dline
3678 org-table-cut-region org-table-delete-column org-table-edit-field
3679 org-table-edit-formulas org-table-end org-table-eval-formula
3680 org-table-export org-table-field-info
3681 org-table-get-stored-formulas org-table-goto-column
3682 org-table-hline-and-move org-table-import org-table-insert-column
3683 org-table-insert-hline org-table-insert-row org-table-iterate
3684 org-table-justify-field-maybe org-table-kill-row
3685 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3686 org-table-move-column org-table-move-column-left
3687 org-table-move-column-right org-table-move-row
3688 org-table-move-row-down org-table-move-row-up
3689 org-table-next-field org-table-next-row org-table-paste-rectangle
3690 org-table-previous-field org-table-recalculate
3691 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3692 org-table-toggle-coordinate-overlays
3693 org-table-toggle-formula-debugger org-table-wrap-region
3694 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3695 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3696 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3698 (defun org-at-table-p (&optional table-type)
3699 "Return t if the cursor is inside an org-type table.
3700 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3701 (if org-enable-table-editor
3702 (save-excursion
3703 (beginning-of-line 1)
3704 (looking-at (if table-type org-table-any-line-regexp
3705 org-table-line-regexp)))
3706 nil))
3707 (defsubst org-table-p () (org-at-table-p))
3709 (defun org-at-table.el-p ()
3710 "Return t if and only if we are at a table.el table."
3711 (and (org-at-table-p 'any)
3712 (save-excursion
3713 (goto-char (org-table-begin 'any))
3714 (looking-at org-table1-hline-regexp))))
3715 (defun org-table-recognize-table.el ()
3716 "If there is a table.el table nearby, recognize it and move into it."
3717 (if org-table-tab-recognizes-table.el
3718 (if (org-at-table.el-p)
3719 (progn
3720 (beginning-of-line 1)
3721 (if (looking-at org-table-dataline-regexp)
3723 (if (looking-at org-table1-hline-regexp)
3724 (progn
3725 (beginning-of-line 2)
3726 (if (looking-at org-table-any-border-regexp)
3727 (beginning-of-line -1)))))
3728 (if (re-search-forward "|" (org-table-end t) t)
3729 (progn
3730 (require 'table)
3731 (if (table--at-cell-p (point))
3733 (message "recognizing table.el table...")
3734 (table-recognize-table)
3735 (message "recognizing table.el table...done")))
3736 (error "This should not happen"))
3738 nil)
3739 nil))
3741 (defun org-at-table-hline-p ()
3742 "Return t if the cursor is inside a hline in a table."
3743 (if org-enable-table-editor
3744 (save-excursion
3745 (beginning-of-line 1)
3746 (looking-at org-table-hline-regexp))
3747 nil))
3749 (defvar org-table-clean-did-remove-column nil)
3751 (defun org-table-map-tables (function &optional quietly)
3752 "Apply FUNCTION to the start of all tables in the buffer."
3753 (save-excursion
3754 (save-restriction
3755 (widen)
3756 (goto-char (point-min))
3757 (while (re-search-forward org-table-any-line-regexp nil t)
3758 (unless quietly
3759 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3760 (beginning-of-line 1)
3761 (when (looking-at org-table-line-regexp)
3762 (save-excursion (funcall function))
3763 (or (looking-at org-table-line-regexp)
3764 (forward-char 1)))
3765 (re-search-forward org-table-any-border-regexp nil 1))))
3766 (unless quietly (message "Mapping tables: done")))
3768 ;; Declare and autoload functions from org-exp.el & Co
3770 (declare-function org-default-export-plist "org-exp")
3771 (declare-function org-infile-export-plist "org-exp")
3772 (declare-function org-get-current-options "org-exp")
3773 (eval-and-compile
3774 (org-autoload "org-exp"
3775 '(org-export org-export-visible
3776 org-insert-export-options-template
3777 org-table-clean-before-export))
3778 (org-autoload "org-ascii"
3779 '(org-export-as-ascii org-export-ascii-preprocess
3780 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3781 org-export-region-as-ascii))
3782 (org-autoload "org-latex"
3783 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3784 org-replace-region-by-latex org-export-region-as-latex
3785 org-export-as-latex org-export-as-pdf
3786 org-export-as-pdf-and-open))
3787 (org-autoload "org-html"
3788 '(org-export-as-html-and-open
3789 org-export-as-html-batch org-export-as-html-to-buffer
3790 org-replace-region-by-html org-export-region-as-html
3791 org-export-as-html))
3792 (org-autoload "org-docbook"
3793 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3794 org-replace-region-by-docbook org-export-region-as-docbook
3795 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3796 org-export-as-docbook))
3797 (org-autoload "org-icalendar"
3798 '(org-export-icalendar-this-file
3799 org-export-icalendar-all-agenda-files
3800 org-export-icalendar-combine-agenda-files))
3801 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3802 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3804 ;; Declare and autoload functions from org-agenda.el
3806 (eval-and-compile
3807 (org-autoload "org-agenda"
3808 '(org-agenda org-agenda-list org-search-view
3809 org-todo-list org-tags-view org-agenda-list-stuck-projects
3810 org-diary org-agenda-to-appt
3811 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3813 ;; Autoload org-remember
3815 (eval-and-compile
3816 (org-autoload "org-remember"
3817 '(org-remember-insinuate org-remember-annotation
3818 org-remember-apply-template org-remember org-remember-handler)))
3820 (eval-and-compile
3821 (org-autoload "org-capture"
3822 '(org-capture org-capture-insert-template-here
3823 org-capture-import-remember-templates)))
3825 ;; Autoload org-clock.el
3827 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3828 (beg end))
3829 (declare-function org-clock-update-mode-line "org-clock" ())
3830 (declare-function org-resolve-clocks "org-clock"
3831 (&optional also-non-dangling-p prompt last-valid))
3832 (defvar org-clock-start-time)
3833 (defvar org-clock-marker (make-marker)
3834 "Marker recording the last clock-in.")
3835 (defvar org-clock-hd-marker (make-marker)
3836 "Marker recording the last clock-in, but the headline position.")
3837 (defvar org-clock-heading ""
3838 "The heading of the current clock entry.")
3839 (defun org-clock-is-active ()
3840 "Return non-nil if clock is currently running.
3841 The return value is actually the clock marker."
3842 (marker-buffer org-clock-marker))
3844 (eval-and-compile
3845 (org-autoload
3846 "org-clock"
3847 '(org-clock-in org-clock-out org-clock-cancel
3848 org-clock-goto org-clock-sum org-clock-display
3849 org-clock-remove-overlays org-clock-report
3850 org-clocktable-shift org-dblock-write:clocktable
3851 org-get-clocktable org-resolve-clocks)))
3853 (defun org-clock-update-time-maybe ()
3854 "If this is a CLOCK line, update it and return t.
3855 Otherwise, return nil."
3856 (interactive)
3857 (save-excursion
3858 (beginning-of-line 1)
3859 (skip-chars-forward " \t")
3860 (when (looking-at org-clock-string)
3861 (let ((re (concat "[ \t]*" org-clock-string
3862 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3863 "\\([ \t]*=>.*\\)?\\)?"))
3864 ts te h m s neg)
3865 (cond
3866 ((not (looking-at re))
3867 nil)
3868 ((not (match-end 2))
3869 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3870 (> org-clock-marker (point))
3871 (<= org-clock-marker (point-at-eol)))
3872 ;; The clock is running here
3873 (setq org-clock-start-time
3874 (apply 'encode-time
3875 (org-parse-time-string (match-string 1))))
3876 (org-clock-update-mode-line)))
3878 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3879 (end-of-line 1)
3880 (setq ts (match-string 1)
3881 te (match-string 3))
3882 (setq s (- (org-float-time
3883 (apply 'encode-time (org-parse-time-string te)))
3884 (org-float-time
3885 (apply 'encode-time (org-parse-time-string ts))))
3886 neg (< s 0)
3887 s (abs s)
3888 h (floor (/ s 3600))
3889 s (- s (* 3600 h))
3890 m (floor (/ s 60))
3891 s (- s (* 60 s)))
3892 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3893 t))))))
3895 (defun org-check-running-clock ()
3896 "Check if the current buffer contains the running clock.
3897 If yes, offer to stop it and to save the buffer with the changes."
3898 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3899 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3900 (buffer-name))))
3901 (org-clock-out)
3902 (when (y-or-n-p "Save changed buffer?")
3903 (save-buffer))))
3905 (defun org-clocktable-try-shift (dir n)
3906 "Check if this line starts a clock table, if yes, shift the time block."
3907 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
3908 (org-clocktable-shift dir n)))
3910 ;; Autoload org-timer.el
3912 (eval-and-compile
3913 (org-autoload
3914 "org-timer"
3915 '(org-timer-start org-timer org-timer-item
3916 org-timer-change-times-in-region
3917 org-timer-set-timer
3918 org-timer-reset-timers
3919 org-timer-show-remaining-time)))
3921 ;; Autoload org-feed.el
3923 (eval-and-compile
3924 (org-autoload
3925 "org-feed"
3926 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3929 ;; Autoload org-indent.el
3931 ;; Define the variable already here, to make sure we have it.
3932 (defvar org-indent-mode nil
3933 "Non-nil if Org-Indent mode is enabled.
3934 Use the command `org-indent-mode' to change this variable.")
3936 (eval-and-compile
3937 (org-autoload
3938 "org-indent"
3939 '(org-indent-mode)))
3941 ;; Autoload org-mobile.el
3943 (eval-and-compile
3944 (org-autoload
3945 "org-mobile"
3946 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3948 ;; Autoload archiving code
3949 ;; The stuff that is needed for cycling and tags has to be defined here.
3951 (defgroup org-archive nil
3952 "Options concerning archiving in Org-mode."
3953 :tag "Org Archive"
3954 :group 'org-structure)
3956 (defcustom org-archive-location "%s_archive::"
3957 "The location where subtrees should be archived.
3959 The value of this variable is a string, consisting of two parts,
3960 separated by a double-colon. The first part is a filename and
3961 the second part is a headline.
3963 When the filename is omitted, archiving happens in the same file.
3964 %s in the filename will be replaced by the current file
3965 name (without the directory part). Archiving to a different file
3966 is useful to keep archived entries from contributing to the
3967 Org-mode Agenda.
3969 The archived entries will be filed as subtrees of the specified
3970 headline. When the headline is omitted, the subtrees are simply
3971 filed away at the end of the file, as top-level entries. Also in
3972 the heading you can use %s to represent the file name, this can be
3973 useful when using the same archive for a number of different files.
3975 Here are a few examples:
3976 \"%s_archive::\"
3977 If the current file is Projects.org, archive in file
3978 Projects.org_archive, as top-level trees. This is the default.
3980 \"::* Archived Tasks\"
3981 Archive in the current file, under the top-level headline
3982 \"* Archived Tasks\".
3984 \"~/org/archive.org::\"
3985 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3987 \"~/org/archive.org::From %s\"
3988 Archive in file ~/org/archive.org (absolute path), under headlines
3989 \"From FILENAME\" where file name is the current file name.
3991 \"basement::** Finished Tasks\"
3992 Archive in file ./basement (relative path), as level 3 trees
3993 below the level 2 heading \"** Finished Tasks\".
3995 You may set this option on a per-file basis by adding to the buffer a
3996 line like
3998 #+ARCHIVE: basement::** Finished Tasks
4000 You may also define it locally for a subtree by setting an ARCHIVE property
4001 in the entry. If such a property is found in an entry, or anywhere up
4002 the hierarchy, it will be used."
4003 :group 'org-archive
4004 :type 'string)
4006 (defcustom org-archive-tag "ARCHIVE"
4007 "The tag that marks a subtree as archived.
4008 An archived subtree does not open during visibility cycling, and does
4009 not contribute to the agenda listings.
4010 After changing this, font-lock must be restarted in the relevant buffers to
4011 get the proper fontification."
4012 :group 'org-archive
4013 :group 'org-keywords
4014 :type 'string)
4016 (defcustom org-agenda-skip-archived-trees t
4017 "Non-nil means the agenda will skip any items located in archived trees.
4018 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4019 variable is no longer recommended, you should leave it at the value t.
4020 Instead, use the key `v' to cycle the archives-mode in the agenda."
4021 :group 'org-archive
4022 :group 'org-agenda-skip
4023 :type 'boolean)
4025 (defcustom org-columns-skip-archived-trees t
4026 "Non-nil means ignore archived trees when creating column view."
4027 :group 'org-archive
4028 :group 'org-properties
4029 :type 'boolean)
4031 (defcustom org-cycle-open-archived-trees nil
4032 "Non-nil means `org-cycle' will open archived trees.
4033 An archived tree is a tree marked with the tag ARCHIVE.
4034 When nil, archived trees will stay folded. You can still open them with
4035 normal outline commands like `show-all', but not with the cycling commands."
4036 :group 'org-archive
4037 :group 'org-cycle
4038 :type 'boolean)
4040 (defcustom org-sparse-tree-open-archived-trees nil
4041 "Non-nil means sparse tree construction shows matches in archived trees.
4042 When nil, matches in these trees are highlighted, but the trees are kept in
4043 collapsed state."
4044 :group 'org-archive
4045 :group 'org-sparse-trees
4046 :type 'boolean)
4048 (defun org-cycle-hide-archived-subtrees (state)
4049 "Re-hide all archived subtrees after a visibility state change."
4050 (when (and (not org-cycle-open-archived-trees)
4051 (not (memq state '(overview folded))))
4052 (save-excursion
4053 (let* ((globalp (memq state '(contents all)))
4054 (beg (if globalp (point-min) (point)))
4055 (end (if globalp (point-max) (org-end-of-subtree t))))
4056 (org-hide-archived-subtrees beg end)
4057 (goto-char beg)
4058 (if (looking-at (concat ".*:" org-archive-tag ":"))
4059 (message "%s" (substitute-command-keys
4060 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4062 (defun org-force-cycle-archived ()
4063 "Cycle subtree even if it is archived."
4064 (interactive)
4065 (setq this-command 'org-cycle)
4066 (let ((org-cycle-open-archived-trees t))
4067 (call-interactively 'org-cycle)))
4069 (defun org-hide-archived-subtrees (beg end)
4070 "Re-hide all archived subtrees after a visibility state change."
4071 (save-excursion
4072 (let* ((re (concat ":" org-archive-tag ":")))
4073 (goto-char beg)
4074 (while (re-search-forward re end t)
4075 (when (org-on-heading-p)
4076 (org-flag-subtree t)
4077 (org-end-of-subtree t))))))
4079 (defun org-flag-subtree (flag)
4080 (save-excursion
4081 (org-back-to-heading t)
4082 (outline-end-of-heading)
4083 (outline-flag-region (point)
4084 (progn (org-end-of-subtree t) (point))
4085 flag)))
4087 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4089 (eval-and-compile
4090 (org-autoload "org-archive"
4091 '(org-add-archive-files org-archive-subtree
4092 org-archive-to-archive-sibling org-toggle-archive-tag
4093 org-archive-subtree-default
4094 org-archive-subtree-default-with-confirmation)))
4096 ;; Autoload Column View Code
4098 (declare-function org-columns-number-to-string "org-colview")
4099 (declare-function org-columns-get-format-and-top-level "org-colview")
4100 (declare-function org-columns-compute "org-colview")
4102 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4103 '(org-columns-number-to-string org-columns-get-format-and-top-level
4104 org-columns-compute org-agenda-columns org-columns-remove-overlays
4105 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4107 ;; Autoload ID code
4109 (declare-function org-id-store-link "org-id")
4110 (declare-function org-id-locations-load "org-id")
4111 (declare-function org-id-locations-save "org-id")
4112 (defvar org-id-track-globally)
4113 (org-autoload "org-id"
4114 '(org-id-get-create org-id-new org-id-copy org-id-get
4115 org-id-get-with-outline-path-completion
4116 org-id-get-with-outline-drilling org-id-store-link
4117 org-id-goto org-id-find org-id-store-link))
4119 ;; Autoload Plotting Code
4121 (org-autoload "org-plot"
4122 '(org-plot/gnuplot))
4124 ;;; Variables for pre-computed regular expressions, all buffer local
4126 (defvar org-drawer-regexp nil
4127 "Matches first line of a hidden block.")
4128 (make-variable-buffer-local 'org-drawer-regexp)
4129 (defvar org-todo-regexp nil
4130 "Matches any of the TODO state keywords.")
4131 (make-variable-buffer-local 'org-todo-regexp)
4132 (defvar org-not-done-regexp nil
4133 "Matches any of the TODO state keywords except the last one.")
4134 (make-variable-buffer-local 'org-not-done-regexp)
4135 (defvar org-not-done-heading-regexp nil
4136 "Matches a TODO headline that is not done.")
4137 (make-variable-buffer-local 'org-not-done-regexp)
4138 (defvar org-todo-line-regexp nil
4139 "Matches a headline and puts TODO state into group 2 if present.")
4140 (make-variable-buffer-local 'org-todo-line-regexp)
4141 (defvar org-complex-heading-regexp nil
4142 "Matches a headline and puts everything into groups:
4143 group 1: the stars
4144 group 2: The todo keyword, maybe
4145 group 3: Priority cookie
4146 group 4: True headline
4147 group 5: Tags")
4148 (make-variable-buffer-local 'org-complex-heading-regexp)
4149 (defvar org-complex-heading-regexp-format nil
4150 "Printf format to make regexp to match an exact headline.
4151 This regexp will match the headline of any node which hase the exact
4152 headline text that is put into the format, but may have any TODO state,
4153 priority and tags.")
4154 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4155 (defvar org-todo-line-tags-regexp nil
4156 "Matches a headline and puts TODO state into group 2 if present.
4157 Also put tags into group 4 if tags are present.")
4158 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4159 (defvar org-nl-done-regexp nil
4160 "Matches newline followed by a headline with the DONE keyword.")
4161 (make-variable-buffer-local 'org-nl-done-regexp)
4162 (defvar org-looking-at-done-regexp nil
4163 "Matches the DONE keyword a point.")
4164 (make-variable-buffer-local 'org-looking-at-done-regexp)
4165 (defvar org-ds-keyword-length 12
4166 "Maximum length of the Deadline and SCHEDULED keywords.")
4167 (make-variable-buffer-local 'org-ds-keyword-length)
4168 (defvar org-deadline-regexp nil
4169 "Matches the DEADLINE keyword.")
4170 (make-variable-buffer-local 'org-deadline-regexp)
4171 (defvar org-deadline-time-regexp nil
4172 "Matches the DEADLINE keyword together with a time stamp.")
4173 (make-variable-buffer-local 'org-deadline-time-regexp)
4174 (defvar org-deadline-line-regexp nil
4175 "Matches the DEADLINE keyword and the rest of the line.")
4176 (make-variable-buffer-local 'org-deadline-line-regexp)
4177 (defvar org-scheduled-regexp nil
4178 "Matches the SCHEDULED keyword.")
4179 (make-variable-buffer-local 'org-scheduled-regexp)
4180 (defvar org-scheduled-time-regexp nil
4181 "Matches the SCHEDULED keyword together with a time stamp.")
4182 (make-variable-buffer-local 'org-scheduled-time-regexp)
4183 (defvar org-closed-time-regexp nil
4184 "Matches the CLOSED keyword together with a time stamp.")
4185 (make-variable-buffer-local 'org-closed-time-regexp)
4187 (defvar org-keyword-time-regexp nil
4188 "Matches any of the 4 keywords, together with the time stamp.")
4189 (make-variable-buffer-local 'org-keyword-time-regexp)
4190 (defvar org-keyword-time-not-clock-regexp nil
4191 "Matches any of the 3 keywords, together with the time stamp.")
4192 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4193 (defvar org-maybe-keyword-time-regexp nil
4194 "Matches a timestamp, possibly preceded by a keyword.")
4195 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4196 (defvar org-planning-or-clock-line-re nil
4197 "Matches a line with planning or clock info.")
4198 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4199 (defvar org-all-time-keywords nil
4200 "List of time keywords.")
4201 (make-variable-buffer-local 'org-all-time-keywords)
4203 (defconst org-plain-time-of-day-regexp
4204 (concat
4205 "\\(\\<[012]?[0-9]"
4206 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4207 "\\(--?"
4208 "\\(\\<[012]?[0-9]"
4209 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4210 "\\)?")
4211 "Regular expression to match a plain time or time range.
4212 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4213 groups carry important information:
4214 0 the full match
4215 1 the first time, range or not
4216 8 the second time, if it is a range.")
4218 (defconst org-plain-time-extension-regexp
4219 (concat
4220 "\\(\\<[012]?[0-9]"
4221 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4222 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4223 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4224 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4225 groups carry important information:
4226 0 the full match
4227 7 hours of duration
4228 9 minutes of duration")
4230 (defconst org-stamp-time-of-day-regexp
4231 (concat
4232 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4233 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4234 "\\(--?"
4235 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4236 "Regular expression to match a timestamp time or time range.
4237 After a match, the following groups carry important information:
4238 0 the full match
4239 1 date plus weekday, for back referencing to make sure both times are on the same day
4240 2 the first time, range or not
4241 4 the second time, if it is a range.")
4243 (defconst org-startup-options
4244 '(("fold" org-startup-folded t)
4245 ("overview" org-startup-folded t)
4246 ("nofold" org-startup-folded nil)
4247 ("showall" org-startup-folded nil)
4248 ("showeverything" org-startup-folded showeverything)
4249 ("content" org-startup-folded content)
4250 ("indent" org-startup-indented t)
4251 ("noindent" org-startup-indented nil)
4252 ("hidestars" org-hide-leading-stars t)
4253 ("showstars" org-hide-leading-stars nil)
4254 ("odd" org-odd-levels-only t)
4255 ("oddeven" org-odd-levels-only nil)
4256 ("align" org-startup-align-all-tables t)
4257 ("noalign" org-startup-align-all-tables nil)
4258 ("inlineimages" org-startup-with-inline-images t)
4259 ("noinlineimages" org-startup-with-inline-images nil)
4260 ("customtime" org-display-custom-times t)
4261 ("logdone" org-log-done time)
4262 ("lognotedone" org-log-done note)
4263 ("nologdone" org-log-done nil)
4264 ("lognoteclock-out" org-log-note-clock-out t)
4265 ("nolognoteclock-out" org-log-note-clock-out nil)
4266 ("logrepeat" org-log-repeat state)
4267 ("lognoterepeat" org-log-repeat note)
4268 ("nologrepeat" org-log-repeat nil)
4269 ("logreschedule" org-log-reschedule time)
4270 ("lognotereschedule" org-log-reschedule note)
4271 ("nologreschedule" org-log-reschedule nil)
4272 ("logredeadline" org-log-redeadline time)
4273 ("lognoteredeadline" org-log-redeadline note)
4274 ("nologredeadline" org-log-redeadline nil)
4275 ("logrefile" org-log-refile time)
4276 ("lognoterefile" org-log-refile note)
4277 ("nologrefile" org-log-refile nil)
4278 ("fninline" org-footnote-define-inline t)
4279 ("nofninline" org-footnote-define-inline nil)
4280 ("fnlocal" org-footnote-section nil)
4281 ("fnauto" org-footnote-auto-label t)
4282 ("fnprompt" org-footnote-auto-label nil)
4283 ("fnconfirm" org-footnote-auto-label confirm)
4284 ("fnplain" org-footnote-auto-label plain)
4285 ("fnadjust" org-footnote-auto-adjust t)
4286 ("nofnadjust" org-footnote-auto-adjust nil)
4287 ("constcgs" constants-unit-system cgs)
4288 ("constSI" constants-unit-system SI)
4289 ("noptag" org-tag-persistent-alist nil)
4290 ("hideblocks" org-hide-block-startup t)
4291 ("nohideblocks" org-hide-block-startup nil)
4292 ("beamer" org-startup-with-beamer-mode t)
4293 ("entitiespretty" org-pretty-entities t)
4294 ("entitiesplain" org-pretty-entities nil))
4295 "Variable associated with STARTUP options for org-mode.
4296 Each element is a list of three items: The startup options as written
4297 in the #+STARTUP line, the corresponding variable, and the value to
4298 set this variable to if the option is found. An optional forth element PUSH
4299 means to push this value onto the list in the variable.")
4301 (defun org-set-regexps-and-options ()
4302 "Precompute regular expressions for current buffer."
4303 (when (org-mode-p)
4304 (org-set-local 'org-todo-kwd-alist nil)
4305 (org-set-local 'org-todo-key-alist nil)
4306 (org-set-local 'org-todo-key-trigger nil)
4307 (org-set-local 'org-todo-keywords-1 nil)
4308 (org-set-local 'org-done-keywords nil)
4309 (org-set-local 'org-todo-heads nil)
4310 (org-set-local 'org-todo-sets nil)
4311 (org-set-local 'org-todo-log-states nil)
4312 (org-set-local 'org-file-properties nil)
4313 (org-set-local 'org-file-tags nil)
4314 (let ((re (org-make-options-regexp
4315 '("CATEGORY" "TODO" "COLUMNS"
4316 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4317 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4318 "OPTIONS")
4319 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4320 (splitre "[ \t]+")
4321 (scripts org-use-sub-superscripts)
4322 kwds kws0 kwsa key log value cat arch tags const links hw dws
4323 tail sep kws1 prio props ftags drawers beamer-p
4324 ext-setup-or-nil setup-contents (start 0))
4325 (save-excursion
4326 (save-restriction
4327 (widen)
4328 (goto-char (point-min))
4329 (while (or (and ext-setup-or-nil
4330 (string-match re ext-setup-or-nil start)
4331 (setq start (match-end 0)))
4332 (and (setq ext-setup-or-nil nil start 0)
4333 (re-search-forward re nil t)))
4334 (setq key (upcase (match-string 1 ext-setup-or-nil))
4335 value (org-match-string-no-properties 2 ext-setup-or-nil))
4336 (if (stringp value) (setq value (org-trim value)))
4337 (cond
4338 ((equal key "CATEGORY")
4339 (setq cat value))
4340 ((member key '("SEQ_TODO" "TODO"))
4341 (push (cons 'sequence (org-split-string value splitre)) kwds))
4342 ((equal key "TYP_TODO")
4343 (push (cons 'type (org-split-string value splitre)) kwds))
4344 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4345 ;; general TODO-like setup
4346 (push (cons (intern (downcase (match-string 1 key)))
4347 (org-split-string value splitre)) kwds))
4348 ((equal key "TAGS")
4349 (setq tags (append tags (if tags '("\\n") nil)
4350 (org-split-string value splitre))))
4351 ((equal key "COLUMNS")
4352 (org-set-local 'org-columns-default-format value))
4353 ((equal key "LINK")
4354 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4355 (push (cons (match-string 1 value)
4356 (org-trim (match-string 2 value)))
4357 links)))
4358 ((equal key "PRIORITIES")
4359 (setq prio (org-split-string value " +")))
4360 ((equal key "PROPERTY")
4361 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4362 (push (cons (match-string 1 value) (match-string 2 value))
4363 props)))
4364 ((equal key "FILETAGS")
4365 (when (string-match "\\S-" value)
4366 (setq ftags
4367 (append
4368 ftags
4369 (apply 'append
4370 (mapcar (lambda (x) (org-split-string x ":"))
4371 (org-split-string value)))))))
4372 ((equal key "DRAWERS")
4373 (setq drawers (org-split-string value splitre)))
4374 ((equal key "CONSTANTS")
4375 (setq const (append const (org-split-string value splitre))))
4376 ((equal key "STARTUP")
4377 (let ((opts (org-split-string value splitre))
4378 l var val)
4379 (while (setq l (pop opts))
4380 (when (setq l (assoc l org-startup-options))
4381 (setq var (nth 1 l) val (nth 2 l))
4382 (if (not (nth 3 l))
4383 (set (make-local-variable var) val)
4384 (if (not (listp (symbol-value var)))
4385 (set (make-local-variable var) nil))
4386 (set (make-local-variable var) (symbol-value var))
4387 (add-to-list var val))))))
4388 ((equal key "ARCHIVE")
4389 (setq arch value)
4390 (remove-text-properties 0 (length arch)
4391 '(face t fontified t) arch))
4392 ((equal key "LATEX_CLASS")
4393 (setq beamer-p (equal value "beamer")))
4394 ((equal key "OPTIONS")
4395 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4396 (setq scripts (read (match-string 2 value)))))
4397 ((equal key "SETUPFILE")
4398 (setq setup-contents (org-file-contents
4399 (expand-file-name
4400 (org-remove-double-quotes value))
4401 'noerror))
4402 (if (not ext-setup-or-nil)
4403 (setq ext-setup-or-nil setup-contents start 0)
4404 (setq ext-setup-or-nil
4405 (concat (substring ext-setup-or-nil 0 start)
4406 "\n" setup-contents "\n"
4407 (substring ext-setup-or-nil start)))))
4408 ))))
4409 (org-set-local 'org-use-sub-superscripts scripts)
4410 (when cat
4411 (org-set-local 'org-category (intern cat))
4412 (push (cons "CATEGORY" cat) props))
4413 (when prio
4414 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4415 (setq prio (mapcar 'string-to-char prio))
4416 (org-set-local 'org-highest-priority (nth 0 prio))
4417 (org-set-local 'org-lowest-priority (nth 1 prio))
4418 (org-set-local 'org-default-priority (nth 2 prio)))
4419 (and props (org-set-local 'org-file-properties (nreverse props)))
4420 (and ftags (org-set-local 'org-file-tags
4421 (mapcar 'org-add-prop-inherited ftags)))
4422 (and drawers (org-set-local 'org-drawers drawers))
4423 (and arch (org-set-local 'org-archive-location arch))
4424 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4425 ;; Process the TODO keywords
4426 (unless kwds
4427 ;; Use the global values as if they had been given locally.
4428 (setq kwds (default-value 'org-todo-keywords))
4429 (if (stringp (car kwds))
4430 (setq kwds (list (cons org-todo-interpretation
4431 (default-value 'org-todo-keywords)))))
4432 (setq kwds (reverse kwds)))
4433 (setq kwds (nreverse kwds))
4434 (let (inter kws kw)
4435 (while (setq kws (pop kwds))
4436 (let ((kws (or
4437 (run-hook-with-args-until-success
4438 'org-todo-setup-filter-hook kws)
4439 kws)))
4440 (setq inter (pop kws) sep (member "|" kws)
4441 kws0 (delete "|" (copy-sequence kws))
4442 kwsa nil
4443 kws1 (mapcar
4444 (lambda (x)
4445 ;; 1 2
4446 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4447 (progn
4448 (setq kw (match-string 1 x)
4449 key (and (match-end 2) (match-string 2 x))
4450 log (org-extract-log-state-settings x))
4451 (push (cons kw (and key (string-to-char key))) kwsa)
4452 (and log (push log org-todo-log-states))
4454 (error "Invalid TODO keyword %s" x)))
4455 kws0)
4456 kwsa (if kwsa (append '((:startgroup))
4457 (nreverse kwsa)
4458 '((:endgroup))))
4459 hw (car kws1)
4460 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4461 tail (list inter hw (car dws) (org-last dws))))
4462 (add-to-list 'org-todo-heads hw 'append)
4463 (push kws1 org-todo-sets)
4464 (setq org-done-keywords (append org-done-keywords dws nil))
4465 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4466 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4467 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4468 (setq org-todo-sets (nreverse org-todo-sets)
4469 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4470 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4471 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4472 ;; Process the constants
4473 (when const
4474 (let (e cst)
4475 (while (setq e (pop const))
4476 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4477 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4478 (setq org-table-formula-constants-local cst)))
4480 ;; Process the tags.
4481 (when tags
4482 (let (e tgs)
4483 (while (setq e (pop tags))
4484 (cond
4485 ((equal e "{") (push '(:startgroup) tgs))
4486 ((equal e "}") (push '(:endgroup) tgs))
4487 ((equal e "\\n") (push '(:newline) tgs))
4488 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4489 (push (cons (match-string 1 e)
4490 (string-to-char (match-string 2 e)))
4491 tgs))
4492 (t (push (list e) tgs))))
4493 (org-set-local 'org-tag-alist nil)
4494 (while (setq e (pop tgs))
4495 (or (and (stringp (car e))
4496 (assoc (car e) org-tag-alist))
4497 (push e org-tag-alist)))))
4499 ;; Compute the regular expressions and other local variables
4500 (if (not org-done-keywords)
4501 (setq org-done-keywords (and org-todo-keywords-1
4502 (list (org-last org-todo-keywords-1)))))
4503 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4504 (length org-scheduled-string)
4505 (length org-clock-string)
4506 (length org-closed-string)))
4507 org-drawer-regexp
4508 (concat "^[ \t]*:\\("
4509 (mapconcat 'regexp-quote org-drawers "\\|")
4510 "\\):[ \t]*$")
4511 org-not-done-keywords
4512 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4513 org-todo-regexp
4514 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4515 "\\|") "\\)\\>")
4516 org-not-done-regexp
4517 (concat "\\<\\("
4518 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4519 "\\)\\>")
4520 org-not-done-heading-regexp
4521 (concat "^\\(\\*+\\)[ \t]+\\("
4522 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4523 "\\)\\>")
4524 org-todo-line-regexp
4525 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4526 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4527 "\\)\\>\\)?[ \t]*\\(.*\\)")
4528 org-complex-heading-regexp
4529 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4530 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4531 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4532 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
4533 org-complex-heading-regexp-format
4534 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4535 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4536 "\\)\\>\\)?"
4537 "\\(?:[ \t]*\\(\\[#.\\]\\)\\)?"
4538 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4539 "[ \t]*\\(%s\\)"
4540 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4541 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?[ \t]*$")
4542 org-nl-done-regexp
4543 (concat "\n\\*+[ \t]+"
4544 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4545 "\\)" "\\>")
4546 org-todo-line-tags-regexp
4547 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4548 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4549 (org-re
4550 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@#%]+:[ \t]*\\)?$\\)"))
4551 org-looking-at-done-regexp
4552 (concat "^" "\\(?:"
4553 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4554 "\\>")
4555 org-deadline-regexp (concat "\\<" org-deadline-string)
4556 org-deadline-time-regexp
4557 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4558 org-deadline-line-regexp
4559 (concat "\\<\\(" org-deadline-string "\\).*")
4560 org-scheduled-regexp
4561 (concat "\\<" org-scheduled-string)
4562 org-scheduled-time-regexp
4563 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4564 org-closed-time-regexp
4565 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4566 org-keyword-time-regexp
4567 (concat "\\<\\(" org-scheduled-string
4568 "\\|" org-deadline-string
4569 "\\|" org-closed-string
4570 "\\|" org-clock-string "\\)"
4571 " *[[<]\\([^]>]+\\)[]>]")
4572 org-keyword-time-not-clock-regexp
4573 (concat "\\<\\(" org-scheduled-string
4574 "\\|" org-deadline-string
4575 "\\|" org-closed-string
4576 "\\)"
4577 " *[[<]\\([^]>]+\\)[]>]")
4578 org-maybe-keyword-time-regexp
4579 (concat "\\(\\<\\(" org-scheduled-string
4580 "\\|" org-deadline-string
4581 "\\|" org-closed-string
4582 "\\|" org-clock-string "\\)\\)?"
4583 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4584 org-planning-or-clock-line-re
4585 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4586 "\\|" org-deadline-string
4587 "\\|" org-closed-string "\\|" org-clock-string
4588 "\\)\\>\\)")
4589 org-all-time-keywords
4590 (mapcar (lambda (w) (substring w 0 -1))
4591 (list org-scheduled-string org-deadline-string
4592 org-clock-string org-closed-string))
4594 (org-compute-latex-and-specials-regexp)
4595 (org-set-font-lock-defaults))))
4597 (defun org-file-contents (file &optional noerror)
4598 "Return the contents of FILE, as a string."
4599 (if (or (not file)
4600 (not (file-readable-p file)))
4601 (if noerror
4602 (progn
4603 (message "Cannot read file \"%s\"" file)
4604 (ding) (sit-for 2)
4606 (error "Cannot read file \"%s\"" file))
4607 (with-temp-buffer
4608 (insert-file-contents file)
4609 (buffer-string))))
4611 (defun org-extract-log-state-settings (x)
4612 "Extract the log state setting from a TODO keyword string.
4613 This will extract info from a string like \"WAIT(w@/!)\"."
4614 (let (kw key log1 log2)
4615 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4616 (setq kw (match-string 1 x)
4617 key (and (match-end 2) (match-string 2 x))
4618 log1 (and (match-end 3) (match-string 3 x))
4619 log2 (and (match-end 4) (match-string 4 x)))
4620 (and (or log1 log2)
4621 (list kw
4622 (and log1 (if (equal log1 "!") 'time 'note))
4623 (and log2 (if (equal log2 "!") 'time 'note)))))))
4625 (defun org-remove-keyword-keys (list)
4626 "Remove a pair of parenthesis at the end of each string in LIST."
4627 (mapcar (lambda (x)
4628 (if (string-match "(.*)$" x)
4629 (substring x 0 (match-beginning 0))
4631 list))
4633 (defun org-assign-fast-keys (alist)
4634 "Assign fast keys to a keyword-key alist.
4635 Respect keys that are already there."
4636 (let (new e (alt ?0))
4637 (while (setq e (pop alist))
4638 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4639 (cdr e)) ;; Key already assigned.
4640 (push e new)
4641 (let ((clist (string-to-list (downcase (car e))))
4642 (used (append new alist)))
4643 (when (= (car clist) ?@)
4644 (pop clist))
4645 (while (and clist (rassoc (car clist) used))
4646 (pop clist))
4647 (unless clist
4648 (while (rassoc alt used)
4649 (incf alt)))
4650 (push (cons (car e) (or (car clist) alt)) new))))
4651 (nreverse new)))
4653 ;;; Some variables used in various places
4655 (defvar org-window-configuration nil
4656 "Used in various places to store a window configuration.")
4657 (defvar org-selected-window nil
4658 "Used in various places to store a window configuration.")
4659 (defvar org-finish-function nil
4660 "Function to be called when `C-c C-c' is used.
4661 This is for getting out of special buffers like remember.")
4664 ;; FIXME: Occasionally check by commenting these, to make sure
4665 ;; no other functions uses these, forgetting to let-bind them.
4666 (defvar entry)
4667 (defvar last-state)
4668 (defvar date)
4670 ;; Defined somewhere in this file, but used before definition.
4671 (defvar org-entities) ;; defined in org-entities.el
4672 (defvar org-struct-menu)
4673 (defvar org-org-menu)
4674 (defvar org-tbl-menu)
4676 ;;;; Define the Org-mode
4678 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4679 (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"))
4682 ;; We use a before-change function to check if a table might need
4683 ;; an update.
4684 (defvar org-table-may-need-update t
4685 "Indicates that a table might need an update.
4686 This variable is set by `org-before-change-function'.
4687 `org-table-align' sets it back to nil.")
4688 (defun org-before-change-function (beg end)
4689 "Every change indicates that a table might need an update."
4690 (setq org-table-may-need-update t))
4691 (defvar org-mode-map)
4692 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4693 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4694 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4695 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4696 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4697 (defvar org-table-buffer-is-an nil)
4698 (defconst org-outline-regexp "\\*+ ")
4700 ;;;###autoload
4701 (define-derived-mode org-mode outline-mode "Org"
4702 "Outline-based notes management and organizer, alias
4703 \"Carsten's outline-mode for keeping track of everything.\"
4705 Org-mode develops organizational tasks around a NOTES file which
4706 contains information about projects as plain text. Org-mode is
4707 implemented on top of outline-mode, which is ideal to keep the content
4708 of large files well structured. It supports ToDo items, deadlines and
4709 time stamps, which magically appear in the diary listing of the Emacs
4710 calendar. Tables are easily created with a built-in table editor.
4711 Plain text URL-like links connect to websites, emails (VM), Usenet
4712 messages (Gnus), BBDB entries, and any files related to the project.
4713 For printing and sharing of notes, an Org-mode file (or a part of it)
4714 can be exported as a structured ASCII or HTML file.
4716 The following commands are available:
4718 \\{org-mode-map}"
4720 ;; Get rid of Outline menus, they are not needed
4721 ;; Need to do this here because define-derived-mode sets up
4722 ;; the keymap so late. Still, it is a waste to call this each time
4723 ;; we switch another buffer into org-mode.
4724 (if (featurep 'xemacs)
4725 (when (boundp 'outline-mode-menu-heading)
4726 ;; Assume this is Greg's port, it uses easymenu
4727 (easy-menu-remove outline-mode-menu-heading)
4728 (easy-menu-remove outline-mode-menu-show)
4729 (easy-menu-remove outline-mode-menu-hide))
4730 (define-key org-mode-map [menu-bar headings] 'undefined)
4731 (define-key org-mode-map [menu-bar hide] 'undefined)
4732 (define-key org-mode-map [menu-bar show] 'undefined))
4734 (org-load-modules-maybe)
4735 (easy-menu-add org-org-menu)
4736 (easy-menu-add org-tbl-menu)
4737 (org-install-agenda-files-menu)
4738 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4739 (add-to-invisibility-spec '(org-cwidth))
4740 (add-to-invisibility-spec '(org-hide-block . t))
4741 (when (featurep 'xemacs)
4742 (org-set-local 'line-move-ignore-invisible t))
4743 (org-set-local 'outline-regexp org-outline-regexp)
4744 (org-set-local 'outline-level 'org-outline-level)
4745 (when (and org-ellipsis
4746 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4747 (fboundp 'make-glyph-code))
4748 (unless org-display-table
4749 (setq org-display-table (make-display-table)))
4750 (set-display-table-slot
4751 org-display-table 4
4752 (vconcat (mapcar
4753 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4754 org-ellipsis)))
4755 (if (stringp org-ellipsis) org-ellipsis "..."))))
4756 (setq buffer-display-table org-display-table))
4757 (org-set-regexps-and-options)
4758 (when (and org-tag-faces (not org-tags-special-faces-re))
4759 ;; tag faces set outside customize.... force initialization.
4760 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4761 ;; Calc embedded
4762 (org-set-local 'calc-embedded-open-mode "# ")
4763 (modify-syntax-entry ?@ "w")
4764 (if org-startup-truncated (setq truncate-lines t))
4765 (org-set-local 'font-lock-unfontify-region-function
4766 'org-unfontify-region)
4767 ;; Activate before-change-function
4768 (org-set-local 'org-table-may-need-update t)
4769 (org-add-hook 'before-change-functions 'org-before-change-function nil
4770 'local)
4771 ;; Check for running clock before killing a buffer
4772 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4773 ;; Paragraphs and auto-filling
4774 (org-set-autofill-regexps)
4775 (setq indent-line-function 'org-indent-line-function)
4776 (org-update-radio-target-regexp)
4777 ;; Beginning/end of defun
4778 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4779 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4780 ;; Next error for sparse trees
4781 (org-set-local 'next-error-function 'org-occur-next-match)
4782 ;; Make sure dependence stuff works reliably, even for users who set it
4783 ;; too late :-(
4784 (if org-enforce-todo-dependencies
4785 (add-hook 'org-blocker-hook
4786 'org-block-todo-from-children-or-siblings-or-parent)
4787 (remove-hook 'org-blocker-hook
4788 'org-block-todo-from-children-or-siblings-or-parent))
4789 (if org-enforce-todo-checkbox-dependencies
4790 (add-hook 'org-blocker-hook
4791 'org-block-todo-from-checkboxes)
4792 (remove-hook 'org-blocker-hook
4793 'org-block-todo-from-checkboxes))
4795 ;; Comment characters
4796 (org-set-local 'comment-start "#")
4797 (org-set-local 'comment-padding " ")
4799 ;; Align options lines
4800 (org-set-local
4801 'align-mode-rules-list
4802 '((org-in-buffer-settings
4803 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4804 (modes . '(org-mode)))))
4806 ;; Imenu
4807 (org-set-local 'imenu-create-index-function
4808 'org-imenu-get-tree)
4810 ;; Make isearch reveal context
4811 (if (or (featurep 'xemacs)
4812 (not (boundp 'outline-isearch-open-invisible-function)))
4813 ;; Emacs 21 and XEmacs make use of the hook
4814 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4815 ;; Emacs 22 deals with this through a special variable
4816 (org-set-local 'outline-isearch-open-invisible-function
4817 (lambda (&rest ignore) (org-show-context 'isearch))))
4819 ;; Turn on org-beamer-mode?
4820 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4822 ;; Setup the pcomplete hooks
4823 (set (make-local-variable 'pcomplete-command-completion-function)
4824 'org-pcomplete-initial)
4825 (set (make-local-variable 'pcomplete-command-name-function)
4826 'org-command-at-point)
4827 (set (make-local-variable 'pcomplete-default-completion-function)
4828 'ignore)
4829 (set (make-local-variable 'pcomplete-parse-arguments-function)
4830 'org-parse-arguments)
4831 (set (make-local-variable 'pcomplete-termination-string) "")
4832 (set (make-local-variable 'face-remapping-alist)
4833 '((default org-default)))
4835 ;; If empty file that did not turn on org-mode automatically, make it to.
4836 (if (and org-insert-mode-line-in-empty-file
4837 (org-called-interactively-p 'any)
4838 (= (point-min) (point-max)))
4839 (insert "# -*- mode: org -*-\n\n"))
4840 (unless org-inhibit-startup
4841 (when org-startup-align-all-tables
4842 (let ((bmp (buffer-modified-p)))
4843 (org-table-map-tables 'org-table-align 'quietly)
4844 (set-buffer-modified-p bmp)))
4845 (when org-startup-with-inline-images
4846 (org-display-inline-images))
4847 (when org-startup-indented
4848 (require 'org-indent)
4849 (org-indent-mode 1))
4850 (unless org-inhibit-startup-visibility-stuff
4851 (org-set-startup-visibility))))
4853 (when (fboundp 'abbrev-table-put)
4854 (abbrev-table-put org-mode-abbrev-table
4855 :parents (list text-mode-abbrev-table)))
4857 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4859 (defun org-current-time ()
4860 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4861 (if (> (car org-time-stamp-rounding-minutes) 1)
4862 (let ((r (car org-time-stamp-rounding-minutes))
4863 (time (decode-time)))
4864 (apply 'encode-time
4865 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4866 (nthcdr 2 time))))
4867 (current-time)))
4869 (defun org-today ()
4870 "Return today date, considering `org-extend-today-until'."
4871 (time-to-days
4872 (time-subtract (current-time)
4873 (list 0 (* 3600 org-extend-today-until) 0))))
4875 ;;;; Font-Lock stuff, including the activators
4877 (defvar org-mouse-map (make-sparse-keymap))
4878 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
4879 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
4880 (when org-mouse-1-follows-link
4881 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4882 (when org-tab-follows-link
4883 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4884 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4886 (require 'font-lock)
4888 (defconst org-non-link-chars "]\t\n\r<>")
4889 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4890 "shell" "elisp" "doi" "message"))
4891 (defvar org-link-types-re nil
4892 "Matches a link that has a url-like prefix like \"http:\"")
4893 (defvar org-link-re-with-space nil
4894 "Matches a link with spaces, optional angular brackets around it.")
4895 (defvar org-link-re-with-space2 nil
4896 "Matches a link with spaces, optional angular brackets around it.")
4897 (defvar org-link-re-with-space3 nil
4898 "Matches a link with spaces, only for internal part in bracket links.")
4899 (defvar org-angle-link-re nil
4900 "Matches link with angular brackets, spaces are allowed.")
4901 (defvar org-plain-link-re nil
4902 "Matches plain link, without spaces.")
4903 (defvar org-bracket-link-regexp nil
4904 "Matches a link in double brackets.")
4905 (defvar org-bracket-link-analytic-regexp nil
4906 "Regular expression used to analyze links.
4907 Here is what the match groups contain after a match:
4908 1: http:
4909 2: http
4910 3: path
4911 4: [desc]
4912 5: desc")
4913 (defvar org-bracket-link-analytic-regexp++ nil
4914 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
4915 (defvar org-any-link-re nil
4916 "Regular expression matching any link.")
4918 (defcustom org-match-sexp-depth 3
4919 "Number of stacked braces for sub/superscript matching.
4920 This has to be set before loading org.el to be effective."
4921 :group 'org-export-translation ; ??????????????????????????/
4922 :type 'integer)
4924 (defun org-create-multibrace-regexp (left right n)
4925 "Create a regular expression which will match a balanced sexp.
4926 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
4927 as single character strings.
4928 The regexp returned will match the entire expression including the
4929 delimiters. It will also define a single group which contains the
4930 match except for the outermost delimiters. The maximum depth of
4931 stacked delimiters is N. Escaping delimiters is not possible."
4932 (let* ((nothing (concat "[^" left right "]*?"))
4933 (or "\\|")
4934 (re nothing)
4935 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
4936 (while (> n 1)
4937 (setq n (1- n)
4938 re (concat re or next)
4939 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
4940 (concat left "\\(" re "\\)" right)))
4942 (defvar org-match-substring-regexp
4943 (concat
4944 "\\([^\\]\\)\\([_^]\\)\\("
4945 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4946 "\\|"
4947 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
4948 "\\|"
4949 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
4950 "The regular expression matching a sub- or superscript.")
4952 (defvar org-match-substring-with-braces-regexp
4953 (concat
4954 "\\([^\\]\\)\\([_^]\\)\\("
4955 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4956 "\\)")
4957 "The regular expression matching a sub- or superscript, forcing braces.")
4959 (defun org-make-link-regexps ()
4960 "Update the link regular expressions.
4961 This should be called after the variable `org-link-types' has changed."
4962 (setq org-link-types-re
4963 (concat
4964 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4965 org-link-re-with-space
4966 (concat
4967 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4968 "\\([^" org-non-link-chars " ]"
4969 "[^" org-non-link-chars "]*"
4970 "[^" org-non-link-chars " ]\\)>?")
4971 org-link-re-with-space2
4972 (concat
4973 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4974 "\\([^" org-non-link-chars " ]"
4975 "[^\t\n\r]*"
4976 "[^" org-non-link-chars " ]\\)>?")
4977 org-link-re-with-space3
4978 (concat
4979 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4980 "\\([^" org-non-link-chars " ]"
4981 "[^\t\n\r]*\\)")
4982 org-angle-link-re
4983 (concat
4984 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4985 "\\([^" org-non-link-chars " ]"
4986 "[^" org-non-link-chars "]*"
4987 "\\)>")
4988 org-plain-link-re
4989 (concat
4990 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4991 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4992 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4993 org-bracket-link-regexp
4994 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4995 org-bracket-link-analytic-regexp
4996 (concat
4997 "\\[\\["
4998 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4999 "\\([^]]+\\)"
5000 "\\]"
5001 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5002 "\\]")
5003 org-bracket-link-analytic-regexp++
5004 (concat
5005 "\\[\\["
5006 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5007 "\\([^]]+\\)"
5008 "\\]"
5009 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5010 "\\]")
5011 org-any-link-re
5012 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5013 org-angle-link-re "\\)\\|\\("
5014 org-plain-link-re "\\)")))
5016 (org-make-link-regexps)
5018 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5019 "Regular expression for fast time stamp matching.")
5020 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?\\)[]>]"
5021 "Regular expression for fast time stamp matching.")
5022 (defconst org-ts-regexp0 "\\(\\([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 This one does not require the space after the date, so it can be used
5025 on a string that terminates immediately after the date.")
5026 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5027 "Regular expression matching time strings for analysis.")
5028 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5029 "Regular expression matching time stamps, with groups.")
5030 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5031 "Regular expression matching time stamps (also [..]), with groups.")
5032 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5033 "Regular expression matching a time stamp range.")
5034 (defconst org-tr-regexp-both
5035 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5036 "Regular expression matching a time stamp range.")
5037 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5038 org-ts-regexp "\\)?")
5039 "Regular expression matching a time stamp or time stamp range.")
5040 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5041 org-ts-regexp-both "\\)?")
5042 "Regular expression matching a time stamp or time stamp range.
5043 The time stamps may be either active or inactive.")
5045 (defvar org-emph-face nil)
5047 (defun org-do-emphasis-faces (limit)
5048 "Run through the buffer and add overlays to links."
5049 (let (rtn a)
5050 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5051 (if (not (= (char-after (match-beginning 3))
5052 (char-after (match-beginning 4))))
5053 (progn
5054 (setq rtn t)
5055 (setq a (assoc (match-string 3) org-emphasis-alist))
5056 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5057 'face
5058 (nth 1 a))
5059 (and (nth 4 a)
5060 (org-remove-flyspell-overlays-in
5061 (match-beginning 0) (match-end 0)))
5062 (add-text-properties (match-beginning 2) (match-end 2)
5063 '(font-lock-multiline t org-emphasis t))
5064 (when org-hide-emphasis-markers
5065 (add-text-properties (match-end 4) (match-beginning 5)
5066 '(invisible org-link))
5067 (add-text-properties (match-beginning 3) (match-end 3)
5068 '(invisible org-link)))))
5069 (backward-char 1))
5070 rtn))
5072 (defun org-emphasize (&optional char)
5073 "Insert or change an emphasis, i.e. a font like bold or italic.
5074 If there is an active region, change that region to a new emphasis.
5075 If there is no region, just insert the marker characters and position
5076 the cursor between them.
5077 CHAR should be either the marker character, or the first character of the
5078 HTML tag associated with that emphasis. If CHAR is a space, the means
5079 to remove the emphasis of the selected region.
5080 If char is not given (for example in an interactive call) it
5081 will be prompted for."
5082 (interactive)
5083 (let ((eal org-emphasis-alist) e det
5084 (erc org-emphasis-regexp-components)
5085 (prompt "")
5086 (string "") beg end move tag c s)
5087 (if (org-region-active-p)
5088 (setq beg (region-beginning) end (region-end)
5089 string (buffer-substring beg end))
5090 (setq move t))
5092 (while (setq e (pop eal))
5093 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5094 c (aref tag 0))
5095 (push (cons c (string-to-char (car e))) det)
5096 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5097 (substring tag 1)))))
5098 (setq det (nreverse det))
5099 (unless char
5100 (message "%s" (concat "Emphasis marker or tag:" prompt))
5101 (setq char (read-char-exclusive)))
5102 (setq char (or (cdr (assoc char det)) char))
5103 (if (equal char ?\ )
5104 (setq s "" move nil)
5105 (unless (assoc (char-to-string char) org-emphasis-alist)
5106 (error "No such emphasis marker: \"%c\"" char))
5107 (setq s (char-to-string char)))
5108 (while (and (> (length string) 1)
5109 (equal (substring string 0 1) (substring string -1))
5110 (assoc (substring string 0 1) org-emphasis-alist))
5111 (setq string (substring string 1 -1)))
5112 (setq string (concat s string s))
5113 (if beg (delete-region beg end))
5114 (unless (or (bolp)
5115 (string-match (concat "[" (nth 0 erc) "\n]")
5116 (char-to-string (char-before (point)))))
5117 (insert " "))
5118 (unless (or (eobp)
5119 (string-match (concat "[" (nth 1 erc) "\n]")
5120 (char-to-string (char-after (point)))))
5121 (insert " ") (backward-char 1))
5122 (insert string)
5123 (and move (backward-char 1))))
5125 (defconst org-nonsticky-props
5126 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5128 (defsubst org-rear-nonsticky-at (pos)
5129 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5131 (defun org-activate-plain-links (limit)
5132 "Run through the buffer and add overlays to links."
5133 (catch 'exit
5134 (let (f)
5135 (if (re-search-forward org-plain-link-re limit t)
5136 (progn
5137 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5138 (setq f (get-text-property (match-beginning 0) 'face))
5139 (if (or (eq f 'org-tag)
5140 (and (listp f) (memq 'org-tag f)))
5142 (add-text-properties (match-beginning 0) (match-end 0)
5143 (list 'mouse-face 'highlight
5144 'face 'org-link
5145 'keymap org-mouse-map))
5146 (org-rear-nonsticky-at (match-end 0)))
5147 t)))))
5149 (defun org-activate-code (limit)
5150 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
5151 (progn
5152 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5153 (remove-text-properties (match-beginning 0) (match-end 0)
5154 '(display t invisible t intangible t))
5155 t)))
5157 (defcustom org-src-fontify-natively nil
5158 "When non-nil, fontify code in code blocks."
5159 :type 'boolean
5160 :group 'org-appearance
5161 :group 'org-babel)
5163 (defun org-fontify-meta-lines-and-blocks (limit)
5164 (condition-case nil
5165 (org-fontify-meta-lines-and-blocks-1 limit)
5166 (error (message "org-mode fontification error"))))
5168 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5169 "Fontify #+ lines and blocks, in the correct ways."
5170 (let ((case-fold-search t))
5171 (if (re-search-forward
5172 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5173 limit t)
5174 (let ((beg (match-beginning 0))
5175 (block-start (match-end 0))
5176 (block-end nil)
5177 (lang (match-string 7))
5178 (beg1 (line-beginning-position 2))
5179 (dc1 (downcase (match-string 2)))
5180 (dc3 (downcase (match-string 3)))
5181 end end1 quoting block-type ovl)
5182 (cond
5183 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5184 ;; a single line of backend-specific content
5185 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5186 (remove-text-properties (match-beginning 0) (match-end 0)
5187 '(display t invisible t intangible t))
5188 (add-text-properties (match-beginning 1) (match-end 3)
5189 '(font-lock-fontified t face org-meta-line))
5190 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5191 '(font-lock-fontified t face org-block))
5192 ; for backend-specific code
5194 ((and (match-end 4) (equal dc3 "begin"))
5195 ;; Truly a block
5196 (setq block-type (downcase (match-string 5))
5197 quoting (member block-type org-protecting-blocks))
5198 (when (re-search-forward
5199 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5200 nil t) ;; on purpose, we look further than LIMIT
5201 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5202 (setq block-end (match-beginning 0))
5203 (when quoting
5204 (remove-text-properties beg end
5205 '(display t invisible t intangible t)))
5206 (add-text-properties
5207 beg end
5208 '(font-lock-fontified t font-lock-multiline t))
5209 (add-text-properties beg beg1 '(face org-meta-line))
5210 (add-text-properties end1 (+ end 1) '(face org-meta-line))
5211 ; for end_src
5212 (cond
5213 ((and lang (not (string= lang "")) org-src-fontify-natively)
5214 (org-src-font-lock-fontify-block lang block-start block-end)
5215 ;; remove old background overlays
5216 (mapc (lambda (ov)
5217 (if (eq (overlay-get ov 'face) 'org-block-background)
5218 (delete-overlay ov)))
5219 (overlays-at (/ (+ beg1 block-end) 2)))
5220 ;; add a background overlay
5221 (setq ovl (make-overlay beg1 block-end))
5222 (overlay-put ovl 'face 'org-block-background)
5223 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5224 (quoting
5225 (add-text-properties beg1 (+ end1 1) '(face org-block)))
5226 ; end of source block
5227 ((not org-fontify-quote-and-verse-blocks))
5228 ((string= block-type "quote")
5229 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5230 ((string= block-type "verse")
5231 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5232 (add-text-properties beg beg1 '(face org-block-begin-line))
5233 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5235 ((member dc1 '("title:" "author:" "email:" "date:"))
5236 (add-text-properties
5237 beg (match-end 3)
5238 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5239 '(font-lock-fontified t invisible t)
5240 '(font-lock-fontified t face org-document-info-keyword)))
5241 (add-text-properties
5242 (match-beginning 6) (match-end 6)
5243 (if (string-equal dc1 "title:")
5244 '(font-lock-fontified t face org-document-title)
5245 '(font-lock-fontified t face org-document-info))))
5246 ((not (member (char-after beg) '(?\ ?\t)))
5247 ;; just any other in-buffer setting, but not indented
5248 (add-text-properties
5249 beg (1+ (match-end 0))
5250 '(font-lock-fontified t face org-meta-line))
5252 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5253 "orgtbl:" "tblfm:" "tblname:" "result:"
5254 "results:" "source:" "srcname:" "call:"
5255 "data:" "header:" "headers:"))
5256 (and (match-end 4) (equal dc3 "attr")))
5257 (add-text-properties
5258 beg (match-end 0)
5259 '(font-lock-fontified t face org-meta-line))
5261 ((member dc3 '(" " ""))
5262 (add-text-properties
5263 beg (match-end 0)
5264 '(font-lock-fontified t face font-lock-comment-face)))
5265 (t nil))))))
5267 (defun org-activate-angle-links (limit)
5268 "Run through the buffer and add overlays to links."
5269 (if (re-search-forward org-angle-link-re limit t)
5270 (progn
5271 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5272 (add-text-properties (match-beginning 0) (match-end 0)
5273 (list 'mouse-face 'highlight
5274 'keymap org-mouse-map))
5275 (org-rear-nonsticky-at (match-end 0))
5276 t)))
5278 (defun org-activate-footnote-links (limit)
5279 "Run through the buffer and add overlays to footnotes."
5280 (let ((fn (org-footnote-next-reference-or-definition limit)))
5281 (when fn
5282 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5283 (org-remove-flyspell-overlays-in beg end)
5284 (add-text-properties beg end
5285 (list 'mouse-face 'highlight
5286 'keymap org-mouse-map
5287 'help-echo
5288 (if (= (point-at-bol) beg)
5289 "Footnote definition"
5290 "Footnote reference")
5291 'font-lock-fontified t
5292 'font-lock-multiline t
5293 'face 'org-footnote))))))
5295 (defun org-activate-bracket-links (limit)
5296 "Run through the buffer and add overlays to bracketed links."
5297 (if (re-search-forward org-bracket-link-regexp limit t)
5298 (let* ((help (concat "LINK: "
5299 (org-match-string-no-properties 1)))
5300 ;; FIXME: above we should remove the escapes.
5301 ;; but that requires another match, protecting match data,
5302 ;; a lot of overhead for font-lock.
5303 (ip (org-maybe-intangible
5304 (list 'invisible 'org-link
5305 'keymap org-mouse-map 'mouse-face 'highlight
5306 'font-lock-multiline t 'help-echo help)))
5307 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5308 'font-lock-multiline t 'help-echo help)))
5309 ;; We need to remove the invisible property here. Table narrowing
5310 ;; may have made some of this invisible.
5311 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5312 (remove-text-properties (match-beginning 0) (match-end 0)
5313 '(invisible nil))
5314 (if (match-end 3)
5315 (progn
5316 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5317 (org-rear-nonsticky-at (match-beginning 3))
5318 (add-text-properties (match-beginning 3) (match-end 3) vp)
5319 (org-rear-nonsticky-at (match-end 3))
5320 (add-text-properties (match-end 3) (match-end 0) ip)
5321 (org-rear-nonsticky-at (match-end 0)))
5322 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5323 (org-rear-nonsticky-at (match-beginning 1))
5324 (add-text-properties (match-beginning 1) (match-end 1) vp)
5325 (org-rear-nonsticky-at (match-end 1))
5326 (add-text-properties (match-end 1) (match-end 0) ip)
5327 (org-rear-nonsticky-at (match-end 0)))
5328 t)))
5330 (defun org-activate-dates (limit)
5331 "Run through the buffer and add overlays to dates."
5332 (if (re-search-forward org-tsr-regexp-both limit t)
5333 (progn
5334 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5335 (add-text-properties (match-beginning 0) (match-end 0)
5336 (list 'mouse-face 'highlight
5337 'keymap org-mouse-map))
5338 (org-rear-nonsticky-at (match-end 0))
5339 (when org-display-custom-times
5340 (if (match-end 3)
5341 (org-display-custom-time (match-beginning 3) (match-end 3)))
5342 (org-display-custom-time (match-beginning 1) (match-end 1)))
5343 t)))
5345 (defvar org-target-link-regexp nil
5346 "Regular expression matching radio targets in plain text.")
5347 (make-variable-buffer-local 'org-target-link-regexp)
5348 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5349 "Regular expression matching a link target.")
5350 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5351 "Regular expression matching a radio target.")
5352 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5353 "Regular expression matching any target.")
5355 (defun org-activate-target-links (limit)
5356 "Run through the buffer and add overlays to target matches."
5357 (when org-target-link-regexp
5358 (let ((case-fold-search t))
5359 (if (re-search-forward org-target-link-regexp limit t)
5360 (progn
5361 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5362 (add-text-properties (match-beginning 0) (match-end 0)
5363 (list 'mouse-face 'highlight
5364 'keymap org-mouse-map
5365 'help-echo "Radio target link"
5366 'org-linked-text t))
5367 (org-rear-nonsticky-at (match-end 0))
5368 t)))))
5370 (defun org-update-radio-target-regexp ()
5371 "Find all radio targets in this file and update the regular expression."
5372 (interactive)
5373 (when (memq 'radio org-activate-links)
5374 (setq org-target-link-regexp
5375 (org-make-target-link-regexp (org-all-targets 'radio)))
5376 (org-restart-font-lock)))
5378 (defun org-hide-wide-columns (limit)
5379 (let (s e)
5380 (setq s (text-property-any (point) (or limit (point-max))
5381 'org-cwidth t))
5382 (when s
5383 (setq e (next-single-property-change s 'org-cwidth))
5384 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5385 (goto-char e)
5386 t)))
5388 (defvar org-latex-and-specials-regexp nil
5389 "Regular expression for highlighting export special stuff.")
5390 (defvar org-match-substring-regexp)
5391 (defvar org-match-substring-with-braces-regexp)
5393 ;; This should be with the exporter code, but we also use if for font-locking
5394 (defconst org-export-html-special-string-regexps
5395 '(("\\\\-" . "&shy;")
5396 ("---\\([^-]\\)" . "&mdash;\\1")
5397 ("--\\([^-]\\)" . "&ndash;\\1")
5398 ("\\.\\.\\." . "&hellip;"))
5399 "Regular expressions for special string conversion.")
5402 (defun org-compute-latex-and-specials-regexp ()
5403 "Compute regular expression for stuff treated specially by exporters."
5404 (if (not org-highlight-latex-fragments-and-specials)
5405 (org-set-local 'org-latex-and-specials-regexp nil)
5406 (require 'org-exp)
5407 (let*
5408 ((matchers (plist-get org-format-latex-options :matchers))
5409 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5410 org-latex-regexps)))
5411 (org-export-allow-BIND nil)
5412 (options (org-combine-plists (org-default-export-plist)
5413 (org-infile-export-plist)))
5414 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5415 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5416 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5417 (org-export-html-expand (plist-get options :expand-quoted-html))
5418 (org-export-with-special-strings (plist-get options :special-strings))
5419 (re-sub
5420 (cond
5421 ((equal org-export-with-sub-superscripts '{})
5422 (list org-match-substring-with-braces-regexp))
5423 (org-export-with-sub-superscripts
5424 (list org-match-substring-regexp))
5425 (t nil)))
5426 (re-latex
5427 (if org-export-with-LaTeX-fragments
5428 (mapcar (lambda (x) (nth 1 x)) latexs)))
5429 (re-macros
5430 (if org-export-with-TeX-macros
5431 (list (concat "\\\\"
5432 (regexp-opt
5433 (append
5435 (delq nil
5436 (mapcar 'car-safe
5437 (append org-entities-user
5438 org-entities)))
5439 (if (boundp 'org-latex-entities)
5440 (mapcar (lambda (x)
5441 (or (car-safe x) x))
5442 org-latex-entities)
5443 nil))
5444 'words))) ; FIXME
5446 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5447 (re-special (if org-export-with-special-strings
5448 (mapcar (lambda (x) (car x))
5449 org-export-html-special-string-regexps)))
5450 (re-rest
5451 (delq nil
5452 (list
5453 (if org-export-html-expand "@<[^>\n]+>")
5454 ))))
5455 (org-set-local
5456 'org-latex-and-specials-regexp
5457 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5458 re-rest) "\\|")))))
5460 (defun org-do-latex-and-special-faces (limit)
5461 "Run through the buffer and add overlays to links."
5462 (when org-latex-and-specials-regexp
5463 (let (rtn d)
5464 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5465 limit t))
5466 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5467 'face))
5468 '(org-code org-verbatim underline)))
5469 (progn
5470 (setq rtn t
5471 d (cond ((member (char-after (1+ (match-beginning 0)))
5472 '(?_ ?^)) 1)
5473 (t 0)))
5474 (font-lock-prepend-text-property
5475 (+ d (match-beginning 0)) (match-end 0)
5476 'face 'org-latex-and-export-specials)
5477 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5478 '(font-lock-multiline t)))))
5479 rtn)))
5481 (defun org-restart-font-lock ()
5482 "Restart `font-lock-mode', to force refontification."
5483 (when (and (boundp 'font-lock-mode) font-lock-mode)
5484 (font-lock-mode -1)
5485 (font-lock-mode 1)))
5487 (defun org-all-targets (&optional radio)
5488 "Return a list of all targets in this file.
5489 With optional argument RADIO, only find radio targets."
5490 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5491 rtn)
5492 (save-excursion
5493 (goto-char (point-min))
5494 (while (re-search-forward re nil t)
5495 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5496 rtn)))
5498 (defun org-make-target-link-regexp (targets)
5499 "Make regular expression matching all strings in TARGETS.
5500 The regular expression finds the targets also if there is a line break
5501 between words."
5502 (and targets
5503 (concat
5504 "\\<\\("
5505 (mapconcat
5506 (lambda (x)
5507 (setq x (regexp-quote x))
5508 (while (string-match " +" x)
5509 (setq x (replace-match "\\s-+" t t x)))
5511 targets
5512 "\\|")
5513 "\\)\\>")))
5515 (defun org-activate-tags (limit)
5516 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5517 (progn
5518 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5519 (add-text-properties (match-beginning 1) (match-end 1)
5520 (list 'mouse-face 'highlight
5521 'keymap org-mouse-map))
5522 (org-rear-nonsticky-at (match-end 1))
5523 t)))
5525 (defun org-outline-level ()
5526 "Compute the outline level of the heading at point.
5527 This function assumes that the cursor is at the beginning of a line matched
5528 by `outline-regexp'. Otherwise it returns garbage.
5529 If this is called at a normal headline, the level is the number of stars.
5530 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5531 (save-excursion
5532 (looking-at outline-regexp)
5533 (1- (- (match-end 0) (match-beginning 0)))))
5535 (defvar org-font-lock-keywords nil)
5537 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5538 "Regular expression matching a property line.")
5540 (defvar org-font-lock-hook nil
5541 "Functions to be called for special font lock stuff.")
5543 (defvar org-font-lock-set-keywords-hook nil
5544 "Functions that can manipulate `org-font-lock-extra-keywords'.
5545 This is calles after `org-font-lock-extra-keywords' is defined, but before
5546 it is installed to be used by font lock. This can be useful if something
5547 needs to be inserted at a specific position in the font-lock sequence.")
5549 (defun org-font-lock-hook (limit)
5550 (run-hook-with-args 'org-font-lock-hook limit))
5552 (defun org-set-font-lock-defaults ()
5553 (let* ((em org-fontify-emphasized-text)
5554 (lk org-activate-links)
5555 (org-font-lock-extra-keywords
5556 (list
5557 ;; Call the hook
5558 '(org-font-lock-hook)
5559 ;; Headlines
5560 `(,(if org-fontify-whole-heading-line
5561 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5562 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5563 (1 (org-get-level-face 1))
5564 (2 (org-get-level-face 2))
5565 (3 (org-get-level-face 3)))
5566 ;; Table lines
5567 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5568 (1 'org-table t))
5569 ;; Table internals
5570 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5571 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5572 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5573 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5574 ;; Drawers
5575 (list org-drawer-regexp '(0 'org-special-keyword t))
5576 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5577 ;; Properties
5578 (list org-property-re
5579 '(1 'org-special-keyword t)
5580 '(3 'org-property-value t))
5581 ;; Links
5582 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5583 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5584 (if (memq 'plain lk) '(org-activate-plain-links))
5585 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5586 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5587 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5588 (if (memq 'footnote lk) '(org-activate-footnote-links))
5589 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5590 '(org-hide-wide-columns (0 nil append))
5591 ;; TODO lines
5592 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5593 '(1 (org-get-todo-face 1) t))
5594 ;; DONE
5595 (if org-fontify-done-headline
5596 (list (concat "^[*]+ +\\<\\("
5597 (mapconcat 'regexp-quote org-done-keywords "\\|")
5598 "\\)\\(.*\\)")
5599 '(2 'org-headline-done t))
5600 nil)
5601 ;; Priorities
5602 '(org-font-lock-add-priority-faces)
5603 ;; Tags
5604 '(org-font-lock-add-tag-faces)
5605 ;; Special keywords
5606 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5607 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5608 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5609 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5610 ;; Emphasis
5611 (if em
5612 (if (featurep 'xemacs)
5613 '(org-do-emphasis-faces (0 nil append))
5614 '(org-do-emphasis-faces)))
5615 ;; Checkboxes
5616 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5617 1 'org-checkbox prepend)
5618 (if (cdr (assq 'checkbox org-list-automatic-rules))
5619 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5620 (0 (org-get-checkbox-statistics-face) t)))
5621 ;; Description list items
5622 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5623 1 'bold prepend)
5624 ;; ARCHIVEd headings
5625 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5626 '(1 'org-archived prepend))
5627 ;; Specials
5628 '(org-do-latex-and-special-faces)
5629 '(org-fontify-entities)
5630 '(org-raise-scripts)
5631 ;; Code
5632 '(org-activate-code (1 'org-code t))
5633 ;; COMMENT
5634 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5635 "\\|" org-quote-string "\\)\\>")
5636 '(1 'org-special-keyword t))
5637 '("^#.*" (0 'font-lock-comment-face t))
5638 ;; Blocks and meta lines
5639 '(org-fontify-meta-lines-and-blocks)
5641 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5642 (run-hooks 'org-font-lock-set-keywords-hook)
5643 ;; Now set the full font-lock-keywords
5644 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5645 (org-set-local 'font-lock-defaults
5646 '(org-font-lock-keywords t nil nil backward-paragraph))
5647 (kill-local-variable 'font-lock-keywords) nil))
5649 (defun org-toggle-pretty-entities ()
5650 "Toggle the composition display of entities as UTF8 characters."
5651 (interactive)
5652 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5653 (org-restart-font-lock)
5654 (if org-pretty-entities
5655 (message "Entities are displayed as UTF8 characers")
5656 (save-restriction
5657 (widen)
5658 (org-decompose-region (point-min) (point-max))
5659 (message "Entities are displayed plain"))))
5661 (defun org-fontify-entities (limit)
5662 "Find an entity to fontify."
5663 (let (ee)
5664 (when org-pretty-entities
5665 (catch 'match
5666 (while (re-search-forward
5667 "\\\\\\([a-zA-Z][a-zA-Z0-9]*\\)\\($\\|[^[:alnum:]\n]\\)"
5668 limit t)
5669 (if (and (not (org-in-indented-comment-line))
5670 (setq ee (org-entity-get (match-string 1)))
5671 (= (length (nth 6 ee)) 1))
5672 (progn
5673 (add-text-properties
5674 (match-beginning 0) (match-end 1)
5675 (list 'font-lock-fontified t))
5676 (compose-region (match-beginning 0) (match-end 1)
5677 (nth 6 ee) nil)
5678 (backward-char 1)
5679 (throw 'match t))))
5680 nil))))
5682 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5683 "Fontify string S like in Org-mode."
5684 (with-temp-buffer
5685 (insert s)
5686 (let ((org-odd-levels-only odd-levels))
5687 (org-mode)
5688 (font-lock-fontify-buffer)
5689 (buffer-string))))
5691 (defvar org-m nil)
5692 (defvar org-l nil)
5693 (defvar org-f nil)
5694 (defun org-get-level-face (n)
5695 "Get the right face for match N in font-lock matching of headlines."
5696 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5697 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5698 (if org-cycle-level-faces
5699 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5700 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5701 (cond
5702 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5703 ((eq n 2) org-f)
5704 (t (if org-level-color-stars-only nil org-f))))
5707 (defun org-get-todo-face (kwd)
5708 "Get the right face for a TODO keyword KWD.
5709 If KWD is a number, get the corresponding match group."
5710 (if (numberp kwd) (setq kwd (match-string kwd)))
5711 (or (org-face-from-face-or-color
5712 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5713 (and (member kwd org-done-keywords) 'org-done)
5714 'org-todo))
5716 (defun org-face-from-face-or-color (context inherit face-or-color)
5717 "Create a face list that inherits INHERIT, but sets the foreground color.
5718 When FACE-OR-COLOR is not a string, just return it."
5719 (if (stringp face-or-color)
5720 (list :inherit inherit
5721 (cdr (assoc context org-faces-easy-properties))
5722 face-or-color)
5723 face-or-color))
5725 (defun org-font-lock-add-tag-faces (limit)
5726 "Add the special tag faces."
5727 (when (and org-tag-faces org-tags-special-faces-re)
5728 (while (re-search-forward org-tags-special-faces-re limit t)
5729 (add-text-properties (match-beginning 1) (match-end 1)
5730 (list 'face (org-get-tag-face 1)
5731 'font-lock-fontified t))
5732 (backward-char 1))))
5734 (defun org-font-lock-add-priority-faces (limit)
5735 "Add the special priority faces."
5736 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5737 (add-text-properties
5738 (match-beginning 0) (match-end 0)
5739 (list 'face (or (org-face-from-face-or-color
5740 'priority 'org-special-keyword
5741 (cdr (assoc (char-after (match-beginning 1))
5742 org-priority-faces)))
5743 'org-special-keyword)
5744 'font-lock-fontified t))))
5746 (defun org-get-tag-face (kwd)
5747 "Get the right face for a TODO keyword KWD.
5748 If KWD is a number, get the corresponding match group."
5749 (if (numberp kwd) (setq kwd (match-string kwd)))
5750 (or (org-face-from-face-or-color
5751 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5752 'org-tag))
5754 (defun org-unfontify-region (beg end &optional maybe_loudly)
5755 "Remove fontification and activation overlays from links."
5756 (font-lock-default-unfontify-region beg end)
5757 (let* ((buffer-undo-list t)
5758 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5759 (inhibit-modification-hooks t)
5760 deactivate-mark buffer-file-name buffer-file-truename)
5761 (org-decompose-region beg end)
5762 (remove-text-properties
5763 beg end
5764 (if org-indent-mode
5765 ;; also remove line-prefix and wrap-prefix properties
5766 '(mouse-face t keymap t org-linked-text t
5767 invisible t intangible t
5768 line-prefix t wrap-prefix t
5769 org-no-flyspell t org-emphasis t)
5770 '(mouse-face t keymap t org-linked-text t
5771 invisible t intangible t
5772 org-no-flyspell t org-emphasis t)))
5773 (org-remove-font-lock-display-properties beg end)))
5775 (defconst org-script-display '(((raise -0.3) (height 0.7))
5776 ((raise 0.3) (height 0.7))
5777 ((raise -0.5))
5778 ((raise 0.5)))
5779 "Display properties for showing superscripts and subscripts.")
5781 (defun org-remove-font-lock-display-properties (beg end)
5782 "Remove specific display properties that have been added by font lock.
5783 The will remove the raise properties that are used to show superscripts
5784 and subscripts."
5785 (let (next prop)
5786 (while (< beg end)
5787 (setq next (next-single-property-change beg 'display nil end)
5788 prop (get-text-property beg 'display))
5789 (if (member prop org-script-display)
5790 (put-text-property beg next 'display nil))
5791 (setq beg next))))
5793 (defun org-raise-scripts (limit)
5794 "Add raise properties to sub/superscripts."
5795 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5796 (if (re-search-forward
5797 (if (eq org-use-sub-superscripts t)
5798 org-match-substring-regexp
5799 org-match-substring-with-braces-regexp)
5800 limit t)
5801 (let* ((pos (point)) table-p comment-p
5802 (mpos (match-beginning 3))
5803 (emph-p (get-text-property mpos 'org-emphasis))
5804 (link-p (get-text-property mpos 'mouse-face))
5805 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5806 (goto-char (point-at-bol))
5807 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5808 comment-p (org-looking-at-p "[ \t]*#"))
5809 (goto-char pos)
5810 ;; FIXME: Should we go back one character here, for a_b^c
5811 ;; (goto-char (1- pos)) ;????????????????????
5812 (if (or comment-p emph-p link-p keyw-p)
5814 (put-text-property (match-beginning 3) (match-end 0)
5815 'display
5816 (if (equal (char-after (match-beginning 2)) ?^)
5817 (nth (if table-p 3 1) org-script-display)
5818 (nth (if table-p 2 0) org-script-display)))
5819 (add-text-properties (match-beginning 2) (match-end 2)
5820 (list 'invisible t
5821 'org-dwidth t 'org-dwidth-n 1))
5822 (if (and (eq (char-after (match-beginning 3)) ?{)
5823 (eq (char-before (match-end 3)) ?}))
5824 (progn
5825 (add-text-properties
5826 (match-beginning 3) (1+ (match-beginning 3))
5827 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
5828 (add-text-properties
5829 (1- (match-end 3)) (match-end 3)
5830 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
5831 t)))))
5833 ;;;; Visibility cycling, including org-goto and indirect buffer
5835 ;;; Cycling
5837 (defvar org-cycle-global-status nil)
5838 (make-variable-buffer-local 'org-cycle-global-status)
5839 (defvar org-cycle-subtree-status nil)
5840 (make-variable-buffer-local 'org-cycle-subtree-status)
5842 ;;;###autoload
5844 (defvar org-inlinetask-min-level)
5846 (defun org-cycle (&optional arg)
5847 "TAB-action and visibility cycling for Org-mode.
5849 This is the command invoked in Org-mode by the TAB key. Its main purpose
5850 is outline visibility cycling, but it also invokes other actions
5851 in special contexts.
5853 - When this function is called with a prefix argument, rotate the entire
5854 buffer through 3 states (global cycling)
5855 1. OVERVIEW: Show only top-level headlines.
5856 2. CONTENTS: Show all headlines of all levels, but no body text.
5857 3. SHOW ALL: Show everything.
5858 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5859 determined by the variable `org-startup-folded', and by any VISIBILITY
5860 properties in the buffer.
5861 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5862 including any drawers.
5864 - When inside a table, re-align the table and move to the next field.
5866 - When point is at the beginning of a headline, rotate the subtree started
5867 by this line through 3 different states (local cycling)
5868 1. FOLDED: Only the main headline is shown.
5869 2. CHILDREN: The main headline and the direct children are shown.
5870 From this state, you can move to one of the children
5871 and zoom in further.
5872 3. SUBTREE: Show the entire subtree, including body text.
5873 If there is no subtree, switch directly from CHILDREN to FOLDED.
5875 - When point is at the beginning of an empty headline and the variable
5876 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5877 of the headline by demoting and promoting it to likely levels. This
5878 speeds up creation document structure by pressing TAB once or several
5879 times right after creating a new headline.
5881 - When there is a numeric prefix, go up to a heading with level ARG, do
5882 a `show-subtree' and return to the previous cursor position. If ARG
5883 is negative, go up that many levels.
5885 - When point is not at the beginning of a headline, execute the global
5886 binding for TAB, which is re-indenting the line. See the option
5887 `org-cycle-emulate-tab' for details.
5889 - Special case: if point is at the beginning of the buffer and there is
5890 no headline in line 1, this function will act as if called with prefix arg
5891 (C-u TAB, same as S-TAB) also when called without prefix arg.
5892 But only if also the variable `org-cycle-global-at-bob' is t."
5893 (interactive "P")
5894 (org-load-modules-maybe)
5895 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5896 (and org-cycle-level-after-item/entry-creation
5897 (or (org-cycle-level)
5898 (org-cycle-item-indentation))))
5899 (let* ((limit-level
5900 (or org-cycle-max-level
5901 (and (boundp 'org-inlinetask-min-level)
5902 org-inlinetask-min-level
5903 (1- org-inlinetask-min-level))))
5904 (nstars (and limit-level
5905 (if org-odd-levels-only
5906 (and limit-level (1- (* limit-level 2)))
5907 limit-level)))
5908 (outline-regexp
5909 (if (not (org-mode-p))
5910 outline-regexp
5911 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
5912 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
5913 (not (looking-at outline-regexp))))
5914 (org-cycle-hook
5915 (if bob-special
5916 (delq 'org-optimize-window-after-visibility-change
5917 (copy-sequence org-cycle-hook))
5918 org-cycle-hook))
5919 (pos (point)))
5921 (if (or bob-special (equal arg '(4)))
5922 ;; special case: use global cycling
5923 (setq arg t))
5925 (cond
5927 ((equal arg '(16))
5928 (setq last-command 'dummy)
5929 (org-set-startup-visibility)
5930 (message "Startup visibility, plus VISIBILITY properties"))
5932 ((equal arg '(64))
5933 (show-all)
5934 (message "Entire buffer visible, including drawers"))
5936 ;; Table: enter it or move to the next field.
5937 ((org-at-table-p 'any)
5938 (if (org-at-table.el-p)
5939 (message "Use C-c ' to edit table.el tables")
5940 (if arg (org-table-edit-field t)
5941 (org-table-justify-field-maybe)
5942 (call-interactively 'org-table-next-field))))
5944 ((run-hook-with-args-until-success
5945 'org-tab-after-check-for-table-hook))
5947 ;; Global cycling: delegate to `org-cycle-internal-global'.
5948 ((eq arg t) (org-cycle-internal-global))
5950 ;; Drawers: delegate to `org-flag-drawer'.
5951 ((and org-drawers org-drawer-regexp
5952 (save-excursion
5953 (beginning-of-line 1)
5954 (looking-at org-drawer-regexp)))
5955 (org-flag-drawer ; toggle block visibility
5956 (not (get-char-property (match-end 0) 'invisible))))
5958 ;; Show-subtree, ARG levels up from here.
5959 ((integerp arg)
5960 (save-excursion
5961 (org-back-to-heading)
5962 (outline-up-heading (if (< arg 0) (- arg)
5963 (- (funcall outline-level) arg)))
5964 (org-show-subtree)))
5966 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
5967 ((and (featurep 'org-inlinetask)
5968 (org-inlinetask-at-task-p)
5969 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5970 (org-inlinetask-toggle-visibility))
5972 ;; At an item/headline: delegate to `org-cycle-internal-local'.
5973 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
5974 (save-excursion (beginning-of-line 1)
5975 (looking-at outline-regexp)))
5976 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5977 (org-cycle-internal-local))
5979 ;; From there: TAB emulation and template completion.
5980 (buffer-read-only (org-back-to-heading))
5982 ((run-hook-with-args-until-success
5983 'org-tab-after-check-for-cycling-hook))
5985 ((org-try-structure-completion))
5987 ((org-try-cdlatex-tab))
5989 ((run-hook-with-args-until-success
5990 'org-tab-before-tab-emulation-hook))
5992 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5993 (or (not (bolp))
5994 (not (looking-at outline-regexp))))
5995 (call-interactively (global-key-binding "\t")))
5997 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5998 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5999 (or (and (eq org-cycle-emulate-tab 'white)
6000 (= (match-end 0) (point-at-eol)))
6001 (and (eq org-cycle-emulate-tab 'whitestart)
6002 (>= (match-end 0) pos))))
6004 (eq org-cycle-emulate-tab t))
6005 (call-interactively (global-key-binding "\t")))
6007 (t (save-excursion
6008 (org-back-to-heading)
6009 (org-cycle)))))))
6011 (defun org-cycle-internal-global ()
6012 "Do the global cycling action."
6013 (cond
6014 ((and (eq last-command this-command)
6015 (eq org-cycle-global-status 'overview))
6016 ;; We just created the overview - now do table of contents
6017 ;; This can be slow in very large buffers, so indicate action
6018 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6019 (message "CONTENTS...")
6020 (org-content)
6021 (message "CONTENTS...done")
6022 (setq org-cycle-global-status 'contents)
6023 (run-hook-with-args 'org-cycle-hook 'contents))
6025 ((and (eq last-command this-command)
6026 (eq org-cycle-global-status 'contents))
6027 ;; We just showed the table of contents - now show everything
6028 (run-hook-with-args 'org-pre-cycle-hook 'all)
6029 (show-all)
6030 (message "SHOW ALL")
6031 (setq org-cycle-global-status 'all)
6032 (run-hook-with-args 'org-cycle-hook 'all))
6035 ;; Default action: go to overview
6036 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6037 (org-overview)
6038 (message "OVERVIEW")
6039 (setq org-cycle-global-status 'overview)
6040 (run-hook-with-args 'org-cycle-hook 'overview))))
6042 (defun org-cycle-internal-local ()
6043 "Do the local cycling action."
6044 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6045 ;; First, determine end of headline (EOH), end of subtree or item
6046 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6047 (save-excursion
6048 (if (org-at-item-p)
6049 (progn
6050 (beginning-of-line)
6051 (setq struct (org-list-struct))
6052 (setq eoh (point-at-eol))
6053 (setq eos (org-list-get-item-end-before-blank (point) struct))
6054 (setq has-children (org-list-has-child-p (point) struct)))
6055 (org-back-to-heading)
6056 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6057 (setq eos (save-excursion
6058 (org-end-of-subtree t)
6059 (unless (eobp)
6060 (skip-chars-forward " \t\n"))
6061 (if (eobp) (point) (1- (point)))))
6062 (setq has-children
6063 (or (save-excursion
6064 (let ((level (funcall outline-level)))
6065 (outline-next-heading)
6066 (and (org-at-heading-p t)
6067 (> (funcall outline-level) level))))
6068 (save-excursion
6069 (org-list-search-forward (org-item-beginning-re) eos t)))))
6070 ;; Determine end invisible part of buffer (EOL)
6071 (beginning-of-line 2)
6072 ;; XEmacs doesn't have `next-single-char-property-change'
6073 (if (featurep 'xemacs)
6074 (while (and (not (eobp)) ;; this is like `next-line'
6075 (get-char-property (1- (point)) 'invisible))
6076 (beginning-of-line 2))
6077 (while (and (not (eobp)) ;; this is like `next-line'
6078 (get-char-property (1- (point)) 'invisible))
6079 (goto-char (next-single-char-property-change (point) 'invisible))
6080 (and (eolp) (beginning-of-line 2))))
6081 (setq eol (point)))
6082 ;; Find out what to do next and set `this-command'
6083 (cond
6084 ((= eos eoh)
6085 ;; Nothing is hidden behind this heading
6086 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6087 (message "EMPTY ENTRY")
6088 (setq org-cycle-subtree-status nil)
6089 (save-excursion
6090 (goto-char eos)
6091 (outline-next-heading)
6092 (if (outline-invisible-p) (org-flag-heading nil))))
6093 ((and (or (>= eol eos)
6094 (not (string-match "\\S-" (buffer-substring eol eos))))
6095 (or has-children
6096 (not (setq children-skipped
6097 org-cycle-skip-children-state-if-no-children))))
6098 ;; Entire subtree is hidden in one line: children view
6099 (run-hook-with-args 'org-pre-cycle-hook 'children)
6100 (if (org-at-item-p)
6101 (org-list-set-item-visibility (point-at-bol) struct 'children)
6102 (org-show-entry)
6103 (show-children)
6104 ;; Fold every list in subtree to top-level items.
6105 (when (eq org-cycle-include-plain-lists 'integrate)
6106 (save-excursion
6107 (org-back-to-heading)
6108 (while (org-list-search-forward (org-item-beginning-re) eos t)
6109 (beginning-of-line 1)
6110 (let* ((struct (org-list-struct))
6111 (prevs (org-list-prevs-alist struct))
6112 (end (org-list-get-bottom-point struct)))
6113 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6114 (org-list-get-all-items (point) struct prevs))
6115 (goto-char end))))))
6116 (message "CHILDREN")
6117 (save-excursion
6118 (goto-char eos)
6119 (outline-next-heading)
6120 (if (outline-invisible-p) (org-flag-heading nil)))
6121 (setq org-cycle-subtree-status 'children)
6122 (run-hook-with-args 'org-cycle-hook 'children))
6123 ((or children-skipped
6124 (and (eq last-command this-command)
6125 (eq org-cycle-subtree-status 'children)))
6126 ;; We just showed the children, or no children are there,
6127 ;; now show everything.
6128 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6129 (outline-flag-region eoh eos nil)
6130 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6131 (setq org-cycle-subtree-status 'subtree)
6132 (run-hook-with-args 'org-cycle-hook 'subtree))
6134 ;; Default action: hide the subtree.
6135 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6136 (outline-flag-region eoh eos t)
6137 (message "FOLDED")
6138 (setq org-cycle-subtree-status 'folded)
6139 (run-hook-with-args 'org-cycle-hook 'folded)))))
6141 ;;;###autoload
6142 (defun org-global-cycle (&optional arg)
6143 "Cycle the global visibility. For details see `org-cycle'.
6144 With \\[universal-argument] prefix arg, switch to startup visibility.
6145 With a numeric prefix, show all headlines up to that level."
6146 (interactive "P")
6147 (let ((org-cycle-include-plain-lists
6148 (if (org-mode-p) org-cycle-include-plain-lists nil)))
6149 (cond
6150 ((integerp arg)
6151 (show-all)
6152 (hide-sublevels arg)
6153 (setq org-cycle-global-status 'contents))
6154 ((equal arg '(4))
6155 (org-set-startup-visibility)
6156 (message "Startup visibility, plus VISIBILITY properties."))
6158 (org-cycle '(4))))))
6160 (defun org-set-startup-visibility ()
6161 "Set the visibility required by startup options and properties."
6162 (cond
6163 ((eq org-startup-folded t)
6164 (org-cycle '(4)))
6165 ((eq org-startup-folded 'content)
6166 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6167 (org-cycle '(4)) (org-cycle '(4)))))
6168 (unless (eq org-startup-folded 'showeverything)
6169 (if org-hide-block-startup (org-hide-block-all))
6170 (org-set-visibility-according-to-property 'no-cleanup)
6171 (org-cycle-hide-archived-subtrees 'all)
6172 (org-cycle-hide-drawers 'all)
6173 (org-cycle-show-empty-lines t)))
6175 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6176 "Switch subtree visibilities according to :VISIBILITY: property."
6177 (interactive)
6178 (let (org-show-entry-below state)
6179 (save-excursion
6180 (goto-char (point-min))
6181 (while (re-search-forward
6182 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6183 nil t)
6184 (setq state (match-string 1))
6185 (save-excursion
6186 (org-back-to-heading t)
6187 (hide-subtree)
6188 (org-reveal)
6189 (cond
6190 ((equal state '("fold" "folded"))
6191 (hide-subtree))
6192 ((equal state "children")
6193 (org-show-hidden-entry)
6194 (show-children))
6195 ((equal state "content")
6196 (save-excursion
6197 (save-restriction
6198 (org-narrow-to-subtree)
6199 (org-content))))
6200 ((member state '("all" "showall"))
6201 (show-subtree)))))
6202 (unless no-cleanup
6203 (org-cycle-hide-archived-subtrees 'all)
6204 (org-cycle-hide-drawers 'all)
6205 (org-cycle-show-empty-lines 'all)))))
6207 (defun org-overview ()
6208 "Switch to overview mode, showing only top-level headlines.
6209 Really, this shows all headlines with level equal or greater than the level
6210 of the first headline in the buffer. This is important, because if the
6211 first headline is not level one, then (hide-sublevels 1) gives confusing
6212 results."
6213 (interactive)
6214 (let ((level (save-excursion
6215 (goto-char (point-min))
6216 (if (re-search-forward (concat "^" outline-regexp) nil t)
6217 (progn
6218 (goto-char (match-beginning 0))
6219 (funcall outline-level))))))
6220 (and level (hide-sublevels level))))
6222 (defun org-content (&optional arg)
6223 "Show all headlines in the buffer, like a table of contents.
6224 With numerical argument N, show content up to level N."
6225 (interactive "P")
6226 (save-excursion
6227 ;; Visit all headings and show their offspring
6228 (and (integerp arg) (org-overview))
6229 (goto-char (point-max))
6230 (catch 'exit
6231 (while (and (progn (condition-case nil
6232 (outline-previous-visible-heading 1)
6233 (error (goto-char (point-min))))
6235 (looking-at outline-regexp))
6236 (if (integerp arg)
6237 (show-children (1- arg))
6238 (show-branches))
6239 (if (bobp) (throw 'exit nil))))))
6242 (defun org-optimize-window-after-visibility-change (state)
6243 "Adjust the window after a change in outline visibility.
6244 This function is the default value of the hook `org-cycle-hook'."
6245 (when (get-buffer-window (current-buffer))
6246 (cond
6247 ((eq state 'content) nil)
6248 ((eq state 'all) nil)
6249 ((eq state 'folded) nil)
6250 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6251 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6253 (defun org-remove-empty-overlays-at (pos)
6254 "Remove outline overlays that do not contain non-white stuff."
6255 (mapc
6256 (lambda (o)
6257 (and (eq 'outline (overlay-get o 'invisible))
6258 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6259 (overlay-end o))))
6260 (delete-overlay o)))
6261 (overlays-at pos)))
6263 (defun org-clean-visibility-after-subtree-move ()
6264 "Fix visibility issues after moving a subtree."
6265 ;; First, find a reasonable region to look at:
6266 ;; Start two siblings above, end three below
6267 (let* ((beg (save-excursion
6268 (and (org-get-last-sibling)
6269 (org-get-last-sibling))
6270 (point)))
6271 (end (save-excursion
6272 (and (org-get-next-sibling)
6273 (org-get-next-sibling)
6274 (org-get-next-sibling))
6275 (if (org-at-heading-p)
6276 (point-at-eol)
6277 (point))))
6278 (level (looking-at "\\*+"))
6279 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6280 (save-excursion
6281 (save-restriction
6282 (narrow-to-region beg end)
6283 (when re
6284 ;; Properly fold already folded siblings
6285 (goto-char (point-min))
6286 (while (re-search-forward re nil t)
6287 (if (and (not (outline-invisible-p))
6288 (save-excursion
6289 (goto-char (point-at-eol)) (outline-invisible-p)))
6290 (hide-entry))))
6291 (org-cycle-show-empty-lines 'overview)
6292 (org-cycle-hide-drawers 'overview)))))
6294 (defun org-cycle-show-empty-lines (state)
6295 "Show empty lines above all visible headlines.
6296 The region to be covered depends on STATE when called through
6297 `org-cycle-hook'. Lisp program can use t for STATE to get the
6298 entire buffer covered. Note that an empty line is only shown if there
6299 are at least `org-cycle-separator-lines' empty lines before the headline."
6300 (when (not (= org-cycle-separator-lines 0))
6301 (save-excursion
6302 (let* ((n (abs org-cycle-separator-lines))
6303 (re (cond
6304 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6305 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6306 (t (let ((ns (number-to-string (- n 2))))
6307 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6308 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6309 beg end b e)
6310 (cond
6311 ((memq state '(overview contents t))
6312 (setq beg (point-min) end (point-max)))
6313 ((memq state '(children folded))
6314 (setq beg (point) end (progn (org-end-of-subtree t t)
6315 (beginning-of-line 2)
6316 (point)))))
6317 (when beg
6318 (goto-char beg)
6319 (while (re-search-forward re end t)
6320 (unless (get-char-property (match-end 1) 'invisible)
6321 (setq e (match-end 1))
6322 (if (< org-cycle-separator-lines 0)
6323 (setq b (save-excursion
6324 (goto-char (match-beginning 0))
6325 (org-back-over-empty-lines)
6326 (if (save-excursion
6327 (goto-char (max (point-min) (1- (point))))
6328 (org-on-heading-p))
6329 (1- (point))
6330 (point))))
6331 (setq b (match-beginning 1)))
6332 (outline-flag-region b e nil)))))))
6333 ;; Never hide empty lines at the end of the file.
6334 (save-excursion
6335 (goto-char (point-max))
6336 (outline-previous-heading)
6337 (outline-end-of-heading)
6338 (if (and (looking-at "[ \t\n]+")
6339 (= (match-end 0) (point-max)))
6340 (outline-flag-region (point) (match-end 0) nil))))
6342 (defun org-show-empty-lines-in-parent ()
6343 "Move to the parent and re-show empty lines before visible headlines."
6344 (save-excursion
6345 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6346 (org-cycle-show-empty-lines context))))
6348 (defun org-files-list ()
6349 "Return `org-agenda-files' list, plus all open org-mode files.
6350 This is useful for operations that need to scan all of a user's
6351 open and agenda-wise Org files."
6352 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6353 (dolist (buf (buffer-list))
6354 (with-current-buffer buf
6355 (if (and (org-mode-p) (buffer-file-name))
6356 (let ((file (expand-file-name (buffer-file-name))))
6357 (unless (member file files)
6358 (push file files))))))
6359 files))
6361 (defsubst org-entry-beginning-position ()
6362 "Return the beginning position of the current entry."
6363 (save-excursion (outline-back-to-heading t) (point)))
6365 (defsubst org-entry-end-position ()
6366 "Return the end position of the current entry."
6367 (save-excursion (outline-next-heading) (point)))
6369 (defun org-cycle-hide-drawers (state)
6370 "Re-hide all drawers after a visibility state change."
6371 (when (and (org-mode-p)
6372 (not (memq state '(overview folded contents))))
6373 (save-excursion
6374 (let* ((globalp (memq state '(contents all)))
6375 (beg (if globalp (point-min) (point)))
6376 (end (if globalp (point-max)
6377 (if (eq state 'children)
6378 (save-excursion (outline-next-heading) (point))
6379 (org-end-of-subtree t)))))
6380 (goto-char beg)
6381 (while (re-search-forward org-drawer-regexp end t)
6382 (org-flag-drawer t))))))
6384 (defun org-flag-drawer (flag)
6385 (save-excursion
6386 (beginning-of-line 1)
6387 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6388 (let ((b (match-end 0))
6389 (outline-regexp org-outline-regexp))
6390 (if (re-search-forward
6391 "^[ \t]*:END:"
6392 (save-excursion (outline-next-heading) (point)) t)
6393 (outline-flag-region b (point-at-eol) flag)
6394 (error ":END: line missing at position %s" b))))))
6396 (defun org-subtree-end-visible-p ()
6397 "Is the end of the current subtree visible?"
6398 (pos-visible-in-window-p
6399 (save-excursion (org-end-of-subtree t) (point))))
6401 (defun org-first-headline-recenter (&optional N)
6402 "Move cursor to the first headline and recenter the headline.
6403 Optional argument N means put the headline into the Nth line of the window."
6404 (goto-char (point-min))
6405 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6406 (beginning-of-line)
6407 (recenter (prefix-numeric-value N))))
6409 ;;; Saving and restoring visibility
6411 (defun org-outline-overlay-data (&optional use-markers)
6412 "Return a list of the locations of all outline overlays.
6413 These are overlays with the `invisible' property value `outline'.
6414 The return value is a list of cons cells, with start and stop
6415 positions for each overlay.
6416 If USE-MARKERS is set, return the positions as markers."
6417 (let (beg end)
6418 (save-excursion
6419 (save-restriction
6420 (widen)
6421 (delq nil
6422 (mapcar (lambda (o)
6423 (when (eq (overlay-get o 'invisible) 'outline)
6424 (setq beg (overlay-start o)
6425 end (overlay-end o))
6426 (and beg end (> end beg)
6427 (if use-markers
6428 (cons (move-marker (make-marker) beg)
6429 (move-marker (make-marker) end))
6430 (cons beg end)))))
6431 (overlays-in (point-min) (point-max))))))))
6433 (defun org-set-outline-overlay-data (data)
6434 "Create visibility overlays for all positions in DATA.
6435 DATA should have been made by `org-outline-overlay-data'."
6436 (let (o)
6437 (save-excursion
6438 (save-restriction
6439 (widen)
6440 (show-all)
6441 (mapc (lambda (c)
6442 (setq o (make-overlay (car c) (cdr c)))
6443 (overlay-put o 'invisible 'outline))
6444 data)))))
6446 ;;; Folding of blocks
6448 (defconst org-block-regexp
6449 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
6450 "Regular expression for hiding blocks.")
6452 (defvar org-hide-block-overlays nil
6453 "Overlays hiding blocks.")
6454 (make-variable-buffer-local 'org-hide-block-overlays)
6456 (defun org-block-map (function &optional start end)
6457 "Call FUNCTION at the head of all source blocks in the current buffer.
6458 Optional arguments START and END can be used to limit the range."
6459 (let ((start (or start (point-min)))
6460 (end (or end (point-max))))
6461 (save-excursion
6462 (goto-char start)
6463 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6464 (save-excursion
6465 (save-match-data
6466 (goto-char (match-beginning 0))
6467 (funcall function)))))))
6469 (defun org-hide-block-toggle-all ()
6470 "Toggle the visibility of all blocks in the current buffer."
6471 (org-block-map #'org-hide-block-toggle))
6473 (defun org-hide-block-all ()
6474 "Fold all blocks in the current buffer."
6475 (interactive)
6476 (org-show-block-all)
6477 (org-block-map #'org-hide-block-toggle-maybe))
6479 (defun org-show-block-all ()
6480 "Unfold all blocks in the current buffer."
6481 (interactive)
6482 (mapc 'delete-overlay org-hide-block-overlays)
6483 (setq org-hide-block-overlays nil))
6485 (defun org-hide-block-toggle-maybe ()
6486 "Toggle visibility of block at point."
6487 (interactive)
6488 (let ((case-fold-search t))
6489 (if (save-excursion
6490 (beginning-of-line 1)
6491 (looking-at org-block-regexp))
6492 (progn (org-hide-block-toggle)
6493 t) ;; to signal that we took action
6494 nil))) ;; to signal that we did not
6496 (defun org-hide-block-toggle (&optional force)
6497 "Toggle the visibility of the current block."
6498 (interactive)
6499 (save-excursion
6500 (beginning-of-line)
6501 (if (re-search-forward org-block-regexp nil t)
6502 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6503 (end (match-end 0)) ;; end of entire body
6505 (if (memq t (mapcar (lambda (overlay)
6506 (eq (overlay-get overlay 'invisible)
6507 'org-hide-block))
6508 (overlays-at start)))
6509 (if (or (not force) (eq force 'off))
6510 (mapc (lambda (ov)
6511 (when (member ov org-hide-block-overlays)
6512 (setq org-hide-block-overlays
6513 (delq ov org-hide-block-overlays)))
6514 (when (eq (overlay-get ov 'invisible)
6515 'org-hide-block)
6516 (delete-overlay ov)))
6517 (overlays-at start)))
6518 (setq ov (make-overlay start end))
6519 (overlay-put ov 'invisible 'org-hide-block)
6520 ;; make the block accessible to isearch
6521 (overlay-put
6522 ov 'isearch-open-invisible
6523 (lambda (ov)
6524 (when (member ov org-hide-block-overlays)
6525 (setq org-hide-block-overlays
6526 (delq ov org-hide-block-overlays)))
6527 (when (eq (overlay-get ov 'invisible)
6528 'org-hide-block)
6529 (delete-overlay ov))))
6530 (push ov org-hide-block-overlays)))
6531 (error "Not looking at a source block"))))
6533 ;; org-tab-after-check-for-cycling-hook
6534 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6535 ;; Remove overlays when changing major mode
6536 (add-hook 'org-mode-hook
6537 (lambda () (org-add-hook 'change-major-mode-hook
6538 'org-show-block-all 'append 'local)))
6540 ;;; Org-goto
6542 (defvar org-goto-window-configuration nil)
6543 (defvar org-goto-marker nil)
6544 (defvar org-goto-map
6545 (let ((map (make-sparse-keymap)))
6546 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6547 (while (setq cmd (pop cmds))
6548 (substitute-key-definition cmd cmd map global-map)))
6549 (suppress-keymap map)
6550 (org-defkey map "\C-m" 'org-goto-ret)
6551 (org-defkey map [(return)] 'org-goto-ret)
6552 (org-defkey map [(left)] 'org-goto-left)
6553 (org-defkey map [(right)] 'org-goto-right)
6554 (org-defkey map [(control ?g)] 'org-goto-quit)
6555 (org-defkey map "\C-i" 'org-cycle)
6556 (org-defkey map [(tab)] 'org-cycle)
6557 (org-defkey map [(down)] 'outline-next-visible-heading)
6558 (org-defkey map [(up)] 'outline-previous-visible-heading)
6559 (if org-goto-auto-isearch
6560 (if (fboundp 'define-key-after)
6561 (define-key-after map [t] 'org-goto-local-auto-isearch)
6562 nil)
6563 (org-defkey map "q" 'org-goto-quit)
6564 (org-defkey map "n" 'outline-next-visible-heading)
6565 (org-defkey map "p" 'outline-previous-visible-heading)
6566 (org-defkey map "f" 'outline-forward-same-level)
6567 (org-defkey map "b" 'outline-backward-same-level)
6568 (org-defkey map "u" 'outline-up-heading))
6569 (org-defkey map "/" 'org-occur)
6570 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6571 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6572 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6573 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6574 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6575 map))
6577 (defconst org-goto-help
6578 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6579 RET=jump to location [Q]uit and return to previous location
6580 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6582 (defvar org-goto-start-pos) ; dynamically scoped parameter
6584 ;; FIXME: Docstring does not mention both interfaces
6585 (defun org-goto (&optional alternative-interface)
6586 "Look up a different location in the current file, keeping current visibility.
6588 When you want look-up or go to a different location in a document, the
6589 fastest way is often to fold the entire buffer and then dive into the tree.
6590 This method has the disadvantage, that the previous location will be folded,
6591 which may not be what you want.
6593 This command works around this by showing a copy of the current buffer
6594 in an indirect buffer, in overview mode. You can dive into the tree in
6595 that copy, use org-occur and incremental search to find a location.
6596 When pressing RET or `Q', the command returns to the original buffer in
6597 which the visibility is still unchanged. After RET is will also jump to
6598 the location selected in the indirect buffer and expose the headline
6599 hierarchy above."
6600 (interactive "P")
6601 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6602 (org-refile-use-outline-path t)
6603 (org-refile-target-verify-function nil)
6604 (interface
6605 (if (not alternative-interface)
6606 org-goto-interface
6607 (if (eq org-goto-interface 'outline)
6608 'outline-path-completion
6609 'outline)))
6610 (org-goto-start-pos (point))
6611 (selected-point
6612 (if (eq interface 'outline)
6613 (car (org-get-location (current-buffer) org-goto-help))
6614 (let ((pa (org-refile-get-location "Goto")))
6615 (org-refile-check-position pa)
6616 (nth 3 pa)))))
6617 (if selected-point
6618 (progn
6619 (org-mark-ring-push org-goto-start-pos)
6620 (goto-char selected-point)
6621 (if (or (outline-invisible-p) (org-invisible-p2))
6622 (org-show-context 'org-goto)))
6623 (message "Quit"))))
6625 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6626 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6627 (defvar org-goto-local-auto-isearch-map) ; defined below
6629 (defun org-get-location (buf help)
6630 "Let the user select a location in the Org-mode buffer BUF.
6631 This function uses a recursive edit. It returns the selected position
6632 or nil."
6633 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6634 (isearch-hide-immediately nil)
6635 (isearch-search-fun-function
6636 (lambda () 'org-goto-local-search-headings))
6637 (org-goto-selected-point org-goto-exit-command)
6638 (pop-up-frames nil)
6639 (special-display-buffer-names nil)
6640 (special-display-regexps nil)
6641 (special-display-function nil))
6642 (save-excursion
6643 (save-window-excursion
6644 (delete-other-windows)
6645 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6646 (switch-to-buffer
6647 (condition-case nil
6648 (make-indirect-buffer (current-buffer) "*org-goto*")
6649 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6650 (with-output-to-temp-buffer "*Help*"
6651 (princ help))
6652 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6653 (setq buffer-read-only nil)
6654 (let ((org-startup-truncated t)
6655 (org-startup-folded nil)
6656 (org-startup-align-all-tables nil))
6657 (org-mode)
6658 (org-overview))
6659 (setq buffer-read-only t)
6660 (if (and (boundp 'org-goto-start-pos)
6661 (integer-or-marker-p org-goto-start-pos))
6662 (let ((org-show-hierarchy-above t)
6663 (org-show-siblings t)
6664 (org-show-following-heading t))
6665 (goto-char org-goto-start-pos)
6666 (and (outline-invisible-p) (org-show-context)))
6667 (goto-char (point-min)))
6668 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6669 (message "Select location and press RET")
6670 (use-local-map org-goto-map)
6671 (recursive-edit)
6673 (kill-buffer "*org-goto*")
6674 (cons org-goto-selected-point org-goto-exit-command)))
6676 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6677 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6678 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6679 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6681 (defun org-goto-local-search-headings (string bound noerror)
6682 "Search and make sure that any matches are in headlines."
6683 (catch 'return
6684 (while (if isearch-forward
6685 (search-forward string bound noerror)
6686 (search-backward string bound noerror))
6687 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6688 (and (member :headline context)
6689 (not (member :tags context))))
6690 (throw 'return (point))))))
6692 (defun org-goto-local-auto-isearch ()
6693 "Start isearch."
6694 (interactive)
6695 (goto-char (point-min))
6696 (let ((keys (this-command-keys)))
6697 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6698 (isearch-mode t)
6699 (isearch-process-search-char (string-to-char keys)))))
6701 (defun org-goto-ret (&optional arg)
6702 "Finish `org-goto' by going to the new location."
6703 (interactive "P")
6704 (setq org-goto-selected-point (point)
6705 org-goto-exit-command 'return)
6706 (throw 'exit nil))
6708 (defun org-goto-left ()
6709 "Finish `org-goto' by going to the new location."
6710 (interactive)
6711 (if (org-on-heading-p)
6712 (progn
6713 (beginning-of-line 1)
6714 (setq org-goto-selected-point (point)
6715 org-goto-exit-command 'left)
6716 (throw 'exit nil))
6717 (error "Not on a heading")))
6719 (defun org-goto-right ()
6720 "Finish `org-goto' by going to the new location."
6721 (interactive)
6722 (if (org-on-heading-p)
6723 (progn
6724 (setq org-goto-selected-point (point)
6725 org-goto-exit-command 'right)
6726 (throw 'exit nil))
6727 (error "Not on a heading")))
6729 (defun org-goto-quit ()
6730 "Finish `org-goto' without cursor motion."
6731 (interactive)
6732 (setq org-goto-selected-point nil)
6733 (setq org-goto-exit-command 'quit)
6734 (throw 'exit nil))
6736 ;;; Indirect buffer display of subtrees
6738 (defvar org-indirect-dedicated-frame nil
6739 "This is the frame being used for indirect tree display.")
6740 (defvar org-last-indirect-buffer nil)
6742 (defun org-tree-to-indirect-buffer (&optional arg)
6743 "Create indirect buffer and narrow it to current subtree.
6744 With numerical prefix ARG, go up to this level and then take that tree.
6745 If ARG is negative, go up that many levels.
6746 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6747 indirect buffer previously made with this command, to avoid proliferation of
6748 indirect buffers. However, when you call the command with a \
6749 \\[universal-argument] prefix, or
6750 when `org-indirect-buffer-display' is `new-frame', the last buffer
6751 is kept so that you can work with several indirect buffers at the same time.
6752 If `org-indirect-buffer-display' is `dedicated-frame', the \
6753 \\[universal-argument] prefix also
6754 requests that a new frame be made for the new buffer, so that the dedicated
6755 frame is not changed."
6756 (interactive "P")
6757 (let ((cbuf (current-buffer))
6758 (cwin (selected-window))
6759 (pos (point))
6760 beg end level heading ibuf)
6761 (save-excursion
6762 (org-back-to-heading t)
6763 (when (numberp arg)
6764 (setq level (org-outline-level))
6765 (if (< arg 0) (setq arg (+ level arg)))
6766 (while (> (setq level (org-outline-level)) arg)
6767 (outline-up-heading 1 t)))
6768 (setq beg (point)
6769 heading (org-get-heading))
6770 (org-end-of-subtree t t)
6771 (if (org-on-heading-p) (backward-char 1))
6772 (setq end (point)))
6773 (if (and (buffer-live-p org-last-indirect-buffer)
6774 (not (eq org-indirect-buffer-display 'new-frame))
6775 (not arg))
6776 (kill-buffer org-last-indirect-buffer))
6777 (setq ibuf (org-get-indirect-buffer cbuf)
6778 org-last-indirect-buffer ibuf)
6779 (cond
6780 ((or (eq org-indirect-buffer-display 'new-frame)
6781 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6782 (select-frame (make-frame))
6783 (delete-other-windows)
6784 (switch-to-buffer ibuf)
6785 (org-set-frame-title heading))
6786 ((eq org-indirect-buffer-display 'dedicated-frame)
6787 (raise-frame
6788 (select-frame (or (and org-indirect-dedicated-frame
6789 (frame-live-p org-indirect-dedicated-frame)
6790 org-indirect-dedicated-frame)
6791 (setq org-indirect-dedicated-frame (make-frame)))))
6792 (delete-other-windows)
6793 (switch-to-buffer ibuf)
6794 (org-set-frame-title (concat "Indirect: " heading)))
6795 ((eq org-indirect-buffer-display 'current-window)
6796 (switch-to-buffer ibuf))
6797 ((eq org-indirect-buffer-display 'other-window)
6798 (pop-to-buffer ibuf))
6799 (t (error "Invalid value")))
6800 (if (featurep 'xemacs)
6801 (save-excursion (org-mode) (turn-on-font-lock)))
6802 (narrow-to-region beg end)
6803 (show-all)
6804 (goto-char pos)
6805 (and (window-live-p cwin) (select-window cwin))))
6807 (defun org-get-indirect-buffer (&optional buffer)
6808 (setq buffer (or buffer (current-buffer)))
6809 (let ((n 1) (base (buffer-name buffer)) bname)
6810 (while (buffer-live-p
6811 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6812 (setq n (1+ n)))
6813 (condition-case nil
6814 (make-indirect-buffer buffer bname 'clone)
6815 (error (make-indirect-buffer buffer bname)))))
6817 (defun org-set-frame-title (title)
6818 "Set the title of the current frame to the string TITLE."
6819 ;; FIXME: how to name a single frame in XEmacs???
6820 (unless (featurep 'xemacs)
6821 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6823 ;;;; Structure editing
6825 ;;; Inserting headlines
6827 (defun org-previous-line-empty-p ()
6828 (save-excursion
6829 (and (not (bobp))
6830 (or (beginning-of-line 0) t)
6831 (save-match-data
6832 (looking-at "[ \t]*$")))))
6834 (defun org-insert-heading (&optional force-heading invisible-ok)
6835 "Insert a new heading or item with same depth at point.
6836 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6837 If point is at the beginning of a headline, insert a sibling before the
6838 current headline. If point is not at the beginning, split the line,
6839 create the new headline with the text in the current line after point
6840 \(but see also the variable `org-M-RET-may-split-line').
6842 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6843 This is important for non-interactive uses of the command."
6844 (interactive "P")
6845 (if (or (= (buffer-size) 0)
6846 (and (not (save-excursion
6847 (and (ignore-errors (org-back-to-heading invisible-ok))
6848 (org-on-heading-p))))
6849 (not (org-in-item-p))))
6850 (progn
6851 (insert "\n* ")
6852 (run-hooks 'org-insert-heading-hook))
6853 (when (or force-heading (not (org-insert-item)))
6854 (let* ((empty-line-p nil)
6855 (level nil)
6856 (on-heading (org-on-heading-p))
6857 (head (save-excursion
6858 (condition-case nil
6859 (progn
6860 (org-back-to-heading invisible-ok)
6861 (when (and (not on-heading)
6862 (featurep 'org-inlinetask)
6863 (integerp org-inlinetask-min-level)
6864 (>= (length (match-string 0))
6865 org-inlinetask-min-level))
6866 ;; Find a heading level before the inline task
6867 (while (and (setq level (org-up-heading-safe))
6868 (>= level org-inlinetask-min-level)))
6869 (if (org-on-heading-p)
6870 (org-back-to-heading invisible-ok)
6871 (error "This should not happen")))
6872 (setq empty-line-p (org-previous-line-empty-p))
6873 (match-string 0))
6874 (error "*"))))
6875 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6876 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6877 pos hide-previous previous-pos)
6878 (cond
6879 ((and (org-on-heading-p) (bolp)
6880 (or (bobp)
6881 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
6882 ;; insert before the current line
6883 (open-line (if blank 2 1)))
6884 ((and (bolp)
6885 (not org-insert-heading-respect-content)
6886 (or (bobp)
6887 (save-excursion
6888 (backward-char 1) (not (outline-invisible-p)))))
6889 ;; insert right here
6890 nil)
6892 ;; somewhere in the line
6893 (save-excursion
6894 (setq previous-pos (point-at-bol))
6895 (end-of-line)
6896 (setq hide-previous (outline-invisible-p)))
6897 (and org-insert-heading-respect-content (org-show-subtree))
6898 (let ((split
6899 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6900 (save-excursion
6901 (let ((p (point)))
6902 (goto-char (point-at-bol))
6903 (and (looking-at org-complex-heading-regexp)
6904 (> p (match-beginning 4)))))))
6905 tags pos)
6906 (cond
6907 (org-insert-heading-respect-content
6908 (org-end-of-subtree nil t)
6909 (when (featurep 'org-inlinetask)
6910 (while (and (not (eobp))
6911 (looking-at "\\(\\*+\\)[ \t]+")
6912 (>= (length (match-string 1))
6913 org-inlinetask-min-level))
6914 (org-end-of-subtree nil t)))
6915 (or (bolp) (newline))
6916 (or (org-previous-line-empty-p)
6917 (and blank (newline)))
6918 (open-line 1))
6919 ((org-on-heading-p)
6920 (when hide-previous
6921 (show-children)
6922 (org-show-entry))
6923 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
6924 (setq tags (and (match-end 2) (match-string 2)))
6925 (and (match-end 1)
6926 (delete-region (match-beginning 1) (match-end 1)))
6927 (setq pos (point-at-bol))
6928 (or split (end-of-line 1))
6929 (delete-horizontal-space)
6930 (if (string-match "\\`\\*+\\'"
6931 (buffer-substring (point-at-bol) (point)))
6932 (insert " "))
6933 (newline (if blank 2 1))
6934 (when tags
6935 (save-excursion
6936 (goto-char pos)
6937 (end-of-line 1)
6938 (insert " " tags)
6939 (org-set-tags nil 'align))))
6941 (or split (end-of-line 1))
6942 (newline (if blank 2 1)))))))
6943 (insert head) (just-one-space)
6944 (setq pos (point))
6945 (end-of-line 1)
6946 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6947 (when (and org-insert-heading-respect-content hide-previous)
6948 (save-excursion
6949 (goto-char previous-pos)
6950 (hide-subtree)))
6951 (run-hooks 'org-insert-heading-hook)))))
6953 (defun org-get-heading (&optional no-tags)
6954 "Return the heading of the current entry, without the stars."
6955 (save-excursion
6956 (org-back-to-heading t)
6957 (if (looking-at
6958 (if no-tags
6959 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@#%]+:[ \t]*\\)?$")
6960 "\\*+[ \t]+\\([^\r\n]*\\)"))
6961 (match-string 1) "")))
6963 (defun org-heading-components ()
6964 "Return the components of the current heading.
6965 This is a list with the following elements:
6966 - the level as an integer
6967 - the reduced level, different if `org-odd-levels-only' is set.
6968 - the TODO keyword, or nil
6969 - the priority character, like ?A, or nil if no priority is given
6970 - the headline text itself, or the tags string if no headline text
6971 - the tags string, or nil."
6972 (save-excursion
6973 (org-back-to-heading t)
6974 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6975 (list (length (match-string 1))
6976 (org-reduced-level (length (match-string 1)))
6977 (org-match-string-no-properties 2)
6978 (and (match-end 3) (aref (match-string 3) 2))
6979 (org-match-string-no-properties 4)
6980 (org-match-string-no-properties 5)))))
6982 (defun org-get-entry ()
6983 "Get the entry text, after heading, entire subtree."
6984 (save-excursion
6985 (org-back-to-heading t)
6986 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6988 (defun org-insert-heading-after-current ()
6989 "Insert a new heading with same level as current, after current subtree."
6990 (interactive)
6991 (org-back-to-heading)
6992 (org-insert-heading)
6993 (org-move-subtree-down)
6994 (end-of-line 1))
6996 (defun org-insert-heading-respect-content ()
6997 (interactive)
6998 (let ((org-insert-heading-respect-content t))
6999 (org-insert-heading t)))
7001 (defun org-insert-todo-heading-respect-content (&optional force-state)
7002 (interactive "P")
7003 (let ((org-insert-heading-respect-content t))
7004 (org-insert-todo-heading force-state t)))
7006 (defun org-insert-todo-heading (arg &optional force-heading)
7007 "Insert a new heading with the same level and TODO state as current heading.
7008 If the heading has no TODO state, or if the state is DONE, use the first
7009 state (TODO by default). Also with prefix arg, force first state."
7010 (interactive "P")
7011 (when (or force-heading (not (org-insert-item 'checkbox)))
7012 (org-insert-heading force-heading)
7013 (save-excursion
7014 (org-back-to-heading)
7015 (outline-previous-heading)
7016 (looking-at org-todo-line-regexp))
7017 (let*
7018 ((new-mark-x
7019 (if (or arg
7020 (not (match-beginning 2))
7021 (member (match-string 2) org-done-keywords))
7022 (car org-todo-keywords-1)
7023 (match-string 2)))
7024 (new-mark
7026 (run-hook-with-args-until-success
7027 'org-todo-get-default-hook new-mark-x nil)
7028 new-mark-x)))
7029 (beginning-of-line 1)
7030 (and (looking-at "\\*+ ") (goto-char (match-end 0))
7031 (if org-treat-insert-todo-heading-as-state-change
7032 (org-todo new-mark)
7033 (insert new-mark " "))))
7034 (when org-provide-todo-statistics
7035 (org-update-parent-todo-statistics))))
7037 (defun org-insert-subheading (arg)
7038 "Insert a new subheading and demote it.
7039 Works for outline headings and for plain lists alike."
7040 (interactive "P")
7041 (org-insert-heading arg)
7042 (cond
7043 ((org-on-heading-p) (org-do-demote))
7044 ((org-at-item-p) (org-indent-item))))
7046 (defun org-insert-todo-subheading (arg)
7047 "Insert a new subheading with TODO keyword or checkbox and demote it.
7048 Works for outline headings and for plain lists alike."
7049 (interactive "P")
7050 (org-insert-todo-heading arg)
7051 (cond
7052 ((org-on-heading-p) (org-do-demote))
7053 ((org-at-item-p) (org-indent-item))))
7055 ;;; Promotion and Demotion
7057 (defvar org-after-demote-entry-hook nil
7058 "Hook run after an entry has been demoted.
7059 The cursor will be at the beginning of the entry.
7060 When a subtree is being demoted, the hook will be called for each node.")
7062 (defvar org-after-promote-entry-hook nil
7063 "Hook run after an entry has been promoted.
7064 The cursor will be at the beginning of the entry.
7065 When a subtree is being promoted, the hook will be called for each node.")
7067 (defun org-promote-subtree ()
7068 "Promote the entire subtree.
7069 See also `org-promote'."
7070 (interactive)
7071 (save-excursion
7072 (org-with-limited-levels (org-map-tree 'org-promote)))
7073 (org-fix-position-after-promote))
7075 (defun org-demote-subtree ()
7076 "Demote the entire subtree. See `org-demote'.
7077 See also `org-promote'."
7078 (interactive)
7079 (save-excursion
7080 (org-with-limited-levels (org-map-tree 'org-demote)))
7081 (org-fix-position-after-promote))
7084 (defun org-do-promote ()
7085 "Promote the current heading higher up the tree.
7086 If the region is active in `transient-mark-mode', promote all headings
7087 in the region."
7088 (interactive)
7089 (save-excursion
7090 (if (org-region-active-p)
7091 (org-map-region 'org-promote (region-beginning) (region-end))
7092 (org-promote)))
7093 (org-fix-position-after-promote))
7095 (defun org-do-demote ()
7096 "Demote the current heading lower down the tree.
7097 If the region is active in `transient-mark-mode', demote all headings
7098 in the region."
7099 (interactive)
7100 (save-excursion
7101 (if (org-region-active-p)
7102 (org-map-region 'org-demote (region-beginning) (region-end))
7103 (org-demote)))
7104 (org-fix-position-after-promote))
7106 (defun org-fix-position-after-promote ()
7107 "Make sure that after pro/demotion cursor position is right."
7108 (let ((pos (point)))
7109 (when (save-excursion
7110 (beginning-of-line 1)
7111 (looking-at org-todo-line-regexp)
7112 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7113 (cond ((eobp) (insert " "))
7114 ((eolp) (insert " "))
7115 ((equal (char-after) ?\ ) (forward-char 1))))))
7117 (defun org-current-level ()
7118 "Return the level of the current entry, or nil if before the first headline.
7119 The level is the number of stars at the beginning of the headline."
7120 (save-excursion
7121 (org-with-limited-levels
7122 (ignore-errors
7123 (org-back-to-heading t)
7124 (funcall outline-level)))))
7126 (defun org-get-previous-line-level ()
7127 "Return the outline depth of the last headline before the current line.
7128 Returns 0 for the first headline in the buffer, and nil if before the
7129 first headline."
7130 (let ((current-level (org-current-level))
7131 (prev-level (when (> (line-number-at-pos) 1)
7132 (save-excursion
7133 (beginning-of-line 0)
7134 (org-current-level)))))
7135 (cond ((null current-level) nil) ; Before first headline
7136 ((null prev-level) 0) ; At first headline
7137 (prev-level))))
7139 (defun org-reduced-level (l)
7140 "Compute the effective level of a heading.
7141 This takes into account the setting of `org-odd-levels-only'."
7142 (cond
7143 ((zerop l) 0)
7144 (org-odd-levels-only (1+ (floor (/ l 2))))
7145 (t l)))
7147 (defun org-level-increment ()
7148 "Return the number of stars that will be added or removed at a
7149 time to headlines when structure editing, based on the value of
7150 `org-odd-levels-only'."
7151 (if org-odd-levels-only 2 1))
7153 (defun org-get-valid-level (level &optional change)
7154 "Rectify a level change under the influence of `org-odd-levels-only'
7155 LEVEL is a current level, CHANGE is by how much the level should be
7156 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7157 even level numbers will become the next higher odd number."
7158 (if org-odd-levels-only
7159 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7160 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7161 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7162 (max 1 (+ level (or change 0)))))
7164 (if (boundp 'define-obsolete-function-alias)
7165 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7166 (define-obsolete-function-alias 'org-get-legal-level
7167 'org-get-valid-level)
7168 (define-obsolete-function-alias 'org-get-legal-level
7169 'org-get-valid-level "23.1")))
7171 (defun org-promote ()
7172 "Promote the current heading higher up the tree.
7173 If the region is active in `transient-mark-mode', promote all headings
7174 in the region."
7175 (org-back-to-heading t)
7176 (let* ((level (save-match-data (funcall outline-level)))
7177 (after-change-functions (remove 'flyspell-after-change-function
7178 after-change-functions))
7179 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7180 (diff (abs (- level (length up-head) -1))))
7181 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7182 (replace-match up-head nil t)
7183 ;; Fixup tag positioning
7184 (and org-auto-align-tags (org-set-tags nil t))
7185 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7186 (run-hooks 'org-after-promote-entry-hook)))
7188 (defun org-demote ()
7189 "Demote the current heading lower down the tree.
7190 If the region is active in `transient-mark-mode', demote all headings
7191 in the region."
7192 (org-back-to-heading t)
7193 (let* ((level (save-match-data (funcall outline-level)))
7194 (after-change-functions (remove 'flyspell-after-change-function
7195 after-change-functions))
7196 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7197 (diff (abs (- level (length down-head) -1))))
7198 (replace-match down-head nil t)
7199 ;; Fixup tag positioning
7200 (and org-auto-align-tags (org-set-tags nil t))
7201 (if org-adapt-indentation (org-fixup-indentation diff))
7202 (run-hooks 'org-after-demote-entry-hook)))
7204 (defun org-cycle-level ()
7205 "Cycle the level of an empty headline through possible states.
7206 This goes first to child, then to parent, level, then up the hierarchy.
7207 After top level, it switches back to sibling level."
7208 (interactive)
7209 (let ((org-adapt-indentation nil))
7210 (when (org-point-at-end-of-empty-headline)
7211 (setq this-command 'org-cycle-level) ; Only needed for caching
7212 (let ((cur-level (org-current-level))
7213 (prev-level (org-get-previous-line-level)))
7214 (cond
7215 ;; If first headline in file, promote to top-level.
7216 ((= prev-level 0)
7217 (loop repeat (/ (- cur-level 1) (org-level-increment))
7218 do (org-do-promote)))
7219 ;; If same level as prev, demote one.
7220 ((= prev-level cur-level)
7221 (org-do-demote))
7222 ;; If parent is top-level, promote to top level if not already.
7223 ((= prev-level 1)
7224 (loop repeat (/ (- cur-level 1) (org-level-increment))
7225 do (org-do-promote)))
7226 ;; If top-level, return to prev-level.
7227 ((= cur-level 1)
7228 (loop repeat (/ (- prev-level 1) (org-level-increment))
7229 do (org-do-demote)))
7230 ;; If less than prev-level, promote one.
7231 ((< cur-level prev-level)
7232 (org-do-promote))
7233 ;; If deeper than prev-level, promote until higher than
7234 ;; prev-level.
7235 ((> cur-level prev-level)
7236 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7237 do (org-do-promote))))
7238 t))))
7240 (defun org-map-tree (fun)
7241 "Call FUN for every heading underneath the current one."
7242 (org-back-to-heading)
7243 (let ((level (funcall outline-level)))
7244 (save-excursion
7245 (funcall fun)
7246 (while (and (progn
7247 (outline-next-heading)
7248 (> (funcall outline-level) level))
7249 (not (eobp)))
7250 (funcall fun)))))
7252 (defun org-map-region (fun beg end)
7253 "Call FUN for every heading between BEG and END."
7254 (let ((org-ignore-region t))
7255 (save-excursion
7256 (setq end (copy-marker end))
7257 (goto-char beg)
7258 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
7259 (< (point) end))
7260 (funcall fun))
7261 (while (and (progn
7262 (outline-next-heading)
7263 (< (point) end))
7264 (not (eobp)))
7265 (funcall fun)))))
7267 (defun org-fixup-indentation (diff)
7268 "Change the indentation in the current entry by DIFF.
7269 However, if any line in the current entry has no indentation, or if it
7270 would end up with no indentation after the change, nothing at all is done."
7271 (save-excursion
7272 (let ((end (save-excursion (outline-next-heading)
7273 (point-marker)))
7274 (prohibit (if (> diff 0)
7275 "^\\S-"
7276 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7277 col)
7278 (unless (save-excursion (end-of-line 1)
7279 (re-search-forward prohibit end t))
7280 (while (and (< (point) end)
7281 (re-search-forward "^[ \t]+" end t))
7282 (goto-char (match-end 0))
7283 (setq col (current-column))
7284 (if (< diff 0) (replace-match ""))
7285 (org-indent-to-column (+ diff col))))
7286 (move-marker end nil))))
7288 (defun org-convert-to-odd-levels ()
7289 "Convert an org-mode file with all levels allowed to one with odd levels.
7290 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7291 level 5 etc."
7292 (interactive)
7293 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7294 (let ((outline-regexp org-outline-regexp)
7295 (outline-level 'org-outline-level)
7296 (org-odd-levels-only nil) n)
7297 (save-excursion
7298 (goto-char (point-min))
7299 (while (re-search-forward "^\\*\\*+ " nil t)
7300 (setq n (- (length (match-string 0)) 2))
7301 (while (>= (setq n (1- n)) 0)
7302 (org-demote))
7303 (end-of-line 1))))))
7305 (defun org-convert-to-oddeven-levels ()
7306 "Convert an org-mode file with only odd levels to one with odd/even levels.
7307 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7308 file contains a section with an even level, conversion would
7309 destroy the structure of the file. An error is signaled in this
7310 case."
7311 (interactive)
7312 (goto-char (point-min))
7313 ;; First check if there are no even levels
7314 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7315 (org-show-context t)
7316 (error "Not all levels are odd in this file. Conversion not possible"))
7317 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7318 (let ((outline-regexp org-outline-regexp)
7319 (outline-level 'org-outline-level)
7320 (org-odd-levels-only nil) n)
7321 (save-excursion
7322 (goto-char (point-min))
7323 (while (re-search-forward "^\\*\\*+ " nil t)
7324 (setq n (/ (1- (length (match-string 0))) 2))
7325 (while (>= (setq n (1- n)) 0)
7326 (org-promote))
7327 (end-of-line 1))))))
7329 (defun org-tr-level (n)
7330 "Make N odd if required."
7331 (if org-odd-levels-only (1+ (/ n 2)) n))
7333 ;;; Vertical tree motion, cutting and pasting of subtrees
7335 (defun org-move-subtree-up (&optional arg)
7336 "Move the current subtree up past ARG headlines of the same level."
7337 (interactive "p")
7338 (org-move-subtree-down (- (prefix-numeric-value arg))))
7340 (defun org-move-subtree-down (&optional arg)
7341 "Move the current subtree down past ARG headlines of the same level."
7342 (interactive "p")
7343 (setq arg (prefix-numeric-value arg))
7344 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7345 'org-get-last-sibling))
7346 (ins-point (make-marker))
7347 (cnt (abs arg))
7348 (col (current-column))
7349 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7350 ;; Select the tree
7351 (org-back-to-heading)
7352 (setq beg0 (point))
7353 (save-excursion
7354 (setq ne-beg (org-back-over-empty-lines))
7355 (setq beg (point)))
7356 (save-match-data
7357 (save-excursion (outline-end-of-heading)
7358 (setq folded (outline-invisible-p)))
7359 (outline-end-of-subtree))
7360 (outline-next-heading)
7361 (setq ne-end (org-back-over-empty-lines))
7362 (setq end (point))
7363 (goto-char beg0)
7364 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7365 ;; include less whitespace
7366 (save-excursion
7367 (goto-char beg)
7368 (forward-line (- ne-beg ne-end))
7369 (setq beg (point))))
7370 ;; Find insertion point, with error handling
7371 (while (> cnt 0)
7372 (or (and (funcall movfunc) (looking-at outline-regexp))
7373 (progn (goto-char beg0)
7374 (error "Cannot move past superior level or buffer limit")))
7375 (setq cnt (1- cnt)))
7376 (if (> arg 0)
7377 ;; Moving forward - still need to move over subtree
7378 (progn (org-end-of-subtree t t)
7379 (save-excursion
7380 (org-back-over-empty-lines)
7381 (or (bolp) (newline)))))
7382 (setq ne-ins (org-back-over-empty-lines))
7383 (move-marker ins-point (point))
7384 (setq txt (buffer-substring beg end))
7385 (org-save-markers-in-region beg end)
7386 (delete-region beg end)
7387 (org-remove-empty-overlays-at beg)
7388 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7389 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7390 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7391 (let ((bbb (point)))
7392 (insert-before-markers txt)
7393 (org-reinstall-markers-in-region bbb)
7394 (move-marker ins-point bbb))
7395 (or (bolp) (insert "\n"))
7396 (setq ins-end (point))
7397 (goto-char ins-point)
7398 (org-skip-whitespace)
7399 (when (and (< arg 0)
7400 (org-first-sibling-p)
7401 (> ne-ins ne-beg))
7402 ;; Move whitespace back to beginning
7403 (save-excursion
7404 (goto-char ins-end)
7405 (let ((kill-whole-line t))
7406 (kill-line (- ne-ins ne-beg)) (point)))
7407 (insert (make-string (- ne-ins ne-beg) ?\n)))
7408 (move-marker ins-point nil)
7409 (if folded
7410 (hide-subtree)
7411 (org-show-entry)
7412 (show-children)
7413 (org-cycle-hide-drawers 'children))
7414 (org-clean-visibility-after-subtree-move)
7415 ;; move back to the initial column we were at
7416 (move-to-column col)))
7418 (defvar org-subtree-clip ""
7419 "Clipboard for cut and paste of subtrees.
7420 This is actually only a copy of the kill, because we use the normal kill
7421 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7423 (defvar org-subtree-clip-folded nil
7424 "Was the last copied subtree folded?
7425 This is used to fold the tree back after pasting.")
7427 (defun org-cut-subtree (&optional n)
7428 "Cut the current subtree into the clipboard.
7429 With prefix arg N, cut this many sequential subtrees.
7430 This is a short-hand for marking the subtree and then cutting it."
7431 (interactive "p")
7432 (org-copy-subtree n 'cut))
7434 (defun org-copy-subtree (&optional n cut force-store-markers)
7435 "Cut the current subtree into the clipboard.
7436 With prefix arg N, cut this many sequential subtrees.
7437 This is a short-hand for marking the subtree and then copying it.
7438 If CUT is non-nil, actually cut the subtree.
7439 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7440 of some markers in the region, even if CUT is non-nil. This is
7441 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7442 (interactive "p")
7443 (let (beg end folded (beg0 (point)))
7444 (if (org-called-interactively-p 'any)
7445 (org-back-to-heading nil) ; take what looks like a subtree
7446 (org-back-to-heading t)) ; take what is really there
7447 (org-back-over-empty-lines)
7448 (setq beg (point))
7449 (skip-chars-forward " \t\r\n")
7450 (save-match-data
7451 (save-excursion (outline-end-of-heading)
7452 (setq folded (outline-invisible-p)))
7453 (condition-case nil
7454 (org-forward-same-level (1- n) t)
7455 (error nil))
7456 (org-end-of-subtree t t))
7457 (org-back-over-empty-lines)
7458 (setq end (point))
7459 (goto-char beg0)
7460 (when (> end beg)
7461 (setq org-subtree-clip-folded folded)
7462 (when (or cut force-store-markers)
7463 (org-save-markers-in-region beg end))
7464 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7465 (setq org-subtree-clip (current-kill 0))
7466 (message "%s: Subtree(s) with %d characters"
7467 (if cut "Cut" "Copied")
7468 (length org-subtree-clip)))))
7470 (defun org-paste-subtree (&optional level tree for-yank)
7471 "Paste the clipboard as a subtree, with modification of headline level.
7472 The entire subtree is promoted or demoted in order to match a new headline
7473 level.
7475 If the cursor is at the beginning of a headline, the same level as
7476 that headline is used to paste the tree
7478 If not, the new level is derived from the *visible* headings
7479 before and after the insertion point, and taken to be the inferior headline
7480 level of the two. So if the previous visible heading is level 3 and the
7481 next is level 4 (or vice versa), level 4 will be used for insertion.
7482 This makes sure that the subtree remains an independent subtree and does
7483 not swallow low level entries.
7485 You can also force a different level, either by using a numeric prefix
7486 argument, or by inserting the heading marker by hand. For example, if the
7487 cursor is after \"*****\", then the tree will be shifted to level 5.
7489 If optional TREE is given, use this text instead of the kill ring.
7491 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7492 move back over whitespace before inserting, and move point to the end of
7493 the inserted text when done."
7494 (interactive "P")
7495 (setq tree (or tree (and kill-ring (current-kill 0))))
7496 (unless (org-kill-is-subtree-p tree)
7497 (error "%s"
7498 (substitute-command-keys
7499 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7500 (let* ((visp (not (outline-invisible-p)))
7501 (txt tree)
7502 (^re (concat "^\\(" outline-regexp "\\)"))
7503 (re (concat "\\(" outline-regexp "\\)"))
7504 (^re_ (concat "\\(\\*+\\)[ \t]*"))
7506 (old-level (if (string-match ^re txt)
7507 (- (match-end 0) (match-beginning 0) 1)
7508 -1))
7509 (force-level (cond (level (prefix-numeric-value level))
7510 ((and (looking-at "[ \t]*$")
7511 (string-match
7512 ^re_ (buffer-substring
7513 (point-at-bol) (point))))
7514 (- (match-end 1) (match-beginning 1)))
7515 ((and (bolp)
7516 (looking-at org-outline-regexp))
7517 (- (match-end 0) (point) 1))
7518 (t nil)))
7519 (previous-level (save-excursion
7520 (condition-case nil
7521 (progn
7522 (outline-previous-visible-heading 1)
7523 (if (looking-at re)
7524 (- (match-end 0) (match-beginning 0) 1)
7526 (error 1))))
7527 (next-level (save-excursion
7528 (condition-case nil
7529 (progn
7530 (or (looking-at outline-regexp)
7531 (outline-next-visible-heading 1))
7532 (if (looking-at re)
7533 (- (match-end 0) (match-beginning 0) 1)
7535 (error 1))))
7536 (new-level (or force-level (max previous-level next-level)))
7537 (shift (if (or (= old-level -1)
7538 (= new-level -1)
7539 (= old-level new-level))
7541 (- new-level old-level)))
7542 (delta (if (> shift 0) -1 1))
7543 (func (if (> shift 0) 'org-demote 'org-promote))
7544 (org-odd-levels-only nil)
7545 beg end newend)
7546 ;; Remove the forced level indicator
7547 (if force-level
7548 (delete-region (point-at-bol) (point)))
7549 ;; Paste
7550 (beginning-of-line 1)
7551 (unless for-yank (org-back-over-empty-lines))
7552 (setq beg (point))
7553 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7554 (insert-before-markers txt)
7555 (unless (string-match "\n\\'" txt) (insert "\n"))
7556 (setq newend (point))
7557 (org-reinstall-markers-in-region beg)
7558 (setq end (point))
7559 (goto-char beg)
7560 (skip-chars-forward " \t\n\r")
7561 (setq beg (point))
7562 (if (and (outline-invisible-p) visp)
7563 (save-excursion (outline-show-heading)))
7564 ;; Shift if necessary
7565 (unless (= shift 0)
7566 (save-restriction
7567 (narrow-to-region beg end)
7568 (while (not (= shift 0))
7569 (org-map-region func (point-min) (point-max))
7570 (setq shift (+ delta shift)))
7571 (goto-char (point-min))
7572 (setq newend (point-max))))
7573 (when (or (org-called-interactively-p 'interactive) for-yank)
7574 (message "Clipboard pasted as level %d subtree" new-level))
7575 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7576 kill-ring
7577 (eq org-subtree-clip (current-kill 0))
7578 org-subtree-clip-folded)
7579 ;; The tree was folded before it was killed/copied
7580 (hide-subtree))
7581 (and for-yank (goto-char newend))))
7583 (defun org-kill-is-subtree-p (&optional txt)
7584 "Check if the current kill is an outline subtree, or a set of trees.
7585 Returns nil if kill does not start with a headline, or if the first
7586 headline level is not the largest headline level in the tree.
7587 So this will actually accept several entries of equal levels as well,
7588 which is OK for `org-paste-subtree'.
7589 If optional TXT is given, check this string instead of the current kill."
7590 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7591 (start-level (and kill
7592 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
7593 org-outline-regexp "\\)")
7594 kill)
7595 (- (match-end 2) (match-beginning 2) 1)))
7596 (re (concat "^" org-outline-regexp))
7597 (start (1+ (or (match-beginning 2) -1))))
7598 (if (not start-level)
7599 (progn
7600 nil) ;; does not even start with a heading
7601 (catch 'exit
7602 (while (setq start (string-match re kill (1+ start)))
7603 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7604 (throw 'exit nil)))
7605 t))))
7607 (defvar org-markers-to-move nil
7608 "Markers that should be moved with a cut-and-paste operation.
7609 Those markers are stored together with their positions relative to
7610 the start of the region.")
7612 (defun org-save-markers-in-region (beg end)
7613 "Check markers in region.
7614 If these markers are between BEG and END, record their position relative
7615 to BEG, so that after moving the block of text, we can put the markers back
7616 into place.
7617 This function gets called just before an entry or tree gets cut from the
7618 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7619 called immediately, to move the markers with the entries."
7620 (setq org-markers-to-move nil)
7621 (when (featurep 'org-clock)
7622 (org-clock-save-markers-for-cut-and-paste beg end))
7623 (when (featurep 'org-agenda)
7624 (org-agenda-save-markers-for-cut-and-paste beg end)))
7626 (defun org-check-and-save-marker (marker beg end)
7627 "Check if MARKER is between BEG and END.
7628 If yes, remember the marker and the distance to BEG."
7629 (when (and (marker-buffer marker)
7630 (equal (marker-buffer marker) (current-buffer)))
7631 (if (and (>= marker beg) (< marker end))
7632 (push (cons marker (- marker beg)) org-markers-to-move))))
7634 (defun org-reinstall-markers-in-region (beg)
7635 "Move all remembered markers to their position relative to BEG."
7636 (mapc (lambda (x)
7637 (move-marker (car x) (+ beg (cdr x))))
7638 org-markers-to-move)
7639 (setq org-markers-to-move nil))
7641 (defun org-narrow-to-subtree ()
7642 "Narrow buffer to the current subtree."
7643 (interactive)
7644 (save-excursion
7645 (save-match-data
7646 (org-with-limited-levels
7647 (narrow-to-region
7648 (progn (org-back-to-heading t) (point))
7649 (progn (org-end-of-subtree t t)
7650 (if (and (org-on-heading-p) (not (eobp))) (backward-char 1))
7651 (point)))))))
7653 (defun org-narrow-to-block ()
7654 "Narrow buffer to the current block."
7655 (interactive)
7656 (let ((bstart "^[ \t]*#\\+begin")
7657 (bend "[ \t]*#\\+end")
7658 (case-fold-search t) ;; allow #+BEGIN
7659 b_start b_end)
7660 (if (org-in-regexps-block-p bstart bend)
7661 (progn
7662 (save-excursion (re-search-backward bstart nil t)
7663 (setq b_start (match-beginning 0)))
7664 (save-excursion (re-search-forward bend nil t)
7665 (setq b_end (match-end 0)))
7666 (narrow-to-region b_start b_end))
7667 (error "Not in a block"))))
7669 (eval-when-compile
7670 (defvar org-property-drawer-re))
7672 (defvar org-property-start-re) ;; defined below
7673 (defun org-clone-subtree-with-time-shift (n &optional shift)
7674 "Clone the task (subtree) at point N times.
7675 The clones will be inserted as siblings.
7677 In interactive use, the user will be prompted for the number of
7678 clones to be produced, and for a time SHIFT, which may be a
7679 repeater as used in time stamps, for example `+3d'.
7681 When a valid repeater is given and the entry contains any time
7682 stamps, the clones will become a sequence in time, with time
7683 stamps in the subtree shifted for each clone produced. If SHIFT
7684 is nil or the empty string, time stamps will be left alone. The
7685 ID property of the original subtree is removed.
7687 If the original subtree did contain time stamps with a repeater,
7688 the following will happen:
7689 - the repeater will be removed in each clone
7690 - an additional clone will be produced, with the current, unshifted
7691 date(s) in the entry.
7692 - the original entry will be placed *after* all the clones, with
7693 repeater intact.
7694 - the start days in the repeater in the original entry will be shifted
7695 to past the last clone.
7696 I this way you can spell out a number of instances of a repeating task,
7697 and still retain the repeater to cover future instances of the task."
7698 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7699 (let (beg end template task idprop
7700 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7701 (if (not (and (integerp n) (> n 0)))
7702 (error "Invalid number of replications %s" n))
7703 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7704 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7705 shift)))
7706 (error "Invalid shift specification %s" shift))
7707 (when doshift
7708 (setq shift-n (string-to-number (match-string 1 shift))
7709 shift-what (cdr (assoc (match-string 2 shift)
7710 '(("d" . day) ("w" . week)
7711 ("m" . month) ("y" . year))))))
7712 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7713 (setq nmin 1 nmax n)
7714 (org-back-to-heading t)
7715 (setq beg (point))
7716 (setq idprop (org-entry-get nil "ID"))
7717 (org-end-of-subtree t t)
7718 (or (bolp) (insert "\n"))
7719 (setq end (point))
7720 (setq template (buffer-substring beg end))
7721 (when (and doshift
7722 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7723 (delete-region beg end)
7724 (setq end beg)
7725 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7726 (goto-char end)
7727 (loop for n from nmin to nmax do
7728 ;; prepare clone
7729 (with-temp-buffer
7730 (insert template)
7731 (org-mode)
7732 (goto-char (point-min))
7733 (and idprop (if org-clone-delete-id
7734 (org-entry-delete nil "ID")
7735 (org-id-get-create t)))
7736 (while (re-search-forward org-property-start-re nil t)
7737 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7738 (goto-char (point-min))
7739 (when doshift
7740 (while (re-search-forward org-ts-regexp-both nil t)
7741 (org-timestamp-change (* n shift-n) shift-what))
7742 (unless (= n n-no-remove)
7743 (goto-char (point-min))
7744 (while (re-search-forward org-ts-regexp nil t)
7745 (save-excursion
7746 (goto-char (match-beginning 0))
7747 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7748 (delete-region (match-beginning 1) (match-end 1)))))))
7749 (setq task (buffer-string)))
7750 (insert task))
7751 (goto-char beg)))
7753 ;;; Outline Sorting
7755 (defun org-sort (with-case)
7756 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7757 Optional argument WITH-CASE means sort case-sensitively.
7758 With a double prefix argument, also remove duplicate entries."
7759 (interactive "P")
7760 (cond
7761 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7762 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7764 (org-call-with-arg 'org-sort-entries with-case))))
7766 (defun org-sort-remove-invisible (s)
7767 (remove-text-properties 0 (length s) org-rm-props s)
7768 (while (string-match org-bracket-link-regexp s)
7769 (setq s (replace-match (if (match-end 2)
7770 (match-string 3 s)
7771 (match-string 1 s)) t t s)))
7774 (defvar org-priority-regexp) ; defined later in the file
7776 (defvar org-after-sorting-entries-or-items-hook nil
7777 "Hook that is run after a bunch of entries or items have been sorted.
7778 When children are sorted, the cursor is in the parent line when this
7779 hook gets called. When a region or a plain list is sorted, the cursor
7780 will be in the first entry of the sorted region/list.")
7782 (defun org-sort-entries
7783 (&optional with-case sorting-type getkey-func compare-func property)
7784 "Sort entries on a certain level of an outline tree.
7785 If there is an active region, the entries in the region are sorted.
7786 Else, if the cursor is before the first entry, sort the top-level items.
7787 Else, the children of the entry at point are sorted.
7789 Sorting can be alphabetically, numerically, by date/time as given by
7790 a time stamp, by a property or by priority.
7792 The command prompts for the sorting type unless it has been given to the
7793 function through the SORTING-TYPE argument, which needs to be a character,
7794 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7795 precise meaning of each character:
7797 n Numerically, by converting the beginning of the entry/item to a number.
7798 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7799 t By date/time, either the first active time stamp in the entry, or, if
7800 none exist, by the first inactive one.
7801 s By the scheduled date/time.
7802 d By deadline date/time.
7803 c By creation time, which is assumed to be the first inactive time stamp
7804 at the beginning of a line.
7805 p By priority according to the cookie.
7806 r By the value of a property.
7808 Capital letters will reverse the sort order.
7810 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7811 called with point at the beginning of the record. It must return either
7812 a string or a number that should serve as the sorting key for that record.
7814 Comparing entries ignores case by default. However, with an optional argument
7815 WITH-CASE, the sorting considers case as well."
7816 (interactive "P")
7817 (let ((case-func (if with-case 'identity 'downcase))
7818 start beg end stars re re2
7819 txt what tmp)
7820 ;; Find beginning and end of region to sort
7821 (cond
7822 ((org-region-active-p)
7823 ;; we will sort the region
7824 (setq end (region-end)
7825 what "region")
7826 (goto-char (region-beginning))
7827 (if (not (org-on-heading-p)) (outline-next-heading))
7828 (setq start (point)))
7829 ((or (org-on-heading-p)
7830 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7831 ;; we will sort the children of the current headline
7832 (org-back-to-heading)
7833 (setq start (point)
7834 end (progn (org-end-of-subtree t t)
7835 (or (bolp) (insert "\n"))
7836 (org-back-over-empty-lines)
7837 (point))
7838 what "children")
7839 (goto-char start)
7840 (show-subtree)
7841 (outline-next-heading))
7843 ;; we will sort the top-level entries in this file
7844 (goto-char (point-min))
7845 (or (org-on-heading-p) (outline-next-heading))
7846 (setq start (point))
7847 (goto-char (point-max))
7848 (beginning-of-line 1)
7849 (when (looking-at ".*?\\S-")
7850 ;; File ends in a non-white line
7851 (end-of-line 1)
7852 (insert "\n"))
7853 (setq end (point-max))
7854 (setq what "top-level")
7855 (goto-char start)
7856 (show-all)))
7858 (setq beg (point))
7859 (if (>= beg end) (error "Nothing to sort"))
7861 (looking-at "\\(\\*+\\)")
7862 (setq stars (match-string 1)
7863 re (concat "^" (regexp-quote stars) " +")
7864 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
7865 txt (buffer-substring beg end))
7866 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7867 (if (and (not (equal stars "*")) (string-match re2 txt))
7868 (error "Region to sort contains a level above the first entry"))
7870 (unless sorting-type
7871 (message
7872 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7873 [t]ime [s]cheduled [d]eadline [c]reated
7874 A/N/T/S/D/C/P/O/F means reversed:"
7875 what)
7876 (setq sorting-type (read-char-exclusive))
7878 (and (= (downcase sorting-type) ?f)
7879 (setq getkey-func
7880 (org-icompleting-read "Sort using function: "
7881 obarray 'fboundp t nil nil))
7882 (setq getkey-func (intern getkey-func)))
7884 (and (= (downcase sorting-type) ?r)
7885 (setq property
7886 (org-icompleting-read "Property: "
7887 (mapcar 'list (org-buffer-property-keys t))
7888 nil t))))
7890 (message "Sorting entries...")
7892 (save-restriction
7893 (narrow-to-region start end)
7894 (let ((dcst (downcase sorting-type))
7895 (case-fold-search nil)
7896 (now (current-time)))
7897 (sort-subr
7898 (/= dcst sorting-type)
7899 ;; This function moves to the beginning character of the "record" to
7900 ;; be sorted.
7901 (lambda nil
7902 (if (re-search-forward re nil t)
7903 (goto-char (match-beginning 0))
7904 (goto-char (point-max))))
7905 ;; This function moves to the last character of the "record" being
7906 ;; sorted.
7907 (lambda nil
7908 (save-match-data
7909 (condition-case nil
7910 (outline-forward-same-level 1)
7911 (error
7912 (goto-char (point-max))))))
7913 ;; This function returns the value that gets sorted against.
7914 (lambda nil
7915 (cond
7916 ((= dcst ?n)
7917 (if (looking-at org-complex-heading-regexp)
7918 (string-to-number (match-string 4))
7919 nil))
7920 ((= dcst ?a)
7921 (if (looking-at org-complex-heading-regexp)
7922 (funcall case-func (match-string 4))
7923 nil))
7924 ((= dcst ?t)
7925 (let ((end (save-excursion (outline-next-heading) (point))))
7926 (if (or (re-search-forward org-ts-regexp end t)
7927 (re-search-forward org-ts-regexp-both end t))
7928 (org-time-string-to-seconds (match-string 0))
7929 (org-float-time now))))
7930 ((= dcst ?c)
7931 (let ((end (save-excursion (outline-next-heading) (point))))
7932 (if (re-search-forward
7933 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7934 end t)
7935 (org-time-string-to-seconds (match-string 0))
7936 (org-float-time now))))
7937 ((= dcst ?s)
7938 (let ((end (save-excursion (outline-next-heading) (point))))
7939 (if (re-search-forward org-scheduled-time-regexp end t)
7940 (org-time-string-to-seconds (match-string 1))
7941 (org-float-time now))))
7942 ((= dcst ?d)
7943 (let ((end (save-excursion (outline-next-heading) (point))))
7944 (if (re-search-forward org-deadline-time-regexp end t)
7945 (org-time-string-to-seconds (match-string 1))
7946 (org-float-time now))))
7947 ((= dcst ?p)
7948 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7949 (string-to-char (match-string 2))
7950 org-default-priority))
7951 ((= dcst ?r)
7952 (or (org-entry-get nil property) ""))
7953 ((= dcst ?o)
7954 (if (looking-at org-complex-heading-regexp)
7955 (- 9999 (length (member (match-string 2)
7956 org-todo-keywords-1)))))
7957 ((= dcst ?f)
7958 (if getkey-func
7959 (progn
7960 (setq tmp (funcall getkey-func))
7961 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7962 tmp)
7963 (error "Invalid key function `%s'" getkey-func)))
7964 (t (error "Invalid sorting type `%c'" sorting-type))))
7966 (cond
7967 ((= dcst ?a) 'string<)
7968 ((= dcst ?f) compare-func)
7969 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7970 (t nil)))))
7971 (run-hooks 'org-after-sorting-entries-or-items-hook)
7972 (message "Sorting entries...done")))
7974 (defun org-do-sort (table what &optional with-case sorting-type)
7975 "Sort TABLE of WHAT according to SORTING-TYPE.
7976 The user will be prompted for the SORTING-TYPE if the call to this
7977 function does not specify it. WHAT is only for the prompt, to indicate
7978 what is being sorted. The sorting key will be extracted from
7979 the car of the elements of the table.
7980 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7981 (unless sorting-type
7982 (message
7983 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7984 what)
7985 (setq sorting-type (read-char-exclusive)))
7986 (let ((dcst (downcase sorting-type))
7987 extractfun comparefun)
7988 ;; Define the appropriate functions
7989 (cond
7990 ((= dcst ?n)
7991 (setq extractfun 'string-to-number
7992 comparefun (if (= dcst sorting-type) '< '>)))
7993 ((= dcst ?a)
7994 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7995 (lambda(x) (downcase (org-sort-remove-invisible x))))
7996 comparefun (if (= dcst sorting-type)
7997 'string<
7998 (lambda (a b) (and (not (string< a b))
7999 (not (string= a b)))))))
8000 ((= dcst ?t)
8001 (setq extractfun
8002 (lambda (x)
8003 (if (or (string-match org-ts-regexp x)
8004 (string-match org-ts-regexp-both x))
8005 (org-float-time
8006 (org-time-string-to-time (match-string 0 x)))
8008 comparefun (if (= dcst sorting-type) '< '>)))
8009 (t (error "Invalid sorting type `%c'" sorting-type)))
8011 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8012 table)
8013 (lambda (a b) (funcall comparefun (car a) (car b))))))
8016 ;;; The orgstruct minor mode
8018 ;; Define a minor mode which can be used in other modes in order to
8019 ;; integrate the org-mode structure editing commands.
8021 ;; This is really a hack, because the org-mode structure commands use
8022 ;; keys which normally belong to the major mode. Here is how it
8023 ;; works: The minor mode defines all the keys necessary to operate the
8024 ;; structure commands, but wraps the commands into a function which
8025 ;; tests if the cursor is currently at a headline or a plain list
8026 ;; item. If that is the case, the structure command is used,
8027 ;; temporarily setting many Org-mode variables like regular
8028 ;; expressions for filling etc. However, when any of those keys is
8029 ;; used at a different location, function uses `key-binding' to look
8030 ;; up if the key has an associated command in another currently active
8031 ;; keymap (minor modes, major mode, global), and executes that
8032 ;; command. There might be problems if any of the keys is otherwise
8033 ;; used as a prefix key.
8035 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8036 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8037 ;; addresses this by checking explicitly for both bindings.
8039 (defvar orgstruct-mode-map (make-sparse-keymap)
8040 "Keymap for the minor `orgstruct-mode'.")
8042 (defvar org-local-vars nil
8043 "List of local variables, for use by `orgstruct-mode'.")
8045 ;;;###autoload
8046 (define-minor-mode orgstruct-mode
8047 "Toggle the minor mode `orgstruct-mode'.
8048 This mode is for using Org-mode structure commands in other
8049 modes. The following keys behave as if Org-mode were active, if
8050 the cursor is on a headline, or on a plain list item (both as
8051 defined by Org-mode).
8053 M-up Move entry/item up
8054 M-down Move entry/item down
8055 M-left Promote
8056 M-right Demote
8057 M-S-up Move entry/item up
8058 M-S-down Move entry/item down
8059 M-S-left Promote subtree
8060 M-S-right Demote subtree
8061 M-q Fill paragraph and items like in Org-mode
8062 C-c ^ Sort entries
8063 C-c - Cycle list bullet
8064 TAB Cycle item visibility
8065 M-RET Insert new heading/item
8066 S-M-RET Insert new TODO heading / Checkbox item
8067 C-c C-c Set tags / toggle checkbox"
8068 nil " OrgStruct" nil
8069 (org-load-modules-maybe)
8070 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8072 ;;;###autoload
8073 (defun turn-on-orgstruct ()
8074 "Unconditionally turn on `orgstruct-mode'."
8075 (orgstruct-mode 1))
8077 (defun orgstruct++-mode (&optional arg)
8078 "Toggle `orgstruct-mode', the enhanced version of it.
8079 In addition to setting orgstruct-mode, this also exports all indentation
8080 and autofilling variables from org-mode into the buffer. It will also
8081 recognize item context in multiline items.
8082 Note that turning off orgstruct-mode will *not* remove the
8083 indentation/paragraph settings. This can only be done by refreshing the
8084 major mode, for example with \\[normal-mode]."
8085 (interactive "P")
8086 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8087 (if (< arg 1)
8088 (orgstruct-mode -1)
8089 (orgstruct-mode 1)
8090 (let (var val)
8091 (mapc
8092 (lambda (x)
8093 (when (string-match
8094 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8095 (symbol-name (car x)))
8096 (setq var (car x) val (nth 1 x))
8097 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8098 org-local-vars)
8099 (org-set-local 'orgstruct-is-++ t))))
8101 (defvar orgstruct-is-++ nil
8102 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8103 (make-variable-buffer-local 'orgstruct-is-++)
8105 ;;;###autoload
8106 (defun turn-on-orgstruct++ ()
8107 "Unconditionally turn on `orgstruct++-mode'."
8108 (orgstruct++-mode 1))
8110 (defun orgstruct-error ()
8111 "Error when there is no default binding for a structure key."
8112 (interactive)
8113 (error "This key has no function outside structure elements"))
8115 (defun orgstruct-setup ()
8116 "Setup orgstruct keymaps."
8117 (let ((nfunc 0)
8118 (bindings
8119 (list
8120 '([(meta up)] org-metaup)
8121 '([(meta down)] org-metadown)
8122 '([(meta left)] org-metaleft)
8123 '([(meta right)] org-metaright)
8124 '([(meta shift up)] org-shiftmetaup)
8125 '([(meta shift down)] org-shiftmetadown)
8126 '([(meta shift left)] org-shiftmetaleft)
8127 '([(meta shift right)] org-shiftmetaright)
8128 '([?\e (up)] org-metaup)
8129 '([?\e (down)] org-metadown)
8130 '([?\e (left)] org-metaleft)
8131 '([?\e (right)] org-metaright)
8132 '([?\e (shift up)] org-shiftmetaup)
8133 '([?\e (shift down)] org-shiftmetadown)
8134 '([?\e (shift left)] org-shiftmetaleft)
8135 '([?\e (shift right)] org-shiftmetaright)
8136 '([(shift up)] org-shiftup)
8137 '([(shift down)] org-shiftdown)
8138 '([(shift left)] org-shiftleft)
8139 '([(shift right)] org-shiftright)
8140 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8141 '("\M-q" fill-paragraph)
8142 '("\C-c^" org-sort)
8143 '("\C-c-" org-cycle-list-bullet)))
8144 elt key fun cmd)
8145 (while (setq elt (pop bindings))
8146 (setq nfunc (1+ nfunc))
8147 (setq key (org-key (car elt))
8148 fun (nth 1 elt)
8149 cmd (orgstruct-make-binding fun nfunc key))
8150 (org-defkey orgstruct-mode-map key cmd))
8152 ;; Special treatment needed for TAB and RET
8153 (org-defkey orgstruct-mode-map [(tab)]
8154 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8155 (org-defkey orgstruct-mode-map "\C-i"
8156 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8158 (org-defkey orgstruct-mode-map "\M-\C-m"
8159 (orgstruct-make-binding 'org-insert-heading 105
8160 "\M-\C-m" [(meta return)]))
8161 (org-defkey orgstruct-mode-map [(meta return)]
8162 (orgstruct-make-binding 'org-insert-heading 106
8163 [(meta return)] "\M-\C-m"))
8165 (org-defkey orgstruct-mode-map [(shift meta return)]
8166 (orgstruct-make-binding 'org-insert-todo-heading 107
8167 [(meta return)] "\M-\C-m"))
8169 (org-defkey orgstruct-mode-map "\e\C-m"
8170 (orgstruct-make-binding 'org-insert-heading 108
8171 "\e\C-m" [?\e (return)]))
8172 (org-defkey orgstruct-mode-map [?\e (return)]
8173 (orgstruct-make-binding 'org-insert-heading 109
8174 [?\e (return)] "\e\C-m"))
8175 (org-defkey orgstruct-mode-map [?\e (shift return)]
8176 (orgstruct-make-binding 'org-insert-todo-heading 110
8177 [?\e (return)] "\e\C-m"))
8179 (unless org-local-vars
8180 (setq org-local-vars (org-get-local-variables)))
8184 (defun orgstruct-make-binding (fun n &rest keys)
8185 "Create a function for binding in the structure minor mode.
8186 FUN is the command to call inside a table. N is used to create a unique
8187 command name. KEYS are keys that should be checked in for a command
8188 to execute outside of tables."
8189 (eval
8190 (list 'defun
8191 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8192 '(arg)
8193 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8194 "Outside of structure, run the binding of `"
8195 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8196 "'.")
8197 '(interactive "p")
8198 (list 'if
8199 `(org-context-p 'headline 'item
8200 (and orgstruct-is-++
8201 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8202 'item-body))
8203 (list 'org-run-like-in-org-mode (list 'quote fun))
8204 (list 'let '(orgstruct-mode)
8205 (list 'call-interactively
8206 (append '(or)
8207 (mapcar (lambda (k)
8208 (list 'key-binding k))
8209 keys)
8210 '('orgstruct-error))))))))
8212 (defun org-context-p (&rest contexts)
8213 "Check if local context is any of CONTEXTS.
8214 Possible values in the list of contexts are `table', `headline', and `item'."
8215 (let ((pos (point)))
8216 (goto-char (point-at-bol))
8217 (prog1 (or (and (memq 'table contexts)
8218 (looking-at "[ \t]*|"))
8219 (and (memq 'headline contexts)
8220 ;;????????? (looking-at "\\*+"))
8221 (looking-at outline-regexp))
8222 (and (memq 'item contexts)
8223 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8224 (and (memq 'item-body contexts)
8225 (org-in-item-p)))
8226 (goto-char pos))))
8228 (defun org-get-local-variables ()
8229 "Return a list of all local variables in an org-mode buffer."
8230 (let (varlist)
8231 (with-current-buffer (get-buffer-create "*Org tmp*")
8232 (erase-buffer)
8233 (org-mode)
8234 (setq varlist (buffer-local-variables)))
8235 (kill-buffer "*Org tmp*")
8236 (delq nil
8237 (mapcar
8238 (lambda (x)
8239 (setq x
8240 (if (symbolp x)
8241 (list x)
8242 (list (car x) (list 'quote (cdr x)))))
8243 (if (string-match
8244 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8245 (symbol-name (car x)))
8246 x nil))
8247 varlist))))
8249 (defun org-clone-local-variables (from-buffer &optional regexp)
8250 "Clone local variables from FROM-BUFFER.
8251 Optional argument REGEXP selects variables to clone."
8252 (mapc
8253 (lambda (pair)
8254 (and (symbolp (car pair))
8255 (or (null regexp)
8256 (string-match regexp (symbol-name (car pair))))
8257 (set (make-local-variable (car pair))
8258 (cdr pair))))
8259 (buffer-local-variables from-buffer)))
8261 ;;;###autoload
8262 (defun org-run-like-in-org-mode (cmd)
8263 "Run a command, pretending that the current buffer is in Org-mode.
8264 This will temporarily bind local variables that are typically bound in
8265 Org-mode to the values they have in Org-mode, and then interactively
8266 call CMD."
8267 (org-load-modules-maybe)
8268 (unless org-local-vars
8269 (setq org-local-vars (org-get-local-variables)))
8270 (eval (list 'let org-local-vars
8271 (list 'call-interactively (list 'quote cmd)))))
8273 ;;;; Archiving
8275 (defun org-get-category (&optional pos force-refresh)
8276 "Get the category applying to position POS."
8277 (if force-refresh (org-refresh-category-properties))
8278 (let ((pos (or pos (point))))
8279 (or (get-text-property pos 'org-category)
8280 (progn (org-refresh-category-properties)
8281 (get-text-property pos 'org-category)))))
8283 (defun org-refresh-category-properties ()
8284 "Refresh category text properties in the buffer."
8285 (let ((def-cat (cond
8286 ((null org-category)
8287 (if buffer-file-name
8288 (file-name-sans-extension
8289 (file-name-nondirectory buffer-file-name))
8290 "???"))
8291 ((symbolp org-category) (symbol-name org-category))
8292 (t org-category)))
8293 beg end cat pos optionp)
8294 (org-unmodified
8295 (save-excursion
8296 (save-restriction
8297 (widen)
8298 (goto-char (point-min))
8299 (put-text-property (point) (point-max) 'org-category def-cat)
8300 (while (re-search-forward
8301 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8302 (setq pos (match-end 0)
8303 optionp (equal (char-after (match-beginning 0)) ?#)
8304 cat (org-trim (match-string 2)))
8305 (if optionp
8306 (setq beg (point-at-bol) end (point-max))
8307 (org-back-to-heading t)
8308 (setq beg (point) end (org-end-of-subtree t t)))
8309 (put-text-property beg end 'org-category cat)
8310 (goto-char pos)))))))
8313 ;;;; Link Stuff
8315 ;;; Link abbreviations
8317 (defun org-link-expand-abbrev (link)
8318 "Apply replacements as defined in `org-link-abbrev-alist."
8319 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8320 (let* ((key (match-string 1 link))
8321 (as (or (assoc key org-link-abbrev-alist-local)
8322 (assoc key org-link-abbrev-alist)))
8323 (tag (and (match-end 2) (match-string 3 link)))
8324 rpl)
8325 (if (not as)
8326 link
8327 (setq rpl (cdr as))
8328 (cond
8329 ((symbolp rpl) (funcall rpl tag))
8330 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8331 ((string-match "%h" rpl)
8332 (replace-match (url-hexify-string (or tag "")) t t rpl))
8333 (t (concat rpl tag)))))
8334 link))
8336 ;;; Storing and inserting links
8338 (defvar org-insert-link-history nil
8339 "Minibuffer history for links inserted with `org-insert-link'.")
8341 (defvar org-stored-links nil
8342 "Contains the links stored with `org-store-link'.")
8344 (defvar org-store-link-plist nil
8345 "Plist with info about the most recently link created with `org-store-link'.")
8347 (defvar org-link-protocols nil
8348 "Link protocols added to Org-mode using `org-add-link-type'.")
8350 (defvar org-store-link-functions nil
8351 "List of functions that are called to create and store a link.
8352 Each function will be called in turn until one returns a non-nil
8353 value. Each function should check if it is responsible for creating
8354 this link (for example by looking at the major mode).
8355 If not, it must exit and return nil.
8356 If yes, it should return a non-nil value after a calling
8357 `org-store-link-props' with a list of properties and values.
8358 Special properties are:
8360 :type The link prefix, like \"http\". This must be given.
8361 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8362 This is obligatory as well.
8363 :description Optional default description for the second pair
8364 of brackets in an Org-mode link. The user can still change
8365 this when inserting this link into an Org-mode buffer.
8367 In addition to these, any additional properties can be specified
8368 and then used in remember templates.")
8370 (defun org-add-link-type (type &optional follow export)
8371 "Add TYPE to the list of `org-link-types'.
8372 Re-compute all regular expressions depending on `org-link-types'
8374 FOLLOW and EXPORT are two functions.
8376 FOLLOW should take the link path as the single argument and do whatever
8377 is necessary to follow the link, for example find a file or display
8378 a mail message.
8380 EXPORT should format the link path for export to one of the export formats.
8381 It should be a function accepting three arguments:
8383 path the path of the link, the text after the prefix (like \"http:\")
8384 desc the description of the link, if any, or a description added by
8385 org-export-normalize-links if there is none
8386 format the export format, a symbol like `html' or `latex' or `ascii'..
8388 The function may use the FORMAT information to return different values
8389 depending on the format. The return value will be put literally into
8390 the exported file. If the return value is nil, this means Org should
8391 do what it normally does with links which do not have EXPORT defined.
8393 Org-mode has a built-in default for exporting links. If you are happy with
8394 this default, there is no need to define an export function for the link
8395 type. For a simple example of an export function, see `org-bbdb.el'."
8396 (add-to-list 'org-link-types type t)
8397 (org-make-link-regexps)
8398 (if (assoc type org-link-protocols)
8399 (setcdr (assoc type org-link-protocols) (list follow export))
8400 (push (list type follow export) org-link-protocols)))
8402 (defvar org-agenda-buffer-name)
8404 ;;;###autoload
8405 (defun org-store-link (arg)
8406 "\\<org-mode-map>Store an org-link to the current location.
8407 This link is added to `org-stored-links' and can later be inserted
8408 into an org-buffer with \\[org-insert-link].
8410 For some link types, a prefix arg is interpreted:
8411 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8412 For file links, arg negates `org-context-in-file-links'."
8413 (interactive "P")
8414 (org-load-modules-maybe)
8415 (setq org-store-link-plist nil) ; reset
8416 (org-with-limited-levels
8417 (let (link cpltxt desc description search txt custom-id agenda-link)
8418 (cond
8420 ((run-hook-with-args-until-success 'org-store-link-functions)
8421 (setq link (plist-get org-store-link-plist :link)
8422 desc (or (plist-get org-store-link-plist :description) link)))
8424 ((equal (buffer-name) "*Org Edit Src Example*")
8425 (let (label gc)
8426 (while (or (not label)
8427 (save-excursion
8428 (save-restriction
8429 (widen)
8430 (goto-char (point-min))
8431 (re-search-forward
8432 (regexp-quote (format org-coderef-label-format label))
8433 nil t))))
8434 (when label (message "Label exists already") (sit-for 2))
8435 (setq label (read-string "Code line label: " label)))
8436 (end-of-line 1)
8437 (setq link (format org-coderef-label-format label))
8438 (setq gc (- 79 (length link)))
8439 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8440 (insert link)
8441 (setq link (concat "(" label ")") desc nil)))
8443 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8444 ;; We are in the agenda, link to referenced location
8445 (let ((m (or (get-text-property (point) 'org-hd-marker)
8446 (get-text-property (point) 'org-marker))))
8447 (when m
8448 (org-with-point-at m
8449 (setq agenda-link
8450 (if (org-called-interactively-p 'any)
8451 (call-interactively 'org-store-link)
8452 (org-store-link nil)))))))
8454 ((eq major-mode 'calendar-mode)
8455 (let ((cd (calendar-cursor-to-date)))
8456 (setq link
8457 (format-time-string
8458 (car org-time-stamp-formats)
8459 (apply 'encode-time
8460 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8461 nil nil nil))))
8462 (org-store-link-props :type "calendar" :date cd)))
8464 ((eq major-mode 'w3-mode)
8465 (setq cpltxt (if (and (buffer-name)
8466 (not (string-match "Untitled" (buffer-name))))
8467 (buffer-name)
8468 (url-view-url t))
8469 link (org-make-link (url-view-url t)))
8470 (org-store-link-props :type "w3" :url (url-view-url t)))
8472 ((eq major-mode 'w3m-mode)
8473 (setq cpltxt (or w3m-current-title w3m-current-url)
8474 link (org-make-link w3m-current-url))
8475 (org-store-link-props :type "w3m" :url (url-view-url t)))
8477 ((setq search (run-hook-with-args-until-success
8478 'org-create-file-search-functions))
8479 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8480 "::" search))
8481 (setq cpltxt (or description link)))
8483 ((eq major-mode 'image-mode)
8484 (setq cpltxt (concat "file:"
8485 (abbreviate-file-name buffer-file-name))
8486 link (org-make-link cpltxt))
8487 (org-store-link-props :type "image" :file buffer-file-name))
8489 ((eq major-mode 'dired-mode)
8490 ;; link to the file in the current line
8491 (let ((file (dired-get-filename nil t)))
8492 (setq file (if file
8493 (abbreviate-file-name
8494 (expand-file-name (dired-get-filename nil t)))
8495 ;; otherwise, no file so use current directory.
8496 default-directory))
8497 (setq cpltxt (concat "file:" file)
8498 link (org-make-link cpltxt))))
8500 ((and (buffer-file-name (buffer-base-buffer)) (org-mode-p))
8501 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8502 (cond
8503 ((org-in-regexp "<<\\(.*?\\)>>")
8504 (setq cpltxt
8505 (concat "file:"
8506 (abbreviate-file-name
8507 (buffer-file-name (buffer-base-buffer)))
8508 "::" (match-string 1))
8509 link (org-make-link cpltxt)))
8510 ((and (featurep 'org-id)
8511 (or (eq org-link-to-org-use-id t)
8512 (and (eq org-link-to-org-use-id 'create-if-interactive)
8513 (org-called-interactively-p 'any))
8514 (and (eq org-link-to-org-use-id
8515 'create-if-interactive-and-no-custom-id)
8516 (org-called-interactively-p 'any)
8517 (not custom-id))
8518 (and org-link-to-org-use-id
8519 (org-entry-get nil "ID"))))
8520 ;; We can make a link using the ID.
8521 (setq link (condition-case nil
8522 (prog1 (org-id-store-link)
8523 (setq desc (plist-get org-store-link-plist
8524 :description)))
8525 (error
8526 ;; probably before first headline, link to file only
8527 (concat "file:"
8528 (abbreviate-file-name
8529 (buffer-file-name (buffer-base-buffer))))))))
8531 ;; Just link to current headline
8532 (setq cpltxt (concat "file:"
8533 (abbreviate-file-name
8534 (buffer-file-name (buffer-base-buffer)))))
8535 ;; Add a context search string
8536 (when (org-xor org-context-in-file-links arg)
8537 (setq txt (cond
8538 ((org-on-heading-p) nil)
8539 ((org-region-active-p)
8540 (buffer-substring (region-beginning) (region-end)))
8541 (t nil)))
8542 (when (or (null txt) (string-match "\\S-" txt))
8543 (setq cpltxt
8544 (concat cpltxt "::"
8545 (condition-case nil
8546 (org-make-org-heading-search-string txt)
8547 (error "")))
8548 desc (or (nth 4 (ignore-errors
8549 (org-heading-components))) "NONE"))))
8550 (if (string-match "::\\'" cpltxt)
8551 (setq cpltxt (substring cpltxt 0 -2)))
8552 (setq link (org-make-link cpltxt)))))
8554 ((buffer-file-name (buffer-base-buffer))
8555 ;; Just link to this file here.
8556 (setq cpltxt (concat "file:"
8557 (abbreviate-file-name
8558 (buffer-file-name (buffer-base-buffer)))))
8559 ;; Add a context string
8560 (when (org-xor org-context-in-file-links arg)
8561 (setq txt (if (org-region-active-p)
8562 (buffer-substring (region-beginning) (region-end))
8563 (buffer-substring (point-at-bol) (point-at-eol))))
8564 ;; Only use search option if there is some text.
8565 (when (string-match "\\S-" txt)
8566 (setq cpltxt
8567 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8568 desc "NONE")))
8569 (setq link (org-make-link cpltxt)))
8571 ((org-called-interactively-p 'interactive)
8572 (error "Cannot link to a buffer which is not visiting a file"))
8574 (t (setq link nil)))
8576 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8577 (setq link (or link cpltxt)
8578 desc (or desc cpltxt))
8579 (if (equal desc "NONE") (setq desc nil))
8581 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8582 (progn
8583 (setq org-stored-links
8584 (cons (list link desc) org-stored-links))
8585 (message "Stored: %s" (or desc link))
8586 (when custom-id
8587 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8588 "::#" custom-id))
8589 (setq org-stored-links
8590 (cons (list link desc) org-stored-links))))
8591 (or agenda-link (and link (org-make-link-string link desc)))))))
8593 (defun org-store-link-props (&rest plist)
8594 "Store link properties, extract names and addresses."
8595 (let (x adr)
8596 (when (setq x (plist-get plist :from))
8597 (setq adr (mail-extract-address-components x))
8598 (setq plist (plist-put plist :fromname (car adr)))
8599 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8600 (when (setq x (plist-get plist :to))
8601 (setq adr (mail-extract-address-components x))
8602 (setq plist (plist-put plist :toname (car adr)))
8603 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8604 (let ((from (plist-get plist :from))
8605 (to (plist-get plist :to)))
8606 (when (and from to org-from-is-user-regexp)
8607 (setq plist
8608 (plist-put plist :fromto
8609 (if (string-match org-from-is-user-regexp from)
8610 (concat "to %t")
8611 (concat "from %f"))))))
8612 (setq org-store-link-plist plist))
8614 (defun org-add-link-props (&rest plist)
8615 "Add these properties to the link property list."
8616 (let (key value)
8617 (while plist
8618 (setq key (pop plist) value (pop plist))
8619 (setq org-store-link-plist
8620 (plist-put org-store-link-plist key value)))))
8622 (defun org-email-link-description (&optional fmt)
8623 "Return the description part of an email link.
8624 This takes information from `org-store-link-plist' and formats it
8625 according to FMT (default from `org-email-link-description-format')."
8626 (setq fmt (or fmt org-email-link-description-format))
8627 (let* ((p org-store-link-plist)
8628 (to (plist-get p :toaddress))
8629 (from (plist-get p :fromaddress))
8630 (table
8631 (list
8632 (cons "%c" (plist-get p :fromto))
8633 (cons "%F" (plist-get p :from))
8634 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8635 (cons "%T" (plist-get p :to))
8636 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8637 (cons "%s" (plist-get p :subject))
8638 (cons "%d" (plist-get p :date))
8639 (cons "%m" (plist-get p :message-id)))))
8640 (when (string-match "%c" fmt)
8641 ;; Check if the user wrote this message
8642 (if (and org-from-is-user-regexp from to
8643 (save-match-data (string-match org-from-is-user-regexp from)))
8644 (setq fmt (replace-match "to %t" t t fmt))
8645 (setq fmt (replace-match "from %f" t t fmt))))
8646 (org-replace-escapes fmt table)))
8648 (defun org-make-org-heading-search-string (&optional string heading)
8649 "Make search string for STRING or current headline."
8650 (interactive)
8651 (let ((s (or string (org-get-heading)))
8652 (lines org-context-in-file-links))
8653 (unless (and string (not heading))
8654 ;; We are using a headline, clean up garbage in there.
8655 (if (string-match org-todo-regexp s)
8656 (setq s (replace-match "" t t s)))
8657 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8658 (setq s (replace-match "" t t s)))
8659 (setq s (org-trim s))
8660 (if (string-match (concat "^\\(" org-quote-string "\\|"
8661 org-comment-string "\\)") s)
8662 (setq s (replace-match "" t t s)))
8663 (while (string-match org-ts-regexp s)
8664 (setq s (replace-match "" t t s))))
8665 (or string (setq s (concat "*" s))) ; Add * for headlines
8666 (when (and string (integerp lines) (> lines 0))
8667 (let ((slines (org-split-string s "\n")))
8668 (when (< lines (length slines))
8669 (setq s (mapconcat
8670 'identity
8671 (reverse (nthcdr (- (length slines) lines)
8672 (reverse slines))) "\n")))))
8673 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8675 (defun org-make-link (&rest strings)
8676 "Concatenate STRINGS."
8677 (apply 'concat strings))
8679 (defun org-make-link-string (link &optional description)
8680 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8681 (unless (string-match "\\S-" link)
8682 (error "Empty link"))
8683 (when (and description
8684 (stringp description)
8685 (not (string-match "\\S-" description)))
8686 (setq description nil))
8687 (when (stringp description)
8688 ;; Remove brackets from the description, they are fatal.
8689 (while (string-match "\\[" description)
8690 (setq description (replace-match "{" t t description)))
8691 (while (string-match "\\]" description)
8692 (setq description (replace-match "}" t t description))))
8693 (when (equal link description)
8694 ;; No description needed, it is identical
8695 (setq description nil))
8696 (when (and (not description)
8697 (not (string-match (org-image-file-name-regexp) link))
8698 (not (equal link (org-link-escape link))))
8699 (setq description (org-extract-attributes link)))
8700 (setq link
8701 (cond ((string-match (org-image-file-name-regexp) link) link)
8702 ((string-match org-link-types-re link)
8703 (concat (match-string 1 link)
8704 (org-link-escape (substring link (match-end 1)))))
8705 (t (org-link-escape link))))
8706 (concat "[[" link "]"
8707 (if description (concat "[" description "]") "")
8708 "]"))
8710 (defconst org-link-escape-chars
8711 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8712 "List of characters that should be escaped in link.
8713 This is the list that is used for internal purposes.")
8715 (defvar org-url-encoding-use-url-hexify nil)
8717 (defconst org-link-escape-chars-browser
8718 '(?\ )
8719 "List of escapes for characters that are problematic in links.
8720 This is the list that is used before handing over to the browser.")
8722 (defun org-link-escape (text &optional table merge)
8723 "Return percent escaped representation of TEXT.
8724 TEXT is a string with the text to escape.
8725 Optional argument TABLE is a list with characters that should be
8726 escaped. When nil, `org-link-escape-chars' is used.
8727 If optional argument MERGE is set, merge TABLE into
8728 `org-link-escape-chars'."
8729 (if (and org-url-encoding-use-url-hexify (not table))
8730 (url-hexify-string text)
8731 (cond
8732 ((and table merge)
8733 (mapc (lambda (defchr)
8734 (unless (member defchr table)
8735 (setq table (cons defchr table)))) org-link-escape-chars))
8736 ((null table)
8737 (setq table org-link-escape-chars)))
8738 (mapconcat
8739 (lambda (char)
8740 (if (or (member char table)
8741 (< char 32) (= char 37) (> char 126))
8742 (mapconcat (lambda (sequence-element)
8743 (format "%%%.2X" sequence-element))
8744 (or (encode-coding-char char 'utf-8)
8745 (error "Unable to percent escape character: %s"
8746 (char-to-string char))) "")
8747 (char-to-string char))) text "")))
8749 (defun org-link-unescape (str)
8750 "Unhex hexified unicode strings as returned from the JavaScript function
8751 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
8752 (unless (and (null str) (string= "" str))
8753 (let ((pos 0) (case-fold-search t) unhexed)
8754 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
8755 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
8756 (setq str (replace-match unhexed t t str))
8757 (setq pos (+ pos (length unhexed))))))
8758 str)
8760 (defun org-link-unescape-compound (hex)
8761 "Unhexify unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
8762 Note: this function also decodes single byte encodings like
8763 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
8764 (save-match-data
8765 (let* ((bytes (cdr (split-string hex "%")))
8766 (ret "")
8767 (eat 0)
8768 (sum 0))
8769 (while bytes
8770 (let* ((val (string-to-number (pop bytes) 16))
8771 (shift-xor
8772 (if (= 0 eat)
8773 (cond
8774 ((>= val 252) (cons 6 252))
8775 ((>= val 248) (cons 5 248))
8776 ((>= val 240) (cons 4 240))
8777 ((>= val 224) (cons 3 224))
8778 ((>= val 192) (cons 2 192))
8779 (t (cons 0 0)))
8780 (cons 6 128))))
8781 (if (>= val 192) (setq eat (car shift-xor)))
8782 (setq val (logxor val (cdr shift-xor)))
8783 (setq sum (+ (lsh sum (car shift-xor)) val))
8784 (if (> eat 0) (setq eat (- eat 1)))
8785 (cond
8786 ((= 0 eat) ;multi byte
8787 (setq ret (concat ret (org-char-to-string sum)))
8788 (setq sum 0))
8789 ((not bytes) ; single byte(s)
8790 (setq ret (org-link-unescape-single-byte-sequence hex))))
8791 )) ;; end (while bytes
8792 ret )))
8794 (defun org-link-unescape-single-byte-sequence (hex)
8795 "Unhexify hex-encoded single byte character sequences."
8796 (mapconcat (lambda (byte)
8797 (char-to-string (string-to-number byte 16)))
8798 (cdr (split-string hex "%")) ""))
8800 (defun org-xor (a b)
8801 "Exclusive or."
8802 (if a (not b) b))
8804 (defun org-fixup-message-id-for-http (s)
8805 "Replace special characters in a message id, so it can be used in an http query."
8806 (when (string-match "%" s)
8807 (setq s (mapconcat (lambda (c)
8808 (if (eq c ?%)
8809 "%25"
8810 (char-to-string c)))
8811 s "")))
8812 (while (string-match "<" s)
8813 (setq s (replace-match "%3C" t t s)))
8814 (while (string-match ">" s)
8815 (setq s (replace-match "%3E" t t s)))
8816 (while (string-match "@" s)
8817 (setq s (replace-match "%40" t t s)))
8820 ;;;###autoload
8821 (defun org-insert-link-global ()
8822 "Insert a link like Org-mode does.
8823 This command can be called in any mode to insert a link in Org-mode syntax."
8824 (interactive)
8825 (org-load-modules-maybe)
8826 (org-run-like-in-org-mode 'org-insert-link))
8828 (defun org-insert-link (&optional complete-file link-location)
8829 "Insert a link. At the prompt, enter the link.
8831 Completion can be used to insert any of the link protocol prefixes like
8832 http or ftp in use.
8834 The history can be used to select a link previously stored with
8835 `org-store-link'. When the empty string is entered (i.e. if you just
8836 press RET at the prompt), the link defaults to the most recently
8837 stored link. As SPC triggers completion in the minibuffer, you need to
8838 use M-SPC or C-q SPC to force the insertion of a space character.
8840 You will also be prompted for a description, and if one is given, it will
8841 be displayed in the buffer instead of the link.
8843 If there is already a link at point, this command will allow you to edit link
8844 and description parts.
8846 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8847 be selected using completion. The path to the file will be relative to the
8848 current directory if the file is in the current directory or a subdirectory.
8849 Otherwise, the link will be the absolute path as completed in the minibuffer
8850 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8851 option `org-link-file-path-type'.
8853 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8854 the current directory or below.
8856 With three \\[universal-argument] prefixes, negate the meaning of
8857 `org-keep-stored-link-after-insertion'.
8859 If `org-make-link-description-function' is non-nil, this function will be
8860 called with the link target, and the result will be the default
8861 link description.
8863 If the LINK-LOCATION parameter is non-nil, this value will be
8864 used as the link location instead of reading one interactively."
8865 (interactive "P")
8866 (let* ((wcf (current-window-configuration))
8867 (region (if (org-region-active-p)
8868 (buffer-substring (region-beginning) (region-end))))
8869 (remove (and region (list (region-beginning) (region-end))))
8870 (desc region)
8871 tmphist ; byte-compile incorrectly complains about this
8872 (link link-location)
8873 entry file all-prefixes)
8874 (cond
8875 (link-location) ; specified by arg, just use it.
8876 ((org-in-regexp org-bracket-link-regexp 1)
8877 ;; We do have a link at point, and we are going to edit it.
8878 (setq remove (list (match-beginning 0) (match-end 0)))
8879 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8880 (setq link (read-string "Link: "
8881 (org-link-unescape
8882 (org-match-string-no-properties 1)))))
8883 ((or (org-in-regexp org-angle-link-re)
8884 (org-in-regexp org-plain-link-re))
8885 ;; Convert to bracket link
8886 (setq remove (list (match-beginning 0) (match-end 0))
8887 link (read-string "Link: "
8888 (org-remove-angle-brackets (match-string 0)))))
8889 ((member complete-file '((4) (16)))
8890 ;; Completing read for file names.
8891 (setq link (org-file-complete-link complete-file)))
8893 ;; Read link, with completion for stored links.
8894 (with-output-to-temp-buffer "*Org Links*"
8895 (princ "Insert a link.
8896 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8897 (when org-stored-links
8898 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8899 (princ (mapconcat
8900 (lambda (x)
8901 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8902 (reverse org-stored-links) "\n"))))
8903 (let ((cw (selected-window)))
8904 (select-window (get-buffer-window "*Org Links*" 'visible))
8905 (with-current-buffer "*Org Links*" (setq truncate-lines) t)
8906 (unless (pos-visible-in-window-p (point-max))
8907 (org-fit-window-to-buffer))
8908 (and (window-live-p cw) (select-window cw)))
8909 ;; Fake a link history, containing the stored links.
8910 (setq tmphist (append (mapcar 'car org-stored-links)
8911 org-insert-link-history))
8912 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8913 (mapcar 'car org-link-abbrev-alist)
8914 org-link-types))
8915 (unwind-protect
8916 (progn
8917 (setq link
8918 (let ((org-completion-use-ido nil)
8919 (org-completion-use-iswitchb nil))
8920 (org-completing-read
8921 "Link: "
8922 (append
8923 (mapcar (lambda (x) (list (concat x ":")))
8924 all-prefixes)
8925 (mapcar 'car org-stored-links))
8926 nil nil nil
8927 'tmphist
8928 (car (car org-stored-links)))))
8929 (if (not (string-match "\\S-" link))
8930 (error "No link selected"))
8931 (if (or (member link all-prefixes)
8932 (and (equal ":" (substring link -1))
8933 (member (substring link 0 -1) all-prefixes)
8934 (setq link (substring link 0 -1))))
8935 (setq link (org-link-try-special-completion link))))
8936 (set-window-configuration wcf)
8937 (kill-buffer "*Org Links*"))
8938 (setq entry (assoc link org-stored-links))
8939 (or entry (push link org-insert-link-history))
8940 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8941 (not org-keep-stored-link-after-insertion))
8942 (setq org-stored-links (delq (assoc link org-stored-links)
8943 org-stored-links)))
8944 (setq desc (or desc (nth 1 entry)))))
8946 (if (string-match org-plain-link-re link)
8947 ;; URL-like link, normalize the use of angular brackets.
8948 (setq link (org-make-link (org-remove-angle-brackets link))))
8950 ;; Check if we are linking to the current file with a search option
8951 ;; If yes, simplify the link by using only the search option.
8952 (when (and buffer-file-name
8953 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8954 (let* ((path (match-string 1 link))
8955 (case-fold-search nil)
8956 (search (match-string 2 link)))
8957 (save-match-data
8958 (if (equal (file-truename buffer-file-name) (file-truename path))
8959 ;; We are linking to this same file, with a search option
8960 (setq link search)))))
8962 ;; Check if we can/should use a relative path. If yes, simplify the link
8963 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8964 (let* ((type (match-string 1 link))
8965 (path (match-string 2 link))
8966 (origpath path)
8967 (case-fold-search nil))
8968 (cond
8969 ((or (eq org-link-file-path-type 'absolute)
8970 (equal complete-file '(16)))
8971 (setq path (abbreviate-file-name (expand-file-name path))))
8972 ((eq org-link-file-path-type 'noabbrev)
8973 (setq path (expand-file-name path)))
8974 ((eq org-link-file-path-type 'relative)
8975 (setq path (file-relative-name path)))
8977 (save-match-data
8978 (if (string-match (concat "^" (regexp-quote
8979 (expand-file-name
8980 (file-name-as-directory
8981 default-directory))))
8982 (expand-file-name path))
8983 ;; We are linking a file with relative path name.
8984 (setq path (substring (expand-file-name path)
8985 (match-end 0)))
8986 (setq path (abbreviate-file-name (expand-file-name path)))))))
8987 (setq link (concat type path))
8988 (if (equal desc origpath)
8989 (setq desc path))))
8991 (if org-make-link-description-function
8992 (setq desc (funcall org-make-link-description-function link desc)))
8994 (setq desc (read-string "Description: " desc))
8995 (unless (string-match "\\S-" desc) (setq desc nil))
8996 (if remove (apply 'delete-region remove))
8997 (insert (org-make-link-string link desc))))
8999 (defun org-link-try-special-completion (type)
9000 "If there is completion support for link type TYPE, offer it."
9001 (let ((fun (intern (concat "org-" type "-complete-link"))))
9002 (if (functionp fun)
9003 (funcall fun)
9004 (read-string "Link (no completion support): " (concat type ":")))))
9006 (defun org-file-complete-link (&optional arg)
9007 "Create a file link using completion."
9008 (let (file link)
9009 (setq file (read-file-name "File: "))
9010 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9011 (pwd1 (file-name-as-directory (abbreviate-file-name
9012 (expand-file-name ".")))))
9013 (cond
9014 ((equal arg '(16))
9015 (setq link (org-make-link
9016 "file:"
9017 (abbreviate-file-name (expand-file-name file)))))
9018 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9019 (setq link (org-make-link "file:" (match-string 1 file))))
9020 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9021 (expand-file-name file))
9022 (setq link (org-make-link
9023 "file:" (match-string 1 (expand-file-name file)))))
9024 (t (setq link (org-make-link "file:" file)))))
9025 link))
9027 (defun org-completing-read (&rest args)
9028 "Completing-read with SPACE being a normal character."
9029 (let ((minibuffer-local-completion-map
9030 (copy-keymap minibuffer-local-completion-map)))
9031 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9032 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9033 (apply 'org-icompleting-read args)))
9035 (defun org-completing-read-no-i (&rest args)
9036 (let (org-completion-use-ido org-completion-use-iswitchb)
9037 (apply 'org-completing-read args)))
9039 (defun org-iswitchb-completing-read (prompt choices &rest args)
9040 "Use iswitch as a completing-read replacement to choose from choices.
9041 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9042 from."
9043 (let* ((iswitchb-use-virtual-buffers nil)
9044 (iswitchb-make-buflist-hook
9045 (lambda ()
9046 (setq iswitchb-temp-buflist choices))))
9047 (iswitchb-read-buffer prompt)))
9049 (defun org-icompleting-read (&rest args)
9050 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9051 (org-without-partial-completion
9052 (if (and org-completion-use-ido
9053 (fboundp 'ido-completing-read)
9054 (boundp 'ido-mode) ido-mode
9055 (listp (second args)))
9056 (let ((ido-enter-matching-directory nil))
9057 (apply 'ido-completing-read (concat (car args))
9058 (if (consp (car (nth 1 args)))
9059 (mapcar 'car (nth 1 args))
9060 (nth 1 args))
9061 (cddr args)))
9062 (if (and org-completion-use-iswitchb
9063 (boundp 'iswitchb-mode) iswitchb-mode
9064 (listp (second args)))
9065 (apply 'org-iswitchb-completing-read (concat (car args))
9066 (if (consp (car (nth 1 args)))
9067 (mapcar 'car (nth 1 args))
9068 (nth 1 args))
9069 (cddr args))
9070 (apply 'completing-read args)))))
9072 (defun org-extract-attributes (s)
9073 "Extract the attributes cookie from a string and set as text property."
9074 (let (a attr (start 0) key value)
9075 (save-match-data
9076 (when (string-match "{{\\([^}]+\\)}}$" s)
9077 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9078 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9079 (setq key (match-string 1 a) value (match-string 2 a)
9080 start (match-end 0)
9081 attr (plist-put attr (intern key) value))))
9082 (org-add-props s nil 'org-attr attr))
9085 (defun org-extract-attributes-from-string (tag)
9086 (let (key value attr)
9087 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9088 (setq key (match-string 1 tag) value (match-string 2 tag)
9089 tag (replace-match "" t t tag)
9090 attr (plist-put attr (intern key) value)))
9091 (cons tag attr)))
9093 (defun org-attributes-to-string (plist)
9094 "Format a property list into an HTML attribute list."
9095 (let ((s "") key value)
9096 (while plist
9097 (setq key (pop plist) value (pop plist))
9098 (and value
9099 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9102 ;;; Opening/following a link
9104 (defvar org-link-search-failed nil)
9106 (defvar org-open-link-functions nil
9107 "Hook for functions finding a plain text link.
9108 These functions must take a single argument, the link content.
9109 They will be called for links that look like [[link text][description]]
9110 when LINK TEXT does not have a protocol like \"http:\" and does not look
9111 like a filename (e.g. \"./blue.png\").
9113 These functions will be called *before* Org attempts to resolve the
9114 link by doing text searches in the current buffer - so if you want a
9115 link \"[[target]]\" to still find \"<<target>>\", your function should
9116 handle this as a special case.
9118 When the function does handle the link, it must return a non-nil value.
9119 If it decides that it is not responsible for this link, it must return
9120 nil to indicate that that Org-mode can continue with other options
9121 like exact and fuzzy text search.")
9123 (defun org-next-link ()
9124 "Move forward to the next link.
9125 If the link is in hidden text, expose it."
9126 (interactive)
9127 (when (and org-link-search-failed (eq this-command last-command))
9128 (goto-char (point-min))
9129 (message "Link search wrapped back to beginning of buffer"))
9130 (setq org-link-search-failed nil)
9131 (let* ((pos (point))
9132 (ct (org-context))
9133 (a (assoc :link ct)))
9134 (if a (goto-char (nth 2 a)))
9135 (if (re-search-forward org-any-link-re nil t)
9136 (progn
9137 (goto-char (match-beginning 0))
9138 (if (outline-invisible-p) (org-show-context)))
9139 (goto-char pos)
9140 (setq org-link-search-failed t)
9141 (error "No further link found"))))
9143 (defun org-previous-link ()
9144 "Move backward to the previous link.
9145 If the link is in hidden text, expose it."
9146 (interactive)
9147 (when (and org-link-search-failed (eq this-command last-command))
9148 (goto-char (point-max))
9149 (message "Link search wrapped back to end of buffer"))
9150 (setq org-link-search-failed nil)
9151 (let* ((pos (point))
9152 (ct (org-context))
9153 (a (assoc :link ct)))
9154 (if a (goto-char (nth 1 a)))
9155 (if (re-search-backward org-any-link-re nil t)
9156 (progn
9157 (goto-char (match-beginning 0))
9158 (if (outline-invisible-p) (org-show-context)))
9159 (goto-char pos)
9160 (setq org-link-search-failed t)
9161 (error "No further link found"))))
9163 (defun org-translate-link (s)
9164 "Translate a link string if a translation function has been defined."
9165 (if (and org-link-translation-function
9166 (fboundp org-link-translation-function)
9167 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9168 (progn
9169 (setq s (funcall org-link-translation-function
9170 (match-string 1) (match-string 2)))
9171 (concat (car s) ":" (cdr s)))
9174 (defun org-translate-link-from-planner (type path)
9175 "Translate a link from Emacs Planner syntax so that Org can follow it.
9176 This is still an experimental function, your mileage may vary."
9177 (cond
9178 ((member type '("http" "https" "news" "ftp"))
9179 ;; standard Internet links are the same.
9180 nil)
9181 ((and (equal type "irc") (string-match "^//" path))
9182 ;; Planner has two / at the beginning of an irc link, we have 1.
9183 ;; We should have zero, actually....
9184 (setq path (substring path 1)))
9185 ((and (equal type "lisp") (string-match "^/" path))
9186 ;; Planner has a slash, we do not.
9187 (setq type "elisp" path (substring path 1)))
9188 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9189 ;; A typical message link. Planner has the id after the final slash,
9190 ;; we separate it with a hash mark
9191 (setq path (concat (match-string 1 path) "#"
9192 (org-remove-angle-brackets (match-string 2 path)))))
9194 (cons type path))
9196 (defun org-find-file-at-mouse (ev)
9197 "Open file link or URL at mouse."
9198 (interactive "e")
9199 (mouse-set-point ev)
9200 (org-open-at-point 'in-emacs))
9202 (defun org-open-at-mouse (ev)
9203 "Open file link or URL at mouse."
9204 (interactive "e")
9205 (mouse-set-point ev)
9206 (if (eq major-mode 'org-agenda-mode)
9207 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9208 (org-open-at-point))
9210 (defvar org-window-config-before-follow-link nil
9211 "The window configuration before following a link.
9212 This is saved in case the need arises to restore it.")
9214 (defvar org-open-link-marker (make-marker)
9215 "Marker pointing to the location where `org-open-at-point; was called.")
9217 ;;;###autoload
9218 (defun org-open-at-point-global ()
9219 "Follow a link like Org-mode does.
9220 This command can be called in any mode to follow a link that has
9221 Org-mode syntax."
9222 (interactive)
9223 (org-run-like-in-org-mode 'org-open-at-point))
9225 ;;;###autoload
9226 (defun org-open-link-from-string (s &optional arg reference-buffer)
9227 "Open a link in the string S, as if it was in Org-mode."
9228 (interactive "sLink: \nP")
9229 (let ((reference-buffer (or reference-buffer (current-buffer))))
9230 (with-temp-buffer
9231 (let ((org-inhibit-startup t))
9232 (org-mode)
9233 (insert s)
9234 (goto-char (point-min))
9235 (when reference-buffer
9236 (setq org-link-abbrev-alist-local
9237 (with-current-buffer reference-buffer
9238 org-link-abbrev-alist-local)))
9239 (org-open-at-point arg reference-buffer)))))
9241 (defvar org-open-at-point-functions nil
9242 "Hook that is run when following a link at point.
9244 Functions in this hook must return t if they identify and follow
9245 a link at point. If they don't find anything interesting at point,
9246 they must return nil.")
9248 (defun org-open-at-point (&optional arg reference-buffer)
9249 "Open link at or after point.
9250 If there is no link at point, this function will search forward up to
9251 the end of the current line.
9252 Normally, files will be opened by an appropriate application. If the
9253 optional prefix argument ARG is non-nil, Emacs will visit the file.
9254 With a double prefix argument, try to open outside of Emacs, in the
9255 application the system uses for this file type."
9256 (interactive "P")
9257 ;; if in a code block, then open the block's results
9258 (unless (call-interactively #'org-babel-open-src-block-result)
9259 (org-load-modules-maybe)
9260 (move-marker org-open-link-marker (point))
9261 (setq org-window-config-before-follow-link (current-window-configuration))
9262 (org-remove-occur-highlights nil nil t)
9263 (cond
9264 ((and (org-on-heading-p)
9265 (not (org-in-regexp
9266 (concat org-plain-link-re "\\|"
9267 org-bracket-link-regexp "\\|"
9268 org-angle-link-re "\\|"
9269 "[ \t]:[^ \t\n]+:[ \t]*$")))
9270 (not (get-text-property (point) 'org-linked-text)))
9271 (or (org-offer-links-in-entry arg)
9272 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9273 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9274 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9275 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9276 (not (org-in-regexp org-bracket-link-regexp)))
9277 (org-footnote-action))
9279 (let (type path link line search (pos (point)))
9280 (catch 'match
9281 (save-excursion
9282 (skip-chars-forward "^]\n\r")
9283 (when (org-in-regexp org-bracket-link-regexp 1)
9284 (setq link (org-extract-attributes
9285 (org-link-unescape (org-match-string-no-properties 1))))
9286 (while (string-match " *\n *" link)
9287 (setq link (replace-match " " t t link)))
9288 (setq link (org-link-expand-abbrev link))
9289 (cond
9290 ((or (file-name-absolute-p link)
9291 (string-match "^\\.\\.?/" link))
9292 (setq type "file" path link))
9293 ((string-match org-link-re-with-space3 link)
9294 (setq type (match-string 1 link) path (match-string 2 link)))
9295 (t (setq type "thisfile" path link)))
9296 (throw 'match t)))
9298 (when (get-text-property (point) 'org-linked-text)
9299 (setq type "thisfile"
9300 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9301 (1+ (point)) (point))
9302 path (buffer-substring
9303 (or (previous-single-property-change pos 'org-linked-text)
9304 (point-min))
9305 (or (next-single-property-change pos 'org-linked-text)
9306 (point-max))))
9307 (throw 'match t))
9309 (save-excursion
9310 (when (or (org-in-regexp org-angle-link-re)
9311 (org-in-regexp org-plain-link-re))
9312 (setq type (match-string 1) path (match-string 2))
9313 (throw 'match t)))
9314 (save-excursion
9315 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9316 (setq type "tags"
9317 path (match-string 1))
9318 (while (string-match ":" path)
9319 (setq path (replace-match "+" t t path)))
9320 (throw 'match t)))
9321 (when (org-in-regexp "<\\([^><\n]+\\)>")
9322 (setq type "tree-match"
9323 path (match-string 1))
9324 (throw 'match t)))
9325 (unless path
9326 (error "No link found"))
9328 ;; switch back to reference buffer
9329 ;; needed when if called in a temporary buffer through
9330 ;; org-open-link-from-string
9331 (with-current-buffer (or reference-buffer (current-buffer))
9333 ;; Remove any trailing spaces in path
9334 (if (string-match " +\\'" path)
9335 (setq path (replace-match "" t t path)))
9336 (if (and org-link-translation-function
9337 (fboundp org-link-translation-function))
9338 ;; Check if we need to translate the link
9339 (let ((tmp (funcall org-link-translation-function type path)))
9340 (setq type (car tmp) path (cdr tmp))))
9342 (cond
9344 ((assoc type org-link-protocols)
9345 (funcall (nth 1 (assoc type org-link-protocols)) path))
9347 ((equal type "mailto")
9348 (let ((cmd (car org-link-mailto-program))
9349 (args (cdr org-link-mailto-program)) args1
9350 (address path) (subject "") a)
9351 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9352 (setq address (match-string 1 path)
9353 subject (org-link-escape (match-string 2 path))))
9354 (while args
9355 (cond
9356 ((not (stringp (car args))) (push (pop args) args1))
9357 (t (setq a (pop args))
9358 (if (string-match "%a" a)
9359 (setq a (replace-match address t t a)))
9360 (if (string-match "%s" a)
9361 (setq a (replace-match subject t t a)))
9362 (push a args1))))
9363 (apply cmd (nreverse args1))))
9365 ((member type '("http" "https" "ftp" "news"))
9366 (browse-url (concat type ":" (org-link-escape
9367 path org-link-escape-chars-browser))))
9369 ((string= type "doi")
9370 (browse-url (concat "http://dx.doi.org/"
9371 (org-link-escape
9372 path org-link-escape-chars-browser))))
9374 ((member type '("message"))
9375 (browse-url (concat type ":" path)))
9377 ((string= type "tags")
9378 (org-tags-view arg path))
9380 ((string= type "tree-match")
9381 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9383 ((string= type "file")
9384 (if (string-match "::\\([0-9]+\\)\\'" path)
9385 (setq line (string-to-number (match-string 1 path))
9386 path (substring path 0 (match-beginning 0)))
9387 (if (string-match "::\\(.+\\)\\'" path)
9388 (setq search (match-string 1 path)
9389 path (substring path 0 (match-beginning 0)))))
9390 (if (string-match "[*?{]" (file-name-nondirectory path))
9391 (dired path)
9392 (org-open-file path arg line search)))
9394 ((string= type "shell")
9395 (let ((cmd path))
9396 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9397 (string-match org-confirm-shell-link-not-regexp cmd))
9398 (not org-confirm-shell-link-function)
9399 (funcall org-confirm-shell-link-function
9400 (format "Execute \"%s\" in shell? "
9401 (org-add-props cmd nil
9402 'face 'org-warning))))
9403 (progn
9404 (message "Executing %s" cmd)
9405 (shell-command cmd))
9406 (error "Abort"))))
9408 ((string= type "elisp")
9409 (let ((cmd path))
9410 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9411 (string-match org-confirm-elisp-link-not-regexp cmd))
9412 (not org-confirm-elisp-link-function)
9413 (funcall org-confirm-elisp-link-function
9414 (format "Execute \"%s\" as elisp? "
9415 (org-add-props cmd nil
9416 'face 'org-warning))))
9417 (message "%s => %s" cmd
9418 (if (equal (string-to-char cmd) ?\()
9419 (eval (read cmd))
9420 (call-interactively (read cmd))))
9421 (error "Abort"))))
9423 ((and (string= type "thisfile")
9424 (run-hook-with-args-until-success
9425 'org-open-link-functions path)))
9427 ((string= type "thisfile")
9428 (if arg
9429 (switch-to-buffer-other-window
9430 (org-get-buffer-for-internal-link (current-buffer)))
9431 (org-mark-ring-push))
9432 (let ((cmd `(org-link-search
9433 ,path
9434 ,(cond ((equal arg '(4)) ''occur)
9435 ((equal arg '(16)) ''org-occur)
9436 (t nil))
9437 ,pos)))
9438 (condition-case nil (eval cmd)
9439 (error (progn (widen) (eval cmd))))))
9442 (browse-url-at-point)))))))
9443 (move-marker org-open-link-marker nil)
9444 (run-hook-with-args 'org-follow-link-hook)))
9446 (defun org-offer-links-in-entry (&optional nth zero)
9447 "Offer links in the current entry and follow the selected link.
9448 If there is only one link, follow it immediately as well.
9449 If NTH is an integer, immediately pick the NTH link found.
9450 If ZERO is a string, check also this string for a link, and if
9451 there is one, offer it as link number zero."
9452 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9453 "\\(" org-angle-link-re "\\)\\|"
9454 "\\(" org-plain-link-re "\\)"))
9455 (cnt ?0)
9456 (in-emacs (if (integerp nth) nil nth))
9457 have-zero end links link c)
9458 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9459 (push (match-string 0 zero) links)
9460 (setq cnt (1- cnt) have-zero t))
9461 (save-excursion
9462 (org-back-to-heading t)
9463 (setq end (save-excursion (outline-next-heading) (point)))
9464 (while (re-search-forward re end t)
9465 (push (match-string 0) links))
9466 (setq links (org-uniquify (reverse links))))
9468 (cond
9469 ((null links)
9470 (message "No links"))
9471 ((equal (length links) 1)
9472 (setq link (list (car links))))
9473 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9474 (setq link (nth (if have-zero nth (1- nth)) links)))
9475 (t ; we have to select a link
9476 (save-excursion
9477 (save-window-excursion
9478 (delete-other-windows)
9479 (with-output-to-temp-buffer "*Select Link*"
9480 (mapc (lambda (l)
9481 (if (not (string-match org-bracket-link-regexp l))
9482 (princ (format "[%c] %s\n" (incf cnt)
9483 (org-remove-angle-brackets l)))
9484 (if (match-end 3)
9485 (princ (format "[%c] %s (%s)\n" (incf cnt)
9486 (match-string 3 l) (match-string 1 l)))
9487 (princ (format "[%c] %s\n" (incf cnt)
9488 (match-string 1 l))))))
9489 links))
9490 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9491 (message "Select link to open, RET to open all:")
9492 (setq c (read-char-exclusive))
9493 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9494 (when (equal c ?q) (error "Abort"))
9495 (if (equal c ?\C-m)
9496 (setq link links)
9497 (setq nth (- c ?0))
9498 (if have-zero (setq nth (1+ nth)))
9499 (unless (and (integerp nth) (>= (length links) nth))
9500 (error "Invalid link selection"))
9501 (setq link (list (nth (1- nth) links))))))
9502 (if link
9503 (let ((buf (current-buffer)))
9504 (dolist (l link)
9505 (org-open-link-from-string l in-emacs buf))
9507 nil)))
9509 ;; Add special file links that specify the way of opening
9511 (org-add-link-type "file+sys" 'org-open-file-with-system)
9512 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9513 (defun org-open-file-with-system (path)
9514 "Open file at PATH using the system way of opening it."
9515 (org-open-file path 'system))
9516 (defun org-open-file-with-emacs (path)
9517 "Open file at PATH in Emacs."
9518 (org-open-file path 'emacs))
9519 (defun org-remove-file-link-modifiers ()
9520 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9521 (goto-char (point-min))
9522 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9523 (org-if-unprotected
9524 (replace-match "file:" t t))))
9525 (eval-after-load "org-exp"
9526 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9527 'org-remove-file-link-modifiers))
9529 ;;;; Time estimates
9531 (defun org-get-effort (&optional pom)
9532 "Get the effort estimate for the current entry."
9533 (org-entry-get pom org-effort-property))
9535 ;;; File search
9537 (defvar org-create-file-search-functions nil
9538 "List of functions to construct the right search string for a file link.
9539 These functions are called in turn with point at the location to
9540 which the link should point.
9542 A function in the hook should first test if it would like to
9543 handle this file type, for example by checking the `major-mode'
9544 or the file extension. If it decides not to handle this file, it
9545 should just return nil to give other functions a chance. If it
9546 does handle the file, it must return the search string to be used
9547 when following the link. The search string will be part of the
9548 file link, given after a double colon, and `org-open-at-point'
9549 will automatically search for it. If special measures must be
9550 taken to make the search successful, another function should be
9551 added to the companion hook `org-execute-file-search-functions',
9552 which see.
9554 A function in this hook may also use `setq' to set the variable
9555 `description' to provide a suggestion for the descriptive text to
9556 be used for this link when it gets inserted into an Org-mode
9557 buffer with \\[org-insert-link].")
9559 (defvar org-execute-file-search-functions nil
9560 "List of functions to execute a file search triggered by a link.
9562 Functions added to this hook must accept a single argument, the
9563 search string that was part of the file link, the part after the
9564 double colon. The function must first check if it would like to
9565 handle this search, for example by checking the `major-mode' or
9566 the file extension. If it decides not to handle this search, it
9567 should just return nil to give other functions a chance. If it
9568 does handle the search, it must return a non-nil value to keep
9569 other functions from trying.
9571 Each function can access the current prefix argument through the
9572 variable `current-prefix-argument'. Note that a single prefix is
9573 used to force opening a link in Emacs, so it may be good to only
9574 use a numeric or double prefix to guide the search function.
9576 In case this is needed, a function in this hook can also restore
9577 the window configuration before `org-open-at-point' was called using:
9579 (set-window-configuration org-window-config-before-follow-link)")
9581 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9582 (defun org-link-search (s &optional type avoid-pos)
9583 "Search for a link search option.
9584 If S is surrounded by forward slashes, it is interpreted as a
9585 regular expression. In org-mode files, this will create an `org-occur'
9586 sparse tree. In ordinary files, `occur' will be used to list matches.
9587 If the current buffer is in `dired-mode', grep will be used to search
9588 in all files. If AVOID-POS is given, ignore matches near that position."
9589 (let ((case-fold-search t)
9590 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9591 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9592 (append '(("") (" ") ("\t") ("\n"))
9593 org-emphasis-alist)
9594 "\\|") "\\)"))
9595 (pos (point))
9596 (pre nil) (post nil)
9597 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9598 (cond
9599 ;; First check if there are any special search functions
9600 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9601 ;; Now try the builtin stuff
9602 ((and (equal (string-to-char s0) ?#)
9603 (> (length s0) 1)
9604 (save-excursion
9605 (goto-char (point-min))
9606 (and
9607 (re-search-forward
9608 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9609 (setq type 'dedicated
9610 pos (match-beginning 0))))
9611 ;; There is an exact target for this
9612 (goto-char pos)
9613 (org-back-to-heading t)))
9614 ((save-excursion
9615 (goto-char (point-min))
9616 (and
9617 (re-search-forward
9618 (concat "<<" (regexp-quote s0) ">>") nil t)
9619 (setq type 'dedicated
9620 pos (match-beginning 0))))
9621 ;; There is an exact target for this
9622 (goto-char pos))
9623 ((and (string-match "^(\\(.*\\))$" s0)
9624 (save-excursion
9625 (goto-char (point-min))
9626 (and
9627 (re-search-forward
9628 (concat "[^[]" (regexp-quote
9629 (format org-coderef-label-format
9630 (match-string 1 s0))))
9631 nil t)
9632 (setq type 'dedicated
9633 pos (1+ (match-beginning 0))))))
9634 ;; There is a coderef target for this
9635 (goto-char pos))
9636 ((string-match "^/\\(.*\\)/$" s)
9637 ;; A regular expression
9638 (cond
9639 ((org-mode-p)
9640 (org-occur (match-string 1 s)))
9641 ;;((eq major-mode 'dired-mode)
9642 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9643 (t (org-do-occur (match-string 1 s)))))
9644 ((and (org-mode-p) org-link-search-must-match-exact-headline)
9645 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9646 (goto-char (point-min))
9647 (cond
9648 ((let (case-fold-search)
9649 (re-search-forward (format org-complex-heading-regexp-format
9650 (regexp-quote s))
9651 nil t))
9652 ;; OK, found a match
9653 (setq type 'dedicated)
9654 (goto-char (match-beginning 0)))
9655 ((and (not org-link-search-inhibit-query)
9656 (eq org-link-search-must-match-exact-headline 'query-to-create)
9657 (y-or-n-p "No match - create this as a new heading? "))
9658 (goto-char (point-max))
9659 (or (bolp) (newline))
9660 (insert "* " s "\n")
9661 (beginning-of-line 0))
9663 (goto-char pos)
9664 (error "No match"))))
9666 ;; A normal search string
9667 (when (equal (string-to-char s) ?*)
9668 ;; Anchor on headlines, post may include tags.
9669 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9670 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9671 s (substring s 1)))
9672 (remove-text-properties
9673 0 (length s)
9674 '(face nil mouse-face nil keymap nil fontified nil) s)
9675 ;; Make a series of regular expressions to find a match
9676 (setq words (org-split-string s "[ \n\r\t]+")
9678 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9679 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9680 "\\)" markers)
9681 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9682 re2a (concat "[ \t\r\n]" re2a_)
9683 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9684 re4 (concat "[^a-zA-Z_]" re4_)
9686 re1 (concat pre re2 post)
9687 re3 (concat pre (if pre re4_ re4) post)
9688 re5 (concat pre ".*" re4)
9689 re2 (concat pre re2)
9690 re2a (concat pre (if pre re2a_ re2a))
9691 re4 (concat pre (if pre re4_ re4))
9692 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9693 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9694 re5 "\\)"
9696 (cond
9697 ((eq type 'org-occur) (org-occur reall))
9698 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9699 (t (goto-char (point-min))
9700 (setq type 'fuzzy)
9701 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9702 (org-search-not-self 1 re1 nil t)
9703 (org-search-not-self 1 re2 nil t)
9704 (org-search-not-self 1 re2a nil t)
9705 (org-search-not-self 1 re3 nil t)
9706 (org-search-not-self 1 re4 nil t)
9707 (org-search-not-self 1 re5 nil t)
9709 (goto-char (match-beginning 1))
9710 (goto-char pos)
9711 (error "No match"))))))
9712 (and (org-mode-p) (org-show-context 'link-search))
9713 type))
9715 (defun org-search-not-self (group &rest args)
9716 "Execute `re-search-forward', but only accept matches that do not
9717 enclose the position of `org-open-link-marker'."
9718 (let ((m org-open-link-marker))
9719 (catch 'exit
9720 (while (apply 're-search-forward args)
9721 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9722 (goto-char (match-end group))
9723 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9724 (> (match-beginning 0) (marker-position m))
9725 (< (match-end 0) (marker-position m)))
9726 (save-match-data
9727 (or (not (org-in-regexp
9728 org-bracket-link-analytic-regexp 1))
9729 (not (match-end 4)) ; no description
9730 (and (<= (match-beginning 4) (point))
9731 (>= (match-end 4) (point))))))
9732 (throw 'exit (point))))))))
9734 (defun org-get-buffer-for-internal-link (buffer)
9735 "Return a buffer to be used for displaying the link target of internal links."
9736 (cond
9737 ((not org-display-internal-link-with-indirect-buffer)
9738 buffer)
9739 ((string-match "(Clone)$" (buffer-name buffer))
9740 (message "Buffer is already a clone, not making another one")
9741 ;; we also do not modify visibility in this case
9742 buffer)
9743 (t ; make a new indirect buffer for displaying the link
9744 (let* ((bn (buffer-name buffer))
9745 (ibn (concat bn "(Clone)"))
9746 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9747 (with-current-buffer ib (org-overview))
9748 ib))))
9750 (defun org-do-occur (regexp &optional cleanup)
9751 "Call the Emacs command `occur'.
9752 If CLEANUP is non-nil, remove the printout of the regular expression
9753 in the *Occur* buffer. This is useful if the regex is long and not useful
9754 to read."
9755 (occur regexp)
9756 (when cleanup
9757 (let ((cwin (selected-window)) win beg end)
9758 (when (setq win (get-buffer-window "*Occur*"))
9759 (select-window win))
9760 (goto-char (point-min))
9761 (when (re-search-forward "match[a-z]+" nil t)
9762 (setq beg (match-end 0))
9763 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9764 (setq end (1- (match-beginning 0)))))
9765 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9766 (goto-char (point-min))
9767 (select-window cwin))))
9769 ;;; The mark ring for links jumps
9771 (defvar org-mark-ring nil
9772 "Mark ring for positions before jumps in Org-mode.")
9773 (defvar org-mark-ring-last-goto nil
9774 "Last position in the mark ring used to go back.")
9775 ;; Fill and close the ring
9776 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9777 (loop for i from 1 to org-mark-ring-length do
9778 (push (make-marker) org-mark-ring))
9779 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9780 org-mark-ring)
9782 (defun org-mark-ring-push (&optional pos buffer)
9783 "Put the current position or POS into the mark ring and rotate it."
9784 (interactive)
9785 (setq pos (or pos (point)))
9786 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9787 (move-marker (car org-mark-ring)
9788 (or pos (point))
9789 (or buffer (current-buffer)))
9790 (message "%s"
9791 (substitute-command-keys
9792 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9794 (defun org-mark-ring-goto (&optional n)
9795 "Jump to the previous position in the mark ring.
9796 With prefix arg N, jump back that many stored positions. When
9797 called several times in succession, walk through the entire ring.
9798 Org-mode commands jumping to a different position in the current file,
9799 or to another Org-mode file, automatically push the old position
9800 onto the ring."
9801 (interactive "p")
9802 (let (p m)
9803 (if (eq last-command this-command)
9804 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9805 (setq p org-mark-ring))
9806 (setq org-mark-ring-last-goto p)
9807 (setq m (car p))
9808 (switch-to-buffer (marker-buffer m))
9809 (goto-char m)
9810 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9812 (defun org-remove-angle-brackets (s)
9813 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9814 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9816 (defun org-add-angle-brackets (s)
9817 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9818 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9820 (defun org-remove-double-quotes (s)
9821 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9822 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9825 ;;; Following specific links
9827 (defun org-follow-timestamp-link ()
9828 (cond
9829 ((org-at-date-range-p t)
9830 (let ((org-agenda-start-on-weekday)
9831 (t1 (match-string 1))
9832 (t2 (match-string 2)))
9833 (setq t1 (time-to-days (org-time-string-to-time t1))
9834 t2 (time-to-days (org-time-string-to-time t2)))
9835 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9836 ((org-at-timestamp-p t)
9837 (org-agenda-list nil (time-to-days (org-time-string-to-time
9838 (substring (match-string 1) 0 10)))
9840 (t (error "This should not happen"))))
9843 ;;; Following file links
9844 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
9845 (declare-function mailcap-extension-to-mime "mailcap" (extn))
9846 (declare-function mailcap-mime-info
9847 "mailcap" (string &optional request no-decode))
9848 (defvar org-wait nil)
9849 (defun org-open-file (path &optional in-emacs line search)
9850 "Open the file at PATH.
9851 First, this expands any special file name abbreviations. Then the
9852 configuration variable `org-file-apps' is checked if it contains an
9853 entry for this file type, and if yes, the corresponding command is launched.
9855 If no application is found, Emacs simply visits the file.
9857 With optional prefix argument IN-EMACS, Emacs will visit the file.
9858 With a double \\[universal-argument] \\[universal-argument] \
9859 prefix arg, Org tries to avoid opening in Emacs
9860 and to use an external application to visit the file.
9862 Optional LINE specifies a line to go to, optional SEARCH a string
9863 to search for. If LINE or SEARCH is given, the file will be
9864 opened in Emacs, unless an entry from org-file-apps that makes
9865 use of groups in a regexp matches.
9866 If the file does not exist, an error is thrown."
9867 (let* ((file (if (equal path "")
9868 buffer-file-name
9869 (substitute-in-file-name (expand-file-name path))))
9870 (file-apps (append org-file-apps (org-default-apps)))
9871 (apps (org-remove-if
9872 'org-file-apps-entry-match-against-dlink-p file-apps))
9873 (apps-dlink (org-remove-if-not
9874 'org-file-apps-entry-match-against-dlink-p file-apps))
9875 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9876 (dirp (if remp nil (file-directory-p file)))
9877 (file (if (and dirp org-open-directory-means-index-dot-org)
9878 (concat (file-name-as-directory file) "index.org")
9879 file))
9880 (a-m-a-p (assq 'auto-mode apps))
9881 (dfile (downcase file))
9882 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9883 (link (cond ((and (eq line nil)
9884 (eq search nil))
9885 file)
9886 (line
9887 (concat file "::" (number-to-string line)))
9888 (search
9889 (concat file "::" search))))
9890 (dlink (downcase link))
9891 (old-buffer (current-buffer))
9892 (old-pos (point))
9893 (old-mode major-mode)
9894 ext cmd link-match-data)
9895 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9896 (setq ext (match-string 1 dfile))
9897 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9898 (setq ext (match-string 1 dfile))))
9899 (cond
9900 ((member in-emacs '((16) system))
9901 (setq cmd (cdr (assoc 'system apps))))
9902 (in-emacs (setq cmd 'emacs))
9904 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9905 (and dirp (cdr (assoc 'directory apps)))
9906 ; first, try matching against apps-dlink
9907 ; if we get a match here, store the match data for later
9908 (let ((match (assoc-default dlink apps-dlink
9909 'string-match)))
9910 (if match
9911 (progn (setq link-match-data (match-data))
9912 match)
9913 (progn (setq in-emacs (or in-emacs line search))
9914 nil))) ; if we have no match in apps-dlink,
9915 ; always open the file in emacs if line or search
9916 ; is given (for backwards compatibility)
9917 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9918 'string-match)
9919 (cdr (assoc ext apps))
9920 (cdr (assoc t apps))))))
9921 (when (eq cmd 'system)
9922 (setq cmd (cdr (assoc 'system apps))))
9923 (when (eq cmd 'default)
9924 (setq cmd (cdr (assoc t apps))))
9925 (when (eq cmd 'mailcap)
9926 (require 'mailcap)
9927 (mailcap-parse-mailcaps)
9928 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9929 (command (mailcap-mime-info mime-type)))
9930 (if (stringp command)
9931 (setq cmd command)
9932 (setq cmd 'emacs))))
9933 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9934 (not (file-exists-p file))
9935 (not org-open-non-existing-files))
9936 (error "No such file: %s" file))
9937 (cond
9938 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9939 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9940 (while (string-match "['\"]%s['\"]" cmd)
9941 (setq cmd (replace-match "%s" t t cmd)))
9942 (while (string-match "%s" cmd)
9943 (setq cmd (replace-match
9944 (save-match-data
9945 (shell-quote-argument
9946 (convert-standard-filename file)))
9947 t t cmd)))
9949 ;; Replace "%1", "%2" etc. in command with group matches from regex
9950 (save-match-data
9951 (let ((match-index 1)
9952 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9953 (set-match-data link-match-data)
9954 (while (<= match-index number-of-groups)
9955 (let ((regex (concat "%" (number-to-string match-index)))
9956 (replace-with (match-string match-index dlink)))
9957 (while (string-match regex cmd)
9958 (setq cmd (replace-match replace-with t t cmd))))
9959 (setq match-index (+ match-index 1)))))
9961 (save-window-excursion
9962 (start-process-shell-command cmd nil cmd)
9963 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9965 ((or (stringp cmd)
9966 (eq cmd 'emacs))
9967 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9968 (widen)
9969 (if line (org-goto-line line)
9970 (if search (org-link-search search))))
9971 ((consp cmd)
9972 (let ((file (convert-standard-filename file)))
9973 (save-match-data
9974 (set-match-data link-match-data)
9975 (eval cmd))))
9976 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9977 (and (org-mode-p) (eq old-mode 'org-mode)
9978 (or (not (equal old-buffer (current-buffer)))
9979 (not (equal old-pos (point))))
9980 (org-mark-ring-push old-pos old-buffer))))
9982 (defun org-file-apps-entry-match-against-dlink-p (entry)
9983 "This function returns non-nil if `entry' uses a regular
9984 expression which should be matched against the whole link by
9985 org-open-file.
9987 It assumes that is the case when the entry uses a regular
9988 expression which has at least one grouping construct and the
9989 action is either a lisp form or a command string containing
9990 '%1', i.e. using at least one subexpression match as a
9991 parameter."
9992 (let ((selector (car entry))
9993 (action (cdr entry)))
9994 (if (stringp selector)
9995 (and (> (regexp-opt-depth selector) 0)
9996 (or (and (stringp action)
9997 (string-match "%[0-9]" action))
9998 (consp action)))
9999 nil)))
10001 (defun org-default-apps ()
10002 "Return the default applications for this operating system."
10003 (cond
10004 ((eq system-type 'darwin)
10005 org-file-apps-defaults-macosx)
10006 ((eq system-type 'windows-nt)
10007 org-file-apps-defaults-windowsnt)
10008 (t org-file-apps-defaults-gnu)))
10010 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10011 "Convert extensions to regular expressions in the cars of LIST.
10012 Also, weed out any non-string entries, because the return value is used
10013 only for regexp matching.
10014 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10015 point to the symbol `emacs', indicating that the file should
10016 be opened in Emacs."
10017 (append
10018 (delq nil
10019 (mapcar (lambda (x)
10020 (if (not (stringp (car x)))
10022 (if (string-match "\\W" (car x))
10024 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10025 list))
10026 (if add-auto-mode
10027 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10029 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10030 (defun org-file-remote-p (file)
10031 "Test whether FILE specifies a location on a remote system.
10032 Return non-nil if the location is indeed remote.
10034 For example, the filename \"/user@host:/foo\" specifies a location
10035 on the system \"/user@host:\"."
10036 (cond ((fboundp 'file-remote-p)
10037 (file-remote-p file))
10038 ((fboundp 'tramp-handle-file-remote-p)
10039 (tramp-handle-file-remote-p file))
10040 ((and (boundp 'ange-ftp-name-format)
10041 (string-match (car ange-ftp-name-format) file))
10043 (t nil)))
10046 ;;;; Refiling
10048 (defun org-get-org-file ()
10049 "Read a filename, with default directory `org-directory'."
10050 (let ((default (or org-default-notes-file remember-data-file)))
10051 (read-file-name (format "File name [%s]: " default)
10052 (file-name-as-directory org-directory)
10053 default)))
10055 (defun org-notes-order-reversed-p ()
10056 "Check if the current file should receive notes in reversed order."
10057 (cond
10058 ((not org-reverse-note-order) nil)
10059 ((eq t org-reverse-note-order) t)
10060 ((not (listp org-reverse-note-order)) nil)
10061 (t (catch 'exit
10062 (let ((all org-reverse-note-order)
10063 entry)
10064 (while (setq entry (pop all))
10065 (if (string-match (car entry) buffer-file-name)
10066 (throw 'exit (cdr entry))))
10067 nil)))))
10069 (defvar org-refile-target-table nil
10070 "The list of refile targets, created by `org-refile'.")
10072 (defvar org-agenda-new-buffers nil
10073 "Buffers created to visit agenda files.")
10075 (defvar org-refile-cache nil
10076 "Cache for refile targets.")
10078 (defvar org-refile-markers nil
10079 "All the markers used for caching refile locations.")
10081 (defun org-refile-marker (pos)
10082 "Get a new refile marker, but only if caching is in use."
10083 (if (not org-refile-use-cache)
10085 (let ((m (make-marker)))
10086 (move-marker m pos)
10087 (push m org-refile-markers)
10088 m)))
10090 (defun org-refile-cache-clear ()
10091 "Clear the refile cache and disable all the markers."
10092 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10093 (setq org-refile-markers nil)
10094 (setq org-refile-cache nil)
10095 (message "Refile cache has been cleared"))
10097 (defun org-refile-cache-check-set (set)
10098 "Check if all the markers in the cache still have live buffers."
10099 (let (marker)
10100 (catch 'exit
10101 (while (and set (setq marker (nth 3 (pop set))))
10102 ;; if org-refile-use-outline-path is 'file, marker may be nil
10103 (when (and marker (null (marker-buffer marker)))
10104 (message "not found") (sit-for 3)
10105 (throw 'exit nil)))
10106 t)))
10108 (defun org-refile-cache-put (set &rest identifiers)
10109 "Push the refile targets SET into the cache, under IDENTIFIERS."
10110 (let* ((key (sha1 (prin1-to-string identifiers)))
10111 (entry (assoc key org-refile-cache)))
10112 (if entry
10113 (setcdr entry set)
10114 (push (cons key set) org-refile-cache))))
10116 (defun org-refile-cache-get (&rest identifiers)
10117 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10118 (cond
10119 ((not org-refile-cache) nil)
10120 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10122 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10123 org-refile-cache))))
10124 (and set (org-refile-cache-check-set set) set)))))
10126 (defun org-refile-get-targets (&optional default-buffer)
10127 "Produce a table with refile targets."
10128 (let ((case-fold-search nil)
10129 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10130 (entries (or org-refile-targets '((nil . (:level . 1)))))
10131 targets tgs txt re files f desc descre fast-path-p level pos0)
10132 (message "Getting targets...")
10133 (with-current-buffer (or default-buffer (current-buffer))
10134 (while (setq entry (pop entries))
10135 (setq files (car entry) desc (cdr entry))
10136 (setq fast-path-p nil)
10137 (cond
10138 ((null files) (setq files (list (current-buffer))))
10139 ((eq files 'org-agenda-files)
10140 (setq files (org-agenda-files 'unrestricted)))
10141 ((and (symbolp files) (fboundp files))
10142 (setq files (funcall files)))
10143 ((and (symbolp files) (boundp files))
10144 (setq files (symbol-value files))))
10145 (if (stringp files) (setq files (list files)))
10146 (cond
10147 ((eq (car desc) :tag)
10148 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10149 ((eq (car desc) :todo)
10150 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10151 ((eq (car desc) :regexp)
10152 (setq descre (cdr desc)))
10153 ((eq (car desc) :level)
10154 (setq descre (concat "^\\*\\{" (number-to-string
10155 (if org-odd-levels-only
10156 (1- (* 2 (cdr desc)))
10157 (cdr desc)))
10158 "\\}[ \t]")))
10159 ((eq (car desc) :maxlevel)
10160 (setq fast-path-p t)
10161 (setq descre (concat "^\\*\\{1," (number-to-string
10162 (if org-odd-levels-only
10163 (1- (* 2 (cdr desc)))
10164 (cdr desc)))
10165 "\\}[ \t]")))
10166 (t (error "Bad refiling target description %s" desc)))
10167 (while (setq f (pop files))
10168 (with-current-buffer
10169 (if (bufferp f) f (org-get-agenda-file-buffer f))
10171 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10172 (progn
10173 (if (bufferp f) (setq f (buffer-file-name
10174 (buffer-base-buffer f))))
10175 (setq f (and f (expand-file-name f)))
10176 (if (eq org-refile-use-outline-path 'file)
10177 (push (list (file-name-nondirectory f) f nil nil) tgs))
10178 (save-excursion
10179 (save-restriction
10180 (widen)
10181 (goto-char (point-min))
10182 (while (re-search-forward descre nil t)
10183 (goto-char (setq pos0 (point-at-bol)))
10184 (catch 'next
10185 (when org-refile-target-verify-function
10186 (save-match-data
10187 (or (funcall org-refile-target-verify-function)
10188 (throw 'next t))))
10189 (when (looking-at org-complex-heading-regexp)
10190 (setq level (org-reduced-level
10191 (- (match-end 1) (match-beginning 1)))
10192 txt (org-link-display-format (match-string 4))
10193 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10194 re (format org-complex-heading-regexp-format
10195 (regexp-quote (match-string 4))))
10196 (when org-refile-use-outline-path
10197 (setq txt (mapconcat
10198 'org-protect-slash
10199 (append
10200 (if (eq org-refile-use-outline-path
10201 'file)
10202 (list (file-name-nondirectory
10203 (buffer-file-name
10204 (buffer-base-buffer))))
10205 (if (eq org-refile-use-outline-path
10206 'full-file-path)
10207 (list (buffer-file-name
10208 (buffer-base-buffer)))))
10209 (org-get-outline-path fast-path-p
10210 level txt)
10211 (list txt))
10212 "/")))
10213 (push (list txt f re (org-refile-marker (point)))
10214 tgs)))
10215 (when (= (point) pos0)
10216 ;; verification function has not moved point
10217 (goto-char (point-at-eol))))))))
10218 (when org-refile-use-cache
10219 (org-refile-cache-put tgs (buffer-file-name) descre))
10220 (setq targets (append tgs targets))
10221 ))))
10222 (message "Getting targets...done")
10223 (nreverse targets)))
10225 (defun org-protect-slash (s)
10226 (while (string-match "/" s)
10227 (setq s (replace-match "\\" t t s)))
10230 (defvar org-olpa (make-vector 20 nil))
10232 (defun org-get-outline-path (&optional fastp level heading)
10233 "Return the outline path to the current entry, as a list.
10235 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10236 routine which makes outline path derivations for an entire file,
10237 avoiding backtracing. Refile target collection makes use of that."
10238 (if fastp
10239 (progn
10240 (if (> level 19)
10241 (error "Outline path failure, more than 19 levels"))
10242 (loop for i from level upto 19 do
10243 (aset org-olpa i nil))
10244 (prog1
10245 (delq nil (append org-olpa nil))
10246 (aset org-olpa level heading)))
10247 (let (rtn case-fold-search)
10248 (save-excursion
10249 (save-restriction
10250 (widen)
10251 (while (org-up-heading-safe)
10252 (when (looking-at org-complex-heading-regexp)
10253 (push (org-match-string-no-properties 4) rtn)))
10254 rtn)))))
10256 (defun org-format-outline-path (path &optional width prefix)
10257 "Format the outline path PATH for display.
10258 Width is the maximum number of characters that is available.
10259 Prefix is a prefix to be included in the returned string,
10260 such as the file name."
10261 (setq width (or width 79))
10262 (if prefix (setq width (- width (length prefix))))
10263 (if (not path)
10264 (or prefix "")
10265 (let* ((nsteps (length path))
10266 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10267 (maxwidth (if (<= total-width width)
10268 10000 ;; everything fits
10269 ;; we need to shorten the level headings
10270 (/ (- width nsteps) nsteps)))
10271 (org-odd-levels-only nil)
10272 (n 0)
10273 (total (1+ (length prefix))))
10274 (setq maxwidth (max maxwidth 10))
10275 (concat prefix
10276 (mapconcat
10277 (lambda (h)
10278 (setq n (1+ n))
10279 (if (and (= n nsteps) (< maxwidth 10000))
10280 (setq maxwidth (- total-width total)))
10281 (if (< (length h) maxwidth)
10282 (progn (setq total (+ total (length h) 1)) h)
10283 (setq h (substring h 0 (- maxwidth 2))
10284 total (+ total maxwidth 1))
10285 (if (string-match "[ \t]+\\'" h)
10286 (setq h (substring h 0 (match-beginning 0))))
10287 (setq h (concat h "..")))
10288 (org-add-props h nil 'face
10289 (nth (% (1- n) org-n-level-faces)
10290 org-level-faces))
10292 path "/")))))
10294 (defun org-display-outline-path (&optional file current)
10295 "Display the current outline path in the echo area."
10296 (interactive "P")
10297 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10298 (case-fold-search nil)
10299 (path (and (org-mode-p) (org-get-outline-path))))
10300 (if current (setq path (append path
10301 (save-excursion
10302 (org-back-to-heading t)
10303 (if (looking-at org-complex-heading-regexp)
10304 (list (match-string 4)))))))
10305 (message "%s"
10306 (org-format-outline-path
10307 path
10308 (1- (frame-width))
10309 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10311 (defvar org-refile-history nil
10312 "History for refiling operations.")
10314 (defvar org-after-refile-insert-hook nil
10315 "Hook run after `org-refile' has inserted its stuff at the new location.
10316 Note that this is still *before* the stuff will be removed from
10317 the *old* location.")
10319 (defvar org-capture-last-stored-marker)
10320 (defun org-refile (&optional goto default-buffer rfloc)
10321 "Move the entry at point to another heading.
10322 The list of target headings is compiled using the information in
10323 `org-refile-targets', which see. This list is created before each use
10324 and will therefore always be up-to-date.
10326 At the target location, the entry is filed as a subitem of the target heading.
10327 Depending on `org-reverse-note-order', the new subitem will either be the
10328 first or the last subitem.
10330 If there is an active region, all entries in that region will be moved.
10331 However, the region must fulfill the requirement that the first heading
10332 is the first one sets the top-level of the moved text - at most siblings
10333 below it are allowed.
10335 With prefix arg GOTO, the command will only visit the target location,
10336 not actually move anything.
10337 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10338 go to the location where the last refiling
10339 operation has put the subtree.
10340 With a prefix argument of `2', refile to the running clock.
10342 RFLOC can be a refile location obtained in a different way.
10344 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10346 If you are using target caching (see `org-refile-use-cache'),
10347 You have to clear the target cache in order to find new targets.
10348 This can be done with a 0 prefix: `C-0 C-c C-w'"
10349 (interactive "P")
10350 (if (member goto '(0 (64)))
10351 (org-refile-cache-clear)
10352 (let* ((cbuf (current-buffer))
10353 (regionp (org-region-active-p))
10354 (region-start (and regionp (region-beginning)))
10355 (region-end (and regionp (region-end)))
10356 (region-length (and regionp (- region-end region-start)))
10357 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10358 pos it nbuf file re level reversed)
10359 (setq last-command nil)
10360 (when regionp
10361 (goto-char region-start)
10362 (or (bolp) (goto-char (point-at-bol)))
10363 (setq region-start (point))
10364 (unless (org-kill-is-subtree-p
10365 (buffer-substring region-start region-end))
10366 (error "The region is not a (sequence of) subtree(s)")))
10367 (if (equal goto '(16))
10368 (org-refile-goto-last-stored)
10369 (when (or
10370 (and (equal goto 2)
10371 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10372 (prog1
10373 (setq it (list (or org-clock-heading "running clock")
10374 (buffer-file-name
10375 (marker-buffer org-clock-hd-marker))
10377 (marker-position org-clock-hd-marker)))
10378 (setq goto nil)))
10379 (setq it (or rfloc
10380 (save-excursion
10381 (org-refile-get-location
10382 (if goto "Goto" "Refile to") default-buffer
10383 org-refile-allow-creating-parent-nodes)))))
10384 (setq file (nth 1 it)
10385 re (nth 2 it)
10386 pos (nth 3 it))
10387 (if (and (not goto)
10389 (equal (buffer-file-name) file)
10390 (if regionp
10391 (and (>= pos region-start)
10392 (<= pos region-end))
10393 (and (>= pos (point))
10394 (< pos (save-excursion
10395 (org-end-of-subtree t t))))))
10396 (error "Cannot refile to position inside the tree or region"))
10398 (setq nbuf (or (find-buffer-visiting file)
10399 (find-file-noselect file)))
10400 (if goto
10401 (progn
10402 (switch-to-buffer nbuf)
10403 (goto-char pos)
10404 (org-show-context 'org-goto))
10405 (if regionp
10406 (progn
10407 (org-kill-new (buffer-substring region-start region-end))
10408 (org-save-markers-in-region region-start region-end))
10409 (org-copy-subtree 1 nil t))
10410 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10411 (find-file-noselect file)))
10412 (setq reversed (org-notes-order-reversed-p))
10413 (save-excursion
10414 (save-restriction
10415 (widen)
10416 (if pos
10417 (progn
10418 (goto-char pos)
10419 (looking-at outline-regexp)
10420 (setq level (org-get-valid-level (funcall outline-level) 1))
10421 (goto-char
10422 (if reversed
10423 (or (outline-next-heading) (point-max))
10424 (or (save-excursion (org-get-next-sibling))
10425 (org-end-of-subtree t t)
10426 (point-max)))))
10427 (setq level 1)
10428 (if (not reversed)
10429 (goto-char (point-max))
10430 (goto-char (point-min))
10431 (or (outline-next-heading) (goto-char (point-max)))))
10432 (if (not (bolp)) (newline))
10433 (org-paste-subtree level)
10434 (when org-log-refile
10435 (org-add-log-setup 'refile nil nil 'findpos
10436 org-log-refile)
10437 (unless (eq org-log-refile 'note)
10438 (save-excursion (org-add-log-note))))
10439 (and org-auto-align-tags (org-set-tags nil t))
10440 (bookmark-set "org-refile-last-stored")
10441 ;; If we are refiling for capture, make sure that the
10442 ;; last-capture pointers point here
10443 (when (org-bound-and-true-p org-refile-for-capture)
10444 (bookmark-set "org-capture-last-stored-marker")
10445 (move-marker org-capture-last-stored-marker (point)))
10446 (if (fboundp 'deactivate-mark) (deactivate-mark))
10447 (run-hooks 'org-after-refile-insert-hook))))
10448 (if regionp
10449 (delete-region (point) (+ (point) region-length))
10450 (org-cut-subtree))
10451 (when (featurep 'org-inlinetask)
10452 (org-inlinetask-remove-END-maybe))
10453 (setq org-markers-to-move nil)
10454 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10456 (defun org-refile-goto-last-stored ()
10457 "Go to the location where the last refile was stored."
10458 (interactive)
10459 (bookmark-jump "org-refile-last-stored")
10460 (message "This is the location of the last refile"))
10462 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
10463 "Prompt the user for a refile location, using PROMPT.
10464 PROMPT should not be suffixed with a colon and a space, because
10465 this function appends the default value from
10466 `org-refile-history' automatically, if that is not empty."
10467 (let ((org-refile-targets org-refile-targets)
10468 (org-refile-use-outline-path org-refile-use-outline-path))
10469 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
10470 (unless org-refile-target-table
10471 (error "No refile targets"))
10472 (let* ((prompt (concat prompt
10473 (and (car org-refile-history)
10474 (concat " (default " (car org-refile-history) ")"))
10475 ": "))
10476 (cbuf (current-buffer))
10477 (partial-completion-mode nil)
10478 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10479 (cfunc (if (and org-refile-use-outline-path
10480 org-outline-path-complete-in-steps)
10481 'org-olpath-completing-read
10482 'org-icompleting-read))
10483 (extra (if org-refile-use-outline-path "/" ""))
10484 (filename (and cfn (expand-file-name cfn)))
10485 (tbl (mapcar
10486 (lambda (x)
10487 (if (and (not (member org-refile-use-outline-path
10488 '(file full-file-path)))
10489 (not (equal filename (nth 1 x))))
10490 (cons (concat (car x) extra " ("
10491 (file-name-nondirectory (nth 1 x)) ")")
10492 (cdr x))
10493 (cons (concat (car x) extra) (cdr x))))
10494 org-refile-target-table))
10495 (completion-ignore-case t)
10496 pa answ parent-target child parent old-hist)
10497 (setq old-hist org-refile-history)
10498 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10499 nil 'org-refile-history (car org-refile-history)))
10500 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10501 (org-refile-check-position pa)
10502 (if pa
10503 (progn
10504 (when (or (not org-refile-history)
10505 (not (eq old-hist org-refile-history))
10506 (not (equal (car pa) (car org-refile-history))))
10507 (setq org-refile-history
10508 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10509 org-refile-history
10510 (cdr org-refile-history))))
10511 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10512 (pop org-refile-history)))
10514 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10515 (progn
10516 (setq parent (match-string 1 answ)
10517 child (match-string 2 answ))
10518 (setq parent-target (or (assoc parent tbl)
10519 (assoc (concat parent "/") tbl)))
10520 (when (and parent-target
10521 (or (eq new-nodes t)
10522 (and (eq new-nodes 'confirm)
10523 (y-or-n-p (format "Create new node \"%s\"? "
10524 child)))))
10525 (org-refile-new-child parent-target child)))
10526 (error "Invalid target location")))))
10528 (defun org-refile-check-position (refile-pointer)
10529 "Check if the refile pointer matches the readline to which it points."
10530 (let* ((file (nth 1 refile-pointer))
10531 (re (nth 2 refile-pointer))
10532 (pos (nth 3 refile-pointer))
10533 buffer)
10534 (when (org-string-nw-p re)
10535 (setq buffer (if (markerp pos)
10536 (marker-buffer pos)
10537 (or (find-buffer-visiting file)
10538 (find-file-noselect file))))
10539 (with-current-buffer buffer
10540 (save-excursion
10541 (save-restriction
10542 (widen)
10543 (goto-char pos)
10544 (beginning-of-line 1)
10545 (unless (org-looking-at-p re)
10546 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10548 (defun org-refile-new-child (parent-target child)
10549 "Use refile target PARENT-TARGET to add new CHILD below it."
10550 (unless parent-target
10551 (error "Cannot find parent for new node"))
10552 (let ((file (nth 1 parent-target))
10553 (pos (nth 3 parent-target))
10554 level)
10555 (with-current-buffer (or (find-buffer-visiting file)
10556 (find-file-noselect file))
10557 (save-excursion
10558 (save-restriction
10559 (widen)
10560 (if pos
10561 (goto-char pos)
10562 (goto-char (point-max))
10563 (if (not (bolp)) (newline)))
10564 (when (looking-at outline-regexp)
10565 (setq level (funcall outline-level))
10566 (org-end-of-subtree t t))
10567 (org-back-over-empty-lines)
10568 (insert "\n" (make-string
10569 (if pos (org-get-valid-level level 1) 1) ?*)
10570 " " child "\n")
10571 (beginning-of-line 0)
10572 (list (concat (car parent-target) "/" child) file "" (point)))))))
10574 (defun org-olpath-completing-read (prompt collection &rest args)
10575 "Read an outline path like a file name."
10576 (let ((thetable collection)
10577 (org-completion-use-ido nil) ; does not work with ido.
10578 (org-completion-use-iswitchb nil)) ; or iswitchb
10579 (apply
10580 'org-icompleting-read prompt
10581 (lambda (string predicate &optional flag)
10582 (let (rtn r f (l (length string)))
10583 (cond
10584 ((eq flag nil)
10585 ;; try completion
10586 (try-completion string thetable))
10587 ((eq flag t)
10588 ;; all-completions
10589 (setq rtn (all-completions string thetable predicate))
10590 (mapcar
10591 (lambda (x)
10592 (setq r (substring x l))
10593 (if (string-match " ([^)]*)$" x)
10594 (setq f (match-string 0 x))
10595 (setq f ""))
10596 (if (string-match "/" r)
10597 (concat string (substring r 0 (match-end 0)) f)
10599 rtn))
10600 ((eq flag 'lambda)
10601 ;; exact match?
10602 (assoc string thetable)))
10604 args)))
10606 ;;;; Dynamic blocks
10608 (defun org-find-dblock (name)
10609 "Find the first dynamic block with name NAME in the buffer.
10610 If not found, stay at current position and return nil."
10611 (let (pos)
10612 (save-excursion
10613 (goto-char (point-min))
10614 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10615 nil t)
10616 (match-beginning 0))))
10617 (if pos (goto-char pos))
10618 pos))
10620 (defconst org-dblock-start-re
10621 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10622 "Matches the start line of a dynamic block, with parameters.")
10624 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10625 "Matches the end of a dynamic block.")
10627 (defun org-create-dblock (plist)
10628 "Create a dynamic block section, with parameters taken from PLIST.
10629 PLIST must contain a :name entry which is used as name of the block."
10630 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10631 (end-of-line 1)
10632 (newline))
10633 (let ((col (current-column))
10634 (name (plist-get plist :name)))
10635 (insert "#+BEGIN: " name)
10636 (while plist
10637 (if (eq (car plist) :name)
10638 (setq plist (cddr plist))
10639 (insert " " (prin1-to-string (pop plist)))))
10640 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10641 (beginning-of-line -2)))
10643 (defun org-prepare-dblock ()
10644 "Prepare dynamic block for refresh.
10645 This empties the block, puts the cursor at the insert position and returns
10646 the property list including an extra property :name with the block name."
10647 (unless (looking-at org-dblock-start-re)
10648 (error "Not at a dynamic block"))
10649 (let* ((begdel (1+ (match-end 0)))
10650 (name (org-no-properties (match-string 1)))
10651 (params (append (list :name name)
10652 (read (concat "(" (match-string 3) ")")))))
10653 (save-excursion
10654 (beginning-of-line 1)
10655 (skip-chars-forward " \t")
10656 (setq params (plist-put params :indentation-column (current-column))))
10657 (unless (re-search-forward org-dblock-end-re nil t)
10658 (error "Dynamic block not terminated"))
10659 (setq params
10660 (append params
10661 (list :content (buffer-substring
10662 begdel (match-beginning 0)))))
10663 (delete-region begdel (match-beginning 0))
10664 (goto-char begdel)
10665 (open-line 1)
10666 params))
10668 (defun org-map-dblocks (&optional command)
10669 "Apply COMMAND to all dynamic blocks in the current buffer.
10670 If COMMAND is not given, use `org-update-dblock'."
10671 (let ((cmd (or command 'org-update-dblock)))
10672 (save-excursion
10673 (goto-char (point-min))
10674 (while (re-search-forward org-dblock-start-re nil t)
10675 (goto-char (match-beginning 0))
10676 (save-excursion
10677 (condition-case nil
10678 (funcall cmd)
10679 (error (message "Error during update of dynamic block"))))
10680 (unless (re-search-forward org-dblock-end-re nil t)
10681 (error "Dynamic block not terminated"))))))
10683 (defun org-dblock-update (&optional arg)
10684 "User command for updating dynamic blocks.
10685 Update the dynamic block at point. With prefix ARG, update all dynamic
10686 blocks in the buffer."
10687 (interactive "P")
10688 (if arg
10689 (org-update-all-dblocks)
10690 (or (looking-at org-dblock-start-re)
10691 (org-beginning-of-dblock))
10692 (org-update-dblock)))
10694 (defun org-update-dblock ()
10695 "Update the dynamic block at point.
10696 This means to empty the block, parse for parameters and then call
10697 the correct writing function."
10698 (interactive)
10699 (save-window-excursion
10700 (let* ((pos (point))
10701 (line (org-current-line))
10702 (params (org-prepare-dblock))
10703 (name (plist-get params :name))
10704 (indent (plist-get params :indentation-column))
10705 (cmd (intern (concat "org-dblock-write:" name))))
10706 (message "Updating dynamic block `%s' at line %d..." name line)
10707 (funcall cmd params)
10708 (message "Updating dynamic block `%s' at line %d...done" name line)
10709 (goto-char pos)
10710 (when (and indent (> indent 0))
10711 (setq indent (make-string indent ?\ ))
10712 (save-excursion
10713 (org-beginning-of-dblock)
10714 (forward-line 1)
10715 (while (not (looking-at org-dblock-end-re))
10716 (insert indent)
10717 (beginning-of-line 2))
10718 (when (looking-at org-dblock-end-re)
10719 (and (looking-at "[ \t]+")
10720 (replace-match ""))
10721 (insert indent)))))))
10723 (defun org-beginning-of-dblock ()
10724 "Find the beginning of the dynamic block at point.
10725 Error if there is no such block at point."
10726 (let ((pos (point))
10727 beg)
10728 (end-of-line 1)
10729 (if (and (re-search-backward org-dblock-start-re nil t)
10730 (setq beg (match-beginning 0))
10731 (re-search-forward org-dblock-end-re nil t)
10732 (> (match-end 0) pos))
10733 (goto-char beg)
10734 (goto-char pos)
10735 (error "Not in a dynamic block"))))
10737 (defun org-update-all-dblocks ()
10738 "Update all dynamic blocks in the buffer.
10739 This function can be used in a hook."
10740 (interactive)
10741 (when (org-mode-p)
10742 (org-map-dblocks 'org-update-dblock)))
10745 ;;;; Completion
10747 (defconst org-additional-option-like-keywords
10748 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10749 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
10750 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10751 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
10752 "BEGIN:" "END:"
10753 "ORGTBL" "TBLFM:" "TBLNAME:"
10754 "BEGIN_EXAMPLE" "END_EXAMPLE"
10755 "BEGIN_QUOTE" "END_QUOTE"
10756 "BEGIN_VERSE" "END_VERSE"
10757 "BEGIN_CENTER" "END_CENTER"
10758 "BEGIN_SRC" "END_SRC"
10759 "BEGIN_RESULT" "END_RESULT"
10760 "SOURCE:" "SRCNAME:" "FUNCTION:"
10761 "RESULTS:" "DATA:"
10762 "HEADER:" "HEADERS:"
10763 "BABEL:"
10764 "CATEGORY:" "COLUMNS:" "PROPERTY:"
10765 "CAPTION:" "LABEL:"
10766 "SETUPFILE:"
10767 "INCLUDE:"
10768 "BIND:"
10769 "MACRO:"))
10771 (defcustom org-structure-template-alist
10773 ("s" "#+begin_src ?\n\n#+end_src"
10774 "<src lang=\"?\">\n\n</src>")
10775 ("e" "#+begin_example\n?\n#+end_example"
10776 "<example>\n?\n</example>")
10777 ("q" "#+begin_quote\n?\n#+end_quote"
10778 "<quote>\n?\n</quote>")
10779 ("v" "#+begin_verse\n?\n#+end_verse"
10780 "<verse>\n?\n/verse>")
10781 ("c" "#+begin_center\n?\n#+end_center"
10782 "<center>\n?\n/center>")
10783 ("l" "#+begin_latex\n?\n#+end_latex"
10784 "<literal style=\"latex\">\n?\n</literal>")
10785 ("L" "#+latex: "
10786 "<literal style=\"latex\">?</literal>")
10787 ("h" "#+begin_html\n?\n#+end_html"
10788 "<literal style=\"html\">\n?\n</literal>")
10789 ("H" "#+html: "
10790 "<literal style=\"html\">?</literal>")
10791 ("a" "#+begin_ascii\n?\n#+end_ascii")
10792 ("A" "#+ascii: ")
10793 ("i" "#+index: ?"
10794 "#+index: ?")
10795 ("I" "#+include %file ?"
10796 "<include file=%file markup=\"?\">")
10798 "Structure completion elements.
10799 This is a list of abbreviation keys and values. The value gets inserted
10800 if you type `<' followed by the key and then press the completion key,
10801 usually `M-TAB'. %file will be replaced by a file name after prompting
10802 for the file using completion. The cursor will be placed at the position
10803 of the `?` in the template.
10804 There are two templates for each key, the first uses the original Org syntax,
10805 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10806 the default when the /org-mtags.el/ module has been loaded. See also the
10807 variable `org-mtags-prefer-muse-templates'.
10808 This is an experimental feature, it is undecided if it is going to stay in."
10809 :group 'org-completion
10810 :type '(repeat
10811 (string :tag "Key")
10812 (string :tag "Template")
10813 (string :tag "Muse Template")))
10815 (defun org-try-structure-completion ()
10816 "Try to complete a structure template before point.
10817 This looks for strings like \"<e\" on an otherwise empty line and
10818 expands them."
10819 (let ((l (buffer-substring (point-at-bol) (point)))
10821 (when (and (looking-at "[ \t]*$")
10822 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
10823 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10824 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10825 (match-beginning 1)) a)
10826 t)))
10828 (defun org-complete-expand-structure-template (start cell)
10829 "Expand a structure template."
10830 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10831 (rpl (nth (if musep 2 1) cell))
10832 (ind ""))
10833 (delete-region start (point))
10834 (when (string-match "\\`#\\+" rpl)
10835 (cond
10836 ((bolp))
10837 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10838 (setq ind (buffer-substring (point-at-bol) (point))))
10839 (t (newline))))
10840 (setq start (point))
10841 (if (string-match "%file" rpl)
10842 (setq rpl (replace-match
10843 (concat
10844 "\""
10845 (save-match-data
10846 (abbreviate-file-name (read-file-name "Include file: ")))
10847 "\"")
10848 t t rpl)))
10849 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10850 (concat "\n" ind)))
10851 (insert rpl)
10852 (if (re-search-backward "\\?" start t) (delete-char 1))))
10854 ;;;; TODO, DEADLINE, Comments
10856 (defun org-toggle-comment ()
10857 "Change the COMMENT state of an entry."
10858 (interactive)
10859 (save-excursion
10860 (org-back-to-heading)
10861 (let (case-fold-search)
10862 (if (looking-at (concat outline-regexp
10863 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10864 (replace-match "" t t nil 1)
10865 (if (looking-at outline-regexp)
10866 (progn
10867 (goto-char (match-end 0))
10868 (insert org-comment-string " ")))))))
10870 (defvar org-last-todo-state-is-todo nil
10871 "This is non-nil when the last TODO state change led to a TODO state.
10872 If the last change removed the TODO tag or switched to DONE, then
10873 this is nil.")
10875 (defvar org-setting-tags nil) ; dynamically skipped
10877 (defvar org-todo-setup-filter-hook nil
10878 "Hook for functions that pre-filter todo specs.
10879 Each function takes a todo spec and returns either nil or the spec
10880 transformed into canonical form." )
10882 (defvar org-todo-get-default-hook nil
10883 "Hook for functions that get a default item for todo.
10884 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10885 nil or a string to be used for the todo mark." )
10887 (defvar org-agenda-headline-snapshot-before-repeat)
10889 (defun org-todo (&optional arg)
10890 "Change the TODO state of an item.
10891 The state of an item is given by a keyword at the start of the heading,
10892 like
10893 *** TODO Write paper
10894 *** DONE Call mom
10896 The different keywords are specified in the variable `org-todo-keywords'.
10897 By default the available states are \"TODO\" and \"DONE\".
10898 So for this example: when the item starts with TODO, it is changed to DONE.
10899 When it starts with DONE, the DONE is removed. And when neither TODO nor
10900 DONE are present, add TODO at the beginning of the heading.
10902 With \\[universal-argument] prefix arg, use completion to determine the new \
10903 state.
10904 With numeric prefix arg, switch to that state.
10905 With a double \\[universal-argument] prefix, switch to the next set of TODO \
10906 keywords (nextset).
10907 With a triple \\[universal-argument] prefix, circumvent any state blocking.
10909 For calling through lisp, arg is also interpreted in the following way:
10910 'none -> empty state
10911 \"\"(empty string) -> switch to empty state
10912 'done -> switch to DONE
10913 'nextset -> switch to the next set of keywords
10914 'previousset -> switch to the previous set of keywords
10915 \"WAITING\" -> switch to the specified keyword, but only if it
10916 really is a member of `org-todo-keywords'."
10917 (interactive "P")
10918 (if (equal arg '(16)) (setq arg 'nextset))
10919 (let ((org-blocker-hook org-blocker-hook)
10920 (case-fold-search nil))
10921 (when (equal arg '(64))
10922 (setq arg nil org-blocker-hook nil))
10923 (when (and org-blocker-hook
10924 (or org-inhibit-blocking
10925 (org-entry-get nil "NOBLOCKING")))
10926 (setq org-blocker-hook nil))
10927 (save-excursion
10928 (catch 'exit
10929 (org-back-to-heading t)
10930 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10931 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10932 (looking-at " *"))
10933 (let* ((match-data (match-data))
10934 (startpos (point-at-bol))
10935 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
10936 (org-log-done org-log-done)
10937 (org-log-repeat org-log-repeat)
10938 (org-todo-log-states org-todo-log-states)
10939 (this (match-string 1))
10940 (hl-pos (match-beginning 0))
10941 (head (org-get-todo-sequence-head this))
10942 (ass (assoc head org-todo-kwd-alist))
10943 (interpret (nth 1 ass))
10944 (done-word (nth 3 ass))
10945 (final-done-word (nth 4 ass))
10946 (last-state (or this ""))
10947 (completion-ignore-case t)
10948 (member (member this org-todo-keywords-1))
10949 (tail (cdr member))
10950 (state (cond
10951 ((and org-todo-key-trigger
10952 (or (and (equal arg '(4))
10953 (eq org-use-fast-todo-selection 'prefix))
10954 (and (not arg) org-use-fast-todo-selection
10955 (not (eq org-use-fast-todo-selection
10956 'prefix)))))
10957 ;; Use fast selection
10958 (org-fast-todo-selection))
10959 ((and (equal arg '(4))
10960 (or (not org-use-fast-todo-selection)
10961 (not org-todo-key-trigger)))
10962 ;; Read a state with completion
10963 (org-icompleting-read
10964 "State: " (mapcar (lambda(x) (list x))
10965 org-todo-keywords-1)
10966 nil t))
10967 ((eq arg 'right)
10968 (if this
10969 (if tail (car tail) nil)
10970 (car org-todo-keywords-1)))
10971 ((eq arg 'left)
10972 (if (equal member org-todo-keywords-1)
10974 (if this
10975 (nth (- (length org-todo-keywords-1)
10976 (length tail) 2)
10977 org-todo-keywords-1)
10978 (org-last org-todo-keywords-1))))
10979 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10980 (setq arg nil))) ; hack to fall back to cycling
10981 (arg
10982 ;; user or caller requests a specific state
10983 (cond
10984 ((equal arg "") nil)
10985 ((eq arg 'none) nil)
10986 ((eq arg 'done) (or done-word (car org-done-keywords)))
10987 ((eq arg 'nextset)
10988 (or (car (cdr (member head org-todo-heads)))
10989 (car org-todo-heads)))
10990 ((eq arg 'previousset)
10991 (let ((org-todo-heads (reverse org-todo-heads)))
10992 (or (car (cdr (member head org-todo-heads)))
10993 (car org-todo-heads))))
10994 ((car (member arg org-todo-keywords-1)))
10995 ((stringp arg)
10996 (error "State `%s' not valid in this file" arg))
10997 ((nth (1- (prefix-numeric-value arg))
10998 org-todo-keywords-1))))
10999 ((null member) (or head (car org-todo-keywords-1)))
11000 ((equal this final-done-word) nil) ;; -> make empty
11001 ((null tail) nil) ;; -> first entry
11002 ((memq interpret '(type priority))
11003 (if (eq this-command last-command)
11004 (car tail)
11005 (if (> (length tail) 0)
11006 (or done-word (car org-done-keywords))
11007 nil)))
11009 (car tail))))
11010 (state (or
11011 (run-hook-with-args-until-success
11012 'org-todo-get-default-hook state last-state)
11013 state))
11014 (next (if state (concat " " state " ") " "))
11015 (change-plist (list :type 'todo-state-change :from this :to state
11016 :position startpos))
11017 dolog now-done-p)
11018 (when org-blocker-hook
11019 (setq org-last-todo-state-is-todo
11020 (not (member this org-done-keywords)))
11021 (unless (save-excursion
11022 (save-match-data
11023 (org-with-wide-buffer
11024 (run-hook-with-args-until-failure
11025 'org-blocker-hook change-plist))))
11026 (if (org-called-interactively-p 'interactive)
11027 (error "TODO state change from %s to %s blocked" this state)
11028 ;; fail silently
11029 (message "TODO state change from %s to %s blocked" this state)
11030 (throw 'exit nil))))
11031 (store-match-data match-data)
11032 (replace-match next t t)
11033 (unless (pos-visible-in-window-p hl-pos)
11034 (message "TODO state changed to %s" (org-trim next)))
11035 (unless head
11036 (setq head (org-get-todo-sequence-head state)
11037 ass (assoc head org-todo-kwd-alist)
11038 interpret (nth 1 ass)
11039 done-word (nth 3 ass)
11040 final-done-word (nth 4 ass)))
11041 (when (memq arg '(nextset previousset))
11042 (message "Keyword-Set %d/%d: %s"
11043 (- (length org-todo-sets) -1
11044 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11045 (length org-todo-sets)
11046 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11047 (setq org-last-todo-state-is-todo
11048 (not (member state org-done-keywords)))
11049 (setq now-done-p (and (member state org-done-keywords)
11050 (not (member this org-done-keywords))))
11051 (and logging (org-local-logging logging))
11052 (when (and (or org-todo-log-states org-log-done)
11053 (not (eq org-inhibit-logging t))
11054 (not (memq arg '(nextset previousset))))
11055 ;; we need to look at recording a time and note
11056 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11057 (nth 2 (assoc this org-todo-log-states))))
11058 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11059 (setq dolog 'time))
11060 (when (and state
11061 (member state org-not-done-keywords)
11062 (not (member this org-not-done-keywords)))
11063 ;; This is now a todo state and was not one before
11064 ;; If there was a CLOSED time stamp, get rid of it.
11065 (org-add-planning-info nil nil 'closed))
11066 (when (and now-done-p org-log-done)
11067 ;; It is now done, and it was not done before
11068 (org-add-planning-info 'closed (org-current-time))
11069 (if (and (not dolog) (eq 'note org-log-done))
11070 (org-add-log-setup 'done state this 'findpos 'note)))
11071 (when (and state dolog)
11072 ;; This is a non-nil state, and we need to log it
11073 (org-add-log-setup 'state state this 'findpos dolog)))
11074 ;; Fixup tag positioning
11075 (org-todo-trigger-tag-changes state)
11076 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11077 (when org-provide-todo-statistics
11078 (org-update-parent-todo-statistics))
11079 (run-hooks 'org-after-todo-state-change-hook)
11080 (if (and arg (not (member state org-done-keywords)))
11081 (setq head (org-get-todo-sequence-head state)))
11082 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11083 ;; Do we need to trigger a repeat?
11084 (when now-done-p
11085 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11086 ;; This is for the agenda, take a snapshot of the headline.
11087 (save-match-data
11088 (setq org-agenda-headline-snapshot-before-repeat
11089 (org-get-heading))))
11090 (org-auto-repeat-maybe state))
11091 ;; Fixup cursor location if close to the keyword
11092 (if (and (outline-on-heading-p)
11093 (not (bolp))
11094 (save-excursion (beginning-of-line 1)
11095 (looking-at org-todo-line-regexp))
11096 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11097 (progn
11098 (goto-char (or (match-end 2) (match-end 1)))
11099 (and (looking-at " ") (just-one-space))))
11100 (when org-trigger-hook
11101 (save-excursion
11102 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11104 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11105 "Block turning an entry into a TODO, using the hierarchy.
11106 This checks whether the current task should be blocked from state
11107 changes. Such blocking occurs when:
11109 1. The task has children which are not all in a completed state.
11111 2. A task has a parent with the property :ORDERED:, and there
11112 are siblings prior to the current task with incomplete
11113 status.
11115 3. The parent of the task is blocked because it has siblings that should
11116 be done first, or is child of a block grandparent TODO entry."
11118 (if (not org-enforce-todo-dependencies)
11119 t ; if locally turned off don't block
11120 (catch 'dont-block
11121 ;; If this is not a todo state change, or if this entry is already DONE,
11122 ;; do not block
11123 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11124 (member (plist-get change-plist :from)
11125 (cons 'done org-done-keywords))
11126 (member (plist-get change-plist :to)
11127 (cons 'todo org-not-done-keywords))
11128 (not (plist-get change-plist :to)))
11129 (throw 'dont-block t))
11130 ;; If this task has children, and any are undone, it's blocked
11131 (save-excursion
11132 (org-back-to-heading t)
11133 (let ((this-level (funcall outline-level)))
11134 (outline-next-heading)
11135 (let ((child-level (funcall outline-level)))
11136 (while (and (not (eobp))
11137 (> child-level this-level))
11138 ;; this todo has children, check whether they are all
11139 ;; completed
11140 (if (and (not (org-entry-is-done-p))
11141 (org-entry-is-todo-p))
11142 (throw 'dont-block nil))
11143 (outline-next-heading)
11144 (setq child-level (funcall outline-level))))))
11145 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11146 ;; any previous siblings are undone, it's blocked
11147 (save-excursion
11148 (org-back-to-heading t)
11149 (let* ((pos (point))
11150 (parent-pos (and (org-up-heading-safe) (point))))
11151 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11152 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11153 (forward-line 1)
11154 (re-search-forward org-not-done-heading-regexp pos t))
11155 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11156 ;; Search further up the hierarchy, to see if an anchestor is blocked
11157 (while t
11158 (goto-char parent-pos)
11159 (if (not (looking-at org-not-done-heading-regexp))
11160 (throw 'dont-block t)) ; do not block, parent is not a TODO
11161 (setq pos (point))
11162 (setq parent-pos (and (org-up-heading-safe) (point)))
11163 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11164 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11165 (forward-line 1)
11166 (re-search-forward org-not-done-heading-regexp pos t))
11167 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11169 (defcustom org-track-ordered-property-with-tag nil
11170 "Should the ORDERED property also be shown as a tag?
11171 The ORDERED property decides if an entry should require subtasks to be
11172 completed in sequence. Since a property is not very visible, setting
11173 this option means that toggling the ORDERED property with the command
11174 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11175 not relevant for the behavior, but it makes things more visible.
11177 Note that toggling the tag with tags commands will not change the property
11178 and therefore not influence behavior!
11180 This can be t, meaning the tag ORDERED should be used, It can also be a
11181 string to select a different tag for this task."
11182 :group 'org-todo
11183 :type '(choice
11184 (const :tag "No tracking" nil)
11185 (const :tag "Track with ORDERED tag" t)
11186 (string :tag "Use other tag")))
11188 (defun org-toggle-ordered-property ()
11189 "Toggle the ORDERED property of the current entry.
11190 For better visibility, you can track the value of this property with a tag.
11191 See variable `org-track-ordered-property-with-tag'."
11192 (interactive)
11193 (let* ((t1 org-track-ordered-property-with-tag)
11194 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11195 (save-excursion
11196 (org-back-to-heading)
11197 (if (org-entry-get nil "ORDERED")
11198 (progn
11199 (org-delete-property "ORDERED")
11200 (and tag (org-toggle-tag tag 'off))
11201 (message "Subtasks can be completed in arbitrary order"))
11202 (org-entry-put nil "ORDERED" "t")
11203 (and tag (org-toggle-tag tag 'on))
11204 (message "Subtasks must be completed in sequence")))))
11206 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11207 (defun org-block-todo-from-checkboxes (change-plist)
11208 "Block turning an entry into a TODO, using checkboxes.
11209 This checks whether the current task should be blocked from state
11210 changes because there are unchecked boxes in this entry."
11211 (if (not org-enforce-todo-checkbox-dependencies)
11212 t ; if locally turned off don't block
11213 (catch 'dont-block
11214 ;; If this is not a todo state change, or if this entry is already DONE,
11215 ;; do not block
11216 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11217 (member (plist-get change-plist :from)
11218 (cons 'done org-done-keywords))
11219 (member (plist-get change-plist :to)
11220 (cons 'todo org-not-done-keywords))
11221 (not (plist-get change-plist :to)))
11222 (throw 'dont-block t))
11223 ;; If this task has checkboxes that are not checked, it's blocked
11224 (save-excursion
11225 (org-back-to-heading t)
11226 (let ((beg (point)) end)
11227 (outline-next-heading)
11228 (setq end (point))
11229 (goto-char beg)
11230 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
11231 end t)
11232 (progn
11233 (if (boundp 'org-blocked-by-checkboxes)
11234 (setq org-blocked-by-checkboxes t))
11235 (throw 'dont-block nil)))))
11236 t))) ; do not block
11238 (defun org-entry-blocked-p ()
11239 "Is the current entry blocked?"
11240 (if (org-entry-get nil "NOBLOCKING")
11241 nil ;; Never block this entry
11242 (not
11243 (run-hook-with-args-until-failure
11244 'org-blocker-hook
11245 (list :type 'todo-state-change
11246 :position (point)
11247 :from 'todo
11248 :to 'done)))))
11250 (defun org-update-statistics-cookies (all)
11251 "Update the statistics cookie, either from TODO or from checkboxes.
11252 This should be called with the cursor in a line with a statistics cookie."
11253 (interactive "P")
11254 (if all
11255 (progn
11256 (org-update-checkbox-count 'all)
11257 (org-map-entries 'org-update-parent-todo-statistics))
11258 (if (not (org-on-heading-p))
11259 (org-update-checkbox-count)
11260 (let ((pos (move-marker (make-marker) (point)))
11261 end l1 l2)
11262 (ignore-errors (org-back-to-heading t))
11263 (if (not (org-on-heading-p))
11264 (org-update-checkbox-count)
11265 (setq l1 (org-outline-level))
11266 (setq end (save-excursion
11267 (outline-next-heading)
11268 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11269 (point)))
11270 (if (and (save-excursion
11271 (re-search-forward
11272 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11273 (not (save-excursion (re-search-forward
11274 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11275 (org-update-checkbox-count)
11276 (if (and l2 (> l2 l1))
11277 (progn
11278 (goto-char end)
11279 (org-update-parent-todo-statistics))
11280 (goto-char pos)
11281 (beginning-of-line 1)
11282 (while (re-search-forward
11283 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11284 (point-at-eol) t)
11285 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11286 (goto-char pos)
11287 (move-marker pos nil)))))
11289 (defvar org-entry-property-inherited-from) ;; defined below
11290 (defun org-update-parent-todo-statistics ()
11291 "Update any statistics cookie in the parent of the current headline.
11292 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11293 the entire subtree and this will travel up the hierarchy and update
11294 statistics everywhere."
11295 (interactive)
11296 (let* ((lim 0) prop
11297 (recursive (or (not org-hierarchical-todo-statistics)
11298 (string-match
11299 "\\<recursive\\>"
11300 (or (setq prop (org-entry-get
11301 nil "COOKIE_DATA" 'inherit)) ""))))
11302 (lim (or (and prop (marker-position
11303 org-entry-property-inherited-from))
11304 lim))
11305 (first t)
11306 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11307 level ltoggle l1 new ndel
11308 (cnt-all 0) (cnt-done 0) is-percent kwd
11309 checkbox-beg ov ovs ove cookie-present)
11310 (catch 'exit
11311 (save-excursion
11312 (beginning-of-line 1)
11313 (if (org-at-heading-p)
11314 (setq ltoggle (funcall outline-level))
11315 (error "This should not happen"))
11316 (while (and (setq level (org-up-heading-safe))
11317 (or recursive first)
11318 (>= (point) lim))
11319 (setq first nil cookie-present nil)
11320 (unless (and level
11321 (not (string-match
11322 "\\<checkbox\\>"
11323 (downcase
11324 (or (org-entry-get
11325 nil "COOKIE_DATA")
11326 "")))))
11327 (throw 'exit nil))
11328 (while (re-search-forward box-re (point-at-eol) t)
11329 (setq cnt-all 0 cnt-done 0 cookie-present t)
11330 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11331 (save-match-data
11332 (unless (outline-next-heading) (throw 'exit nil))
11333 (while (and (looking-at org-complex-heading-regexp)
11334 (> (setq l1 (length (match-string 1))) level))
11335 (setq kwd (and (or recursive (= l1 ltoggle))
11336 (match-string 2)))
11337 (if (or (eq org-provide-todo-statistics 'all-headlines)
11338 (and (listp org-provide-todo-statistics)
11339 (or (member kwd org-provide-todo-statistics)
11340 (member kwd org-done-keywords))))
11341 (setq cnt-all (1+ cnt-all))
11342 (if (eq org-provide-todo-statistics t)
11343 (and kwd (setq cnt-all (1+ cnt-all)))))
11344 (and (member kwd org-done-keywords)
11345 (setq cnt-done (1+ cnt-done)))
11346 (outline-next-heading)))
11347 (setq new
11348 (if is-percent
11349 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11350 (format "[%d/%d]" cnt-done cnt-all))
11351 ndel (- (match-end 0) checkbox-beg))
11352 ;; handle overlays when updating cookie from column view
11353 (when (setq ov (car (overlays-at checkbox-beg)))
11354 (setq ovs (overlay-start ov) ove (overlay-end ov))
11355 (delete-overlay ov))
11356 (goto-char checkbox-beg)
11357 (insert new)
11358 (delete-region (point) (+ (point) ndel))
11359 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11360 (when ov (move-overlay ov ovs ove)))
11361 (when cookie-present
11362 (run-hook-with-args 'org-after-todo-statistics-hook
11363 cnt-done (- cnt-all cnt-done))))))
11364 (run-hooks 'org-todo-statistics-hook)))
11366 (defvar org-after-todo-statistics-hook nil
11367 "Hook that is called after a TODO statistics cookie has been updated.
11368 Each function is called with two arguments: the number of not-done entries
11369 and the number of done entries.
11371 For example, the following function, when added to this hook, will switch
11372 an entry to DONE when all children are done, and back to TODO when new
11373 entries are set to a TODO status. Note that this hook is only called
11374 when there is a statistics cookie in the headline!
11376 (defun org-summary-todo (n-done n-not-done)
11377 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11378 (let (org-log-done org-log-states) ; turn off logging
11379 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11382 (defvar org-todo-statistics-hook nil
11383 "Hook that is run whenever Org thinks TODO statistics should be updated.
11384 This hook runs even if there is no statistics cookie present, in which case
11385 `org-after-todo-statistics-hook' would not run.")
11387 (defun org-todo-trigger-tag-changes (state)
11388 "Apply the changes defined in `org-todo-state-tags-triggers'."
11389 (let ((l org-todo-state-tags-triggers)
11390 changes)
11391 (when (or (not state) (equal state ""))
11392 (setq changes (append changes (cdr (assoc "" l)))))
11393 (when (and (stringp state) (> (length state) 0))
11394 (setq changes (append changes (cdr (assoc state l)))))
11395 (when (member state org-not-done-keywords)
11396 (setq changes (append changes (cdr (assoc 'todo l)))))
11397 (when (member state org-done-keywords)
11398 (setq changes (append changes (cdr (assoc 'done l)))))
11399 (dolist (c changes)
11400 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11402 (defun org-local-logging (value)
11403 "Get logging settings from a property VALUE."
11404 (let* (words w a)
11405 ;; directly set the variables, they are already local.
11406 (setq org-log-done nil
11407 org-log-repeat nil
11408 org-todo-log-states nil)
11409 (setq words (org-split-string value))
11410 (while (setq w (pop words))
11411 (cond
11412 ((setq a (assoc w org-startup-options))
11413 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11414 (set (nth 1 a) (nth 2 a))))
11415 ((setq a (org-extract-log-state-settings w))
11416 (and (member (car a) org-todo-keywords-1)
11417 (push a org-todo-log-states)))))))
11419 (defun org-get-todo-sequence-head (kwd)
11420 "Return the head of the TODO sequence to which KWD belongs.
11421 If KWD is not set, check if there is a text property remembering the
11422 right sequence."
11423 (let (p)
11424 (cond
11425 ((not kwd)
11426 (or (get-text-property (point-at-bol) 'org-todo-head)
11427 (progn
11428 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11429 nil (point-at-eol)))
11430 (get-text-property p 'org-todo-head))))
11431 ((not (member kwd org-todo-keywords-1))
11432 (car org-todo-keywords-1))
11433 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11435 (defun org-fast-todo-selection ()
11436 "Fast TODO keyword selection with single keys.
11437 Returns the new TODO keyword, or nil if no state change should occur."
11438 (let* ((fulltable org-todo-key-alist)
11439 (done-keywords org-done-keywords) ;; needed for the faces.
11440 (maxlen (apply 'max (mapcar
11441 (lambda (x)
11442 (if (stringp (car x)) (string-width (car x)) 0))
11443 fulltable)))
11444 (expert nil)
11445 (fwidth (+ maxlen 3 1 3))
11446 (ncol (/ (- (window-width) 4) fwidth))
11447 tg cnt e c tbl
11448 groups ingroup)
11449 (save-excursion
11450 (save-window-excursion
11451 (if expert
11452 (set-buffer (get-buffer-create " *Org todo*"))
11453 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11454 (erase-buffer)
11455 (org-set-local 'org-done-keywords done-keywords)
11456 (setq tbl fulltable cnt 0)
11457 (while (setq e (pop tbl))
11458 (cond
11459 ((equal e '(:startgroup))
11460 (push '() groups) (setq ingroup t)
11461 (when (not (= cnt 0))
11462 (setq cnt 0)
11463 (insert "\n"))
11464 (insert "{ "))
11465 ((equal e '(:endgroup))
11466 (setq ingroup nil cnt 0)
11467 (insert "}\n"))
11468 ((equal e '(:newline))
11469 (when (not (= cnt 0))
11470 (setq cnt 0)
11471 (insert "\n")
11472 (setq e (car tbl))
11473 (while (equal (car tbl) '(:newline))
11474 (insert "\n")
11475 (setq tbl (cdr tbl)))))
11477 (setq tg (car e) c (cdr e))
11478 (if ingroup (push tg (car groups)))
11479 (setq tg (org-add-props tg nil 'face
11480 (org-get-todo-face tg)))
11481 (if (and (= cnt 0) (not ingroup)) (insert " "))
11482 (insert "[" c "] " tg (make-string
11483 (- fwidth 4 (length tg)) ?\ ))
11484 (when (= (setq cnt (1+ cnt)) ncol)
11485 (insert "\n")
11486 (if ingroup (insert " "))
11487 (setq cnt 0)))))
11488 (insert "\n")
11489 (goto-char (point-min))
11490 (if (not expert) (org-fit-window-to-buffer))
11491 (message "[a-z..]:Set [SPC]:clear")
11492 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11493 (cond
11494 ((or (= c ?\C-g)
11495 (and (= c ?q) (not (rassoc c fulltable))))
11496 (setq quit-flag t))
11497 ((= c ?\ ) nil)
11498 ((setq e (rassoc c fulltable) tg (car e))
11500 (t (setq quit-flag t)))))))
11502 (defun org-entry-is-todo-p ()
11503 (member (org-get-todo-state) org-not-done-keywords))
11505 (defun org-entry-is-done-p ()
11506 (member (org-get-todo-state) org-done-keywords))
11508 (defun org-get-todo-state ()
11509 (save-excursion
11510 (org-back-to-heading t)
11511 (and (looking-at org-todo-line-regexp)
11512 (match-end 2)
11513 (match-string 2))))
11515 (defun org-at-date-range-p (&optional inactive-ok)
11516 "Is the cursor inside a date range?"
11517 (interactive)
11518 (save-excursion
11519 (catch 'exit
11520 (let ((pos (point)))
11521 (skip-chars-backward "^[<\r\n")
11522 (skip-chars-backward "<[")
11523 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11524 (>= (match-end 0) pos)
11525 (throw 'exit t))
11526 (skip-chars-backward "^<[\r\n")
11527 (skip-chars-backward "<[")
11528 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11529 (>= (match-end 0) pos)
11530 (throw 'exit t)))
11531 nil)))
11533 (defun org-get-repeat (&optional tagline)
11534 "Check if there is a deadline/schedule with repeater in this entry."
11535 (save-match-data
11536 (save-excursion
11537 (org-back-to-heading t)
11538 (and (re-search-forward (if tagline
11539 (concat tagline "\\s-*" org-repeat-re)
11540 org-repeat-re)
11541 (org-entry-end-position) t)
11542 (match-string-no-properties 1)))))
11544 (defvar org-last-changed-timestamp)
11545 (defvar org-last-inserted-timestamp)
11546 (defvar org-log-post-message)
11547 (defvar org-log-note-purpose)
11548 (defvar org-log-note-how)
11549 (defvar org-log-note-extra)
11550 (defun org-auto-repeat-maybe (done-word)
11551 "Check if the current headline contains a repeated deadline/schedule.
11552 If yes, set TODO state back to what it was and change the base date
11553 of repeating deadline/scheduled time stamps to new date.
11554 This function is run automatically after each state change to a DONE state."
11555 ;; last-state is dynamically scoped into this function
11556 (let* ((repeat (org-get-repeat))
11557 (aa (assoc last-state org-todo-kwd-alist))
11558 (interpret (nth 1 aa))
11559 (head (nth 2 aa))
11560 (whata '(("d" . day) ("m" . month) ("y" . year)))
11561 (msg "Entry repeats: ")
11562 (org-log-done nil)
11563 (org-todo-log-states nil)
11564 re type n what ts time to-state)
11565 (when repeat
11566 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11567 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11568 org-todo-repeat-to-state))
11569 (unless (and to-state (member to-state org-todo-keywords-1))
11570 (setq to-state (if (eq interpret 'type) last-state head)))
11571 (org-todo to-state)
11572 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11573 (org-entry-put nil "LAST_REPEAT" (format-time-string
11574 (org-time-stamp-format t t))))
11575 (when org-log-repeat
11576 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11577 (memq 'org-add-log-note post-command-hook))
11578 ;; OK, we are already setup for some record
11579 (if (eq org-log-repeat 'note)
11580 ;; make sure we take a note, not only a time stamp
11581 (setq org-log-note-how 'note))
11582 ;; Set up for taking a record
11583 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11584 last-state
11585 'findpos org-log-repeat)))
11586 (org-back-to-heading t)
11587 (org-add-planning-info nil nil 'closed)
11588 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11589 org-deadline-time-regexp "\\)\\|\\("
11590 org-ts-regexp "\\)"))
11591 (while (re-search-forward
11592 re (save-excursion (outline-next-heading) (point)) t)
11593 (setq type (if (match-end 1) org-scheduled-string
11594 (if (match-end 3) org-deadline-string "Plain:"))
11595 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11596 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11597 (setq n (string-to-number (match-string 2 ts))
11598 what (match-string 3 ts))
11599 (if (equal what "w") (setq n (* n 7) what "d"))
11600 ;; Preparation, see if we need to modify the start date for the change
11601 (when (match-end 1)
11602 (setq time (save-match-data (org-time-string-to-time ts)))
11603 (cond
11604 ((equal (match-string 1 ts) ".")
11605 ;; Shift starting date to today
11606 (org-timestamp-change
11607 (- (time-to-days (current-time)) (time-to-days time))
11608 'day))
11609 ((equal (match-string 1 ts) "+")
11610 (let ((nshiftmax 10) (nshift 0))
11611 (while (or (= nshift 0)
11612 (<= (time-to-days time)
11613 (time-to-days (current-time))))
11614 (when (= (incf nshift) nshiftmax)
11615 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11616 (error "Abort")))
11617 (org-timestamp-change n (cdr (assoc what whata)))
11618 (org-at-timestamp-p t)
11619 (setq ts (match-string 1))
11620 (setq time (save-match-data (org-time-string-to-time ts)))))
11621 (org-timestamp-change (- n) (cdr (assoc what whata)))
11622 ;; rematch, so that we have everything in place for the real shift
11623 (org-at-timestamp-p t)
11624 (setq ts (match-string 1))
11625 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11626 (org-timestamp-change n (cdr (assoc what whata)))
11627 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11628 (setq org-log-post-message msg)
11629 (message "%s" msg))))
11631 (defun org-show-todo-tree (arg)
11632 "Make a compact tree which shows all headlines marked with TODO.
11633 The tree will show the lines where the regexp matches, and all higher
11634 headlines above the match.
11635 With a \\[universal-argument] prefix, prompt for a regexp to match.
11636 With a numeric prefix N, construct a sparse tree for the Nth element
11637 of `org-todo-keywords-1'."
11638 (interactive "P")
11639 (let ((case-fold-search nil)
11640 (kwd-re
11641 (cond ((null arg) org-not-done-regexp)
11642 ((equal arg '(4))
11643 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11644 (mapcar 'list org-todo-keywords-1))))
11645 (concat "\\("
11646 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11647 "\\)\\>")))
11648 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11649 (regexp-quote (nth (1- (prefix-numeric-value arg))
11650 org-todo-keywords-1)))
11651 (t (error "Invalid prefix argument: %s" arg)))))
11652 (message "%d TODO entries found"
11653 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
11655 (defun org-deadline (&optional remove time)
11656 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11657 With argument REMOVE, remove any deadline from the item.
11658 When TIME is set, it should be an internal time specification, and the
11659 scheduling will use the corresponding date."
11660 (interactive "P")
11661 (let* ((old-date (org-entry-get nil "DEADLINE"))
11662 (repeater (and old-date
11663 (string-match
11664 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11665 old-date)
11666 (match-string 1 old-date))))
11667 (if remove
11668 (progn
11669 (when (and old-date org-log-redeadline)
11670 (org-add-log-setup 'deldeadline nil old-date 'findpos
11671 org-log-redeadline))
11672 (org-remove-timestamp-with-keyword org-deadline-string)
11673 (message "Item no longer has a deadline."))
11674 (org-add-planning-info 'deadline time 'closed)
11675 (when (and old-date org-log-redeadline
11676 (not (equal old-date
11677 (substring org-last-inserted-timestamp 1 -1))))
11678 (org-add-log-setup 'redeadline nil old-date 'findpos
11679 org-log-redeadline))
11680 (when repeater
11681 (save-excursion
11682 (org-back-to-heading t)
11683 (when (re-search-forward (concat org-deadline-string " "
11684 org-last-inserted-timestamp)
11685 (save-excursion
11686 (outline-next-heading) (point)) t)
11687 (goto-char (1- (match-end 0)))
11688 (insert " " repeater)
11689 (setq org-last-inserted-timestamp
11690 (concat (substring org-last-inserted-timestamp 0 -1)
11691 " " repeater
11692 (substring org-last-inserted-timestamp -1))))))
11693 (message "Deadline on %s" org-last-inserted-timestamp))))
11695 (defun org-schedule (&optional remove time)
11696 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11697 With argument REMOVE, remove any scheduling date from the item.
11698 When TIME is set, it should be an internal time specification, and the
11699 scheduling will use the corresponding date."
11700 (interactive "P")
11701 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11702 (repeater (and old-date
11703 (string-match
11704 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11705 old-date)
11706 (match-string 1 old-date))))
11707 (if remove
11708 (progn
11709 (when (and old-date org-log-reschedule)
11710 (org-add-log-setup 'delschedule nil old-date 'findpos
11711 org-log-reschedule))
11712 (org-remove-timestamp-with-keyword org-scheduled-string)
11713 (message "Item is no longer scheduled."))
11714 (org-add-planning-info 'scheduled time 'closed)
11715 (when (and old-date org-log-reschedule
11716 (not (equal old-date
11717 (substring org-last-inserted-timestamp 1 -1))))
11718 (org-add-log-setup 'reschedule nil old-date 'findpos
11719 org-log-reschedule))
11720 (when repeater
11721 (save-excursion
11722 (org-back-to-heading t)
11723 (when (re-search-forward (concat org-scheduled-string " "
11724 org-last-inserted-timestamp)
11725 (save-excursion
11726 (outline-next-heading) (point)) t)
11727 (goto-char (1- (match-end 0)))
11728 (insert " " repeater)
11729 (setq org-last-inserted-timestamp
11730 (concat (substring org-last-inserted-timestamp 0 -1)
11731 " " repeater
11732 (substring org-last-inserted-timestamp -1))))))
11733 (message "Scheduled to %s" org-last-inserted-timestamp))))
11735 (defun org-get-scheduled-time (pom &optional inherit)
11736 "Get the scheduled time as a time tuple, of a format suitable
11737 for calling org-schedule with, or if there is no scheduling,
11738 returns nil."
11739 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11740 (when time
11741 (apply 'encode-time (org-parse-time-string time)))))
11743 (defun org-get-deadline-time (pom &optional inherit)
11744 "Get the deadline as a time tuple, of a format suitable for
11745 calling org-deadline with, or if there is no scheduling, returns
11746 nil."
11747 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11748 (when time
11749 (apply 'encode-time (org-parse-time-string time)))))
11751 (defun org-remove-timestamp-with-keyword (keyword)
11752 "Remove all time stamps with KEYWORD in the current entry."
11753 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11754 beg)
11755 (save-excursion
11756 (org-back-to-heading t)
11757 (setq beg (point))
11758 (outline-next-heading)
11759 (while (re-search-backward re beg t)
11760 (replace-match "")
11761 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11762 (equal (char-before) ?\ ))
11763 (backward-delete-char 1)
11764 (if (string-match "^[ \t]*$" (buffer-substring
11765 (point-at-bol) (point-at-eol)))
11766 (delete-region (point-at-bol)
11767 (min (point-max) (1+ (point-at-eol))))))))))
11769 (defun org-add-planning-info (what &optional time &rest remove)
11770 "Insert new timestamp with keyword in the line directly after the headline.
11771 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11772 If non is given, the user is prompted for a date.
11773 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11774 be removed."
11775 (interactive)
11776 (let (org-time-was-given org-end-time-was-given ts
11777 end default-time default-input)
11779 (catch 'exit
11780 (when (and (not time) (memq what '(scheduled deadline)))
11781 ;; Try to get a default date/time from existing timestamp
11782 (save-excursion
11783 (org-back-to-heading t)
11784 (setq end (save-excursion (outline-next-heading) (point)))
11785 (when (re-search-forward (if (eq what 'scheduled)
11786 org-scheduled-time-regexp
11787 org-deadline-time-regexp)
11788 end t)
11789 (setq ts (match-string 1)
11790 default-time
11791 (apply 'encode-time (org-parse-time-string ts))
11792 default-input (and ts (org-get-compact-tod ts))))))
11793 (when what
11794 ;; If necessary, get the time from the user
11795 (setq time (or time (org-read-date nil 'to-time nil nil
11796 default-time default-input))))
11798 (when (and org-insert-labeled-timestamps-at-point
11799 (member what '(scheduled deadline)))
11800 (insert
11801 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11802 (org-insert-time-stamp time org-time-was-given
11803 nil nil nil (list org-end-time-was-given))
11804 (setq what nil))
11805 (save-excursion
11806 (save-restriction
11807 (let (col list elt ts buffer-invisibility-spec)
11808 (org-back-to-heading t)
11809 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11810 (goto-char (match-end 1))
11811 (setq col (current-column))
11812 (goto-char (match-end 0))
11813 (if (eobp) (insert "\n") (forward-char 1))
11814 (when (and (not what)
11815 (not (looking-at
11816 (concat "[ \t]*"
11817 org-keyword-time-not-clock-regexp))))
11818 ;; Nothing to add, nothing to remove...... :-)
11819 (throw 'exit nil))
11820 (if (and (not (looking-at outline-regexp))
11821 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11822 "[^\r\n]*"))
11823 (not (equal (match-string 1) org-clock-string)))
11824 (narrow-to-region (match-beginning 0) (match-end 0))
11825 (insert-before-markers "\n")
11826 (backward-char 1)
11827 (narrow-to-region (point) (point))
11828 (and org-adapt-indentation (org-indent-to-column col)))
11829 ;; Check if we have to remove something.
11830 (setq list (cons what remove))
11831 (while list
11832 (setq elt (pop list))
11833 (when (or (and (eq elt 'scheduled)
11834 (re-search-forward org-scheduled-time-regexp nil t))
11835 (and (eq elt 'deadline)
11836 (re-search-forward org-deadline-time-regexp nil t))
11837 (and (eq elt 'closed)
11838 (re-search-forward org-closed-time-regexp nil t)))
11839 (replace-match "")
11840 (if (looking-at "--+<[^>]+>") (replace-match ""))))
11841 (and (looking-at "^[ \t]+") (replace-match ""))
11842 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11843 (when what
11844 (insert
11845 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11846 (cond ((eq what 'scheduled) org-scheduled-string)
11847 ((eq what 'deadline) org-deadline-string)
11848 ((eq what 'closed) org-closed-string))
11849 " ")
11850 (setq ts (org-insert-time-stamp
11851 time
11852 (or org-time-was-given
11853 (and (eq what 'closed) org-log-done-with-time))
11854 (eq what 'closed)
11855 nil nil (list org-end-time-was-given)))
11856 (insert
11857 (if (not (or (bolp) (eq (char-before) ?\ )
11858 (eq (char-after) ?\ ))) " " ""))
11859 (end-of-line 1))
11860 (goto-char (point-min))
11861 (widen)
11862 (if (and (looking-at "[ \t]*\n")
11863 (equal (char-before) ?\n))
11864 (delete-region (1- (point)) (point-at-eol)))
11865 ts))))))
11867 (defvar org-log-note-marker (make-marker))
11868 (defvar org-log-note-purpose nil)
11869 (defvar org-log-note-state nil)
11870 (defvar org-log-note-previous-state nil)
11871 (defvar org-log-note-how nil)
11872 (defvar org-log-note-extra nil)
11873 (defvar org-log-note-window-configuration nil)
11874 (defvar org-log-note-return-to (make-marker))
11875 (defvar org-log-post-message nil
11876 "Message to be displayed after a log note has been stored.
11877 The auto-repeater uses this.")
11879 (defun org-add-note ()
11880 "Add a note to the current entry.
11881 This is done in the same way as adding a state change note."
11882 (interactive)
11883 (org-add-log-setup 'note nil nil 'findpos nil))
11885 (defvar org-property-end-re)
11886 (defun org-add-log-setup (&optional purpose state prev-state
11887 findpos how extra)
11888 "Set up the post command hook to take a note.
11889 If this is about to TODO state change, the new state is expected in STATE.
11890 When FINDPOS is non-nil, find the correct position for the note in
11891 the current entry. If not, assume that it can be inserted at point.
11892 HOW is an indicator what kind of note should be created.
11893 EXTRA is additional text that will be inserted into the notes buffer."
11894 (let* ((org-log-into-drawer (org-log-into-drawer))
11895 (drawer (cond ((stringp org-log-into-drawer)
11896 org-log-into-drawer)
11897 (org-log-into-drawer "LOGBOOK")
11898 (t nil))))
11899 (save-restriction
11900 (save-excursion
11901 (when findpos
11902 (org-back-to-heading t)
11903 (narrow-to-region (point) (save-excursion
11904 (outline-next-heading) (point)))
11905 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11906 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11907 "[^\r\n]*\\)?"))
11908 (goto-char (match-end 0))
11909 (cond
11910 (drawer
11911 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11912 nil t)
11913 (progn
11914 (goto-char (match-end 0))
11915 (or org-log-states-order-reversed
11916 (and (re-search-forward org-property-end-re nil t)
11917 (goto-char (1- (match-beginning 0))))))
11918 (insert "\n:" drawer ":\n:END:")
11919 (beginning-of-line 0)
11920 (org-indent-line-function)
11921 (beginning-of-line 2)
11922 (org-indent-line-function)
11923 (end-of-line 0)))
11924 ((and org-log-state-notes-insert-after-drawers
11925 (save-excursion
11926 (forward-line) (looking-at org-drawer-regexp)))
11927 (forward-line)
11928 (while (looking-at org-drawer-regexp)
11929 (goto-char (match-end 0))
11930 (re-search-forward org-property-end-re (point-max) t)
11931 (forward-line))
11932 (forward-line -1)))
11933 (unless org-log-states-order-reversed
11934 (and (= (char-after) ?\n) (forward-char 1))
11935 (org-skip-over-state-notes)
11936 (skip-chars-backward " \t\n\r")))
11937 (move-marker org-log-note-marker (point))
11938 (setq org-log-note-purpose purpose
11939 org-log-note-state state
11940 org-log-note-previous-state prev-state
11941 org-log-note-how how
11942 org-log-note-extra extra)
11943 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11945 (defun org-skip-over-state-notes ()
11946 "Skip past the list of State notes in an entry."
11947 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11948 (when (ignore-errors (goto-char (org-in-item-p)))
11949 (let* ((struct (org-list-struct))
11950 (prevs (org-list-prevs-alist struct)))
11951 (while (looking-at "[ \t]*- State")
11952 (goto-char (or (org-list-get-next-item (point) struct prevs)
11953 (org-list-get-item-end (point) struct)))))))
11955 (defun org-add-log-note (&optional purpose)
11956 "Pop up a window for taking a note, and add this note later at point."
11957 (remove-hook 'post-command-hook 'org-add-log-note)
11958 (setq org-log-note-window-configuration (current-window-configuration))
11959 (delete-other-windows)
11960 (move-marker org-log-note-return-to (point))
11961 (switch-to-buffer (marker-buffer org-log-note-marker))
11962 (goto-char org-log-note-marker)
11963 (org-switch-to-buffer-other-window "*Org Note*")
11964 (erase-buffer)
11965 (if (memq org-log-note-how '(time state))
11966 (let (current-prefix-arg) (org-store-log-note))
11967 (let ((org-inhibit-startup t)) (org-mode))
11968 (insert (format "# Insert note for %s.
11969 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11970 (cond
11971 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11972 ((eq org-log-note-purpose 'done) "closed todo item")
11973 ((eq org-log-note-purpose 'state)
11974 (format "state change from \"%s\" to \"%s\""
11975 (or org-log-note-previous-state "")
11976 (or org-log-note-state "")))
11977 ((eq org-log-note-purpose 'reschedule)
11978 "rescheduling")
11979 ((eq org-log-note-purpose 'delschedule)
11980 "no longer scheduled")
11981 ((eq org-log-note-purpose 'redeadline)
11982 "changing deadline")
11983 ((eq org-log-note-purpose 'deldeadline)
11984 "removing deadline")
11985 ((eq org-log-note-purpose 'refile)
11986 "refiling")
11987 ((eq org-log-note-purpose 'note)
11988 "this entry")
11989 (t (error "This should not happen")))))
11990 (if org-log-note-extra (insert org-log-note-extra))
11991 (org-set-local 'org-finish-function 'org-store-log-note)))
11993 (defvar org-note-abort nil) ; dynamically scoped
11994 (defun org-store-log-note ()
11995 "Finish taking a log note, and insert it to where it belongs."
11996 (let ((txt (buffer-string))
11997 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11998 lines ind bul)
11999 (kill-buffer (current-buffer))
12000 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12001 (setq txt (replace-match "" t t txt)))
12002 (if (string-match "\\s-+\\'" txt)
12003 (setq txt (replace-match "" t t txt)))
12004 (setq lines (org-split-string txt "\n"))
12005 (when (and note (string-match "\\S-" note))
12006 (setq note
12007 (org-replace-escapes
12008 note
12009 (list (cons "%u" (user-login-name))
12010 (cons "%U" user-full-name)
12011 (cons "%t" (format-time-string
12012 (org-time-stamp-format 'long 'inactive)
12013 (current-time)))
12014 (cons "%T" (format-time-string
12015 (org-time-stamp-format 'long nil)
12016 (current-time)))
12017 (cons "%s" (if org-log-note-state
12018 (concat "\"" org-log-note-state "\"")
12019 ""))
12020 (cons "%S" (if org-log-note-previous-state
12021 (concat "\"" org-log-note-previous-state "\"")
12022 "\"\"")))))
12023 (if lines (setq note (concat note " \\\\")))
12024 (push note lines))
12025 (when (or current-prefix-arg org-note-abort)
12026 (when org-log-into-drawer
12027 (org-remove-empty-drawer-at
12028 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12029 org-log-note-marker))
12030 (setq lines nil))
12031 (when lines
12032 (with-current-buffer (marker-buffer org-log-note-marker)
12033 (save-excursion
12034 (goto-char org-log-note-marker)
12035 (move-marker org-log-note-marker nil)
12036 (end-of-line 1)
12037 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12038 (setq ind (save-excursion
12039 (if (ignore-errors (goto-char (org-in-item-p)))
12040 (let ((struct (org-list-struct)))
12041 (org-list-get-ind
12042 (org-list-get-top-point struct) struct))
12043 (skip-chars-backward " \r\t\n")
12044 (cond
12045 ((and (org-at-heading-p)
12046 org-adapt-indentation)
12047 (1+ (org-current-level)))
12048 ((org-at-heading-p) 0)
12049 (t (org-get-indentation))))))
12050 (setq bul (org-list-bullet-string "-"))
12051 (org-indent-line-to ind)
12052 (insert bul (pop lines))
12053 (let ((ind-body (+ (length bul) ind)))
12054 (while lines
12055 (insert "\n")
12056 (org-indent-line-to ind-body)
12057 (insert (pop lines))))
12058 (message "Note stored")
12059 (org-back-to-heading t)
12060 (org-cycle-hide-drawers 'children)))))
12061 (set-window-configuration org-log-note-window-configuration)
12062 (with-current-buffer (marker-buffer org-log-note-return-to)
12063 (goto-char org-log-note-return-to))
12064 (move-marker org-log-note-return-to nil)
12065 (and org-log-post-message (message "%s" org-log-post-message)))
12067 (defun org-remove-empty-drawer-at (drawer pos)
12068 "Remove an empty drawer DRAWER at position POS.
12069 POS may also be a marker."
12070 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12071 (save-excursion
12072 (save-restriction
12073 (widen)
12074 (goto-char pos)
12075 (if (org-in-regexp
12076 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12077 (replace-match ""))))))
12079 (defun org-sparse-tree (&optional arg)
12080 "Create a sparse tree, prompt for the details.
12081 This command can create sparse trees. You first need to select the type
12082 of match used to create the tree:
12084 t Show all TODO entries.
12085 T Show entries with a specific TODO keyword.
12086 m Show entries selected by a tags/property match.
12087 p Enter a property name and its value (both with completion on existing
12088 names/values) and show entries with that property.
12089 r Show entries matching a regular expression (`/' can be used as well)
12090 d Show deadlines due within `org-deadline-warning-days'.
12091 b Show deadlines and scheduled items before a date.
12092 a Show deadlines and scheduled items after a date."
12093 (interactive "P")
12094 (let (ans kwd value)
12095 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12096 (setq ans (read-char-exclusive))
12097 (cond
12098 ((equal ans ?d)
12099 (call-interactively 'org-check-deadlines))
12100 ((equal ans ?b)
12101 (call-interactively 'org-check-before-date))
12102 ((equal ans ?a)
12103 (call-interactively 'org-check-after-date))
12104 ((equal ans ?t)
12105 (org-show-todo-tree nil))
12106 ((equal ans ?T)
12107 (org-show-todo-tree '(4)))
12108 ((member ans '(?T ?m))
12109 (call-interactively 'org-match-sparse-tree))
12110 ((member ans '(?p ?P))
12111 (setq kwd (org-icompleting-read "Property: "
12112 (mapcar 'list (org-buffer-property-keys))))
12113 (setq value (org-icompleting-read "Value: "
12114 (mapcar 'list (org-property-values kwd))))
12115 (unless (string-match "\\`{.*}\\'" value)
12116 (setq value (concat "\"" value "\"")))
12117 (org-match-sparse-tree arg (concat kwd "=" value)))
12118 ((member ans '(?r ?R ?/))
12119 (call-interactively 'org-occur))
12120 (t (error "No such sparse tree command \"%c\"" ans)))))
12122 (defvar org-occur-highlights nil
12123 "List of overlays used for occur matches.")
12124 (make-variable-buffer-local 'org-occur-highlights)
12125 (defvar org-occur-parameters nil
12126 "Parameters of the active org-occur calls.
12127 This is a list, each call to org-occur pushes as cons cell,
12128 containing the regular expression and the callback, onto the list.
12129 The list can contain several entries if `org-occur' has been called
12130 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12131 will only contain one set of parameters. When the highlights are
12132 removed (for example with `C-c C-c', or with the next edit (depending
12133 on `org-remove-highlights-with-change'), this variable is emptied
12134 as well.")
12135 (make-variable-buffer-local 'org-occur-parameters)
12137 (defun org-occur (regexp &optional keep-previous callback)
12138 "Make a compact tree which shows all matches of REGEXP.
12139 The tree will show the lines where the regexp matches, and all higher
12140 headlines above the match. It will also show the heading after the match,
12141 to make sure editing the matching entry is easy.
12142 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12143 call to `org-occur' will be kept, to allow stacking of calls to this
12144 command.
12145 If CALLBACK is non-nil, it is a function which is called to confirm
12146 that the match should indeed be shown."
12147 (interactive "sRegexp: \nP")
12148 (when (equal regexp "")
12149 (error "Regexp cannot be empty"))
12150 (unless keep-previous
12151 (org-remove-occur-highlights nil nil t))
12152 (push (cons regexp callback) org-occur-parameters)
12153 (let ((cnt 0))
12154 (save-excursion
12155 (goto-char (point-min))
12156 (if (or (not keep-previous) ; do not want to keep
12157 (not org-occur-highlights)) ; no previous matches
12158 ;; hide everything
12159 (org-overview))
12160 (while (re-search-forward regexp nil t)
12161 (when (or (not callback)
12162 (save-match-data (funcall callback)))
12163 (setq cnt (1+ cnt))
12164 (when org-highlight-sparse-tree-matches
12165 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12166 (org-show-context 'occur-tree))))
12167 (when org-remove-highlights-with-change
12168 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12169 nil 'local))
12170 (unless org-sparse-tree-open-archived-trees
12171 (org-hide-archived-subtrees (point-min) (point-max)))
12172 (run-hooks 'org-occur-hook)
12173 (if (org-called-interactively-p 'interactive)
12174 (message "%d match(es) for regexp %s" cnt regexp))
12175 cnt))
12177 (defun org-occur-next-match (&optional n reset)
12178 "Function for `next-error-function' to find sparse tree matches.
12179 N is the number of matches to move, when negative move backwards.
12180 RESET is entirely ignored - this function always goes back to the
12181 starting point when no match is found."
12182 (let* ((limit (if (< n 0) (point-min) (point-max)))
12183 (search-func (if (< n 0)
12184 'previous-single-char-property-change
12185 'next-single-char-property-change))
12186 (n (abs n))
12187 (pos (point))
12189 (catch 'exit
12190 (while (setq p1 (funcall search-func (point) 'org-type))
12191 (when (equal p1 limit)
12192 (goto-char pos)
12193 (error "No more matches"))
12194 (when (equal (get-char-property p1 'org-type) 'org-occur)
12195 (setq n (1- n))
12196 (when (= n 0)
12197 (goto-char p1)
12198 (throw 'exit (point))))
12199 (goto-char p1))
12200 (goto-char p1)
12201 (error "No more matches"))))
12203 (defun org-show-context (&optional key)
12204 "Make sure point and context are visible.
12205 How much context is shown depends upon the variables
12206 `org-show-hierarchy-above', `org-show-following-heading'. and
12207 `org-show-siblings'."
12208 (let ((heading-p (org-on-heading-p t))
12209 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12210 (following-p (org-get-alist-option org-show-following-heading key))
12211 (entry-p (org-get-alist-option org-show-entry-below key))
12212 (siblings-p (org-get-alist-option org-show-siblings key)))
12213 (catch 'exit
12214 ;; Show heading or entry text
12215 (if (and heading-p (not entry-p))
12216 (org-flag-heading nil) ; only show the heading
12217 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12218 (org-show-hidden-entry))) ; show entire entry
12219 (when following-p
12220 ;; Show next sibling, or heading below text
12221 (save-excursion
12222 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12223 (org-flag-heading nil))))
12224 (when siblings-p (org-show-siblings))
12225 (when hierarchy-p
12226 ;; show all higher headings, possibly with siblings
12227 (save-excursion
12228 (while (and (condition-case nil
12229 (progn (org-up-heading-all 1) t)
12230 (error nil))
12231 (not (bobp)))
12232 (org-flag-heading nil)
12233 (when siblings-p (org-show-siblings))))))))
12235 (defvar org-reveal-start-hook nil
12236 "Hook run before revealing a location.")
12238 (defun org-reveal (&optional siblings)
12239 "Show current entry, hierarchy above it, and the following headline.
12240 This can be used to show a consistent set of context around locations
12241 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12242 not t for the search context.
12244 With optional argument SIBLINGS, on each level of the hierarchy all
12245 siblings are shown. This repairs the tree structure to what it would
12246 look like when opened with hierarchical calls to `org-cycle'.
12247 With double optional argument \\[universal-argument] \\[universal-argument], \
12248 go to the parent and show the
12249 entire tree."
12250 (interactive "P")
12251 (run-hooks 'org-reveal-start-hook)
12252 (let ((org-show-hierarchy-above t)
12253 (org-show-following-heading t)
12254 (org-show-siblings (if siblings t org-show-siblings)))
12255 (org-show-context nil))
12256 (when (equal siblings '(16))
12257 (save-excursion
12258 (when (org-up-heading-safe)
12259 (org-show-subtree)
12260 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12262 (defun org-highlight-new-match (beg end)
12263 "Highlight from BEG to END and mark the highlight is an occur headline."
12264 (let ((ov (make-overlay beg end)))
12265 (overlay-put ov 'face 'secondary-selection)
12266 (overlay-put ov 'org-type 'org-occur)
12267 (push ov org-occur-highlights)))
12269 (defun org-remove-occur-highlights (&optional beg end noremove)
12270 "Remove the occur highlights from the buffer.
12271 BEG and END are ignored. If NOREMOVE is nil, remove this function
12272 from the `before-change-functions' in the current buffer."
12273 (interactive)
12274 (unless org-inhibit-highlight-removal
12275 (mapc 'delete-overlay org-occur-highlights)
12276 (setq org-occur-highlights nil)
12277 (setq org-occur-parameters nil)
12278 (unless noremove
12279 (remove-hook 'before-change-functions
12280 'org-remove-occur-highlights 'local))))
12282 ;;;; Priorities
12284 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12285 "Regular expression matching the priority indicator.")
12287 (defvar org-remove-priority-next-time nil)
12289 (defun org-priority-up ()
12290 "Increase the priority of the current item."
12291 (interactive)
12292 (org-priority 'up))
12294 (defun org-priority-down ()
12295 "Decrease the priority of the current item."
12296 (interactive)
12297 (org-priority 'down))
12299 (defun org-priority (&optional action)
12300 "Change the priority of an item by ARG.
12301 ACTION can be `set', `up', `down', or a character."
12302 (interactive)
12303 (unless org-enable-priority-commands
12304 (error "Priority commands are disabled"))
12305 (setq action (or action 'set))
12306 (let (current new news have remove)
12307 (save-excursion
12308 (org-back-to-heading t)
12309 (if (looking-at org-priority-regexp)
12310 (setq current (string-to-char (match-string 2))
12311 have t))
12312 (cond
12313 ((eq action 'remove)
12314 (setq remove t new ?\ ))
12315 ((or (eq action 'set)
12316 (if (featurep 'xemacs) (characterp action) (integerp action)))
12317 (if (not (eq action 'set))
12318 (setq new action)
12319 (message "Priority %c-%c, SPC to remove: "
12320 org-highest-priority org-lowest-priority)
12321 (save-match-data
12322 (setq new (read-char-exclusive))))
12323 (if (and (= (upcase org-highest-priority) org-highest-priority)
12324 (= (upcase org-lowest-priority) org-lowest-priority))
12325 (setq new (upcase new)))
12326 (cond ((equal new ?\ ) (setq remove t))
12327 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12328 (error "Priority must be between `%c' and `%c'"
12329 org-highest-priority org-lowest-priority))))
12330 ((eq action 'up)
12331 (setq new (if have
12332 (1- current) ; normal cycling
12333 ;; last priority was empty
12334 (if (eq last-command this-command)
12335 org-lowest-priority ; wrap around empty to lowest
12336 ;; default
12337 (if org-priority-start-cycle-with-default
12338 org-default-priority
12339 (1- org-default-priority))))))
12340 ((eq action 'down)
12341 (setq new (if have
12342 (1+ current) ; normal cycling
12343 ;; last priority was empty
12344 (if (eq last-command this-command)
12345 org-highest-priority ; wrap around empty to highest
12346 ;; default
12347 (if org-priority-start-cycle-with-default
12348 org-default-priority
12349 (1+ org-default-priority))))))
12350 (t (error "Invalid action")))
12351 (if (or (< (upcase new) org-highest-priority)
12352 (> (upcase new) org-lowest-priority))
12353 (if (and (memq action '(up down))
12354 (not have) (not (eq last-command this-command)))
12355 ;; `new' is from default priority
12356 (error
12357 "The default can not be set, see `org-default-priority' why")
12358 ;; normal cycling: `new' is beyond highest/lowest priority
12359 ;; and is wrapped around to the empty priority
12360 (setq remove t)))
12361 (setq news (format "%c" new))
12362 (if have
12363 (if remove
12364 (replace-match "" t t nil 1)
12365 (replace-match news t t nil 2))
12366 (if remove
12367 (error "No priority cookie found in line")
12368 (let ((case-fold-search nil))
12369 (looking-at org-todo-line-regexp))
12370 (if (match-end 2)
12371 (progn
12372 (goto-char (match-end 2))
12373 (insert " [#" news "]"))
12374 (goto-char (match-beginning 3))
12375 (insert "[#" news "] "))))
12376 (org-preserve-lc (org-set-tags nil 'align)))
12377 (if remove
12378 (message "Priority removed")
12379 (message "Priority of current item set to %s" news))))
12381 (defun org-get-priority (s)
12382 "Find priority cookie and return priority."
12383 (if (functionp org-get-priority-function)
12384 (funcall org-get-priority-function)
12385 (save-match-data
12386 (if (not (string-match org-priority-regexp s))
12387 (* 1000 (- org-lowest-priority org-default-priority))
12388 (* 1000 (- org-lowest-priority
12389 (string-to-char (match-string 2 s))))))))
12391 ;;;; Tags
12393 (defvar org-agenda-archives-mode)
12394 (defvar org-map-continue-from nil
12395 "Position from where mapping should continue.
12396 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12398 (defvar org-scanner-tags nil
12399 "The current tag list while the tags scanner is running.")
12400 (defvar org-trust-scanner-tags nil
12401 "Should `org-get-tags-at' use the tags for the scanner.
12402 This is for internal dynamical scoping only.
12403 When this is non-nil, the function `org-get-tags-at' will return the value
12404 of `org-scanner-tags' instead of building the list by itself. This
12405 can lead to large speed-ups when the tags scanner is used in a file with
12406 many entries, and when the list of tags is retrieved, for example to
12407 obtain a list of properties. Building the tags list for each entry in such
12408 a file becomes an N^2 operation - but with this variable set, it scales
12409 as N.")
12411 (defun org-scan-tags (action matcher &optional todo-only)
12412 "Scan headline tags with inheritance and produce output ACTION.
12414 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12415 or `agenda' to produce an entry list for an agenda view. It can also be
12416 a Lisp form or a function that should be called at each matched headline, in
12417 this case the return value is a list of all return values from these calls.
12419 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12420 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12421 only lines with a TODO keyword are included in the output."
12422 (require 'org-agenda)
12423 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
12424 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12425 (org-re
12426 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12427 (props (list 'face 'default
12428 'done-face 'org-agenda-done
12429 'undone-face 'default
12430 'mouse-face 'highlight
12431 'org-not-done-regexp org-not-done-regexp
12432 'org-todo-regexp org-todo-regexp
12433 'help-echo
12434 (format "mouse-2 or RET jump to org file %s"
12435 (abbreviate-file-name
12436 (or (buffer-file-name (buffer-base-buffer))
12437 (buffer-name (buffer-base-buffer)))))))
12438 (case-fold-search nil)
12439 (org-map-continue-from nil)
12440 lspos tags tags-list
12441 (tags-alist (list (cons 0 org-file-tags)))
12442 (llast 0) rtn rtn1 level category i txt
12443 todo marker entry priority)
12444 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12445 (setq action (list 'lambda nil action)))
12446 (save-excursion
12447 (goto-char (point-min))
12448 (when (eq action 'sparse-tree)
12449 (org-overview)
12450 (org-remove-occur-highlights))
12451 (while (re-search-forward re nil t)
12452 (catch :skip
12453 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12454 tags (if (match-end 4) (org-match-string-no-properties 4)))
12455 (goto-char (setq lspos (match-beginning 0)))
12456 (setq level (org-reduced-level (funcall outline-level))
12457 category (org-get-category))
12458 (setq i llast llast level)
12459 ;; remove tag lists from same and sublevels
12460 (while (>= i level)
12461 (when (setq entry (assoc i tags-alist))
12462 (setq tags-alist (delete entry tags-alist)))
12463 (setq i (1- i)))
12464 ;; add the next tags
12465 (when tags
12466 (setq tags (org-split-string tags ":")
12467 tags-alist
12468 (cons (cons level tags) tags-alist)))
12469 ;; compile tags for current headline
12470 (setq tags-list
12471 (if org-use-tag-inheritance
12472 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12473 tags)
12474 org-scanner-tags tags-list)
12475 (when org-use-tag-inheritance
12476 (setcdr (car tags-alist)
12477 (mapcar (lambda (x)
12478 (setq x (copy-sequence x))
12479 (org-add-prop-inherited x))
12480 (cdar tags-alist))))
12481 (when (and tags org-use-tag-inheritance
12482 (or (not (eq t org-use-tag-inheritance))
12483 org-tags-exclude-from-inheritance))
12484 ;; selective inheritance, remove uninherited ones
12485 (setcdr (car tags-alist)
12486 (org-remove-uninherited-tags (cdar tags-alist))))
12487 (when (and
12489 ;; eval matcher only when the todo condition is OK
12490 (and (or (not todo-only) (member todo org-not-done-keywords))
12491 (let ((case-fold-search t)) (eval matcher)))
12493 ;; Call the skipper, but return t if it does not skip,
12494 ;; so that the `and' form continues evaluating
12495 (progn
12496 (unless (eq action 'sparse-tree) (org-agenda-skip))
12499 ;; Check if timestamps are deselecting this entry
12500 (or (not todo-only)
12501 (and (member todo org-not-done-keywords)
12502 (or (not org-agenda-tags-todo-honor-ignore-options)
12503 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12505 ;; Extra check for the archive tag
12506 ;; FIXME: Does the skipper already do this????
12508 (not (member org-archive-tag tags-list))
12509 ;; we have an archive tag, should we use this anyway?
12510 (or (not org-agenda-skip-archived-trees)
12511 (and (eq action 'agenda) org-agenda-archives-mode))))
12513 ;; select this headline
12515 (cond
12516 ((eq action 'sparse-tree)
12517 (and org-highlight-sparse-tree-matches
12518 (org-get-heading) (match-end 0)
12519 (org-highlight-new-match
12520 (match-beginning 0) (match-beginning 1)))
12521 (org-show-context 'tags-tree))
12522 ((eq action 'agenda)
12523 (setq txt (org-format-agenda-item
12525 (concat
12526 (if (eq org-tags-match-list-sublevels 'indented)
12527 (make-string (1- level) ?.) "")
12528 (org-get-heading))
12529 category
12530 tags-list
12532 priority (org-get-priority txt))
12533 (goto-char lspos)
12534 (setq marker (org-agenda-new-marker))
12535 (org-add-props txt props
12536 'org-marker marker 'org-hd-marker marker 'org-category category
12537 'todo-state todo
12538 'priority priority 'type "tagsmatch")
12539 (push txt rtn))
12540 ((functionp action)
12541 (setq org-map-continue-from nil)
12542 (save-excursion
12543 (setq rtn1 (funcall action))
12544 (push rtn1 rtn)))
12545 (t (error "Invalid action")))
12547 ;; if we are to skip sublevels, jump to end of subtree
12548 (unless org-tags-match-list-sublevels
12549 (org-end-of-subtree t)
12550 (backward-char 1))))
12551 ;; Get the correct position from where to continue
12552 (if org-map-continue-from
12553 (goto-char org-map-continue-from)
12554 (and (= (point) lspos) (end-of-line 1)))))
12555 (when (and (eq action 'sparse-tree)
12556 (not org-sparse-tree-open-archived-trees))
12557 (org-hide-archived-subtrees (point-min) (point-max)))
12558 (nreverse rtn)))
12560 (defun org-remove-uninherited-tags (tags)
12561 "Remove all tags that are not inherited from the list TAGS."
12562 (cond
12563 ((eq org-use-tag-inheritance t)
12564 (if org-tags-exclude-from-inheritance
12565 (org-delete-all org-tags-exclude-from-inheritance tags)
12566 tags))
12567 ((not org-use-tag-inheritance) nil)
12568 ((stringp org-use-tag-inheritance)
12569 (delq nil (mapcar
12570 (lambda (x)
12571 (if (and (string-match org-use-tag-inheritance x)
12572 (not (member x org-tags-exclude-from-inheritance)))
12573 x nil))
12574 tags)))
12575 ((listp org-use-tag-inheritance)
12576 (delq nil (mapcar
12577 (lambda (x)
12578 (if (member x org-use-tag-inheritance) x nil))
12579 tags)))))
12581 (defvar todo-only) ;; dynamically scoped
12583 (defun org-match-sparse-tree (&optional todo-only match)
12584 "Create a sparse tree according to tags string MATCH.
12585 MATCH can contain positive and negative selection of tags, like
12586 \"+WORK+URGENT-WITHBOSS\".
12587 If optional argument TODO-ONLY is non-nil, only select lines that are
12588 also TODO lines."
12589 (interactive "P")
12590 (org-prepare-agenda-buffers (list (current-buffer)))
12591 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12593 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12595 (defvar org-cached-props nil)
12596 (defun org-cached-entry-get (pom property)
12597 (if (or (eq t org-use-property-inheritance)
12598 (and (stringp org-use-property-inheritance)
12599 (string-match org-use-property-inheritance property))
12600 (and (listp org-use-property-inheritance)
12601 (member property org-use-property-inheritance)))
12602 ;; Caching is not possible, check it directly
12603 (org-entry-get pom property 'inherit)
12604 ;; Get all properties, so that we can do complicated checks easily
12605 (cdr (assoc property (or org-cached-props
12606 (setq org-cached-props
12607 (org-entry-properties pom)))))))
12609 (defun org-global-tags-completion-table (&optional files)
12610 "Return the list of all tags in all agenda buffer/files.
12611 Optional FILES argument is a list of files to which can be used
12612 instead of the agenda files."
12613 (save-excursion
12614 (org-uniquify
12615 (delq nil
12616 (apply 'append
12617 (mapcar
12618 (lambda (file)
12619 (set-buffer (find-file-noselect file))
12620 (append (org-get-buffer-tags)
12621 (mapcar (lambda (x) (if (stringp (car-safe x))
12622 (list (car-safe x)) nil))
12623 org-tag-alist)))
12624 (if (and files (car files))
12625 files
12626 (org-agenda-files))))))))
12628 (defun org-make-tags-matcher (match)
12629 "Create the TAGS/TODO matcher form for the selection string MATCH."
12630 ;; todo-only is scoped dynamically into this function, and the function
12631 ;; may change it if the matcher asks for it.
12632 (unless match
12633 ;; Get a new match request, with completion
12634 (let ((org-last-tags-completion-table
12635 (org-global-tags-completion-table)))
12636 (setq match (org-completing-read-no-i
12637 "Match: " 'org-tags-completion-function nil nil nil
12638 'org-tags-history))))
12640 ;; Parse the string and create a lisp form
12641 (let ((match0 match)
12642 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12643 minus tag mm
12644 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12645 orterms term orlist re-p str-p level-p level-op time-p
12646 prop-p pn pv po gv rest)
12647 (if (string-match "/+" match)
12648 ;; match contains also a todo-matching request
12649 (progn
12650 (setq tagsmatch (substring match 0 (match-beginning 0))
12651 todomatch (substring match (match-end 0)))
12652 (if (string-match "^!" todomatch)
12653 (setq todo-only t todomatch (substring todomatch 1)))
12654 (if (string-match "^\\s-*$" todomatch)
12655 (setq todomatch nil)))
12656 ;; only matching tags
12657 (setq tagsmatch match todomatch nil))
12659 ;; Make the tags matcher
12660 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12661 (setq tagsmatcher t)
12662 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12663 (while (setq term (pop orterms))
12664 (while (and (equal (substring term -1) "\\") orterms)
12665 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12666 (while (string-match re term)
12667 (setq rest (substring term (match-end 0))
12668 minus (and (match-end 1)
12669 (equal (match-string 1 term) "-"))
12670 tag (save-match-data (replace-regexp-in-string
12671 "\\\\-" "-"
12672 (match-string 2 term)))
12673 re-p (equal (string-to-char tag) ?{)
12674 level-p (match-end 4)
12675 prop-p (match-end 5)
12676 mm (cond
12677 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12678 (level-p
12679 (setq level-op (org-op-to-function (match-string 3 term)))
12680 `(,level-op level ,(string-to-number
12681 (match-string 4 term))))
12682 (prop-p
12683 (setq pn (match-string 5 term)
12684 po (match-string 6 term)
12685 pv (match-string 7 term)
12686 re-p (equal (string-to-char pv) ?{)
12687 str-p (equal (string-to-char pv) ?\")
12688 time-p (save-match-data
12689 (string-match "^\"[[<].*[]>]\"$" pv))
12690 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12691 (if time-p (setq pv (org-matcher-time pv)))
12692 (setq po (org-op-to-function po (if time-p 'time str-p)))
12693 (cond
12694 ((equal pn "CATEGORY")
12695 (setq gv '(get-text-property (point) 'org-category)))
12696 ((equal pn "TODO")
12697 (setq gv 'todo))
12699 (setq gv `(org-cached-entry-get nil ,pn))))
12700 (if re-p
12701 (if (eq po 'org<>)
12702 `(not (string-match ,pv (or ,gv "")))
12703 `(string-match ,pv (or ,gv "")))
12704 (if str-p
12705 `(,po (or ,gv "") ,pv)
12706 `(,po (string-to-number (or ,gv ""))
12707 ,(string-to-number pv) ))))
12708 (t `(member ,tag tags-list)))
12709 mm (if minus (list 'not mm) mm)
12710 term rest)
12711 (push mm tagsmatcher))
12712 (push (if (> (length tagsmatcher) 1)
12713 (cons 'and tagsmatcher)
12714 (car tagsmatcher))
12715 orlist)
12716 (setq tagsmatcher nil))
12717 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12718 (setq tagsmatcher
12719 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12720 ;; Make the todo matcher
12721 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12722 (setq todomatcher t)
12723 (setq orterms (org-split-string todomatch "|") orlist nil)
12724 (while (setq term (pop orterms))
12725 (while (string-match re term)
12726 (setq minus (and (match-end 1)
12727 (equal (match-string 1 term) "-"))
12728 kwd (match-string 2 term)
12729 re-p (equal (string-to-char kwd) ?{)
12730 term (substring term (match-end 0))
12731 mm (if re-p
12732 `(string-match ,(substring kwd 1 -1) todo)
12733 (list 'equal 'todo kwd))
12734 mm (if minus (list 'not mm) mm))
12735 (push mm todomatcher))
12736 (push (if (> (length todomatcher) 1)
12737 (cons 'and todomatcher)
12738 (car todomatcher))
12739 orlist)
12740 (setq todomatcher nil))
12741 (setq todomatcher (if (> (length orlist) 1)
12742 (cons 'or orlist) (car orlist))))
12744 ;; Return the string and lisp forms of the matcher
12745 (setq matcher (if todomatcher
12746 (list 'and tagsmatcher todomatcher)
12747 tagsmatcher))
12748 (cons match0 matcher)))
12750 (defun org-op-to-function (op &optional stringp)
12751 "Turn an operator into the appropriate function."
12752 (setq op
12753 (cond
12754 ((equal op "<" ) '(< string< org-time<))
12755 ((equal op ">" ) '(> org-string> org-time>))
12756 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12757 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12758 ((member op '("=" "==")) '(= string= org-time=))
12759 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12760 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12762 (defun org<> (a b) (not (= a b)))
12763 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12764 (defun org-string>= (a b) (not (string< a b)))
12765 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12766 (defun org-string<> (a b) (not (string= a b)))
12767 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
12768 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
12769 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
12770 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
12771 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
12772 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12773 (defun org-2ft (s)
12774 "Convert S to a floating point time.
12775 If S is already a number, just return it. If it is a string, parse
12776 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12777 (cond
12778 ((numberp s) s)
12779 ((stringp s)
12780 (condition-case nil
12781 (float-time (apply 'encode-time (org-parse-time-string s)))
12782 (error 0.)))
12783 (t 0.)))
12785 (defun org-time-today ()
12786 "Time in seconds today at 0:00.
12787 Returns the float number of seconds since the beginning of the
12788 epoch to the beginning of today (00:00)."
12789 (float-time (apply 'encode-time
12790 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12792 (defun org-matcher-time (s)
12793 "Interpret a time comparison value."
12794 (save-match-data
12795 (cond
12796 ((string= s "<now>") (float-time))
12797 ((string= s "<today>") (org-time-today))
12798 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12799 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12800 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12801 (+ (org-time-today)
12802 (* (string-to-number (match-string 1 s))
12803 (cdr (assoc (match-string 2 s)
12804 '(("d" . 86400.0) ("w" . 604800.0)
12805 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12806 (t (org-2ft s)))))
12808 (defun org-match-any-p (re list)
12809 "Does re match any element of list?"
12810 (setq list (mapcar (lambda (x) (string-match re x)) list))
12811 (delq nil list))
12813 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12814 (defvar org-tags-overlay (make-overlay 1 1))
12815 (org-detach-overlay org-tags-overlay)
12817 (defun org-get-local-tags-at (&optional pos)
12818 "Get a list of tags defined in the current headline."
12819 (org-get-tags-at pos 'local))
12821 (defun org-get-local-tags ()
12822 "Get a list of tags defined in the current headline."
12823 (org-get-tags-at nil 'local))
12825 (defun org-get-tags-at (&optional pos local)
12826 "Get a list of all headline tags applicable at POS.
12827 POS defaults to point. If tags are inherited, the list contains
12828 the targets in the same sequence as the headlines appear, i.e.
12829 the tags of the current headline come last.
12830 When LOCAL is non-nil, only return tags from the current headline,
12831 ignore inherited ones."
12832 (interactive)
12833 (if (and org-trust-scanner-tags
12834 (or (not pos) (equal pos (point)))
12835 (not local))
12836 org-scanner-tags
12837 (let (tags ltags lastpos parent)
12838 (save-excursion
12839 (save-restriction
12840 (widen)
12841 (goto-char (or pos (point)))
12842 (save-match-data
12843 (catch 'done
12844 (condition-case nil
12845 (progn
12846 (org-back-to-heading t)
12847 (while (not (equal lastpos (point)))
12848 (setq lastpos (point))
12849 (when (looking-at
12850 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
12851 (setq ltags (org-split-string
12852 (org-match-string-no-properties 1) ":"))
12853 (when parent
12854 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12855 (setq tags (append
12856 (if parent
12857 (org-remove-uninherited-tags ltags)
12858 ltags)
12859 tags)))
12860 (or org-use-tag-inheritance (throw 'done t))
12861 (if local (throw 'done t))
12862 (or (org-up-heading-safe) (error nil))
12863 (setq parent t)))
12864 (error nil)))))
12865 (if local
12866 tags
12867 (append (org-remove-uninherited-tags org-file-tags) tags))))))
12869 (defun org-add-prop-inherited (s)
12870 (add-text-properties 0 (length s) '(inherited t) s)
12873 (defun org-toggle-tag (tag &optional onoff)
12874 "Toggle the tag TAG for the current line.
12875 If ONOFF is `on' or `off', don't toggle but set to this state."
12876 (let (res current)
12877 (save-excursion
12878 (org-back-to-heading t)
12879 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
12880 (point-at-eol) t)
12881 (progn
12882 (setq current (match-string 1))
12883 (replace-match ""))
12884 (setq current ""))
12885 (setq current (nreverse (org-split-string current ":")))
12886 (cond
12887 ((eq onoff 'on)
12888 (setq res t)
12889 (or (member tag current) (push tag current)))
12890 ((eq onoff 'off)
12891 (or (not (member tag current)) (setq current (delete tag current))))
12892 (t (if (member tag current)
12893 (setq current (delete tag current))
12894 (setq res t)
12895 (push tag current))))
12896 (end-of-line 1)
12897 (if current
12898 (progn
12899 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12900 (org-set-tags nil t))
12901 (delete-horizontal-space))
12902 (run-hooks 'org-after-tags-change-hook))
12903 res))
12905 (defun org-align-tags-here (to-col)
12906 ;; Assumes that this is a headline
12907 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12908 (beginning-of-line 1)
12909 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
12910 (< pos (match-beginning 2)))
12911 (progn
12912 (setq tags-l (- (match-end 2) (match-beginning 2)))
12913 (goto-char (match-beginning 1))
12914 (insert " ")
12915 (delete-region (point) (1+ (match-beginning 2)))
12916 (setq ncol (max (1+ (current-column))
12917 (1+ col)
12918 (if (> to-col 0)
12919 to-col
12920 (- (abs to-col) tags-l))))
12921 (setq p (point))
12922 (insert (make-string (- ncol (current-column)) ?\ ))
12923 (setq ncol (current-column))
12924 (when indent-tabs-mode (tabify p (point-at-eol)))
12925 (org-move-to-column (min ncol col) t))
12926 (goto-char pos))))
12928 (defun org-set-tags-command (&optional arg just-align)
12929 "Call the set-tags command for the current entry."
12930 (interactive "P")
12931 (if (org-on-heading-p)
12932 (org-set-tags arg just-align)
12933 (save-excursion
12934 (org-back-to-heading t)
12935 (org-set-tags arg just-align))))
12937 (defun org-set-tags-to (data)
12938 "Set the tags of the current entry to DATA, replacing the current tags.
12939 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12940 If DATA is nil or the empty string, any tags will be removed."
12941 (interactive "sTags: ")
12942 (setq data
12943 (cond
12944 ((eq data nil) "")
12945 ((equal data "") "")
12946 ((stringp data)
12947 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12948 ":"))
12949 ((listp data)
12950 (concat ":" (mapconcat 'identity data ":") ":"))
12951 (t nil)))
12952 (when data
12953 (save-excursion
12954 (org-back-to-heading t)
12955 (when (looking-at org-complex-heading-regexp)
12956 (if (match-end 5)
12957 (progn
12958 (goto-char (match-beginning 5))
12959 (insert data)
12960 (delete-region (point) (point-at-eol))
12961 (org-set-tags nil 'align))
12962 (goto-char (point-at-eol))
12963 (insert " " data)
12964 (org-set-tags nil 'align)))
12965 (beginning-of-line 1)
12966 (if (looking-at ".*?\\([ \t]+\\)$")
12967 (delete-region (match-beginning 1) (match-end 1))))))
12969 (defun org-align-all-tags ()
12970 "Align the tags i all headings."
12971 (interactive)
12972 (save-excursion
12973 (or (ignore-errors (org-back-to-heading t))
12974 (outline-next-heading))
12975 (if (org-on-heading-p)
12976 (org-set-tags t)
12977 (message "No headings"))))
12979 (defvar org-indent-indentation-per-level)
12980 (defun org-set-tags (&optional arg just-align)
12981 "Set the tags for the current headline.
12982 With prefix ARG, realign all tags in headings in the current buffer."
12983 (interactive "P")
12984 (let* ((re (concat "^" outline-regexp))
12985 (current (org-get-tags-string))
12986 (col (current-column))
12987 (org-setting-tags t)
12988 table current-tags inherited-tags ; computed below when needed
12989 tags p0 c0 c1 rpl di tc level)
12990 (if arg
12991 (save-excursion
12992 (goto-char (point-min))
12993 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12994 (while (re-search-forward re nil t)
12995 (org-set-tags nil t)
12996 (end-of-line 1)))
12997 (message "All tags realigned to column %d" org-tags-column))
12998 (if just-align
12999 (setq tags current)
13000 ;; Get a new set of tags from the user
13001 (save-excursion
13002 (setq table (append org-tag-persistent-alist
13003 (or org-tag-alist (org-get-buffer-tags))
13004 (and
13005 org-complete-tags-always-offer-all-agenda-tags
13006 (org-global-tags-completion-table
13007 (org-agenda-files))))
13008 org-last-tags-completion-table table
13009 current-tags (org-split-string current ":")
13010 inherited-tags (nreverse
13011 (nthcdr (length current-tags)
13012 (nreverse (org-get-tags-at))))
13013 tags
13014 (if (or (eq t org-use-fast-tag-selection)
13015 (and org-use-fast-tag-selection
13016 (delq nil (mapcar 'cdr table))))
13017 (org-fast-tag-selection
13018 current-tags inherited-tags table
13019 (if org-fast-tag-selection-include-todo
13020 org-todo-key-alist))
13021 (let ((org-add-colon-after-tag-completion t))
13022 (org-trim
13023 (org-icompleting-read "Tags: "
13024 'org-tags-completion-function
13025 nil nil current 'org-tags-history))))))
13026 (while (string-match "[-+&]+" tags)
13027 ;; No boolean logic, just a list
13028 (setq tags (replace-match ":" t t tags))))
13030 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13032 (if org-tags-sort-function
13033 (setq tags (mapconcat 'identity
13034 (sort (org-split-string
13035 tags (org-re "[^[:alnum:]_@#%]+"))
13036 org-tags-sort-function) ":")))
13038 (if (string-match "\\`[\t ]*\\'" tags)
13039 (setq tags "")
13040 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13041 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13043 ;; Insert new tags at the correct column
13044 (beginning-of-line 1)
13045 (setq level (or (and (looking-at org-outline-regexp)
13046 (- (match-end 0) (point) 1))
13048 (cond
13049 ((and (equal current "") (equal tags "")))
13050 ((re-search-forward
13051 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13052 (point-at-eol) t)
13053 (if (equal tags "")
13054 (setq rpl "")
13055 (goto-char (match-beginning 0))
13056 (setq c0 (current-column)
13057 ;; compute offset for the case of org-indent-mode active
13058 di (if org-indent-mode
13059 (* (1- org-indent-indentation-per-level) (1- level))
13061 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13062 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13063 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13064 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13065 (replace-match rpl t t)
13066 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13067 tags)
13068 (t (error "Tags alignment failed")))
13069 (org-move-to-column col)
13070 (unless just-align
13071 (run-hooks 'org-after-tags-change-hook)))))
13073 (defun org-change-tag-in-region (beg end tag off)
13074 "Add or remove TAG for each entry in the region.
13075 This works in the agenda, and also in an org-mode buffer."
13076 (interactive
13077 (list (region-beginning) (region-end)
13078 (let ((org-last-tags-completion-table
13079 (if (org-mode-p)
13080 (org-get-buffer-tags)
13081 (org-global-tags-completion-table))))
13082 (org-icompleting-read
13083 "Tag: " 'org-tags-completion-function nil nil nil
13084 'org-tags-history))
13085 (progn
13086 (message "[s]et or [r]emove? ")
13087 (equal (read-char-exclusive) ?r))))
13088 (if (fboundp 'deactivate-mark) (deactivate-mark))
13089 (let ((agendap (equal major-mode 'org-agenda-mode))
13090 l1 l2 m buf pos newhead (cnt 0))
13091 (goto-char end)
13092 (setq l2 (1- (org-current-line)))
13093 (goto-char beg)
13094 (setq l1 (org-current-line))
13095 (loop for l from l1 to l2 do
13096 (org-goto-line l)
13097 (setq m (get-text-property (point) 'org-hd-marker))
13098 (when (or (and (org-mode-p) (org-on-heading-p))
13099 (and agendap m))
13100 (setq buf (if agendap (marker-buffer m) (current-buffer))
13101 pos (if agendap m (point)))
13102 (with-current-buffer buf
13103 (save-excursion
13104 (save-restriction
13105 (goto-char pos)
13106 (setq cnt (1+ cnt))
13107 (org-toggle-tag tag (if off 'off 'on))
13108 (setq newhead (org-get-heading)))))
13109 (and agendap (org-agenda-change-all-lines newhead m))))
13110 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13112 (defun org-tags-completion-function (string predicate &optional flag)
13113 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13114 (confirm (lambda (x) (stringp (car x)))))
13115 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13116 (setq s1 (match-string 1 string)
13117 s2 (match-string 2 string))
13118 (setq s1 "" s2 string))
13119 (cond
13120 ((eq flag nil)
13121 ;; try completion
13122 (setq rtn (try-completion s2 ctable confirm))
13123 (if (stringp rtn)
13124 (setq rtn
13125 (concat s1 s2 (substring rtn (length s2))
13126 (if (and org-add-colon-after-tag-completion
13127 (assoc rtn ctable))
13128 ":" ""))))
13129 rtn)
13130 ((eq flag t)
13131 ;; all-completions
13132 (all-completions s2 ctable confirm)
13134 ((eq flag 'lambda)
13135 ;; exact match?
13136 (assoc s2 ctable)))
13139 (defun org-fast-tag-insert (kwd tags face &optional end)
13140 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13141 (insert (format "%-12s" (concat kwd ":"))
13142 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13143 (or end "")))
13145 (defun org-fast-tag-show-exit (flag)
13146 (save-excursion
13147 (org-goto-line 3)
13148 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13149 (replace-match ""))
13150 (when flag
13151 (end-of-line 1)
13152 (org-move-to-column (- (window-width) 19) t)
13153 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13155 (defun org-set-current-tags-overlay (current prefix)
13156 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13157 (if (featurep 'xemacs)
13158 (org-overlay-display org-tags-overlay (concat prefix s)
13159 'secondary-selection)
13160 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13161 (org-overlay-display org-tags-overlay (concat prefix s)))))
13163 (defvar org-last-tag-selection-key nil)
13164 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13165 "Fast tag selection with single keys.
13166 CURRENT is the current list of tags in the headline, INHERITED is the
13167 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13168 possibly with grouping information. TODO-TABLE is a similar table with
13169 TODO keywords, should these have keys assigned to them.
13170 If the keys are nil, a-z are automatically assigned.
13171 Returns the new tags string, or nil to not change the current settings."
13172 (let* ((fulltable (append table todo-table))
13173 (maxlen (apply 'max (mapcar
13174 (lambda (x)
13175 (if (stringp (car x)) (string-width (car x)) 0))
13176 fulltable)))
13177 (buf (current-buffer))
13178 (expert (eq org-fast-tag-selection-single-key 'expert))
13179 (buffer-tags nil)
13180 (fwidth (+ maxlen 3 1 3))
13181 (ncol (/ (- (window-width) 4) fwidth))
13182 (i-face 'org-done)
13183 (c-face 'org-todo)
13184 tg cnt e c char c1 c2 ntable tbl rtn
13185 ov-start ov-end ov-prefix
13186 (exit-after-next org-fast-tag-selection-single-key)
13187 (done-keywords org-done-keywords)
13188 groups ingroup)
13189 (save-excursion
13190 (beginning-of-line 1)
13191 (if (looking-at
13192 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13193 (setq ov-start (match-beginning 1)
13194 ov-end (match-end 1)
13195 ov-prefix "")
13196 (setq ov-start (1- (point-at-eol))
13197 ov-end (1+ ov-start))
13198 (skip-chars-forward "^\n\r")
13199 (setq ov-prefix
13200 (concat
13201 (buffer-substring (1- (point)) (point))
13202 (if (> (current-column) org-tags-column)
13204 (make-string (- org-tags-column (current-column)) ?\ ))))))
13205 (move-overlay org-tags-overlay ov-start ov-end)
13206 (save-window-excursion
13207 (if expert
13208 (set-buffer (get-buffer-create " *Org tags*"))
13209 (delete-other-windows)
13210 (split-window-vertically)
13211 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13212 (erase-buffer)
13213 (org-set-local 'org-done-keywords done-keywords)
13214 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13215 (org-fast-tag-insert "Current" current c-face "\n\n")
13216 (org-fast-tag-show-exit exit-after-next)
13217 (org-set-current-tags-overlay current ov-prefix)
13218 (setq tbl fulltable char ?a cnt 0)
13219 (while (setq e (pop tbl))
13220 (cond
13221 ((equal (car e) :startgroup)
13222 (push '() groups) (setq ingroup t)
13223 (when (not (= cnt 0))
13224 (setq cnt 0)
13225 (insert "\n"))
13226 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13227 ((equal (car e) :endgroup)
13228 (setq ingroup nil cnt 0)
13229 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13230 ((equal e '(:newline))
13231 (when (not (= cnt 0))
13232 (setq cnt 0)
13233 (insert "\n")
13234 (setq e (car tbl))
13235 (while (equal (car tbl) '(:newline))
13236 (insert "\n")
13237 (setq tbl (cdr tbl)))))
13239 (setq tg (copy-sequence (car e)) c2 nil)
13240 (if (cdr e)
13241 (setq c (cdr e))
13242 ;; automatically assign a character.
13243 (setq c1 (string-to-char
13244 (downcase (substring
13245 tg (if (= (string-to-char tg) ?@) 1 0)))))
13246 (if (or (rassoc c1 ntable) (rassoc c1 table))
13247 (while (or (rassoc char ntable) (rassoc char table))
13248 (setq char (1+ char)))
13249 (setq c2 c1))
13250 (setq c (or c2 char)))
13251 (if ingroup (push tg (car groups)))
13252 (setq tg (org-add-props tg nil 'face
13253 (cond
13254 ((not (assoc tg table))
13255 (org-get-todo-face tg))
13256 ((member tg current) c-face)
13257 ((member tg inherited) i-face)
13258 (t nil))))
13259 (if (and (= cnt 0) (not ingroup)) (insert " "))
13260 (insert "[" c "] " tg (make-string
13261 (- fwidth 4 (length tg)) ?\ ))
13262 (push (cons tg c) ntable)
13263 (when (= (setq cnt (1+ cnt)) ncol)
13264 (insert "\n")
13265 (if ingroup (insert " "))
13266 (setq cnt 0)))))
13267 (setq ntable (nreverse ntable))
13268 (insert "\n")
13269 (goto-char (point-min))
13270 (if (not expert) (org-fit-window-to-buffer))
13271 (setq rtn
13272 (catch 'exit
13273 (while t
13274 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13275 (if (not groups) "no " "")
13276 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13277 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13278 (setq org-last-tag-selection-key c)
13279 (cond
13280 ((= c ?\r) (throw 'exit t))
13281 ((= c ?!)
13282 (setq groups (not groups))
13283 (goto-char (point-min))
13284 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13285 ((= c ?\C-c)
13286 (if (not expert)
13287 (org-fast-tag-show-exit
13288 (setq exit-after-next (not exit-after-next)))
13289 (setq expert nil)
13290 (delete-other-windows)
13291 (set-window-buffer (split-window-vertically) " *Org tags*")
13292 (org-switch-to-buffer-other-window " *Org tags*")
13293 (org-fit-window-to-buffer)))
13294 ((or (= c ?\C-g)
13295 (and (= c ?q) (not (rassoc c ntable))))
13296 (org-detach-overlay org-tags-overlay)
13297 (setq quit-flag t))
13298 ((= c ?\ )
13299 (setq current nil)
13300 (if exit-after-next (setq exit-after-next 'now)))
13301 ((= c ?\t)
13302 (condition-case nil
13303 (setq tg (org-icompleting-read
13304 "Tag: "
13305 (or buffer-tags
13306 (with-current-buffer buf
13307 (org-get-buffer-tags)))))
13308 (quit (setq tg "")))
13309 (when (string-match "\\S-" tg)
13310 (add-to-list 'buffer-tags (list tg))
13311 (if (member tg current)
13312 (setq current (delete tg current))
13313 (push tg current)))
13314 (if exit-after-next (setq exit-after-next 'now)))
13315 ((setq e (rassoc c todo-table) tg (car e))
13316 (with-current-buffer buf
13317 (save-excursion (org-todo tg)))
13318 (if exit-after-next (setq exit-after-next 'now)))
13319 ((setq e (rassoc c ntable) tg (car e))
13320 (if (member tg current)
13321 (setq current (delete tg current))
13322 (loop for g in groups do
13323 (if (member tg g)
13324 (mapc (lambda (x)
13325 (setq current (delete x current)))
13326 g)))
13327 (push tg current))
13328 (if exit-after-next (setq exit-after-next 'now))))
13330 ;; Create a sorted list
13331 (setq current
13332 (sort current
13333 (lambda (a b)
13334 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13335 (if (eq exit-after-next 'now) (throw 'exit t))
13336 (goto-char (point-min))
13337 (beginning-of-line 2)
13338 (delete-region (point) (point-at-eol))
13339 (org-fast-tag-insert "Current" current c-face)
13340 (org-set-current-tags-overlay current ov-prefix)
13341 (while (re-search-forward
13342 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13343 (setq tg (match-string 1))
13344 (add-text-properties
13345 (match-beginning 1) (match-end 1)
13346 (list 'face
13347 (cond
13348 ((member tg current) c-face)
13349 ((member tg inherited) i-face)
13350 (t (get-text-property (match-beginning 1) 'face))))))
13351 (goto-char (point-min)))))
13352 (org-detach-overlay org-tags-overlay)
13353 (if rtn
13354 (mapconcat 'identity current ":")
13355 nil))))
13357 (defun org-get-tags-string ()
13358 "Get the TAGS string in the current headline."
13359 (unless (org-on-heading-p t)
13360 (error "Not on a heading"))
13361 (save-excursion
13362 (beginning-of-line 1)
13363 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13364 (org-match-string-no-properties 1)
13365 "")))
13367 (defun org-get-tags ()
13368 "Get the list of tags specified in the current headline."
13369 (org-split-string (org-get-tags-string) ":"))
13371 (defun org-get-buffer-tags ()
13372 "Get a table of all tags used in the buffer, for completion."
13373 (let (tags)
13374 (save-excursion
13375 (goto-char (point-min))
13376 (while (re-search-forward
13377 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13378 (when (equal (char-after (point-at-bol 0)) ?*)
13379 (mapc (lambda (x) (add-to-list 'tags x))
13380 (org-split-string (org-match-string-no-properties 1) ":")))))
13381 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13382 (mapcar 'list tags)))
13384 ;;;; The mapping API
13386 ;;;###autoload
13387 (defun org-map-entries (func &optional match scope &rest skip)
13388 "Call FUNC at each headline selected by MATCH in SCOPE.
13390 FUNC is a function or a lisp form. The function will be called without
13391 arguments, with the cursor positioned at the beginning of the headline.
13392 The return values of all calls to the function will be collected and
13393 returned as a list.
13395 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13396 does not need to preserve point. After evaluation, the cursor will be
13397 moved to the end of the line (presumably of the headline of the
13398 processed entry) and search continues from there. Under some
13399 circumstances, this may not produce the wanted results. For example,
13400 if you have removed (e.g. archived) the current (sub)tree it could
13401 mean that the next entry will be skipped entirely. In such cases, you
13402 can specify the position from where search should continue by making
13403 FUNC set the variable `org-map-continue-from' to the desired buffer
13404 position.
13406 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13407 Only headlines that are matched by this query will be considered during
13408 the iteration. When MATCH is nil or t, all headlines will be
13409 visited by the iteration.
13411 SCOPE determines the scope of this command. It can be any of:
13413 nil The current buffer, respecting the restriction if any
13414 tree The subtree started with the entry at point
13415 file The current buffer, without restriction
13416 file-with-archives
13417 The current buffer, and any archives associated with it
13418 agenda All agenda files
13419 agenda-with-archives
13420 All agenda files with any archive files associated with them
13421 \(file1 file2 ...)
13422 If this is a list, all files in the list will be scanned
13424 The remaining args are treated as settings for the skipping facilities of
13425 the scanner. The following items can be given here:
13427 archive skip trees with the archive tag.
13428 comment skip trees with the COMMENT keyword
13429 function or Emacs Lisp form:
13430 will be used as value for `org-agenda-skip-function', so whenever
13431 the function returns t, FUNC will not be called for that
13432 entry and search will continue from the point where the
13433 function leaves it.
13435 If your function needs to retrieve the tags including inherited tags
13436 at the *current* entry, you can use the value of the variable
13437 `org-scanner-tags' which will be much faster than getting the value
13438 with `org-get-tags-at'. If your function gets properties with
13439 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13440 to t around the call to `org-entry-properties' to get the same speedup.
13441 Note that if your function moves around to retrieve tags and properties at
13442 a *different* entry, you cannot use these techniques."
13443 (let* ((org-agenda-archives-mode nil) ; just to make sure
13444 (org-agenda-skip-archived-trees (memq 'archive skip))
13445 (org-agenda-skip-comment-trees (memq 'comment skip))
13446 (org-agenda-skip-function
13447 (car (org-delete-all '(comment archive) skip)))
13448 (org-tags-match-list-sublevels t)
13449 matcher file res
13450 org-todo-keywords-for-agenda
13451 org-done-keywords-for-agenda
13452 org-todo-keyword-alist-for-agenda
13453 org-drawers-for-agenda
13454 org-tag-alist-for-agenda)
13456 (cond
13457 ((eq match t) (setq matcher t))
13458 ((eq match nil) (setq matcher t))
13459 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13461 (save-excursion
13462 (save-restriction
13463 (when (eq scope 'tree)
13464 (org-back-to-heading t)
13465 (org-narrow-to-subtree)
13466 (setq scope nil))
13468 (if (not scope)
13469 (progn
13470 (org-prepare-agenda-buffers
13471 (list (buffer-file-name (current-buffer))))
13472 (setq res (org-scan-tags func matcher)))
13473 ;; Get the right scope
13474 (cond
13475 ((and scope (listp scope) (symbolp (car scope)))
13476 (setq scope (eval scope)))
13477 ((eq scope 'agenda)
13478 (setq scope (org-agenda-files t)))
13479 ((eq scope 'agenda-with-archives)
13480 (setq scope (org-agenda-files t))
13481 (setq scope (org-add-archive-files scope)))
13482 ((eq scope 'file)
13483 (setq scope (list (buffer-file-name))))
13484 ((eq scope 'file-with-archives)
13485 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13486 (org-prepare-agenda-buffers scope)
13487 (while (setq file (pop scope))
13488 (with-current-buffer (org-find-base-buffer-visiting file)
13489 (save-excursion
13490 (save-restriction
13491 (widen)
13492 (goto-char (point-min))
13493 (setq res (append res (org-scan-tags func matcher))))))))))
13494 res))
13496 ;;;; Properties
13498 ;;; Setting and retrieving properties
13500 (defconst org-special-properties
13501 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13502 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13503 "The special properties valid in Org-mode.
13505 These are properties that are not defined in the property drawer,
13506 but in some other way.")
13508 (defconst org-default-properties
13509 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13510 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13511 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13512 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13513 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13514 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13515 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13516 "Some properties that are used by Org-mode for various purposes.
13517 Being in this list makes sure that they are offered for completion.")
13519 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13520 "Regular expression matching the first line of a property drawer.")
13522 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13523 "Regular expression matching the last line of a property drawer.")
13525 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13526 "Regular expression matching the first line of a property drawer.")
13528 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13529 "Regular expression matching the first line of a property drawer.")
13531 (defconst org-property-drawer-re
13532 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13533 org-property-end-re "\\)\n?")
13534 "Matches an entire property drawer.")
13536 (defconst org-clock-drawer-re
13537 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13538 org-property-end-re "\\)\n?")
13539 "Matches an entire clock drawer.")
13541 (defsubst org-re-property (property)
13542 "Return a regexp matching PROPERTY.
13543 Match group 1 will be set to the value "
13544 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13546 (defun org-property-action ()
13547 "Do an action on properties."
13548 (interactive)
13549 (let (c)
13550 (org-at-property-p)
13551 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13552 (setq c (read-char-exclusive))
13553 (cond
13554 ((equal c ?s)
13555 (call-interactively 'org-set-property))
13556 ((equal c ?d)
13557 (call-interactively 'org-delete-property))
13558 ((equal c ?D)
13559 (call-interactively 'org-delete-property-globally))
13560 ((equal c ?c)
13561 (call-interactively 'org-compute-property-at-point))
13562 (t (error "No such property action %c" c)))))
13564 (defun org-set-effort (&optional value)
13565 "Set the effort property of the current entry.
13566 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13567 allowed value."
13568 (interactive "P")
13569 (if (equal value 0) (setq value 10))
13570 (let* ((completion-ignore-case t)
13571 (prop org-effort-property)
13572 (cur (org-entry-get nil prop))
13573 (allowed (org-property-get-allowed-values nil prop 'table))
13574 (existing (mapcar 'list (org-property-values prop)))
13576 (val (cond
13577 ((stringp value) value)
13578 ((and allowed (integerp value))
13579 (or (car (nth (1- value) allowed))
13580 (car (org-last allowed))))
13581 (allowed
13582 (message "Select 1-9,0, [RET%s]: %s"
13583 (if cur (concat "=" cur) "")
13584 (mapconcat 'car allowed " "))
13585 (setq rpl (read-char-exclusive))
13586 (if (equal rpl ?\r)
13588 (setq rpl (- rpl ?0))
13589 (if (equal rpl 0) (setq rpl 10))
13590 (if (and (> rpl 0) (<= rpl (length allowed)))
13591 (car (nth (1- rpl) allowed))
13592 (org-completing-read "Effort: " allowed nil))))
13594 (let (org-completion-use-ido org-completion-use-iswitchb)
13595 (org-completing-read
13596 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13597 (concat "[" cur "]") "")
13598 ": ")
13599 existing nil nil "" nil cur))))))
13600 (unless (equal (org-entry-get nil prop) val)
13601 (org-entry-put nil prop val))
13602 (message "%s is now %s" prop val)))
13604 (defun org-at-property-p ()
13605 "Is cursor inside a property drawer?"
13606 (save-excursion
13607 (beginning-of-line 1)
13608 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13609 (save-match-data ;; Used by calling procedures
13610 (let ((p (point))
13611 (range (unless (org-before-first-heading-p)
13612 (org-get-property-block))))
13613 (and range (<= (car range) p) (< p (cdr range))))))))
13615 (defun org-get-property-block (&optional beg end force)
13616 "Return the (beg . end) range of the body of the property drawer.
13617 BEG and END can be beginning and end of subtree, if not given
13618 they will be found.
13619 If the drawer does not exist and FORCE is non-nil, create the drawer."
13620 (catch 'exit
13621 (save-excursion
13622 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13623 (end (or end (progn (outline-next-heading) (point)))))
13624 (goto-char beg)
13625 (if (re-search-forward org-property-start-re end t)
13626 (setq beg (1+ (match-end 0)))
13627 (if force
13628 (save-excursion
13629 (org-insert-property-drawer)
13630 (setq end (progn (outline-next-heading) (point))))
13631 (throw 'exit nil))
13632 (goto-char beg)
13633 (if (re-search-forward org-property-start-re end t)
13634 (setq beg (1+ (match-end 0)))))
13635 (if (re-search-forward org-property-end-re end t)
13636 (setq end (match-beginning 0))
13637 (or force (throw 'exit nil))
13638 (goto-char beg)
13639 (setq end beg)
13640 (org-indent-line-function)
13641 (insert ":END:\n"))
13642 (cons beg end)))))
13644 (defun org-entry-properties (&optional pom which specific)
13645 "Get all properties of the entry at point-or-marker POM.
13646 This includes the TODO keyword, the tags, time strings for deadline,
13647 scheduled, and clocking, and any additional properties defined in the
13648 entry. The return value is an alist, keys may occur multiple times
13649 if the property key was used several times.
13650 POM may also be nil, in which case the current entry is used.
13651 If WHICH is nil or `all', get all properties. If WHICH is
13652 `special' or `standard', only get that subclass. If WHICH
13653 is a string only get exactly this property. SPECIFIC can be a string, the
13654 specific property we are interested in. Specifying it can speed
13655 things up because then unnecessary parsing is avoided."
13656 (setq which (or which 'all))
13657 (org-with-point-at pom
13658 (let ((clockstr (substring org-clock-string 0 -1))
13659 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13660 (case-fold-search nil)
13661 beg end range props sum-props key key1 value string clocksum)
13662 (save-excursion
13663 (when (condition-case nil
13664 (and (org-mode-p) (org-back-to-heading t))
13665 (error nil))
13666 (setq beg (point))
13667 (setq sum-props (get-text-property (point) 'org-summaries))
13668 (setq clocksum (get-text-property (point) :org-clock-minutes))
13669 (outline-next-heading)
13670 (setq end (point))
13671 (when (memq which '(all special))
13672 ;; Get the special properties, like TODO and tags
13673 (goto-char beg)
13674 (when (and (or (not specific) (string= specific "TODO"))
13675 (looking-at org-todo-line-regexp) (match-end 2))
13676 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13677 (when (and (or (not specific) (string= specific "PRIORITY"))
13678 (looking-at org-priority-regexp))
13679 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13680 (when (or (not specific) (string= specific "FILE"))
13681 (push (cons "FILE" buffer-file-name) props))
13682 (when (and (or (not specific) (string= specific "TAGS"))
13683 (setq value (org-get-tags-string))
13684 (string-match "\\S-" value))
13685 (push (cons "TAGS" value) props))
13686 (when (and (or (not specific) (string= specific "ALLTAGS"))
13687 (setq value (org-get-tags-at)))
13688 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13689 ":"))
13690 props))
13691 (when (or (not specific) (string= specific "BLOCKED"))
13692 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13693 (when (or (not specific)
13694 (member specific
13695 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13696 "TIMESTAMP" "TIMESTAMP_IA")))
13697 (catch 'match
13698 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13699 (setq key (if (match-end 1)
13700 (substring (org-match-string-no-properties 1)
13701 0 -1))
13702 string (if (equal key clockstr)
13703 (org-no-properties
13704 (org-trim
13705 (buffer-substring
13706 (match-beginning 3) (goto-char
13707 (point-at-eol)))))
13708 (substring (org-match-string-no-properties 3)
13709 1 -1)))
13710 ;; Get the correct property name from the key. This is
13711 ;; necessary if the user has configured time keywords.
13712 (setq key1 (concat key ":"))
13713 (cond
13714 ((not key)
13715 (setq key
13716 (if (= (char-after (match-beginning 3)) ?\[)
13717 "TIMESTAMP_IA" "TIMESTAMP")))
13718 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
13719 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
13720 ((equal key1 org-closed-string) (setq key "CLOSED"))
13721 ((equal key1 org-clock-string) (setq key "CLOCK")))
13722 (if (and specific (equal key specific) (not (equal key "CLOCK")))
13723 (progn
13724 (push (cons key string) props)
13725 ;; no need to search further if match is found
13726 (throw 'match t))
13727 (when (or (equal key "CLOCK") (not (assoc key props)))
13728 (push (cons key string) props))))))
13731 (when (memq which '(all standard))
13732 ;; Get the standard properties, like :PROP: ...
13733 (setq range (org-get-property-block beg end))
13734 (when range
13735 (goto-char (car range))
13736 (while (re-search-forward
13737 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13738 (cdr range) t)
13739 (setq key (org-match-string-no-properties 1)
13740 value (org-trim (or (org-match-string-no-properties 2) "")))
13741 (unless (member key excluded)
13742 (push (cons key (or value "")) props)))))
13743 (if clocksum
13744 (push (cons "CLOCKSUM"
13745 (org-columns-number-to-string (/ (float clocksum) 60.)
13746 'add_times))
13747 props))
13748 (unless (assoc "CATEGORY" props)
13749 (push (cons "CATEGORY" (org-get-category)) props))
13750 (append sum-props (nreverse props)))))))
13752 (defun org-entry-get (pom property &optional inherit literal-nil)
13753 "Get value of PROPERTY for entry at point-or-marker POM.
13754 If INHERIT is non-nil and the entry does not have the property,
13755 then also check higher levels of the hierarchy.
13756 If INHERIT is the symbol `selective', use inheritance only if the setting
13757 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13758 If the property is present but empty, the return value is the empty string.
13759 If the property is not present at all, nil is returned.
13761 If LITERAL-NIL is set, return the string value \"nil\" as a string,
13762 do not interpret it as the list atom nil. This is used for inheritance
13763 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
13764 (org-with-point-at pom
13765 (if (and inherit (if (eq inherit 'selective)
13766 (org-property-inherit-p property)
13768 (org-entry-get-with-inheritance property literal-nil)
13769 (if (member property org-special-properties)
13770 ;; We need a special property. Use `org-entry-properties' to
13771 ;; retrieve it, but specify the wanted property
13772 (cdr (assoc property (org-entry-properties nil 'special property)))
13773 (let ((range (unless (org-before-first-heading-p)
13774 (org-get-property-block))))
13775 (if (and range
13776 (goto-char (car range))
13777 (re-search-forward
13778 (org-re-property property)
13779 (cdr range) t))
13780 ;; Found the property, return it.
13781 (if (match-end 1)
13782 (if literal-nil
13783 (org-match-string-no-properties 1)
13784 (org-not-nil (org-match-string-no-properties 1)))
13785 "")))))))
13787 (defun org-property-or-variable-value (var &optional inherit)
13788 "Check if there is a property fixing the value of VAR.
13789 If yes, return this value. If not, return the current value of the variable."
13790 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13791 (if (and prop (stringp prop) (string-match "\\S-" prop))
13792 (read prop)
13793 (symbol-value var))))
13795 (defun org-entry-delete (pom property)
13796 "Delete the property PROPERTY from entry at point-or-marker POM."
13797 (org-with-point-at pom
13798 (if (member property org-special-properties)
13799 nil ; cannot delete these properties.
13800 (let ((range (org-get-property-block)))
13801 (if (and range
13802 (goto-char (car range))
13803 (re-search-forward
13804 (org-re-property property)
13805 (cdr range) t))
13806 (progn
13807 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13809 nil)))))
13811 ;; Multi-values properties are properties that contain multiple values
13812 ;; These values are assumed to be single words, separated by whitespace.
13813 (defun org-entry-add-to-multivalued-property (pom property value)
13814 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13815 (let* ((old (org-entry-get pom property))
13816 (values (and old (org-split-string old "[ \t]"))))
13817 (setq value (org-entry-protect-space value))
13818 (unless (member value values)
13819 (setq values (cons value values))
13820 (org-entry-put pom property
13821 (mapconcat 'identity values " ")))))
13823 (defun org-entry-remove-from-multivalued-property (pom property value)
13824 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13825 (let* ((old (org-entry-get pom property))
13826 (values (and old (org-split-string old "[ \t]"))))
13827 (setq value (org-entry-protect-space value))
13828 (when (member value values)
13829 (setq values (delete value values))
13830 (org-entry-put pom property
13831 (mapconcat 'identity values " ")))))
13833 (defun org-entry-member-in-multivalued-property (pom property value)
13834 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13835 (let* ((old (org-entry-get pom property))
13836 (values (and old (org-split-string old "[ \t]"))))
13837 (setq value (org-entry-protect-space value))
13838 (member value values)))
13840 (defun org-entry-get-multivalued-property (pom property)
13841 "Return a list of values in a multivalued property."
13842 (let* ((value (org-entry-get pom property))
13843 (values (and value (org-split-string value "[ \t]"))))
13844 (mapcar 'org-entry-restore-space values)))
13846 (defun org-entry-put-multivalued-property (pom property &rest values)
13847 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13848 VALUES should be a list of strings. Spaces will be protected."
13849 (org-entry-put pom property
13850 (mapconcat 'org-entry-protect-space values " "))
13851 (let* ((value (org-entry-get pom property))
13852 (values (and value (org-split-string value "[ \t]"))))
13853 (mapcar 'org-entry-restore-space values)))
13855 (defun org-entry-protect-space (s)
13856 "Protect spaces and newline in string S."
13857 (while (string-match " " s)
13858 (setq s (replace-match "%20" t t s)))
13859 (while (string-match "\n" s)
13860 (setq s (replace-match "%0A" t t s)))
13863 (defun org-entry-restore-space (s)
13864 "Restore spaces and newline in string S."
13865 (while (string-match "%20" s)
13866 (setq s (replace-match " " t t s)))
13867 (while (string-match "%0A" s)
13868 (setq s (replace-match "\n" t t s)))
13871 (defvar org-entry-property-inherited-from (make-marker)
13872 "Marker pointing to the entry from where a property was inherited.
13873 Each call to `org-entry-get-with-inheritance' will set this marker to the
13874 location of the entry where the inheritance search matched. If there was
13875 no match, the marker will point nowhere.
13876 Note that also `org-entry-get' calls this function, if the INHERIT flag
13877 is set.")
13879 (defun org-entry-get-with-inheritance (property &optional literal-nil)
13880 "Get entry property, and search higher levels if not present.
13881 The search will stop at the first ancestor which has the property defined.
13882 If the value found is \"nil\", return nil to show that the property
13883 should be considered as undefined (this is the meaning of nil here).
13884 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
13885 (move-marker org-entry-property-inherited-from nil)
13886 (let (tmp)
13887 (unless (org-before-first-heading-p)
13888 (save-excursion
13889 (save-restriction
13890 (widen)
13891 (catch 'ex
13892 (while t
13893 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
13894 (org-back-to-heading t)
13895 (move-marker org-entry-property-inherited-from (point))
13896 (throw 'ex tmp))
13897 (or (org-up-heading-safe) (throw 'ex nil)))))))
13898 (setq tmp (or tmp
13899 (cdr (assoc property org-file-properties))
13900 (cdr (assoc property org-global-properties))
13901 (cdr (assoc property org-global-properties-fixed))))
13902 (if literal-nil tmp (org-not-nil tmp))))
13904 (defvar org-property-changed-functions nil
13905 "Hook called when the value of a property has changed.
13906 Each hook function should accept two arguments, the name of the property
13907 and the new value.")
13909 (defun org-entry-put (pom property value)
13910 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13911 (org-with-point-at pom
13912 (org-back-to-heading t)
13913 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13914 range)
13915 (cond
13916 ((equal property "TODO")
13917 (when (and (stringp value) (string-match "\\S-" value)
13918 (not (member value org-todo-keywords-1)))
13919 (error "\"%s\" is not a valid TODO state" value))
13920 (if (or (not value)
13921 (not (string-match "\\S-" value)))
13922 (setq value 'none))
13923 (org-todo value)
13924 (org-set-tags nil 'align))
13925 ((equal property "PRIORITY")
13926 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13927 (string-to-char value) ?\ ))
13928 (org-set-tags nil 'align))
13929 ((equal property "SCHEDULED")
13930 (if (re-search-forward org-scheduled-time-regexp end t)
13931 (cond
13932 ((eq value 'earlier) (org-timestamp-change -1 'day))
13933 ((eq value 'later) (org-timestamp-change 1 'day))
13934 (t (call-interactively 'org-schedule)))
13935 (call-interactively 'org-schedule)))
13936 ((equal property "DEADLINE")
13937 (if (re-search-forward org-deadline-time-regexp end t)
13938 (cond
13939 ((eq value 'earlier) (org-timestamp-change -1 'day))
13940 ((eq value 'later) (org-timestamp-change 1 'day))
13941 (t (call-interactively 'org-deadline)))
13942 (call-interactively 'org-deadline)))
13943 ((member property org-special-properties)
13944 (error "The %s property can not yet be set with `org-entry-put'"
13945 property))
13946 (t ; a non-special property
13947 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13948 (setq range (org-get-property-block beg end 'force))
13949 (goto-char (car range))
13950 (if (re-search-forward
13951 (org-re-property property) (cdr range) t)
13952 (progn
13953 (delete-region (match-beginning 0) (match-end 0))
13954 (goto-char (match-beginning 0)))
13955 (goto-char (cdr range))
13956 (insert "\n")
13957 (backward-char 1)
13958 (org-indent-line-function))
13959 (insert ":" property ":")
13960 (and value (insert " " value))
13961 (org-indent-line-function)))))
13962 (run-hook-with-args 'org-property-changed-functions property value)))
13964 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13965 "Get all property keys in the current buffer.
13966 With INCLUDE-SPECIALS, also list the special properties that reflect things
13967 like tags and TODO state.
13968 With INCLUDE-DEFAULTS, also include properties that has special meaning
13969 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
13970 and others.
13971 With INCLUDE-COLUMNS, also include property names given in COLUMN
13972 formats in the current buffer."
13973 (let (rtn range cfmt s p)
13974 (save-excursion
13975 (save-restriction
13976 (widen)
13977 (goto-char (point-min))
13978 (while (re-search-forward org-property-start-re nil t)
13979 (setq range (org-get-property-block))
13980 (goto-char (car range))
13981 (while (re-search-forward
13982 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13983 (cdr range) t)
13984 (add-to-list 'rtn (org-match-string-no-properties 1)))
13985 (outline-next-heading))))
13987 (when include-specials
13988 (setq rtn (append org-special-properties rtn)))
13990 (when include-defaults
13991 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13992 (add-to-list 'rtn org-effort-property))
13994 (when include-columns
13995 (save-excursion
13996 (save-restriction
13997 (widen)
13998 (goto-char (point-min))
13999 (while (re-search-forward
14000 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14001 nil t)
14002 (setq cfmt (match-string 2) s 0)
14003 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14004 cfmt s)
14005 (setq s (match-end 0)
14006 p (match-string 1 cfmt))
14007 (unless (or (equal p "ITEM")
14008 (member p org-special-properties))
14009 (add-to-list 'rtn (match-string 1 cfmt))))))))
14011 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14013 (defun org-property-values (key)
14014 "Return a list of all values of property KEY in the current buffer."
14015 (save-excursion
14016 (save-restriction
14017 (widen)
14018 (goto-char (point-min))
14019 (let ((re (org-re-property key))
14020 values)
14021 (while (re-search-forward re nil t)
14022 (add-to-list 'values (org-trim (match-string 1))))
14023 (delete "" values)))))
14025 (defun org-insert-property-drawer ()
14026 "Insert a property drawer into the current entry."
14027 (interactive)
14028 (org-back-to-heading t)
14029 (looking-at outline-regexp)
14030 (let ((indent (if org-adapt-indentation
14031 (- (match-end 0)(match-beginning 0))
14033 (beg (point))
14034 (re (concat "^[ \t]*" org-keyword-time-regexp))
14035 end hiddenp)
14036 (outline-next-heading)
14037 (setq end (point))
14038 (goto-char beg)
14039 (while (re-search-forward re end t))
14040 (setq hiddenp (outline-invisible-p))
14041 (end-of-line 1)
14042 (and (equal (char-after) ?\n) (forward-char 1))
14043 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14044 (if (member (match-string 1) '("CLOCK:" ":END:"))
14045 ;; just skip this line
14046 (beginning-of-line 2)
14047 ;; Drawer start, find the end
14048 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14049 (beginning-of-line 1)))
14050 (org-skip-over-state-notes)
14051 (skip-chars-backward " \t\n\r")
14052 (if (eq (char-before) ?*) (forward-char 1))
14053 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14054 (beginning-of-line 0)
14055 (org-indent-to-column indent)
14056 (beginning-of-line 2)
14057 (org-indent-to-column indent)
14058 (beginning-of-line 0)
14059 (if hiddenp
14060 (save-excursion
14061 (org-back-to-heading t)
14062 (hide-entry))
14063 (org-flag-drawer t))))
14065 (defvar org-property-set-functions-alist nil
14066 "Property set function alist.
14067 Each entry should have the following format:
14069 (PROPERTY . READ-FUNCTION)
14071 The read function will be called with the same argument as
14072 `org-completing-read'.")
14074 (defun org-set-property-function (property)
14075 "Get the function that should be used to set PROPERTY.
14076 This is computed according to `org-property-set-functions-alist'."
14077 (or (cdr (assoc property org-property-set-functions-alist))
14078 'org-completing-read))
14080 (defun org-read-property-value (property)
14081 "Read PROPERTY value from user."
14082 (let* ((completion-ignore-case t)
14083 (allowed (org-property-get-allowed-values nil property 'table))
14084 (cur (org-entry-get nil property))
14085 (prompt (concat property " value"
14086 (if (and cur (string-match "\\S-" cur))
14087 (concat " [" cur "]") "") ": "))
14088 (set-function (org-set-property-function property))
14089 (val (if allowed
14090 (funcall set-function prompt allowed nil
14091 (not (get-text-property 0 'org-unrestricted
14092 (caar allowed))))
14093 (let (org-completion-use-ido org-completion-use-iswitchb)
14094 (funcall set-function prompt
14095 (mapcar 'list (org-property-values property))
14096 nil nil "" nil cur)))))
14097 (if (equal val "")
14099 val)))
14101 (defun org-read-property-name ()
14102 "Read a property name."
14103 (let* ((completion-ignore-case t)
14104 (keys (org-buffer-property-keys nil t t))
14105 (default-prop (save-excursion
14106 (save-match-data
14107 (beginning-of-line)
14108 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14109 (null (string= (match-string 1) "END"))
14110 (match-string 1)))))
14111 (property (org-icompleting-read
14112 (concat "Property"
14113 (if default-prop (concat " [" default-prop "]") "")
14114 ": ")
14115 (mapcar 'list keys)
14116 nil nil nil nil
14117 default-prop
14119 (if (member property keys)
14120 property
14121 (or (cdr (assoc (downcase property)
14122 (mapcar (lambda (x) (cons (downcase x) x))
14123 keys)))
14124 property))))
14126 (defun org-set-property (property value)
14127 "In the current entry, set PROPERTY to VALUE.
14128 When called interactively, this will prompt for a property name, offering
14129 completion on existing and default properties. And then it will prompt
14130 for a value, offering completion either on allowed values (via an inherited
14131 xxx_ALL property) or on existing values in other instances of this property
14132 in the current file."
14133 (interactive (list nil nil))
14134 (let* ((property (or property (org-read-property-name)))
14135 (value (or value (org-read-property-value property))))
14136 (unless (equal (org-entry-get nil property) value)
14137 (org-entry-put nil property value))))
14139 (defun org-delete-property (property)
14140 "In the current entry, delete PROPERTY."
14141 (interactive
14142 (let* ((completion-ignore-case t)
14143 (prop (org-icompleting-read "Property: "
14144 (org-entry-properties nil 'standard))))
14145 (list prop)))
14146 (message "Property %s %s" property
14147 (if (org-entry-delete nil property)
14148 "deleted"
14149 "was not present in the entry")))
14151 (defun org-delete-property-globally (property)
14152 "Remove PROPERTY globally, from all entries."
14153 (interactive
14154 (let* ((completion-ignore-case t)
14155 (prop (org-icompleting-read
14156 "Globally remove property: "
14157 (mapcar 'list (org-buffer-property-keys)))))
14158 (list prop)))
14159 (save-excursion
14160 (save-restriction
14161 (widen)
14162 (goto-char (point-min))
14163 (let ((cnt 0))
14164 (while (re-search-forward
14165 (org-re-property property)
14166 nil t)
14167 (setq cnt (1+ cnt))
14168 (replace-match ""))
14169 (message "Property \"%s\" removed from %d entries" property cnt)))))
14171 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14173 (defun org-compute-property-at-point ()
14174 "Compute the property at point.
14175 This looks for an enclosing column format, extracts the operator and
14176 then applies it to the property in the column format's scope."
14177 (interactive)
14178 (unless (org-at-property-p)
14179 (error "Not at a property"))
14180 (let ((prop (org-match-string-no-properties 2)))
14181 (org-columns-get-format-and-top-level)
14182 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14183 (error "No operator defined for property %s" prop))
14184 (org-columns-compute prop)))
14186 (defvar org-property-allowed-value-functions nil
14187 "Hook for functions supplying allowed values for a specific property.
14188 The functions must take a single argument, the name of the property, and
14189 return a flat list of allowed values. If \":ETC\" is one of
14190 the values, this means that these values are intended as defaults for
14191 completion, but that other values should be allowed too.
14192 The functions must return nil if they are not responsible for this
14193 property.")
14195 (defun org-property-get-allowed-values (pom property &optional table)
14196 "Get allowed values for the property PROPERTY.
14197 When TABLE is non-nil, return an alist that can directly be used for
14198 completion."
14199 (let (vals)
14200 (cond
14201 ((equal property "TODO")
14202 (setq vals (org-with-point-at pom
14203 (append org-todo-keywords-1 '("")))))
14204 ((equal property "PRIORITY")
14205 (let ((n org-lowest-priority))
14206 (while (>= n org-highest-priority)
14207 (push (char-to-string n) vals)
14208 (setq n (1- n)))))
14209 ((member property org-special-properties))
14210 ((setq vals (run-hook-with-args-until-success
14211 'org-property-allowed-value-functions property)))
14213 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14214 (when (and vals (string-match "\\S-" vals))
14215 (setq vals (car (read-from-string (concat "(" vals ")"))))
14216 (setq vals (mapcar (lambda (x)
14217 (cond ((stringp x) x)
14218 ((numberp x) (number-to-string x))
14219 ((symbolp x) (symbol-name x))
14220 (t "???")))
14221 vals)))))
14222 (when (member ":ETC" vals)
14223 (setq vals (remove ":ETC" vals))
14224 (org-add-props (car vals) '(org-unrestricted t)))
14225 (if table (mapcar 'list vals) vals)))
14227 (defun org-property-previous-allowed-value (&optional previous)
14228 "Switch to the next allowed value for this property."
14229 (interactive)
14230 (org-property-next-allowed-value t))
14232 (defun org-property-next-allowed-value (&optional previous)
14233 "Switch to the next allowed value for this property."
14234 (interactive)
14235 (unless (org-at-property-p)
14236 (error "Not at a property"))
14237 (let* ((key (match-string 2))
14238 (value (match-string 3))
14239 (allowed (or (org-property-get-allowed-values (point) key)
14240 (and (member value '("[ ]" "[-]" "[X]"))
14241 '("[ ]" "[X]"))))
14242 nval)
14243 (unless allowed
14244 (error "Allowed values for this property have not been defined"))
14245 (if previous (setq allowed (reverse allowed)))
14246 (if (member value allowed)
14247 (setq nval (car (cdr (member value allowed)))))
14248 (setq nval (or nval (car allowed)))
14249 (if (equal nval value)
14250 (error "Only one allowed value for this property"))
14251 (org-at-property-p)
14252 (replace-match (concat " :" key ": " nval) t t)
14253 (org-indent-line-function)
14254 (beginning-of-line 1)
14255 (skip-chars-forward " \t")
14256 (run-hook-with-args 'org-property-changed-functions key nval)))
14258 (defun org-find-olp (path &optional this-buffer)
14259 "Return a marker pointing to the entry at outline path OLP.
14260 If anything goes wrong, throw an error.
14261 You can wrap this call to catch the error like this:
14263 (condition-case msg
14264 (org-mobile-locate-entry (match-string 4))
14265 (error (nth 1 msg)))
14267 The return value will then be either a string with the error message,
14268 or a marker if everything is OK.
14270 If THIS-BUFFER is set, the outline path does not contain a file,
14271 only headings."
14272 (let* ((file (if this-buffer buffer-file-name (pop path)))
14273 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14274 (level 1)
14275 (lmin 1)
14276 (lmax 1)
14277 limit re end found pos heading cnt flevel)
14278 (unless buffer (error "File not found :%s" file))
14279 (with-current-buffer buffer
14280 (save-excursion
14281 (save-restriction
14282 (widen)
14283 (setq limit (point-max))
14284 (goto-char (point-min))
14285 (while (setq heading (pop path))
14286 (setq re (format org-complex-heading-regexp-format
14287 (regexp-quote heading)))
14288 (setq cnt 0 pos (point))
14289 (while (re-search-forward re end t)
14290 (setq level (- (match-end 1) (match-beginning 1)))
14291 (if (and (>= level lmin) (<= level lmax))
14292 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14293 (when (= cnt 0) (error "Heading not found on level %d: %s"
14294 lmax heading))
14295 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14296 lmax heading))
14297 (goto-char found)
14298 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14299 (setq end (save-excursion (org-end-of-subtree t t))))
14300 (when (org-on-heading-p)
14301 (move-marker (make-marker) (point))))))))
14303 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14304 "Find node HEADING in BUFFER.
14305 Return a marker to the heading if it was found, or nil if not.
14306 If POS-ONLY is set, return just the position instead of a marker.
14308 The heading text must match exact, but it may have a TODO keyword,
14309 a priority cookie and tags in the standard locations."
14310 (with-current-buffer (or buffer (current-buffer))
14311 (save-excursion
14312 (save-restriction
14313 (widen)
14314 (goto-char (point-min))
14315 (let (case-fold-search)
14316 (if (re-search-forward
14317 (format org-complex-heading-regexp-format
14318 (regexp-quote heading)) nil t)
14319 (if pos-only
14320 (match-beginning 0)
14321 (move-marker (make-marker) (match-beginning 0)))))))))
14323 (defun org-find-exact-heading-in-directory (heading &optional dir)
14324 "Find Org node headline HEADING in all .org files in directory DIR.
14325 When the target headline is found, return a marker to this location."
14326 (let ((files (directory-files (or dir default-directory)
14327 nil "\\`[^.#].*\\.org\\'"))
14328 file visiting m buffer)
14329 (catch 'found
14330 (while (setq file (pop files))
14331 (message "trying %s" file)
14332 (setq visiting (org-find-base-buffer-visiting file))
14333 (setq buffer (or visiting (find-file-noselect file)))
14334 (setq m (org-find-exact-headline-in-buffer
14335 heading buffer))
14336 (when (and (not m) (not visiting)) (kill-buffer buffer))
14337 (and m (throw 'found m))))))
14339 (defun org-find-entry-with-id (ident)
14340 "Locate the entry that contains the ID property with exact value IDENT.
14341 IDENT can be a string, a symbol or a number, this function will search for
14342 the string representation of it.
14343 Return the position where this entry starts, or nil if there is no such entry."
14344 (interactive "sID: ")
14345 (let ((id (cond
14346 ((stringp ident) ident)
14347 ((symbol-name ident) (symbol-name ident))
14348 ((numberp ident) (number-to-string ident))
14349 (t (error "IDENT %s must be a string, symbol or number" ident))))
14350 (case-fold-search nil))
14351 (save-excursion
14352 (save-restriction
14353 (widen)
14354 (goto-char (point-min))
14355 (when (re-search-forward
14356 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14357 nil t)
14358 (org-back-to-heading t)
14359 (point))))))
14361 ;;;; Timestamps
14363 (defvar org-last-changed-timestamp nil)
14364 (defvar org-last-inserted-timestamp nil
14365 "The last time stamp inserted with `org-insert-time-stamp'.")
14366 (defvar org-time-was-given) ; dynamically scoped parameter
14367 (defvar org-end-time-was-given) ; dynamically scoped parameter
14368 (defvar org-ts-what) ; dynamically scoped parameter
14370 (defun org-time-stamp (arg &optional inactive)
14371 "Prompt for a date/time and insert a time stamp.
14372 If the user specifies a time like HH:MM, or if this command is called
14373 with a prefix argument, the time stamp will contain date and time.
14374 Otherwise, only the date will be included. All parts of a date not
14375 specified by the user will be filled in from the current date/time.
14376 So if you press just return without typing anything, the time stamp
14377 will represent the current date/time. If there is already a timestamp
14378 at the cursor, it will be modified."
14379 (interactive "P")
14380 (let* ((ts nil)
14381 (default-time
14382 ;; Default time is either today, or, when entering a range,
14383 ;; the range start.
14384 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14385 (save-excursion
14386 (re-search-backward
14387 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14388 (- (point) 20) t)))
14389 (apply 'encode-time (org-parse-time-string (match-string 1)))
14390 (current-time)))
14391 (default-input (and ts (org-get-compact-tod ts)))
14392 (repeater (save-excursion
14393 (save-match-data
14394 (beginning-of-line)
14395 (when (re-search-forward
14396 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14397 (save-excursion (progn (end-of-line) (point))) t)
14398 (match-string 0)))))
14399 org-time-was-given org-end-time-was-given time)
14400 (cond
14401 ((and (org-at-timestamp-p t)
14402 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14403 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14404 (insert "--")
14405 (setq time (let ((this-command this-command))
14406 (org-read-date arg 'totime nil nil
14407 default-time default-input)))
14408 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14409 ((org-at-timestamp-p t)
14410 (setq time (let ((this-command this-command))
14411 (org-read-date arg 'totime nil nil default-time default-input)))
14412 (when (org-at-timestamp-p t) ; just to get the match data
14413 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14414 (replace-match "")
14415 (setq org-last-changed-timestamp
14416 (org-insert-time-stamp
14417 time (or org-time-was-given arg)
14418 inactive nil nil (list org-end-time-was-given)))
14419 (when repeater (goto-char (1- (point))) (insert " " repeater)
14420 (setq org-last-changed-timestamp
14421 (concat (substring org-last-inserted-timestamp 0 -1)
14422 " " repeater ">"))))
14423 (message "Timestamp updated"))
14425 (setq time (let ((this-command this-command))
14426 (org-read-date arg 'totime nil nil default-time default-input)))
14427 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14428 nil nil (list org-end-time-was-given))))))
14430 ;; FIXME: can we use this for something else, like computing time differences?
14431 (defun org-get-compact-tod (s)
14432 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14433 (let* ((t1 (match-string 1 s))
14434 (h1 (string-to-number (match-string 2 s)))
14435 (m1 (string-to-number (match-string 3 s)))
14436 (t2 (and (match-end 4) (match-string 5 s)))
14437 (h2 (and t2 (string-to-number (match-string 6 s))))
14438 (m2 (and t2 (string-to-number (match-string 7 s))))
14439 dh dm)
14440 (if (not t2)
14442 (setq dh (- h2 h1) dm (- m2 m1))
14443 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14444 (concat t1 "+" (number-to-string dh)
14445 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14447 (defun org-time-stamp-inactive (&optional arg)
14448 "Insert an inactive time stamp.
14449 An inactive time stamp is enclosed in square brackets instead of angle
14450 brackets. It is inactive in the sense that it does not trigger agenda entries,
14451 does not link to the calendar and cannot be changed with the S-cursor keys.
14452 So these are more for recording a certain time/date."
14453 (interactive "P")
14454 (org-time-stamp arg 'inactive))
14456 (defvar org-date-ovl (make-overlay 1 1))
14457 (overlay-put org-date-ovl 'face 'org-warning)
14458 (org-detach-overlay org-date-ovl)
14460 (defvar org-ans1) ; dynamically scoped parameter
14461 (defvar org-ans2) ; dynamically scoped parameter
14463 (defvar org-plain-time-of-day-regexp) ; defined below
14465 (defvar org-overriding-default-time nil) ; dynamically scoped
14466 (defvar org-read-date-overlay nil)
14467 (defvar org-dcst nil) ; dynamically scoped
14468 (defvar org-read-date-history nil)
14469 (defvar org-read-date-final-answer nil)
14470 (defvar org-read-date-analyze-futurep nil)
14471 (defvar org-read-date-analyze-forced-year nil)
14473 (defun org-read-date (&optional with-time to-time from-string prompt
14474 default-time default-input)
14475 "Read a date, possibly a time, and make things smooth for the user.
14476 The prompt will suggest to enter an ISO date, but you can also enter anything
14477 which will at least partially be understood by `parse-time-string'.
14478 Unrecognized parts of the date will default to the current day, month, year,
14479 hour and minute. If this command is called to replace a timestamp at point,
14480 of to enter the second timestamp of a range, the default time is taken
14481 from the existing stamp. Furthermore, the command prefers the future,
14482 so if you are giving a date where the year is not given, and the day-month
14483 combination is already past in the current year, it will assume you
14484 mean next year. For details, see the manual. A few examples:
14486 3-2-5 --> 2003-02-05
14487 feb 15 --> currentyear-02-15
14488 2/15 --> currentyear-02-15
14489 sep 12 9 --> 2009-09-12
14490 12:45 --> today 12:45
14491 22 sept 0:34 --> currentyear-09-22 0:34
14492 12 --> currentyear-currentmonth-12
14493 Fri --> nearest Friday (today or later)
14494 etc.
14496 Furthermore you can specify a relative date by giving, as the *first* thing
14497 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14498 change in days weeks, months, years.
14499 With a single plus or minus, the date is relative to today. With a double
14500 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14501 +4d --> four days from today
14502 +4 --> same as above
14503 +2w --> two weeks from today
14504 ++5 --> five days from default date
14506 The function understands only English month and weekday abbreviations,
14507 but this can be configured with the variables `parse-time-months' and
14508 `parse-time-weekdays'.
14510 While prompting, a calendar is popped up - you can also select the
14511 date with the mouse (button 1). The calendar shows a period of three
14512 months. To scroll it to other months, use the keys `>' and `<'.
14513 If you don't like the calendar, turn it off with
14514 \(setq org-read-date-popup-calendar nil)
14516 With optional argument TO-TIME, the date will immediately be converted
14517 to an internal time.
14518 With an optional argument WITH-TIME, the prompt will suggest to also
14519 insert a time. Note that when WITH-TIME is not set, you can still
14520 enter a time, and this function will inform the calling routine about
14521 this change. The calling routine may then choose to change the format
14522 used to insert the time stamp into the buffer to include the time.
14523 With optional argument FROM-STRING, read from this string instead from
14524 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14525 the time/date that is used for everything that is not specified by the
14526 user."
14527 (require 'parse-time)
14528 (let* ((org-time-stamp-rounding-minutes
14529 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14530 (org-dcst org-display-custom-times)
14531 (ct (org-current-time))
14532 (def (or org-overriding-default-time default-time ct))
14533 (defdecode (decode-time def))
14534 (dummy (progn
14535 (when (< (nth 2 defdecode) org-extend-today-until)
14536 (setcar (nthcdr 2 defdecode) -1)
14537 (setcar (nthcdr 1 defdecode) 59)
14538 (setq def (apply 'encode-time defdecode)
14539 defdecode (decode-time def)))))
14540 (calendar-frame-setup nil)
14541 (calendar-setup nil)
14542 (calendar-move-hook nil)
14543 (calendar-view-diary-initially-flag nil)
14544 (calendar-view-holidays-initially-flag nil)
14545 (timestr (format-time-string
14546 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14547 (prompt (concat (if prompt (concat prompt " ") "")
14548 (format "Date+time [%s]: " timestr)))
14549 ans (org-ans0 "") org-ans1 org-ans2 final)
14551 (cond
14552 (from-string (setq ans from-string))
14553 (org-read-date-popup-calendar
14554 (save-excursion
14555 (save-window-excursion
14556 (calendar)
14557 (unwind-protect
14558 (progn
14559 (calendar-forward-day (- (time-to-days def)
14560 (calendar-absolute-from-gregorian
14561 (calendar-current-date))))
14562 (org-eval-in-calendar nil t)
14563 (let* ((old-map (current-local-map))
14564 (map (copy-keymap calendar-mode-map))
14565 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14566 (org-defkey map (kbd "RET") 'org-calendar-select)
14567 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14568 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14569 (org-defkey minibuffer-local-map [(meta shift left)]
14570 (lambda () (interactive)
14571 (org-eval-in-calendar '(calendar-backward-month 1))))
14572 (org-defkey minibuffer-local-map [(meta shift right)]
14573 (lambda () (interactive)
14574 (org-eval-in-calendar '(calendar-forward-month 1))))
14575 (org-defkey minibuffer-local-map [(meta shift up)]
14576 (lambda () (interactive)
14577 (org-eval-in-calendar '(calendar-backward-year 1))))
14578 (org-defkey minibuffer-local-map [(meta shift down)]
14579 (lambda () (interactive)
14580 (org-eval-in-calendar '(calendar-forward-year 1))))
14581 (org-defkey minibuffer-local-map [?\e (shift left)]
14582 (lambda () (interactive)
14583 (org-eval-in-calendar '(calendar-backward-month 1))))
14584 (org-defkey minibuffer-local-map [?\e (shift right)]
14585 (lambda () (interactive)
14586 (org-eval-in-calendar '(calendar-forward-month 1))))
14587 (org-defkey minibuffer-local-map [?\e (shift up)]
14588 (lambda () (interactive)
14589 (org-eval-in-calendar '(calendar-backward-year 1))))
14590 (org-defkey minibuffer-local-map [?\e (shift down)]
14591 (lambda () (interactive)
14592 (org-eval-in-calendar '(calendar-forward-year 1))))
14593 (org-defkey minibuffer-local-map [(shift up)]
14594 (lambda () (interactive)
14595 (org-eval-in-calendar '(calendar-backward-week 1))))
14596 (org-defkey minibuffer-local-map [(shift down)]
14597 (lambda () (interactive)
14598 (org-eval-in-calendar '(calendar-forward-week 1))))
14599 (org-defkey minibuffer-local-map [(shift left)]
14600 (lambda () (interactive)
14601 (org-eval-in-calendar '(calendar-backward-day 1))))
14602 (org-defkey minibuffer-local-map [(shift right)]
14603 (lambda () (interactive)
14604 (org-eval-in-calendar '(calendar-forward-day 1))))
14605 (org-defkey minibuffer-local-map ">"
14606 (lambda () (interactive)
14607 (org-eval-in-calendar '(scroll-calendar-left 1))))
14608 (org-defkey minibuffer-local-map "<"
14609 (lambda () (interactive)
14610 (org-eval-in-calendar '(scroll-calendar-right 1))))
14611 (org-defkey minibuffer-local-map "\C-v"
14612 (lambda () (interactive)
14613 (org-eval-in-calendar
14614 '(calendar-scroll-left-three-months 1))))
14615 (org-defkey minibuffer-local-map "\M-v"
14616 (lambda () (interactive)
14617 (org-eval-in-calendar
14618 '(calendar-scroll-right-three-months 1))))
14619 (run-hooks 'org-read-date-minibuffer-setup-hook)
14620 (unwind-protect
14621 (progn
14622 (use-local-map map)
14623 (add-hook 'post-command-hook 'org-read-date-display)
14624 (setq org-ans0 (read-string prompt default-input
14625 'org-read-date-history nil))
14626 ;; org-ans0: from prompt
14627 ;; org-ans1: from mouse click
14628 ;; org-ans2: from calendar motion
14629 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14630 (remove-hook 'post-command-hook 'org-read-date-display)
14631 (use-local-map old-map)
14632 (when org-read-date-overlay
14633 (delete-overlay org-read-date-overlay)
14634 (setq org-read-date-overlay nil)))))
14635 (bury-buffer "*Calendar*")))))
14637 (t ; Naked prompt only
14638 (unwind-protect
14639 (setq ans (read-string prompt default-input
14640 'org-read-date-history timestr))
14641 (when org-read-date-overlay
14642 (delete-overlay org-read-date-overlay)
14643 (setq org-read-date-overlay nil)))))
14645 (setq final (org-read-date-analyze ans def defdecode))
14647 (when org-read-date-analyze-forced-year
14648 (message "Year was forced into %s"
14649 (if org-read-date-force-compatible-dates
14650 "compatible range (1970-2037)"
14651 "range representable on this machine"))
14652 (ding))
14654 ;; One round trip to get rid of 34th of August and stuff like that....
14655 (setq final (decode-time (apply 'encode-time final)))
14657 (setq org-read-date-final-answer ans)
14659 (if to-time
14660 (apply 'encode-time final)
14661 (if (and (boundp 'org-time-was-given) org-time-was-given)
14662 (format "%04d-%02d-%02d %02d:%02d"
14663 (nth 5 final) (nth 4 final) (nth 3 final)
14664 (nth 2 final) (nth 1 final))
14665 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14667 (defvar def)
14668 (defvar defdecode)
14669 (defvar with-time)
14670 (defun org-read-date-display ()
14671 "Display the current date prompt interpretation in the minibuffer."
14672 (when org-read-date-display-live
14673 (when org-read-date-overlay
14674 (delete-overlay org-read-date-overlay))
14675 (let ((p (point)))
14676 (end-of-line 1)
14677 (while (not (equal (buffer-substring
14678 (max (point-min) (- (point) 4)) (point))
14679 " "))
14680 (insert " "))
14681 (goto-char p))
14682 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14683 " " (or org-ans1 org-ans2)))
14684 (org-end-time-was-given nil)
14685 (f (org-read-date-analyze ans def defdecode))
14686 (fmts (if org-dcst
14687 org-time-stamp-custom-formats
14688 org-time-stamp-formats))
14689 (fmt (if (or with-time
14690 (and (boundp 'org-time-was-given) org-time-was-given))
14691 (cdr fmts)
14692 (car fmts)))
14693 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14694 (when (and org-end-time-was-given
14695 (string-match org-plain-time-of-day-regexp txt))
14696 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14697 org-end-time-was-given
14698 (substring txt (match-end 0)))))
14699 (when org-read-date-analyze-futurep
14700 (setq txt (concat txt " (=>F)")))
14701 (setq org-read-date-overlay
14702 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14703 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14705 (defun org-read-date-analyze (ans def defdecode)
14706 "Analyze the combined answer of the date prompt."
14707 ;; FIXME: cleanup and comment
14708 (let ((nowdecode (decode-time (current-time)))
14709 delta deltan deltaw deltadef year month day
14710 hour minute second wday pm h2 m2 tl wday1
14711 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14712 (setq org-read-date-analyze-futurep nil
14713 org-read-date-analyze-forced-year nil)
14714 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14715 (setq ans "+0"))
14717 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14718 (setq ans (replace-match "" t t ans)
14719 deltan (car delta)
14720 deltaw (nth 1 delta)
14721 deltadef (nth 2 delta)))
14723 ;; Check if there is an iso week date in there
14724 ;; If yes, store the info and postpone interpreting it until the rest
14725 ;; of the parsing is done
14726 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14727 (setq iso-year (if (match-end 1)
14728 (org-small-year-to-year
14729 (string-to-number (match-string 1 ans))))
14730 iso-weekday (if (match-end 3)
14731 (string-to-number (match-string 3 ans)))
14732 iso-week (string-to-number (match-string 2 ans)))
14733 (setq ans (replace-match "" t t ans)))
14735 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14736 (when (string-match
14737 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14738 (setq year (if (match-end 2)
14739 (string-to-number (match-string 2 ans))
14740 (progn (setq kill-year t)
14741 (string-to-number (format-time-string "%Y"))))
14742 month (string-to-number (match-string 3 ans))
14743 day (string-to-number (match-string 4 ans)))
14744 (if (< year 100) (setq year (+ 2000 year)))
14745 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14746 t nil ans)))
14748 ;; Help matching dottet european dates
14749 (when (string-match
14750 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
14751 (setq year (if (match-end 3)
14752 (string-to-number (match-string 3 ans))
14753 (progn (setq kill-year t)
14754 (string-to-number (format-time-string "%Y"))))
14755 day (string-to-number (match-string 1 ans))
14756 month (string-to-number (match-string 2 ans))
14757 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14758 t nil ans)))
14760 ;; Help matching american dates, like 5/30 or 5/30/7
14761 (when (string-match
14762 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14763 (setq year (if (match-end 4)
14764 (string-to-number (match-string 4 ans))
14765 (progn (setq kill-year t)
14766 (string-to-number (format-time-string "%Y"))))
14767 month (string-to-number (match-string 1 ans))
14768 day (string-to-number (match-string 2 ans)))
14769 (if (< year 100) (setq year (+ 2000 year)))
14770 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14771 t nil ans)))
14772 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14773 ;; If there is a time with am/pm, and *no* time without it, we convert
14774 ;; so that matching will be successful.
14775 (loop for i from 1 to 2 do ; twice, for end time as well
14776 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14777 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14778 (setq hour (string-to-number (match-string 1 ans))
14779 minute (if (match-end 3)
14780 (string-to-number (match-string 3 ans))
14782 pm (equal ?p
14783 (string-to-char (downcase (match-string 4 ans)))))
14784 (if (and (= hour 12) (not pm))
14785 (setq hour 0)
14786 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14787 (setq ans (replace-match (format "%02d:%02d" hour minute)
14788 t t ans))))
14790 ;; Check if a time range is given as a duration
14791 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14792 (setq hour (string-to-number (match-string 1 ans))
14793 h2 (+ hour (string-to-number (match-string 3 ans)))
14794 minute (string-to-number (match-string 2 ans))
14795 m2 (+ minute (if (match-end 5) (string-to-number
14796 (match-string 5 ans))0)))
14797 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14798 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14799 t t ans)))
14801 ;; Check if there is a time range
14802 (when (boundp 'org-end-time-was-given)
14803 (setq org-time-was-given nil)
14804 (when (and (string-match org-plain-time-of-day-regexp ans)
14805 (match-end 8))
14806 (setq org-end-time-was-given (match-string 8 ans))
14807 (setq ans (concat (substring ans 0 (match-beginning 7))
14808 (substring ans (match-end 7))))))
14810 (setq tl (parse-time-string ans)
14811 day (or (nth 3 tl) (nth 3 defdecode))
14812 month (or (nth 4 tl)
14813 (if (and org-read-date-prefer-future
14814 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14815 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14816 (nth 4 defdecode)))
14817 year (or (and (not kill-year) (nth 5 tl))
14818 (if (and org-read-date-prefer-future
14819 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14820 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14821 (nth 5 defdecode)))
14822 hour (or (nth 2 tl) (nth 2 defdecode))
14823 minute (or (nth 1 tl) (nth 1 defdecode))
14824 second (or (nth 0 tl) 0)
14825 wday (nth 6 tl))
14827 (when (and (eq org-read-date-prefer-future 'time)
14828 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
14829 (equal day (nth 3 nowdecode))
14830 (equal month (nth 4 nowdecode))
14831 (equal year (nth 5 nowdecode))
14832 (nth 2 tl)
14833 (or (< (nth 2 tl) (nth 2 nowdecode))
14834 (and (= (nth 2 tl) (nth 2 nowdecode))
14835 (nth 1 tl)
14836 (< (nth 1 tl) (nth 1 nowdecode)))))
14837 (setq day (1+ day)
14838 futurep t))
14840 ;; Special date definitions below
14841 (cond
14842 (iso-week
14843 ;; There was an iso week
14844 (require 'cal-iso)
14845 (setq futurep nil)
14846 (setq year (or iso-year year)
14847 day (or iso-weekday wday 1)
14848 wday nil ; to make sure that the trigger below does not match
14849 iso-date (calendar-gregorian-from-absolute
14850 (calendar-absolute-from-iso
14851 (list iso-week day year))))
14852 ; FIXME: Should we also push ISO weeks into the future?
14853 ; (when (and org-read-date-prefer-future
14854 ; (not iso-year)
14855 ; (< (calendar-absolute-from-gregorian iso-date)
14856 ; (time-to-days (current-time))))
14857 ; (setq year (1+ year)
14858 ; iso-date (calendar-gregorian-from-absolute
14859 ; (calendar-absolute-from-iso
14860 ; (list iso-week day year)))))
14861 (setq month (car iso-date)
14862 year (nth 2 iso-date)
14863 day (nth 1 iso-date)))
14864 (deltan
14865 (setq futurep nil)
14866 (unless deltadef
14867 (let ((now (decode-time (current-time))))
14868 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14869 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14870 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14871 ((equal deltaw "m") (setq month (+ month deltan)))
14872 ((equal deltaw "y") (setq year (+ year deltan)))))
14873 ((and wday (not (nth 3 tl)))
14874 (setq futurep nil)
14875 ;; Weekday was given, but no day, so pick that day in the week
14876 ;; on or after the derived date.
14877 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14878 (unless (equal wday wday1)
14879 (setq day (+ day (% (- wday wday1 -7) 7))))))
14880 (if (and (boundp 'org-time-was-given)
14881 (nth 2 tl))
14882 (setq org-time-was-given t))
14883 (if (< year 100) (setq year (+ 2000 year)))
14884 ;; Check of the date is representable
14885 (if org-read-date-force-compatible-dates
14886 (progn
14887 (if (< year 1970)
14888 (setq year 1970 org-read-date-analyze-forced-year t))
14889 (if (> year 2037)
14890 (setq year 2037 org-read-date-analyze-forced-year t)))
14891 (condition-case nil
14892 (ignore (encode-time second minute hour day month year))
14893 (error
14894 (setq year (nth 5 defdecode))
14895 (setq org-read-date-analyze-forced-year t))))
14896 (setq org-read-date-analyze-futurep futurep)
14897 (list second minute hour day month year)))
14899 (defvar parse-time-weekdays)
14901 (defun org-read-date-get-relative (s today default)
14902 "Check string S for special relative date string.
14903 TODAY and DEFAULT are internal times, for today and for a default.
14904 Return shift list (N what def-flag)
14905 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
14906 N is the number of WHATs to shift.
14907 DEF-FLAG is t when a double ++ or -- indicates shift relative to
14908 the DEFAULT date rather than TODAY."
14909 (when (and
14910 (string-match
14911 (concat
14912 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14913 "\\([0-9]+\\)?"
14914 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14915 "\\([ \t]\\|$\\)") s)
14916 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
14917 (let* ((dir (if (> (match-end 1) (match-beginning 1))
14918 (string-to-char (substring (match-string 1 s) -1))
14919 ?+))
14920 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
14921 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
14922 (what (if (match-end 3) (match-string 3 s) "d"))
14923 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
14924 (date (if rel default today))
14925 (wday (nth 6 (decode-time date)))
14926 delta)
14927 (if wday1
14928 (progn
14929 (setq delta (mod (+ 7 (- wday1 wday)) 7))
14930 (if (= dir ?-) (setq delta (- delta 7)))
14931 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
14932 (list delta "d" rel))
14933 (list (* n (if (= dir ?-) -1 1)) what rel)))))
14935 (defun org-order-calendar-date-args (arg1 arg2 arg3)
14936 "Turn a user-specified date into the internal representation.
14937 The internal representation needed by the calendar is (month day year).
14938 This is a wrapper to handle the brain-dead convention in calendar that
14939 user function argument order change dependent on argument order."
14940 (if (boundp 'calendar-date-style)
14941 (cond
14942 ((eq calendar-date-style 'american)
14943 (list arg1 arg2 arg3))
14944 ((eq calendar-date-style 'european)
14945 (list arg2 arg1 arg3))
14946 ((eq calendar-date-style 'iso)
14947 (list arg2 arg3 arg1)))
14948 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
14949 (if (org-bound-and-true-p european-calendar-style)
14950 (list arg2 arg1 arg3)
14951 (list arg1 arg2 arg3)))))
14953 (defun org-eval-in-calendar (form &optional keepdate)
14954 "Eval FORM in the calendar window and return to current window.
14955 Also, store the cursor date in variable org-ans2."
14956 (let ((sf (selected-frame))
14957 (sw (selected-window)))
14958 (select-window (get-buffer-window "*Calendar*" t))
14959 (eval form)
14960 (when (and (not keepdate) (calendar-cursor-to-date))
14961 (let* ((date (calendar-cursor-to-date))
14962 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14963 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14964 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14965 (select-window sw)
14966 (org-select-frame-set-input-focus sf)))
14968 (defun org-calendar-select ()
14969 "Return to `org-read-date' with the date currently selected.
14970 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14971 (interactive)
14972 (when (calendar-cursor-to-date)
14973 (let* ((date (calendar-cursor-to-date))
14974 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14975 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14976 (if (active-minibuffer-window) (exit-minibuffer))))
14978 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14979 "Insert a date stamp for the date given by the internal TIME.
14980 WITH-HM means use the stamp format that includes the time of the day.
14981 INACTIVE means use square brackets instead of angular ones, so that the
14982 stamp will not contribute to the agenda.
14983 PRE and POST are optional strings to be inserted before and after the
14984 stamp.
14985 The command returns the inserted time stamp."
14986 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14987 stamp)
14988 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14989 (insert-before-markers (or pre ""))
14990 (when (listp extra)
14991 (setq extra (car extra))
14992 (if (and (stringp extra)
14993 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14994 (setq extra (format "-%02d:%02d"
14995 (string-to-number (match-string 1 extra))
14996 (string-to-number (match-string 2 extra))))
14997 (setq extra nil)))
14998 (when extra
14999 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15000 (insert-before-markers (setq stamp (format-time-string fmt time)))
15001 (insert-before-markers (or post ""))
15002 (setq org-last-inserted-timestamp stamp)))
15004 (defun org-toggle-time-stamp-overlays ()
15005 "Toggle the use of custom time stamp formats."
15006 (interactive)
15007 (setq org-display-custom-times (not org-display-custom-times))
15008 (unless org-display-custom-times
15009 (let ((p (point-min)) (bmp (buffer-modified-p)))
15010 (while (setq p (next-single-property-change p 'display))
15011 (if (and (get-text-property p 'display)
15012 (eq (get-text-property p 'face) 'org-date))
15013 (remove-text-properties
15014 p (setq p (next-single-property-change p 'display))
15015 '(display t))))
15016 (set-buffer-modified-p bmp)))
15017 (if (featurep 'xemacs)
15018 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15019 (org-restart-font-lock)
15020 (setq org-table-may-need-update t)
15021 (if org-display-custom-times
15022 (message "Time stamps are overlayed with custom format")
15023 (message "Time stamp overlays removed")))
15025 (defun org-display-custom-time (beg end)
15026 "Overlay modified time stamp format over timestamp between BEG and END."
15027 (let* ((ts (buffer-substring beg end))
15028 t1 w1 with-hm tf time str w2 (off 0))
15029 (save-match-data
15030 (setq t1 (org-parse-time-string ts t))
15031 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15032 (setq off (- (match-end 0) (match-beginning 0)))))
15033 (setq end (- end off))
15034 (setq w1 (- end beg)
15035 with-hm (and (nth 1 t1) (nth 2 t1))
15036 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15037 time (org-fix-decoded-time t1)
15038 str (org-add-props
15039 (format-time-string
15040 (substring tf 1 -1) (apply 'encode-time time))
15041 nil 'mouse-face 'highlight)
15042 w2 (length str))
15043 (if (not (= w2 w1))
15044 (add-text-properties (1+ beg) (+ 2 beg)
15045 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15046 (if (featurep 'xemacs)
15047 (progn
15048 (put-text-property beg end 'invisible t)
15049 (put-text-property beg end 'end-glyph (make-glyph str)))
15050 (put-text-property beg end 'display str))))
15052 (defun org-translate-time (string)
15053 "Translate all timestamps in STRING to custom format.
15054 But do this only if the variable `org-display-custom-times' is set."
15055 (when org-display-custom-times
15056 (save-match-data
15057 (let* ((start 0)
15058 (re org-ts-regexp-both)
15059 t1 with-hm inactive tf time str beg end)
15060 (while (setq start (string-match re string start))
15061 (setq beg (match-beginning 0)
15062 end (match-end 0)
15063 t1 (save-match-data
15064 (org-parse-time-string (substring string beg end) t))
15065 with-hm (and (nth 1 t1) (nth 2 t1))
15066 inactive (equal (substring string beg (1+ beg)) "[")
15067 tf (funcall (if with-hm 'cdr 'car)
15068 org-time-stamp-custom-formats)
15069 time (org-fix-decoded-time t1)
15070 str (format-time-string
15071 (concat
15072 (if inactive "[" "<") (substring tf 1 -1)
15073 (if inactive "]" ">"))
15074 (apply 'encode-time time))
15075 string (replace-match str t t string)
15076 start (+ start (length str)))))))
15077 string)
15079 (defun org-fix-decoded-time (time)
15080 "Set 0 instead of nil for the first 6 elements of time.
15081 Don't touch the rest."
15082 (let ((n 0))
15083 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15085 (defun org-days-to-time (timestamp-string)
15086 "Difference between TIMESTAMP-STRING and now in days."
15087 (- (time-to-days (org-time-string-to-time timestamp-string))
15088 (time-to-days (current-time))))
15090 (defun org-deadline-close (timestamp-string &optional ndays)
15091 "Is the time in TIMESTAMP-STRING close to the current date?"
15092 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15093 (and (< (org-days-to-time timestamp-string) ndays)
15094 (not (org-entry-is-done-p))))
15096 (defun org-get-wdays (ts)
15097 "Get the deadline lead time appropriate for timestring TS."
15098 (cond
15099 ((<= org-deadline-warning-days 0)
15100 ;; 0 or negative, enforce this value no matter what
15101 (- org-deadline-warning-days))
15102 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15103 ;; lead time is specified.
15104 (floor (* (string-to-number (match-string 1 ts))
15105 (cdr (assoc (match-string 2 ts)
15106 '(("d" . 1) ("w" . 7)
15107 ("m" . 30.4) ("y" . 365.25)))))))
15108 ;; go for the default.
15109 (t org-deadline-warning-days)))
15111 (defun org-calendar-select-mouse (ev)
15112 "Return to `org-read-date' with the date currently selected.
15113 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15114 (interactive "e")
15115 (mouse-set-point ev)
15116 (when (calendar-cursor-to-date)
15117 (let* ((date (calendar-cursor-to-date))
15118 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15119 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15120 (if (active-minibuffer-window) (exit-minibuffer))))
15122 (defun org-check-deadlines (ndays)
15123 "Check if there are any deadlines due or past due.
15124 A deadline is considered due if it happens within `org-deadline-warning-days'
15125 days from today's date. If the deadline appears in an entry marked DONE,
15126 it is not shown. The prefix arg NDAYS can be used to test that many
15127 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15128 (interactive "P")
15129 (let* ((org-warn-days
15130 (cond
15131 ((equal ndays '(4)) 100000)
15132 (ndays (prefix-numeric-value ndays))
15133 (t (abs org-deadline-warning-days))))
15134 (case-fold-search nil)
15135 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15136 (callback
15137 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15139 (message "%d deadlines past-due or due within %d days"
15140 (org-occur regexp nil callback)
15141 org-warn-days)))
15143 (defun org-check-before-date (date)
15144 "Check if there are deadlines or scheduled entries before DATE."
15145 (interactive (list (org-read-date)))
15146 (let ((case-fold-search nil)
15147 (regexp (concat "\\<\\(" org-deadline-string
15148 "\\|" org-scheduled-string
15149 "\\) *<\\([^>]+\\)>"))
15150 (callback
15151 (lambda () (time-less-p
15152 (org-time-string-to-time (match-string 2))
15153 (org-time-string-to-time date)))))
15154 (message "%d entries before %s"
15155 (org-occur regexp nil callback) date)))
15157 (defun org-check-after-date (date)
15158 "Check if there are deadlines or scheduled entries after DATE."
15159 (interactive (list (org-read-date)))
15160 (let ((case-fold-search nil)
15161 (regexp (concat "\\<\\(" org-deadline-string
15162 "\\|" org-scheduled-string
15163 "\\) *<\\([^>]+\\)>"))
15164 (callback
15165 (lambda () (not
15166 (time-less-p
15167 (org-time-string-to-time (match-string 2))
15168 (org-time-string-to-time date))))))
15169 (message "%d entries after %s"
15170 (org-occur regexp nil callback) date)))
15172 (defun org-evaluate-time-range (&optional to-buffer)
15173 "Evaluate a time range by computing the difference between start and end.
15174 Normally the result is just printed in the echo area, but with prefix arg
15175 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15176 If the time range is actually in a table, the result is inserted into the
15177 next column.
15178 For time difference computation, a year is assumed to be exactly 365
15179 days in order to avoid rounding problems."
15180 (interactive "P")
15182 (org-clock-update-time-maybe)
15183 (save-excursion
15184 (unless (org-at-date-range-p t)
15185 (goto-char (point-at-bol))
15186 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15187 (if (not (org-at-date-range-p t))
15188 (error "Not at a time-stamp range, and none found in current line")))
15189 (let* ((ts1 (match-string 1))
15190 (ts2 (match-string 2))
15191 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15192 (match-end (match-end 0))
15193 (time1 (org-time-string-to-time ts1))
15194 (time2 (org-time-string-to-time ts2))
15195 (t1 (org-float-time time1))
15196 (t2 (org-float-time time2))
15197 (diff (abs (- t2 t1)))
15198 (negative (< (- t2 t1) 0))
15199 ;; (ys (floor (* 365 24 60 60)))
15200 (ds (* 24 60 60))
15201 (hs (* 60 60))
15202 (fy "%dy %dd %02d:%02d")
15203 (fy1 "%dy %dd")
15204 (fd "%dd %02d:%02d")
15205 (fd1 "%dd")
15206 (fh "%02d:%02d")
15207 y d h m align)
15208 (if havetime
15209 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15211 d (floor (/ diff ds)) diff (mod diff ds)
15212 h (floor (/ diff hs)) diff (mod diff hs)
15213 m (floor (/ diff 60)))
15214 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15216 d (floor (+ (/ diff ds) 0.5))
15217 h 0 m 0))
15218 (if (not to-buffer)
15219 (message "%s" (org-make-tdiff-string y d h m))
15220 (if (org-at-table-p)
15221 (progn
15222 (goto-char match-end)
15223 (setq align t)
15224 (and (looking-at " *|") (goto-char (match-end 0))))
15225 (goto-char match-end))
15226 (if (looking-at
15227 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15228 (replace-match ""))
15229 (if negative (insert " -"))
15230 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15231 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15232 (insert " " (format fh h m))))
15233 (if align (org-table-align))
15234 (message "Time difference inserted")))))
15236 (defun org-make-tdiff-string (y d h m)
15237 (let ((fmt "")
15238 (l nil))
15239 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15240 l (push y l)))
15241 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15242 l (push d l)))
15243 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15244 l (push h l)))
15245 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15246 l (push m l)))
15247 (apply 'format fmt (nreverse l))))
15249 (defun org-time-string-to-time (s)
15250 (apply 'encode-time (org-parse-time-string s)))
15251 (defun org-time-string-to-seconds (s)
15252 (org-float-time (org-time-string-to-time s)))
15254 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
15255 "Convert a time stamp to an absolute day number.
15256 If there is a specifier for a cyclic time stamp, get the closest date to
15257 DAYNR.
15258 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15259 The variable date is bound by the calendar when this is called."
15260 (cond
15261 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15262 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15263 daynr
15264 (+ daynr 1000)))
15265 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15266 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15267 (time-to-days (current-time))) (match-string 0 s)
15268 prefer show-all))
15269 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
15271 (defun org-days-to-iso-week (days)
15272 "Return the iso week number."
15273 (require 'cal-iso)
15274 (car (calendar-iso-from-absolute days)))
15276 (defun org-small-year-to-year (year)
15277 "Convert 2-digit years into 4-digit years.
15278 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15279 The year 2000 cannot be abbreviated. Any year larger than 99
15280 is returned unchanged."
15281 (if (< year 38)
15282 (setq year (+ 2000 year))
15283 (if (< year 100)
15284 (setq year (+ 1900 year))))
15285 year)
15287 (defun org-time-from-absolute (d)
15288 "Return the time corresponding to date D.
15289 D may be an absolute day number, or a calendar-type list (month day year)."
15290 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15291 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15293 (defun org-calendar-holiday ()
15294 "List of holidays, for Diary display in Org-mode."
15295 (require 'holidays)
15296 (let ((hl (funcall
15297 (if (fboundp 'calendar-check-holidays)
15298 'calendar-check-holidays 'check-calendar-holidays) date)))
15299 (if hl (mapconcat 'identity hl "; "))))
15301 (defun org-diary-sexp-entry (sexp entry date)
15302 "Process a SEXP diary ENTRY for DATE."
15303 (require 'diary-lib)
15304 (let ((result (if calendar-debug-sexp
15305 (let ((stack-trace-on-error t))
15306 (eval (car (read-from-string sexp))))
15307 (condition-case nil
15308 (eval (car (read-from-string sexp)))
15309 (error
15310 (beep)
15311 (message "Bad sexp at line %d in %s: %s"
15312 (org-current-line)
15313 (buffer-file-name) sexp)
15314 (sleep-for 2))))))
15315 (cond ((stringp result) (split-string result "; "))
15316 ((and (consp result)
15317 (not (consp (cdr result)))
15318 (stringp (cdr result))) (cdr result))
15319 ((and (consp result)
15320 (stringp (car result))) result)
15321 (result entry)
15322 (t nil))))
15324 (defun org-diary-to-ical-string (frombuf)
15325 "Get iCalendar entries from diary entries in buffer FROMBUF.
15326 This uses the icalendar.el library."
15327 (let* ((tmpdir (if (featurep 'xemacs)
15328 (temp-directory)
15329 temporary-file-directory))
15330 (tmpfile (make-temp-name
15331 (expand-file-name "orgics" tmpdir)))
15332 buf rtn b e)
15333 (with-current-buffer frombuf
15334 (icalendar-export-region (point-min) (point-max) tmpfile)
15335 (setq buf (find-buffer-visiting tmpfile))
15336 (set-buffer buf)
15337 (goto-char (point-min))
15338 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15339 (setq b (match-beginning 0)))
15340 (goto-char (point-max))
15341 (if (re-search-backward "^END:VEVENT" nil t)
15342 (setq e (match-end 0)))
15343 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15344 (kill-buffer buf)
15345 (delete-file tmpfile)
15346 rtn))
15348 (defun org-closest-date (start current change prefer show-all)
15349 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15350 When PREFER is `past', return a date that is either CURRENT or past.
15351 When PREFER is `future', return a date that is either CURRENT or future.
15352 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15353 ;; Make the proper lists from the dates
15354 (catch 'exit
15355 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15356 dn dw sday cday n1 n2 n0
15357 d m y y1 y2 date1 date2 nmonths nm ny m2)
15359 (setq start (org-date-to-gregorian start)
15360 current (org-date-to-gregorian
15361 (if show-all
15362 current
15363 (time-to-days (current-time))))
15364 sday (calendar-absolute-from-gregorian start)
15365 cday (calendar-absolute-from-gregorian current))
15367 (if (<= cday sday) (throw 'exit sday))
15369 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15370 (setq dn (string-to-number (match-string 1 change))
15371 dw (cdr (assoc (match-string 2 change) a1)))
15372 (error "Invalid change specifier: %s" change))
15373 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15374 (cond
15375 ((eq dw 'day)
15376 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15377 n2 (+ n1 dn)))
15378 ((eq dw 'year)
15379 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15380 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15381 (setq date1 (list m d y1)
15382 n1 (calendar-absolute-from-gregorian date1)
15383 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15384 n2 (calendar-absolute-from-gregorian date2)))
15385 ((eq dw 'month)
15386 ;; approx number of month between the two dates
15387 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15388 ;; How often does dn fit in there?
15389 (setq d (nth 1 start) m (car start) y (nth 2 start)
15390 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15391 m (+ m nm)
15392 ny (floor (/ m 12))
15393 y (+ y ny)
15394 m (- m (* ny 12)))
15395 (while (> m 12) (setq m (- m 12) y (1+ y)))
15396 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15397 (setq m2 (+ m dn) y2 y)
15398 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15399 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15400 (while (<= n2 cday)
15401 (setq n1 n2 m m2 y y2)
15402 (setq m2 (+ m dn) y2 y)
15403 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15404 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15405 ;; Make sure n1 is the earlier date
15406 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15407 (if show-all
15408 (cond
15409 ((eq prefer 'past) (if (= cday n2) n2 n1))
15410 ((eq prefer 'future) (if (= cday n1) n1 n2))
15411 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15412 (cond
15413 ((eq prefer 'past) (if (= cday n2) n2 n1))
15414 ((eq prefer 'future) (if (= cday n1) n1 n2))
15415 (t (if (= cday n1) n1 n2)))))))
15417 (defun org-date-to-gregorian (date)
15418 "Turn any specification of DATE into a Gregorian date for the calendar."
15419 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15420 ((and (listp date) (= (length date) 3)) date)
15421 ((stringp date)
15422 (setq date (org-parse-time-string date))
15423 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15424 ((listp date)
15425 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15427 (defun org-parse-time-string (s &optional nodefault)
15428 "Parse the standard Org-mode time string.
15429 This should be a lot faster than the normal `parse-time-string'.
15430 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15431 hour and minute fields will be nil if not given."
15432 (if (string-match org-ts-regexp0 s)
15433 (list 0
15434 (if (or (match-beginning 8) (not nodefault))
15435 (string-to-number (or (match-string 8 s) "0")))
15436 (if (or (match-beginning 7) (not nodefault))
15437 (string-to-number (or (match-string 7 s) "0")))
15438 (string-to-number (match-string 4 s))
15439 (string-to-number (match-string 3 s))
15440 (string-to-number (match-string 2 s))
15441 nil nil nil)
15442 (error "Not a standard Org-mode time string: %s" s)))
15444 (defun org-timestamp-up (&optional arg)
15445 "Increase the date item at the cursor by one.
15446 If the cursor is on the year, change the year. If it is on the month or
15447 the day, change that.
15448 With prefix ARG, change by that many units."
15449 (interactive "p")
15450 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15452 (defun org-timestamp-down (&optional arg)
15453 "Decrease the date item at the cursor by one.
15454 If the cursor is on the year, change the year. If it is on the month or
15455 the day, change that.
15456 With prefix ARG, change by that many units."
15457 (interactive "p")
15458 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15460 (defun org-timestamp-up-day (&optional arg)
15461 "Increase the date in the time stamp by one day.
15462 With prefix ARG, change that many days."
15463 (interactive "p")
15464 (if (and (not (org-at-timestamp-p t))
15465 (org-on-heading-p))
15466 (org-todo 'up)
15467 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15469 (defun org-timestamp-down-day (&optional arg)
15470 "Decrease the date in the time stamp by one day.
15471 With prefix ARG, change that many days."
15472 (interactive "p")
15473 (if (and (not (org-at-timestamp-p t))
15474 (org-on-heading-p))
15475 (org-todo 'down)
15476 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15478 (defun org-at-timestamp-p (&optional inactive-ok)
15479 "Determine if the cursor is in or at a timestamp."
15480 (interactive)
15481 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15482 (pos (point))
15483 (ans (or (looking-at tsr)
15484 (save-excursion
15485 (skip-chars-backward "^[<\n\r\t")
15486 (if (> (point) (point-min)) (backward-char 1))
15487 (and (looking-at tsr)
15488 (> (- (match-end 0) pos) -1))))))
15489 (and ans
15490 (boundp 'org-ts-what)
15491 (setq org-ts-what
15492 (cond
15493 ((= pos (match-beginning 0)) 'bracket)
15494 ((= pos (1- (match-end 0))) 'bracket)
15495 ((org-pos-in-match-range pos 2) 'year)
15496 ((org-pos-in-match-range pos 3) 'month)
15497 ((org-pos-in-match-range pos 7) 'hour)
15498 ((org-pos-in-match-range pos 8) 'minute)
15499 ((or (org-pos-in-match-range pos 4)
15500 (org-pos-in-match-range pos 5)) 'day)
15501 ((and (> pos (or (match-end 8) (match-end 5)))
15502 (< pos (match-end 0)))
15503 (- pos (or (match-end 8) (match-end 5))))
15504 (t 'day))))
15505 ans))
15507 (defun org-toggle-timestamp-type ()
15508 "Toggle the type (<active> or [inactive]) of a time stamp."
15509 (interactive)
15510 (when (org-at-timestamp-p t)
15511 (let ((beg (match-beginning 0)) (end (match-end 0))
15512 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15513 (save-excursion
15514 (goto-char beg)
15515 (while (re-search-forward "[][<>]" end t)
15516 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15517 t t)))
15518 (message "Timestamp is now %sactive"
15519 (if (equal (char-after beg) ?<) "" "in")))))
15521 (defun org-timestamp-change (n &optional what updown)
15522 "Change the date in the time stamp at point.
15523 The date will be changed by N times WHAT. WHAT can be `day', `month',
15524 `year', `minute', `second'. If WHAT is not given, the cursor position
15525 in the timestamp determines what will be changed."
15526 (let ((pos (point))
15527 with-hm inactive
15528 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15529 org-ts-what
15530 extra rem
15531 ts time time0)
15532 (if (not (org-at-timestamp-p t))
15533 (error "Not at a timestamp"))
15534 (if (and (not what) (eq org-ts-what 'bracket))
15535 (org-toggle-timestamp-type)
15536 (if (and (not what) (not (eq org-ts-what 'day))
15537 org-display-custom-times
15538 (get-text-property (point) 'display)
15539 (not (get-text-property (1- (point)) 'display)))
15540 (setq org-ts-what 'day))
15541 (setq org-ts-what (or what org-ts-what)
15542 inactive (= (char-after (match-beginning 0)) ?\[)
15543 ts (match-string 0))
15544 (replace-match "")
15545 (if (string-match
15546 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15548 (setq extra (match-string 1 ts)))
15549 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15550 (setq with-hm t))
15551 (setq time0 (org-parse-time-string ts))
15552 (when (and updown
15553 (eq org-ts-what 'minute)
15554 (not current-prefix-arg))
15555 ;; This looks like s-up and s-down. Change by one rounding step.
15556 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15557 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15558 (setcar (cdr time0) (+ (nth 1 time0)
15559 (if (> n 0) (- rem) (- dm rem))))))
15560 (setq time
15561 (encode-time (or (car time0) 0)
15562 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15563 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15564 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15565 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15566 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15567 (nthcdr 6 time0)))
15568 (when (and (member org-ts-what '(hour minute))
15569 extra
15570 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15571 (setq extra (org-modify-ts-extra
15572 extra
15573 (if (eq org-ts-what 'hour) 2 5)
15574 n dm)))
15575 (when (integerp org-ts-what)
15576 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15577 (if (eq what 'calendar)
15578 (let ((cal-date (org-get-date-from-calendar)))
15579 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15580 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15581 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15582 (setcar time0 (or (car time0) 0))
15583 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15584 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15585 (setq time (apply 'encode-time time0))))
15586 (setq org-last-changed-timestamp
15587 (org-insert-time-stamp time with-hm inactive nil nil extra))
15588 (org-clock-update-time-maybe)
15589 (goto-char pos)
15590 ;; Try to recenter the calendar window, if any
15591 (if (and org-calendar-follow-timestamp-change
15592 (get-buffer-window "*Calendar*" t)
15593 (memq org-ts-what '(day month year)))
15594 (org-recenter-calendar (time-to-days time))))))
15596 (defun org-modify-ts-extra (s pos n dm)
15597 "Change the different parts of the lead-time and repeat fields in timestamp."
15598 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15599 ng h m new rem)
15600 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15601 (cond
15602 ((or (org-pos-in-match-range pos 2)
15603 (org-pos-in-match-range pos 3))
15604 (setq m (string-to-number (match-string 3 s))
15605 h (string-to-number (match-string 2 s)))
15606 (if (org-pos-in-match-range pos 2)
15607 (setq h (+ h n))
15608 (setq n (* dm (org-no-warnings (signum n))))
15609 (when (not (= 0 (setq rem (% m dm))))
15610 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15611 (setq m (+ m n)))
15612 (if (< m 0) (setq m (+ m 60) h (1- h)))
15613 (if (> m 59) (setq m (- m 60) h (1+ h)))
15614 (setq h (min 24 (max 0 h)))
15615 (setq ng 1 new (format "-%02d:%02d" h m)))
15616 ((org-pos-in-match-range pos 6)
15617 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15618 ((org-pos-in-match-range pos 5)
15619 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15621 ((org-pos-in-match-range pos 9)
15622 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15623 ((org-pos-in-match-range pos 8)
15624 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15626 (when ng
15627 (setq s (concat
15628 (substring s 0 (match-beginning ng))
15630 (substring s (match-end ng))))))
15633 (defun org-recenter-calendar (date)
15634 "If the calendar is visible, recenter it to DATE."
15635 (let* ((win (selected-window))
15636 (cwin (get-buffer-window "*Calendar*" t))
15637 (calendar-move-hook nil))
15638 (when cwin
15639 (select-window cwin)
15640 (calendar-goto-date (if (listp date) date
15641 (calendar-gregorian-from-absolute date)))
15642 (select-window win))))
15644 (defun org-goto-calendar (&optional arg)
15645 "Go to the Emacs calendar at the current date.
15646 If there is a time stamp in the current line, go to that date.
15647 A prefix ARG can be used to force the current date."
15648 (interactive "P")
15649 (let ((tsr org-ts-regexp) diff
15650 (calendar-move-hook nil)
15651 (calendar-view-holidays-initially-flag nil)
15652 (calendar-view-diary-initially-flag nil))
15653 (if (or (org-at-timestamp-p)
15654 (save-excursion
15655 (beginning-of-line 1)
15656 (looking-at (concat ".*" tsr))))
15657 (let ((d1 (time-to-days (current-time)))
15658 (d2 (time-to-days
15659 (org-time-string-to-time (match-string 1)))))
15660 (setq diff (- d2 d1))))
15661 (calendar)
15662 (calendar-goto-today)
15663 (if (and diff (not arg)) (calendar-forward-day diff))))
15665 (defun org-get-date-from-calendar ()
15666 "Return a list (month day year) of date at point in calendar."
15667 (with-current-buffer "*Calendar*"
15668 (save-match-data
15669 (calendar-cursor-to-date))))
15671 (defun org-date-from-calendar ()
15672 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15673 If there is already a time stamp at the cursor position, update it."
15674 (interactive)
15675 (if (org-at-timestamp-p t)
15676 (org-timestamp-change 0 'calendar)
15677 (let ((cal-date (org-get-date-from-calendar)))
15678 (org-insert-time-stamp
15679 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15681 (defun org-minutes-to-hh:mm-string (m)
15682 "Compute H:MM from a number of minutes."
15683 (let ((h (/ m 60)))
15684 (setq m (- m (* 60 h)))
15685 (format org-time-clocksum-format h m)))
15687 (defun org-hh:mm-string-to-minutes (s)
15688 "Convert a string H:MM to a number of minutes.
15689 If the string is just a number, interpret it as minutes.
15690 In fact, the first hh:mm or number in the string will be taken,
15691 there can be extra stuff in the string.
15692 If no number is found, the return value is 0."
15693 (cond
15694 ((integerp s) s)
15695 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
15696 (+ (* (string-to-number (match-string 1 s)) 60)
15697 (string-to-number (match-string 2 s))))
15698 ((string-match "\\([0-9]+\\)" s)
15699 (string-to-number (match-string 1 s)))
15700 (t 0)))
15702 (defcustom org-effort-durations
15703 `(("h" . 60)
15704 ("d" . ,(* 60 8))
15705 ("w" . ,(* 60 8 5))
15706 ("m" . ,(* 60 8 5 4))
15707 ("y" . ,(* 60 8 5 40)))
15708 "Conversion factor to minutes for an effort modifier.
15710 Each entry has the form (MODIFIER . MINUTES).
15712 In an effort string, a number followed by MODIFIER is multiplied
15713 by the specified number of MINUTES to obtain an effort in
15714 minutes.
15716 For example, if the value of this variable is ((\"hours\" . 60)), then an
15717 effort string \"2hours\" is equivalent to 120 minutes."
15718 :group 'org-agenda
15719 :type '(alist :key-type (string :tag "Modifier")
15720 :value-type (number :tag "Minutes")))
15722 (defun org-duration-string-to-minutes (s)
15723 "Convert a duration string S to minutes.
15725 A bare number is interpreted as minutes, modifiers can be set by
15726 customizing `org-effort-durations' (which see).
15728 Entries containing a colon are interpreted as H:MM by
15729 `org-hh:mm-string-to-minutes'."
15730 (let ((result 0)
15731 (re (concat "\\([0-9]+\\) *\\("
15732 (regexp-opt (mapcar 'car org-effort-durations))
15733 "\\)")))
15734 (while (string-match re s)
15735 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
15736 (string-to-number (match-string 1 s))))
15737 (setq s (replace-match "" nil t s)))
15738 (incf result (org-hh:mm-string-to-minutes s))
15739 result))
15741 ;;;; Files
15743 (defun org-save-all-org-buffers ()
15744 "Save all Org-mode buffers without user confirmation."
15745 (interactive)
15746 (message "Saving all Org-mode buffers...")
15747 (save-some-buffers t 'org-mode-p)
15748 (when (featurep 'org-id) (org-id-locations-save))
15749 (message "Saving all Org-mode buffers... done"))
15751 (defun org-revert-all-org-buffers ()
15752 "Revert all Org-mode buffers.
15753 Prompt for confirmation when there are unsaved changes.
15754 Be sure you know what you are doing before letting this function
15755 overwrite your changes.
15757 This function is useful in a setup where one tracks org files
15758 with a version control system, to revert on one machine after pulling
15759 changes from another. I believe the procedure must be like this:
15761 1. M-x org-save-all-org-buffers
15762 2. Pull changes from the other machine, resolve conflicts
15763 3. M-x org-revert-all-org-buffers"
15764 (interactive)
15765 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
15766 (error "Abort"))
15767 (save-excursion
15768 (save-window-excursion
15769 (mapc
15770 (lambda (b)
15771 (when (and (with-current-buffer b (org-mode-p))
15772 (with-current-buffer b buffer-file-name))
15773 (switch-to-buffer b)
15774 (revert-buffer t 'no-confirm)))
15775 (buffer-list))
15776 (when (and (featurep 'org-id) org-id-track-globally)
15777 (org-id-locations-load)))))
15779 ;;;; Agenda files
15781 ;;;###autoload
15782 (defun org-switchb (&optional arg)
15783 "Switch between Org buffers.
15784 With a prefix argument, restrict available to files.
15785 With two prefix arguments, restrict available buffers to agenda files.
15787 Defaults to `iswitchb' for buffer name completion.
15788 Set `org-completion-use-ido' to make it use ido instead."
15789 (interactive "P")
15790 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
15791 ((equal arg '(16)) (org-buffer-list 'agenda))
15792 (t (org-buffer-list))))
15793 (org-completion-use-iswitchb org-completion-use-iswitchb)
15794 (org-completion-use-ido org-completion-use-ido))
15795 (unless (or org-completion-use-ido org-completion-use-iswitchb)
15796 (setq org-completion-use-iswitchb t))
15797 (switch-to-buffer
15798 (org-icompleting-read "Org buffer: "
15799 (mapcar 'list (mapcar 'buffer-name blist))
15800 nil t))))
15802 ;;; Define some older names previously used for this functionality
15803 ;;;###autoload
15804 (defalias 'org-ido-switchb 'org-switchb)
15805 ;;;###autoload
15806 (defalias 'org-iswitchb 'org-switchb)
15808 (defun org-buffer-list (&optional predicate exclude-tmp)
15809 "Return a list of Org buffers.
15810 PREDICATE can be `export', `files' or `agenda'.
15812 export restrict the list to Export buffers.
15813 files restrict the list to buffers visiting Org files.
15814 agenda restrict the list to buffers visiting agenda files.
15816 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
15817 (let* ((bfn nil)
15818 (agenda-files (and (eq predicate 'agenda)
15819 (mapcar 'file-truename (org-agenda-files t))))
15820 (filter
15821 (cond
15822 ((eq predicate 'files)
15823 (lambda (b) (with-current-buffer b (org-mode-p))))
15824 ((eq predicate 'export)
15825 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
15826 ((eq predicate 'agenda)
15827 (lambda (b)
15828 (with-current-buffer b
15829 (and (org-mode-p)
15830 (setq bfn (buffer-file-name b))
15831 (member (file-truename bfn) agenda-files)))))
15832 (t (lambda (b) (with-current-buffer b
15833 (or (org-mode-p)
15834 (string-match "\*Org .*Export"
15835 (buffer-name b)))))))))
15836 (delq nil
15837 (mapcar
15838 (lambda(b)
15839 (if (and (funcall filter b)
15840 (or (not exclude-tmp)
15841 (not (string-match "tmp" (buffer-name b)))))
15843 nil))
15844 (buffer-list)))))
15846 (defun org-agenda-files (&optional unrestricted archives)
15847 "Get the list of agenda files.
15848 Optional UNRESTRICTED means return the full list even if a restriction
15849 is currently in place.
15850 When ARCHIVES is t, include all archive files that are really being
15851 used by the agenda files. If ARCHIVE is `ifmode', do this only if
15852 `org-agenda-archives-mode' is t."
15853 (let ((files
15854 (cond
15855 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
15856 ((stringp org-agenda-files) (org-read-agenda-file-list))
15857 ((listp org-agenda-files) org-agenda-files)
15858 (t (error "Invalid value of `org-agenda-files'")))))
15859 (setq files (apply 'append
15860 (mapcar (lambda (f)
15861 (if (file-directory-p f)
15862 (directory-files
15863 f t org-agenda-file-regexp)
15864 (list f)))
15865 files)))
15866 (when org-agenda-skip-unavailable-files
15867 (setq files (delq nil
15868 (mapcar (function
15869 (lambda (file)
15870 (and (file-readable-p file) file)))
15871 files))))
15872 (when (or (eq archives t)
15873 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
15874 (setq files (org-add-archive-files files)))
15875 files))
15877 (defun org-agenda-file-p (&optional file)
15878 "Return non-nil, if FILE is an agenda file.
15879 If FILE is omitted, use the file associated with the current
15880 buffer."
15881 (member (or file (buffer-file-name))
15882 (org-agenda-files t)))
15884 (defun org-edit-agenda-file-list ()
15885 "Edit the list of agenda files.
15886 Depending on setup, this either uses customize to edit the variable
15887 `org-agenda-files', or it visits the file that is holding the list. In the
15888 latter case, the buffer is set up in a way that saving it automatically kills
15889 the buffer and restores the previous window configuration."
15890 (interactive)
15891 (if (stringp org-agenda-files)
15892 (let ((cw (current-window-configuration)))
15893 (find-file org-agenda-files)
15894 (org-set-local 'org-window-configuration cw)
15895 (org-add-hook 'after-save-hook
15896 (lambda ()
15897 (set-window-configuration
15898 (prog1 org-window-configuration
15899 (kill-buffer (current-buffer))))
15900 (org-install-agenda-files-menu)
15901 (message "New agenda file list installed"))
15902 nil 'local)
15903 (message "%s" (substitute-command-keys
15904 "Edit list and finish with \\[save-buffer]")))
15905 (customize-variable 'org-agenda-files)))
15907 (defun org-store-new-agenda-file-list (list)
15908 "Set new value for the agenda file list and save it correctly."
15909 (if (stringp org-agenda-files)
15910 (let ((fe (org-read-agenda-file-list t)) b u)
15911 (while (setq b (find-buffer-visiting org-agenda-files))
15912 (kill-buffer b))
15913 (with-temp-file org-agenda-files
15914 (insert
15915 (mapconcat
15916 (lambda (f) ;; Keep un-expanded entries.
15917 (if (setq u (assoc f fe))
15918 (cdr u)
15920 list "\n")
15921 "\n")))
15922 (let ((org-mode-hook nil) (org-inhibit-startup t)
15923 (org-insert-mode-line-in-empty-file nil))
15924 (setq org-agenda-files list)
15925 (customize-save-variable 'org-agenda-files org-agenda-files))))
15927 (defun org-read-agenda-file-list (&optional pair-with-expansion)
15928 "Read the list of agenda files from a file.
15929 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
15930 filenames, used by `org-store-new-agenda-file-list' to write back
15931 un-expanded file names."
15932 (when (file-directory-p org-agenda-files)
15933 (error "`org-agenda-files' cannot be a single directory"))
15934 (when (stringp org-agenda-files)
15935 (with-temp-buffer
15936 (insert-file-contents org-agenda-files)
15937 (mapcar
15938 (lambda (f)
15939 (let ((e (expand-file-name (substitute-in-file-name f)
15940 org-directory)))
15941 (if pair-with-expansion
15942 (cons e f)
15943 e)))
15944 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
15946 ;;;###autoload
15947 (defun org-cycle-agenda-files ()
15948 "Cycle through the files in `org-agenda-files'.
15949 If the current buffer visits an agenda file, find the next one in the list.
15950 If the current buffer does not, find the first agenda file."
15951 (interactive)
15952 (let* ((fs (org-agenda-files t))
15953 (files (append fs (list (car fs))))
15954 (tcf (if buffer-file-name (file-truename buffer-file-name)))
15955 file)
15956 (unless files (error "No agenda files"))
15957 (catch 'exit
15958 (while (setq file (pop files))
15959 (if (equal (file-truename file) tcf)
15960 (when (car files)
15961 (find-file (car files))
15962 (throw 'exit t))))
15963 (find-file (car fs)))
15964 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
15966 (defun org-agenda-file-to-front (&optional to-end)
15967 "Move/add the current file to the top of the agenda file list.
15968 If the file is not present in the list, it is added to the front. If it is
15969 present, it is moved there. With optional argument TO-END, add/move to the
15970 end of the list."
15971 (interactive "P")
15972 (let ((org-agenda-skip-unavailable-files nil)
15973 (file-alist (mapcar (lambda (x)
15974 (cons (file-truename x) x))
15975 (org-agenda-files t)))
15976 (ctf (file-truename buffer-file-name))
15977 x had)
15978 (setq x (assoc ctf file-alist) had x)
15980 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
15981 (if to-end
15982 (setq file-alist (append (delq x file-alist) (list x)))
15983 (setq file-alist (cons x (delq x file-alist))))
15984 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
15985 (org-install-agenda-files-menu)
15986 (message "File %s to %s of agenda file list"
15987 (if had "moved" "added") (if to-end "end" "front"))))
15989 (defun org-remove-file (&optional file)
15990 "Remove current file from the list of files in variable `org-agenda-files'.
15991 These are the files which are being checked for agenda entries.
15992 Optional argument FILE means use this file instead of the current."
15993 (interactive)
15994 (let* ((org-agenda-skip-unavailable-files nil)
15995 (file (or file buffer-file-name))
15996 (true-file (file-truename file))
15997 (afile (abbreviate-file-name file))
15998 (files (delq nil (mapcar
15999 (lambda (x)
16000 (if (equal true-file
16001 (file-truename x))
16002 nil x))
16003 (org-agenda-files t)))))
16004 (if (not (= (length files) (length (org-agenda-files t))))
16005 (progn
16006 (org-store-new-agenda-file-list files)
16007 (org-install-agenda-files-menu)
16008 (message "Removed file: %s" afile))
16009 (message "File was not in list: %s (not removed)" afile))))
16011 (defun org-file-menu-entry (file)
16012 (vector file (list 'find-file file) t))
16014 (defun org-check-agenda-file (file)
16015 "Make sure FILE exists. If not, ask user what to do."
16016 (when (not (file-exists-p file))
16017 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16018 (abbreviate-file-name file))
16019 (let ((r (downcase (read-char-exclusive))))
16020 (cond
16021 ((equal r ?r)
16022 (org-remove-file file)
16023 (throw 'nextfile t))
16024 (t (error "Abort"))))))
16026 (defun org-get-agenda-file-buffer (file)
16027 "Get a buffer visiting FILE. If the buffer needs to be created, add
16028 it to the list of buffers which might be released later."
16029 (let ((buf (org-find-base-buffer-visiting file)))
16030 (if buf
16031 buf ; just return it
16032 ;; Make a new buffer and remember it
16033 (setq buf (find-file-noselect file))
16034 (if buf (push buf org-agenda-new-buffers))
16035 buf)))
16037 (defun org-release-buffers (blist)
16038 "Release all buffers in list, asking the user for confirmation when needed.
16039 When a buffer is unmodified, it is just killed. When modified, it is saved
16040 \(if the user agrees) and then killed."
16041 (let (buf file)
16042 (while (setq buf (pop blist))
16043 (setq file (buffer-file-name buf))
16044 (when (and (buffer-modified-p buf)
16045 file
16046 (y-or-n-p (format "Save file %s? " file)))
16047 (with-current-buffer buf (save-buffer)))
16048 (kill-buffer buf))))
16050 (defun org-prepare-agenda-buffers (files)
16051 "Create buffers for all agenda files, protect archived trees and comments."
16052 (interactive)
16053 (let ((pa '(:org-archived t))
16054 (pc '(:org-comment t))
16055 (pall '(:org-archived t :org-comment t))
16056 (inhibit-read-only t)
16057 (rea (concat ":" org-archive-tag ":"))
16058 bmp file re)
16059 (save-excursion
16060 (save-restriction
16061 (while (setq file (pop files))
16062 (catch 'nextfile
16063 (if (bufferp file)
16064 (set-buffer file)
16065 (org-check-agenda-file file)
16066 (set-buffer (org-get-agenda-file-buffer file)))
16067 (widen)
16068 (setq bmp (buffer-modified-p))
16069 (org-refresh-category-properties)
16070 (setq org-todo-keywords-for-agenda
16071 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16072 (setq org-done-keywords-for-agenda
16073 (append org-done-keywords-for-agenda org-done-keywords))
16074 (setq org-todo-keyword-alist-for-agenda
16075 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16076 (setq org-drawers-for-agenda
16077 (append org-drawers-for-agenda org-drawers))
16078 (setq org-tag-alist-for-agenda
16079 (append org-tag-alist-for-agenda org-tag-alist))
16081 (save-excursion
16082 (remove-text-properties (point-min) (point-max) pall)
16083 (when org-agenda-skip-archived-trees
16084 (goto-char (point-min))
16085 (while (re-search-forward rea nil t)
16086 (if (org-on-heading-p t)
16087 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16088 (goto-char (point-min))
16089 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
16090 (while (re-search-forward re nil t)
16091 (add-text-properties
16092 (match-beginning 0) (org-end-of-subtree t) pc)))
16093 (set-buffer-modified-p bmp)))))
16094 (setq org-todo-keywords-for-agenda
16095 (org-uniquify org-todo-keywords-for-agenda))
16096 (setq org-todo-keyword-alist-for-agenda
16097 (org-uniquify org-todo-keyword-alist-for-agenda)
16098 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16100 ;;;; Embedded LaTeX
16102 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16103 "Keymap for the minor `org-cdlatex-mode'.")
16105 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16106 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16107 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16108 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16109 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16111 (defvar org-cdlatex-texmathp-advice-is-done nil
16112 "Flag remembering if we have applied the advice to texmathp already.")
16114 (define-minor-mode org-cdlatex-mode
16115 "Toggle the minor `org-cdlatex-mode'.
16116 This mode supports entering LaTeX environment and math in LaTeX fragments
16117 in Org-mode.
16118 \\{org-cdlatex-mode-map}"
16119 nil " OCDL" nil
16120 (when org-cdlatex-mode (require 'cdlatex))
16121 (unless org-cdlatex-texmathp-advice-is-done
16122 (setq org-cdlatex-texmathp-advice-is-done t)
16123 (defadvice texmathp (around org-math-always-on activate)
16124 "Always return t in org-mode buffers.
16125 This is because we want to insert math symbols without dollars even outside
16126 the LaTeX math segments. If Orgmode thinks that point is actually inside
16127 an embedded LaTeX fragment, let texmathp do its job.
16128 \\[org-cdlatex-mode-map]"
16129 (interactive)
16130 (let (p)
16131 (cond
16132 ((not (org-mode-p)) ad-do-it)
16133 ((eq this-command 'cdlatex-math-symbol)
16134 (setq ad-return-value t
16135 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16137 (let ((p (org-inside-LaTeX-fragment-p)))
16138 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16139 (setq ad-return-value t
16140 texmathp-why '("Org-mode embedded math" . 0))
16141 (if p ad-do-it)))))))))
16143 (defun turn-on-org-cdlatex ()
16144 "Unconditionally turn on `org-cdlatex-mode'."
16145 (org-cdlatex-mode 1))
16147 (defun org-inside-LaTeX-fragment-p ()
16148 "Test if point is inside a LaTeX fragment.
16149 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16150 sequence appearing also before point.
16151 Even though the matchers for math are configurable, this function assumes
16152 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16153 delimiters are skipped when they have been removed by customization.
16154 The return value is nil, or a cons cell with the delimiter and the
16155 position of this delimiter.
16157 This function does a reasonably good job, but can locally be fooled by
16158 for example currency specifications. For example it will assume being in
16159 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16160 fragments that are properly closed, but during editing, we have to live
16161 with the uncertainty caused by missing closing delimiters. This function
16162 looks only before point, not after."
16163 (catch 'exit
16164 (let ((pos (point))
16165 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16166 (lim (progn
16167 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16168 (point)))
16169 dd-on str (start 0) m re)
16170 (goto-char pos)
16171 (when dodollar
16172 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16173 re (nth 1 (assoc "$" org-latex-regexps)))
16174 (while (string-match re str start)
16175 (cond
16176 ((= (match-end 0) (length str))
16177 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16178 ((= (match-end 0) (- (length str) 5))
16179 (throw 'exit nil))
16180 (t (setq start (match-end 0))))))
16181 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16182 (goto-char pos)
16183 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16184 (and (match-beginning 2) (throw 'exit nil))
16185 ;; count $$
16186 (while (re-search-backward "\\$\\$" lim t)
16187 (setq dd-on (not dd-on)))
16188 (goto-char pos)
16189 (if dd-on (cons "$$" m))))))
16191 (defun org-inside-latex-macro-p ()
16192 "Is point inside a LaTeX macro or its arguments?"
16193 (save-match-data
16194 (org-in-regexp
16195 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16197 (defun org-try-cdlatex-tab ()
16198 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16199 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16200 - inside a LaTeX fragment, or
16201 - after the first word in a line, where an abbreviation expansion could
16202 insert a LaTeX environment."
16203 (when org-cdlatex-mode
16204 (cond
16205 ((save-excursion
16206 (skip-chars-backward "a-zA-Z0-9*")
16207 (skip-chars-backward " \t")
16208 (bolp))
16209 (cdlatex-tab) t)
16210 ((org-inside-LaTeX-fragment-p)
16211 (cdlatex-tab) t)
16212 (t nil))))
16214 (defun org-cdlatex-underscore-caret (&optional arg)
16215 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16216 Revert to the normal definition outside of these fragments."
16217 (interactive "P")
16218 (if (org-inside-LaTeX-fragment-p)
16219 (call-interactively 'cdlatex-sub-superscript)
16220 (let (org-cdlatex-mode)
16221 (call-interactively (key-binding (vector last-input-event))))))
16223 (defun org-cdlatex-math-modify (&optional arg)
16224 "Execute `cdlatex-math-modify' in LaTeX fragments.
16225 Revert to the normal definition outside of these fragments."
16226 (interactive "P")
16227 (if (org-inside-LaTeX-fragment-p)
16228 (call-interactively 'cdlatex-math-modify)
16229 (let (org-cdlatex-mode)
16230 (call-interactively (key-binding (vector last-input-event))))))
16232 (defvar org-latex-fragment-image-overlays nil
16233 "List of overlays carrying the images of latex fragments.")
16234 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16236 (defun org-remove-latex-fragment-image-overlays ()
16237 "Remove all overlays with LaTeX fragment images in current buffer."
16238 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16239 (setq org-latex-fragment-image-overlays nil))
16241 (defun org-preview-latex-fragment (&optional subtree)
16242 "Preview the LaTeX fragment at point, or all locally or globally.
16243 If the cursor is in a LaTeX fragment, create the image and overlay
16244 it over the source code. If there is no fragment at point, display
16245 all fragments in the current text, from one headline to the next. With
16246 prefix SUBTREE, display all fragments in the current subtree. With a
16247 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16248 the cursor is before the first headline,
16249 display all fragments in the buffer.
16250 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16251 (interactive "P")
16252 (org-remove-latex-fragment-image-overlays)
16253 (save-excursion
16254 (save-restriction
16255 (let (beg end at msg)
16256 (cond
16257 ((or (equal subtree '(16))
16258 (not (save-excursion
16259 (re-search-backward (concat "^" outline-regexp) nil t))))
16260 (setq beg (point-min) end (point-max)
16261 msg "Creating images for buffer...%s"))
16262 ((equal subtree '(4))
16263 (org-back-to-heading)
16264 (setq beg (point) end (org-end-of-subtree t)
16265 msg "Creating images for subtree...%s"))
16267 (if (setq at (org-inside-LaTeX-fragment-p))
16268 (goto-char (max (point-min) (- (cdr at) 2)))
16269 (org-back-to-heading))
16270 (setq beg (point) end (progn (outline-next-heading) (point))
16271 msg (if at "Creating image...%s"
16272 "Creating images for entry...%s"))))
16273 (message msg "")
16274 (narrow-to-region beg end)
16275 (goto-char beg)
16276 (org-format-latex
16277 (concat "ltxpng/" (file-name-sans-extension
16278 (file-name-nondirectory
16279 buffer-file-name)))
16280 default-directory 'overlays msg at 'forbuffer 'dvipng)
16281 (message msg "done. Use `C-c C-c' to remove images.")))))
16283 (defvar org-latex-regexps
16284 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16285 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16286 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16287 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16288 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16289 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16290 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16291 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16292 "Regular expressions for matching embedded LaTeX.")
16294 (defvar org-export-have-math nil) ;; dynamic scoping
16295 (defun org-format-latex (prefix &optional dir overlays msg at
16296 forbuffer processing-type)
16297 "Replace LaTeX fragments with links to an image, and produce images.
16298 Some of the options can be changed using the variable
16299 `org-format-latex-options'."
16300 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16301 (let* ((prefixnodir (file-name-nondirectory prefix))
16302 (absprefix (expand-file-name prefix dir))
16303 (todir (file-name-directory absprefix))
16304 (opt org-format-latex-options)
16305 (matchers (plist-get opt :matchers))
16306 (re-list org-latex-regexps)
16307 (org-format-latex-header-extra
16308 (plist-get (org-infile-export-plist) :latex-header-extra))
16309 (cnt 0) txt hash link beg end re e checkdir
16310 executables-checked string
16311 m n block linkfile movefile ov)
16312 ;; Check the different regular expressions
16313 (while (setq e (pop re-list))
16314 (setq m (car e) re (nth 1 e) n (nth 2 e)
16315 block (if (nth 3 e) "\n\n" ""))
16316 (when (member m matchers)
16317 (goto-char (point-min))
16318 (while (re-search-forward re nil t)
16319 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16320 (not (get-text-property (match-beginning n)
16321 'org-protected))
16322 (or (not overlays)
16323 (not (eq (get-char-property (match-beginning n)
16324 'org-overlay-type)
16325 'org-latex-overlay))))
16326 (setq org-export-have-math t)
16327 (cond
16328 ((eq processing-type 'verbatim)
16329 ;; Leave the text verbatim, just protect it
16330 (add-text-properties (match-beginning n) (match-end n)
16331 '(org-protected t)))
16332 ((eq processing-type 'mathjax)
16333 ;; Prepare for MathJax processing
16334 (setq string (match-string n))
16335 (if (member m '("$" "$1"))
16336 (save-excursion
16337 (delete-region (match-beginning n) (match-end n))
16338 (goto-char (match-beginning n))
16339 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16340 "\\)")
16341 '(org-protected t))))
16342 (add-text-properties (match-beginning n) (match-end n)
16343 '(org-protected t))))
16344 ((or (eq processing-type 'dvipng) t)
16345 ;; Process to an image
16346 (setq txt (match-string n)
16347 beg (match-beginning n) end (match-end n)
16348 cnt (1+ cnt))
16349 (let (print-length print-level) ; make sure full list is printed
16350 (setq hash (sha1 (prin1-to-string
16351 (list org-format-latex-header
16352 org-format-latex-header-extra
16353 org-export-latex-default-packages-alist
16354 org-export-latex-packages-alist
16355 org-format-latex-options
16356 forbuffer txt)))
16357 linkfile (format "%s_%s.png" prefix hash)
16358 movefile (format "%s_%s.png" absprefix hash)))
16359 (setq link (concat block "[[file:" linkfile "]]" block))
16360 (if msg (message msg cnt))
16361 (goto-char beg)
16362 (unless checkdir ; make sure the directory exists
16363 (setq checkdir t)
16364 (or (file-directory-p todir) (make-directory todir t)))
16366 (unless executables-checked
16367 (org-check-external-command
16368 "latex" "needed to convert LaTeX fragments to images")
16369 (org-check-external-command
16370 "dvipng" "needed to convert LaTeX fragments to images")
16371 (setq executables-checked t))
16373 (unless (file-exists-p movefile)
16374 (org-create-formula-image
16375 txt movefile opt forbuffer))
16376 (if overlays
16377 (progn
16378 (mapc (lambda (o)
16379 (if (eq (overlay-get o 'org-overlay-type)
16380 'org-latex-overlay)
16381 (delete-overlay o)))
16382 (overlays-in beg end))
16383 (setq ov (make-overlay beg end))
16384 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16385 (if (featurep 'xemacs)
16386 (progn
16387 (overlay-put ov 'invisible t)
16388 (overlay-put
16389 ov 'end-glyph
16390 (make-glyph (vector 'png :file movefile))))
16391 (overlay-put
16392 ov 'display
16393 (list 'image :type 'png :file movefile :ascent 'center)))
16394 (push ov org-latex-fragment-image-overlays)
16395 (goto-char end))
16396 (delete-region beg end)
16397 (insert (org-add-props link
16398 (list 'org-latex-src
16399 (replace-regexp-in-string
16400 "\"" "" txt)))))))))))))
16402 ;; This function borrows from Ganesh Swami's latex2png.el
16403 (defun org-create-formula-image (string tofile options buffer)
16404 "This calls dvipng."
16405 (require 'org-latex)
16406 (let* ((tmpdir (if (featurep 'xemacs)
16407 (temp-directory)
16408 temporary-file-directory))
16409 (texfilebase (make-temp-name
16410 (expand-file-name "orgtex" tmpdir)))
16411 (texfile (concat texfilebase ".tex"))
16412 (dvifile (concat texfilebase ".dvi"))
16413 (pngfile (concat texfilebase ".png"))
16414 (fnh (if (featurep 'xemacs)
16415 (font-height (get-face-font 'default))
16416 (face-attribute 'default :height nil)))
16417 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16418 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16419 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16420 "Black"))
16421 (bg (or (plist-get options (if buffer :background :html-background))
16422 "Transparent")))
16423 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16424 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16425 (with-temp-file texfile
16426 (insert (org-splice-latex-header
16427 org-format-latex-header
16428 org-export-latex-default-packages-alist
16429 org-export-latex-packages-alist t
16430 org-format-latex-header-extra))
16431 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16432 (require 'org-latex)
16433 (org-export-latex-fix-inputenc))
16434 (let ((dir default-directory))
16435 (condition-case nil
16436 (progn
16437 (cd tmpdir)
16438 (call-process "latex" nil nil nil texfile))
16439 (error nil))
16440 (cd dir))
16441 (if (not (file-exists-p dvifile))
16442 (progn (message "Failed to create dvi file from %s" texfile) nil)
16443 (condition-case nil
16444 (call-process "dvipng" nil nil nil
16445 "-fg" fg "-bg" bg
16446 "-D" dpi
16447 ;;"-x" scale "-y" scale
16448 "-T" "tight"
16449 "-o" pngfile
16450 dvifile)
16451 (error nil))
16452 (if (not (file-exists-p pngfile))
16453 (if org-format-latex-signal-error
16454 (error "Failed to create png file from %s" texfile)
16455 (message "Failed to create png file from %s" texfile)
16456 nil)
16457 ;; Use the requested file name and clean up
16458 (copy-file pngfile tofile 'replace)
16459 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16460 (delete-file (concat texfilebase e)))
16461 pngfile))))
16463 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16464 "Fill a LaTeX header template TPL.
16465 In the template, the following place holders will be recognized:
16467 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16468 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16469 [PACKAGES] \\usepackage statements for PKG
16470 [NO-PACKAGES] do not include PKG
16471 [EXTRA] the string EXTRA
16472 [NO-EXTRA] do not include EXTRA
16474 For backward compatibility, if both the positive and the negative place
16475 holder is missing, the positive one (without the \"NO-\") will be
16476 assumed to be present at the end of the template.
16477 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16478 EXTRA is a string.
16479 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16480 (let (rpl (end ""))
16481 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16482 (setq rpl (if (or (match-end 1) (not def-pkg))
16483 "" (org-latex-packages-to-string def-pkg snippets-p t))
16484 tpl (replace-match rpl t t tpl))
16485 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16487 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16488 (setq rpl (if (or (match-end 1) (not pkg))
16489 "" (org-latex-packages-to-string pkg snippets-p t))
16490 tpl (replace-match rpl t t tpl))
16491 (if pkg (setq end
16492 (concat end "\n"
16493 (org-latex-packages-to-string pkg snippets-p)))))
16495 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16496 (setq rpl (if (or (match-end 1) (not extra))
16497 "" (concat extra "\n"))
16498 tpl (replace-match rpl t t tpl))
16499 (if (and extra (string-match "\\S-" extra))
16500 (setq end (concat end "\n" extra))))
16502 (if (string-match "\\S-" end)
16503 (concat tpl "\n" end)
16504 tpl)))
16506 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16507 "Turn an alist of packages into a string with the \\usepackage macros."
16508 (setq pkg (mapconcat (lambda(p)
16509 (cond
16510 ((stringp p) p)
16511 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16512 (format "%% Package %s omitted" (cadr p)))
16513 ((equal "" (car p))
16514 (format "\\usepackage{%s}" (cadr p)))
16516 (format "\\usepackage[%s]{%s}"
16517 (car p) (cadr p)))))
16519 "\n"))
16520 (if newline (concat pkg "\n") pkg))
16522 (defun org-dvipng-color (attr)
16523 "Return an rgb color specification for dvipng."
16524 (apply 'format "rgb %s %s %s"
16525 (mapcar 'org-normalize-color
16526 (color-values (face-attribute 'default attr nil)))))
16528 (defun org-normalize-color (value)
16529 "Return string to be used as color value for an RGB component."
16530 (format "%g" (/ value 65535.0)))
16532 ;; Image display
16535 (defvar org-inline-image-overlays nil)
16536 (make-variable-buffer-local 'org-inline-image-overlays)
16538 (defun org-toggle-inline-images (&optional include-linked)
16539 "Toggle the display of inline images.
16540 INCLUDE-LINKED is passed to `org-display-inline-images'."
16541 (interactive "P")
16542 (if org-inline-image-overlays
16543 (progn
16544 (org-remove-inline-images)
16545 (message "Inline image display turned off"))
16546 (org-display-inline-images include-linked)
16547 (if org-inline-image-overlays
16548 (message "%d images displayed inline"
16549 (length org-inline-image-overlays))
16550 (message "No images to display inline"))))
16552 (defun org-display-inline-images (&optional include-linked refresh beg end)
16553 "Display inline images.
16554 Normally only links without a description part are inlined, because this
16555 is how it will work for export. When INCLUDE-LINKED is set, also links
16556 with a description part will be inlined. This can be nice for a quick
16557 look at those images, but it does not reflect what exported files will look
16558 like.
16559 When REFRESH is set, refresh existing images between BEG and END.
16560 This will create new image displays only if necessary.
16561 BEG and END default to the buffer boundaries."
16562 (interactive "P")
16563 (unless refresh
16564 (org-remove-inline-images)
16565 (if (fboundp 'clear-image-cache) (clear-image-cache)))
16566 (save-excursion
16567 (save-restriction
16568 (widen)
16569 (setq beg (or beg (point-min)) end (or end (point-max)))
16570 (goto-char (point-min))
16571 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
16572 (substring (org-image-file-name-regexp) 0 -2)
16573 "\\)\\]" (if include-linked "" "\\]")))
16574 old file ov img)
16575 (while (re-search-forward re end t)
16576 (setq old (get-char-property-and-overlay (match-beginning 1)
16577 'org-image-overlay))
16578 (setq file (expand-file-name
16579 (concat (or (match-string 3) "") (match-string 4))))
16580 (when (file-exists-p file)
16581 (if (and (car-safe old) refresh)
16582 (image-refresh (overlay-get (cdr old) 'display))
16583 (setq img (save-match-data (create-image file)))
16584 (when img
16585 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
16586 (overlay-put ov 'display img)
16587 (overlay-put ov 'face 'default)
16588 (overlay-put ov 'org-image-overlay t)
16589 (overlay-put ov 'modification-hooks
16590 (list 'org-display-inline-modification-hook))
16591 (push ov org-inline-image-overlays)))))))))
16593 (defun org-display-inline-modification-hook (ov after beg end &optional len)
16594 "Remove inline-display overlay if a corresponding region is modified."
16595 (let ((inhibit-modification-hooks t))
16596 (when (and ov after)
16597 (delete ov org-inline-image-overlays)
16598 (delete-overlay ov))))
16600 (defun org-remove-inline-images ()
16601 "Remove inline display of images."
16602 (interactive)
16603 (mapc 'delete-overlay org-inline-image-overlays)
16604 (setq org-inline-image-overlays nil))
16606 ;;;; Key bindings
16608 ;; Make `C-c C-x' a prefix key
16609 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
16611 ;; TAB key with modifiers
16612 (org-defkey org-mode-map "\C-i" 'org-cycle)
16613 (org-defkey org-mode-map [(tab)] 'org-cycle)
16614 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
16615 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
16616 (org-defkey org-mode-map "\M-\t" 'pcomplete)
16617 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
16618 ;; The following line is necessary under Suse GNU/Linux
16619 (unless (featurep 'xemacs)
16620 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
16621 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
16622 (define-key org-mode-map [backtab] 'org-shifttab)
16624 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
16625 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
16626 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
16628 ;; Cursor keys with modifiers
16629 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
16630 (org-defkey org-mode-map [(meta right)] 'org-metaright)
16631 (org-defkey org-mode-map [(meta up)] 'org-metaup)
16632 (org-defkey org-mode-map [(meta down)] 'org-metadown)
16634 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
16635 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
16636 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
16637 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
16639 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
16640 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
16641 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
16642 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
16644 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
16645 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
16647 ;; Babel keys
16648 (define-key org-mode-map org-babel-key-prefix org-babel-map)
16649 (mapc (lambda (pair)
16650 (define-key org-babel-map (car pair) (cdr pair)))
16651 org-babel-key-bindings)
16653 ;;; Extra keys for tty access.
16654 ;; We only set them when really needed because otherwise the
16655 ;; menus don't show the simple keys
16657 (when (or org-use-extra-keys
16658 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
16659 (not window-system))
16660 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
16661 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
16662 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
16663 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
16664 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
16665 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
16666 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
16667 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
16668 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
16669 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
16670 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
16671 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
16672 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
16673 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16674 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16675 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16676 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
16677 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
16678 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
16679 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
16680 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
16681 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
16682 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
16683 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
16684 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
16685 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
16686 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
16687 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
16689 ;; All the other keys
16691 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16692 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
16693 (if (boundp 'narrow-map)
16694 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
16695 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
16696 (if (boundp 'narrow-map)
16697 (org-defkey narrow-map "b" 'org-narrow-to-block)
16698 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
16699 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
16700 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
16701 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
16702 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
16703 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
16704 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
16705 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
16706 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
16707 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
16708 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
16709 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
16710 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
16711 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
16712 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
16713 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
16714 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
16715 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
16716 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
16717 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
16718 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
16719 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
16720 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
16721 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
16722 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
16723 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
16724 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
16725 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
16726 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
16727 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
16728 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16729 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16730 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16731 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16732 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
16733 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
16734 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16735 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
16736 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
16737 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
16738 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
16739 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16740 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
16741 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
16742 (org-defkey org-mode-map "\C-c^" 'org-sort)
16743 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16744 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
16745 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
16746 (org-defkey org-mode-map "\C-m" 'org-return)
16747 (org-defkey org-mode-map "\C-j" 'org-return-indent)
16748 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
16749 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
16750 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
16751 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
16752 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
16753 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
16754 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16755 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16756 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
16757 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
16758 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
16759 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
16760 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
16761 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16762 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
16763 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
16764 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
16765 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
16766 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
16767 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
16768 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
16770 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
16771 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16772 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16773 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16775 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16776 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16777 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16778 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
16779 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16780 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16781 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16782 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16783 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16784 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
16785 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
16786 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16787 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
16788 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
16789 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
16790 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
16791 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
16792 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
16794 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
16795 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
16796 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
16797 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
16798 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
16800 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
16802 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
16804 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
16805 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
16807 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
16810 (when (featurep 'xemacs)
16811 (org-defkey org-mode-map 'button3 'popup-mode-menu))
16814 (defconst org-speed-commands-default
16816 ("Outline Navigation")
16817 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
16818 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
16819 ("f" . (org-speed-move-safe 'org-forward-same-level))
16820 ("b" . (org-speed-move-safe 'org-backward-same-level))
16821 ("u" . (org-speed-move-safe 'outline-up-heading))
16822 ("j" . org-goto)
16823 ("g" . (org-refile t))
16824 ("Outline Visibility")
16825 ("c" . org-cycle)
16826 ("C" . org-shifttab)
16827 (" " . org-display-outline-path)
16828 ("Outline Structure Editing")
16829 ("U" . org-shiftmetaup)
16830 ("D" . org-shiftmetadown)
16831 ("r" . org-metaright)
16832 ("l" . org-metaleft)
16833 ("R" . org-shiftmetaright)
16834 ("L" . org-shiftmetaleft)
16835 ("i" . (progn (forward-char 1) (call-interactively
16836 'org-insert-heading-respect-content)))
16837 ("^" . org-sort)
16838 ("w" . org-refile)
16839 ("a" . org-archive-subtree-default-with-confirmation)
16840 ("." . org-mark-subtree)
16841 ("Clock Commands")
16842 ("I" . org-clock-in)
16843 ("O" . org-clock-out)
16844 ("Meta Data Editing")
16845 ("t" . org-todo)
16846 ("0" . (org-priority ?\ ))
16847 ("1" . (org-priority ?A))
16848 ("2" . (org-priority ?B))
16849 ("3" . (org-priority ?C))
16850 (";" . org-set-tags-command)
16851 ("e" . org-set-effort)
16852 ("Agenda Views etc")
16853 ("v" . org-agenda)
16854 ("/" . org-sparse-tree)
16855 ("Misc")
16856 ("o" . org-open-at-point)
16857 ("?" . org-speed-command-help)
16858 ("<" . (org-agenda-set-restriction-lock 'subtree))
16859 (">" . (org-agenda-remove-restriction-lock))
16861 "The default speed commands.")
16863 (defun org-print-speed-command (e)
16864 (if (> (length (car e)) 1)
16865 (progn
16866 (princ "\n")
16867 (princ (car e))
16868 (princ "\n")
16869 (princ (make-string (length (car e)) ?-))
16870 (princ "\n"))
16871 (princ (car e))
16872 (princ " ")
16873 (if (symbolp (cdr e))
16874 (princ (symbol-name (cdr e)))
16875 (prin1 (cdr e)))
16876 (princ "\n")))
16878 (defun org-speed-command-help ()
16879 "Show the available speed commands."
16880 (interactive)
16881 (if (not org-use-speed-commands)
16882 (error "Speed commands are not activated, customize `org-use-speed-commands'")
16883 (with-output-to-temp-buffer "*Help*"
16884 (princ "User-defined Speed commands\n===========================\n")
16885 (mapc 'org-print-speed-command org-speed-commands-user)
16886 (princ "\n")
16887 (princ "Built-in Speed commands\n=======================\n")
16888 (mapc 'org-print-speed-command org-speed-commands-default))
16889 (with-current-buffer "*Help*"
16890 (setq truncate-lines t))))
16892 (defun org-speed-move-safe (cmd)
16893 "Execute CMD, but make sure that the cursor always ends up in a headline.
16894 If not, return to the original position and throw an error."
16895 (interactive)
16896 (let ((pos (point)))
16897 (call-interactively cmd)
16898 (unless (and (bolp) (org-on-heading-p))
16899 (goto-char pos)
16900 (error "Boundary reached while executing %s" cmd))))
16902 (defvar org-self-insert-command-undo-counter 0)
16904 (defvar org-table-auto-blank-field) ; defined in org-table.el
16905 (defvar org-speed-command nil)
16907 (defun org-speed-command-default-hook (keys)
16908 "Hook for activating single-letter speed commands.
16909 `org-speed-commands-default' specifies a minimal command set. Use
16910 `org-speed-commands-user' for further customization."
16911 (when (or (and (bolp) (looking-at outline-regexp))
16912 (and (functionp org-use-speed-commands)
16913 (funcall org-use-speed-commands)))
16914 (cdr (assoc keys (append org-speed-commands-user
16915 org-speed-commands-default)))))
16917 (defun org-babel-speed-command-hook (keys)
16918 "Hook for activating single-letter code block commands."
16919 (when (and (bolp) (looking-at org-babel-src-block-regexp))
16920 (cdr (assoc keys org-babel-key-bindings))))
16922 (defcustom org-speed-command-hook
16923 '(org-speed-command-default-hook org-babel-speed-command-hook)
16924 "Hook for activating speed commands at strategic locations.
16925 Hook functions are called in sequence until a valid handler is
16926 found.
16928 Each hook takes a single argument, a user-pressed command key
16929 which is also a `self-insert-command' from the global map.
16931 Within the hook, examine the cursor position and the command key
16932 and return nil or a valid handler as appropriate. Handler could
16933 be one of an interactive command, a function, or a form.
16935 Set `org-use-speed-commands' to non-nil value to enable this
16936 hook. The default setting is `org-speed-command-default-hook'."
16937 :group 'org-structure
16938 :type 'hook)
16940 (defun org-self-insert-command (N)
16941 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16942 If the cursor is in a table looking at whitespace, the whitespace is
16943 overwritten, and the table is not marked as requiring realignment."
16944 (interactive "p")
16945 (cond
16946 ((and org-use-speed-commands
16947 (setq org-speed-command
16948 (run-hook-with-args-until-success
16949 'org-speed-command-hook (this-command-keys))))
16950 (cond
16951 ((commandp org-speed-command)
16952 (setq this-command org-speed-command)
16953 (call-interactively org-speed-command))
16954 ((functionp org-speed-command)
16955 (funcall org-speed-command))
16956 ((and org-speed-command (listp org-speed-command))
16957 (eval org-speed-command))
16958 (t (let (org-use-speed-commands)
16959 (call-interactively 'org-self-insert-command)))))
16960 ((and
16961 (org-table-p)
16962 (progn
16963 ;; check if we blank the field, and if that triggers align
16964 (and (featurep 'org-table) org-table-auto-blank-field
16965 (member last-command
16966 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
16967 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16968 ;; got extra space, this field does not determine column width
16969 (let (org-table-may-need-update) (org-table-blank-field))
16970 ;; no extra space, this field may determine column width
16971 (org-table-blank-field)))
16973 (eq N 1)
16974 (looking-at "[^|\n]* |"))
16975 (let (org-table-may-need-update)
16976 (goto-char (1- (match-end 0)))
16977 (delete-char -1)
16978 (goto-char (match-beginning 0))
16979 (self-insert-command N)))
16981 (setq org-table-may-need-update t)
16982 (self-insert-command N)
16983 (org-fix-tags-on-the-fly)
16984 (if org-self-insert-cluster-for-undo
16985 (if (not (eq last-command 'org-self-insert-command))
16986 (setq org-self-insert-command-undo-counter 1)
16987 (if (>= org-self-insert-command-undo-counter 20)
16988 (setq org-self-insert-command-undo-counter 1)
16989 (and (> org-self-insert-command-undo-counter 0)
16990 buffer-undo-list (listp buffer-undo-list)
16991 (not (cadr buffer-undo-list)) ; remove nil entry
16992 (setcdr buffer-undo-list (cddr buffer-undo-list)))
16993 (setq org-self-insert-command-undo-counter
16994 (1+ org-self-insert-command-undo-counter))))))))
16996 (defun org-fix-tags-on-the-fly ()
16997 (when (and (equal (char-after (point-at-bol)) ?*)
16998 (org-on-heading-p))
16999 (org-align-tags-here org-tags-column)))
17001 (defun org-delete-backward-char (N)
17002 "Like `delete-backward-char', insert whitespace at field end in tables.
17003 When deleting backwards, in tables this function will insert whitespace in
17004 front of the next \"|\" separator, to keep the table aligned. The table will
17005 still be marked for re-alignment if the field did fill the entire column,
17006 because, in this case the deletion might narrow the column."
17007 (interactive "p")
17008 (if (and (org-table-p)
17009 (eq N 1)
17010 (string-match "|" (buffer-substring (point-at-bol) (point)))
17011 (looking-at ".*?|"))
17012 (let ((pos (point))
17013 (noalign (looking-at "[^|\n\r]* |"))
17014 (c org-table-may-need-update))
17015 (backward-delete-char N)
17016 (if (not overwrite-mode)
17017 (progn
17018 (skip-chars-forward "^|")
17019 (insert " ")
17020 (goto-char (1- pos))))
17021 ;; noalign: if there were two spaces at the end, this field
17022 ;; does not determine the width of the column.
17023 (if noalign (setq org-table-may-need-update c)))
17024 (backward-delete-char N)
17025 (org-fix-tags-on-the-fly)))
17027 (defun org-delete-char (N)
17028 "Like `delete-char', but insert whitespace at field end in tables.
17029 When deleting characters, in tables this function will insert whitespace in
17030 front of the next \"|\" separator, to keep the table aligned. The table will
17031 still be marked for re-alignment if the field did fill the entire column,
17032 because, in this case the deletion might narrow the column."
17033 (interactive "p")
17034 (if (and (org-table-p)
17035 (not (bolp))
17036 (not (= (char-after) ?|))
17037 (eq N 1))
17038 (if (looking-at ".*?|")
17039 (let ((pos (point))
17040 (noalign (looking-at "[^|\n\r]* |"))
17041 (c org-table-may-need-update))
17042 (replace-match (concat
17043 (substring (match-string 0) 1 -1)
17044 " |"))
17045 (goto-char pos)
17046 ;; noalign: if there were two spaces at the end, this field
17047 ;; does not determine the width of the column.
17048 (if noalign (setq org-table-may-need-update c)))
17049 (delete-char N))
17050 (delete-char N)
17051 (org-fix-tags-on-the-fly)))
17053 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17054 (put 'org-self-insert-command 'delete-selection t)
17055 (put 'orgtbl-self-insert-command 'delete-selection t)
17056 (put 'org-delete-char 'delete-selection 'supersede)
17057 (put 'org-delete-backward-char 'delete-selection 'supersede)
17058 (put 'org-yank 'delete-selection 'yank)
17060 ;; Make `flyspell-mode' delay after some commands
17061 (put 'org-self-insert-command 'flyspell-delayed t)
17062 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17063 (put 'org-delete-char 'flyspell-delayed t)
17064 (put 'org-delete-backward-char 'flyspell-delayed t)
17066 ;; Make pabbrev-mode expand after org-mode commands
17067 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17068 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17070 ;; How to do this: Measure non-white length of current string
17071 ;; If equal to column width, we should realign.
17073 (defun org-remap (map &rest commands)
17074 "In MAP, remap the functions given in COMMANDS.
17075 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17076 (let (new old)
17077 (while commands
17078 (setq old (pop commands) new (pop commands))
17079 (if (fboundp 'command-remapping)
17080 (org-defkey map (vector 'remap old) new)
17081 (substitute-key-definition old new map global-map)))))
17083 (when (eq org-enable-table-editor 'optimized)
17084 ;; If the user wants maximum table support, we need to hijack
17085 ;; some standard editing functions
17086 (org-remap org-mode-map
17087 'self-insert-command 'org-self-insert-command
17088 'delete-char 'org-delete-char
17089 'delete-backward-char 'org-delete-backward-char)
17090 (org-defkey org-mode-map "|" 'org-force-self-insert))
17092 (defvar org-ctrl-c-ctrl-c-hook nil
17093 "Hook for functions attaching themselves to `C-c C-c'.
17094 This can be used to add additional functionality to the C-c C-c key which
17095 executes context-dependent commands.
17096 Each function will be called with no arguments. The function must check
17097 if the context is appropriate for it to act. If yes, it should do its
17098 thing and then return a non-nil value. If the context is wrong,
17099 just do nothing and return nil.")
17101 (defvar org-tab-first-hook nil
17102 "Hook for functions to attach themselves to TAB.
17103 See `org-ctrl-c-ctrl-c-hook' for more information.
17104 This hook runs as the first action when TAB is pressed, even before
17105 `org-cycle' messes around with the `outline-regexp' to cater for
17106 inline tasks and plain list item folding.
17107 If any function in this hook returns t, any other actions that
17108 would have been caused by TAB (such as table field motion or visibility
17109 cycling) will not occur.")
17111 (defvar org-tab-after-check-for-table-hook nil
17112 "Hook for functions to attach themselves to TAB.
17113 See `org-ctrl-c-ctrl-c-hook' for more information.
17114 This hook runs after it has been established that the cursor is not in a
17115 table, but before checking if the cursor is in a headline or if global cycling
17116 should be done.
17117 If any function in this hook returns t, not other actions like visibility
17118 cycling will be done.")
17120 (defvar org-tab-after-check-for-cycling-hook nil
17121 "Hook for functions to attach themselves to TAB.
17122 See `org-ctrl-c-ctrl-c-hook' for more information.
17123 This hook runs after it has been established that not table field motion and
17124 not visibility should be done because of current context. This is probably
17125 the place where a package like yasnippets can hook in.")
17127 (defvar org-tab-before-tab-emulation-hook nil
17128 "Hook for functions to attach themselves to TAB.
17129 See `org-ctrl-c-ctrl-c-hook' for more information.
17130 This hook runs after every other options for TAB have been exhausted, but
17131 before indentation and \t insertion takes place.")
17133 (defvar org-metaleft-hook nil
17134 "Hook for functions attaching themselves to `M-left'.
17135 See `org-ctrl-c-ctrl-c-hook' for more information.")
17136 (defvar org-metaright-hook nil
17137 "Hook for functions attaching themselves to `M-right'.
17138 See `org-ctrl-c-ctrl-c-hook' for more information.")
17139 (defvar org-metaup-hook nil
17140 "Hook for functions attaching themselves to `M-up'.
17141 See `org-ctrl-c-ctrl-c-hook' for more information.")
17142 (defvar org-metadown-hook nil
17143 "Hook for functions attaching themselves to `M-down'.
17144 See `org-ctrl-c-ctrl-c-hook' for more information.")
17145 (defvar org-shiftmetaleft-hook nil
17146 "Hook for functions attaching themselves to `M-S-left'.
17147 See `org-ctrl-c-ctrl-c-hook' for more information.")
17148 (defvar org-shiftmetaright-hook nil
17149 "Hook for functions attaching themselves to `M-S-right'.
17150 See `org-ctrl-c-ctrl-c-hook' for more information.")
17151 (defvar org-shiftmetaup-hook nil
17152 "Hook for functions attaching themselves to `M-S-up'.
17153 See `org-ctrl-c-ctrl-c-hook' for more information.")
17154 (defvar org-shiftmetadown-hook nil
17155 "Hook for functions attaching themselves to `M-S-down'.
17156 See `org-ctrl-c-ctrl-c-hook' for more information.")
17157 (defvar org-metareturn-hook nil
17158 "Hook for functions attaching themselves to `M-RET'.
17159 See `org-ctrl-c-ctrl-c-hook' for more information.")
17160 (defvar org-shiftup-hook nil
17161 "Hook for functions attaching themselves to `S-up'.
17162 See `org-ctrl-c-ctrl-c-hook' for more information.")
17163 (defvar org-shiftup-final-hook nil
17164 "Hook for functions attaching themselves to `S-up'.
17165 This one runs after all other options except shift-select have been excluded.
17166 See `org-ctrl-c-ctrl-c-hook' for more information.")
17167 (defvar org-shiftdown-hook nil
17168 "Hook for functions attaching themselves to `S-down'.
17169 See `org-ctrl-c-ctrl-c-hook' for more information.")
17170 (defvar org-shiftdown-final-hook nil
17171 "Hook for functions attaching themselves to `S-down'.
17172 This one runs after all other options except shift-select have been excluded.
17173 See `org-ctrl-c-ctrl-c-hook' for more information.")
17174 (defvar org-shiftleft-hook nil
17175 "Hook for functions attaching themselves to `S-left'.
17176 See `org-ctrl-c-ctrl-c-hook' for more information.")
17177 (defvar org-shiftleft-final-hook nil
17178 "Hook for functions attaching themselves to `S-left'.
17179 This one runs after all other options except shift-select have been excluded.
17180 See `org-ctrl-c-ctrl-c-hook' for more information.")
17181 (defvar org-shiftright-hook nil
17182 "Hook for functions attaching themselves to `S-right'.
17183 See `org-ctrl-c-ctrl-c-hook' for more information.")
17184 (defvar org-shiftright-final-hook nil
17185 "Hook for functions attaching themselves to `S-right'.
17186 This one runs after all other options except shift-select have been excluded.
17187 See `org-ctrl-c-ctrl-c-hook' for more information.")
17189 (defun org-modifier-cursor-error ()
17190 "Throw an error, a modified cursor command was applied in wrong context."
17191 (error "This command is active in special context like tables, headlines or items"))
17193 (defun org-shiftselect-error ()
17194 "Throw an error because Shift-Cursor command was applied in wrong context."
17195 (if (and (boundp 'shift-select-mode) shift-select-mode)
17196 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17197 (error "This command works only in special context like headlines or timestamps")))
17199 (defun org-call-for-shift-select (cmd)
17200 (let ((this-command-keys-shift-translated t))
17201 (call-interactively cmd)))
17203 (defun org-shifttab (&optional arg)
17204 "Global visibility cycling or move to previous table field.
17205 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17206 on context.
17207 See the individual commands for more information."
17208 (interactive "P")
17209 (cond
17210 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17211 ((integerp arg)
17212 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17213 (message "Content view to level: %d" arg)
17214 (org-content (prefix-numeric-value arg2))
17215 (setq org-cycle-global-status 'overview)))
17216 (t (call-interactively 'org-global-cycle))))
17218 (defun org-shiftmetaleft ()
17219 "Promote subtree or delete table column.
17220 Calls `org-promote-subtree', `org-outdent-item',
17221 or `org-table-delete-column', depending on context.
17222 See the individual commands for more information."
17223 (interactive)
17224 (cond
17225 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17226 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17227 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17228 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17229 (t (org-modifier-cursor-error))))
17231 (defun org-shiftmetaright ()
17232 "Demote subtree or insert table column.
17233 Calls `org-demote-subtree', `org-indent-item',
17234 or `org-table-insert-column', depending on context.
17235 See the individual commands for more information."
17236 (interactive)
17237 (cond
17238 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17239 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17240 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17241 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17242 (t (org-modifier-cursor-error))))
17244 (defun org-shiftmetaup (&optional arg)
17245 "Move subtree up or kill table row.
17246 Calls `org-move-subtree-up' or `org-table-kill-row' or
17247 `org-move-item-up' depending on context. See the individual commands
17248 for more information."
17249 (interactive "P")
17250 (cond
17251 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17252 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17253 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17254 ((org-at-item-p) (call-interactively 'org-move-item-up))
17255 (t (org-modifier-cursor-error))))
17257 (defun org-shiftmetadown (&optional arg)
17258 "Move subtree down or insert table row.
17259 Calls `org-move-subtree-down' or `org-table-insert-row' or
17260 `org-move-item-down', depending on context. See the individual
17261 commands for more information."
17262 (interactive "P")
17263 (cond
17264 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17265 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17266 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17267 ((org-at-item-p) (call-interactively 'org-move-item-down))
17268 (t (org-modifier-cursor-error))))
17270 (defsubst org-hidden-tree-error ()
17271 (error
17272 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17274 (defun org-metaleft (&optional arg)
17275 "Promote heading or move table column to left.
17276 Calls `org-do-promote' or `org-table-move-column', depending on context.
17277 With no specific context, calls the Emacs default `backward-word'.
17278 See the individual commands for more information."
17279 (interactive "P")
17280 (cond
17281 ((run-hook-with-args-until-success 'org-metaleft-hook))
17282 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17283 ((org-with-limited-levels
17284 (or (org-on-heading-p)
17285 (and (org-region-active-p)
17286 (save-excursion
17287 (goto-char (region-beginning))
17288 (org-on-heading-p)))))
17289 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17290 (call-interactively 'org-do-promote))
17291 ;; At an inline task.
17292 ((org-on-heading-p)
17293 (call-interactively 'org-inlinetask-promote))
17294 ((or (org-at-item-p)
17295 (and (org-region-active-p)
17296 (save-excursion
17297 (goto-char (region-beginning))
17298 (org-at-item-p))))
17299 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17300 (call-interactively 'org-outdent-item))
17301 (t (call-interactively 'backward-word))))
17303 (defun org-metaright (&optional arg)
17304 "Demote subtree or move table column to right.
17305 Calls `org-do-demote' or `org-table-move-column', depending on context.
17306 With no specific context, calls the Emacs default `forward-word'.
17307 See the individual commands for more information."
17308 (interactive "P")
17309 (cond
17310 ((run-hook-with-args-until-success 'org-metaright-hook))
17311 ((org-at-table-p) (call-interactively 'org-table-move-column))
17312 ((org-with-limited-levels
17313 (or (org-on-heading-p)
17314 (and (org-region-active-p)
17315 (save-excursion
17316 (goto-char (region-beginning))
17317 (org-on-heading-p)))))
17318 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17319 (call-interactively 'org-do-demote))
17320 ;; At an inline task.
17321 ((org-on-heading-p)
17322 (call-interactively 'org-inlinetask-demote))
17323 ((or (org-at-item-p)
17324 (and (org-region-active-p)
17325 (save-excursion
17326 (goto-char (region-beginning))
17327 (org-at-item-p))))
17328 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17329 (call-interactively 'org-indent-item))
17330 (t (call-interactively 'forward-word))))
17332 (defun org-check-for-hidden (what)
17333 "Check if there are hidden headlines/items in the current visual line.
17334 WHAT can be either `headlines' or `items'. If the current line is
17335 an outline or item heading and it has a folded subtree below it,
17336 this function returns t, nil otherwise."
17337 (let ((re (cond
17338 ((eq what 'headlines) (concat "^" org-outline-regexp))
17339 ((eq what 'items) (org-item-beginning-re))
17340 (t (error "This should not happen"))))
17341 beg end)
17342 (save-excursion
17343 (catch 'exit
17344 (unless (org-region-active-p)
17345 (setq beg (point-at-bol))
17346 (beginning-of-line 2)
17347 (while (and (not (eobp)) ;; this is like `next-line'
17348 (get-char-property (1- (point)) 'invisible))
17349 (beginning-of-line 2))
17350 (setq end (point))
17351 (goto-char beg)
17352 (goto-char (point-at-eol))
17353 (setq end (max end (point)))
17354 (while (re-search-forward re end t)
17355 (if (get-char-property (match-beginning 0) 'invisible)
17356 (throw 'exit t))))
17357 nil))))
17359 (defun org-metaup (&optional arg)
17360 "Move subtree up or move table row up.
17361 Calls `org-move-subtree-up' or `org-table-move-row' or
17362 `org-move-item-up', depending on context. See the individual commands
17363 for more information."
17364 (interactive "P")
17365 (cond
17366 ((run-hook-with-args-until-success 'org-metaup-hook))
17367 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17368 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17369 ((org-at-item-p) (call-interactively 'org-move-item-up))
17370 (t (transpose-lines 1) (beginning-of-line -1))))
17372 (defun org-metadown (&optional arg)
17373 "Move subtree down or move table row down.
17374 Calls `org-move-subtree-down' or `org-table-move-row' or
17375 `org-move-item-down', depending on context. See the individual
17376 commands for more information."
17377 (interactive "P")
17378 (cond
17379 ((run-hook-with-args-until-success 'org-metadown-hook))
17380 ((org-at-table-p) (call-interactively 'org-table-move-row))
17381 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17382 ((org-at-item-p) (call-interactively 'org-move-item-down))
17383 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17385 (defun org-shiftup (&optional arg)
17386 "Increase item in timestamp or increase priority of current headline.
17387 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17388 depending on context. See the individual commands for more information."
17389 (interactive "P")
17390 (cond
17391 ((run-hook-with-args-until-success 'org-shiftup-hook))
17392 ((and org-support-shift-select (org-region-active-p))
17393 (org-call-for-shift-select 'previous-line))
17394 ((org-at-timestamp-p t)
17395 (call-interactively (if org-edit-timestamp-down-means-later
17396 'org-timestamp-down 'org-timestamp-up)))
17397 ((and (not (eq org-support-shift-select 'always))
17398 org-enable-priority-commands
17399 (org-on-heading-p))
17400 (call-interactively 'org-priority-up))
17401 ((and (not org-support-shift-select) (org-at-item-p))
17402 (call-interactively 'org-previous-item))
17403 ((org-clocktable-try-shift 'up arg))
17404 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17405 (org-support-shift-select
17406 (org-call-for-shift-select 'previous-line))
17407 (t (org-shiftselect-error))))
17409 (defun org-shiftdown (&optional arg)
17410 "Decrease item in timestamp or decrease priority of current headline.
17411 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
17412 depending on context. See the individual commands for more information."
17413 (interactive "P")
17414 (cond
17415 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17416 ((and org-support-shift-select (org-region-active-p))
17417 (org-call-for-shift-select 'next-line))
17418 ((org-at-timestamp-p t)
17419 (call-interactively (if org-edit-timestamp-down-means-later
17420 'org-timestamp-up 'org-timestamp-down)))
17421 ((and (not (eq org-support-shift-select 'always))
17422 org-enable-priority-commands
17423 (org-on-heading-p))
17424 (call-interactively 'org-priority-down))
17425 ((and (not org-support-shift-select) (org-at-item-p))
17426 (call-interactively 'org-next-item))
17427 ((org-clocktable-try-shift 'down arg))
17428 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17429 (org-support-shift-select
17430 (org-call-for-shift-select 'next-line))
17431 (t (org-shiftselect-error))))
17433 (defun org-shiftright (&optional arg)
17434 "Cycle the thing at point or in the current line, depending on context.
17435 Depending on context, this does one of the following:
17437 - switch a timestamp at point one day into the future
17438 - on a headline, switch to the next TODO keyword.
17439 - on an item, switch entire list to the next bullet type
17440 - on a property line, switch to the next allowed value
17441 - on a clocktable definition line, move time block into the future"
17442 (interactive "P")
17443 (cond
17444 ((run-hook-with-args-until-success 'org-shiftright-hook))
17445 ((and org-support-shift-select (org-region-active-p))
17446 (org-call-for-shift-select 'forward-char))
17447 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17448 ((and (not (eq org-support-shift-select 'always))
17449 (org-on-heading-p))
17450 (let ((org-inhibit-logging
17451 (not org-treat-S-cursor-todo-selection-as-state-change))
17452 (org-inhibit-blocking
17453 (not org-treat-S-cursor-todo-selection-as-state-change)))
17454 (org-call-with-arg 'org-todo 'right)))
17455 ((or (and org-support-shift-select
17456 (not (eq org-support-shift-select 'always))
17457 (org-at-item-bullet-p))
17458 (and (not org-support-shift-select) (org-at-item-p)))
17459 (org-call-with-arg 'org-cycle-list-bullet nil))
17460 ((and (not (eq org-support-shift-select 'always))
17461 (org-at-property-p))
17462 (call-interactively 'org-property-next-allowed-value))
17463 ((org-clocktable-try-shift 'right arg))
17464 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
17465 (org-support-shift-select
17466 (org-call-for-shift-select 'forward-char))
17467 (t (org-shiftselect-error))))
17469 (defun org-shiftleft (&optional arg)
17470 "Cycle the thing at point or in the current line, depending on context.
17471 Depending on context, this does one of the following:
17473 - switch a timestamp at point one day into the past
17474 - on a headline, switch to the previous TODO keyword.
17475 - on an item, switch entire list to the previous bullet type
17476 - on a property line, switch to the previous allowed value
17477 - on a clocktable definition line, move time block into the past"
17478 (interactive "P")
17479 (cond
17480 ((run-hook-with-args-until-success 'org-shiftleft-hook))
17481 ((and org-support-shift-select (org-region-active-p))
17482 (org-call-for-shift-select 'backward-char))
17483 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17484 ((and (not (eq org-support-shift-select 'always))
17485 (org-on-heading-p))
17486 (let ((org-inhibit-logging
17487 (not org-treat-S-cursor-todo-selection-as-state-change))
17488 (org-inhibit-blocking
17489 (not org-treat-S-cursor-todo-selection-as-state-change)))
17490 (org-call-with-arg 'org-todo 'left)))
17491 ((or (and org-support-shift-select
17492 (not (eq org-support-shift-select 'always))
17493 (org-at-item-bullet-p))
17494 (and (not org-support-shift-select) (org-at-item-p)))
17495 (org-call-with-arg 'org-cycle-list-bullet 'previous))
17496 ((and (not (eq org-support-shift-select 'always))
17497 (org-at-property-p))
17498 (call-interactively 'org-property-previous-allowed-value))
17499 ((org-clocktable-try-shift 'left arg))
17500 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
17501 (org-support-shift-select
17502 (org-call-for-shift-select 'backward-char))
17503 (t (org-shiftselect-error))))
17505 (defun org-shiftcontrolright ()
17506 "Switch to next TODO set."
17507 (interactive)
17508 (cond
17509 ((and org-support-shift-select (org-region-active-p))
17510 (org-call-for-shift-select 'forward-word))
17511 ((and (not (eq org-support-shift-select 'always))
17512 (org-on-heading-p))
17513 (org-call-with-arg 'org-todo 'nextset))
17514 (org-support-shift-select
17515 (org-call-for-shift-select 'forward-word))
17516 (t (org-shiftselect-error))))
17518 (defun org-shiftcontrolleft ()
17519 "Switch to previous TODO set."
17520 (interactive)
17521 (cond
17522 ((and org-support-shift-select (org-region-active-p))
17523 (org-call-for-shift-select 'backward-word))
17524 ((and (not (eq org-support-shift-select 'always))
17525 (org-on-heading-p))
17526 (org-call-with-arg 'org-todo 'previousset))
17527 (org-support-shift-select
17528 (org-call-for-shift-select 'backward-word))
17529 (t (org-shiftselect-error))))
17531 (defun org-ctrl-c-ret ()
17532 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
17533 (interactive)
17534 (cond
17535 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
17536 (t (call-interactively 'org-insert-heading))))
17538 (defun org-copy-special ()
17539 "Copy region in table or copy current subtree.
17540 Calls `org-table-copy' or `org-copy-subtree', depending on context.
17541 See the individual commands for more information."
17542 (interactive)
17543 (call-interactively
17544 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
17546 (defun org-cut-special ()
17547 "Cut region in table or cut current subtree.
17548 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17549 See the individual commands for more information."
17550 (interactive)
17551 (call-interactively
17552 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17554 (defun org-paste-special (arg)
17555 "Paste rectangular region into table, or past subtree relative to level.
17556 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17557 See the individual commands for more information."
17558 (interactive "P")
17559 (if (org-at-table-p)
17560 (org-table-paste-rectangle)
17561 (org-paste-subtree arg)))
17563 (defun org-edit-special (&optional arg)
17564 "Call a special editor for the stuff at point.
17565 When at a table, call the formula editor with `org-table-edit-formulas'.
17566 When at the first line of an src example, call `org-edit-src-code'.
17567 When in an #+include line, visit the include file. Otherwise call
17568 `ffap' to visit the file at point."
17569 (interactive)
17570 ;; possibly prep session before editing source
17571 (when arg
17572 (let* ((info (org-babel-get-src-block-info))
17573 (lang (nth 0 info))
17574 (params (nth 2 info))
17575 (session (cdr (assoc :session params))))
17576 (when (and info session) ;; we are in a source-code block with a session
17577 (funcall
17578 (intern (concat "org-babel-prep-session:" lang)) session params))))
17579 (cond ;; proceed with `org-edit-special'
17580 ((save-excursion
17581 (beginning-of-line 1)
17582 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
17583 (find-file (org-trim (match-string 1))))
17584 ((org-edit-src-code))
17585 ((org-edit-fixed-width-region))
17586 ((org-at-table.el-p)
17587 (org-edit-src-code))
17588 ((or (org-at-table-p)
17589 (save-excursion
17590 (beginning-of-line 1)
17591 (looking-at "[ \t]*#\\+TBLFM:")))
17592 (call-interactively 'org-table-edit-formulas))
17593 (t (call-interactively 'ffap))))
17595 (defun org-ctrl-c-ctrl-c (&optional arg)
17596 "Set tags in headline, or update according to changed information at point.
17598 This command does many different things, depending on context:
17600 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
17601 this is what we do.
17603 - If the cursor is on a statistics cookie, update it.
17605 - If the cursor is in a headline, prompt for tags and insert them
17606 into the current line, aligned to `org-tags-column'. When called
17607 with prefix arg, realign all tags in the current buffer.
17609 - If the cursor is in one of the special #+KEYWORD lines, this
17610 triggers scanning the buffer for these lines and updating the
17611 information.
17613 - If the cursor is inside a table, realign the table. This command
17614 works even if the automatic table editor has been turned off.
17616 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17617 the entire table.
17619 - If the cursor is at a footnote reference or definition, jump to
17620 the corresponding definition or references, respectively.
17622 - If the cursor is a the beginning of a dynamic block, update it.
17624 - If the current buffer is a capture buffer, close note and file it.
17626 - If the cursor is on a <<<target>>>, update radio targets and
17627 corresponding links in this buffer.
17629 - If the cursor is on a numbered item in a plain list, renumber the
17630 ordered list.
17632 - If the cursor is on a checkbox, toggle it.
17634 - If the cursor is on a code block, evaluate it. The variable
17635 `org-confirm-babel-evaluate' can be used to control prompting
17636 before code block evaluation, by default every code block
17637 evaluation requires confirmation. Code block evaluation can be
17638 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
17639 (interactive "P")
17640 (let ((org-enable-table-editor t))
17641 (cond
17642 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
17643 org-occur-highlights
17644 org-latex-fragment-image-overlays)
17645 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
17646 (org-remove-occur-highlights)
17647 (org-remove-latex-fragment-image-overlays)
17648 (message "Temporary highlights/overlays removed from current buffer"))
17649 ((and (local-variable-p 'org-finish-function (current-buffer))
17650 (fboundp org-finish-function))
17651 (funcall org-finish-function))
17652 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
17653 ((or (looking-at org-property-start-re)
17654 (org-at-property-p))
17655 (call-interactively 'org-property-action))
17656 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17657 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
17658 (or (org-on-heading-p) (org-at-item-p)))
17659 (call-interactively 'org-update-statistics-cookies))
17660 ((org-on-heading-p) (call-interactively 'org-set-tags))
17661 ((org-at-table.el-p)
17662 (message "Use C-c ' to edit table.el tables"))
17663 ((org-at-table-p)
17664 (org-table-maybe-eval-formula)
17665 (if arg
17666 (call-interactively 'org-table-recalculate)
17667 (org-table-maybe-recalculate-line))
17668 (call-interactively 'org-table-align)
17669 (orgtbl-send-table 'maybe))
17670 ((or (org-footnote-at-reference-p)
17671 (org-footnote-at-definition-p))
17672 (call-interactively 'org-footnote-action))
17673 ((org-at-item-checkbox-p)
17674 ;; Cursor at a checkbox: repair list and update checkboxes. Send
17675 ;; list only if at top item.
17676 (let* ((cbox (match-string 1))
17677 (struct (org-list-struct))
17678 (old-struct (copy-tree struct))
17679 (parents (org-list-parents-alist struct))
17680 (prevs (org-list-prevs-alist struct))
17681 (orderedp (org-entry-get nil "ORDERED"))
17682 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
17683 block-item)
17684 ;; Use a light version of `org-toggle-checkbox' to avoid
17685 ;; computing list structure twice.
17686 (org-list-set-checkbox (point-at-bol) struct
17687 (cond
17688 ((equal arg '(16)) "[-]")
17689 ((equal arg '(4)) nil)
17690 ((equal "[X]" cbox) "[ ]")
17691 (t "[X]")))
17692 (org-list-struct-fix-ind struct parents)
17693 (org-list-struct-fix-bul struct prevs)
17694 (setq block-item
17695 (org-list-struct-fix-box struct parents prevs orderedp))
17696 (when block-item
17697 (message
17698 "Checkboxes were removed due to unchecked box at line %d"
17699 (org-current-line block-item)))
17700 (org-list-struct-apply-struct struct old-struct)
17701 (org-update-checkbox-count-maybe)
17702 (when firstp (org-list-send-list 'maybe))))
17703 ((org-at-item-p)
17704 ;; Cursor at an item: repair list. Do checkbox related actions
17705 ;; only if function was called with an argument. Send list only
17706 ;; if at top item.
17707 (let* ((struct (org-list-struct))
17708 (old-struct (copy-tree struct))
17709 (parents (org-list-parents-alist struct))
17710 (prevs (org-list-prevs-alist struct))
17711 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
17712 (org-list-struct-fix-ind struct parents)
17713 (org-list-struct-fix-bul struct prevs)
17714 (when arg
17715 (org-list-set-checkbox (point-at-bol) struct "[ ]")
17716 (org-list-struct-fix-box struct parents prevs))
17717 (org-list-struct-apply-struct struct old-struct)
17718 (when arg (org-update-checkbox-count-maybe))
17719 (when firstp (org-list-send-list 'maybe))))
17720 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
17721 ;; Dynamic block
17722 (beginning-of-line 1)
17723 (save-excursion (org-update-dblock)))
17724 ((save-excursion
17725 (beginning-of-line 1)
17726 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
17727 (cond
17728 ((equal (match-string 1) "TBLFM")
17729 ;; Recalculate the table before this line
17730 (save-excursion
17731 (beginning-of-line 1)
17732 (skip-chars-backward " \r\n\t")
17733 (if (org-at-table-p)
17734 (org-call-with-arg 'org-table-recalculate (or arg t)))))
17736 (let ((org-inhibit-startup-visibility-stuff t)
17737 (org-startup-align-all-tables nil))
17738 (org-save-outline-visibility 'use-markers (org-mode-restart)))
17739 (message "Local setup has been refreshed"))))
17740 ((org-clock-update-time-maybe))
17741 (t (error "C-c C-c can do nothing useful at this location")))))
17743 (defun org-mode-restart ()
17744 "Restart Org-mode, to scan again for special lines.
17745 Also updates the keyword regular expressions."
17746 (interactive)
17747 (org-mode)
17748 (message "Org-mode restarted"))
17750 (defun org-kill-note-or-show-branches ()
17751 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
17752 (interactive)
17753 (if (not org-finish-function)
17754 (progn
17755 (hide-subtree)
17756 (call-interactively 'show-branches))
17757 (let ((org-note-abort t))
17758 (funcall org-finish-function))))
17760 (defun org-return (&optional indent)
17761 "Goto next table row or insert a newline.
17762 Calls `org-table-next-row' or `newline', depending on context.
17763 See the individual commands for more information."
17764 (interactive)
17765 (cond
17766 ((bobp) (if indent (newline-and-indent) (newline)))
17767 ((org-at-table-p)
17768 (org-table-justify-field-maybe)
17769 (call-interactively 'org-table-next-row))
17770 ;; when `newline-and-indent' is called within a list, make sure
17771 ;; text moved stays inside the item.
17772 ((and (org-in-item-p) indent)
17773 (if (and (org-at-item-p) (>= (point) (match-end 0)))
17774 (progn
17775 (newline)
17776 (org-indent-line-to (length (match-string 0))))
17777 (let ((ind (org-get-indentation)))
17778 (newline)
17779 (if (org-looking-back org-list-end-re)
17780 (org-indent-line-function)
17781 (org-indent-line-to ind)))))
17782 ((and org-return-follows-link
17783 (eq (get-text-property (point) 'face) 'org-link))
17784 (call-interactively 'org-open-at-point))
17785 ((and (org-at-heading-p)
17786 (looking-at
17787 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
17788 (org-show-entry)
17789 (end-of-line 1)
17790 (newline))
17791 (t (if indent (newline-and-indent) (newline)))))
17793 (defun org-return-indent ()
17794 "Goto next table row or insert a newline and indent.
17795 Calls `org-table-next-row' or `newline-and-indent', depending on
17796 context. See the individual commands for more information."
17797 (interactive)
17798 (org-return t))
17800 (defun org-ctrl-c-star ()
17801 "Compute table, or change heading status of lines.
17802 Calls `org-table-recalculate' or `org-toggle-heading',
17803 depending on context."
17804 (interactive)
17805 (cond
17806 ((org-at-table-p)
17807 (call-interactively 'org-table-recalculate))
17809 ;; Convert all lines in region to list items
17810 (call-interactively 'org-toggle-heading))))
17812 (defun org-ctrl-c-minus ()
17813 "Insert separator line in table or modify bullet status of line.
17814 Also turns a plain line or a region of lines into list items.
17815 Calls `org-table-insert-hline', `org-toggle-item', or
17816 `org-cycle-list-bullet', depending on context."
17817 (interactive)
17818 (cond
17819 ((org-at-table-p)
17820 (call-interactively 'org-table-insert-hline))
17821 ((org-region-active-p)
17822 (call-interactively 'org-toggle-item))
17823 ((org-in-item-p)
17824 (call-interactively 'org-cycle-list-bullet))
17826 (call-interactively 'org-toggle-item))))
17828 (defun org-toggle-item (arg)
17829 "Convert headings or normal lines to items, items to normal lines.
17830 If there is no active region, only the current line is considered.
17832 If the first non blank line in the region is an headline, convert
17833 all headlines to items, shifting text accordingly.
17835 If it is an item, convert all items to normal lines.
17837 If it is normal text, change region into an item. With a prefix
17838 argument ARG, change each line in region into an item."
17839 (interactive "P")
17840 (let ((shift-text
17841 (function
17842 ;; Shift text in current section to IND, from point to END.
17843 ;; The function leaves point to END line.
17844 (lambda (ind end)
17845 (let ((min-i 1000) (end (copy-marker end)))
17846 ;; First determine the minimum indentation (MIN-I) of
17847 ;; the text.
17848 (save-excursion
17849 (catch 'exit
17850 (while (< (point) end)
17851 (let ((i (org-get-indentation)))
17852 (cond
17853 ;; Skip blank lines and inline tasks.
17854 ((looking-at "^[ \t]*$"))
17855 ((looking-at "^\\*+ "))
17856 ;; We can't find less than 0 indentation.
17857 ((zerop i) (throw 'exit (setq min-i 0)))
17858 ((< i min-i) (setq min-i i))))
17859 (forward-line))))
17860 ;; Then indent each line so that a line indented to
17861 ;; MIN-I becomes indented to IND. Ignore blank lines
17862 ;; and inline tasks in the process.
17863 (let ((delta (- ind min-i)))
17864 (while (< (point) end)
17865 (unless (or (looking-at "^[ \t]*$")
17866 (looking-at "^\\*+ "))
17867 (org-indent-line-to (+ (org-get-indentation) delta)))
17868 (forward-line)))))))
17869 (skip-blanks
17870 (function
17871 ;; Return beginning of first non-blank line, starting from
17872 ;; line at POS.
17873 (lambda (pos)
17874 (save-excursion
17875 (goto-char pos)
17876 (skip-chars-forward " \r\t\n")
17877 (point-at-bol)))))
17878 beg end)
17879 ;; Determine boundaries of changes.
17880 (if (org-region-active-p)
17881 (setq beg (funcall skip-blanks (region-beginning))
17882 end (copy-marker (region-end)))
17883 (setq beg (funcall skip-blanks (point-at-bol))
17884 end (copy-marker (point-at-eol))))
17885 ;; Depending on the starting line, choose an action on the text
17886 ;; between BEG and END.
17887 (org-with-limited-levels
17888 (save-excursion
17889 (goto-char beg)
17890 (cond
17891 ;; Case 1. Start at an item: de-itemize. Note that it only
17892 ;; happens when a region is active: `org-ctrl-c-minus'
17893 ;; would call `org-cycle-list-bullet' otherwise.
17894 ((org-at-item-p)
17895 (while (< (point) end)
17896 (when (org-at-item-p)
17897 (skip-chars-forward " \t")
17898 (delete-region (point) (match-end 0)))
17899 (forward-line)))
17900 ;; Case 2. Start at an heading: convert to items.
17901 ((org-on-heading-p)
17902 (let* ((bul (org-list-bullet-string "-"))
17903 (bul-len (length bul))
17904 ;; Indentation of the first heading. It should be
17905 ;; relative to the indentation of its parent, if any.
17906 (start-ind (save-excursion
17907 (cond
17908 ((not org-adapt-indentation) 0)
17909 ((not (outline-previous-heading)) 0)
17910 (t (length (match-string 0))))))
17911 ;; Level of first heading. Further headings will be
17912 ;; compared to it to determine hierarchy in the list.
17913 (ref-level (org-reduced-level (org-outline-level))))
17914 (while (< (point) end)
17915 (let* ((level (org-reduced-level (org-outline-level)))
17916 (delta (max 0 (- level ref-level))))
17917 ;; If current headline is less indented than the first
17918 ;; one, set it as reference, in order to preserve
17919 ;; subtrees.
17920 (when (< level ref-level) (setq ref-level level))
17921 (replace-match bul t t)
17922 (org-indent-line-to (+ start-ind (* delta bul-len)))
17923 ;; Ensure all text down to END (or SECTION-END) belongs
17924 ;; to the newly created item.
17925 (let ((section-end (save-excursion
17926 (or (outline-next-heading) (point)))))
17927 (forward-line)
17928 (funcall shift-text
17929 (+ start-ind (* (1+ delta) bul-len))
17930 (min end section-end)))))))
17931 ;; Case 3. Normal line with ARG: turn each non-item line into
17932 ;; an item.
17933 (arg
17934 (while (< (point) end)
17935 (unless (or (org-on-heading-p) (org-at-item-p))
17936 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17937 (replace-match
17938 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
17939 (forward-line)))
17940 ;; Case 4. Normal line without ARG: make the first line of
17941 ;; region an item, and shift indentation of others
17942 ;; lines to set them as item's body.
17943 (t (let* ((bul (org-list-bullet-string "-"))
17944 (bul-len (length bul))
17945 (ref-ind (org-get-indentation)))
17946 (skip-chars-forward " \t")
17947 (insert bul)
17948 (forward-line)
17949 (while (< (point) end)
17950 ;; Ensure that lines less indented than first one
17951 ;; still get included in item body.
17952 (funcall shift-text
17953 (+ ref-ind bul-len)
17954 (min end (save-excursion (or (outline-next-heading)
17955 (point)))))
17956 (forward-line)))))))))
17958 (defun org-toggle-heading (&optional nstars)
17959 "Convert headings to normal text, or items or text to headings.
17960 If there is no active region, only the current line is considered.
17962 If the first non blank line is an headline, remove the stars from
17963 all headlines in the region.
17965 If it is a plain list item, turn all plain list items into headings.
17967 If it is a normal line, turn each and every normal line (i.e. not
17968 an heading or an item) in the region into a heading.
17970 When converting a line into a heading, the number of stars is chosen
17971 such that the lines become children of the current entry. However,
17972 when a prefix argument is given, its value determines the number of
17973 stars to add."
17974 (interactive "P")
17975 (let ((skip-blanks
17976 (function
17977 ;; Return beginning of first non-blank line, starting from
17978 ;; line at POS.
17979 (lambda (pos)
17980 (save-excursion
17981 (goto-char pos)
17982 (skip-chars-forward " \r\t\n")
17983 (point-at-bol)))))
17984 beg end)
17985 ;; Determine boundaries of changes. If region ends at a bol, do
17986 ;; not consider the last line to be in the region.
17987 (if (org-region-active-p)
17988 (setq beg (funcall skip-blanks (region-beginning))
17989 end (copy-marker (save-excursion
17990 (goto-char (region-end))
17991 (if (bolp) (point) (point-at-eol)))))
17992 (setq beg (funcall skip-blanks (point-at-bol))
17993 end (copy-marker (point-at-eol))))
17994 ;; Ensure inline tasks don't count as headings.
17995 (org-with-limited-levels
17996 (save-excursion
17997 (goto-char beg)
17998 (cond
17999 ;; Case 1. Started at an heading: de-star headings.
18000 ((org-on-heading-p)
18001 (while (< (point) end)
18002 (when (org-on-heading-p t)
18003 (looking-at outline-regexp) (replace-match ""))
18004 (forward-line)))
18005 ;; Case 2. Started at an item: change items into headlines.
18006 ;; One star will be added by `org-list-to-subtree'.
18007 ((org-at-item-p)
18008 (let* ((stars (make-string
18009 (if nstars
18010 ;; subtract the star that will be added again by
18011 ;; `org-list-to-subtree'
18012 (1- (prefix-numeric-value current-prefix-arg))
18013 (or (org-current-level) 0))
18014 ?*))
18015 (add-stars
18016 (cond (nstars "") ; stars from prefix only
18017 ((equal stars "") "") ; before first heading
18018 (org-odd-levels-only "*") ; inside heading, odd
18019 (t "")))) ; inside heading, oddeven
18020 (while (< (point) end)
18021 (when (org-at-item-p)
18022 ;; Pay attention to cases when region ends before list.
18023 (let* ((struct (org-list-struct))
18024 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18025 (save-restriction
18026 (narrow-to-region (point) list-end)
18027 (insert
18028 (org-list-to-subtree
18029 (org-list-parse-list t)
18030 '(:istart (concat stars add-stars (funcall get-stars depth))
18031 :icount (concat stars add-stars (funcall get-stars depth))))))))
18032 (forward-line))))
18033 ;; Case 3. Started at normal text: make every line an heading,
18034 ;; skipping headlines and items.
18035 (t (let* ((stars (make-string
18036 (if nstars
18037 (prefix-numeric-value current-prefix-arg)
18038 (or (org-current-level) 0))
18039 ?*))
18040 (add-stars
18041 (cond (nstars "") ; stars from prefix only
18042 ((equal stars "") "*") ; before first heading
18043 (org-odd-levels-only "**") ; inside heading, odd
18044 (t "*"))) ; inside heading, oddeven
18045 (rpl (concat stars add-stars " ")))
18046 (while (< (point) end)
18047 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
18048 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18049 (replace-match (concat rpl (match-string 2))))
18050 (forward-line)))))))))
18052 (defun org-meta-return (&optional arg)
18053 "Insert a new heading or wrap a region in a table.
18054 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18055 See the individual commands for more information."
18056 (interactive "P")
18057 (cond
18058 ((run-hook-with-args-until-success 'org-metareturn-hook))
18059 ((org-at-table-p)
18060 (call-interactively 'org-table-wrap-region))
18061 (t (call-interactively 'org-insert-heading))))
18063 ;;; Menu entries
18065 ;; Define the Org-mode menus
18066 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18067 '("Tbl"
18068 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18069 ["Next Field" org-cycle (org-at-table-p)]
18070 ["Previous Field" org-shifttab (org-at-table-p)]
18071 ["Next Row" org-return (org-at-table-p)]
18072 "--"
18073 ["Blank Field" org-table-blank-field (org-at-table-p)]
18074 ["Edit Field" org-table-edit-field (org-at-table-p)]
18075 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18076 "--"
18077 ("Column"
18078 ["Move Column Left" org-metaleft (org-at-table-p)]
18079 ["Move Column Right" org-metaright (org-at-table-p)]
18080 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18081 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18082 ("Row"
18083 ["Move Row Up" org-metaup (org-at-table-p)]
18084 ["Move Row Down" org-metadown (org-at-table-p)]
18085 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18086 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18087 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18088 "--"
18089 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18090 ("Rectangle"
18091 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18092 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18093 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18094 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18095 "--"
18096 ("Calculate"
18097 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18098 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18099 ["Edit Formulas" org-edit-special (org-at-table-p)]
18100 "--"
18101 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18102 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18103 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18104 "--"
18105 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18106 "--"
18107 ["Sum Column/Rectangle" org-table-sum
18108 (or (org-at-table-p) (org-region-active-p))]
18109 ["Which Column?" org-table-current-column (org-at-table-p)])
18110 ["Debug Formulas"
18111 org-table-toggle-formula-debugger
18112 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18113 ["Show Col/Row Numbers"
18114 org-table-toggle-coordinate-overlays
18115 :style toggle
18116 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18117 "--"
18118 ["Create" org-table-create (and (not (org-at-table-p))
18119 org-enable-table-editor)]
18120 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18121 ["Import from File" org-table-import (not (org-at-table-p))]
18122 ["Export to File" org-table-export (org-at-table-p)]
18123 "--"
18124 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18126 (easy-menu-define org-org-menu org-mode-map "Org menu"
18127 '("Org"
18128 ("Show/Hide"
18129 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18130 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18131 ["Sparse Tree..." org-sparse-tree t]
18132 ["Reveal Context" org-reveal t]
18133 ["Show All" show-all t]
18134 "--"
18135 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18136 "--"
18137 ["New Heading" org-insert-heading t]
18138 ("Navigate Headings"
18139 ["Up" outline-up-heading t]
18140 ["Next" outline-next-visible-heading t]
18141 ["Previous" outline-previous-visible-heading t]
18142 ["Next Same Level" outline-forward-same-level t]
18143 ["Previous Same Level" outline-backward-same-level t]
18144 "--"
18145 ["Jump" org-goto t])
18146 ("Edit Structure"
18147 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18148 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18149 "--"
18150 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18151 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18152 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18153 "--"
18154 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18155 "--"
18156 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18157 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18158 ["Demote Heading" org-metaright (not (org-at-table-p))]
18159 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18160 "--"
18161 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18162 "--"
18163 ["Convert to odd levels" org-convert-to-odd-levels t]
18164 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18165 ("Editing"
18166 ["Emphasis..." org-emphasize t]
18167 ["Edit Source Example" org-edit-special t]
18168 "--"
18169 ["Footnote new/jump" org-footnote-action t]
18170 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18171 ("Archive"
18172 ["Archive (default method)" org-archive-subtree-default t]
18173 "--"
18174 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18175 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18176 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18178 "--"
18179 ("Hyperlinks"
18180 ["Store Link (Global)" org-store-link t]
18181 ["Find existing link to here" org-occur-link-in-agenda-files t]
18182 ["Insert Link" org-insert-link t]
18183 ["Follow Link" org-open-at-point t]
18184 "--"
18185 ["Next link" org-next-link t]
18186 ["Previous link" org-previous-link t]
18187 "--"
18188 ["Descriptive Links"
18189 (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
18190 :style radio
18191 :selected (member '(org-link) buffer-invisibility-spec)]
18192 ["Literal Links"
18193 (progn
18194 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
18195 :style radio
18196 :selected (not (member '(org-link) buffer-invisibility-spec))])
18197 "--"
18198 ("TODO Lists"
18199 ["TODO/DONE/-" org-todo t]
18200 ("Select keyword"
18201 ["Next keyword" org-shiftright (org-on-heading-p)]
18202 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18203 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18204 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18205 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18206 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18207 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18208 "--"
18209 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18210 :selected org-enforce-todo-dependencies :style toggle :active t]
18211 "Settings for tree at point"
18212 ["Do Children sequentially" org-toggle-ordered-property :style radio
18213 :selected (org-entry-get nil "ORDERED")
18214 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18215 ["Do Children parallel" org-toggle-ordered-property :style radio
18216 :selected (not (org-entry-get nil "ORDERED"))
18217 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18218 "--"
18219 ["Set Priority" org-priority t]
18220 ["Priority Up" org-shiftup t]
18221 ["Priority Down" org-shiftdown t]
18222 "--"
18223 ["Get news from all feeds" org-feed-update-all t]
18224 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18225 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18226 ("TAGS and Properties"
18227 ["Set Tags" org-set-tags-command t]
18228 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18229 "--"
18230 ["Set property" org-set-property t]
18231 ["Column view of properties" org-columns t]
18232 ["Insert Column View DBlock" org-insert-columns-dblock t])
18233 ("Dates and Scheduling"
18234 ["Timestamp" org-time-stamp t]
18235 ["Timestamp (inactive)" org-time-stamp-inactive t]
18236 ("Change Date"
18237 ["1 Day Later" org-shiftright t]
18238 ["1 Day Earlier" org-shiftleft t]
18239 ["1 ... Later" org-shiftup t]
18240 ["1 ... Earlier" org-shiftdown t])
18241 ["Compute Time Range" org-evaluate-time-range t]
18242 ["Schedule Item" org-schedule t]
18243 ["Deadline" org-deadline t]
18244 "--"
18245 ["Custom time format" org-toggle-time-stamp-overlays
18246 :style radio :selected org-display-custom-times]
18247 "--"
18248 ["Goto Calendar" org-goto-calendar t]
18249 ["Date from Calendar" org-date-from-calendar t]
18250 "--"
18251 ["Start/Restart Timer" org-timer-start t]
18252 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18253 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18254 ["Insert Timer String" org-timer t]
18255 ["Insert Timer Item" org-timer-item t])
18256 ("Logging work"
18257 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18258 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18259 ["Clock out" org-clock-out t]
18260 ["Clock cancel" org-clock-cancel t]
18261 "--"
18262 ["Mark as default task" org-clock-mark-default-task t]
18263 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18264 ["Goto running clock" org-clock-goto t]
18265 "--"
18266 ["Display times" org-clock-display t]
18267 ["Create clock table" org-clock-report t]
18268 "--"
18269 ["Record DONE time"
18270 (progn (setq org-log-done (not org-log-done))
18271 (message "Switching to %s will %s record a timestamp"
18272 (car org-done-keywords)
18273 (if org-log-done "automatically" "not")))
18274 :style toggle :selected org-log-done])
18275 "--"
18276 ["Agenda Command..." org-agenda t]
18277 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18278 ("File List for Agenda")
18279 ("Special views current file"
18280 ["TODO Tree" org-show-todo-tree t]
18281 ["Check Deadlines" org-check-deadlines t]
18282 ["Timeline" org-timeline t]
18283 ["Tags/Property tree" org-match-sparse-tree t])
18284 "--"
18285 ["Export/Publish..." org-export t]
18286 ("LaTeX"
18287 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18288 :selected org-cdlatex-mode]
18289 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18290 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18291 ["Modify math symbol" org-cdlatex-math-modify
18292 (org-inside-LaTeX-fragment-p)]
18293 ["Insert citation" org-reftex-citation t]
18294 "--"
18295 ["Template for BEAMER" org-insert-beamer-options-template t])
18296 "--"
18297 ("MobileOrg"
18298 ["Push Files and Views" org-mobile-push t]
18299 ["Get Captured and Flagged" org-mobile-pull t]
18300 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18301 "--"
18302 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18303 "--"
18304 ("Documentation"
18305 ["Show Version" org-version t]
18306 ["Info Documentation" org-info t])
18307 ("Customize"
18308 ["Browse Org Group" org-customize t]
18309 "--"
18310 ["Expand This Menu" org-create-customize-menu
18311 (fboundp 'customize-menu-create)])
18312 ["Send bug report" org-submit-bug-report t]
18313 "--"
18314 ("Refresh/Reload"
18315 ["Refresh setup current buffer" org-mode-restart t]
18316 ["Reload Org (after update)" org-reload t]
18317 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18320 (defun org-info (&optional node)
18321 "Read documentation for Org-mode in the info system.
18322 With optional NODE, go directly to that node."
18323 (interactive)
18324 (info (format "(org)%s" (or node ""))))
18326 ;;;###autoload
18327 (defun org-submit-bug-report ()
18328 "Submit a bug report on Org-mode via mail.
18330 Don't hesitate to report any problems or inaccurate documentation.
18332 If you don't have setup sending mail from (X)Emacs, please copy the
18333 output buffer into your mail program, as it gives us important
18334 information about your Org-mode version and configuration."
18335 (interactive)
18336 (require 'reporter)
18337 (org-load-modules-maybe)
18338 (org-require-autoloaded-modules)
18339 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18340 (reporter-submit-bug-report
18341 "emacs-orgmode@gnu.org"
18342 (org-version)
18343 (let (list)
18344 (save-window-excursion
18345 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
18346 (delete-other-windows)
18347 (erase-buffer)
18348 (insert "You are about to submit a bug report to the Org-mode mailing list.
18350 We would like to add your full Org-mode and Outline configuration to the
18351 bug report. This greatly simplifies the work of the maintainer and
18352 other experts on the mailing list.
18354 HOWEVER, some variables you have customized may contain private
18355 information. The names of customers, colleagues, or friends, might
18356 appear in the form of file names, tags, todo states, or search strings.
18357 If you answer yes to the prompt, you might want to check and remove
18358 such private information before sending the email.")
18359 (add-text-properties (point-min) (point-max) '(face org-warning))
18360 (when (yes-or-no-p "Include your Org-mode configuration ")
18361 (mapatoms
18362 (lambda (v)
18363 (and (boundp v)
18364 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
18365 (or (and (symbol-value v)
18366 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
18367 (and
18368 (get v 'custom-type) (get v 'standard-value)
18369 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18370 (push v list)))))
18371 (kill-buffer (get-buffer "*Warn about privacy*"))
18372 list))
18373 nil nil
18374 "Remember to cover the basics, that is, what you expected to happen and
18375 what in fact did happen. You don't know how to make a good report? See
18377 http://orgmode.org/manual/Feedback.html#Feedback
18379 Your bug report will be posted to the Org-mode mailing list.
18380 ------------------------------------------------------------------------")
18381 (save-excursion
18382 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
18383 (replace-match "\\1Bug: \\3 [\\2]")))))
18386 (defun org-install-agenda-files-menu ()
18387 (let ((bl (buffer-list)))
18388 (save-excursion
18389 (while bl
18390 (set-buffer (pop bl))
18391 (if (org-mode-p) (setq bl nil)))
18392 (when (org-mode-p)
18393 (easy-menu-change
18394 '("Org") "File List for Agenda"
18395 (append
18396 (list
18397 ["Edit File List" (org-edit-agenda-file-list) t]
18398 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
18399 ["Remove Current File from List" org-remove-file t]
18400 ["Cycle through agenda files" org-cycle-agenda-files t]
18401 ["Occur in all agenda files" org-occur-in-agenda-files t]
18402 "--")
18403 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
18405 ;;;; Documentation
18407 ;;;###autoload
18408 (defun org-require-autoloaded-modules ()
18409 (interactive)
18410 (mapc 'require
18411 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
18412 org-docbook org-exp org-html org-icalendar
18413 org-id org-latex
18414 org-publish org-remember org-table
18415 org-timer org-xoxo)))
18417 ;;;###autoload
18418 (defun org-reload (&optional uncompiled)
18419 "Reload all org lisp files.
18420 With prefix arg UNCOMPILED, load the uncompiled versions."
18421 (interactive "P")
18422 (require 'find-func)
18423 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
18424 (dir-org (file-name-directory (org-find-library-name "org")))
18425 (dir-org-contrib (ignore-errors
18426 (file-name-directory
18427 (org-find-library-name "org-contribdir"))))
18428 (babel-files
18429 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
18430 (append (list nil "comint" "eval" "exp" "keys"
18431 "lob" "ref" "table" "tangle")
18432 (delq nil
18433 (mapcar
18434 (lambda (lang)
18435 (when (cdr lang) (symbol-name (car lang))))
18436 org-babel-load-languages)))))
18437 (files
18438 (append (directory-files dir-org t file-re)
18439 babel-files
18440 (and dir-org-contrib
18441 (directory-files dir-org-contrib t file-re))))
18442 (remove-re (concat (if (featurep 'xemacs)
18443 "org-colview" "org-colview-xemacs")
18444 "\\'")))
18445 (setq files (mapcar 'file-name-sans-extension files))
18446 (setq files (mapcar
18447 (lambda (x) (if (string-match remove-re x) nil x))
18448 files))
18449 (setq files (delq nil files))
18450 (mapc
18451 (lambda (f)
18452 (when (featurep (intern (file-name-nondirectory f)))
18453 (if (and (not uncompiled)
18454 (file-exists-p (concat f ".elc")))
18455 (load (concat f ".elc") nil nil t)
18456 (load (concat f ".el") nil nil t))))
18457 files))
18458 (org-version))
18460 ;;;###autoload
18461 (defun org-customize ()
18462 "Call the customize function with org as argument."
18463 (interactive)
18464 (org-load-modules-maybe)
18465 (org-require-autoloaded-modules)
18466 (customize-browse 'org))
18468 (defun org-create-customize-menu ()
18469 "Create a full customization menu for Org-mode, insert it into the menu."
18470 (interactive)
18471 (org-load-modules-maybe)
18472 (org-require-autoloaded-modules)
18473 (if (fboundp 'customize-menu-create)
18474 (progn
18475 (easy-menu-change
18476 '("Org") "Customize"
18477 `(["Browse Org group" org-customize t]
18478 "--"
18479 ,(customize-menu-create 'org)
18480 ["Set" Custom-set t]
18481 ["Save" Custom-save t]
18482 ["Reset to Current" Custom-reset-current t]
18483 ["Reset to Saved" Custom-reset-saved t]
18484 ["Reset to Standard Settings" Custom-reset-standard t]))
18485 (message "\"Org\"-menu now contains full customization menu"))
18486 (error "Cannot expand menu (outdated version of cus-edit.el)")))
18488 ;;;; Miscellaneous stuff
18490 ;;; Generally useful functions
18492 (defun org-get-at-bol (property)
18493 "Get text property PROPERTY at beginning of line."
18494 (get-text-property (point-at-bol) property))
18496 (defun org-find-text-property-in-string (prop s)
18497 "Return the first non-nil value of property PROP in string S."
18498 (or (get-text-property 0 prop s)
18499 (get-text-property (or (next-single-property-change 0 prop s) 0)
18500 prop s)))
18502 (defun org-display-warning (message) ;; Copied from Emacs-Muse
18503 "Display the given MESSAGE as a warning."
18504 (if (fboundp 'display-warning)
18505 (display-warning 'org message
18506 (if (featurep 'xemacs) 'warning :warning))
18507 (let ((buf (get-buffer-create "*Org warnings*")))
18508 (with-current-buffer buf
18509 (goto-char (point-max))
18510 (insert "Warning (Org): " message)
18511 (unless (bolp)
18512 (newline)))
18513 (display-buffer buf)
18514 (sit-for 0))))
18516 (defun org-eval (form)
18517 "Eval FORM and return result."
18518 (condition-case error
18519 (eval form)
18520 (error (format "%%![Error: %s]" error))))
18522 (defun org-in-commented-line ()
18523 "Is point in a line starting with `#'?"
18524 (equal (char-after (point-at-bol)) ?#))
18526 (defun org-in-indented-comment-line ()
18527 "Is point in a line starting with `#' after some white space?"
18528 (save-excursion
18529 (save-match-data
18530 (goto-char (point-at-bol))
18531 (looking-at "[ \t]*#"))))
18533 (defun org-in-verbatim-emphasis ()
18534 (save-match-data
18535 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
18537 (defun org-goto-marker-or-bmk (marker &optional bookmark)
18538 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
18539 (if (and marker (marker-buffer marker)
18540 (buffer-live-p (marker-buffer marker)))
18541 (progn
18542 (switch-to-buffer (marker-buffer marker))
18543 (if (or (> marker (point-max)) (< marker (point-min)))
18544 (widen))
18545 (goto-char marker)
18546 (org-show-context 'org-goto))
18547 (if bookmark
18548 (bookmark-jump bookmark)
18549 (error "Cannot find location"))))
18551 (defun org-quote-csv-field (s)
18552 "Quote field for inclusion in CSV material."
18553 (if (string-match "[\",]" s)
18554 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
18557 (defun org-force-self-insert (N)
18558 "Needed to enforce self-insert under remapping."
18559 (interactive "p")
18560 (self-insert-command N))
18562 (defun org-string-width (s)
18563 "Compute width of string, ignoring invisible characters.
18564 This ignores character with invisibility property `org-link', and also
18565 characters with property `org-cwidth', because these will become invisible
18566 upon the next fontification round."
18567 (let (b l)
18568 (when (or (eq t buffer-invisibility-spec)
18569 (assq 'org-link buffer-invisibility-spec))
18570 (while (setq b (text-property-any 0 (length s)
18571 'invisible 'org-link s))
18572 (setq s (concat (substring s 0 b)
18573 (substring s (or (next-single-property-change
18574 b 'invisible s) (length s)))))))
18575 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
18576 (setq s (concat (substring s 0 b)
18577 (substring s (or (next-single-property-change
18578 b 'org-cwidth s) (length s))))))
18579 (setq l (string-width s) b -1)
18580 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
18581 (setq l (- l (get-text-property b 'org-dwidth-n s))))
18584 (defun org-shorten-string (s maxlength)
18585 "Shorten string S so tht it is no longer than MAXLENGTH characters.
18586 If the string is shorter or has length MAXLENGTH, just return the
18587 original string. If it is longer, the functions finds a space in the
18588 string, breaks this string off at that locations and adds three dots
18589 as ellipsis. Including the ellipsis, the string will not be longer
18590 than MAXLENGTH. If finding a good breaking point in the string does
18591 not work, the string is just chopped off in the middle of a word
18592 if necessary."
18593 (if (<= (length s) maxlength)
18595 (let* ((n (max (- maxlength 4) 1))
18596 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
18597 (if (string-match re s)
18598 (concat (match-string 1 s) "...")
18599 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
18601 (defun org-get-indentation (&optional line)
18602 "Get the indentation of the current line, interpreting tabs.
18603 When LINE is given, assume it represents a line and compute its indentation."
18604 (if line
18605 (if (string-match "^ *" (org-remove-tabs line))
18606 (match-end 0))
18607 (save-excursion
18608 (beginning-of-line 1)
18609 (skip-chars-forward " \t")
18610 (current-column))))
18612 (defun org-get-string-indentation (s)
18613 "What indentation has S due to SPACE and TAB at the beginning of the string?"
18614 (let ((n -1) (i 0) (w tab-width) c)
18615 (catch 'exit
18616 (while (< (setq n (1+ n)) (length s))
18617 (setq c (aref s n))
18618 (cond ((= c ?\ ) (setq i (1+ i)))
18619 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
18620 (t (throw 'exit t)))))
18623 (defun org-remove-tabs (s &optional width)
18624 "Replace tabulators in S with spaces.
18625 Assumes that s is a single line, starting in column 0."
18626 (setq width (or width tab-width))
18627 (while (string-match "\t" s)
18628 (setq s (replace-match
18629 (make-string
18630 (- (* width (/ (+ (match-beginning 0) width) width))
18631 (match-beginning 0)) ?\ )
18632 t t s)))
18635 (defun org-fix-indentation (line ind)
18636 "Fix indentation in LINE.
18637 IND is a cons cell with target and minimum indentation.
18638 If the current indentation in LINE is smaller than the minimum,
18639 leave it alone. If it is larger than ind, set it to the target."
18640 (let* ((l (org-remove-tabs line))
18641 (i (org-get-indentation l))
18642 (i1 (car ind)) (i2 (cdr ind)))
18643 (if (>= i i2) (setq l (substring line i2)))
18644 (if (> i1 0)
18645 (concat (make-string i1 ?\ ) l)
18646 l)))
18648 (defun org-remove-indentation (code &optional n)
18649 "Remove the maximum common indentation from the lines in CODE.
18650 N may optionally be the number of spaces to remove."
18651 (with-temp-buffer
18652 (insert code)
18653 (org-do-remove-indentation n)
18654 (buffer-string)))
18656 (defun org-do-remove-indentation (&optional n)
18657 "Remove the maximum common indentation from the buffer."
18658 (untabify (point-min) (point-max))
18659 (let ((min 10000) re)
18660 (if n
18661 (setq min n)
18662 (goto-char (point-min))
18663 (while (re-search-forward "^ *[^ \n]" nil t)
18664 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
18665 (unless (or (= min 0) (= min 10000))
18666 (setq re (format "^ \\{%d\\}" min))
18667 (goto-char (point-min))
18668 (while (re-search-forward re nil t)
18669 (replace-match "")
18670 (end-of-line 1))
18671 min)))
18673 (defun org-fill-template (template alist)
18674 "Find each %key of ALIST in TEMPLATE and replace it."
18675 (let ((case-fold-search nil)
18676 entry key value)
18677 (setq alist (sort (copy-sequence alist)
18678 (lambda (a b) (< (length (car a)) (length (car b))))))
18679 (while (setq entry (pop alist))
18680 (setq template
18681 (replace-regexp-in-string
18682 (concat "%" (regexp-quote (car entry)))
18683 (cdr entry) template t t)))
18684 template))
18686 (defun org-base-buffer (buffer)
18687 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
18688 (if (not buffer)
18689 buffer
18690 (or (buffer-base-buffer buffer)
18691 buffer)))
18693 (defun org-trim (s)
18694 "Remove whitespace at beginning and end of string."
18695 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
18696 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
18699 (defun org-wrap (string &optional width lines)
18700 "Wrap string to either a number of lines, or a width in characters.
18701 If WIDTH is non-nil, the string is wrapped to that width, however many lines
18702 that costs. If there is a word longer than WIDTH, the text is actually
18703 wrapped to the length of that word.
18704 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
18705 many lines, whatever width that takes.
18706 The return value is a list of lines, without newlines at the end."
18707 (let* ((words (org-split-string string "[ \t\n]+"))
18708 (maxword (apply 'max (mapcar 'org-string-width words)))
18709 w ll)
18710 (cond (width
18711 (org-do-wrap words (max maxword width)))
18712 (lines
18713 (setq w maxword)
18714 (setq ll (org-do-wrap words maxword))
18715 (if (<= (length ll) lines)
18717 (setq ll words)
18718 (while (> (length ll) lines)
18719 (setq w (1+ w))
18720 (setq ll (org-do-wrap words w)))
18721 ll))
18722 (t (error "Cannot wrap this")))))
18724 (defun org-do-wrap (words width)
18725 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
18726 (let (lines line)
18727 (while words
18728 (setq line (pop words))
18729 (while (and words (< (+ (length line) (length (car words))) width))
18730 (setq line (concat line " " (pop words))))
18731 (setq lines (push line lines)))
18732 (nreverse lines)))
18734 (defun org-split-string (string &optional separators)
18735 "Splits STRING into substrings at SEPARATORS.
18736 No empty strings are returned if there are matches at the beginning
18737 and end of string."
18738 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
18739 (start 0)
18740 notfirst
18741 (list nil))
18742 (while (and (string-match rexp string
18743 (if (and notfirst
18744 (= start (match-beginning 0))
18745 (< start (length string)))
18746 (1+ start) start))
18747 (< (match-beginning 0) (length string)))
18748 (setq notfirst t)
18749 (or (eq (match-beginning 0) 0)
18750 (and (eq (match-beginning 0) (match-end 0))
18751 (eq (match-beginning 0) start))
18752 (setq list
18753 (cons (substring string start (match-beginning 0))
18754 list)))
18755 (setq start (match-end 0)))
18756 (or (eq start (length string))
18757 (setq list
18758 (cons (substring string start)
18759 list)))
18760 (nreverse list)))
18762 (defun org-quote-vert (s)
18763 "Replace \"|\" with \"\\vert\"."
18764 (while (string-match "|" s)
18765 (setq s (replace-match "\\vert" t t s)))
18768 (defun org-uuidgen-p (s)
18769 "Is S an ID created by UUIDGEN?"
18770 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
18772 (defun org-context ()
18773 "Return a list of contexts of the current cursor position.
18774 If several contexts apply, all are returned.
18775 Each context entry is a list with a symbol naming the context, and
18776 two positions indicating start and end of the context. Possible
18777 contexts are:
18779 :headline anywhere in a headline
18780 :headline-stars on the leading stars in a headline
18781 :todo-keyword on a TODO keyword (including DONE) in a headline
18782 :tags on the TAGS in a headline
18783 :priority on the priority cookie in a headline
18784 :item on the first line of a plain list item
18785 :item-bullet on the bullet/number of a plain list item
18786 :checkbox on the checkbox in a plain list item
18787 :table in an org-mode table
18788 :table-special on a special filed in a table
18789 :table-table in a table.el table
18790 :link on a hyperlink
18791 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
18792 :target on a <<target>>
18793 :radio-target on a <<<radio-target>>>
18794 :latex-fragment on a LaTeX fragment
18795 :latex-preview on a LaTeX fragment with overlayed preview image
18797 This function expects the position to be visible because it uses font-lock
18798 faces as a help to recognize the following contexts: :table-special, :link,
18799 and :keyword."
18800 (let* ((f (get-text-property (point) 'face))
18801 (faces (if (listp f) f (list f)))
18802 (p (point)) clist o)
18803 ;; First the large context
18804 (cond
18805 ((org-on-heading-p t)
18806 (push (list :headline (point-at-bol) (point-at-eol)) clist)
18807 (when (progn
18808 (beginning-of-line 1)
18809 (looking-at org-todo-line-tags-regexp))
18810 (push (org-point-in-group p 1 :headline-stars) clist)
18811 (push (org-point-in-group p 2 :todo-keyword) clist)
18812 (push (org-point-in-group p 4 :tags) clist))
18813 (goto-char p)
18814 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
18815 (if (looking-at "\\[#[A-Z0-9]\\]")
18816 (push (org-point-in-group p 0 :priority) clist)))
18818 ((org-at-item-p)
18819 (push (org-point-in-group p 2 :item-bullet) clist)
18820 (push (list :item (point-at-bol)
18821 (save-excursion (org-end-of-item) (point)))
18822 clist)
18823 (and (org-at-item-checkbox-p)
18824 (push (org-point-in-group p 0 :checkbox) clist)))
18826 ((org-at-table-p)
18827 (push (list :table (org-table-begin) (org-table-end)) clist)
18828 (if (memq 'org-formula faces)
18829 (push (list :table-special
18830 (previous-single-property-change p 'face)
18831 (next-single-property-change p 'face)) clist)))
18832 ((org-at-table-p 'any)
18833 (push (list :table-table) clist)))
18834 (goto-char p)
18836 ;; Now the small context
18837 (cond
18838 ((org-at-timestamp-p)
18839 (push (org-point-in-group p 0 :timestamp) clist))
18840 ((memq 'org-link faces)
18841 (push (list :link
18842 (previous-single-property-change p 'face)
18843 (next-single-property-change p 'face)) clist))
18844 ((memq 'org-special-keyword faces)
18845 (push (list :keyword
18846 (previous-single-property-change p 'face)
18847 (next-single-property-change p 'face)) clist))
18848 ((org-on-target-p)
18849 (push (org-point-in-group p 0 :target) clist)
18850 (goto-char (1- (match-beginning 0)))
18851 (if (looking-at org-radio-target-regexp)
18852 (push (org-point-in-group p 0 :radio-target) clist))
18853 (goto-char p))
18854 ((setq o (car (delq nil
18855 (mapcar
18856 (lambda (x)
18857 (if (memq x org-latex-fragment-image-overlays) x))
18858 (overlays-at (point))))))
18859 (push (list :latex-fragment
18860 (overlay-start o) (overlay-end o)) clist)
18861 (push (list :latex-preview
18862 (overlay-start o) (overlay-end o)) clist))
18863 ((org-inside-LaTeX-fragment-p)
18864 ;; FIXME: positions wrong.
18865 (push (list :latex-fragment (point) (point)) clist)))
18867 (setq clist (nreverse (delq nil clist)))
18868 clist))
18870 ;; FIXME: Compare with at-regexp-p Do we need both?
18871 (defun org-in-regexp (re &optional nlines visually)
18872 "Check if point is inside a match of regexp.
18873 Normally only the current line is checked, but you can include NLINES extra
18874 lines both before and after point into the search.
18875 If VISUALLY is set, require that the cursor is not after the match but
18876 really on, so that the block visually is on the match."
18877 (catch 'exit
18878 (let ((pos (point))
18879 (eol (point-at-eol (+ 1 (or nlines 0))))
18880 (inc (if visually 1 0)))
18881 (save-excursion
18882 (beginning-of-line (- 1 (or nlines 0)))
18883 (while (re-search-forward re eol t)
18884 (if (and (<= (match-beginning 0) pos)
18885 (>= (+ inc (match-end 0)) pos))
18886 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
18888 (defun org-at-regexp-p (regexp)
18889 "Is point inside a match of REGEXP in the current line?"
18890 (catch 'exit
18891 (save-excursion
18892 (let ((pos (point)) (end (point-at-eol)))
18893 (beginning-of-line 1)
18894 (while (re-search-forward regexp end t)
18895 (if (and (<= (match-beginning 0) pos)
18896 (>= (match-end 0) pos))
18897 (throw 'exit t)))
18898 nil))))
18900 (defun org-in-regexps-block-p (start-re end-re &optional bound)
18901 "Return t if the current point is between matches of START-RE and END-RE.
18902 This will also return t if point is on one of the two matches or
18903 in an unfinished block. END-RE can be a string or a form
18904 returning a string.
18906 An optional third argument bounds the search for START-RE. It
18907 defaults to previous heading or `point-min'."
18908 (let ((pos (point))
18909 (limit (or bound (save-excursion (outline-previous-heading)))))
18910 (save-excursion
18911 ;; we're on a block when point is on start-re...
18912 (or (org-at-regexp-p start-re)
18913 ;; ... or start-re can be found above...
18914 (and (re-search-backward start-re limit t)
18915 ;; ... but no end-re between start-re and point.
18916 (not (re-search-forward (eval end-re) pos t)))))))
18918 (defun org-occur-in-agenda-files (regexp &optional nlines)
18919 "Call `multi-occur' with buffers for all agenda files."
18920 (interactive "sOrg-files matching: \np")
18921 (let* ((files (org-agenda-files))
18922 (tnames (mapcar 'file-truename files))
18923 (extra org-agenda-text-search-extra-files)
18925 (when (eq (car extra) 'agenda-archives)
18926 (setq extra (cdr extra))
18927 (setq files (org-add-archive-files files)))
18928 (while (setq f (pop extra))
18929 (unless (member (file-truename f) tnames)
18930 (add-to-list 'files f 'append)
18931 (add-to-list 'tnames (file-truename f) 'append)))
18932 (multi-occur
18933 (mapcar (lambda (x)
18934 (with-current-buffer
18935 (or (get-file-buffer x) (find-file-noselect x))
18936 (widen)
18937 (current-buffer)))
18938 files)
18939 regexp)))
18941 (if (boundp 'occur-mode-find-occurrence-hook)
18942 ;; Emacs 23
18943 (add-hook 'occur-mode-find-occurrence-hook
18944 (lambda ()
18945 (when (org-mode-p)
18946 (org-reveal))))
18947 ;; Emacs 22
18948 (defadvice occur-mode-goto-occurrence
18949 (after org-occur-reveal activate)
18950 (and (org-mode-p) (org-reveal)))
18951 (defadvice occur-mode-goto-occurrence-other-window
18952 (after org-occur-reveal activate)
18953 (and (org-mode-p) (org-reveal)))
18954 (defadvice occur-mode-display-occurrence
18955 (after org-occur-reveal activate)
18956 (when (org-mode-p)
18957 (let ((pos (occur-mode-find-occurrence)))
18958 (with-current-buffer (marker-buffer pos)
18959 (save-excursion
18960 (goto-char pos)
18961 (org-reveal)))))))
18963 (defun org-occur-link-in-agenda-files ()
18964 "Create a link and search for it in the agendas.
18965 The link is not stored in `org-stored-links', it is just created
18966 for the search purpose."
18967 (interactive)
18968 (let ((link (condition-case nil
18969 (org-store-link nil)
18970 (error "Unable to create a link to here"))))
18971 (org-occur-in-agenda-files (regexp-quote link))))
18973 (defun org-uniquify (list)
18974 "Remove duplicate elements from LIST."
18975 (let (res)
18976 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
18977 res))
18979 (defun org-delete-all (elts list)
18980 "Remove all elements in ELTS from LIST."
18981 (while elts
18982 (setq list (delete (pop elts) list)))
18983 list)
18985 (defun org-count (cl-item cl-seq)
18986 "Count the number of occurrences of ITEM in SEQ.
18987 Taken from `count' in cl-seq.el with all keyword arguments removed."
18988 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
18989 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
18990 (while (< cl-start cl-end)
18991 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
18992 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
18993 (setq cl-start (1+ cl-start)))
18994 cl-count))
18996 (defun org-remove-if (predicate seq)
18997 "Remove everything from SEQ that fulfills PREDICATE."
18998 (let (res e)
18999 (while seq
19000 (setq e (pop seq))
19001 (if (not (funcall predicate e)) (push e res)))
19002 (nreverse res)))
19004 (defun org-remove-if-not (predicate seq)
19005 "Remove everything from SEQ that does not fulfill PREDICATE."
19006 (let (res e)
19007 (while seq
19008 (setq e (pop seq))
19009 (if (funcall predicate e) (push e res)))
19010 (nreverse res)))
19012 (defun org-back-over-empty-lines ()
19013 "Move backwards over whitespace, to the beginning of the first empty line.
19014 Returns the number of empty lines passed."
19015 (let ((pos (point)))
19016 (if (cdr (assoc 'heading org-blank-before-new-entry))
19017 (skip-chars-backward " \t\n\r")
19018 (forward-line -1))
19019 (beginning-of-line 2)
19020 (goto-char (min (point) pos))
19021 (count-lines (point) pos)))
19023 (defun org-skip-whitespace ()
19024 (skip-chars-forward " \t\n\r"))
19026 (defun org-point-in-group (point group &optional context)
19027 "Check if POINT is in match-group GROUP.
19028 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19029 match. If the match group does not exist or point is not inside it,
19030 return nil."
19031 (and (match-beginning group)
19032 (>= point (match-beginning group))
19033 (<= point (match-end group))
19034 (if context
19035 (list context (match-beginning group) (match-end group))
19036 t)))
19038 (defun org-switch-to-buffer-other-window (&rest args)
19039 "Switch to buffer in a second window on the current frame.
19040 In particular, do not allow pop-up frames.
19041 Returns the newly created buffer."
19042 (let (pop-up-frames special-display-buffer-names special-display-regexps
19043 special-display-function)
19044 (apply 'switch-to-buffer-other-window args)))
19046 (defun org-combine-plists (&rest plists)
19047 "Create a single property list from all plists in PLISTS.
19048 The process starts by copying the first list, and then setting properties
19049 from the other lists. Settings in the last list are the most significant
19050 ones and overrule settings in the other lists."
19051 (let ((rtn (copy-sequence (pop plists)))
19052 p v ls)
19053 (while plists
19054 (setq ls (pop plists))
19055 (while ls
19056 (setq p (pop ls) v (pop ls))
19057 (setq rtn (plist-put rtn p v))))
19058 rtn))
19060 (defun org-move-line-down (arg)
19061 "Move the current line down. With prefix argument, move it past ARG lines."
19062 (interactive "p")
19063 (let ((col (current-column))
19064 beg end pos)
19065 (beginning-of-line 1) (setq beg (point))
19066 (beginning-of-line 2) (setq end (point))
19067 (beginning-of-line (+ 1 arg))
19068 (setq pos (move-marker (make-marker) (point)))
19069 (insert (delete-and-extract-region beg end))
19070 (goto-char pos)
19071 (org-move-to-column col)))
19073 (defun org-move-line-up (arg)
19074 "Move the current line up. With prefix argument, move it past ARG lines."
19075 (interactive "p")
19076 (let ((col (current-column))
19077 beg end pos)
19078 (beginning-of-line 1) (setq beg (point))
19079 (beginning-of-line 2) (setq end (point))
19080 (beginning-of-line (- arg))
19081 (setq pos (move-marker (make-marker) (point)))
19082 (insert (delete-and-extract-region beg end))
19083 (goto-char pos)
19084 (org-move-to-column col)))
19086 (defun org-replace-escapes (string table)
19087 "Replace %-escapes in STRING with values in TABLE.
19088 TABLE is an association list with keys like \"%a\" and string values.
19089 The sequences in STRING may contain normal field width and padding information,
19090 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19091 so values can contain further %-escapes if they are define later in TABLE."
19092 (let ((tbl (copy-alist table))
19093 (case-fold-search nil)
19094 (pchg 0)
19095 e re rpl)
19096 (while (setq e (pop tbl))
19097 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19098 (when (and (cdr e) (string-match re (cdr e)))
19099 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19100 (safe "SREF"))
19101 (add-text-properties 0 3 (list 'sref sref) safe)
19102 (setcdr e (replace-match safe t t (cdr e)))))
19103 (while (string-match re string)
19104 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19105 (cdr e)))
19106 (setq string (replace-match rpl t t string))))
19107 (while (setq pchg (next-property-change pchg string))
19108 (let ((sref (get-text-property pchg 'sref string)))
19109 (when (and sref (string-match "SREF" string pchg))
19110 (setq string (replace-match sref t t string)))))
19111 string))
19113 (defun org-sublist (list start end)
19114 "Return a section of LIST, from START to END.
19115 Counting starts at 1."
19116 (let (rtn (c start))
19117 (setq list (nthcdr (1- start) list))
19118 (while (and list (<= c end))
19119 (push (pop list) rtn)
19120 (setq c (1+ c)))
19121 (nreverse rtn)))
19123 (defun org-find-base-buffer-visiting (file)
19124 "Like `find-buffer-visiting' but always return the base buffer and
19125 not an indirect buffer."
19126 (let ((buf (or (get-file-buffer file)
19127 (find-buffer-visiting file))))
19128 (if buf
19129 (or (buffer-base-buffer buf) buf)
19130 nil)))
19132 (defun org-image-file-name-regexp (&optional extensions)
19133 "Return regexp matching the file names of images.
19134 If EXTENSIONS is given, only match these."
19135 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19136 (image-file-name-regexp)
19137 (let ((image-file-name-extensions
19138 (or extensions
19139 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19140 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19141 (concat "\\."
19142 (regexp-opt (nconc (mapcar 'upcase
19143 image-file-name-extensions)
19144 image-file-name-extensions)
19146 "\\'"))))
19148 (defun org-file-image-p (file &optional extensions)
19149 "Return non-nil if FILE is an image."
19150 (save-match-data
19151 (string-match (org-image-file-name-regexp extensions) file)))
19153 (defun org-get-cursor-date ()
19154 "Return the date at cursor in as a time.
19155 This works in the calendar and in the agenda, anywhere else it just
19156 returns the current time."
19157 (let (date day defd)
19158 (cond
19159 ((eq major-mode 'calendar-mode)
19160 (setq date (calendar-cursor-to-date)
19161 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19162 ((eq major-mode 'org-agenda-mode)
19163 (setq day (get-text-property (point) 'day))
19164 (if day
19165 (setq date (calendar-gregorian-from-absolute day)
19166 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19167 (nth 2 date))))))
19168 (or defd (current-time))))
19170 (defvar org-agenda-action-marker (make-marker)
19171 "Marker pointing to the entry for the next agenda action.")
19173 (defun org-mark-entry-for-agenda-action ()
19174 "Mark the current entry as target of an agenda action.
19175 Agenda actions are actions executed from the agenda with the key `k',
19176 which make use of the date at the cursor."
19177 (interactive)
19178 (move-marker org-agenda-action-marker
19179 (save-excursion (org-back-to-heading t) (point))
19180 (current-buffer))
19181 (message
19182 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19184 (defun org-mark-subtree ()
19185 "Mark the current subtree.
19186 This puts point at the start of the current subtree, and mark at the end.
19188 If point is in an inline task, mark that task instead."
19189 (interactive)
19190 (let ((inline-task-p
19191 (and (featurep 'org-inlinetask)
19192 (org-inlinetask-in-task-p)))
19193 (beg))
19194 ;; Get beginning of subtree
19195 (cond
19196 (inline-task-p (org-inlinetask-goto-beginning))
19197 ((org-at-heading-p) (beginning-of-line))
19198 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19199 (setq beg (point))
19200 ;; Get end of it
19201 (if inline-task-p
19202 (org-inlinetask-goto-end)
19203 (org-end-of-subtree))
19204 ;; Mark zone
19205 (push-mark (point) nil t)
19206 (goto-char beg)))
19208 ;;; Paragraph filling stuff.
19209 ;; We want this to be just right, so use the full arsenal.
19211 (defun org-indent-line-function ()
19212 "Indent line depending on context."
19213 (interactive)
19214 (let* ((pos (point))
19215 (itemp (org-at-item-p))
19216 (case-fold-search t)
19217 (org-drawer-regexp (or org-drawer-regexp "\000"))
19218 (inline-task-p (and (featurep 'org-inlinetask)
19219 (org-inlinetask-in-task-p)))
19220 (inline-re (and inline-task-p
19221 (org-inlinetask-outline-regexp)))
19222 column)
19223 (beginning-of-line 1)
19224 (cond
19225 ;; Comments
19226 ((looking-at "# ") (setq column 0))
19227 ;; Headings
19228 ((looking-at "\\*+ ") (setq column 0))
19229 ;; Included files
19230 ((looking-at "#\\+include:") (setq column 0))
19231 ;; Footnote definition
19232 ((looking-at org-footnote-definition-re) (setq column 0))
19233 ;; Literal examples
19234 ((looking-at "[ \t]*:[ \t]")
19235 (setq column (org-get-indentation))) ; do nothing
19236 ;; Lists
19237 ((ignore-errors (goto-char (org-in-item-p)))
19238 (setq column (if itemp
19239 (org-get-indentation)
19240 (org-list-item-body-column (point))))
19241 (goto-char pos))
19242 ;; Drawers
19243 ((and (looking-at "[ \t]*:END:")
19244 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19245 (save-excursion
19246 (goto-char (1- (match-beginning 1)))
19247 (setq column (current-column))))
19248 ;; Special blocks
19249 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19250 (save-excursion
19251 (re-search-backward
19252 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19253 (setq column (org-get-indentation (match-string 0))))
19254 ((and (not (looking-at "[ \t]*#\\+begin_"))
19255 (org-in-regexps-block-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19256 (save-excursion
19257 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19258 (setq column
19259 (if (equal (downcase (match-string 1)) "src")
19260 ;; src blocks: let `org-edit-src-exit' handle them
19261 (org-get-indentation)
19262 (org-get-indentation (match-string 0)))))
19263 ;; This line has nothing special, look at the previous relevant
19264 ;; line to compute indentation
19266 (beginning-of-line 0)
19267 (while (and (not (bobp))
19268 (not (looking-at org-drawer-regexp))
19269 ;; When point started in an inline task, do not move
19270 ;; above task starting line.
19271 (not (and inline-task-p (looking-at inline-re)))
19272 ;; Skip drawers, blocks, empty lines, verbatim,
19273 ;; comments, tables, footnotes definitions, lists,
19274 ;; inline tasks.
19275 (or (and (looking-at "[ \t]*:END:")
19276 (re-search-backward org-drawer-regexp nil t))
19277 (and (looking-at "[ \t]*#\\+end_")
19278 (re-search-backward "[ \t]*#\\+begin_"nil t))
19279 (looking-at "[ \t]*[\n:#|]")
19280 (looking-at org-footnote-definition-re)
19281 (and (ignore-errors (goto-char (org-in-item-p)))
19282 (goto-char
19283 (org-list-get-top-point (org-list-struct))))
19284 (and (not inline-task-p)
19285 (featurep 'org-inlinetask)
19286 (org-inlinetask-in-task-p)
19287 (or (org-inlinetask-goto-beginning) t))))
19288 (beginning-of-line 0))
19289 (cond
19290 ;; There was an heading above.
19291 ((looking-at "\\*+[ \t]+")
19292 (if (not org-adapt-indentation)
19293 (setq column 0)
19294 (goto-char (match-end 0))
19295 (setq column (current-column))))
19296 ;; A drawer had started and is unfinished
19297 ((looking-at org-drawer-regexp)
19298 (goto-char (1- (match-beginning 1)))
19299 (setq column (current-column)))
19300 ;; Else, nothing noticeable found: get indentation and go on.
19301 (t (setq column (org-get-indentation))))))
19302 ;; Now apply indentation and move cursor accordingly
19303 (goto-char pos)
19304 (if (<= (current-column) (current-indentation))
19305 (org-indent-line-to column)
19306 (save-excursion (org-indent-line-to column)))
19307 ;; Special polishing for properties, see `org-property-format'
19308 (setq column (current-column))
19309 (beginning-of-line 1)
19310 (if (looking-at
19311 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
19312 (replace-match (concat (match-string 1)
19313 (format org-property-format
19314 (match-string 2) (match-string 3)))
19315 t t))
19316 (org-move-to-column column)))
19318 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
19319 "Variable to store copy of `adaptive-fill-regexp'.
19320 Since `adaptive-fill-regexp' is set to never match, we need to
19321 store a backup of its value before entering `org-mode' so that
19322 the functionality can be provided as a fall-back.")
19324 (defun org-set-autofill-regexps ()
19325 (interactive)
19326 ;; In the paragraph separator we include headlines, because filling
19327 ;; text in a line directly attached to a headline would otherwise
19328 ;; fill the headline as well.
19329 (org-set-local 'comment-start-skip "^#+[ \t]*")
19330 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
19331 ;; The paragraph starter includes hand-formatted lists.
19332 (org-set-local
19333 'paragraph-start
19334 (concat
19335 "\f" "\\|"
19336 "[ ]*$" "\\|"
19337 "\\*+ " "\\|"
19338 "[ \t]*#" "\\|"
19339 (org-item-re) "\\|"
19340 "[ \t]*[:|]" "\\|"
19341 "\\$\\$" "\\|"
19342 "\\\\\\(begin\\|end\\|[][]\\)"))
19343 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
19344 ;; But only if the user has not turned off tables or fixed-width regions
19345 (org-set-local
19346 'auto-fill-inhibit-regexp
19347 (concat "\\*+ \\|#\\+"
19348 "\\|[ \t]*" org-keyword-time-regexp
19349 (if (or org-enable-table-editor org-enable-fixed-width-editor)
19350 (concat
19351 "\\|[ \t]*["
19352 (if org-enable-table-editor "|" "")
19353 (if org-enable-fixed-width-editor ":" "")
19354 "]"))))
19355 ;; We use our own fill-paragraph function, to make sure that tables
19356 ;; and fixed-width regions are not wrapped. That function will pass
19357 ;; through to `fill-paragraph' when appropriate.
19358 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
19359 ;; Prevent auto-fill from inserting unwanted new items.
19360 (org-set-local 'fill-nobreak-predicate
19361 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
19362 fill-nobreak-predicate
19363 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate)))
19364 ;; Adaptive filling: To get full control, first make sure that
19365 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
19366 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
19367 (org-set-local 'org-adaptive-fill-regexp-backup
19368 adaptive-fill-regexp))
19369 (org-set-local 'adaptive-fill-regexp "\000")
19370 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
19371 (org-set-local 'adaptive-fill-function
19372 'org-adaptive-fill-function)
19373 (org-set-local
19374 'align-mode-rules-list
19375 '((org-in-buffer-settings
19376 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
19377 (modes . '(org-mode))))))
19379 (defun org-fill-item-nobreak-p ()
19380 "Non-nil when a line break at point would insert a new item."
19381 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
19383 (defun org-fill-paragraph (&optional justify)
19384 "Re-align a table, pass through to fill-paragraph if no table."
19385 (let ((table-p (org-at-table-p))
19386 (table.el-p (org-at-table.el-p))
19387 (itemp (org-in-item-p)))
19388 (cond ((and (equal (char-after (point-at-bol)) ?*)
19389 (save-excursion (goto-char (point-at-bol))
19390 (looking-at outline-regexp)))
19391 t) ; skip headlines
19392 (table.el-p t) ; skip table.el tables
19393 (table-p (org-table-align) t) ; align Org tables
19394 (itemp ; align text in items
19395 (let* ((struct (save-excursion (goto-char itemp)
19396 (org-list-struct)))
19397 (parents (org-list-parents-alist struct))
19398 (children (org-list-get-children itemp struct parents))
19399 beg end prev next prefix)
19400 ;; Determine in which part of item point is: before
19401 ;; first child, after last child, between two
19402 ;; sub-lists, or simply in item if there's no child.
19403 (cond
19404 ((not children)
19405 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19406 beg itemp
19407 end (org-list-get-item-end itemp struct)))
19408 ((< (point) (setq next (car children)))
19409 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19410 beg itemp
19411 end next))
19412 ((> (point) (setq prev (car (last children))))
19413 (setq beg (org-list-get-item-end prev struct)
19414 end (org-list-get-item-end itemp struct)
19415 prefix (save-excursion
19416 (goto-char beg)
19417 (skip-chars-forward " \t")
19418 (make-string (current-column) ?\ ))))
19419 (t (catch 'exit
19420 (while (setq next (pop children))
19421 (if (> (point) next)
19422 (setq prev next)
19423 (setq beg (org-list-get-item-end prev struct)
19424 end next
19425 prefix (save-excursion
19426 (goto-char beg)
19427 (skip-chars-forward " \t")
19428 (make-string (current-column) ?\ )))
19429 (throw 'exit nil))))))
19430 ;; Use `fill-paragraph' with buffer narrowed to item
19431 ;; without any child, and with our computed PREFIX.
19432 (flet ((fill-context-prefix (from to &optional flr) prefix))
19433 (save-restriction
19434 (narrow-to-region beg end)
19435 (save-excursion (fill-paragraph justify)))) t))
19436 ;; Special case where point is not in a list but is on
19437 ;; a paragraph adjacent to a list: make sure this paragraph
19438 ;; doesn't get merged with the end of the list by narrowing
19439 ;; buffer first.
19440 ((save-excursion (forward-paragraph -1)
19441 (setq itemp (org-in-item-p)))
19442 (let ((struct (save-excursion (goto-char itemp)
19443 (org-list-struct))))
19444 (save-restriction
19445 (narrow-to-region (org-list-get-bottom-point struct)
19446 (save-excursion (forward-paragraph 1)
19447 (point)))
19448 (fill-paragraph justify) t)))
19449 ;; Else simply call `fill-paragraph'.
19450 (t nil))))
19452 ;; For reference, this is the default value of adaptive-fill-regexp
19453 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
19455 (defun org-adaptive-fill-function ()
19456 "Return a fill prefix for org-mode files."
19457 (let (itemp)
19458 (save-excursion
19459 (cond
19460 ;; Comment line
19461 ((looking-at "#[ \t]+")
19462 (match-string-no-properties 0))
19463 ;; Plain list item
19464 ((org-at-item-p)
19465 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
19466 ;; Point is in a list after `backward-paragraph': original
19467 ;; point wasn't in the list, or filling would have been taken
19468 ;; care of by `org-auto-fill-function', but the list and the
19469 ;; real paragraph are not separated by a blank line. Thus, move
19470 ;; point after the list to go back to real paragraph and
19471 ;; determine fill-prefix.
19472 ((setq itemp (org-in-item-p))
19473 (goto-char itemp)
19474 (let* ((struct (org-list-struct))
19475 (bottom (org-list-get-bottom-point struct)))
19476 (goto-char bottom)
19477 (make-string (org-get-indentation) ?\ )))
19478 ;; Other text
19479 ((looking-at org-adaptive-fill-regexp-backup)
19480 (match-string-no-properties 0))))))
19482 (defun org-auto-fill-function ()
19483 "Auto-fill function."
19484 (let (itemp prefix)
19485 ;; When in a list, compute an appropriate fill-prefix and make
19486 ;; sure it will be used by `do-auto-fill'.
19487 (if (setq itemp (org-in-item-p))
19488 (progn
19489 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
19490 (flet ((fill-context-prefix (from to &optional flr) prefix))
19491 (do-auto-fill)))
19492 ;; Else just use `do-auto-fill'.
19493 (do-auto-fill))))
19495 ;;; Other stuff.
19497 (defun org-toggle-fixed-width-section (arg)
19498 "Toggle the fixed-width export.
19499 If there is no active region, the QUOTE keyword at the current headline is
19500 inserted or removed. When present, it causes the text between this headline
19501 and the next to be exported as fixed-width text, and unmodified.
19502 If there is an active region, this command adds or removes a colon as the
19503 first character of this line. If the first character of a line is a colon,
19504 this line is also exported in fixed-width font."
19505 (interactive "P")
19506 (let* ((cc 0)
19507 (regionp (org-region-active-p))
19508 (beg (if regionp (region-beginning) (point)))
19509 (end (if regionp (region-end)))
19510 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
19511 (case-fold-search nil)
19512 (re "[ \t]*\\(: \\)")
19513 off)
19514 (if regionp
19515 (save-excursion
19516 (goto-char beg)
19517 (setq cc (current-column))
19518 (beginning-of-line 1)
19519 (setq off (looking-at re))
19520 (while (> nlines 0)
19521 (setq nlines (1- nlines))
19522 (beginning-of-line 1)
19523 (cond
19524 (arg
19525 (org-move-to-column cc t)
19526 (insert ": \n")
19527 (forward-line -1))
19528 ((and off (looking-at re))
19529 (replace-match "" t t nil 1))
19530 ((not off) (org-move-to-column cc t) (insert ": ")))
19531 (forward-line 1)))
19532 (save-excursion
19533 (org-back-to-heading)
19534 (if (looking-at (concat outline-regexp
19535 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
19536 (replace-match "" t t nil 1)
19537 (if (looking-at outline-regexp)
19538 (progn
19539 (goto-char (match-end 0))
19540 (insert org-quote-string " "))))))))
19542 (defun org-reftex-citation ()
19543 "Use reftex-citation to insert a citation into the buffer.
19544 This looks for a line like
19546 #+BIBLIOGRAPHY: foo plain option:-d
19548 and derives from it that foo.bib is the bibliography file relevant
19549 for this document. It then installs the necessary environment for RefTeX
19550 to work in this buffer and calls `reftex-citation' to insert a citation
19551 into the buffer.
19553 Export of such citations to both LaTeX and HTML is handled by the contributed
19554 package org-exp-bibtex by Taru Karttunen."
19555 (interactive)
19556 (let ((reftex-docstruct-symbol 'rds)
19557 (reftex-cite-format "\\cite{%l}")
19558 rds bib)
19559 (save-excursion
19560 (save-restriction
19561 (widen)
19562 (let ((case-fold-search t)
19563 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
19564 (if (not (save-excursion
19565 (or (re-search-forward re nil t)
19566 (re-search-backward re nil t))))
19567 (error "No bibliography defined in file")
19568 (setq bib (concat (match-string 1) ".bib")
19569 rds (list (list 'bib bib)))))))
19570 (call-interactively 'reftex-citation)))
19572 ;;;; Functions extending outline functionality
19574 (defun org-beginning-of-line (&optional arg)
19575 "Go to the beginning of the current line. If that is invisible, continue
19576 to a visible line beginning. This makes the function of C-a more intuitive.
19577 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19578 first attempt, and only move to after the tags when the cursor is already
19579 beyond the end of the headline."
19580 (interactive "P")
19581 (let ((pos (point))
19582 (special (if (consp org-special-ctrl-a/e)
19583 (car org-special-ctrl-a/e)
19584 org-special-ctrl-a/e))
19585 refpos)
19586 (if (org-bound-and-true-p line-move-visual)
19587 (beginning-of-visual-line 1)
19588 (beginning-of-line 1))
19589 (if (and arg (fboundp 'move-beginning-of-line))
19590 (call-interactively 'move-beginning-of-line)
19591 (if (bobp)
19593 (backward-char 1)
19594 (if (org-truely-invisible-p)
19595 (while (and (not (bobp)) (org-truely-invisible-p))
19596 (backward-char 1)
19597 (beginning-of-line 1))
19598 (forward-char 1))))
19599 (when special
19600 (cond
19601 ((and (looking-at org-complex-heading-regexp)
19602 (= (char-after (match-end 1)) ?\ ))
19603 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
19604 (point-at-eol)))
19605 (goto-char
19606 (if (eq special t)
19607 (cond ((> pos refpos) refpos)
19608 ((= pos (point)) refpos)
19609 (t (point)))
19610 (cond ((> pos (point)) (point))
19611 ((not (eq last-command this-command)) (point))
19612 (t refpos)))))
19613 ((org-at-item-p)
19614 (goto-char
19615 (if (eq special t)
19616 (cond ((> pos (match-end 0)) (match-end 0))
19617 ((= pos (point)) (match-end 0))
19618 (t (point)))
19619 (cond ((> pos (point)) (point))
19620 ((not (eq last-command this-command)) (point))
19621 (t (match-end 0))))))))
19622 (org-no-warnings
19623 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19625 (defun org-end-of-line (&optional arg)
19626 "Go to the end of the line.
19627 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19628 first attempt, and only move to after the tags when the cursor is already
19629 beyond the end of the headline."
19630 (interactive "P")
19631 (let ((special (if (consp org-special-ctrl-a/e)
19632 (cdr org-special-ctrl-a/e)
19633 org-special-ctrl-a/e)))
19634 (if (or (not special)
19635 (not (org-on-heading-p))
19636 arg)
19637 (call-interactively
19638 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
19639 ((fboundp 'move-end-of-line) 'move-end-of-line)
19640 (t 'end-of-line)))
19641 (let ((pos (point)))
19642 (beginning-of-line 1)
19643 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
19644 (if (eq special t)
19645 (if (or (< pos (match-beginning 1))
19646 (= pos (match-end 0)))
19647 (goto-char (match-beginning 1))
19648 (goto-char (match-end 0)))
19649 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
19650 (goto-char (match-end 0))
19651 (goto-char (match-beginning 1))))
19652 (call-interactively (if (fboundp 'move-end-of-line)
19653 'move-end-of-line
19654 'end-of-line)))))
19655 (org-no-warnings
19656 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19658 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
19659 (define-key org-mode-map "\C-e" 'org-end-of-line)
19661 (defun org-backward-sentence (&optional arg)
19662 "Go to beginning of sentence, or beginning of table field.
19663 This will call `backward-sentence' or `org-table-beginning-of-field',
19664 depending on context."
19665 (interactive "P")
19666 (cond
19667 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
19668 (t (call-interactively 'backward-sentence))))
19670 (defun org-forward-sentence (&optional arg)
19671 "Go to end of sentence, or end of table field.
19672 This will call `forward-sentence' or `org-table-end-of-field',
19673 depending on context."
19674 (interactive "P")
19675 (cond
19676 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
19677 (t (call-interactively 'forward-sentence))))
19679 (define-key org-mode-map "\M-a" 'org-backward-sentence)
19680 (define-key org-mode-map "\M-e" 'org-forward-sentence)
19682 (defun org-kill-line (&optional arg)
19683 "Kill line, to tags or end of line."
19684 (interactive "P")
19685 (cond
19686 ((or (not org-special-ctrl-k)
19687 (bolp)
19688 (not (org-on-heading-p)))
19689 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
19690 org-ctrl-k-protect-subtree)
19691 (if (or (eq org-ctrl-k-protect-subtree 'error)
19692 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
19693 (error "C-k aborted - would kill hidden subtree")))
19694 (call-interactively 'kill-line))
19695 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
19696 (kill-region (point) (match-beginning 1))
19697 (org-set-tags nil t))
19698 (t (kill-region (point) (point-at-eol)))))
19700 (define-key org-mode-map "\C-k" 'org-kill-line)
19702 (defun org-yank (&optional arg)
19703 "Yank. If the kill is a subtree, treat it specially.
19704 This command will look at the current kill and check if is a single
19705 subtree, or a series of subtrees[1]. If it passes the test, and if the
19706 cursor is at the beginning of a line or after the stars of a currently
19707 empty headline, then the yank is handled specially. How exactly depends
19708 on the value of the following variables, both set by default.
19710 org-yank-folded-subtrees
19711 When set, the subtree(s) will be folded after insertion, but only
19712 if doing so would now swallow text after the yanked text.
19714 org-yank-adjusted-subtrees
19715 When set, the subtree will be promoted or demoted in order to
19716 fit into the local outline tree structure, which means that the level
19717 will be adjusted so that it becomes the smaller one of the two
19718 *visible* surrounding headings.
19720 Any prefix to this command will cause `yank' to be called directly with
19721 no special treatment. In particular, a simple \\[universal-argument] prefix \
19722 will just
19723 plainly yank the text as it is.
19725 \[1] The test checks if the first non-white line is a heading
19726 and if there are no other headings with fewer stars."
19727 (interactive "P")
19728 (org-yank-generic 'yank arg))
19730 (defun org-yank-generic (command arg)
19731 "Perform some yank-like command.
19733 This function implements the behavior described in the `org-yank'
19734 documentation. However, it has been generalized to work for any
19735 interactive command with similar behavior."
19737 ;; pretend to be command COMMAND
19738 (setq this-command command)
19740 (if arg
19741 (call-interactively command)
19743 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
19744 (and (org-kill-is-subtree-p)
19745 (or (bolp)
19746 (and (looking-at "[ \t]*$")
19747 (string-match
19748 "\\`\\*+\\'"
19749 (buffer-substring (point-at-bol) (point)))))))
19750 swallowp)
19751 (cond
19752 ((and subtreep org-yank-folded-subtrees)
19753 (let ((beg (point))
19754 end)
19755 (if (and subtreep org-yank-adjusted-subtrees)
19756 (org-paste-subtree nil nil 'for-yank)
19757 (call-interactively command))
19759 (setq end (point))
19760 (goto-char beg)
19761 (when (and (bolp) subtreep
19762 (not (setq swallowp
19763 (org-yank-folding-would-swallow-text beg end))))
19764 (or (looking-at outline-regexp)
19765 (re-search-forward (concat "^" outline-regexp) end t))
19766 (while (and (< (point) end) (looking-at outline-regexp))
19767 (hide-subtree)
19768 (org-cycle-show-empty-lines 'folded)
19769 (condition-case nil
19770 (outline-forward-same-level 1)
19771 (error (goto-char end)))))
19772 (when swallowp
19773 (message
19774 "Inserted text not folded because that would swallow text"))
19776 (goto-char end)
19777 (skip-chars-forward " \t\n\r")
19778 (beginning-of-line 1)
19779 (push-mark beg 'nomsg)))
19780 ((and subtreep org-yank-adjusted-subtrees)
19781 (let ((beg (point-at-bol)))
19782 (org-paste-subtree nil nil 'for-yank)
19783 (push-mark beg 'nomsg)))
19785 (call-interactively command))))))
19787 (defun org-yank-folding-would-swallow-text (beg end)
19788 "Would hide-subtree at BEG swallow any text after END?"
19789 (let (level)
19790 (save-excursion
19791 (goto-char beg)
19792 (when (or (looking-at outline-regexp)
19793 (re-search-forward (concat "^" outline-regexp) end t))
19794 (setq level (org-outline-level)))
19795 (goto-char end)
19796 (skip-chars-forward " \t\r\n\v\f")
19797 (if (or (eobp)
19798 (and (bolp) (looking-at org-outline-regexp)
19799 (<= (org-outline-level) level)))
19800 nil ; Nothing would be swallowed
19801 t)))) ; something would swallow
19803 (define-key org-mode-map "\C-y" 'org-yank)
19805 (defun org-truely-invisible-p ()
19806 "Check if point is at a character currently not visible.
19807 This version does not only check the character property, but also
19808 `visible-mode'."
19809 ;; Early versions of noutline don't have `outline-invisible-p'.
19810 (if (org-bound-and-true-p visible-mode)
19812 (outline-invisible-p)))
19814 (defun org-invisible-p2 ()
19815 "Check if point is at a character currently not visible."
19816 (save-excursion
19817 (if (and (eolp) (not (bobp))) (backward-char 1))
19818 ;; Early versions of noutline don't have `outline-invisible-p'.
19819 (outline-invisible-p)))
19821 (defun org-back-to-heading (&optional invisible-ok)
19822 "Call `outline-back-to-heading', but provide a better error message."
19823 (condition-case nil
19824 (outline-back-to-heading invisible-ok)
19825 (error (error "Before first headline at position %d in buffer %s"
19826 (point) (current-buffer)))))
19828 (defun org-beginning-of-defun ()
19829 "Go to the beginning of the subtree, i.e. back to the heading."
19830 (org-back-to-heading))
19831 (defun org-end-of-defun ()
19832 "Go to the end of the subtree."
19833 (org-end-of-subtree nil t))
19835 (defun org-before-first-heading-p ()
19836 "Before first heading?"
19837 (save-excursion
19838 (end-of-line)
19839 (null (re-search-backward "^\\*+ " nil t))))
19841 (defun org-on-heading-p (&optional ignored)
19842 (outline-on-heading-p t))
19843 (defun org-at-heading-p (&optional ignored)
19844 (outline-on-heading-p t))
19846 (defun org-point-at-end-of-empty-headline ()
19847 "If point is at the end of an empty headline, return t, else nil.
19848 If the heading only contains a TODO keyword, it is still still considered
19849 empty."
19850 (and (looking-at "[ \t]*$")
19851 (save-excursion
19852 (beginning-of-line 1)
19853 (let ((case-fold-search nil))
19854 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
19855 "\\)?[ \t]*$"))))))
19856 (defun org-at-heading-or-item-p ()
19857 (or (org-on-heading-p) (org-at-item-p)))
19859 (defun org-on-target-p ()
19860 (or (org-in-regexp org-radio-target-regexp)
19861 (org-in-regexp org-target-regexp)))
19863 (defun org-up-heading-all (arg)
19864 "Move to the heading line of which the present line is a subheading.
19865 This function considers both visible and invisible heading lines.
19866 With argument, move up ARG levels."
19867 (if (fboundp 'outline-up-heading-all)
19868 (outline-up-heading-all arg) ; emacs 21 version of outline.el
19869 (outline-up-heading arg t))) ; emacs 22 version of outline.el
19871 (defun org-up-heading-safe ()
19872 "Move to the heading line of which the present line is a subheading.
19873 This version will not throw an error. It will return the level of the
19874 headline found, or nil if no higher level is found.
19876 Also, this function will be a lot faster than `outline-up-heading',
19877 because it relies on stars being the outline starters. This can really
19878 make a significant difference in outlines with very many siblings."
19879 (let (start-level re)
19880 (org-back-to-heading t)
19881 (setq start-level (funcall outline-level))
19882 (if (equal start-level 1)
19884 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
19885 (if (re-search-backward re nil t)
19886 (funcall outline-level)))))
19888 (defun org-first-sibling-p ()
19889 "Is this heading the first child of its parents?"
19890 (interactive)
19891 (let ((re (concat "^" outline-regexp))
19892 level l)
19893 (unless (org-at-heading-p t)
19894 (error "Not at a heading"))
19895 (setq level (funcall outline-level))
19896 (save-excursion
19897 (if (not (re-search-backward re nil t))
19899 (setq l (funcall outline-level))
19900 (< l level)))))
19902 (defun org-goto-sibling (&optional previous)
19903 "Goto the next sibling, even if it is invisible.
19904 When PREVIOUS is set, go to the previous sibling instead. Returns t
19905 when a sibling was found. When none is found, return nil and don't
19906 move point."
19907 (let ((fun (if previous 're-search-backward 're-search-forward))
19908 (pos (point))
19909 (re (concat "^" outline-regexp))
19910 level l)
19911 (when (condition-case nil (org-back-to-heading t) (error nil))
19912 (setq level (funcall outline-level))
19913 (catch 'exit
19914 (or previous (forward-char 1))
19915 (while (funcall fun re nil t)
19916 (setq l (funcall outline-level))
19917 (when (< l level) (goto-char pos) (throw 'exit nil))
19918 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
19919 (goto-char pos)
19920 nil))))
19922 (defun org-show-siblings ()
19923 "Show all siblings of the current headline."
19924 (save-excursion
19925 (while (org-goto-sibling) (org-flag-heading nil)))
19926 (save-excursion
19927 (while (org-goto-sibling 'previous)
19928 (org-flag-heading nil))))
19930 (defun org-goto-first-child ()
19931 "Goto the first child, even if it is invisible.
19932 Return t when a child was found. Otherwise don't move point and
19933 return nil."
19934 (let (level (pos (point)) (re (concat "^" outline-regexp)))
19935 (when (condition-case nil (org-back-to-heading t) (error nil))
19936 (setq level (outline-level))
19937 (forward-char 1)
19938 (if (and (re-search-forward re nil t) (> (outline-level) level))
19939 (progn (goto-char (match-beginning 0)) t)
19940 (goto-char pos) nil))))
19942 (defun org-show-hidden-entry ()
19943 "Show an entry where even the heading is hidden."
19944 (save-excursion
19945 (org-show-entry)))
19947 (defun org-flag-heading (flag &optional entry)
19948 "Flag the current heading. FLAG non-nil means make invisible.
19949 When ENTRY is non-nil, show the entire entry."
19950 (save-excursion
19951 (org-back-to-heading t)
19952 ;; Check if we should show the entire entry
19953 (if entry
19954 (progn
19955 (org-show-entry)
19956 (save-excursion
19957 (and (outline-next-heading)
19958 (org-flag-heading nil))))
19959 (outline-flag-region (max (point-min) (1- (point)))
19960 (save-excursion (outline-end-of-heading) (point))
19961 flag))))
19963 (defun org-get-next-sibling ()
19964 "Move to next heading of the same level, and return point.
19965 If there is no such heading, return nil.
19966 This is like outline-next-sibling, but invisible headings are ok."
19967 (let ((level (funcall outline-level)))
19968 (outline-next-heading)
19969 (while (and (not (eobp)) (> (funcall outline-level) level))
19970 (outline-next-heading))
19971 (if (or (eobp) (< (funcall outline-level) level))
19973 (point))))
19975 (defun org-get-last-sibling ()
19976 "Move to previous heading of the same level, and return point.
19977 If there is no such heading, return nil."
19978 (let ((opoint (point))
19979 (level (funcall outline-level)))
19980 (outline-previous-heading)
19981 (when (and (/= (point) opoint) (outline-on-heading-p t))
19982 (while (and (> (funcall outline-level) level)
19983 (not (bobp)))
19984 (outline-previous-heading))
19985 (if (< (funcall outline-level) level)
19987 (point)))))
19989 (defun org-end-of-subtree (&optional invisible-OK to-heading)
19990 ;; This contains an exact copy of the original function, but it uses
19991 ;; `org-back-to-heading', to make it work also in invisible
19992 ;; trees. And is uses an invisible-OK argument.
19993 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
19994 ;; Furthermore, when used inside Org, finding the end of a large subtree
19995 ;; with many children and grandchildren etc, this can be much faster
19996 ;; than the outline version.
19997 (org-back-to-heading invisible-OK)
19998 (let ((first t)
19999 (level (funcall outline-level)))
20000 (if (and (org-mode-p) (< level 1000))
20001 ;; A true heading (not a plain list item), in Org-mode
20002 ;; This means we can easily find the end by looking
20003 ;; only for the right number of stars. Using a regexp to do
20004 ;; this is so much faster than using a Lisp loop.
20005 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20006 (forward-char 1)
20007 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20008 ;; something else, do it the slow way
20009 (while (and (not (eobp))
20010 (or first (> (funcall outline-level) level)))
20011 (setq first nil)
20012 (outline-next-heading)))
20013 (unless to-heading
20014 (if (memq (preceding-char) '(?\n ?\^M))
20015 (progn
20016 ;; Go to end of line before heading
20017 (forward-char -1)
20018 (if (memq (preceding-char) '(?\n ?\^M))
20019 ;; leave blank line before heading
20020 (forward-char -1))))))
20021 (point))
20023 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20024 "Use Org version in org-mode, for dramatic speed-up."
20025 (if (org-mode-p)
20026 (progn
20027 (org-end-of-subtree nil t)
20028 (unless (eobp) (backward-char 1)))
20029 ad-do-it))
20031 (defun org-end-of-meta-data-and-drawers ()
20032 "Jump to the first text after meta data and drawers in the current entry.
20033 This will move over empty lines, lines with planning time stamps,
20034 clocking lines, and drawers."
20035 (org-back-to-heading t)
20036 (let ((end (save-excursion (outline-next-heading) (point)))
20037 (re (concat "\\(" org-drawer-regexp "\\)"
20038 "\\|" "[ \t]*" org-keyword-time-regexp)))
20039 (forward-line 1)
20040 (while (re-search-forward re end t)
20041 (if (not (match-end 1))
20042 ;; empty or planning line
20043 (forward-line 1)
20044 ;; a drawer, find the end
20045 (re-search-forward "^[ \t]*:END:" end 'move)
20046 (forward-line 1)))
20047 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
20048 (point)))
20050 (defun org-forward-same-level (arg &optional invisible-ok)
20051 "Move forward to the arg'th subheading at same level as this one.
20052 Stop at the first and last subheadings of a superior heading.
20053 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20054 it wil also look at invisible ones."
20055 (interactive "p")
20056 (org-back-to-heading invisible-ok)
20057 (org-on-heading-p)
20058 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20059 (re (format "^\\*\\{1,%d\\} " level))
20061 (forward-char 1)
20062 (while (> arg 0)
20063 (while (and (re-search-forward re nil 'move)
20064 (setq l (- (match-end 0) (match-beginning 0) 1))
20065 (= l level)
20066 (not invisible-ok)
20067 (progn (backward-char 1) (outline-invisible-p)))
20068 (if (< l level) (setq arg 1)))
20069 (setq arg (1- arg)))
20070 (beginning-of-line 1)))
20072 (defun org-backward-same-level (arg &optional invisible-ok)
20073 "Move backward to the arg'th subheading at same level as this one.
20074 Stop at the first and last subheadings of a superior heading."
20075 (interactive "p")
20076 (org-back-to-heading)
20077 (org-on-heading-p)
20078 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20079 (re (format "^\\*\\{1,%d\\} " level))
20081 (while (> arg 0)
20082 (while (and (re-search-backward re nil 'move)
20083 (setq l (- (match-end 0) (match-beginning 0) 1))
20084 (= l level)
20085 (not invisible-ok)
20086 (outline-invisible-p))
20087 (if (< l level) (setq arg 1)))
20088 (setq arg (1- arg)))))
20090 (defun org-show-subtree ()
20091 "Show everything after this heading at deeper levels."
20092 (outline-flag-region
20093 (point)
20094 (save-excursion
20095 (org-end-of-subtree t t))
20096 nil))
20098 (defun org-show-entry ()
20099 "Show the body directly following this heading.
20100 Show the heading too, if it is currently invisible."
20101 (interactive)
20102 (save-excursion
20103 (condition-case nil
20104 (progn
20105 (org-back-to-heading t)
20106 (outline-flag-region
20107 (max (point-min) (1- (point)))
20108 (save-excursion
20109 (if (re-search-forward
20110 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
20111 (match-beginning 1)
20112 (point-max)))
20113 nil)
20114 (org-cycle-hide-drawers 'children))
20115 (error nil))))
20117 (defun org-make-options-regexp (kwds &optional extra)
20118 "Make a regular expression for keyword lines."
20119 (concat
20121 "#?[ \t]*\\+\\("
20122 (mapconcat 'regexp-quote kwds "\\|")
20123 (if extra (concat "\\|" extra))
20124 "\\):[ \t]*"
20125 "\\(.*\\)"))
20127 ;; Make isearch reveal the necessary context
20128 (defun org-isearch-end ()
20129 "Reveal context after isearch exits."
20130 (when isearch-success ; only if search was successful
20131 (if (featurep 'xemacs)
20132 ;; Under XEmacs, the hook is run in the correct place,
20133 ;; we directly show the context.
20134 (org-show-context 'isearch)
20135 ;; In Emacs the hook runs *before* restoring the overlays.
20136 ;; So we have to use a one-time post-command-hook to do this.
20137 ;; (Emacs 22 has a special variable, see function `org-mode')
20138 (unless (and (boundp 'isearch-mode-end-hook-quit)
20139 isearch-mode-end-hook-quit)
20140 ;; Only when the isearch was not quitted.
20141 (org-add-hook 'post-command-hook 'org-isearch-post-command
20142 'append 'local)))))
20144 (defun org-isearch-post-command ()
20145 "Remove self from hook, and show context."
20146 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20147 (org-show-context 'isearch))
20150 ;;;; Integration with and fixes for other packages
20152 ;;; Imenu support
20154 (defvar org-imenu-markers nil
20155 "All markers currently used by Imenu.")
20156 (make-variable-buffer-local 'org-imenu-markers)
20158 (defun org-imenu-new-marker (&optional pos)
20159 "Return a new marker for use by Imenu, and remember the marker."
20160 (let ((m (make-marker)))
20161 (move-marker m (or pos (point)))
20162 (push m org-imenu-markers)
20165 (defun org-imenu-get-tree ()
20166 "Produce the index for Imenu."
20167 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20168 (setq org-imenu-markers nil)
20169 (let* ((n org-imenu-depth)
20170 (re (concat "^" outline-regexp))
20171 (subs (make-vector (1+ n) nil))
20172 (last-level 0)
20173 m level head)
20174 (save-excursion
20175 (save-restriction
20176 (widen)
20177 (goto-char (point-max))
20178 (while (re-search-backward re nil t)
20179 (setq level (org-reduced-level (funcall outline-level)))
20180 (when (<= level n)
20181 (looking-at org-complex-heading-regexp)
20182 (setq head (org-link-display-format
20183 (org-match-string-no-properties 4))
20184 m (org-imenu-new-marker))
20185 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20186 (if (>= level last-level)
20187 (push (cons head m) (aref subs level))
20188 (push (cons head (aref subs (1+ level))) (aref subs level))
20189 (loop for i from (1+ level) to n do (aset subs i nil)))
20190 (setq last-level level)))))
20191 (aref subs 1)))
20193 (eval-after-load "imenu"
20194 '(progn
20195 (add-hook 'imenu-after-jump-hook
20196 (lambda ()
20197 (if (org-mode-p)
20198 (org-show-context 'org-goto))))))
20200 (defun org-link-display-format (link)
20201 "Replace a link with either the description, or the link target
20202 if no description is present"
20203 (save-match-data
20204 (if (string-match org-bracket-link-analytic-regexp link)
20205 (replace-match (if (match-end 5)
20206 (match-string 5 link)
20207 (concat (match-string 1 link)
20208 (match-string 3 link)))
20209 nil t link)
20210 link)))
20212 ;; Speedbar support
20214 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20215 "Overlay marking the agenda restriction line in speedbar.")
20216 (overlay-put org-speedbar-restriction-lock-overlay
20217 'face 'org-agenda-restriction-lock)
20218 (overlay-put org-speedbar-restriction-lock-overlay
20219 'help-echo "Agendas are currently limited to this item.")
20220 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20222 (defun org-speedbar-set-agenda-restriction ()
20223 "Restrict future agenda commands to the location at point in speedbar.
20224 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20225 (interactive)
20226 (require 'org-agenda)
20227 (let (p m tp np dir txt)
20228 (cond
20229 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20230 'org-imenu t))
20231 (setq m (get-text-property p 'org-imenu-marker))
20232 (with-current-buffer (marker-buffer m)
20233 (goto-char m)
20234 (org-agenda-set-restriction-lock 'subtree)))
20235 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20236 'speedbar-function 'speedbar-find-file))
20237 (setq tp (previous-single-property-change
20238 (1+ p) 'speedbar-function)
20239 np (next-single-property-change
20240 tp 'speedbar-function)
20241 dir (speedbar-line-directory)
20242 txt (buffer-substring-no-properties (or tp (point-min))
20243 (or np (point-max))))
20244 (with-current-buffer (find-file-noselect
20245 (let ((default-directory dir))
20246 (expand-file-name txt)))
20247 (unless (org-mode-p)
20248 (error "Cannot restrict to non-Org-mode file"))
20249 (org-agenda-set-restriction-lock 'file)))
20250 (t (error "Don't know how to restrict Org-mode's agenda")))
20251 (move-overlay org-speedbar-restriction-lock-overlay
20252 (point-at-bol) (point-at-eol))
20253 (setq current-prefix-arg nil)
20254 (org-agenda-maybe-redo)))
20256 (eval-after-load "speedbar"
20257 '(progn
20258 (speedbar-add-supported-extension ".org")
20259 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
20260 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
20261 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
20262 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20263 (add-hook 'speedbar-visiting-tag-hook
20264 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
20266 ;;; Fixes and Hacks for problems with other packages
20268 ;; Make flyspell not check words in links, to not mess up our keymap
20269 (defun org-mode-flyspell-verify ()
20270 "Don't let flyspell put overlays at active buttons, or on
20271 {todo,all-time,additional-option-like}-keywords."
20272 (let ((pos (max (1- (point)) (point-min)))
20273 (word (thing-at-point 'word)))
20274 (and (not (get-text-property pos 'keymap))
20275 (not (get-text-property pos 'org-no-flyspell))
20276 (not (member word org-todo-keywords-1))
20277 (not (member word org-all-time-keywords))
20278 (not (member word org-additional-option-like-keywords)))))
20280 (defun org-remove-flyspell-overlays-in (beg end)
20281 "Remove flyspell overlays in region."
20282 (and (org-bound-and-true-p flyspell-mode)
20283 (fboundp 'flyspell-delete-region-overlays)
20284 (flyspell-delete-region-overlays beg end))
20285 (add-text-properties beg end '(org-no-flyspell t)))
20287 ;; Make `bookmark-jump' shows the jump location if it was hidden.
20288 (eval-after-load "bookmark"
20289 '(if (boundp 'bookmark-after-jump-hook)
20290 ;; We can use the hook
20291 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20292 ;; Hook not available, use advice
20293 (defadvice bookmark-jump (after org-make-visible activate)
20294 "Make the position visible."
20295 (org-bookmark-jump-unhide))))
20297 ;; Make sure saveplace shows the location if it was hidden
20298 (eval-after-load "saveplace"
20299 '(defadvice save-place-find-file-hook (after org-make-visible activate)
20300 "Make the position visible."
20301 (org-bookmark-jump-unhide)))
20303 ;; Make sure ecb shows the location if it was hidden
20304 (eval-after-load "ecb"
20305 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
20306 "Make hierarchy visible when jumping into location from ECB tree buffer."
20307 (if (org-mode-p)
20308 (org-show-context))))
20310 (defun org-bookmark-jump-unhide ()
20311 "Unhide the current position, to show the bookmark location."
20312 (and (org-mode-p)
20313 (or (outline-invisible-p)
20314 (save-excursion (goto-char (max (point-min) (1- (point))))
20315 (outline-invisible-p)))
20316 (org-show-context 'bookmark-jump)))
20318 ;; Make session.el ignore our circular variable
20319 (eval-after-load "session"
20320 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20322 ;;;; Experimental code
20324 (defun org-closed-in-range ()
20325 "Sparse tree of items closed in a certain time range.
20326 Still experimental, may disappear in the future."
20327 (interactive)
20328 ;; Get the time interval from the user.
20329 (let* ((time1 (org-float-time
20330 (org-read-date nil 'to-time nil "Starting date: ")))
20331 (time2 (org-float-time
20332 (org-read-date nil 'to-time nil "End date:")))
20333 ;; callback function
20334 (callback (lambda ()
20335 (let ((time
20336 (org-float-time
20337 (apply 'encode-time
20338 (org-parse-time-string
20339 (match-string 1))))))
20340 ;; check if time in interval
20341 (and (>= time time1) (<= time time2))))))
20342 ;; make tree, check each match with the callback
20343 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
20345 ;;;; Finish up
20347 (provide 'org)
20349 (run-hooks 'org-load-hook)
20351 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
20353 ;;; org.el ends here